repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
csortu/drugMLPytorch
|
[
"7ea6ef8c46dc3027a7ebd21836b7b12c23659db8"
] |
[
"splitData.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 13 13:32:14 2019\n\n@author: ortutay\n\"\"\"\n\nimport pandas as pd \nimport numpy as np\n\nlink = 'http://bit.ly/uforeports'\nufo = pd.read_csv(link)\n\n# We split 60-20-20% tran-validation-test sets\n\ntrain, validate, test = np.split(ufo.sample(frac=1), \n [int(.6*len(ufo)),int(.8*len(ufo))])\n\n\na = pd.DataFrame({'col1': np.arange(1, 21),'col2': np.arange(21,41)})\n\ntrain, validate, test = np.split(a.sample(frac=1), [int(.8 * len(a)), int(.9 * len(a))])"
] |
[
[
"numpy.arange",
"pandas.read_csv"
]
] |
tobikuhlmann/Conditional_Density_Estimation
|
[
"5e64fca31e0f8aafac43cfca7a37f70edb4d90fe"
] |
[
"cde/density_estimator/MDN.py"
] |
[
"import numpy as np\nimport sklearn\nimport tensorflow as tf\nimport edward as ed\nfrom edward.models import Categorical, Mixture, MultivariateNormalDiag\nfrom cde.utils.tf_utils.network import MLP\nimport cde.utils.tf_utils.layers as L\nfrom cde.utils.tf_utils.layers_powered import LayersPowered\nfrom cde.utils.serializable import Serializable\n\n#import matplotlib.pyplot as plt\n\nfrom .BaseNNMixtureEstimator import BaseNNMixtureEstimator\n\nclass MixtureDensityNetwork(BaseNNMixtureEstimator):\n \"\"\" Mixture Density Network Estimator\n\n See \"Mixture Density networks\", Bishop 1994\n\n Args:\n name: (str) name space of MDN (should be unique in code, otherwise tensorflow namespace collitions may arise)\n ndim_x: (int) dimensionality of x variable\n ndim_y: (int) dimensionality of y variable\n n_centers: Number of Gaussian mixture components\n hidden_sizes: (tuple of int) sizes of the hidden layers of the neural network\n hidden_nonlinearity: (tf function) nonlinearity of the hidden layers\n n_training_epochs: Number of epochs for training\n x_noise_std: (optional) standard deviation of Gaussian noise over the the training data X -> regularization through noise\n y_noise_std: (optional) standard deviation of Gaussian noise over the the training data Y -> regularization through noise\n entropy_reg_coef: (optional) scalar float coefficient for shannon entropy penalty on the mixture component weight distribution\n weight_normalization: (boolean) whether weight normalization shall be used\n data_normalization: (boolean) whether to normalize the data (X and Y) to exhibit zero-mean and std\n random_seed: (optional) seed (int) of the random number generators used\n \"\"\"\n\n\n def __init__(self, name, ndim_x, ndim_y, n_centers=20, hidden_sizes=(16, 16), hidden_nonlinearity=tf.nn.tanh, n_training_epochs=1000,\n x_noise_std=None, y_noise_std=None, entropy_reg_coef=0.0, weight_normalization=True, data_normalization=True, random_seed=None):\n\n Serializable.quick_init(self, locals())\n self._check_uniqueness_of_scope(name)\n\n self.name = name\n self.ndim_x = ndim_x\n self.ndim_y = ndim_y\n\n self.random_seed = random_seed\n self.random_state = np.random.RandomState(seed=random_seed)\n tf.set_random_seed(random_seed)\n\n self.n_centers = n_centers\n\n self.hidden_sizes = hidden_sizes\n self.hidden_nonlinearity = hidden_nonlinearity\n\n self.n_training_epochs = n_training_epochs\n\n # regularization parameters\n self.x_noise_std = x_noise_std\n self.y_noise_std = y_noise_std\n self.entropy_reg_coef = entropy_reg_coef\n self.weight_normalization = weight_normalization\n self.data_normalization = data_normalization\n\n self.can_sample = True\n self.has_pdf = True\n self.has_cdf = True\n\n self.fitted = False\n\n # build tensorflow model\n self._build_model()\n\n def fit(self, X, Y, random_seed=None, verbose=True, eval_set=None, **kwargs):\n \"\"\" Fits the conditional density model with provided data\n\n Args:\n X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)\n Y: numpy array of y targets - shape: (n_samples, n_dim_y)\n random_seed: the seed (integer) used by the random number generator\n verbose: (boolean) controls the verbosity (console output)\n\n \"\"\"\n X, Y = self._handle_input_dimensionality(X, Y, fitting=True)\n\n self._setup_inference_and_initialize()\n\n # data normalization if desired\n if self.data_normalization: # this must happen after the initialization\n self._compute_data_normalization(X, Y) # computes mean & std of data and assigns it to tf graph for normalization\n\n # train the model\n self._partial_fit(X, Y, n_epoch=self.n_training_epochs, verbose=verbose, **kwargs)\n self.fitted = True\n\n def _partial_fit(self, X, Y, n_epoch=1, eval_set=None, verbose=True):\n \"\"\"\n update model\n \"\"\"\n\n # loop over epochs\n for i in range(n_epoch):\n\n # run inference, update trainable variables of the model\n info_dict = self.inference.update(feed_dict={self.X_ph: X, self.Y_ph: Y, self.train_phase: True})\n\n train_loss = info_dict['loss'] / len(Y)\n\n if eval_set is not None:\n X_test, y_test = eval_set\n test_loss = self.sess.run(self.inference.loss, feed_dict={self.X_ph: X_test, self.y_ph: y_test}) / len(y_test)\n\n #scales = self.sess.run(self.scales, feed_dict={self.X_ph: X[:2,:]})\n #print(scales[1])\n\n # only print progress for the initial fit, not for additional updates\n if not self.fitted and verbose:\n self.inference.print_progress(info_dict)\n\n if verbose:\n print(\"mean log-loss train: {:.3f}\".format(train_loss))\n if eval_set is not None:\n print(\"mean log-loss test: {:.3f}\".format(test_loss))\n\n def _build_model(self):\n \"\"\"\n implementation of the MDN\n \"\"\"\n\n with tf.variable_scope(self.name):\n self.layer_in_x, self.layer_in_y = self._build_input_layers() # add playeholders, data_normalization and data_noise if desired\n # create core multi-layer perceptron\n mlp_output_dim = 2 * self.ndim_y * self.n_centers + self.n_centers\n core_network = MLP(\n name=\"core_network\",\n input_layer=self.layer_in_x,\n output_dim=mlp_output_dim,\n hidden_sizes=self.hidden_sizes,\n hidden_nonlinearity=self.hidden_nonlinearity,\n output_nonlinearity=None,\n weight_normalization=self.weight_normalization\n )\n\n core_output_layer = core_network.output_layer\n\n # slice output of MLP into three equally sized parts for loc, scale and mixture weights\n slice_layer_locs = L.SliceLayer(core_output_layer, indices=slice(0, self.ndim_y * self.n_centers), axis=-1)\n slice_layer_scales = L.SliceLayer(core_output_layer, indices=slice(self.ndim_y * self.n_centers, 2 * self.ndim_y * self.n_centers), axis=-1)\n slice_layer_weights = L.SliceLayer(core_output_layer, indices=slice(2 * self.ndim_y * self.n_centers, mlp_output_dim), axis=-1)\n\n # locations mixture components\n self.reshape_layer_locs = L.ReshapeLayer(slice_layer_locs, (-1, self.n_centers, self.ndim_y))\n self.locs = L.get_output(self.reshape_layer_locs)\n\n # scales of the mixture components\n reshape_layer_scales = L.ReshapeLayer(slice_layer_scales, (-1, self.n_centers, self.ndim_y))\n self.softplus_layer_scales = L.NonlinearityLayer(reshape_layer_scales, nonlinearity=tf.nn.softplus)\n self.scales = L.get_output(self.softplus_layer_scales)\n\n # weights of the mixture components\n self.logits = L.get_output(slice_layer_weights)\n self.softmax_layer_weights = L.NonlinearityLayer(slice_layer_weights, nonlinearity=tf.nn.softmax)\n self.weights = L.get_output(self.softmax_layer_weights)\n\n # # put mixture components together\n self.y_input = L.get_output(self.layer_in_y)\n self.cat = cat = Categorical(logits=self.logits)\n self.components = components = [MultivariateNormalDiag(loc=loc, scale_diag=scale) for loc, scale\n in zip(tf.unstack(self.locs, axis=1), tf.unstack( self.scales, axis=1))]\n self.mixture = mixture = Mixture(cat=cat, components=components, value=tf.zeros_like(self.y_input))\n\n # softmax entropy penalty -> regularization\n self.softmax_entropy = tf.reduce_sum(- tf.multiply(tf.log(self.weights), self.weights), axis=1)\n self.entropy_reg_coef_ph = tf.placeholder_with_default(float(self.entropy_reg_coef), name='entropy_reg_coef', shape=())\n self.softmax_entrop_loss = self.entropy_reg_coef_ph * self.softmax_entropy\n tf.losses.add_loss(self.softmax_entrop_loss, tf.GraphKeys.REGULARIZATION_LOSSES)\n\n # tensor to store samples\n self.samples = mixture.sample() #TODO either use it or remove it\n\n # tensor to compute probabilities\n if self.data_normalization:\n self.pdf_ = mixture.prob(self.y_input) / tf.reduce_prod(self.std_y_sym)\n self.log_pdf_ = mixture.log_prob(self.y_input) - tf.reduce_sum(tf.log(self.std_y_sym))\n else:\n self.pdf_ = mixture.prob(self.y_input)\n self.log_pdf_ = mixture.log_prob(self.y_input)\n\n # symbolic tensors for getting the unnormalized mixture components\n if self.data_normalization:\n self.scales_unnormalized = self.scales * self.std_y_sym\n self.locs_unnormalized = self.locs * self.std_y_sym + self.mean_y_sym\n else:\n self.scales_unnormalized = self.scales\n self.locs_unnormalized = self.locs\n\n # initialize LayersPowered --> provides functions for serializing tf models\n LayersPowered.__init__(self, [self.softmax_layer_weights, self.softplus_layer_scales, self.reshape_layer_locs,\n self.layer_in_y])\n\n def _param_grid(self):\n\n param_grid = {\n \"n_centers\": [5, 10, 20],\n \"x_noise_std\": [0.1, 0.15, 0.2, 0.3],\n \"y_noise_std\": [0.5, 0.1, 0.15, 0.2]\n }\n return param_grid\n\n def _get_mixture_components(self, X):\n assert self.fitted\n weights, locs, scales = self.sess.run([self.weights, self.locs_unnormalized, self.scales_unnormalized], feed_dict={self.X_ph: X})\n assert weights.shape[0] == locs.shape[0] == scales.shape[0] == X.shape[0]\n assert weights.shape[1] == locs.shape[1] == scales.shape[1] == self.n_centers\n assert locs.shape[2] == scales.shape[2] == self.ndim_y\n assert locs.ndim == 3 and scales.ndim == 3 and weights.ndim == 2\n return weights, locs, scales\n\n def __str__(self):\n return \"\\nEstimator type: {}\\n n_centers: {}\\n entropy_reg_coef: {}\\n data_normalization: {} \\n weight_normalization: {}\\n\" \\\n \"n_training_epochs: {}\\n x_noise_std: {}\\n y_noise_std: {}\\n \".format(self.__class__.__name__, self.n_centers, self.entropy_reg_coef,\n self.data_normalization, self.weight_normalization, self.n_training_epochs, self.x_noise_std, self.y_noise_std)"
] |
[
[
"tensorflow.unstack",
"tensorflow.zeros_like",
"tensorflow.variable_scope",
"tensorflow.reduce_prod",
"tensorflow.log",
"tensorflow.set_random_seed",
"numpy.random.RandomState",
"tensorflow.losses.add_loss"
]
] |
jmdearman/code_triage
|
[
"67626b40429365370b5bec11efa29b7ee8a1983e"
] |
[
"code_triage.py"
] |
[
"#!/usr/bin/env python2\nfrom __future__ import division, print_function\nimport collections\nimport os\nimport numpy as np\nimport h5py\n\nheader_text = \"\"\"\nINTRO TO ANTIPATTERNS IN SCIENTIFIC COMPUTING PART I: CODE TRIAGE\n-----------------------------------------------------------------\n\nInstructions to follow along:\n\n>>> git clone https://github.com/jmdearman/code_triage\n>>> cd code_triage\n>>> ./code_triage start\n\"\"\"\n\nintro_text = \"\"\"\nSCENARIO\n--------\n\nYou are an engineer at NASA.\n\nYou've told all of your colleagues how awesome Python is, and you managed to\nconvince your friend, Marty, to check it out.\n\nMarty works on the Guidance team for NASA's next generation space capsule.\n\nHe's working on some code to assess landing performance against 2 metrics:\n 1. The capsule must splashdown within a given range to the target site. \n 2. To be extra safe, there's also a keep-out zone to let the Navy\n know where to park the recovery ship out of harms way.\n\nMarty is having trouble with the code he wrote this morning.\n\"\"\"\n\nmessage_text = \"\"\"\n================================================================================\nSubject: Python Bug\nFrom: Marty McFly\n================================================================================\n\nDear Colleague,\n\nI was initially really excited about this Python thing you showed me last week.\nI read PEP8 and translated my code from MATLAB, but my second ellipse is\ncoming out wrong (too small).\n\nDo you think there's a bug in Python?\n\nI attached a copy of my code (marty.py) and the data file (touchdown_data.h5).\n\nCheers,\n-Marty\n\nP.S. Can you give me any pointers on how I can improve my code?\n\"\"\"\n\nend_text = \"\"\"\nCODE TRIAGE WRAP-UP\n-------------------\n- use __future__ to get Python 3 integer division (return floats)\n- use astropy.units instead of rolling your own conversions\n- define functions or use iteration to avoid repetition (DRY)\n- vectorize computational for-loops with numpy\n- use adapter classes to improve workflow\n- sign up for INTRO TO ANTIPATTERNS IN SCIENTIFIC COMPUTING PART II\n\nLINKS\n-----\n- Raymond Hettinger: Beyond PEP 8\n https://youtu.be/wf-BqAjZb8M\n- Katherine D. Huff & Anthony Scopatz: Effective Computation in Physics\n https://youtu.be/Qc9035gw2OQ\n- Erik Rose: Designing Poetic APIs\n https://youtu.be/JQYnFyG7A8c\n\"\"\"\n\ndef configure():\n \"\"\"Generate data for Code Triage.\"\"\"\n Variable = collections.namedtuple('Variable', ('name', 'sigma', 'unit'))\n\n filename = 'touchdown_data.h5'\n nruns = 10000\n seed = 0\n\n variables = [\n Variable('miss_x', 2000, 'm'),\n Variable('miss_y', 500, 'm'),\n Variable('velocity_x', 5, 'm/s'),\n Variable('velocity_y', 4, 'm/s'),\n Variable('velocity_z', 8, 'm/s'),\n Variable('yaw', .1, 'rad'),\n Variable('pitch', .2, 'rad'),\n Variable('roll', .5, 'rad'),\n Variable('wind_x', 5, 'm/s'),\n Variable('wind_y', 4, 'm/s'),\n Variable('wind_z', 1, 'm/s')\n ]\n\n rs = np.random.RandomState(seed) # seed the random number generator\n\n with h5py.File(filename, 'w') as f:\n for v in variables:\n ds = f.create_dataset(v.name, data=v.sigma*rs.randn(nruns))\n ds.attrs['unit'] = v.unit\n\ndef start():\n \"\"\"Show intro messages.\"\"\"\n configure()\n clear()\n print(header_text, end='')\n raw_input()\n clear()\n print(intro_text)\n raw_input('Press return to check your email...')\n clear()\n print(message_text)\n\ndef end():\n \"\"\"Show wrap up message.\"\"\"\n clear()\n print(end_text)\n\ndef clear():\n \"\"\"Clear the screen.\"\"\"\n os.system('clear')\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(description='python adventure game',\n add_help=False)\n parser.add_argument('action', choices=('help', 'start', 'end', 'configure'),\n help='action', nargs='?', default='help')\n args = parser.parse_args()\n\n if args.action == 'configure':\n configure()\n elif args.action == 'start':\n start()\n elif args.action == 'end':\n end()\n elif args.action == 'help':\n parser.print_help()\n"
] |
[
[
"numpy.random.RandomState"
]
] |
Aquaveo/tethysext-atcore
|
[
"7a83ccea24fdbbe806f12154f938554dd6c8015f"
] |
[
"tethysext/atcore/tests/integrated_tests/controllers/resource_workflows/results_views/plot_workflow_results_view_tests.py"
] |
[
"from unittest import mock\nimport pandas as pd\nfrom tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view import PlotWorkflowResultView # noqa: E501\nfrom tethysext.atcore.tests.utilities.sqlalchemy_helpers import SqlAlchemyTestCase\nfrom tethysext.atcore.tests.utilities.sqlalchemy_helpers import setup_module_for_sqlalchemy_tests, \\\n tear_down_module_for_sqlalchemy_tests\nfrom datetime import datetime\nimport numpy as np\n\n\ndef setUpModule():\n setup_module_for_sqlalchemy_tests()\n\n\ndef tearDownModule():\n tear_down_module_for_sqlalchemy_tests()\n\n\nclass PlotWorkflowResultViewTests(SqlAlchemyTestCase):\n def setUp(self):\n super().setUp()\n self.instance = PlotWorkflowResultView()\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.BokehView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_bokeh(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'BokehView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n mock_pandas_data = mock.MagicMock(spec=pd.DataFrame)\n mock_pandas_data.columns = ['foo', 'bar', 'baz']\n mock_result.name = 'title'\n mock_result.datasets = [{\n 'title': 'series title',\n 'dataset': mock_pandas_data,\n }]\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['bokeh', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'BokehView',\n }\n mock_sup_get_context.return_value = {}\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n\n mock_options.get.assert_has_calls([\n mock.call('page_title', 'title'),\n mock.call('no_dataset_message', 'No dataset found.')],\n )\n\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotlyView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_plotly(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'PlotlyView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n mock_pandas_data_x = mock.MagicMock(spec=pd.DataFrame, to_list=mock.MagicMock())\n mock_pandas_data_y = mock.MagicMock(spec=pd.DataFrame, to_list=mock.MagicMock())\n mock_pandas_data_x.to_list.side_effect = [[1, 2, 3]]\n mock_pandas_data_y.to_list.side_effect = [[4, 5, 6]]\n mock_result.name = 'page_title'\n data_test = [[datetime(2020, 1, 1), 5], [datetime(2020, 1, 2), 6], [datetime(2020, 1, 3), 7],\n [datetime(2020, 1, 4), 8], [datetime(2020, 1, 5), 9], [datetime(2020, 1, 6), 10]]\n\n df = pd.DataFrame(data=data_test)\n mock_result.datasets = [{\n 'title': 'series title',\n 'dataset': df,\n }]\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['plotly', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'PlotlyView',\n }\n mock_sup_get_context.return_value = {}\n\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotlyView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_plot_object(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'PlotlyView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n mock_result.name = 'page_title'\n mock_result.datasets = [{\n 'plot_object': 'plot_object',\n }]\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['plotly', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'PlotlyView',\n }\n mock_sup_get_context.return_value = {}\n\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.BokehView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_bokeh_add_series_list(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'BokehView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n data_test = [[datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5),\n datetime(2020, 1, 6), datetime(2020, 1, 7)], [2, 3, 4, 5, 6, 7]]\n\n mock_result.datasets = [{\n 'title': 'series title',\n 'dataset': data_test,\n }]\n\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['bokeh', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'BokehView',\n }\n mock_sup_get_context.return_value = {}\n\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.BokehView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_bokeh_scatter_add_series_list(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'BokehView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n data_test = [[datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5),\n datetime(2020, 1, 6), datetime(2020, 1, 7)], [2, 3, 4, 5, 6, 7]]\n\n mock_result.datasets = [{\n 'title': 'series title',\n 'dataset': data_test,\n }]\n\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['bokeh', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'BokehView',\n }\n mock_sup_get_context.return_value = {}\n\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotlyView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_add_series_list(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'PlotlyView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n data_test = [[datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4), datetime(2020, 1, 5),\n datetime(2020, 1, 6), datetime(2020, 1, 7)], [2, 3, 4, 5, 6, 7]]\n\n mock_result.datasets = [{\n 'title': 'series title',\n 'dataset': data_test,\n }]\n\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['plotly', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'PlotlyView',\n }\n mock_sup_get_context.return_value = {}\n\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotlyView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_add_series_numpy(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'PlotlyView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n data_test = [np.arange('2020-01-02', '2020-01-07', dtype='datetime64[D]'), np.array([1, 2, 3, 4, 5, 6])]\n\n mock_result.datasets = [{\n 'title': 'series title',\n 'dataset': data_test,\n }]\n\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['plotly', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'PlotlyView',\n }\n mock_sup_get_context.return_value = {}\n\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotlyView') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.results_views.plot_workflow_results_view.PlotWorkflowResultView.get_result') # noqa: E501\n @mock.patch('tethysext.atcore.controllers.resource_workflows.workflow_results_view.WorkflowResultsView.get_context') # noqa: E501\n def test_get_context_add_series_pandas_multiple_columns(self, mock_sup_get_context, mock_get_result, mock_plot):\n mock_resource = mock.MagicMock()\n mock_request = mock.MagicMock()\n mock_session = mock.MagicMock()\n mock_context = mock.MagicMock()\n mock_model_db = mock.MagicMock()\n mock_workflow_id = mock.MagicMock()\n mock_step_id = mock.MagicMock()\n mock_result_id = mock.MagicMock()\n mock_plot.return_value = 'PlotlyView'\n mock_result = mock.MagicMock(get_plot_object=mock_plot)\n mock_get_result.return_value = mock_result\n\n data_test = {\n 'x': [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3), datetime(2020, 1, 4),\n datetime(2020, 1, 5), datetime(2020, 1, 6)],\n 'y': [2, 4, 8, 16, 25, 36],\n 'y2': [3, 3*3, 9*3, 27*3, 9*3, 9],\n }\n data_test = pd.DataFrame(data=data_test)\n\n mock_result.datasets = [{\n 'dataset': data_test,\n 'series_axes': [('x', 'y'), ('x', 'y1'), ('x', 'y2')],\n 'series_labels':['s1', 's2', 's3'],\n }]\n\n mock_options = mock.MagicMock(get=mock.MagicMock())\n mock_result.options = mock_options\n mock_options.get.side_effect = ['plotly', 'page title', 'No dataset found.']\n baseline = {\n 'page_title': 'page title',\n 'no_dataset_message': 'No dataset found.',\n 'plot_view_input': 'PlotlyView',\n }\n mock_sup_get_context.return_value = {}\n\n ret = self.instance.get_context(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n # Test all things were called here\n mock_sup_get_context.assert_called_with(\n request=mock_request,\n session=mock_session,\n resource=mock_resource,\n context=mock_context,\n model_db=mock_model_db,\n workflow_id=mock_workflow_id,\n step_id=mock_step_id,\n result_id=mock_result_id\n )\n\n mock_get_result.assert_called_with(\n request=mock_request,\n result_id=mock_result_id,\n session=mock_session\n )\n self.assertEqual(baseline['no_dataset_message'], ret['no_dataset_message'])\n self.assertEqual(baseline['plot_view_input'], ret['plot_view_input'])\n"
] |
[
[
"numpy.arange",
"numpy.array",
"pandas.DataFrame"
]
] |
oawiles/habitat-api
|
[
"b6a08dac1b9e92e6ad0d66d75cf9cee0ee1ebaef"
] |
[
"habitat_baselines/slambased/mappers.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom habitat_baselines.slambased.reprojection import (\n get_map_size_in_cells,\n project2d_pcl_into_worldmap,\n reproject_local_to_global,\n)\n\n\ndef depth2local3d(depth, fx, fy, cx, cy):\n r\"\"\"Projects depth map to 3d point cloud\n with origin in the camera focus\n \"\"\"\n device = depth.device\n h, w = depth.squeeze().size()\n x = torch.linspace(0, w - 1, w).to(device)\n y = torch.linspace(0, h - 1, h).to(device)\n xv, yv = torch.meshgrid([x, y])\n dfl = depth.t().flatten()\n return torch.cat(\n [\n (dfl * (xv.flatten() - cx) / fx).unsqueeze(-1), # x\n (dfl * (yv.flatten() - cy) / fy).unsqueeze(-1), # y\n dfl.unsqueeze(-1),\n ],\n dim=1,\n ) # z\n\n\ndef pcl_to_obstacles(pts3d, map_size=40, cell_size=0.2, min_pts=10):\n r\"\"\"Counts number of 3d points in 2d map cell.\n Height is sum-pooled.\n \"\"\"\n device = pts3d.device\n map_size_in_cells = get_map_size_in_cells(map_size, cell_size) - 1\n init_map = torch.zeros(\n (map_size_in_cells, map_size_in_cells), device=device\n )\n if len(pts3d) <= 1:\n return init_map\n num_pts, dim = pts3d.size()\n pts2d = torch.cat([pts3d[:, 2:3], pts3d[:, 0:1]], dim=1)\n data_idxs = torch.round(\n project2d_pcl_into_worldmap(pts2d, map_size, cell_size)\n )\n if len(data_idxs) > min_pts:\n u, counts = np.unique(\n data_idxs.detach().cpu().numpy(), axis=0, return_counts=True\n )\n init_map[u[:, 0], u[:, 1]] = torch.from_numpy(counts).to(\n dtype=torch.float32, device=device\n )\n return init_map\n\n\nclass DirectDepthMapper(nn.Module):\n r\"\"\"Estimates obstacle map given the depth image\n ToDo: replace numpy histogram counting with differentiable\n pytorch soft count like in\n https://papers.nips.cc/paper/7545-unsupervised-learning-of-shape-and-pose-with-differentiable-point-clouds.pdf\n \"\"\"\n\n def __init__(\n self,\n camera_height=0,\n near_th=0.1,\n far_th=4.0,\n h_min=0.0,\n h_max=1.0,\n map_size=40,\n map_cell_size=0.1,\n device=torch.device(\"cpu\"),\n **kwargs\n ):\n super(DirectDepthMapper, self).__init__()\n self.device = device\n self.near_th = near_th\n self.far_th = far_th\n self.h_min_th = h_min\n self.h_max_th = h_max\n self.camera_height = camera_height\n self.map_size_meters = map_size\n self.map_cell_size = map_cell_size\n return\n\n def forward(self, depth, pose=torch.eye(4).float()):\n self.device = depth.device\n # Works for FOV = 90 degrees\n # Should be adjusted, if FOV changed\n self.fx = float(depth.size(1)) / 2.0\n self.fy = float(depth.size(0)) / 2.0\n self.cx = int(self.fx) - 1\n self.cy = int(self.fy) - 1\n pose = pose.to(self.device)\n local_3d_pcl = depth2local3d(depth, self.fx, self.fy, self.cx, self.cy)\n idxs = (torch.abs(local_3d_pcl[:, 2]) < self.far_th) * (\n torch.abs(local_3d_pcl[:, 2]) >= self.near_th\n )\n survived_points = local_3d_pcl[idxs]\n if len(survived_points) < 20:\n map_size_in_cells = (\n get_map_size_in_cells(self.map_size_meters, self.map_cell_size)\n - 1\n )\n init_map = torch.zeros(\n (map_size_in_cells, map_size_in_cells), device=self.device\n )\n return init_map\n global_3d_pcl = reproject_local_to_global(survived_points, pose)[:, :3]\n # Because originally y looks down and from agent camera height\n global_3d_pcl[:, 1] = -global_3d_pcl[:, 1] + self.camera_height\n idxs = (global_3d_pcl[:, 1] > self.h_min_th) * (\n global_3d_pcl[:, 1] < self.h_max_th\n )\n global_3d_pcl = global_3d_pcl[idxs]\n obstacle_map = pcl_to_obstacles(\n global_3d_pcl, self.map_size_meters, self.map_cell_size\n )\n return obstacle_map\n"
] |
[
[
"torch.abs",
"torch.linspace",
"torch.cat",
"torch.zeros",
"torch.eye",
"torch.from_numpy",
"torch.device",
"torch.meshgrid"
]
] |
Wonseok-Oh/gym_hiprlgrid
|
[
"7a67ef8f3f6cf50062be76e909bfc6ac6de568c9"
] |
[
"gym_minigrid/envs/multi_hiprlgrid_short_pose.py"
] |
[
"from gym_minigrid.minigrid import *\nfrom gym_minigrid.register import register\nfrom gym_minigrid.envs.empty import EmptyEnv\nimport numpy as np\nfrom SpatialMap import SpatialMap, ObjectMap, BinaryMap, BinaryMap_MLP, ObjectMap_MLP\nimport rospy\nfrom std_srvs.srv import Empty\nfrom rosplan_dispatch_msgs.srv import DispatchService\nfrom nav_msgs.msg import OccupancyGrid\nfrom std_msgs.msg import Int32MultiArray\nfrom find_frontier.msg import ActionArray\nfrom geometry_msgs.msg import PoseStamped, TransformStamped, PoseArray, Pose\nfrom tf import transformations\nimport time, copy\nimport roslaunch\nfrom rosparam import upload_params\nfrom yaml import load\n\nfrom find_frontier.srv import *\nfrom hiprl_replicate.msg import Obs, Obs_multi\nfrom hiprl_replicate.srv import ActionExecution, ActionExecutionRequest\nfrom rosplan_dispatch_msgs.msg import CompletePlan\nfrom rosplan_knowledge_msgs.msg import processReset\n\n#import tf_conversions\n#import tf2_ros\nfrom math import pi\n#from builtins import None\n\n\n\nclass MultiHiPRLGridShortPoseV0(MiniGridEnv):\n \"\"\"\n Environment similar to kitchen.\n This environment has goals and rewards.\n \"\"\"\n def dir_vec_i(self, id):\n \"\"\"\n Get the direction vector for the agent, pointing in the direction\n of forward movement.\n \"\"\"\n\n assert self.agents[id].dir >= 0 and self.agents[id].dir < 4\n return DIR_TO_VEC[self.agents[id].dir]\n\n def right_vec_i(self, id):\n \"\"\"\n Get the vector pointing to the right of the agent.\n \"\"\"\n\n dx, dy = self.dir_vec_i(id)\n return np.array((-dy, dx))\n \n class Agent(object):\n def __init__(self, id, multihiprlgridshortposev0):\n self.multihiprlgridshortposev0 = multihiprlgridshortposev0\n self.mode = self.multihiprlgridshortposev0.Option_mode.init\n self.pos = None\n self.prev_pos = None\n self.dir = None\n self.prev_dir = None\n self.id = id\n self.action_list = []\n self.carrying = None\n self.preCarrying = None\n\n def front_pos(self):\n assert self.dir>= 0 and self.dir < 4\n return self.pos + DIR_TO_VEC[self.dir]\n\n # Enumeration of possible actions\n class MetaActions(IntEnum):\n # explore, scan, plan\n explore = 0\n scan = 1\n plan = 2\n #keep_previous = 3\n # stop this episode\n #stop = 3\n \n class Option_mode(IntEnum):\n init = 0\n explore = 1\n scan = 2\n plan = 3 \n \n class PlanningMode(IntEnum):\n search = 0\n keep = 1\n bring = 2\n \n def place_agent_i(\n self,\n id = 0,\n top=None,\n size=None,\n rand_dir=True,\n max_tries=math.inf\n ):\n \"\"\"\n Set the agent's starting point at an empty position in the grid\n \"\"\"\n\n self.agents[id].pos = None\n pos = self.place_obj_multi(None, top, size, max_tries=max_tries)\n self.agents[id].pos = pos\n\n if rand_dir:\n self.agents[id].dir = self._rand_int(0, 4)\n return pos\n \n def place_obj_multi(self,\n obj,\n top=None,\n size=None,\n reject_fn=None,\n max_tries=math.inf\n ):\n \"\"\"\n Place an object at an empty position in the grid\n\n :param top: top-left position of the rectangle where to place\n :param size: size of the rectangle where to place\n :param reject_fn: function to filter out potential positions\n \"\"\"\n\n if top is None:\n top = (0, 0)\n else:\n top = (max(top[0], 0), max(top[1], 0))\n\n if size is None:\n size = (self.grid.width, self.grid.height)\n\n num_tries = 0\n\n while True:\n # This is to handle with rare cases where rejection sampling\n # gets stuck in an infinite loop\n# if obj is not None:\n# print('placing object %s' %(obj.type))\n \n if num_tries > max_tries:\n raise RecursionError('rejection sampling failed in place_obj')\n\n num_tries += 1\n\n pos = np.array((\n self._rand_int(top[0], min(top[0] + size[0], self.grid.width)),\n self._rand_int(top[1], min(top[1] + size[1], self.grid.height))\n ))\n\n # Don't place the object on top of another object\n if self.grid.get(*pos) != None:\n continue\n\n obj_agent_same_pos = False\n # Don't place the object where the agent is\n for agent in self.agents:\n if np.array_equal(pos, agent.pos):\n obj_agent_same_pos = True\n break\n if obj_agent_same_pos:\n continue\n\n # Check if there is a filtering criterion\n if reject_fn and reject_fn(self, pos):\n continue\n\n break\n\n self.grid.set(*pos, obj)\n\n if obj is not None:\n obj.init_pos = pos\n obj.cur_pos = pos\n\n return pos\n \n \n \n def __init__(self, grid_size_ = 20, max_steps_ = 200, agent_view_size_ = 5, num_objects=1, num_boxes = 10, process_num = 0, num_agents=3):\n self.agents = [self.Agent(i, self) for i in range(num_agents)]\n self.num_agents = num_agents\n see_through_walls = False\n seed = 1337\n self.process_num = process_num\n self.mode = self.Option_mode.init\n\n width = None\n height = None\n\n # Can't set both grid_size and width/height\n if grid_size_:\n assert width == None and height == None\n width = grid_size_\n height = grid_size_\n\n # Action enumeration for this environment\n self.actions = MiniGridEnv.Actions\n\n # Actions are discrete integer values\n self.action_space = spaces.MultiDiscrete([len(self.actions), len(self.actions), len(self.actions)])\n \n # Number of cells (width and height) in the agent view\n assert agent_view_size_ % 2 == 1\n assert agent_view_size_ >= 3\n self.agent_view_size = agent_view_size_\n\n # Meta action enumeration for this environment\n self.meta_actions = self.MetaActions\n \n # Meta actions are discrete integer values\n self.meta_action_space = spaces.MultiDiscrete([len(self.meta_actions), len(self.meta_actions), len(self.meta_actions)])\n \n # total action space & meta action space\n #self.total_action_space = [self.action_space for i in range(num_agents)]\n #self.total_meta_action_space = [self.meta_action_space for i in range(num_agents)]\n\n self.observation_space = spaces.Box(\n low=0,\n high=255,\n shape=(width*height*10+3,),\n dtype='uint8'\n )\n\n # variable to check whether the mission complete or not\n self.success = False\n print('gym_env' + str(process_num))\n\n # ROS Environment for communication with external process (explorer, knowledge manager, planner)\n if (process_num % 8 == 0):\n self.init_node = rospy.init_node('gym_env' + str(process_num), anonymous=True)\n self.spatial_map_pub = rospy.Publisher(\"spatial_map\" + str(process_num), OccupancyGrid, queue_size = 1, latch=True)\n self.object_map_pub = rospy.Publisher(\"object_map\" + str(process_num), OccupancyGrid, queue_size = 1)\n self.agent_pos_pub = rospy.Publisher(\"pose\" + str(process_num), PoseArray, queue_size = 1, latch=True)\n\n self.agents_pose_pub_vis = []\n for i in range(num_agents):\n self.agents_pose_pub_vis.append(rospy.Publisher(\"pose\" + str(process_num) +'_'+ str(i), PoseStamped, queue_size = 1, latch=True))\n self.goal_pos_pub = rospy.Publisher(\"goal_pose\" + str(process_num), PoseStamped, queue_size = 1, latch=True)\n self.agent_init_pos_pub = rospy.Publisher(\"initial_pose\" + str(process_num), PoseArray, queue_size = 1, latch=True)\n self.navigation_map_pub = rospy.Publisher(\"navigation_map\" + str(process_num), OccupancyGrid, queue_size = 1, latch=True)\n self.planning_map_pub = rospy.Publisher(\"planning_map\" + str(process_num), OccupancyGrid, queue_size = 1, latch=True)\n self.explore_action_sub = rospy.Subscriber(\"action_plan\" + str(process_num), ActionArray, self.explore_plan_cb)\n self.observation_pub = rospy.Publisher(\"observation\" + str(process_num), Obs_multi, queue_size = 1)\n self.reset_pub = rospy.Publisher(\"rosplan_knowledge_base\" + str(process_num)+ \"/reset\", processReset, queue_size = 1, latch=True)\n #self.action_service = rospy.Service(\"action_execution\", ActionExecution, self.execute_action)\n self.complete_plan_sub = rospy.Subscriber(\"complete_plan\"+ str(process_num), ActionArray, self.complete_plan_cb)\n #self.complete_plan_sub = []\n #for i in range(num_agents):\n # self.complete_plan_sub.append(rospy.Subscriber(\"/rosplan_parsing_interface\"+ str(process_num) + \"_\" + str(i) + \"/complete_plan\" , CompletePlan, self.complete_plan_cb, (i)))\n\n # Reward Coefficients\n self.coverage_reward_coeff = 0.00002\n self.open_reward_coeff = 0.01\n self.carry_reward_coeff = 0.2\n \n # Map initialize\n self.spatial_map = SpatialMap(grid_size_, grid_size_)\n self.object_map = ObjectMap(grid_size_, grid_size_, 3)\n \n # Planning mode init\n self.planning_mode = self.PlanningMode.search\n \n #self.floor_map_one_hot = BinaryMap(grid_size_, grid_size_)\n #self.goal_map_one_hot = BinaryMap(grid_size_, grid_size_)\n #self.wall_map_one_hot = BinaryMap(grid_size_, grid_size_)\n #self.box_map_one_hot = BinaryMap(grid_size_, grid_size_)\n #self.checked_box_map_one_hot = BinaryMap(grid_size_, grid_size_)\n #self.ball_map_one_hot = BinaryMap(grid_size_, grid_size_)\n #self.unknown_map_one_hot = BinaryMap(grid_size_, grid_size_)\n\n self.floor_map_one_hot = BinaryMap_MLP(grid_size_, grid_size_)\n self.goal_map_one_hot = BinaryMap_MLP(grid_size_, grid_size_)\n self.wall_map_one_hot = BinaryMap_MLP(grid_size_, grid_size_)\n self.box_map_one_hot = BinaryMap_MLP(grid_size_, grid_size_)\n self.checked_box_map_one_hot = BinaryMap_MLP(grid_size_, grid_size_)\n self.ball_map_one_hot = BinaryMap_MLP(grid_size_, grid_size_)\n self.unknown_map_one_hot = BinaryMap_MLP(grid_size_, grid_size_)\n \n self.num_objects = num_objects\n self.num_boxes = num_boxes\n self.width = grid_size_\n self.height = grid_size_\n self.render_counter = 0\n self.explore_action_list = []\n self.explore_action_set = False\n self.complete_plan = [] * self.num_agents\n self.complete_plan_flag = False\n self.complete_plan_id_list = set([])\n self.goal_pos = None\n self.planner_action_num = 0\n\n # Environment configuration\n self.width = width\n self.height = height\n self.max_steps = max_steps_\n self.see_through_walls = see_through_walls\n\n self.seed(seed = seed)\n self.reset()\n #return self.reset()\n #print(obs)\n #self.update_maps(obs, None)\n #print(\"agent_pos: %d, %d\" %(self.agent_pos[0], self.agent_pos[1]))\n #print(\"agent_dir: %d\" % self.agent_dir)\n #print(\"map_size: %d x %d\" %(self.spatial_map.map.info.width, self.spatial_map.map.info.height))\n# for i in range(5):\n# self.spatial_map_pub.publish(self.spatial_map.map)\n# self.object_map_pub.publish(self.object_map.map)\n# self.spatial_map.rate.sleep()\n\n #def __del__(self):\n #self.process0.stop()\n #self.process1.stop()\n #self.process2.stop()\n #self.process3.stop()\n #self.process4.stop()\n #self.process5.stop()\n #self.process6.stop()\n #self.launch.stop()\n #rospy.signal_shutdown(\"End class\")\n\n def complete_plan_cb(self, msg):\n self.complete_plan_flag = True\n print(\"complete_plan: {}\".format(msg))\n\n def generate_actions_from_complete_plan(self, id_list):\n potential_goal_update = False\n planner_tracking_dir = [-1] * self.num_agents\n for i in id_list:\n planner_tracking_dir[i] = self.agents[i].dir\n self.agents[i].action_list = []\n \n prev_time = 0\n actions = []\n for item in self.complete_plan:\n item_actions = []\n prev_time = item_time\n item_time = item.dispatch_time * 1000\n \n # if one timestep passed, let rest of agent do nothing\n if item_time - prev_time >= 1:\n current_max_len = 0\n for i in id_list:\n if len(self.agents[i].action_list) > current_max_len:\n current_max_len = len(self.agents[i].action_list)\n \n for i in id_list:\n if current_max_len > len(self.agents[i].action_list):\n for j in range(current_max_len - len(self.agents[i].action_list)):\n self.agents[i].action_list.append(self.Actions.done)\n \n agent_key_value = item.parameters[0]\n \n # the robot parameter should be set as 'a'\n assert(agent_key_value.key == 'a')\n\n agent_num = agent_key_value.value\n #print('agent: {}'.format(agent_num))\n agent_num = int(agent_num[-1])\n #print('agent_num: {}'.format(agent_num))\n \n dir_key_value = item.parameters[-1]\n \n # the last parameter should set key as dir\n assert(dir_key_value.key == 'dir')\n \n # make robot to face given direction\n if dir_key_value.value == 'left':\n goal_dir = 2\n elif dir_key_value.value == 'up':\n goal_dir = 3\n elif dir_key_value.value == 'right':\n goal_dir = 0\n elif dir_key_value.value == 'down':\n goal_dir = 1\n\n dth = planner_tracking_dir[agent_num] - goal_dir\n if dth < 0:\n dth += 4\n if dth == 3:\n item_actions.append(self.Actions.right)\n \n else:\n for i in range(dth):\n item_actions.append(self.Actions.left)\n \n planner_tracking_dir[agent_num] = goal_dir\n if item.name == \"move-robot\":\n item_actions.append(self.Actions.forward)\n \n \n elif item.name == \"openobject\":\n item_actions.append(self.Actions.open)\n potential_goal_update = True\n \n elif item.name == \"pickupobjectinreceptacle\" or item.name == \"pickupobject\":\n item_actions.append(self.Actions.pickup)\n potential_goal_update = True\n \n elif item.name == \"putobjectinreceptacle\" or item.name == \"putobject\":\n item_actions.append(self.Actions.drop)\n \n elif item.name == \"closeobject\":\n item_actions.append(self.Actions.close)\n \n actions.append((item, item_actions, potential_goal_update))\n \n for action in item_actions:\n self.agents[agent_num].action_list.append(action)\n \n return actions\n \n def explore_plan_cb(self, msg):\n print(\"Explore_plan_cb called\")\n j = 0\n min_len = 1000\n for i in range(self.num_agents):\n if self.agents[i].mode != self.Option_mode.explore:\n continue\n \n if j >= len(msg.list):\n break\n \n #print(\"len(msg.list): {}, j: {}\".format(len(msg.list), j))\n if len(msg.list) > 0 and len(msg.list[j].data) < min_len and len(msg.list[j].data) > 1:\n min_len = len(msg.list[j].data) \n #print(\"agent {}'s action length: {}\".format(i, len(msg.list[j].data)))\n self.agents[i].action_list = [0] * len(msg.list[j].data)\n for k in range(len(msg.list[j].data)):\n self.agents[i].action_list[k] = msg.list[j].data[k]\n \n j = j + 1\n \n j = 0\n for i in range(self.num_agents):\n if self.agents[i].mode != self.Option_mode.explore:\n continue\n \n if j >= len(msg.list):\n break\n \n if len(msg.list) > 0 and len(msg.list[j].data) <= 1:\n if len(msg.list[j].data) == 0 or msg.list[j].data[0] < 0:\n #self.agents[i].action_list = [self.Actions.done] * min_len\n self.meaningless = True\n j = j + 1\n \n if min_len == 1000:\n for i in range(self.num_agents):\n if self.agents[i].mode != self.Option_mode.explore:\n continue\n #self.agents[i].action_list = [self.Actions.done]\n self.meaningless = True\n self.explore_action_set = True\n \n\n def _gen_grid(self, width, height):\n # Create the grid\n self.grid = Grid(width, height)\n\n # Generate the surrounding walls\n self.grid.horz_wall(0, 0)\n self.grid.horz_wall(0, height-1)\n self.grid.vert_wall(0, 0)\n self.grid.vert_wall(width-1, 0)\n\n # Types and colors of objects we can generate\n types = ['key', 'ball']\n\n objs = []\n objPos = []\n boxes = []\n self.boxPos = []\n\n def near_obj(env, p1):\n for p2 in objPos:\n dx = p1[0] - p2[0]\n dy = p1[1] - p2[1]\n if abs(dx) <= 1 and abs(dy) <= 1:\n return True\n return False\n # initially, put a box containing a ball\n boxColor = self._rand_elem(COLOR_NAMES)\n objColor = self._rand_elem(COLOR_NAMES)\n obj = Box(len(boxes), boxColor, Ball(len(objs), objColor) )\n boxes.append(boxColor)\n objs.append(('ball', objColor))\n pos = self.place_obj_multi(obj, reject_fn=near_obj)\n objPos.append(pos)\n self.boxPos.append(pos)\n # Until we have generated all the objects\n while len(objs) < self.num_objects:\n objType = self._rand_elem(types)\n objColor = self._rand_elem(COLOR_NAMES)\n\n # If this object already exists, try again\n if (objType, objColor) in objs:\n continue\n\n if objType == 'key':\n obj = Key(len(objs), objColor)\n elif objType == 'ball':\n obj = Ball(len(objs), objColor)\n \n pos = self.place_obj_multi(obj, reject_fn=near_obj)\n\n objs.append((objType, objColor))\n objPos.append(pos)\n\n while len(boxes) < self.num_boxes:\n boxColor = self._rand_elem(COLOR_NAMES)\n \n # If this object already exists, try again\n #if boxColor in boxes:\n # continue\n \n box = Box(len(boxes), boxColor)\n #print(\"box.isOpen: %d\" % box.isOpen)\n pos = self.place_obj_multi(box, reject_fn=near_obj)\n boxes.append(boxColor)\n self.boxPos.append(pos)\n \n # place a goal \n obj = Goal()\n objColor = self._rand_elem(COLOR_NAMES)\n self.goal_pos = self.place_obj_multi(obj, reject_fn = near_obj)\n \n # publish the goal position to update the knowledge base\n self.publish_ros_goal_pos(self.goal_pos)\n \n # Randomize the agent start position and orientation\n for i in range(len(self.agents)):\n self.place_agent_i(i)\n\n # Choose a random object to be moved\n self.objIdx = self._rand_int(0, len(objs))\n self.move_type, self.moveColor = objs[self.objIdx]\n self.move_pos = objPos[self.objIdx]\n\n # Choose a target object (to put the first object into)\n self.target_pos = self.goal_pos\n\n self.mission = 'put the %s %s into the goal' % (\n self.moveColor,\n self.move_type,\n )\n \n def reset(self):\n #print(\"reset is called\")\n for agent in self.agents:\n agent.pos = None\n agent.dir = None\n \n # Item picked up, being carried, initially nothing\n agent.carrying = None\n agent.preCarrying = None\n agent.mode = agent.multihiprlgridshortposev0.Option_mode.init\n agent.prev_pos = None\n agent.prev_dir = None\n agent.action_list = []\n \n \n # Generate a new random grid at the start of each episode\n # To keep the same grid for each episode, call env.seed() with\n # the same seed before calling env.reset()\n self._gen_grid(self.width, self.height)\n \n # These fields should be defined by _gen_grid\n for agent in self.agents:\n #print(\"agent.pos: {}\".format(agent.pos))\n #print(\"agent.dir: {}\".format(agent.dir))\n\n assert agent.pos is not None\n assert agent.dir is not None\n \n # Check that the agent doesn't overlap with an object\n for agent in self.agents:\n start_cell = self.grid.get(*agent.pos)\n assert start_cell is None or start_cell.can_overlap()\n \n # Step count since episode start\n self.step_count = 0\n \n self.opened_receptacles = set()\n self.closed_receptacles = set()\n self.seen_obj = set()\n self.seen_receptacles = set()\n self.checked_receptacles = set()\n self.visited_locations = set()\n self.can_end = False\n self.object_map = ObjectMap(self.width, self.height, 3)\n self.spatial_map = SpatialMap(self.width, self.height)\n self.object_map_mlp = ObjectMap_MLP(self.width, self.height, ObjectMap_MLP.ObjGridStates.unknown)\n \n self.floor_map_one_hot = BinaryMap_MLP(self.width, self.height)\n self.goal_map_one_hot = BinaryMap_MLP(self.width, self.height)\n self.wall_map_one_hot = BinaryMap_MLP(self.width, self.height)\n self.box_map_one_hot = BinaryMap_MLP(self.width, self.height)\n self.checked_box_map_one_hot = BinaryMap_MLP(self.width, self.height)\n self.ball_map_one_hot = BinaryMap_MLP(self.width, self.height)\n self.unknown_map_one_hot = BinaryMap_MLP(self.width, self.height, value = 1)\n \n self.planning_mode = self.PlanningMode.search\n \n self.new_coverage = 0\n self.prev_agent_pos = None\n self.render_counter = 0\n self.explore_action_set = False\n #self.planner_action_set = False\n #self.planner_action_plan = []\n self.planner_action_num = 0\n #self.dispatch_plan_end = True\n self.action_execution_flag = False\n self.complete_plan = []\n self.complete_plan_flag = False\n reset_msg = processReset()\n reset_msg.domain_path = \"/home/morin/catkin_ws/src/hiprl_replicate/pddl/hiprl_mini_multi.pddl\"\n reset_msg.problem_path = \"/home/morin/catkin_ws/src/hiprl_replicate/pddl/hiprl_problem0_multi.pddl\"\n self.reset_pub.publish(reset_msg)\n obs = self.gen_obs()\n \n # Temporal comment for test\n self.update_maps(obs, None)\n self.spatial_map_pub.publish(self.spatial_map.map)\n self.object_map_pub.publish(self.object_map.map)\n self.agent_init_pos = self.publish_ros_agent_pos()\n self.agent_init_dir = [self.agents[i].dir for i in range(len(self.agents))] \n self.agent_init_pos_pub.publish(self.agent_init_pos)\n self.publish_observation(obs['image'])\n self.success = False\n self.meaningless = False\n #return obs['image']\n \n return self.generate_network_input_one_hot_for_mlp(obs)\n #return np.reshape(self.object_map.map.data, (self.width*self.object_map.factor, self.height*self.object_map.factor))\n \n # Currently, collision is not considered yet --> should be considered\n def step(self, action):\n assert len(action) == self.num_agents\n \n obs_n = []\n reward_n = []\n done_n = []\n info_n = {'n': []}\n i = 0\n \n self.step_count += 1\n reward = 0\n done = False\n for i in range(len(self.agents)):\n info = None\n self.agents[i].preCarrying = self.agents[i].carrying\n self.agents[i].prev_pos = self.agents[i].pos\n self.agents[i].prev_dir = self.agents[i].dir\n fwd_pos = self.agents[i].front_pos()\n fwd_cell = self.grid.get(*fwd_pos)\n \n # Rotate left\n if action[i] == self.actions.left:\n self.agents[i].dir -= 1\n if self.agents[i].dir < 0:\n self.agents[i].dir += 4\n \n # Rotate right\n elif action[i] == self.actions.right:\n self.agents[i].dir = (self.agents[i].dir + 1) % 4\n \n # Move forward\n elif action[i] == self.actions.forward:\n if fwd_cell == None or fwd_cell.can_overlap():\n self.agents[i].pos = fwd_pos\n \n # Pick up an object\n elif action[i] == self.actions.pickup:\n if fwd_cell and fwd_cell.can_pickup():\n if self.agents[i].carrying is None and fwd_cell.type != 'box':\n self.agents[i].carrying = fwd_cell\n self.agents[i].carrying.cur_pos = np.array([-1, -1])\n self.grid.set(*fwd_pos, None)\n elif self.agents[i].carrying is None and fwd_cell.type == 'box':\n self.plannnig_mode = self.PlanningMode.bring\n self.agents[i].carrying = fwd_cell.contains\n self.agents[i].carrying.cur_pos = np.array([-1, -1])\n self.grid.set(*fwd_pos, Box(fwd_cell.objectId, fwd_cell.color, contains = None, isOpen=True))\n \n # Drop an object \n elif action[i] == self.actions.drop:\n if not fwd_cell:\n if self.agents[i].carrying:\n self.grid.set(*fwd_pos, self.agents[i].carrying)\n self.agents[i].carrying.cur_pos = fwd_pos\n self.agents[i].carrying = None\n elif fwd_cell.type == 'box' and fwd_cell.isOpen and fwd_cell.contains == None and self.agents[i].carrying:\n fwd_cell.contains = self.agents[i].carrying\n self.agents[i].carrying.cur_pos = fwd_pos\n self.agents[i].carrying = None\n \n # open an object\n elif action[i] == self.actions.open:\n if fwd_cell and fwd_cell.can_toggle():\n fwd_cell.isOpen = True\n info = fwd_cell\n \n # close an object\n elif action[i] == self.actions.close:\n if fwd_cell and fwd_cell.can_toggle():\n fwd_cell.isOpen = False\n info = fwd_cell\n \n # Done action (not used by default)\n elif action[i] == self.actions.done:\n pass\n\n else:\n assert False, \"unknown action\"\n\n info_n['fwd_cell'+str(i)] = info\n\n\n if self.step_count >= self.max_steps:\n done = True\n\n \n #print(\"agent_pos: %d, %d\" %(self.agent_pos[0], self.agent_pos[1]))\n #print(\"agent_dir: %d\" % self.agent_dir)\n \n #obs, reward, done, info = MiniGridEnv.step(self, action)\n obs = self.gen_obs()\n \n reward = -0.0001 # constant time penalty\n\n # update spatial map & object map\n #print(\"obs: {}\".format(obs))\n self.update_maps(obs, action)\n self.spatial_map_pub.publish(self.spatial_map.map)\n self.object_map_pub.publish(self.object_map.map)\n self.publish_ros_agent_pos()\n \n # publish observation information to update knowledgebase\n self.publish_observation(obs['image'])\n \n #print(obs['image'])\n \n # reward for open/close action\n for i in range(len(self.agents)):\n #print(info) \n if info_n['fwd_cell'+str(i)] is not None:\n if info_n['fwd_cell'+str(i)].can_toggle() and action[i] == self.Actions.open:\n if info_n['fwd_cell'+str(i)].objectId in self.closed_receptacles: # if the receptacle was closed\n self.opened_receptacles.add(info_n['fwd_cell'+str(i)].objectId) # add to the opened_receptacles list\n self.closed_receptacles.discard(info_n['fwd_cell'+str(i)].objectId)\n if info_n['fwd_cell'+str(i)].objectId in self.checked_receptacles: # if the receptacle was checked before, penalize\n reward += -1.0 * self.open_reward_coeff\n else: # else, if it was not checked, give reward\n self.checked_receptacles.add(info_n['fwd_cell'+str(i)].objectId)\n reward += 1.0 * self.open_reward_coeff\n \n elif info_n['fwd_cell'+str(i)].objectId in self.opened_receptacles: # penalty for open opened_receptacles\n reward += -1.0 * self.open_reward_coeff\n elif info_n['fwd_cell'+str(i)].can_toggle() and action[i] == self.Actions.close: \n if info_n['fwd_cell'+str(i)].objectId in self.opened_receptacles: # if the receptacle was opened\n self.closed_receptacles.add(info_n['fwd_cell'+str(i)].objectId) # add to the closed_receptacles list\n self.opened_receptacles.discard(info_n['fwd_cell'+str(i)].objectId)\n \n elif info_n['fwd_cell'+str(i)].objectId in self.closed_receptacles:\n reward += -1.0 * self.open_reward_coeff # penalty for close closed_receptacles \n \n \n # reward(penalize) for carrying (non)target object or \n # just finish the episode\n if self.agents[i].carrying != None:\n if self.objIdx == self.agents[i].carrying.objectId:\n self.planning_mode = self.PlanningMode.bring\n if self.agents[i].preCarrying is None:\n reward += 1.0 * self.carry_reward_coeff\n else:\n if self.agents[i].preCarrying is None:\n reward += -1.0 * self.carry_reward_coeff\n\n # If successfully dropping an object into the target\n u, v = self.dir_vec_i(i)\n ox, oy = (self.agents[i].pos[0] + u, self.agents[i].pos[1] + v)\n tx, ty = self.target_pos\n if action[i] == self.Actions.drop and self.agents[i].preCarrying:\n front_obj = self.grid.get(ox,oy)\n if front_obj.type is 'goal':\n if abs(ox - tx) == 0 and abs(oy - ty) == 0:\n done = True\n self.success = True\n #reward = 1.0\n reward += 1.0\n \n \n # coverage reward\n reward += self.new_coverage * self.coverage_reward_coeff\n\n # reward_for_test\n # reward = 0\n\n \n \n \n # if step num exceed 200, done\n if self.steps_remaining <= 0:\n reward += -0.1\n done = True\n \n\n self.new_coverage = 0\n #print(\"obs: \")\n #print(obs)\n \n #print(self.opened_receptacles)\n #print(self.closed_receptacles)\n #print(self.checked_receptacles)\n obs = self.generate_network_input_one_hot_for_mlp(obs)\n return obs, reward, done, info_n\n\n def publish_observation(self, image):\n ros_msg = Obs_multi()\n for k in range(len(image)):\n agent_observation = Obs()\n for i in range(self.agent_view_size):\n for j in range(self.agent_view_size):\n # print(\"{}'th column, {}'th row\".format(i,j))\n abs_i, abs_j = self.get_world_coordinate_i(i, j, k)\n # print(\"{}, {}\".format(abs_i, abs_j))\n if image[k][i][j][0] == OBJECT_TO_IDX['wall']:\n agent_observation.type_id_list.append(image[k][i][j][0])\n agent_observation.object_id_list.append(0)\n agent_observation.object_pos_list.append(abs_i)\n agent_observation.object_pos_list.append(abs_j)\n agent_observation.object_state_list.append(0)\n \n elif image[k][i][j][0] == OBJECT_TO_IDX['box']:\n agent_observation.type_id_list.append(image[k][i][j][0])\n agent_observation.object_id_list.append(image[k][i][j][3])\n agent_observation.object_pos_list.append(abs_i)\n agent_observation.object_pos_list.append(abs_j)\n agent_observation.object_state_list.append(image[k][i][j][2])\n \n elif image[k][i][j][0] == OBJECT_TO_IDX['empty']:\n agent_observation.type_id_list.append(image[k][i][j][0])\n agent_observation.object_id_list.append(0)\n agent_observation.object_pos_list.append(abs_i)\n agent_observation.object_pos_list.append(abs_j)\n agent_observation.object_state_list.append(0)\n \n elif image[k][i][j][0] == OBJECT_TO_IDX['ball']:\n agent_observation.type_id_list.append(image[k][i][j][0])\n agent_observation.object_id_list.append(image[k][i][j][3])\n agent_observation.object_pos_list.append(abs_i)\n agent_observation.object_pos_list.append(abs_j)\n agent_observation.object_state_list.append(image[k][i][j][2])\n \n elif image[k][i][j][0] == OBJECT_TO_IDX['goal']:\n agent_observation.type_id_list.append(image[k][i][j][0])\n agent_observation.object_id_list.append(0)\n agent_observation.object_pos_list.append(abs_i)\n agent_observation.object_pos_list.append(abs_j)\n agent_observation.object_state_list.append(0)\n\n agent_observation.agent_dir = self.agents[k].dir\n ros_msg.observation_list.append(agent_observation)\n self.observation_pub.publish(ros_msg) \n \n def dispatch_plan(self, actions, render = False):\n print(\"dispatch plan called\")\n reward_sum = 0\n obs, reward, done, info = None, None, None, {'fwd_cell': None}\n if self.dispatch_plan_action_id - self.prev_dispatch_plan_action_id > 0 and len(actions) > 0:\n precondition_check = self.check_precondition(actions[self.dispatch_plan_action_id][0])\n if precondition_check == False:\n print(\"dispatch_plan: {} precondition not achieved\".format(actions[self.dispatch_plan_action_id][0].name))\n self.dispatch_plan_action_id = 0\n self.prev_dispatch_plan_action_id = -1\n return None, None, None, None\n # dispatch plan until potential goal update\n # 'actions[self.dispatch_plan_action_id][2] == False' means it is not potential goal update related semantic action\n print(\"actions length: {}, dispatch_plan_id: {}\".format(len(actions), self.dispatch_plan_action_id))\n print(\"actions self.dispatch_plan_action_id length: {}\".format(len(actions[self.dispatch_plan_action_id])))\n\n while actions[self.dispatch_plan_action_id][2] == False:\n print(\"actions length: {}, dispatch_plan_id: {}\".format(len(actions), self.dispatch_plan_action_id))\n print(\"actions self.dispatch_plan_action_id length: {}\".format(len(actions[self.dispatch_plan_action_id])))\n\n while len(actions[self.dispatch_plan_action_id][1]) > 0: \n action = actions[self.dispatch_plan_action_id][1].pop(0)\n obs, reward, done, info = self.step(action)\n if render:\n self.render()\n reward_sum += reward\n self.prev_dispatch_plan_action_id = self.dispatch_plan_action_id \n \n # if actions for semantic action is done (= actions[dispatch_plan_action_id][1] is empty)\n if not actions[self.dispatch_plan_action_id][1]:\n self.process_action_effect(actions[self.dispatch_plan_action_id][0])\n if len(actions)-1 > self.dispatch_plan_action_id:\n self.dispatch_plan_action_id += 1\n else:\n break\n \n if self.dispatch_plan_action_id + 1 <= len(actions):\n while len(actions[self.dispatch_plan_action_id][1]) > 0: \n action = actions[self.dispatch_plan_action_id][1].pop(0)\n obs, reward, done, info = self.step(action)\n if render:\n self.render()\n reward_sum += reward\n self.prev_dispatch_plan_action_id = self.dispatch_plan_action_id \n \n # if actions for semantic action is done (= actions[dispatch_plan_action_id][1] is empty)\n if not actions[self.dispatch_plan_action_id][1]:\n self.process_action_effect(actions[self.dispatch_plan_action_id][0])\n if len(actions)-1 > self.dispatch_plan_action_id:\n self.dispatch_plan_action_id += 1\n \n return obs, reward_sum, done, info \n \n def invoke(self, meta_action, render = False):\n reward_sum = 0\n assert len(meta_action) == self.num_agents\n #print(\"mode: {}, meta_action: {}\".format(self.mode, meta_action))\n done = False\n info = {'fwd_cell': None}\n explore_agent_id_list = []\n plan_agent_id_list = []\n scan_agent_id_list = []\n for i in range(len(meta_action)):\n if meta_action[i] == self.meta_actions.explore:\n explore_agent_id_list.append(i)\n self.agents[i].mode = self.Option_mode.explore\n \n elif meta_action[i] == self.meta_actions.plan:\n plan_agent_id_list.append(i)\n self.agents[i].mode = self.Option_mode.plan\n \n elif meta_action[i] == self.meta_actions.scan:\n scan_agent_id_list.append(i)\n self.agents[i].mode = self.Option_mode.scan \n \n if len(explore_agent_id_list) > 0:\n self.explore(explore_agent_id_list)\n \n if len(plan_agent_id_list) > 0:\n self.plan(plan_agent_id_list)\n\n if len(scan_agent_id_list) > 0:\n self.scan(scan_agent_id_list)\n \n min_option_len = 1000 # 1000 is nothing special, just for simple infinity value\n for i in range(len(self.agents)):\n if len(self.agents[i].action_list) < min_option_len:\n min_option_len = len(self.agents[i].action_list)\n \n if self.meaningless: \n done = True\n info['is_mission_succeeded'] = self.success\n info['mission_completion_time'] = self.max_steps - self.steps_remaining\n obs = self.gen_obs()\n map = self.generate_network_input_one_hot_for_mlp(obs)\n return map, -0.1, done, info\n \n \n for i in range(min_option_len):\n action = []\n for j in range(self.num_agents):\n action.append(self.agents[j].action_list.pop(0))\n obs, reward, done, info = self.step(action)\n \n \n reward_sum += reward\n if done:\n info['is_mission_succeeded'] = self.success\n info['mission_completion_time'] = self.max_steps - self.steps_remaining\n return obs, reward_sum, done, info\n \n info['is_mission_succeeded'] = self.success\n info['mission_completion_time'] = self.max_steps - self.steps_remaining\n \n \n obs = self.gen_obs()\n map = self.generate_network_input_one_hot_for_mlp(obs)\n #print(\"map: \")\n #print(map)\n print('%s, Overall reward=%.2f' % (meta_action, reward_sum))\n #print(\"obs: {}, reard_sum: {}, {}, {}, {}\".format(type(obs), type(reward_sum), type(done), type(info), type(map)))\n #return obs, reward_sum, done, info\n return map, reward_sum, done, info #, map\n \n #print('%s, Overall reward=%.2f' % (meta_action, reward_sum))\n #return obs, reward_sum, done, info\n \n\n #obs = self.gen_obs()\n # map = self.generate_network_input(obs)\n #map = self.generate_network_input_one_hot_for_mlp(obs)\n #print(\"map: \")\n #print(map)\n #print('%s, Overall reward=%.2f' % (meta_action, reward_sum))\n #print(\"{}, {}, {}, {}, {}\".format(type(obs), type(reward_sum), type(done), type(info), type(map)))\n #return obs, reward_sum, done, info\n #return map, reward_sum, done, info #, map\n\n def generate_network_input_one_hot_for_mlp(self, obs):\n temp_ball_map = copy.deepcopy(self.ball_map_one_hot)\n map = np.zeros(shape=(20, 20, 10), dtype=np.uint8)\n \n for i in range(self.num_agents):\n obs_grid, _ = Grid.decode(obs['image'][i])\n object = obs_grid.get(obs_grid.width//2, obs_grid.height-1)\n wx, wy = self.get_world_coordinate_i(obs_grid.width//2, obs_grid.height-1, i)\n map[self.agents[i].pos[0],self.spatial_map.map.info.height-self.agents[i].pos[1],7+i] = 1\n if np.array_equal(self.agents[i].pos, np.array([wx,wy])):\n wy = self.spatial_map.map.info.height - wy - 1\n #self.spatial_map.update_cell(np.array([wx,wy]), SpatialMap.OccGridStates.free\n if object is not None and object.type == 'ball':\n temp_ball_map.update_cell(np.array([wx, wy]), 255)\n map[:,:,0] = copy.deepcopy(np.reshape(temp_ball_map.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height))) \n map[:,:,1] = copy.deepcopy(np.reshape(self.box_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,2] = copy.deepcopy(np.reshape(self.checked_box_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,3] = copy.deepcopy(np.reshape(self.floor_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,4] = copy.deepcopy(np.reshape(self.goal_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,5] = copy.deepcopy(np.reshape(self.unknown_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,6] = copy.deepcopy(np.reshape(self.wall_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n flatten_map = np.reshape(map, (20*20*10,))\n \n for i in range(self.num_agents):\n flatten_map = np.append(flatten_map, self.agents[i].carrying is not None)\n #print(\"gen_net_input_one_hot_for_mlp's return shape: {}\".format(flatten_map.shape))\n return flatten_map\n\n\n def generate_network_input_one_hot(self, obs):\n temp_ball_map = copy.deepcopy(self.ball_map_one_hot)\n map = np.zeros(shape=(50, 50, 7), dtype=np.uint8)\n\n obs_grid, _ = Grid.decode(obs['image'])\n object = obs_grid.get(obs_grid.width//2, obs_grid.height-1)\n wx, wy = self.get_world_coordinate(obs_grid.width//2, obs_grid.height-1)\n if np.array_equal(self.agent_pos, np.array([wx,wy])):\n wy = self.spatial_map.map.info.height - wy - 1\n #self.spatial_map.update_cell(np.array([wx,wy]), SpatialMap.OccGridStates.free\n if object is not None and object.type == 'ball':\n temp_ball_map.update_cell(np.array([wx, wy]), 1)\n map[:,:,0] = copy.deepcopy(np.reshape(temp_ball_map.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height))) \n map[:,:,1] = copy.deepcopy(np.reshape(self.box_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,2] = copy.deepcopy(np.reshape(self.checked_box_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,3] = copy.deepcopy(np.reshape(self.floor_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,4] = copy.deepcopy(np.reshape(self.goal_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,5] = copy.deepcopy(np.reshape(self.unknown_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n map[:,:,6] = copy.deepcopy(np.reshape(self.wall_map_one_hot.map.data, (self.ball_map_one_hot.map.info.width, self.ball_map_one_hot.map.info.height)))\n return map\n \n def generate_network_input(self, obs):\n map = copy.deepcopy(self.object_map_mlp)\n #map = np.reshape(self.object_map.map.data, (self.width*self.object_map.factor, self.height*self.object_map.factor))\n obs_grid, _ = Grid.decode(obs['image'])\n object = obs_grid.get(obs_grid.width//2, obs_grid.height-1)\n wx, wy = self.get_world_coordinate(obs_grid.width//2, obs_grid.height-1)\n if np.array_equal(self.agent_pos, np.array([wx,wy])):\n wy = self.spatial_map.map.info.height - wy - 1\n #self.spatial_map.update_cell(np.array([wx,wy]), SpatialMap.OccGridStates.free\n if object is not None and object.type == 'ball':\n map.update_cell(np.array([wx, wy]), ObjectMap_MLP.ObjGridStates.ball+ObjectMap_MLP.ObjGridStates.agent)\n else:\n value = map.get_value(np.array([wx, wy]))\n map.update_cell(np.array([wx, wy]), value + ObjectMap_MLP.ObjGridStates.agent)\n flatten_map = np.reshape(map, (self.width*self.height,))\n return flatten_map\n \n def get_view_exts_i(self, id):\n \"\"\"\n Get the extents of the square set of tiles visible to the agent\n Note: the bottom extent indices are not included in the set\n \"\"\"\n\n # Facing right\n if self.agents[id].dir == 0:\n topX = self.agents[id].pos[0]\n topY = self.agents[id].pos[1] - self.agent_view_size // 2\n # Facing down\n elif self.agents[id].dir == 1:\n topX = self.agents[id].pos[0] - self.agent_view_size // 2\n topY = self.agents[id].pos[1]\n # Facing left\n elif self.agents[id].dir == 2:\n topX = self.agents[id].pos[0] - self.agent_view_size + 1\n topY = self.agents[id].pos[1] - self.agent_view_size // 2\n # Facing up\n elif self.agents[id].dir == 3:\n topX = self.agents[id].pos[0] - self.agent_view_size // 2\n topY = self.agents[id].pos[1] - self.agent_view_size + 1\n else:\n assert False, \"invalid agent direction\"\n\n botX = topX + self.agent_view_size\n botY = topY + self.agent_view_size\n\n return (topX, topY, botX, botY)\n\n def gen_obs_grid_i(self, id):\n \"\"\"\n Generate the sub-grid observed by the agent[id].\n This method also outputs a visibility mask telling us which grid\n cells the agent can actually see.\n \"\"\"\n\n topX, topY, botX, botY = self.get_view_exts_i(id)\n\n grid = self.grid.slice(topX, topY, self.agent_view_size, self.agent_view_size)\n\n for i in range(self.agents[id].dir + 1):\n grid = grid.rotate_left()\n\n # Process occluders and visibility\n # Note that this incurs some performance cost\n if not self.see_through_walls:\n vis_mask = grid.process_vis(agent_pos=(self.agent_view_size // 2 , self.agent_view_size - 1))\n else:\n vis_mask = np.ones(shape=(grid.width, grid.height), dtype=np.bool)\n\n # Make it so the agent sees what it's carrying\n # We do this by placing the carried object at the agent's position\n # in the agent's partially observable view\n agent_pos = grid.width // 2, grid.height - 1\n if self.agents[id].carrying:\n grid.set(*agent_pos, self.agents[id].carrying)\n else:\n grid.set(*agent_pos, None)\n\n return grid, vis_mask\n \n def gen_obs(self):\n grid = [None] * self.num_agents\n vis_mask = [None] * self.num_agents\n image = [None] * self.num_agents\n for id in range(self.num_agents):\n grid[id], vis_mask[id] = self.gen_obs_grid_i(id)\n \n # Encode the partially observable view into a numpy array\n image[id] = grid[id].encode(vis_mask[id])\n assert hasattr(self, 'mission'), \"environments must define a textual mission string\"\n \n # Observations are dictionaries containing:\n # - an image (partially observable view of the environment)\n # - a textual mission string (instructions for the agent)\n obs = {\n 'image': image,\n 'mission': self.mission\n }\n return obs\n \n def get_world_coordinate_i(self, vx, vy, id):\n ax, ay = self.agents[id].pos\n dx, dy = self.dir_vec_i(id)\n rx, ry = self.right_vec_i(id)\n \n sz = self.agent_view_size\n hs = self.agent_view_size // 2\n tx = ax + (dx * (sz-1)) - (rx * hs)\n ty = ay + (dy * (sz-1)) - (ry * hs)\n \n lx = (-dy*vx - ry*vy) // (-rx*dy + ry*dx)\n ly = (dx*vx + rx*vy) // (-rx*dy + ry*dx)\n \n wx = lx + tx\n wy = ly + ty\n return wx, wy \n \n def render(self, mode = 'human', close = False, highlight = True, tile_size = TILE_PIXELS):\n if close:\n if self.window:\n self.window.close()\n return\n\n if mode == 'human' and not self.window:\n import gym_minigrid.window\n self.window = gym_minigrid.window.Window('gym_minigrid')\n self.window.show(block=False)\n\n # Mask of which cells to highlight\n highlight_mask = np.zeros(shape=(self.width, self.height), dtype=np.bool)\n \n for i in range(len(self.agents)):\n # Compute which cells are visible to the agent\n _, vis_mask = self.gen_obs_grid_i(i)\n \n # Compute the world coordinates of the bottom-left corner\n # of the agent's view area\n #f_vec = self.dir_vec\n #r_vec = self.right_vec\n #top_left = self.agent_pos + f_vec * (self.agent_view_size-1) - r_vec * (self.agent_view_size // 2)\n \n \n # For each cell in the visibility mask\n for vis_j in range(0, self.agent_view_size):\n for vis_i in range(0, self.agent_view_size):\n # If this cell is not visible, don't highlight it\n if not vis_mask[vis_i, vis_j]:\n continue\n \n # Compute the world coordinates of this cell\n abs_i, abs_j = self.get_world_coordinate_i(vis_i,vis_j, i)\n \n if abs_i < 0 or abs_i >= self.width:\n continue\n if abs_j < 0 or abs_j >= self.height:\n continue\n \n # Mark this cell to be highlighted\n highlight_mask[abs_i, abs_j] = True\n\n agents_pos = []\n agents_dir = []\n for agent in self.agents:\n agents_pos.append(agent.pos)\n agents_dir.append(agent.dir)\n \n # Render the whole grid\n img = self.grid.render_multi(\n tile_size,\n agents_pos,\n agents_dir,\n highlight_mask=highlight_mask if highlight else None\n )\n\n if mode == 'human':\n self.window.set_caption(self.mission)\n self.window.show_img(img)\n\n obs = self.gen_obs()\n if self.render_counter == 0:\n self.update_maps(obs, None)\n self.spatial_map_pub.publish(self.spatial_map.map)\n self.object_map_pub.publish(self.object_map.map)\n self.publish_ros_agent_pos()\n# self.agent_init_dir = self.agent_dir\n# self.agent_init_pos_pub.publish(self.agent_init_pos)\n self.publish_observation(obs['image'])\n #self.broadcast_tf()\n self.render_counter += 1\n return img\n '''\n def broadcast_tf(self):\n t = TransformStamped()\n t.header.stamp = rospy.Time.now()\n t.header.frame_id = \"map\"\n t.child_frame_id = \"base_link\"\n t.transform.translation.x = (self.agent_pos[0] + 0.5) * self.spatial_map.map.info.resolution\n t.transform.translation.y = (self.agent_pos[1] + 0.5) * self.spatial_map.map.info.resolution\n t.transform.translation.z = 0\n q = tf_conversions.transformations.quaternion_from_euler(0, 0, self.agent_dir*pi/2 + pi/2)\n t.transform.rotation.x = q[0]\n t.transform.rotation.y = q[1]\n t.transform.rotation.z = q[2]\n t.transform.rotation.w = q[3]\n br.sendTransform(t)\n ''' \n def publish_ros_agent_pos(self):\n ros_agent_pos = PoseArray()\n ros_agent_pos.header.frame_id = \"map\"\n ros_agent_pos.header.stamp = rospy.Time.now()\n #print(\"self.agent_pos: %d, %d\" % (self.agent_pos[0], self.agent_pos[1]) )\n for i in range(len(self.agents)):\n pose = Pose()\n pose.position.x = (self.agents[i].pos[0]+0.5) * self.spatial_map.map.info.resolution \n pose.position.y = (self.spatial_map.map.info.height - self.agents[i].pos[1] - 1 + 0.5) * self.spatial_map.map.info.resolution\n pose.position.z = 0\n orientation = self.dir_to_quaternion(i)\n pose.orientation.x = orientation[0]\n pose.orientation.y = orientation[1]\n pose.orientation.z = orientation[2]\n pose.orientation.w = orientation[3]\n \n pose_vis = PoseStamped()\n pose_vis.header.frame_id = \"map\"\n pose_vis.header.stamp = rospy.Time.now()\n pose_vis.pose.position.x = pose.position.x\n pose_vis.pose.position.y = pose.position.y\n pose_vis.pose.position.z = pose.position.z\n pose_vis.pose.orientation.x = pose.orientation.x\n pose_vis.pose.orientation.y = pose.orientation.y\n pose_vis.pose.orientation.z = pose.orientation.z\n pose_vis.pose.orientation.w = pose.orientation.w\n self.agents_pose_pub_vis[i].publish(pose_vis)\n ros_agent_pos.poses.append(pose)\n self.agent_pos_pub.publish(ros_agent_pos)\n return ros_agent_pos\n\n def publish_ros_goal_pos(self, pos):\n goal_pos = PoseStamped()\n goal_pos.header.frame_id = \"map\"\n goal_pos.header.stamp = rospy.Time.now()\n goal_pos.pose.position.x = pos[0]\n goal_pos.pose.position.y = pos[1]\n self.goal_pos_pub.publish(goal_pos)\n return goal_pos\n\n def dir_to_quaternion(self, id):\n dir = self.agents[id].dir\n ##########\n # 0: >\n # 1: V\n # 2: <\n # 3: ^\n ##########\n if dir == 0:\n yaw = 0\n elif dir == 1:\n yaw = -pi/2\n elif dir == 2:\n yaw = pi\n elif dir == 3:\n yaw = pi/2\n return transformations.quaternion_from_euler(0, 0, yaw) \n \n # now, spatial map update algorithm is done \n def update_maps(self, obs, action):\n #print(obs['image'])\n #print(self.agent_dir)\n for i in range(len(self.agents)):\n #print(\"i: {}\".format(i))\n if np.array_equal(self.agents[i].prev_pos, self.agents[i].pos) and np.array_equal(self.agents[i].prev_dir, self.agents[i].dir): # no movement\n if action is not None and (action[i] == self.Actions.open or action[i] == self.Actions.pickup or action[i] == self.Actions.drop):\n front = self.agents[i].front_pos()\n fwd_cell = self.grid.get(front[0], front[1])\n \n front[1] = self.spatial_map.map.info.height - front[1] - 1\n if fwd_cell is None: # empty cell or out of range\n if 0 <= front[0] and front[0] <= self.spatial_map.map.info.width-1 and 0 <= front[1] and front[1] <= self.spatial_map.map.info.height-1:\n self.spatial_map.update_cell(front, SpatialMap.OccGridStates.free)\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.floor)\n self.floor_map_one_hot.update_cell(front, 255)\n self.unknown_map_one_hot.update_cell(front, 0)\n self.object_map_mlp.update_cell(front, ObjectMap_MLP.ObjGridStates.floor)\n else:\n \n # update object map\n if fwd_cell.type == 'box':\n self.seen_receptacles.add(fwd_cell.objectId)\n #print(\"fwd_cell.objectId: %d\" % fwd_cell.objectId)\n if fwd_cell.isOpen == True:\n if fwd_cell.contains is not None:\n if fwd_cell.contains.type == 'ball':\n self.planning_mode = self.PlanningMode.keep\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.ball, center_only = True)\n self.ball_map_one_hot.update_cell(front, 255)\n self.unknown_map_one_hot.update_cell(front, 0)\n self.object_map_mlp.update_cell(front, ObjectMap_MLP.ObjGridStates.ball + ObjectMap_MLP.ObjGridStates.box)\n \n elif fwd_cell.contains.type == 'key':\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.key, center_only = True)\n else:\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.checked_box)\n self.checked_box_map_one_hot.update_cell(front, 255)\n self.unknown_map_one_hot.update_cell(front, 0)\n self.object_map_mlp.update_cell(front, ObjectMap_MLP.ObjGridStates.checked_box)\n \n elif fwd_cell.objectId not in self.checked_receptacles:\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.box)\n self.box_map_one_hot.update_cell(front, 255)\n self.unknown_map_one_hot.update_cell(front, 0)\n self.object_map_mlp.update_cell(front, ObjectMap_MLP.ObjGridStates.box)\n \n elif fwd_cell.type == 'key':\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.key, center_only = True)\n self.unknown_map_one_hot.update_cell(front, 0)\n \n elif fwd_cell.type == 'ball':\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.ball, center_only = True)\n self.ball_map_one_hot.update_cell(front, 255)\n self.unknown_map_one_hot.update_cell(front, 0)\n self.object_map_mlp.update_cell(front, ObjectMap_MLP.ObjGridStates.ball)\n \n elif fwd_cell.type == 'wall':\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.wall)\n self.wall_map_one_hot.update_cell(front, 255)\n self.unknown_map_one_hot.update_cell(front, 0)\n self.object_map_mlp.update_cell(front, ObjectMap_MLP.ObjGridStates.wall)\n \n elif fwd_cell.type == 'goal':\n self.object_map.update_cell(front, ObjectMap.ObjGridStates.goal)\n self.object_map_mlp.update_cell(front, ObjectMap_MLP.ObjGridStates.goal)\n self.goal_map_one_hot.update_cell(front, 255)\n self.unknown_map_one_hot.update_cell(front, 0)\n else:\n print(\"update_maps: this should not happen. new type\")\n \n # update spatial map\n if fwd_cell.can_overlap():\n self.spatial_map.update_cell(front, SpatialMap.OccGridStates.free)\n else:\n self.spatial_map.update_cell(front, SpatialMap.OccGridStates.occupied)\n \n \n else:\n continue\n else:\n # for all the cells in the agent's view, update the cells info into the map unless it is not chekced receptacles\n obs_grid, _ = Grid.decode(obs['image'][i])\n for k in range(obs_grid.width):\n for j in range(obs_grid.height):\n object = obs_grid.get(k,j)\n wx, wy = self.get_world_coordinate_i(k,j, i)\n wy = self.spatial_map.map.info.height - wy - 1\n agent_pos = np.array([self.agents[i].pos[0], self.spatial_map.map.info.height - self.agents[i].pos[1] - 1])\n #print(\"i, wx, wy: {}, {}, {}, agent_pos: {}, {}\".format(i, wx, wy, self.agents[i].pos[0], self.agents[i].pos[1]))\n if np.array_equal(agent_pos, np.array([wx,wy])):\n #print(\"i, wx, wy: {}, {}, {}\".format(i, wx, wy)) \n self.spatial_map.update_cell(np.array([wx,wy]), SpatialMap.OccGridStates.free)\n continue\n \n if object is None: # empty cell or out of range\n if 0 <= wx and wx <= self.spatial_map.map.info.width-1 and 0 <= wy and wy <= self.spatial_map.map.info.height-1:\n self.spatial_map.update_cell(np.array([wx,wy]), SpatialMap.OccGridStates.free)\n self.object_map.update_cell(np.array([wx,wy]), ObjectMap.ObjGridStates.floor)\n self.floor_map_one_hot.update_cell(np.array([wx,wy]), 255)\n self.unknown_map_one_hot.update_cell(np.array([wx,wy]), 0)\n self.object_map_mlp.update_cell(np.array([wx,wy]), ObjectMap_MLP.ObjGridStates.floor)\n else:\n # update object map\n if object.type == 'box':\n self.seen_receptacles.add(object.objectId)\n if object.objectId in self.checked_receptacles:\n pass\n \n elif object.isOpen == True:\n self.opened_receptacles.add(object.objectId)\n if object.contains is not None:\n if object.contains.type == 'ball':\n self.object_map.update_cell(np.array([wx,wy]), ObjectMap.ObjGridStates.ball, center_only = True)\n self.ball_map_one_hot.update_cell(np.array([wx,wy]), 255)\n self.unknown_map_one_hot.update_cell(np.array([wx,wy]), 0)\n self.object_map_mlp.update_cell(np.array([wx,wy]), ObjectMap_MLP.ObjGridStates.ball + ObjectMap_MLP.ObjGridStates.box)\n \n elif object.contains.type == 'key':\n self.object_map.update_cell(np.array([wx,wy]), ObjectMap.ObjGridStates.key, center_only = True)\n else:\n self.object_map.update_cell(np.array([wx,wy]), ObjectMap.ObjGridStates.checked_box)\n self.box_map_one_hot.update_cell(np.array([wx,wy]), 255)\n self.unknown_map_one_hot.update_cell(np.array([wx,wy]), 0)\n self.object_map_mlp.update_cell(np.array([wx,wy]), ObjectMap_MLP.ObjGridStates.checked_box)\n self.checked_receptacles.add(object.objectId)\n \n else:\n self.closed_receptacles.add(object.objectId)\n self.object_map.update_cell(np.array([wx, wy]), ObjectMap.ObjGridStates.box)\n self.box_map_one_hot.update_cell(np.array([wx,wy]), 255)\n self.unknown_map_one_hot.update_cell(np.array([wx,wy]), 0)\n self.object_map_mlp.update_cell(np.array([wx,wy]), ObjectMap_MLP.ObjGridStates.box)\n \n elif object.type == 'key':\n self.object_map.update_cell(np.array([wx,wy]), ObjectMap.ObjGridStates.key, center_only = True)\n \n elif object.type == 'ball':\n self.object_map.update_cell(np.array([wx,wy]), ObjectMap.ObjGridStates.ball, center_only = True)\n self.ball_map_one_hot.update_cell(np.array([wx,wy]), 255)\n self.unknown_map_one_hot.update_cell(np.array([wx,wy]), 0)\n self.object_map_mlp.update_cell(np.array([wx,wy]), ObjectMap_MLP.ObjGridStates.ball)\n \n elif object.type == 'wall':\n self.object_map.update_cell(np.array([wx, wy]), ObjectMap.ObjGridStates.wall)\n self.wall_map_one_hot.update_cell(np.array([wx,wy]), 255)\n self.unknown_map_one_hot.update_cell(np.array([wx,wy]), 0)\n self.object_map_mlp.update_cell(np.array([wx,wy]), ObjectMap_MLP.ObjGridStates.wall)\n \n elif object.type == 'goal':\n self.object_map.update_cell(np.array([wx, wy]), ObjectMap.ObjGridStates.goal)\n self.goal_map_one_hot.update_cell(np.array([wx,wy]), 255)\n self.unknown_map_one_hot.update_cell(np.array([wx,wy]), 0)\n self.object_map_mlp.update_cell(np.array([wx,wy]), ObjectMap_MLP.ObjGridStates.goal)\n \n else:\n print(\"update_maps: this should not happen. new type\")\n \n \n index = self.spatial_map.xy_to_index(wx, wy)\n if self.spatial_map.map.data[index] == SpatialMap.OccGridStates.unknown:\n self.new_coverage += 1\n \n # update spatial map\n if object.can_overlap():\n self.spatial_map.update_cell(np.array([wx,wy]), SpatialMap.OccGridStates.free)\n else:\n self.spatial_map.update_cell(np.array([wx,wy]), SpatialMap.OccGridStates.occupied)\n\n \n self.spatial_map.map.header.stamp = rospy.Time.now()\n self.object_map.map.header.stamp = rospy.Time.now() \n\n def scan(self, id_list):\n for i in id_list:\n self.agents[i].action_list = [self.Actions.left] * 4\n\n def explore(self, id_list):\n #print(\"multi_hiprlgrid: explore called\")\n rospy.wait_for_service('init_pose_list_update' + str(self.process_num))\n result = False\n try:\n init_pose_update = rospy.ServiceProxy('init_pose_list_update' + str(self.process_num), InitPosList)\n result = init_pose_update([self.agent_init_pos.poses[i].position.x for i in range(self.num_agents)],\n [self.agent_init_pos.poses[i].position.y for i in range(self.num_agents)], \n [self.agent_init_dir[i] for i in range(self.num_agents)],\n id_list)\n \n except rospy.ServiceException as e:\n print(\"Service call failed: %s\" %e)\n #print(\"init_pose_list_update: \", result)\n\n try:\n pose_update = rospy.ServiceProxy('pose_list_update' + str(self.process_num), InitPosList)\n x = [(self.agents[i].pos[0] + 0.5) * self.spatial_map.map.info.resolution for i in range(self.num_agents)]\n y = [(self.spatial_map.map.info.height - self.agents[i].pos[1] - 0.5) * self.spatial_map.map.info.resolution for i in range(self.num_agents)]\n dir = [self.agents[i].dir for i in range(self.num_agents)]\n result = pose_update(x, y, dir, id_list)\n except rospy.ServiceException as e:\n print(\"Service call failed: %s\" %e)\n \n #print(\"pose_list_update: \", result) \n \n # add agents locations as obstacle to copied map instance which is for navigation\n navigation_map = copy.deepcopy(self.spatial_map)\n for i in range(self.num_agents):\n agent_x = self.agents[i].pos[0]\n agent_y = self.spatial_map.map.info.height - self.agents[i].pos[1] - 1\n navigation_map.update_cell([agent_x, agent_y],self.spatial_map.OccGridStates.occupied)\n\n # Execute mapConvert in findFrontier, which generates plan\n self.navigation_map_pub.publish(navigation_map.map)\n \n counter = 0\n while(self.explore_action_set is False):\n #print(\"explore_action_set: \", self.explore_action_set)\n counter = counter + 1\n time.sleep(0.1)\n if counter > 10:\n return\n #block until explore plan is subscribed and updated\n \n fail_counter = 0\n for i in id_list:\n if self.agents[i].mode != self.Option_mode.explore:\n continue\n #print(\"agent {} plan: {}\".format(i, self.agents[i].action_list))\n if len(self.agents[i].action_list) == 0 or self.agents[i].action_list[0] == self.Actions.done:\n fail_counter = fail_counter + 1\n \n# if fail_counter == len(id_list):\n# for i in range(len(id_list)):\n# self.navigation_map_pub.publish(self.agents[i].map)\n self.explore_action_set = False\n \n \n \n # step using actions extracted from explore_action_list\n # temporally, set left\n #self.explore_action_list = [self.Actions.left] * 4\n return\n \n def plan(self, id_list):\n #print(\"plan in planning_mode: {}\".format(self.planning_mode))\n try:\n pose_update = rospy.ServiceProxy('pose_list_update' + str(self.process_num), InitPosList)\n x = [(self.agents[i].pos[0] + 0.5) * self.spatial_map.map.info.resolution for i in range(self.num_agents)]\n y = [(self.spatial_map.map.info.height - self.agents[i].pos[1] - 0.5) * self.spatial_map.map.info.resolution for i in range(self.num_agents)]\n dir = [self.agents[i].dir for i in range(self.num_agents)]\n result = pose_update(x, y, dir, id_list)\n except rospy.ServiceException as e:\n result = False\n print(\"Service call failed: %s\" %e)\n \n #print(\"pose_list_update: \", result) \n\n \n self.navigation_map_pub.publish(self.spatial_map.map)\n \n if self.planning_mode == self.PlanningMode.search:\n #print(\"Allocating tasks / generate plan for planning agents to search\")\n rospy.wait_for_service('/task_allocate'+ str(self.process_num))\n try:\n task_allocate = rospy.ServiceProxy('/task_allocate' + str(self.process_num), PlanningID)\n x = [(self.agents[i].pos[0] + 0.5) * self.spatial_map.map.info.resolution for i in id_list]\n y = [(self.spatial_map.map.info.height - self.agents[i].pos[1] - 0.5) * self.spatial_map.map.info.resolution for i in id_list]\n dir = [self.agents[i].dir for i in id_list]\n boxes_id = self.seen_receptacles - self.checked_receptacles\n #boxes_idx = np.nonzero(np.array(self.box_map_one_hot.map.data))\n #box_pos_x_list = []\n #box_pos_y_list = [] \n box_pos_x = []\n box_pos_y = []\n \n #box_pos_x, box_pos_y = self.box_map_one_hot.index_to_xy(boxes_idx[0])\n #print(\"boxes_id: {}\".format(boxes_id))\n #print(\"self.boxPos: {}\".format(self.boxPos))\n box_pos_list = [self.boxPos[i] for i in boxes_id]\n \n #print(\"box_pos_list: {}\".format(box_pos_list))\n for box_pos in box_pos_list:\n box_pos_x.append((box_pos[0]+0.5) * self.spatial_map.map.info.resolution)\n box_pos_y.append((self.spatial_map.map.info.height - box_pos[1] - 0.5) * self.spatial_map.map.info.resolution)\n \n \n resp = task_allocate(id_list, x, y, dir, boxes_id, box_pos_x, box_pos_y, self.planning_mode)\n except rospy.ServiceException as e:\n print(\"Planning Agent Update Service call failed: %s\" %e)\n return None\n \n elif self.planning_mode == self.PlanningMode.keep:\n #print(\"Generate plan for planning agents to keep\")\n rospy.wait_for_service('/task_allocate'+ str(self.process_num))\n try:\n task_allocate = rospy.ServiceProxy('/task_allocate' + str(self.process_num), PlanningID)\n x = [(self.agents[i].pos[0] + 0.5) * self.spatial_map.map.info.resolution for i in id_list]\n y = [(self.spatial_map.map.info.height - self.agents[i].pos[1] - 0.5) * self.spatial_map.map.info.resolution for i in id_list]\n dir = [self.agents[i].dir for i in id_list]\n boxes_id = [0]\n \n box_pos_x = []\n box_pos_y = []\n \n #box_pos_x, box_pos_y = self.box_map_one_hot.index_to_xy(boxes_idx[0])\n #print(\"boxes_id: {}\".format(boxes_id))\n #print(\"self.boxPos: {}\".format(self.boxPos))\n box_pos_list = [self.boxPos[i] for i in boxes_id]\n #print(\"box_pos_list: {}\".format(box_pos_list))\n for box_pos in box_pos_list:\n box_pos_x.append((box_pos[0]+0.5) * self.spatial_map.map.info.resolution)\n box_pos_y.append((self.spatial_map.map.info.height - box_pos[1] - 0.5) * self.spatial_map.map.info.resolution)\n \n \n resp = task_allocate(id_list, x, y, dir, boxes_id, box_pos_x, box_pos_y, self.planning_mode)\n except rospy.ServiceException as e:\n print(\"Planning Agent Update Service call failed: %s\" %e)\n return None\n \n elif self.planning_mode == self.PlanningMode.bring:\n #print(\"Generate plan for planning agents to bring\")\n rospy.wait_for_service('/task_allocate'+ str(self.process_num))\n try:\n task_allocate = rospy.ServiceProxy('/task_allocate' + str(self.process_num), PlanningID)\n x = [(self.agents[i].pos[0] + 0.5) * self.spatial_map.map.info.resolution for i in id_list]\n y = [(self.spatial_map.map.info.height - self.agents[i].pos[1] - 0.5) * self.spatial_map.map.info.resolution for i in id_list]\n dir = [self.agents[i].dir for i in id_list]\n boxes_id = [0]\n \n box_pos_x = []\n box_pos_y = []\n \n #box_pos_x, box_pos_y = self.box_map_one_hot.index_to_xy(boxes_idx[0])\n #print(\"boxes_id: {}\".format(boxes_id))\n #print(\"self.boxPos: {}\".format(self.boxPos))\n box_pos_x.append((self.goal_pos[0]+0.5) * self.spatial_map.map.info.resolution)\n box_pos_y.append((self.spatial_map.map.info.height - self.goal_pos[1] - 0.5) * self.spatial_map.map.info.resolution)\n \n \n resp = task_allocate(id_list, x, y, dir, boxes_id, box_pos_x, box_pos_y, self.planning_mode)\n except rospy.ServiceException as e:\n print(\"Planning Agent Update Service call failed: %s\" %e)\n return None\n \n \n j = 0\n min_len = 1000\n for i in range(self.num_agents):\n if self.agents[i].mode != self.Option_mode.plan:\n continue\n\n if j >= len(resp.action_array.list):\n break\n\n if len(resp.action_array.list) > 0 and len(resp.action_array.list[j].data) < min_len and len(resp.action_array.list[j].data) > 0 and resp.action_array.list[j].data[0] >= 0:\n min_len = len(resp.action_array.list[j].data) \n #print(\"agent {}'s plan action length: {}\".format(i, len(resp.action_array.list[j].data)))\n self.agents[i].action_list = [0] * len(resp.action_array.list[j].data)\n for k in range(len(resp.action_array.list[j].data)):\n self.agents[i].action_list[k] = resp.action_array.list[j].data[k]\n \n \n j = j + 1\n \n j = 0\n for i in range(self.num_agents):\n if self.agents[i].mode != self.Option_mode.plan:\n continue\n \n if j >= len(resp.action_array.list):\n break\n \n if len(resp.action_array.list) > 0 and len(resp.action_array.list[j].data) == 1 and resp.action_array.list[j].data[0] < 0:\n #self.agents[i].action_list = [self.Actions.done] * min_len\n self.meaningless = True\n j = j + 1\n \n # in case all failed to plan\n if min_len == 1000:\n for i in range(self.num_agents):\n if self.agents[i].mode != self.Option_mode.plan:\n continue\n #self.agents[i].action_list = [self.Actions.done]\n self.meaningless = True\n \n \n #self.generate_actions_from_complete_plan(id_list)\n #self.dispatch_plan_action_id = 0\n self.prev_dispatch_plan_action_id = -1\n self.complete_plan_flag = False\n return \n \n\n \n def check_precondition(self, item):\n rospy.wait_for_service('/check_precondition' + str(self.process_num))\n try:\n check_precondition = rospy.ServiceProxy('/check_precondition' + str(self.process_num), ActionExecution)\n req = ActionExecutionRequest()\n req.name = item.name\n req.action_id = item.action_id\n req.parameters = copy.deepcopy(item.parameters)\n resp = check_precondition(req)\n return resp.success\n except rospy.ServiceException as e:\n print(\"Check Precondition Service call failed: %s\" %e)\n return False\n \n def process_action_effect(self, item):\n rospy.wait_for_service('/process_action_effect' + str(self.process_num))\n try:\n check_precondition = rospy.ServiceProxy('/process_action_effect' + str(self.process_num), ActionExecution)\n req = ActionExecutionRequest()\n req.name = item.name\n req.action_id = item.action_id\n req.parameters = copy.deepcopy(item.parameters)\n resp = check_precondition(req)\n return resp.success\n except rospy.ServiceException as e:\n print(\"process_action_effect service call failed: %s\" %e)\n return False \nregister(\n id='MiniGrid-MultiHiPRLGridShortPose-v0',\n entry_point='gym_minigrid.envs:MultiHiPRLGridShortPoseV0'\n)\n\n\"\"\"\nprint(self.observation_space)\n data_path = '/home/morin/catkin_ws/src/hiprl_replicate/pddl/'\n domain_path = data_path + 'hiprl_mini.pddl'\n problem0_path = data_path + 'hiprl_problem0.pddl'\n problem_path = data_path + 'problem.pddl'\n planner_command = '/home/morin/catkin_ws/src/rosplan/rosplan_planning_system/common/bin/popf2 DOMAIN PROBLEM /home/morin/catkin_ws/src/hiprl_replicate/pddl/plan0.pddl'\n \n # objmap_to_image converter launch\n file0_package = 'find_frontier'\n file0_executable = 'objmap_to_image_converter'\n node0 = roslaunch.core.Node(file0_package, file0_executable, name = 'objmap_to_image_converter' + str(process_num), args = str(process_num), output='screen')\n self.launch = roslaunch.scriptapi.ROSLaunch()\n self.launch.start()\n self.process0 = self.launch.launch(node0)\n \n # hiprl_explore launch\n file1_package = 'find_frontier'\n file1_executable = 'find_frontier_node'\n node1 = roslaunch.core.Node(file1_package, file1_executable, name = 'hiprl_explore' + str(process_num), args = str(process_num), output='screen')\n f = open('/home/morin/catkin_ws/src/find_frontier/param/global_costmap' + str(process_num) + '.yaml', 'r')\n yaml_file = load(f)\n f.close()\n upload_params('/hiprl_explore' + str(process_num) + '/', yaml_file)\n self.process1 = self.launch.launch(node1)\n rospy.set_param('use_sim_time', False)\n \n # knowledge manager launch\n file2_package = 'rosplan_knowledge_base'\n file2_executable = 'knowledgeBase'\n node2 = roslaunch.core.Node(file2_package, file2_executable, name = 'rosplan_knowledge_base' + str(process_num), args = str(process_num), output='screen')\n rospy.set_param('rosplan_knowledge_base' + str(process_num) + '/domain_path', domain_path)\n rospy.set_param('rosplan_knowledge_base' + str(process_num) + '/problem_path', problem0_path)\n rospy.set_param('rosplan_knowledge_base' + str(process_num) + '/use_unknowns', False)\n self.process2 = self.launch.launch(node2)\n \n file3_package = 'rosplan_planning_system'\n file3_executable = 'problemInterface'\n node3 = roslaunch.core.Node(file3_package, file3_executable, name = 'rosplan_problem_interface' + str(process_num), args = str(process_num), output='screen')\n rospy.set_param('rosplan_problem_interface' + str(process_num) + '/knowledge_base', 'rosplan_knowledge_base' + str(process_num))\n rospy.set_param('rosplan_problem_interface' + str(process_num) + '/domain_path', domain_path)\n rospy.set_param('rosplan_problem_interface' + str(process_num) + '/problem_path', problem_path)\n rospy.set_param('rosplan_problem_interface' + str(process_num) + '/problem_topic', 'problem_instance')\n self.process3 = self.launch.launch(node3)\n \n file4_package = 'hiprl_replicate'\n file4_executable = 'knowledge_update_node'\n node4 = roslaunch.core.Node(file4_package, file4_executable, name = 'rosplan_knowledge_update_node' + str(process_num), args = str(process_num), output='screen')\n rospy.set_param('rosplan_knowledge_update_node' + str(process_num) + '/knowledge_base', 'rosplan_knowledge_base' + str(process_num))\n self.process4 = self.launch.launch(node4)\n \n # planner launch\n file5_package = 'rosplan_planning_system'\n file5_executable = 'popf_planner_interface'\n node5 = roslaunch.core.Node(file5_package, file5_executable, name = 'rosplan_planner_interface' + str(process_num), args = str(process_num), output='screen')\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/use_problem_topic', True)\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/problem_topic', 'rosplan_problem_interface' + str(process_num) + '/problem_instance')\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/planner_topic', 'planner_output')\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/domain_path', domain_path)\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/problem_path', problem_path)\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/data_path', data_path)\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/planner_interface', 'popf_planner_interface')\n rospy.set_param('rosplan_planner_interface' + str(process_num) + '/planner_command', planner_command)\n self.process5 = self.launch.launch(node5)\n \n file6_package = 'rosplan_planning_system'\n file6_executable = 'pddl_simple_plan_parser'\n node6 = roslaunch.core.Node(file6_package, file6_executable, name = 'rosplan_parsing_interface' + str(process_num), args = str(process_num), output='screen')\n rospy.set_param('rosplan_parsing_interface' + str(process_num) + '/knowledge_base', 'rosplan_knowledge_base' + str(process_num))\n rospy.set_param('rosplan_parsing_interface' + str(process_num) + '/planner_topic', 'rosplan_planner_interface' + str(process_num) + '/planner_output')\n rospy.set_param('rosplan_parsing_interface' + str(process_num) + '/plan_topic', 'complete_plan')\n self.process6 = self.launch.launch(node6)\n\"\"\"\n\n\"\"\" For advanced sim\n # Place random objects in the world\n types1 = ['cup', 'apple', 'egg']\n types2 = ['cabinet', 'table', 'refrigerator', 'microwave', 'sink']\n objColor = self._rand_elem(COLOR_NAMES)\n tableObj = Table(objColor)\n self.place_obj(tableObj)\n \n objColor = self._rand_elem(COLOR_NAMES)\n refrigeratorObj = Refrigerator(objColor)\n self.place_obj(refrigeratorObj)\n \n objColor = self._rand_elem(COLOR_NAMES)\n microwaveObj = Microwave(objColor)\n self.place_obj(microwaveObj)\n \n objColor = self._rand_elem(COLOR_NAMES)\n sinkObj = Sink(objColor)\n self.place_obj(sinkObj)\n \n objColor = self._rand_elem(COLOR_NAMES)\n cabinetObj = Cabinet(objColor)\n self.place_obj(cabinetObj)\n \n for i in range(0, 5):\n objType = self._rand_elem(types1)\n objColor = self._rand_elem(COLOR_NAMES)\n if objType == 'cup':\n obj = Cup(i, objColor)\n elif objType == 'apple':\n obj = Apple(i, objColor)\n elif objType == 'egg':\n obj = Egg(i, objColor) \n self.place_obj(obj)\n\n # No explicit mission in this environment --> to be modified\n self.mission = '' \"\"\"\n \n\"\"\"\n def dispatch_plan(self, actions, render = False):\n print(\"dispatch plan called\")\n reward_sum = 0\n obs, reward, done, info = None, None, None, {'fwd_cell': None}\n if self.dispatch_plan_action_id - self.prev_dispatch_plan_action_id > 0 and len(actions) > 0:\n precondition_check = self.check_precondition(actions[self.dispatch_plan_action_id][0])\n if precondition_check == False:\n print(\"dispatch_plan: {} precondition not achieved\".format(actions[self.dispatch_plan_action_id][0].name))\n self.dispatch_plan_action_id = 0\n self.prev_dispatch_plan_action_id = -1\n return None, None, None, None\n # dispatch plan until potential goal update\n # 'actions[self.dispatch_plan_action_id][2] == False' means it is not potential goal update related semantic action\n print(\"actions length: {}, dispatch_plan_id: {}\".format(len(actions), self.dispatch_plan_action_id))\n print(\"actions self.dispatch_plan_action_id length: {}\".format(len(actions[self.dispatch_plan_action_id])))\n\n while actions[self.dispatch_plan_action_id][2] == False:\n print(\"actions length: {}, dispatch_plan_id: {}\".format(len(actions), self.dispatch_plan_action_id))\n print(\"actions self.dispatch_plan_action_id length: {}\".format(len(actions[self.dispatch_plan_action_id])))\n\n while len(actions[self.dispatch_plan_action_id][1]) > 0: \n action = actions[self.dispatch_plan_action_id][1].pop(0)\n obs, reward, done, info = self.step(action)\n if render:\n self.render()\n reward_sum += reward\n self.prev_dispatch_plan_action_id = self.dispatch_plan_action_id \n \n # if actions for semantic action is done (= actions[dispatch_plan_action_id][1] is empty)\n if not actions[self.dispatch_plan_action_id][1]:\n self.process_action_effect(actions[self.dispatch_plan_action_id][0])\n if len(actions)-1 > self.dispatch_plan_action_id:\n self.dispatch_plan_action_id += 1\n else:\n break\n \n if self.dispatch_plan_action_id + 1 <= len(actions):\n while len(actions[self.dispatch_plan_action_id][1]) > 0: \n action = actions[self.dispatch_plan_action_id][1].pop(0)\n obs, reward, done, info = self.step(action)\n if render:\n self.render()\n reward_sum += reward\n self.prev_dispatch_plan_action_id = self.dispatch_plan_action_id \n \n # if actions for semantic action is done (= actions[dispatch_plan_action_id][1] is empty)\n if not actions[self.dispatch_plan_action_id][1]:\n self.process_action_effect(actions[self.dispatch_plan_action_id][0])\n if len(actions)-1 > self.dispatch_plan_action_id:\n self.dispatch_plan_action_id += 1\n \n return obs, reward_sum, done, info\n\"\"\"\n\"\"\"\n def dispatch_plan(self, actions, render = False):\n print(\"dispatch plan called\")\n reward_sum = 0\n obs, reward, done, info = None, None, None, {'fwd_cell': None}\n if self.dispatch_plan_action_id - self.prev_dispatch_plan_action_id > 0 and len(actions) > 0:\n precondition_check = self.check_precondition(actions[self.dispatch_plan_action_id][0])\n if precondition_check == False:\n print(\"dispatch_plan: {} precondition not achieved\".format(actions[self.dispatch_plan_action_id][0].name))\n self.dispatch_plan_action_id = 0\n self.prev_dispatch_plan_action_id = -1\n return None, None, None, None\n # dispatch plan until potential goal update\n # 'actions[self.dispatch_plan_action_id][2] == False' means it is not potential goal update related semantic action\n #print(\"actions length: {}, dispatch_plan_id: {}\".format(len(actions), self.dispatch_plan_action_id))\n #print(\"actions self.dispatch_plan_action_id length: {}\".format(len(actions[self.dispatch_plan_action_id])))\n\n if len(actions[self.dispatch_plan_action_id][1]) > 0: \n action = actions[self.dispatch_plan_action_id][1].pop(0)\n obs, reward, done, info = self.step(action)\n if render:\n self.render()\n reward_sum += reward\n self.prev_dispatch_plan_action_id = self.dispatch_plan_action_id \n\n # if actions for semantic action is done (= actions[dispatch_plan_action_id][1] is empty)\n if not actions[self.dispatch_plan_action_id][1]:\n self.process_action_effect(actions[self.dispatch_plan_action_id][0])\n if len(actions)-1 > self.dispatch_plan_action_id:\n self.dispatch_plan_action_id += 1\n \n \n return obs, reward_sum, done, info\n \n \n # plan 2021 12 08 \n def plan(self, id_list):\n print(\"Updating knowledge for planning-only agents\")\n rospy.wait_for_service('/planning_agent_update'+ str(self.process_num))\n try:\n planning_agent_update = rospy.ServiceProxy('/planning_agent_update' + str(self.process_num), PlanningID) \n resp = planning_agent_update(id_list)\n except rospy.ServiceException as e:\n print(\"Planning Agent Update Service call failed: %s\" %e)\n return None\n \n print(\"Allocating tasks for planning-only agents\")\n rospy.wait_for_service('/task_allocate'+ str(self.process_num))\n try:\n task_allocate = rospy.ServiceProxy('/task_allocate' + str(self.process_num), PlanningID)\n resp = task_allocate(id_list)\n except rospy.ServiceException as e:\n print(\"Planning Agent Update Service call failed: %s\" %e)\n return None\n \n self.complete_plan_id_list = set([])\n for i in id_list:\n print(\"Generating a Problem for each agent\")\n rospy.wait_for_service('/rosplan_problem_interface'+ str(self.process_num) + '_' + str(i) + '/problem_generation_server')\n try:\n problem_generation = rospy.ServiceProxy('/rosplan_problem_interface' + str(self.process_num) + '_' + str(i) + '/problem_generation_server', Empty)\n resp = problem_generation()\n except rospy.ServiceException as e:\n print(\"Problem Generation Service call failed: %s\" %e)\n return None\n\n print(\"Planning for each agent\") \n rospy.wait_for_service('/rosplan_planner_interface' + str(self.process_num) + '_' + str(i) +'/planning_server')\n try:\n run_planner = rospy.ServiceProxy('/rosplan_planner_interface' + str(self.process_num) + '_' + str(i) + '/planning_server', Empty)\n resp = run_planner()\n\n except rospy.ServiceException as e:\n print(\"Planning Service call failed: %s\" %e)\n return None\n\n print(\"Executing the Plan\") \n rospy.wait_for_service('/rosplan_parsing_interface' + str(self.process_num) + '_' + str(i) + '/parse_plan')\n try:\n parse_plan = rospy.ServiceProxy('/rosplan_parsing_interface' + str(self.process_num) + '_' + str(i) + '/parse_plan', Empty)\n resp = parse_plan()\n except rospy.ServiceException as e:\n print(\"Plan Parsing Service call failed: %s\" %e)\n return None\n #rospy.wait_for_service('/rosplan_parsing_interface/alert_plan_action_num')\n #try:\n # alert_plan_action_num = rospy.ServiceProxy('/rosplan_parsing_interface/alert_plan_action_num', AlertPlanActionNum)\n # resp = alert_plan_action_num()\n # self.planner_action_num = resp.num_actions\n #except rospy.ServiceException as e:\n # print(\"Plan Parsing Service call failed: %s\" %e)\n counter = 0\n while(len(self.complete_plan_id_list & set(id_list)) != len(id_list)):\n time.sleep(0.1)\n counter = counter + 1\n print(\"complete_plan_flag: \", self.action_execution_flag)\n if counter > 10:\n self.dispatch_plan_action_id = 0\n self.prev_dispatch_plan_action_id = -1\n return None\n print(\"complete_plan_flag is set to True\")\n \n self.generate_actions_from_complete_plan(id_list)\n self.dispatch_plan_action_id = 0\n self.prev_dispatch_plan_action_id = -1\n self.complete_plan_flag = False\n return \n \"\"\""
] |
[
[
"numpy.array_equal",
"numpy.reshape",
"numpy.ones",
"numpy.append",
"numpy.array",
"numpy.zeros"
]
] |
aleccrowell/covid
|
[
"1ee264d64ac81cf1f8a2bbcf24832541e1b7574d"
] |
[
"covid/covidtracking.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport itertools\nimport cachetools.func\n\nimport requests\nimport io\n\[email protected]_cache(ttl=3600)\ndef load_us():\n s=requests.get('https://covidtracking.com/api/states/daily.csv',verify=False).content\n df = pd.read_csv(io.StringIO(s.decode('utf-8')))\n df.date = pd.to_datetime(df.date, format='%Y%m%d')\n df = df.set_index('date')\n df = df.drop(columns=['dateChecked'])\n df['confirmed'] = df['positive'] # useful alias to match other data\n df['deaths'] = df['death']\n df = df.pivot(columns='state')\n df.columns = df.columns.swaplevel()\n df.sort_index(axis=1, inplace=True)\n return df\n\n\[email protected]_cache(ttl=3600)\ndef load_us_flat(start='2020-03-04'):\n \n s=requests.get('https://covidtracking.com/api/states/daily.csv',verify=False).content\n df = pd.read_csv(io.StringIO(s.decode('utf-8')))\n df.date = pd.to_datetime(df.date, format='%Y%m%d')\n \n df = df.set_index(['state', 'date'])\n df.sort_index(axis=0, inplace=True)\n \n states = df.index.unique(level=0)\n days = df.index.unique(level=1)\n full_index = itertools.product(states, days)\n df = df.reindex(full_index)\n df.sort_index(axis=0, inplace=True)\n\n end = None\n df = df.loc[(slice(None),slice(start, end)),:]\n\n return df\n"
] |
[
[
"pandas.to_datetime"
]
] |
lcreyes/PULearningSelfTutorial
|
[
"a9a34da83033ca5205871a9c4e2fda4db650d4ef"
] |
[
"kNNClassification.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import neighbors\nfrom matplotlib.colors import ListedColormap\n\n#define constants\n\nn_l = 500 #number of labeled positive points\nn_p = 500 #number of positive points\nn_n = 1000 # number of negative points\n\n#define Gaussians mean and covariance matrices\n\nmean1 = [0,0]\nmean2 = [4,3]\n\ncov1 = [[1, 0.5], [0.5, 1]]\ncov2 = [[1, -0.5], [-0.5, 1]]\n\n\n#random generated data\npositive = np.transpose(np.random.multivariate_normal(mean1,cov1,n_p).T)\nnegative = np.transpose(np.random.multivariate_normal(mean2,cov2,n_n).T)\n\ndata = np.vstack((positive,negative))\nlabel = [1]*n_l + [-1]*(n_p+n_n-n_l)\n\n\n# run classification\nclf = neighbors.KNeighborsClassifier(15, 'uniform')\nclf.fit(data, label)\n\n#xy grid of points to be evaluated with classifier\nxx, yy = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200))\n\n#calculate \"distances\" to hyperplane\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\n\n\n#plot \nplt.figure()\ncmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])\nplt.pcolormesh(xx, yy, Z, cmap=cmap_light)\n\nplt.scatter(data[:, 0], data[:, 1], s=30, c=label, cmap=plt.cm.Paired)\nplt.xticks(())\nplt.yticks(())\nplt.axis([-10, 10, -10, 10])\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.scatter",
"numpy.linspace",
"numpy.random.multivariate_normal",
"sklearn.neighbors.KNeighborsClassifier",
"matplotlib.colors.ListedColormap",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.pcolormesh",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"numpy.vstack",
"matplotlib.pyplot.figure"
]
] |
dipesg/Face-Mask-Detector
|
[
"81ef0f52752f8f1034a35c932289fe62a6787a93"
] |
[
"src/detect_and_predict_mask.py"
] |
[
"from tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nimport numpy as np\nimport cv2\nfrom src import logger\n\nclass Mask:\n def __init__(self):\n self.log_writer = logger.App_Logger()\n self.file_object = open(\"../logs/Detect_and_predict_mask.log\", 'a+')\n def detect_and_predict_mask(self,frame, faceNet, maskNet):\n self.log_writer.log(self.file_object,\"Running detect_and_predict_mask\")\n # grab the dimensions of the frame and then construct a blob\n # from it\n (h, w) = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),\n (104.0, 177.0, 123.0))\n\n # pass the blob through the network and obtain the face detections\n faceNet.setInput(blob)\n detections = faceNet.forward()\n print(detections.shape)\n\n # initialize our list of faces, their corresponding locations,\n # and the list of predictions from our face mask network\n faces = []\n locs = []\n preds = []\n\n # loop over the detections\n for i in range(0, detections.shape[2]):\n # extract the confidence (i.e., probability) associated with\n # the detection\n confidence = detections[0, 0, i, 2]\n\n # filter out weak detections by ensuring the confidence is\n # greater than the minimum confidence\n if confidence > 0.5:\n # compute the (x, y)-coordinates of the bounding box for\n # the object\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # ensure the bounding boxes fall within the dimensions of\n # the frame\n (startX, startY) = (max(0, startX), max(0, startY))\n (endX, endY) = (min(w - 1, endX), min(h - 1, endY))\n\n # extract the face ROI, convert it from BGR to RGB channel\n # ordering, resize it to 224x224, and preprocess it\n face = frame[startY:endY, startX:endX]\n face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n face = cv2.resize(face, (224, 224))\n face = img_to_array(face)\n face = preprocess_input(face)\n\n # add the face and bounding boxes to their respective\n # lists\n faces.append(face)\n locs.append((startX, startY, endX, endY))\n\n # only make a predictions if at least one face was detected\n if len(faces) > 0:\n # for faster inference we'll make batch predictions on *all*\n # faces at the same time rather than one-by-one predictions\n # in the above `for` loop\n faces = np.array(faces, dtype=\"float32\")\n\n \n preds = maskNet.predict(faces, batch_size=32)\n \n\n # return a 2-tuple of the face locations and their corresponding\n # locations\n return (locs, preds)\n "
] |
[
[
"tensorflow.keras.applications.mobilenet_v2.preprocess_input",
"numpy.array",
"tensorflow.keras.preprocessing.image.img_to_array"
]
] |
viktorvesely/Agent01
|
[
"b5a16e68dd97e8a75db7699af336650f5a863138"
] |
[
"src/DQN.py"
] |
[
"import model as md\nimport numpy as np\nimport tensorflow as tf\n\nclass DQN:\n def __init__(self,\n num_states,\n num_actions,\n hidden_units,\n gamma,\n max_experiences,\n min_experiences,\n batch_size\n ):\n self.num_actions = num_actions\n self.batch_size = batch_size\n self.optimizer = tf.keras.optimizers.RMSprop(0.001)\n self.gamma = gamma\n self.model = md.Model(num_actions, num_states, hidden_units)\n self.experience = {'s': [], 'a': [], 'r': [], 's2': [], 'done': []}\n self.max_experiences = max_experiences\n self.min_experiences = min_experiences\n\n self.model.compile(\n self.optimizer,\n loss = tf.keras.losses.MeanSquaredError()\n )\n \n def predict(self, inputs):\n reworked_inputs = np.atleast_2d(inputs.astype('float32'))\n return self.model(reworked_inputs)\n\n def train(self, TargetNet):\n if len(self.experience['s']) < self.min_experiences:\n return 0\n ids = np.random.randint(low=0, high=len(self.experience['s']), size=self.batch_size)\n states = np.asarray([self.experience['s'][i] for i in ids])\n actions = np.asarray([self.experience['a'][i] for i in ids])\n rewards = np.asarray([self.experience['r'][i] for i in ids])\n states_next = np.asarray([self.experience['s2'][i] for i in ids])\n dones = np.asarray([self.experience['done'][i] for i in ids])\n value_next = np.max(TargetNet.predict(states_next), axis=1)\n actual_values = np.where(dones, rewards, rewards+self.gamma*value_next)\n\n selected_action_values = tf.math.reduce_sum(\n self.predict(states) * tf.one_hot(actions, self.num_actions), axis=1\n )\n\n with tf.GradientTape() as tape:\n selected_action_values = tf.math.reduce_sum(\n self.predict(states) * tf.one_hot(actions, self.num_actions), axis=1\n )\n loss = tf.math.reduce_sum(tf.square(actual_values - selected_action_values))\n variables = self.model.trainable_variables\n gradients = tape.gradient(loss, variables)\n self.optimizer.apply_gradients(zip(gradients, variables))\n\n def get_action(self, states, epsilon):\n if np.random.random() < epsilon:\n return np.random.choice(self.num_actions)\n else:\n return np.argmax(self.predict(np.atleast_2d(states))[0])\n \n def add_experience(self, exp):\n if len(self.experience['s']) >= self.max_experiences:\n for key in self.experience.keys():\n self.experience[key].pop(0)\n for key, value in exp.items():\n self.experience[key].append(value)\n\n def copy_weights(self, TrainNet):\n variables1 = self.model.trainable_variables\n variables2 = TrainNet.model.trainable_variables\n for v1, v2 in zip(variables1, variables2):\n v1.assign(v2.numpy())\n"
] |
[
[
"numpy.random.random",
"numpy.random.choice",
"numpy.asarray",
"tensorflow.keras.losses.MeanSquaredError",
"tensorflow.keras.optimizers.RMSprop",
"numpy.atleast_2d",
"tensorflow.one_hot",
"tensorflow.square",
"numpy.where",
"tensorflow.GradientTape"
]
] |
chenw23/open_lth
|
[
"2ce732fe48abd5a80c10a153c45d397b048e980c"
] |
[
"training/test/test_train.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\n\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport numpy as np\n\nimport datasets.registry\nfrom foundations.step import Step\nimport models.registry\nfrom training import train\nfrom testing import test_case\n\n\nclass TestTrain(test_case.TestCase):\n def setUp(self):\n super(TestTrain, self).setUp()\n self.hparams = models.registry.get_default_hparams('mnist_lenet_10_10')\n self.hparams.dataset_hparams.subsample_fraction = 0.01\n self.hparams.dataset_hparams.batch_size = 50 # Leads to 12 iterations per epoch.\n self.hparams.dataset_hparams.do_not_augment = True\n self.hparams.training_hparams.data_order_seed = 0\n self.train_loader = datasets.registry.get(self.hparams.dataset_hparams)\n\n self.hparams.training_hparams.training_steps = '3ep'\n self.hparams.training_hparams.warmup_steps = '10it'\n self.hparams.training_hparams.gamma = 0.1\n self.hparams.training_hparams.milestone_steps = '2ep'\n\n self.model = models.registry.get(self.hparams.model_hparams)\n\n self.step_counter = 0\n self.ep = 0\n self.it = 0\n self.lr = 0.0\n\n def callback(output_location, step, model, optimizer, logger):\n self.step_counter += 1\n self.ep, self.it = step.ep, step.it\n self.lr = np.round(optimizer.param_groups[0]['lr'], 10)\n\n self.callback = callback\n\n def test_train_zero_steps(self):\n before = TestTrain.get_state(self.model)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n end_step=Step.from_iteration(0, len(self.train_loader)))\n\n after = TestTrain.get_state(self.model)\n for k in before:\n self.assertTrue(np.array_equal(before[k], after[k]))\n self.assertEqual(self.step_counter, 0)\n self.assertEqual(self.ep, 0)\n self.assertEqual(self.it, 0)\n\n def test_train_two_steps(self):\n before = TestTrain.get_state(self.model)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n end_step=Step.from_iteration(2, len(self.train_loader)))\n\n after = TestTrain.get_state(self.model)\n for k in before:\n with self.subTest(k=k):\n self.assertFalse(np.array_equal(before[k], after[k]), k)\n\n self.assertEqual(self.step_counter, 3)\n self.assertEqual(self.ep, 0)\n self.assertEqual(self.it, 2)\n self.assertEqual(self.lr, 0.02)\n\n def test_train_one_epoch(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n end_step=Step.from_epoch(1, 0, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 13) # Same as len(self.train_loader) + 1\n self.assertEqual(self.ep, 1)\n self.assertEqual(self.it, 0)\n self.assertEqual(self.lr, 0.1)\n\n def test_train_more_than_two_epochs(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n end_step=Step.from_epoch(2, 1, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 26)\n self.assertEqual(self.ep, 2)\n self.assertEqual(self.it, 1)\n self.assertEqual(self.lr, 0.01)\n\n def test_train_in_full(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback])\n\n self.assertEqual(self.step_counter, 37)\n self.assertEqual(self.ep, 3)\n self.assertEqual(self.it, 0)\n self.assertEqual(self.lr, 0.01)\n\n def test_train_zero_steps_late_start(self):\n before = TestTrain.get_state(self.model)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(0, 5, len(self.train_loader)),\n end_step=Step.from_epoch(0, 5, len(self.train_loader)))\n\n after = TestTrain.get_state(self.model)\n for k in before:\n self.assertTrue(np.array_equal(before[k], after[k]))\n self.assertEqual(self.step_counter, 0)\n self.assertEqual(self.ep, 0)\n self.assertEqual(self.it, 0)\n\n def test_train_one_step_late_start(self):\n before = TestTrain.get_state(self.model)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(0, 5, len(self.train_loader)),\n end_step=Step.from_epoch(0, 6, len(self.train_loader)))\n\n after = TestTrain.get_state(self.model)\n for k in before:\n self.assertFalse(np.array_equal(before[k], after[k]))\n self.assertEqual(self.step_counter, 2)\n self.assertEqual(self.ep, 0)\n self.assertEqual(self.it, 6)\n self.assertEqual(self.lr, 0.06)\n\n def test_train_one_epoch_late_start(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(0, 5, len(self.train_loader)),\n end_step=Step.from_epoch(1, 5, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 13)\n self.assertEqual(self.ep, 1)\n self.assertEqual(self.it, 5)\n self.assertEqual(self.lr, 0.1)\n\n def test_train_two_epoch_late_start(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(0, 5, len(self.train_loader)),\n end_step=Step.from_epoch(2, 5, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 25)\n self.assertEqual(self.ep, 2)\n self.assertEqual(self.it, 5)\n self.assertEqual(self.lr, 0.01)\n\n def test_train_in_full_late_start(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(0, 5, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 32)\n self.assertEqual(self.ep, 3)\n self.assertEqual(self.it, 0)\n self.assertEqual(self.lr, 0.01)\n\n def test_train_in_full_later_start(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 5, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 20)\n self.assertEqual(self.ep, 3)\n self.assertEqual(self.it, 0)\n self.assertEqual(self.lr, 0.01)\n\n def test_train_in_parts(self):\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n end_step=Step.from_epoch(0, 7, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 8)\n self.assertEqual(self.ep, 0)\n self.assertEqual(self.it, 7)\n self.assertEqual(self.lr, 0.07)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(0, 7, len(self.train_loader)),\n end_step=Step.from_epoch(0, 8, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 10)\n self.assertEqual(self.ep, 0)\n self.assertEqual(self.it, 8)\n self.assertEqual(self.lr, 0.08)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(0, 8, len(self.train_loader)),\n end_step=Step.from_epoch(1, 2, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 17)\n self.assertEqual(self.ep, 1)\n self.assertEqual(self.it, 2)\n self.assertEqual(self.lr, 0.1)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 2, len(self.train_loader)),\n end_step=Step.from_epoch(2, 1, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 29)\n self.assertEqual(self.ep, 2)\n self.assertEqual(self.it, 1)\n self.assertEqual(self.lr, 0.01)\n\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(2, 1, len(self.train_loader)),\n end_step=Step.from_epoch(3, 0, len(self.train_loader)))\n\n self.assertEqual(self.step_counter, 41)\n self.assertEqual(self.ep, 3)\n self.assertEqual(self.it, 0)\n self.assertEqual(self.lr, 0.01)\n\n def test_repeatable_data_order_with_seed(self):\n init = {k: v.clone().detach() for k, v in self.model.state_dict().items()}\n\n # Train the model once and get the state.\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 0, len(self.train_loader)),\n end_step=Step.from_epoch(1, 1, len(self.train_loader)))\n state1 = TestTrain.get_state(self.model)\n\n # Train the model again and get the state.\n self.model.load_state_dict(init)\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 0, len(self.train_loader)),\n end_step=Step.from_epoch(1, 1, len(self.train_loader)))\n state2 = TestTrain.get_state(self.model)\n\n # Ensure that the model states are the same.\n for k in state1:\n self.assertTrue(np.array_equal(state1[k], state2[k]))\n\n def test_nonrepeatable_data_order_without_seed(self):\n del self.hparams.training_hparams.data_order_seed\n\n init = {k: v.clone().detach() for k, v in self.model.state_dict().items()}\n\n # Train the model once and get the state.\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 0, len(self.train_loader)),\n end_step=Step.from_epoch(1, 1, len(self.train_loader)))\n state1 = TestTrain.get_state(self.model)\n\n # Train the model again and get the state.\n self.model.load_state_dict(init)\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 0, len(self.train_loader)),\n end_step=Step.from_epoch(1, 1, len(self.train_loader)))\n state2 = TestTrain.get_state(self.model)\n\n # Ensure that the model states are NOT the same.\n for k in state1:\n self.assertFalse(np.array_equal(state1[k], state2[k]))\n\n def test_different_data_on_different_steps(self):\n init = {k: v.clone().detach() for k, v in self.model.state_dict().items()}\n\n # Train the model once and get the state.\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 0, len(self.train_loader)),\n end_step=Step.from_epoch(1, 1, len(self.train_loader)))\n state1 = TestTrain.get_state(self.model)\n\n # Train the model again and get the state.\n self.model.load_state_dict(init)\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 1, len(self.train_loader)),\n end_step=Step.from_epoch(1, 2, len(self.train_loader)))\n state2 = TestTrain.get_state(self.model)\n\n # Ensure that the model states are NOT the same.\n for k in state1:\n self.assertFalse(np.array_equal(state1[k], state2[k]))\n\n def test_different_data_order_on_different_epochs(self):\n del self.hparams.training_hparams.gamma\n del self.hparams.training_hparams.milestone_steps\n del self.hparams.training_hparams.warmup_steps\n\n init = {k: v.clone().detach() for k, v in self.model.state_dict().items()}\n\n # Train the model once and get the state.\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(1, 0, len(self.train_loader)),\n end_step=Step.from_epoch(1, 1, len(self.train_loader)))\n state1 = TestTrain.get_state(self.model)\n\n # Train the model again and get the state.\n self.model.load_state_dict(init)\n train.train(self.hparams.training_hparams, self.model, self.train_loader,\n self.root, callbacks=[self.callback],\n start_step=Step.from_epoch(2, 0, len(self.train_loader)),\n end_step=Step.from_epoch(2, 1, len(self.train_loader)))\n state2 = TestTrain.get_state(self.model)\n\n # Ensure that the model states are NOT the same.\n for k in state1:\n self.assertFalse(np.array_equal(state1[k], state2[k]))\n\n\ntest_case.main()\n"
] |
[
[
"numpy.round",
"numpy.array_equal"
]
] |
sternarubra/powerlawnoise
|
[
"4e03aae66a8379b4b755a39b9cf0df2c1b85c0d4"
] |
[
"pypowerlawnoise/pypowerlawnoise/tests/test_power_law_noise.py"
] |
[
"# Copyright (C) 2020 by Landmark Acoustics LLC\n\nimport pytest\n\nimport numpy as np\n\nfrom pypowerlawnoise import PowerLawNoise\n\nALPHAS = [-2, -1, 0, 1, 2]\nCOLOR_NAMES = ['red', 'pink', 'white', 'blue', 'violet']\nN = 5\nEQUIS = np.linspace(1, 0, N, dtype=float)\n\n\ndef pytest_generate_tests(metafunc):\n if metafunc.cls is not None and 'Trivial' in metafunc.cls.__name__:\n metafunc.parametrize('alpha', ALPHAS, ids=COLOR_NAMES)\n\n\[email protected]('alpha, answer',\n zip(ALPHAS,\n [1 + 0.75,\n 1.453125,\n 1.0,\n 0.359375,\n 1.0 - 0.75 - 0.5 - 0.25]),\n ids=COLOR_NAMES)\ndef test_integer_powers(alpha, answer):\n law = PowerLawNoise(alpha, N)\n assert law.make_one_sample(EQUIS) == answer\n\n\nclass TestTrivialExamples:\n @pytest.mark.parametrize('degree', range(N))\n def test_different_degrees(self, alpha, degree):\n law = PowerLawNoise(alpha, degree)\n assert law.degree == degree\n assert len(law.terms) == degree + 1\n\n @pytest.mark.parametrize('x', EQUIS)\n def test_zero_degree_is_white_noise(self, alpha, x):\n law = PowerLawNoise(alpha, 0)\n assert law(np.r_[x]) == x\n"
] |
[
[
"numpy.linspace"
]
] |
markomanninen/picoDAQ
|
[
"a07be1c9018577b1b5671fd3a184148a4fac337b"
] |
[
"picodaqa/animHists.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport time, numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\n\nclass animHists(object):\n ''' display histogram, as normalised frequency distibutions\n\n requency distribution of a scalar quantity\n '''\n\n def __init__(self, Hdescr, name='Histograms'):\n '''\n Args:\n list of histogram descriptors,\n where each descriptor is a list itself: [min, max, nbins, ymax, name, type]\n min: minimum value\n max: maximum value\n nbins: nubmer of bins\n ymax: scale factor for bin with highest number of entries\n name: name of the quantity being histogrammed\n type: 0 linear, 1 for logarithmic y scale\n name forfigure window\n '''\n\n self.nHist = len(Hdescr)\n self.entries = np.zeros(self.nHist)\n self.frqs = []\n\n # histrogram properties\n self.mins = []\n self.maxs = []\n self.nbins = []\n self.ymxs = []\n self.names = []\n self.types = []\n self.bedges = []\n self.bcents = []\n self.widths = []\n for ih in range(self.nHist):\n self.mins.append(Hdescr[ih][0])\n self.maxs.append(Hdescr[ih][1])\n self.nbins.append(Hdescr[ih][2])\n self.ymxs.append(Hdescr[ih][3])\n self.names.append(Hdescr[ih][4])\n self.types.append(Hdescr[ih][5])\n be = np.linspace(self.mins[ih], self.maxs[ih], self.nbins[ih] +1 ) # bin edges\n self.bedges.append(be)\n self.bcents.append( 0.5*(be[:-1] + be[1:]) ) # bin centers\n self.widths.append( 0.85*(be[1]-be[0]) ) # bar width\n\n # create figure\n ncols = int(np.sqrt(self.nHist))\n nrows = ncols\n if ncols * nrows < self.nHist: nrows +=1\n if ncols * nrows < self.nHist: ncols +=1\n self.fig, axarray = plt.subplots(nrows=nrows, ncols=ncols,\n figsize=(3.*ncols, 2.*nrows) )\n #self.fig.canvas.set_window_title(name)\n self.fig.subplots_adjust(left=0.25/ncols, bottom=0.25/nrows, right=0.975, top=0.95,\n wspace=0.35, hspace=0.35)\n# sort axes in linear array\n self.axes = []\n if self.nHist == 1:\n self.axes = [axarray]\n elif self.nHist == 2:\n for a in axarray:\n self.axes.append(a)\n else:\n nh = 0\n for ir in range(nrows):\n for ic in range(ncols):\n nh += 1\n if nh <= self.nHist:\n self.axes.append(axarray[ir,ic])\n else:\n axarray[ir,ic].axis('off')\n\n for ih in range(self.nHist):\n self.axes[ih].set_ylabel('frequency')\n self.axes[ih].set_xlabel(self.names[ih])\n# guess an appropriate y-range for normalized histogram\n if self.types[ih]: # log plot\n self.axes[ih].set_yscale('log')\n ymx=self.ymxs[ih]/self.nbins[ih]\n self.axes[ih].set_ylim(1E-3 * ymx, ymx)\n self.frqs.append(1E-4*ymx*np.ones(self.nbins[ih]) )\n else: # linear y scale\n self.axes[ih].set_ylim(0., self.ymxs[ih]/self.nbins[ih])\n self.frqs.append(np.zeros(self.nbins[ih]))\n\n def init(self):\n self.rects = []\n self.animtxts = []\n for ih in range(self.nHist):\n # plot an empty histogram\n self.rects.append(self.axes[ih].bar( self.bcents[ih], self.frqs[ih],\n align='center', width=self.widths[ih], facecolor='b', alpha=0.7) )\n # emty text\n self.animtxts.append(self.axes[ih].text(0.5, 0.925 , ' ',\n transform=self.axes[ih].transAxes,\n size='small', color='darkred') )\n\n grobjs = tuple(self.animtxts) \\\n + tuple(itertools.chain.from_iterable(self.rects) )\n return grobjs # return tuple of graphics objects\n\n def __call__(self, vals):\n # add recent values to frequency array, input is a list of arrays\n for ih in range(self.nHist):\n vs = vals[ih]\n self.entries[ih] += len(vs)\n for v in vs:\n iv = int(self.nbins[ih] * (v-self.mins[ih]) / (self.maxs[ih]-self.mins[ih]))\n if iv >=0 and iv < self.nbins[ih]:\n self.frqs[ih][iv]+=1\n if(len(vs)):\n norm = np.sum(self.frqs[ih]) # normalisation to one\n # set new heights for histogram bars\n for rect, frq in zip(self.rects[ih], self.frqs[ih]):\n rect.set_height(frq/norm)\n # update text\n self.animtxts[ih].set_text('Entries: %i'%(self.entries[ih]) )\n\n return tuple(self.animtxts) \\\n + tuple(itertools.chain.from_iterable(self.rects) )\n"
] |
[
[
"numpy.sqrt",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.ones",
"numpy.zeros",
"numpy.sum"
]
] |
blues-lin/Char-level-CNN-for-Chinese-Text-Classification-in-Keras
|
[
"81c7cdec48d4b17640e4c5465a4a412e338a7e62"
] |
[
"lib/vector_generator.py"
] |
[
"\"\"\" Generate vector. \"\"\"\nimport os.path\nimport random\nimport numpy as np\nfrom lib import Vectorizer\n\nBASE_PATH = os.path.dirname(os.path.realpath(__file__))\nCHAR_PATH = os.path.join(BASE_PATH, 'data/charTable.txt')\nLABEL_PATH = os.path.join(BASE_PATH, 'data/label.txt')\n\n\nclass VectGenerator:\n \"\"\"\n Generate vector from list of tuples.\n tuple[0] is text and tuple[1] is label.\n \"\"\"\n\n def __init__(\n self, dataList, textLength,\n forPredict=None,\n training=0.7,\n testing=0.15,\n validation=0.15,\n backend=\"th\"):\n\n self._vectorizer = Vectorizer(CHAR_PATH, LABEL_PATH)\n random.shuffle(dataList)\n self._textLength = textLength\n self._backend = backend\n if forPredict is None:\n dataLen = len(dataList)\n testLen = int(dataLen * testing)\n validLen = int(dataLen * validation)\n self._testList = dataList[0:testLen]\n self._validList = dataList[testLen:(testLen + validLen)]\n self._trainingList = dataList[(testLen + validLen):]\n else:\n self._predictList = dataList[:]\n if self._backend == \"th\":\n self._inputShape = (\n 1, self._vectorizer.getCharSpace(), self._textLength)\n else:\n self._inputShape = (\n self._vectorizer.getCharSpace(), self._textLength, 1)\n\n def getVectorizer(self):\n return self._vectorizer\n\n def _dataGenerator(self, dataSet, batch_size):\n x_batch = []\n y_batch = []\n while 1:\n for data in dataSet:\n x_batch.append(\n self._vectorizer.vectorize(data[0], self._textLength))\n y_batch.append(\n self._vectorizer.vectorizeLabel(data[1]))\n if (len(x_batch) == batch_size):\n X_vect_batch = np.array(x_batch)\n y_vect_batch = np.array(y_batch)\n if self._backend == \"th\":\n X_vect_batch = X_vect_batch.reshape(\n X_vect_batch.shape[0], 1,\n self._vectorizer.getCharSpace(),\n self._textLength)\n else:\n X_vect_batch = X_vect_batch.reshape(\n X_vect_batch.shape[0],\n self._vectorizer.getCharSpace(),\n self._textLength, 1)\n\n yield (X_vect_batch, y_vect_batch)\n x_batch = []\n y_batch = []\n\n def trainGenerator(self, batch_size):\n for data in self._dataGenerator(self._trainingList, batch_size):\n yield data\n\n def testGenerator(self, batch_size):\n for data in self._dataGenerator(self._testList, batch_size):\n yield data\n\n def validGenerator(self, batch_size):\n for data in self._dataGenerator(self._validList, batch_size):\n yield data\n\n def predictGenerator(self, batch_size):\n for data in self._dataGenerator(self._predictList, batch_size):\n yield data[0]\n\n def nb_train_samples(self):\n if self._trainingList is not None:\n return len(self._trainingList)\n\n def nb_test_samples(self):\n if self._testList is not None:\n return len(self._testList)\n\n def nb_val_samples(self):\n if self._validList is not None:\n return len(self._validList)\n\n def nb_predict_samples(self):\n if self._predictList is not None:\n return len(self._predictList)\n\n def nb_char_space(self):\n return self._vectorizer.getCharSpace()\n\n def nb_classes(self):\n return self._vectorizer.getClassSpace()\n\n def input_shape(self):\n return self._inputShape\n"
] |
[
[
"numpy.array"
]
] |
oom-debugger/GraphZoo-1
|
[
"7ef1184c0016090597e56b8706a87539a3f62fd6"
] |
[
"graphzoo/models/base_models.py"
] |
[
"\"\"\"\nBase model class\n\"\"\"\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score, average_precision_score\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom graphzoo.layers.layers import FermiDiracDecoder\nfrom graphzoo import manifolds\nimport graphzoo.models.encoders as encoders\nfrom graphzoo.models.decoders import model2decoder\nfrom graphzoo.utils.eval_utils import acc_f1\n\n\nclass BaseModel(nn.Module):\n \"\"\"\n Base model for graph embedding tasks\n\n Input Parameters\n ----------\n 'task': ('nc', 'which tasks to train on, can be any of [lp, nc] (type: str)')\n 'model': ('HGCN', 'which encoder to use, can be any of [Shallow, MLP, HNN, GCN, GAT, HGCN, HGAT] (type: str)')\n 'dim': (128, 'embedding dimension (type: int)')\n 'manifold': ('PoincareBall', 'which manifold to use, can be any of [Euclidean, Hyperboloid, PoincareBall] (type: str)')\n 'c': (1.0, 'hyperbolic radius, set to None for trainable curvature (type: float)')\n 'r': (2.0, 'fermi-dirac decoder parameter for lp (type: float)')\n 't': (1.0, 'fermi-dirac decoder parameter for lp (type: float)')\n 'pretrained-embeddings': (None, 'path to pretrained embeddings (.npy file) for Shallow node classification (type: str)')\n 'num-layers': (2, 'number of hidden layers in encoder (type: int)')\n 'bias': (1, 'whether to use bias (1) or not (0) (type: int)')\n 'act': ('relu', 'which activation function to use or None for no activation (type: str)')\n 'n-heads': (4, 'number of attention heads for graph attention networks, must be a divisor dim (type: int)')\n 'alpha': (0.2, 'alpha for leakyrelu in graph attention networks (type: float)')\n 'use-att': (0, 'whether to use hyperbolic attention (1) or not (0) (type: int)')\n 'local-agg': (0, 'whether to local tangent space aggregation (1) or not (0) (type: int)')\n 'n_classes': (7, 'number of classes in the dataset (type: int)')\n 'n_nodes': (2708, 'number of nodes in the graph (type: int)')\n 'feat_dim': (1433, 'feature dimension of the dataset (type: int)') \n \n API Input Parameters\n ----------\n args: list of above defined input parameters from `graphzoo.config`\n \"\"\"\n\n def __init__(self, args):\n super(BaseModel, self).__init__()\n self.manifold_name = args.manifold\n if args.c is not None:\n self.c = torch.tensor([args.c])\n if not args.cuda == -1:\n self.c = self.c.to(args.device)\n else:\n self.c = nn.Parameter(torch.Tensor([1.]))\n self.manifold = getattr(manifolds, self.manifold_name)()\n if self.manifold.name == 'Hyperboloid':\n args.feat_dim = args.feat_dim + 1\n \n self.nnodes = args.n_nodes\n self.encoder = getattr(encoders, args.model)(self.c, args)\n\n def encode(self, x, adj):\n if self.manifold.name == 'Hyperboloid':\n o = torch.zeros_like(x)\n x = torch.cat([o[:, 0:1], x], dim=1)\n h = self.encoder.encode(x, adj)\n return h\n\n def compute_metrics(self, embeddings, data, split):\n raise NotImplementedError\n\n def init_metric_dict(self):\n raise NotImplementedError\n\n def has_improved(self, m1, m2):\n raise NotImplementedError\n\n\nclass NCModel(BaseModel):\n \"\"\"\n Base model for node classification task\n \"\"\"\n\n def __init__(self, args):\n super(NCModel, self).__init__(args)\n self.decoder = model2decoder[args.model](self.c, args)\n\n if args.n_classes > 2:\n self.f1_average = 'micro'\n else:\n self.f1_average = 'binary'\n \n self.weights = torch.Tensor([1.] * args.n_classes)\n \n if not args.cuda == -1:\n self.weights = self.weights.to(args.device)\n\n def decode(self, h, adj, idx):\n output = self.decoder.decode(h, adj)\n return F.log_softmax(output[idx], dim=1)\n\n def compute_metrics(self, embeddings, data, split):\n idx = data[f'idx_{split}']\n output = self.decode(embeddings, data['adj_train_norm'], idx)\n loss = F.nll_loss(output, data['labels'][idx], self.weights)\n acc, f1 = acc_f1(output, data['labels'][idx], average=self.f1_average)\n metrics = {'loss': loss, 'acc': acc, 'f1': f1}\n return metrics\n\n def init_metric_dict(self):\n return {'acc': -1, 'f1': -1}\n\n def has_improved(self, m1, m2):\n return m1[\"f1\"] < m2[\"f1\"]\n\n\nclass LPModel(BaseModel):\n \"\"\"\n Base model for link prediction task\n \"\"\"\n\n def __init__(self, args):\n super(LPModel, self).__init__(args)\n self.dc = FermiDiracDecoder(r=args.r, t=args.t)\n\n def decode(self, h, idx):\n if self.manifold_name == 'Euclidean':\n h = self.manifold.normalize(h)\n emb_in = h[idx[:, 0], :]\n emb_out = h[idx[:, 1], :]\n sqdist = self.manifold.sqdist(emb_in, emb_out, self.c)\n probs = self.dc.forward(sqdist)\n return probs\n\n def compute_metrics(self, embeddings, data, split):\n if split == 'train':\n nb_false_edges = len(data['train_edges_false'])\n nb_edges = len(data['train_edges'])\n edges_false = data[f'{split}_edges_false'][np.random.randint(0, nb_false_edges, nb_edges)]\n else:\n edges_false = data[f'{split}_edges_false']\n pos_scores = self.decode(embeddings, data[f'{split}_edges'])\n neg_scores = self.decode(embeddings, edges_false)\n loss = F.binary_cross_entropy(pos_scores, torch.ones_like(pos_scores))\n loss += F.binary_cross_entropy(neg_scores, torch.zeros_like(neg_scores))\n if pos_scores.is_cuda:\n pos_scores = pos_scores.cpu()\n neg_scores = neg_scores.cpu()\n labels = [1] * pos_scores.shape[0] + [0] * neg_scores.shape[0]\n preds = list(pos_scores.data.numpy()) + list(neg_scores.data.numpy())\n roc = roc_auc_score(labels, preds)\n ap = average_precision_score(labels, preds)\n metrics = {'loss': loss, 'roc': roc, 'ap': ap}\n return metrics\n\n def init_metric_dict(self):\n return {'roc': -1, 'ap': -1}\n\n def has_improved(self, m1, m2):\n return 0.5 * (m1['roc'] + m1['ap']) < 0.5 * (m2['roc'] + m2['ap'])\n\n"
] |
[
[
"sklearn.metrics.roc_auc_score",
"torch.nn.functional.log_softmax",
"torch.nn.functional.nll_loss",
"torch.Tensor",
"torch.cat",
"torch.zeros_like",
"torch.tensor",
"sklearn.metrics.average_precision_score",
"torch.ones_like",
"numpy.random.randint"
]
] |
valterlej/CustomBMT
|
[
"c9326752d1355c81f845f2caab9c047be76067de"
] |
[
"model/proposal_generator.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom model.encoders import BiModalEncoder, Encoder\nfrom utilities.proposal_utils import add_dict_to_another_dict, select_topk_predictions, tiou_vectorized\n\nfrom model.blocks import Transpose, FeatureEmbedder, Identity, PositionalEncoder\n\n\nclass ProposalGenerationHead(nn.Module):\n\n def __init__(self, d_model_list, kernel_size, dout_p, layer_norm=False):\n super(ProposalGenerationHead, self).__init__()\n assert kernel_size % 2 == 1, 'It is more convenient to use odd kernel_sizes for padding'\n conv_layers = []\n in_dims = d_model_list[:-1]\n out_dims = d_model_list[1:]\n N_layers = len(d_model_list) - 1\n\n for n, (in_d, out_d) in enumerate(zip(in_dims, out_dims)):\n if layer_norm:\n conv_layers.append(Transpose())\n conv_layers.append(nn.LayerNorm(in_d))\n conv_layers.append(Transpose())\n\n if n == 0:\n conv_layers.append(nn.Conv1d(in_d, out_d, kernel_size, padding=kernel_size//2))\n else:\n conv_layers.append(nn.Conv1d(in_d, out_d, kernel_size=1))\n\n if n < (N_layers - 1):\n if dout_p > 0:\n conv_layers.append(nn.Dropout(dout_p))\n conv_layers.append(nn.ReLU())\n\n self.conv_layers = nn.Sequential(*conv_layers)\n\n def forward(self, x):\n # (B, D, S) <- (B, S, D)\n x = x.permute(0, 2, 1)\n # (B, d, S) <- (B, D, S)\n x = self.conv_layers(x)\n # (B, S, d) <- (B, d, S)\n x = x.permute(0, 2, 1)\n # x = self.fc_layer(x)\n return x\n \n\nclass ProposalGenerator(nn.Module):\n \n def __init__(self, cfg, anchors):\n super(ProposalGenerator, self).__init__()\n self.cfg = cfg\n self.EPS = 1e-16\n self.num_logits = 3 # 3: c, w, obj\n self.anchors = anchors\n self.anchors_list = anchors[cfg.modality]\n self.anchors_num = len(self.anchors_list)\n\n if cfg.modality == 'video':\n self.d_feat = cfg.d_vid\n self.d_model_modality = cfg.d_model_video\n self.d_ff = cfg.d_ff_video\n layer_dims = [\n self.d_model_modality, *cfg.conv_layers_video, self.num_logits*self.anchors_num\n ]\n elif cfg.modality == 'audio':\n self.d_feat = cfg.d_aud\n self.d_model_modality = cfg.d_model_audio\n self.d_ff = cfg.d_ff_audio\n layer_dims = [\n self.d_model_modality, *cfg.conv_layers_audio, self.num_logits*self.anchors_num\n ]\n else:\n raise NotImplementedError\n\n if cfg.use_linear_embedder:\n self.emb = FeatureEmbedder(self.d_feat, self.d_model_modality)\n else:\n self.emb = Identity()\n self.pos_enc = PositionalEncoder(self.d_model_modality, cfg.dout_p)\n\n # load the pre-trained encoder from captioning module\n if cfg.pretrained_cap_model_path is not None:\n print(f'Caption path: \\n {cfg.pretrained_cap_model_path}')\n cap_model_cpt = torch.load(cfg.pretrained_cap_model_path, map_location='cpu')\n encoder_config = cap_model_cpt['config']\n if cfg.modality == 'video':\n self.d_model_modality = encoder_config.d_model_video\n self.d_ff = encoder_config.d_ff_video\n elif cfg.modality == 'audio':\n self.d_model_modality = encoder_config.d_model_audio\n self.d_ff = encoder_config.d_ff_audio\n else:\n raise NotImplementedError\n self.encoder = Encoder(\n self.d_model_modality, encoder_config.dout_p, encoder_config.H, self.d_ff, \n encoder_config.N\n )\n encoder_weights = {k: v for k, v in cap_model_cpt['model_state_dict'].items() if 'encoder' in k}\n encoder_weights = {k.replace('module.encoder.', ''): v for k, v in encoder_weights.items()}\n self.encoder.load_state_dict(encoder_weights)\n self.encoder = self.encoder.to(cfg.device)\n for param in self.encoder.parameters():\n param.requires_grad = cfg.finetune_cap_encoder\n else:\n self.encoder = Encoder(self.d_model_modality, cfg.dout_p, cfg.H, self.d_ff, cfg.N)\n # encoder initialization\n for p in self.encoder.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n self.detection_layers = torch.nn.ModuleList([\n ProposalGenerationHead(layer_dims, k, cfg.dout_p, cfg.layer_norm) for k in cfg.kernel_sizes[cfg.modality]\n ])\n\n print(self.detection_layers)\n self.bce_loss = nn.BCELoss()\n self.mse_loss = nn.MSELoss()\n\n def kernel_size_forward(self, x, layer, stride, targets):\n # in case targets is None\n loss = 0\n losses = {}\n x = layer(x)\n\n B, S, D = x.shape\n x = x.view(B, S, self.anchors_num, self.num_logits)\n\n x = x.permute(0, 2, 1, 3).contiguous()\n grid_cell = torch.arange(S).view(1, 1, S).float().to(self.cfg.device)\n # After dividing anchors by the stride, they represent the size size of\n # how many grid celts they are overlapping: 1.2 = 1 and 20% of a grid cell.\n # After multiplying them by the stride, the pixel values are going to be\n # obtained.\n anchors_list = [[anchor / stride] for anchor in self.anchors_list]\n anchors_tensor = torch.tensor(anchors_list, device=self.cfg.device)\n # (A, 2) -> (1, A, 1) for broadcasting\n prior_length = anchors_tensor.view(1, self.anchors_num, 1)\n\n # prediction values for the *loss* calculation (training)\n sigma_c = torch.sigmoid(x[:, :, :, 0]) # center shift\n l = x[:, :, :, 1] # log coefficient\n sigma_o = torch.sigmoid(x[:, :, :, 2]) # objectness\n\n # prediction values that are going to be used for the original image\n # we need to detach them from the graph as we don't need to backproparate on them\n predictions = x.clone().detach()\n # broadcasting (B, A, S) + (1, 1, S)\n predictions[:, :, :, 0] = sigma_c + grid_cell\n # broadcasting (1, A, 1) * (B, A, S)\n predictions[:, :, :, 1] = prior_length * torch.exp(l)\n predictions[:, :, :, 2] = sigma_o\n\n if targets is not None:\n obj_mask, noobj_mask, gt_x, gt_w, gt_obj = make_targets(predictions, targets, \n anchors_tensor, stride)\n ## Loss\n # Localization\n loss_x = self.mse_loss(sigma_c[obj_mask], gt_x[obj_mask])\n loss_w = self.mse_loss(l[obj_mask], gt_w[obj_mask])\n loss_loc = loss_x + loss_w\n # Confidence\n loss_obj = self.bce_loss(sigma_o[obj_mask], gt_obj[obj_mask])\n loss_noobj = self.bce_loss(sigma_o[noobj_mask], gt_obj[noobj_mask])\n loss_conf = self.cfg.obj_coeff * loss_obj + self.cfg.noobj_coeff * loss_noobj\n # Total loss\n loss = loss_loc + loss_conf\n\n losses = {\n 'loss_x': loss_x, \n 'loss_w': loss_w, \n 'loss_conf_obj': loss_obj, \n 'loss_conf_noobj': loss_noobj\n }\n\n # for NMS: (B, A, S, 3) -> (B, A*S, 3)\n predictions = predictions.view(B, S*self.anchors_num, self.num_logits)\n predictions[:, :, :2] *= stride\n \n return predictions, loss, losses\n \n def forward(self, x, targets, masks):\n\n if self.cfg.modality == 'video':\n x = x['rgb'] + x['flow']\n stride = self.cfg.strides['video']\n x = self.emb(x)\n x = self.pos_enc(x)\n x = self.encoder(x, masks['V_mask'])\n elif self.cfg.modality == 'audio':\n x = x['audio']\n stride = self.cfg.strides['audio']\n x = self.emb(x)\n x = self.pos_enc(x)\n x = self.encoder(x, masks['A_mask'])\n\n all_predictions = []\n # total_loss should have backward\n sum_losses_dict = {}\n total_loss = 0\n \n for layer in self.detection_layers:\n predictions, loss, loss_dict = self.kernel_size_forward(x, layer, stride, targets)\n total_loss += loss\n all_predictions.append(predictions)\n sum_losses_dict = add_dict_to_another_dict(loss_dict, sum_losses_dict)\n\n all_predictions = torch.cat(all_predictions, dim=1)\n\n return all_predictions, total_loss, sum_losses_dict\n \n\nclass MultimodalProposalGenerator(nn.Module):\n\n def __init__(self, cfg, anchors):\n super(MultimodalProposalGenerator, self).__init__()\n assert cfg.modality == 'audio_video'\n self.cfg = cfg\n self.anchors = anchors\n self.EPS = 1e-16\n self.num_logits = 3 # 3: c, w, obj\n\n if cfg.use_linear_embedder:\n self.emb_V = FeatureEmbedder(cfg.d_vid, cfg.d_model_video)\n self.emb_A = FeatureEmbedder(cfg.d_aud, cfg.d_model_audio)\n else:\n self.emb_V = Identity()\n self.emb_A = Identity()\n self.pos_enc_V = PositionalEncoder(cfg.d_model_video, cfg.dout_p)\n self.pos_enc_A = PositionalEncoder(cfg.d_model_audio, cfg.dout_p)\n\n # load the pre-trained encoder from captioning module\n if cfg.pretrained_cap_model_path is not None:\n print(f'Pretrained caption path: \\n {cfg.pretrained_cap_model_path}')\n cap_model_cpt = torch.load(cfg.pretrained_cap_model_path, map_location='cpu')\n encoder_config = cap_model_cpt['config']\n self.encoder = BiModalEncoder(\n encoder_config.d_model_audio, encoder_config.d_model_video, encoder_config.d_model, \n encoder_config.dout_p, encoder_config.H, encoder_config.d_ff_audio, \n encoder_config.d_ff_video, encoder_config.N\n )\n encoder_weights = {k: v for k, v in cap_model_cpt['model_state_dict'].items() if 'encoder' in k}\n encoder_weights = {k.replace('module.encoder.', ''): v for k, v in encoder_weights.items()}\n self.encoder.load_state_dict(encoder_weights)\n self.encoder = self.encoder.to(cfg.device)\n for param in self.encoder.parameters():\n param.requires_grad = cfg.finetune_cap_encoder\n else:\n self.encoder = BiModalEncoder(\n cfg.d_model_audio, cfg.d_model_video, cfg.d_model, cfg.dout_p, cfg.H,\n cfg.d_ff_audio, cfg.d_ff_video, cfg.N\n )\n # encoder initialization\n for p in self.encoder.parameters():\n if p.dim() > 1:\n nn.init.xavier_uniform_(p)\n\n dims_A = [cfg.d_model_audio, *cfg.conv_layers_audio, self.num_logits*cfg.anchors_num_audio]\n dims_V = [cfg.d_model_video, *cfg.conv_layers_video, self.num_logits*cfg.anchors_num_video]\n self.detection_layers_A = torch.nn.ModuleList([\n ProposalGenerationHead(dims_A, k, cfg.dout_p, cfg.layer_norm) for k in cfg.kernel_sizes['audio']\n ])\n self.detection_layers_V = torch.nn.ModuleList([\n ProposalGenerationHead(dims_V, k, cfg.dout_p, cfg.layer_norm) for k in cfg.kernel_sizes['video']\n ])\n \n self.bce_loss = nn.BCELoss()\n self.mse_loss = nn.MSELoss()\n\n def forward_modality(self, x, targets, detection, stride, anchors_list):\n anchors_num = len(anchors_list)\n # in case targets is None\n loss = 0\n losses = {}\n\n x = detection(x)\n\n B, S, D = x.shape\n x = x.view(B, S, anchors_num, self.num_logits)\n\n x = x.permute(0, 2, 1, 3).contiguous()\n grid_cell = torch.arange(S).view(1, 1, S).float().to(self.cfg.device)\n # After dividing anchors by the stride, they represent the size size of\n # how many grid celts they are overlapping: 1.2 = 1 and 20% of a grid cell.\n # After multiplying them by the stride, the pixel values are going to be\n # obtained.\n anchors_list = [[anchor / stride] for anchor in anchors_list]\n anchors_tensor = torch.tensor(anchors_list, device=self.cfg.device)\n # (A, 2) -> (1, A, 1) for broadcasting\n prior_length = anchors_tensor.view(1, anchors_num, 1)\n\n # prediction values for the *loss* calculation (training)\n sigma_c = torch.sigmoid(x[:, :, :, 0]) # center\n l = x[:, :, :, 1] # length\n sigma_o = torch.sigmoid(x[:, :, :, 2]) # objectness\n\n # prediction values that are going to be used for the original image\n # we need to detach them from the graph as we don't need to backproparate\n # on them\n predictions = x.clone().detach()\n # broadcasting (B, A, S) + (1, 1, S)\n # For now, we are not going to multiply them by stride since\n # we need them in make_targets\n predictions[:, :, :, 0] = sigma_c + grid_cell\n # broadcasting (1, A, 1) * (B, A, S)\n predictions[:, :, :, 1] = prior_length * torch.exp(l)\n predictions[:, :, :, 2] = sigma_o\n\n if targets is not None:\n obj_mask, noobj_mask, gt_x, gt_w, gt_obj = make_targets(predictions, targets, \n anchors_tensor, stride)\n ## Loss\n # Localization\n loss_x = self.mse_loss(sigma_c[obj_mask], gt_x[obj_mask])\n loss_w = self.mse_loss(l[obj_mask], gt_w[obj_mask])\n loss_loc = loss_x + loss_w\n # Confidence\n loss_obj = self.bce_loss(sigma_o[obj_mask], gt_obj[obj_mask])\n loss_noobj = self.bce_loss(sigma_o[noobj_mask], gt_obj[noobj_mask])\n loss_conf = self.cfg.obj_coeff * loss_obj + self.cfg.noobj_coeff * loss_noobj\n # Total loss\n loss = loss_loc + loss_conf\n\n losses = {\n 'loss_x': loss_x,\n 'loss_w': loss_w,\n 'loss_conf_obj': loss_obj,\n 'loss_conf_noobj': loss_noobj\n }\n\n # for NMS: (B, A, S, 3) -> (B, A*S, 3)\n predictions = predictions.view(B, S*anchors_num, self.num_logits)\n predictions[:, :, :2] *= stride\n\n return predictions, loss, losses\n\n def forward(self, x, targets, masks):\n V, A = x['rgb'] + x['flow'], x['audio']\n\n # (B, Sm, Dm) < - (B, Sm, Dm), m in [a, v]\n A = self.emb_A(A)\n V = self.emb_V(V)\n A = self.pos_enc_A(A)\n V = self.pos_enc_V(V)\n # notation: M1m2m2 (B, Sm1, Dm1), M1 is the target modality, m2 is the source modality\n Av, Va = self.encoder((A, V), masks)\n\n all_predictions_A = []\n all_predictions_V = []\n # total_loss should have backward\n sum_losses_dict_A = {}\n sum_losses_dict_V = {}\n total_loss_A = 0\n total_loss_V = 0\n\n for layer in self.detection_layers_A:\n props_A, loss_A, losses_A = self.forward_modality(\n Av, targets, layer, self.cfg.strides['audio'], self.anchors['audio']\n )\n total_loss_A += loss_A\n all_predictions_A.append(props_A)\n sum_losses_dict_A = add_dict_to_another_dict(losses_A, sum_losses_dict_A)\n\n for layer in self.detection_layers_V:\n props_V, loss_V, losses_V = self.forward_modality(\n Va, targets, layer, self.cfg.strides['video'], self.anchors['video']\n )\n total_loss_V += loss_V\n all_predictions_V.append(props_V)\n sum_losses_dict_V = add_dict_to_another_dict(losses_V, sum_losses_dict_V)\n\n all_predictions_A = torch.cat(all_predictions_A, dim=1)\n all_predictions_V = torch.cat(all_predictions_V, dim=1)\n\n total_loss = total_loss_A + total_loss_V\n\n # combine predictions\n all_predictions = torch.cat([all_predictions_A, all_predictions_V], dim=1)\n # if you like the predictions to be half from audio and half from the video modalities\n # all_predictions = torch.cat([\n # select_topk_predictions(all_predictions_A, k=self.cfg.max_prop_per_vid // 2),\n # select_topk_predictions(all_predictions_V, k=self.cfg.max_prop_per_vid // 2)\n # ], dim=1)\n\n return all_predictions, total_loss, sum_losses_dict_A, sum_losses_dict_V\n\ndef make_targets(predictions, targets, anchors, stride):\n '''\n The implementation relies on YOLOv3 for object detection\n - https://github.com/eriklindernoren/PyTorch-YOLOv3/blob/master/models.py\n - https://github.com/v-iashin/PersonalProjects/blob/master/detector/darknet.py\n '''\n B, num_anchs, G, num_feats = predictions.size()\n\n # classes = 1\n EPS = 1e-16\n\n # create the placeholders\n noobj_mask = torch.ones(B, num_anchs, G, device=predictions.device).bool()\n obj_mask = torch.zeros_like(noobj_mask).bool()\n target_x = torch.zeros_like(noobj_mask).float()\n target_w = torch.zeros_like(noobj_mask).float()\n\n # image index within the batch, the g.t. label of an object on the image\n vid_idx = targets[:, 0].long()\n # ground truth center coordinates and bbox dimensions\n # since the target bbox coordinates are in seconds, we transoform\n # them into grid-axis\n # So, the gt_x will represent the position of the center in grid cells\n # Similarly, the size sizes are also scaled to grid size\n gt_x = targets[:, 1] / stride\n gt_w = targets[:, 2] / stride\n # ious between scaled anchors (anchors_from_cfg / stride) and gt bboxes\n gt_anchor_ious = tiou_vectorized(anchors, gt_w.unsqueeze(-1), without_center_coords=True)\n # selecting the best anchors for the g.t. bboxes\n best_ious, best_anchors = gt_anchor_ious.max(dim=0)\n\n # remove a decimal part -> gi point to the grid position to which an object will correspond \n # for example: 9.89 -> 9\n gt_cell = gt_x.long()\n # helps with RuntimeError: CUDA error: device-side assert triggered\n # This aims to avoid gt_cell[i] exceeding the bounds\n gt_cell[gt_cell < 0] = 0\n gt_cell[gt_cell > G - 1] = G - 1\n # update the obj and noobj masks.\n # the noobj mask has 0 where obj mask has 1 and where IoU between\n # g.t. bbox and anchor is higher than ignore_thresh\n obj_mask[vid_idx, best_anchors, gt_cell] = 1\n noobj_mask[vid_idx, best_anchors, gt_cell] = 0\n\n # center shift: for example 9.89 -> 0.89\n target_x[vid_idx, best_anchors, gt_cell] = gt_x - gt_x.floor()\n\n # Yolo predicts the coefficients (log of coefs actually, see exp() in the paper) \n # that will be used to multiply with anchor lengths for predicted segment lengths\n # Therefore, we modify targets and apply log transformation.\n target_w[vid_idx, best_anchors, gt_cell] = torch.log(gt_w.t() / anchors[best_anchors][:, 0] + EPS)\n # since YOLO loss penalizes the model only for wrong predictions at the ground truth\n # cells, we extract only these predictions from the tensor\n # Extracting the labels from the prediciton tensor\n pred_x_w = predictions[vid_idx, best_anchors, gt_cell, :2]\n\n # ground truth objectness\n target_obj = obj_mask.float()\n\n return obj_mask, noobj_mask, target_x, target_w, target_obj\n"
] |
[
[
"torch.nn.Sequential",
"torch.sigmoid",
"torch.nn.Dropout",
"torch.ones",
"torch.cat",
"torch.load",
"torch.zeros_like",
"torch.arange",
"torch.tensor",
"torch.nn.BCELoss",
"torch.exp",
"torch.nn.LayerNorm",
"torch.nn.init.xavier_uniform_",
"torch.nn.Conv1d",
"torch.nn.ReLU",
"torch.nn.MSELoss"
]
] |
thusithaC/QGforQA
|
[
"81beed7122abbf9a62745af8ab7d6d4d4bf52c73"
] |
[
"LIB/bert/run_classifier.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport csv\nimport os\n\nimport modeling\nimport optimization\nimport tensorflow as tf\n\nfrom bert import tokenization\n\nflags = tf.flags\n\nFLAGS = flags.FLAGS\n\n## Required parameters\nflags.DEFINE_string(\n \"data_dir\", None,\n \"The input data dir. Should contain the .tsv files (or other data files) \"\n \"for the task.\")\n\nflags.DEFINE_string(\n \"bert_config_file\", None,\n \"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\")\n\nflags.DEFINE_string(\"vocab_file\", None,\n \"The vocabulary file that the BERT model was trained on.\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\n## Other parameters\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 128,\n \"The maximum total input sequence length after WordPiece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_bool(\n \"do_predict\", False,\n \"Whether to run the model in inference mode on the test set.\")\n\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\n\nflags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\")\n\nflags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\")\n\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\n \"Total number of training epochs to perform.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 1000,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\ntf.flags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\ntf.flags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_integer(\n \"num_tpu_cores\", 8,\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass PaddingInputExample(object):\n \"\"\"Fake example so the num input examples is a multiple of the batch size.\n\n When running eval/predict on the TPU, we need to pad the number of examples\n to be a multiple of the batch size, because the TPU requires a fixed batch\n size. The alternative is to drop the last batch, which is bad because it means\n the entire output data won't be generated.\n\n We use this class instead of `None` because treating `None` as padding\n battches could cause silent errors.\n \"\"\"\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n input_ids,\n input_mask,\n segment_ids,\n label_id,\n is_real_example=True):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n self.is_real_example = is_real_example\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_test_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for prediction.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\n\nclass XnliProcessor(DataProcessor):\n \"\"\"Processor for the XNLI data set.\"\"\"\n\n def __init__(self):\n self.language = \"zh\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n lines = self._read_tsv(\n os.path.join(data_dir, \"multinli\",\n \"multinli.train.%s.tsv\" % self.language))\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"train-%d\" % (i)\n text_a = tokenization.convert_to_unicode(line[0])\n text_b = tokenization.convert_to_unicode(line[1])\n label = tokenization.convert_to_unicode(line[2])\n if label == tokenization.convert_to_unicode(\"contradictory\"):\n label = tokenization.convert_to_unicode(\"contradiction\")\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n lines = self._read_tsv(os.path.join(data_dir, \"xnli.dev.tsv\"))\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"dev-%d\" % (i)\n language = tokenization.convert_to_unicode(line[0])\n if language != tokenization.convert_to_unicode(self.language):\n continue\n text_a = tokenization.convert_to_unicode(line[6])\n text_b = tokenization.convert_to_unicode(line[7])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n\nclass MnliProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")),\n \"dev_matched\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test_matched.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, tokenization.convert_to_unicode(line[0]))\n text_a = tokenization.convert_to_unicode(line[8])\n text_b = tokenization.convert_to_unicode(line[9])\n if set_type == \"test\":\n label = \"contradiction\"\n else:\n label = tokenization.convert_to_unicode(line[-1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MrpcProcessor(DataProcessor):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[3])\n text_b = tokenization.convert_to_unicode(line[4])\n if set_type == \"test\":\n label = \"0\"\n else:\n label = tokenization.convert_to_unicode(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass ColaProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # Only the test set has a header\n if set_type == \"test\" and i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n if set_type == \"test\":\n text_a = tokenization.convert_to_unicode(line[1])\n label = \"0\"\n else:\n text_a = tokenization.convert_to_unicode(line[3])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\ndef convert_single_example(ex_index, example, label_list, max_seq_length,\n tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n\n if isinstance(example, PaddingInputExample):\n return InputFeatures(\n input_ids=[0] * max_seq_length,\n input_mask=[0] * max_seq_length,\n segment_ids=[0] * max_seq_length,\n label_id=0,\n is_real_example=False)\n\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n if ex_index < 5:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"guid: %s\" % (example.guid))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n tf.logging.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id,\n is_real_example=True)\n return feature\n\n\ndef file_based_convert_examples_to_features(\n examples, label_list, max_seq_length, tokenizer, output_file):\n \"\"\"Convert a set of `InputExample`s to a TFRecord file.\"\"\"\n\n writer = tf.python_io.TFRecordWriter(output_file)\n\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n features = collections.OrderedDict()\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"label_ids\"] = create_int_feature([feature.label_id])\n features[\"is_real_example\"] = create_int_feature(\n [int(feature.is_real_example)])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n writer.close()\n\n\ndef file_based_input_fn_builder(input_file, seq_length, is_training,\n drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n name_to_features = {\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"label_ids\": tf.FixedLenFeature([], tf.int64),\n \"is_real_example\": tf.FixedLenFeature([], tf.int64),\n }\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.contrib.data.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n labels, num_labels, use_one_hot_embeddings):\n \"\"\"Creates a classification model.\"\"\"\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # In the demo, we are doing a simple classification task on the entire\n # segment.\n #\n # If you want to use the token-level output, use model.get_sequence_output()\n # instead.\n output_layer = model.get_pooled_output()\n\n hidden_size = output_layer.shape[-1].value\n\n output_weights = tf.get_variable(\n \"output_weights\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n # I.e., 0.1 dropout\n output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n probabilities = tf.nn.softmax(logits, axis=-1)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(per_example_loss)\n\n return (loss, per_example_loss, logits, probabilities)\n\n\ndef model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n tf.logging.info(\"*** Features ***\")\n for name in sorted(features.keys()):\n tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n label_ids = features[\"label_ids\"]\n is_real_example = None\n if \"is_real_example\" in features:\n is_real_example = tf.cast(features[\"is_real_example\"], dtype=tf.float32)\n else:\n is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n (total_loss, per_example_loss, logits, probabilities) = create_model(\n bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,\n num_labels, use_one_hot_embeddings)\n\n tvars = tf.trainable_variables()\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map, initialized_variable_names\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n if use_tpu:\n\n def tpu_scaffold():\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n tf.logging.info(\"**** Trainable Variables ****\")\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n init_string)\n\n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n elif mode == tf.estimator.ModeKeys.EVAL:\n\n def metric_fn(per_example_loss, label_ids, logits, is_real_example):\n predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)\n accuracy = tf.metrics.accuracy(\n labels=label_ids, predictions=predictions, weights=is_real_example)\n loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)\n return {\n \"eval_accuracy\": accuracy,\n \"eval_loss\": loss,\n }\n\n eval_metrics = (metric_fn,\n [per_example_loss, label_ids, logits, is_real_example])\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n eval_metrics=eval_metrics,\n scaffold_fn=scaffold_fn)\n else:\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n predictions={\"probabilities\": probabilities},\n scaffold_fn=scaffold_fn)\n return output_spec\n\n return model_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef input_fn_builder(features, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n all_input_ids = []\n all_input_mask = []\n all_segment_ids = []\n all_label_ids = []\n\n for feature in features:\n all_input_ids.append(feature.input_ids)\n all_input_mask.append(feature.input_mask)\n all_segment_ids.append(feature.segment_ids)\n all_label_ids.append(feature.label_id)\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n num_examples = len(features)\n\n # This is for demo purposes and does NOT scale to large data sets. We do\n # not use Dataset.from_generator() because that uses tf.py_func which is\n # not TPU compatible. The right way to load data is with TFRecordReader.\n d = tf.data.Dataset.from_tensor_slices({\n \"input_ids\":\n tf.constant(\n all_input_ids, shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input_mask\":\n tf.constant(\n all_input_mask,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"segment_ids\":\n tf.constant(\n all_segment_ids,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"label_ids\":\n tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),\n })\n\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)\n return d\n\n return input_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer):\n \"\"\"Convert a set of `InputExample`s to a list of `InputFeatures`.\"\"\"\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n features.append(feature)\n return features\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n\n processors = {\n \"cola\": ColaProcessor,\n \"mnli\": MnliProcessor,\n \"mrpc\": MrpcProcessor,\n \"xnli\": XnliProcessor,\n }\n\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\n FLAGS.init_checkpoint)\n\n if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:\n raise ValueError(\n \"At least one of `do_train`, `do_eval` or `do_predict' must be True.\")\n\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n tf.gfile.MakeDirs(FLAGS.output_dir)\n\n task_name = FLAGS.task_name.lower()\n\n if task_name not in processors:\n raise ValueError(\"Task not found: %s\" % (task_name))\n\n processor = processors[task_name]()\n\n label_list = processor.get_labels()\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n if FLAGS.do_train:\n train_examples = processor.get_train_examples(FLAGS.data_dir)\n num_train_steps = int(\n len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=len(label_list),\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=FLAGS.train_batch_size,\n eval_batch_size=FLAGS.eval_batch_size,\n predict_batch_size=FLAGS.predict_batch_size)\n\n if FLAGS.do_train:\n train_file = os.path.join(FLAGS.output_dir, \"train.tf_record\")\n file_based_convert_examples_to_features(\n train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)\n tf.logging.info(\"***** Running training *****\")\n tf.logging.info(\" Num examples = %d\", len(train_examples))\n tf.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\n tf.logging.info(\" Num steps = %d\", num_train_steps)\n train_input_fn = file_based_input_fn_builder(\n input_file=train_file,\n seq_length=FLAGS.max_seq_length,\n is_training=True,\n drop_remainder=True)\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n\n if FLAGS.do_eval:\n eval_examples = processor.get_dev_examples(FLAGS.data_dir)\n num_actual_eval_examples = len(eval_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on. These do NOT count towards the metric (all tf.metrics\n # support a per-instance weight, and these get a weight of 0.0).\n while len(eval_examples) % FLAGS.eval_batch_size != 0:\n eval_examples.append(PaddingInputExample())\n\n eval_file = os.path.join(FLAGS.output_dir, \"eval.tf_record\")\n file_based_convert_examples_to_features(\n eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)\n\n tf.logging.info(\"***** Running evaluation *****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(eval_examples), num_actual_eval_examples,\n len(eval_examples) - num_actual_eval_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)\n\n # This tells the estimator to run through the entire set.\n eval_steps = None\n # However, if running eval on the TPU, you will need to specify the\n # number of steps.\n if FLAGS.use_tpu:\n assert len(eval_examples) % FLAGS.eval_batch_size == 0\n eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)\n\n eval_drop_remainder = True if FLAGS.use_tpu else False\n eval_input_fn = file_based_input_fn_builder(\n input_file=eval_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=eval_drop_remainder)\n\n result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)\n\n output_eval_file = os.path.join(FLAGS.output_dir, \"eval_results.txt\")\n with tf.gfile.GFile(output_eval_file, \"w\") as writer:\n tf.logging.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n tf.logging.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n if FLAGS.do_predict:\n predict_examples = processor.get_test_examples(FLAGS.data_dir)\n num_actual_predict_examples = len(predict_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on.\n while len(predict_examples) % FLAGS.predict_batch_size != 0:\n predict_examples.append(PaddingInputExample())\n\n predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\")\n file_based_convert_examples_to_features(predict_examples, label_list,\n FLAGS.max_seq_length, tokenizer,\n predict_file)\n\n tf.logging.info(\"***** Running prediction*****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(predict_examples), num_actual_predict_examples,\n len(predict_examples) - num_actual_predict_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n predict_drop_remainder = True if FLAGS.use_tpu else False\n predict_input_fn = file_based_input_fn_builder(\n input_file=predict_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=predict_drop_remainder)\n\n result = estimator.predict(input_fn=predict_input_fn)\n\n output_predict_file = os.path.join(FLAGS.output_dir, \"test_results.tsv\")\n with tf.gfile.GFile(output_predict_file, \"w\") as writer:\n num_written_lines = 0\n tf.logging.info(\"***** Predict results *****\")\n for (i, prediction) in enumerate(result):\n probabilities = prediction[\"probabilities\"]\n if i >= num_actual_predict_examples:\n break\n output_line = \"\\t\".join(\n str(class_probability)\n for class_probability in probabilities) + \"\\n\"\n writer.write(output_line)\n num_written_lines += 1\n assert num_written_lines == num_actual_predict_examples\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"data_dir\")\n flags.mark_flag_as_required(\"task_name\")\n flags.mark_flag_as_required(\"vocab_file\")\n flags.mark_flag_as_required(\"bert_config_file\")\n flags.mark_flag_as_required(\"output_dir\")\n tf.app.run()\n"
] |
[
[
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.metrics.accuracy",
"tensorflow.FixedLenFeature",
"tensorflow.nn.log_softmax",
"tensorflow.reduce_sum",
"tensorflow.gfile.GFile",
"tensorflow.cast",
"tensorflow.train.init_from_checkpoint",
"tensorflow.gfile.MakeDirs",
"tensorflow.to_int32",
"tensorflow.contrib.tpu.TPUEstimatorSpec",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.data.TFRecordDataset",
"tensorflow.truncated_normal_initializer",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.logging.set_verbosity",
"tensorflow.trainable_variables",
"tensorflow.parse_single_example",
"tensorflow.argmax",
"tensorflow.app.run",
"tensorflow.nn.dropout",
"tensorflow.metrics.mean",
"tensorflow.matmul",
"tensorflow.gfile.Open",
"tensorflow.shape",
"tensorflow.zeros_initializer",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.train.Features",
"tensorflow.nn.bias_add",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.train.Scaffold",
"tensorflow.reduce_mean",
"tensorflow.flags.DEFINE_string",
"tensorflow.variable_scope"
]
] |
amjal/Smart-Irrigation-using-Reinforcement-Learning
|
[
"efa8c8adf42cdeaab77e1107a02015a62bb38f04"
] |
[
"ElementaryRLAgent.py"
] |
[
"import numpy\nimport random\nimport math\nimport copy\nimport requests\nimport time\n\n# TODO use heuristic in pick_random action\n\n\nclass Action:\n def __init__(self, intensity):\n self.intensity = int(intensity)\n\n def __eq__(self, other):\n return self.intensity == other.intensity\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __str__(self):\n return str(self.intensity)\n\n def __hash__(self):\n return hash(self.intensity)\n\n\nclass State:\n def __init__(self, moisture, season, time_of_day):\n self.moisture = numpy.round(moisture, 2)\n self.season = season\n self.time_of_day = int(time_of_day/60)\n\n def __eq__(self, other):\n return self.moisture == other.moisture and self.season == other.season and self.time_of_day == other.time_of_day\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __str__(self):\n return str(self.moisture)+\" \"+self.season+\" \"+str(self.time_of_day)\n\n def __hash__(self):\n return hash((self.moisture, self.time_of_day, self.season))\n\n\nclass Policy:\n state_action_values = {}\n\n # Epsilon is exploring probability\n # Gamma is discount factor\n # Alpha is learning weight\n def __init__(self, gamma, alpha, intensities, **kwargs):\n self.gamma = gamma\n self.alpha = alpha\n self.intensities = intensities\n self.epsilon = kwargs.get('epsilon', 1)\n # Optimism value says what value to assume for our next state when it's an unknown state with empty actions\n self.optimism_value = kwargs.get('optimism_value', 0)\n # heuristic tells something about the soil: If it's negative we are below moisture and if positive we are above\n self.heuristic = kwargs.get('heuristic', 0)\n # Exponential moving average of the delta rewards for exploitation. This is used increase epsilon\n # whenever necessary. And the reason that the initial value for exploitation is more than exploration is\n # that at first, we already have a high probability of exploration, and we don't want to stay in that state\n # until things go wrong and then go to exploitation. Instead, what we do here is that we gradually increase\n # the chance of exploitation and then if things go wrong with exploitation we go back to exploration\n self.exploit_delta_reward_EMA = 0.1\n # Exponential moving average of the delta rewards for exploration. This is used increase epsilon whenever necessary\n self.explore_delta_reward_EMA = 0\n self.reward_EMA = 0\n self.reward_EMV = 0\n # Initiate to 1 so we won't have division by zero\n self.exploration_iteration = 1\n self.exploit_better_count = 0\n\n def check_add_state(self, state):\n if state not in self.state_action_values:\n actions = {}\n for i in self.intensities:\n actions[Action(i)] = self.optimism_value\n self.state_action_values[state] = actions\n\n def mapper(self, state):\n actions = self.state_action_values[state]\n # with probability 1-epsilon, we will act greedily and exploit\n if random.random() > self.epsilon:\n action_to_take = max(actions, key=actions.get)\n explore_exploit = 'exploit'\n # with probability epsilon we will explore, meaning take a random action\n # In the process of picking an action randomly we will use heuristic\n else:\n action_to_take = self.pick_random_action()\n explore_exploit = 'explore'\n return action_to_take, explore_exploit\n\n def pick_random_action(self):\n # The smaller our action space, the more unbalanced the probability distribution of choosing an action randomly\n probabilistic_action_space_indices = numpy.random.exponential(\n math.log2(len(self.intensities))*(1-abs(self.heuristic)), 1000)\n # We don't want to have zero because that would cause index out of bounds in the case of negative heuristic\n probabilistic_action_space_indices += 0.0001\n probabilistic_action_space_indices = probabilistic_action_space_indices[\n probabilistic_action_space_indices < len(self.intensities)]\n if self.heuristic < 0:\n probabilistic_action_space_indices = len(self.intensities) - probabilistic_action_space_indices\n random_index = int(random.random()*len(probabilistic_action_space_indices))\n return Action(self.intensities[int(probabilistic_action_space_indices[random_index])])\n\n # Updates the Q-function, EMA, and epsilon according to action taken and reward received\n def value_updater(self, explore_exploit, reward, delta_reward, state, next_state, action_taken):\n diff = self.exploit_delta_reward_EMA - self.explore_delta_reward_EMA\n # If exploring has been showing more improving rewards for a long enough time then keep exploring\n if diff < 0:\n if self.exploit_better_count > 0:\n self.exploit_better_count = 0\n self.exploration_iteration = max(2, self.exploration_iteration-1)\n else:\n self.exploit_better_count += 1\n self.exploration_iteration = min(self.exploit_better_count+self.exploration_iteration, 2**30)\n # If I've been getting bad results for a long enough time exploiting, and not much change has been\n # made, regardless of value of delta_reward history for exploring, it might be a good idea to start\n # exploring again. Because unlike exploration, exploitation has a chance of getting stuck\n if reward < 0.95 and self.reward_EMA < 0.95 and abs(self.exploit_delta_reward_EMA) < self.alpha*0.1:\n # Set exploration iteration so that epsilon becomes 0.5\n self.exploration_iteration = len(self.intensities)**2\n # Also enhance the histories so that a reset is actually done\n self.exploit_delta_reward_EMA = copy.copy(self.alpha)\n self.explore_delta_reward_EMA = copy.copy(self.alpha)\n if explore_exploit == 'explore':\n self.explore_delta_reward_EMA = self.alpha * delta_reward + (1 - self.alpha) * self.explore_delta_reward_EMA\n elif explore_exploit == 'exploit':\n self.exploit_delta_reward_EMA = self.alpha * delta_reward + (1 - self.alpha) * self.exploit_delta_reward_EMA\n # The speed of transition from initial exploration to exploitation depends on the size of action space\n self.epsilon = math.log2(len(self.intensities))/math.log2(self.exploration_iteration)\n self.reward_EMV = (1 - self.alpha) * (self.reward_EMV + self.alpha * (delta_reward - self.reward_EMA) ** 2)\n self.reward_EMA = (1-self.alpha)*self.reward_EMA + self.alpha*reward\n # In this algorithm, instead of sum of all possible next state values, a sample is taken\n max_value_of_next_state = max(self.state_action_values[next_state].values())\n self.state_action_values[state][action_taken] += self.alpha*(reward +\n self.gamma*max_value_of_next_state - self.state_action_values[state][action_taken])\n\n def __str__(self):\n out_str = \"\"\n for state, actions in self.state_action_values.items():\n out_str += \"state \"+str(state)+\":\\n\"\n for action, value in actions.items():\n out_str += \"\\tintensity \"+str(action)+\" :\"+str(value)+'\\n'\n return out_str\n\n\nclass Agent:\n\n def __init__(self, t, policy, min_moisture, max_moisture, measures, url):\n self.time = t\n self.policy = policy\n self.min_moisture = min_moisture\n self.max_moisture = max_moisture\n self.learning_iteration = 0\n self.state = State(numpy.mean(measures), self.time.season, self.time.time_of_day)\n self.policy.check_add_state(self.state)\n # These two are made properties of the Agent class for debugging reasons\n self.action_to_take = numpy.nan\n self.measures = measures\n self.reward = 0\n self.url = url\n\n def Q_learning_iteration(self):\n # Choose action\n self.action_to_take, explore_exploit = self.policy.mapper(self.state)\n # Take action\n requests.get(self.url, params={'action_to_take': self.action_to_take.intensity,\n 'is_watering': self.action_to_take.intensity > 0})\n # Wait for irrigation action to complete\n time.sleep(24*3600/self.time.day_time_limit)\n # Observe the impact of what we did on the world\n response = requests.get(self.url, params={'q': 'measures'})\n self.measures = []\n if response.status_code == 200:\n for m in response.json()['measures']:\n self.measures.append(m)\n reward, next_state = self.observer(self.action_to_take)\n # Update Q-function\n self.policy.value_updater(explore_exploit, reward, reward - self.reward,\n self.state, next_state, self.action_to_take)\n self.reward = reward\n # state is never assigned to anything so there's no need for copying\n self.state = next_state\n self.learning_iteration += 1\n\n def observer(self, action_taken):\n mean_moisture = numpy.mean(self.measures)\n next_state = State(mean_moisture, self.time.season, self.time.time_of_day)\n self.policy.check_add_state(next_state)\n if mean_moisture < self.min_moisture:\n reward = 1 - self.min_moisture + mean_moisture\n self.policy.heuristic = mean_moisture - self.min_moisture\n elif mean_moisture > self.max_moisture:\n reward = 1 - mean_moisture + self.max_moisture\n self.policy.heuristic = mean_moisture - self.max_moisture\n else:\n reward = 2 - action_taken.intensity/max(self.policy.intensities)\n self.policy.heuristic = 0\n return reward, next_state\n\n"
] |
[
[
"numpy.round",
"numpy.mean"
]
] |
june6723/sumo-rl-offset
|
[
"775cddc8d168fb7c4959610a96a791d746fa0afd"
] |
[
"experiments/DDPG_offset.py"
] |
[
"import argparse\nimport os\nimport sys\nif 'SUMO_HOME' in os.environ:\n tools = os.path.join(os.environ['SUMO_HOME'], 'tools')\n sys.path.append(tools)\nelse:\n sys.exit(\"Please declare the environment variable 'SUMO_HOME'\")\nimport pandas as pd\nimport ray\nfrom ray.rllib.agents.ddpg.ddpg import DDPGTrainer\nfrom ray.rllib.agents.ddpg.ddpg import DDPGTFPolicy\nfrom ray.tune.registry import register_env\nfrom ray.tune.logger import pretty_print\nfrom gym import spaces\nimport numpy as np\nfrom sumo_rl.environment.env import SumoEnvironment\nimport traci\n\ndef policy_mapping(id):\n # if id == 'gneJ00':\n # return 'gneJ00'\n # else:\n return 'offset_agent'\n\nif __name__ == '__main__':\n ray.init()\n\n register_env(\"2TLS\", lambda _: SumoEnvironment(net_file='/home/sonic/Desktop/sumo-rl-research-offset/sumo-rl-research/experiments/nets/Research/case04/intersection.net.xml',\n route_file='/home/sonic/Desktop/sumo-rl-research-offset/sumo-rl-research/experiments/nets/Research/case04/intersection.rou.xml',\n out_csv_path='outputs/case04/',\n out_csv_name='DDPG',\n use_gui=False,\n num_seconds=12240612,\n time_to_load_vehicles=612,\n max_depart_delay=0)\n )\n\n trainer = DDPGTrainer(env=\"2TLS\", config={\n \"multiagent\": {\n \"policy_graphs\": {\n 'offset_agent': (DDPGTFPolicy, spaces.Box(low=np.zeros(2), high=np.array(['inf']*2)), spaces.Box(low=np.array([0,0]), high=np.array([+1,+1])), {})\n },\n \"policy_mapping_fn\": policy_mapping # Traffic lights are always controlled by this policy\n },\n \"lr\": 0.0001,\n })\n \n while True:\n result = trainer.train()\n# /home/sonic/Desktop/sumo-rl-research-offset/sumo-rl-research/experiments/"
] |
[
[
"numpy.array",
"numpy.zeros"
]
] |
eliberis/tensorpack
|
[
"f6313a070bca9bff0e6a2760a395b6b2ab7c4a3d"
] |
[
"examples/FasterRCNN/data.py"
] |
[
"# -*- coding: utf-8 -*-\n# File: data.py\n\nimport copy\nimport itertools\nimport numpy as np\nimport cv2\nfrom tabulate import tabulate\nfrom termcolor import colored\n\nfrom tensorpack.dataflow import (\n DataFromList, MapData, MapDataComponent, MultiProcessMapDataZMQ, MultiThreadMapData,\n TestDataSpeed, imgaug)\nfrom tensorpack.utils import logger\nfrom tensorpack.utils.argtools import log_once, memoized\n\nfrom common import (\n CustomResize, DataFromListOfDict, box_to_point8, filter_boxes_inside_shape, np_iou,\n point8_to_box, segmentation_to_mask)\nfrom config import config as cfg\nfrom dataset import DatasetRegistry\nfrom utils.generate_anchors import generate_anchors\nfrom utils.np_box_ops import area as np_area\nfrom utils.np_box_ops import ioa as np_ioa\n\n# import tensorpack.utils.viz as tpviz\n\n\nclass MalformedData(BaseException):\n pass\n\n\ndef print_class_histogram(roidbs):\n \"\"\"\n Args:\n roidbs (list[dict]): the same format as the output of `training_roidbs`.\n \"\"\"\n # labels are in [1, NUM_CATEGORY], hence +2 for bins\n hist_bins = np.arange(cfg.DATA.NUM_CATEGORY + 2)\n\n # Histogram of ground-truth objects\n gt_hist = np.zeros((cfg.DATA.NUM_CATEGORY + 1,), dtype=np.int)\n for entry in roidbs:\n # filter crowd?\n gt_inds = np.where(\n (entry['class'] > 0) & (entry['is_crowd'] == 0))[0]\n gt_classes = entry['class'][gt_inds]\n gt_hist += np.histogram(gt_classes, bins=hist_bins)[0]\n data = [[cfg.DATA.CLASS_NAMES[i], v] for i, v in enumerate(gt_hist)]\n data.append(['total', sum(x[1] for x in data)])\n # the first line is BG\n table = tabulate(data[1:], headers=['class', '#box'], tablefmt='pipe')\n logger.info(\"Ground-Truth Boxes:\\n\" + colored(table, 'cyan'))\n\n\n@memoized\ndef get_all_anchors(*, stride, sizes, ratios, max_size):\n \"\"\"\n Get all anchors in the largest possible image, shifted, floatbox\n Args:\n stride (int): the stride of anchors.\n sizes (tuple[int]): the sizes (sqrt area) of anchors\n ratios (tuple[int]): the aspect ratios of anchors\n max_size (int): maximum size of input image\n\n Returns:\n anchors: SxSxNUM_ANCHORx4, where S == ceil(MAX_SIZE/STRIDE), floatbox\n The layout in the NUM_ANCHOR dim is NUM_RATIO x NUM_SIZE.\n\n \"\"\"\n # Generates a NAx4 matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors\n # are centered on stride / 2, have (approximate) sqrt areas of the specified\n # sizes, and aspect ratios as given.\n cell_anchors = generate_anchors(\n stride,\n scales=np.array(sizes, dtype=np.float) / stride,\n ratios=np.array(ratios, dtype=np.float))\n # anchors are intbox here.\n # anchors at featuremap [0,0] are centered at fpcoor (8,8) (half of stride)\n\n field_size = int(np.ceil(max_size / stride))\n shifts = np.arange(0, field_size) * stride\n shift_x, shift_y = np.meshgrid(shifts, shifts)\n shift_x = shift_x.flatten()\n shift_y = shift_y.flatten()\n shifts = np.vstack((shift_x, shift_y, shift_x, shift_y)).transpose()\n # Kx4, K = field_size * field_size\n K = shifts.shape[0]\n\n A = cell_anchors.shape[0]\n field_of_anchors = (\n cell_anchors.reshape((1, A, 4)) +\n shifts.reshape((1, K, 4)).transpose((1, 0, 2)))\n field_of_anchors = field_of_anchors.reshape((field_size, field_size, A, 4))\n # FSxFSxAx4\n # Many rounding happens inside the anchor code anyway\n # assert np.all(field_of_anchors == field_of_anchors.astype('int32'))\n field_of_anchors = field_of_anchors.astype('float32')\n field_of_anchors[:, :, :, [2, 3]] += 1\n return field_of_anchors\n\n\n@memoized\ndef get_all_anchors_fpn(*, strides, sizes, ratios, max_size):\n \"\"\"\n Returns:\n [anchors]: each anchors is a SxSx NUM_ANCHOR_RATIOS x4 array.\n \"\"\"\n assert len(strides) == len(sizes)\n foas = []\n for stride, size in zip(strides, sizes):\n foa = get_all_anchors(stride=stride, sizes=(size,), ratios=ratios, max_size=max_size)\n foas.append(foa)\n return foas\n\n\nclass TrainingDataPreprocessor:\n \"\"\"\n The mapper to preprocess the input data for training.\n\n Since the mapping may run in other processes, we write a new class and\n explicitly pass cfg to it, in the spirit of \"explicitly pass resources to subprocess\".\n \"\"\"\n def __init__(self, cfg):\n self.cfg = cfg\n self.aug = imgaug.AugmentorList(\n [CustomResize(cfg.PREPROC.TRAIN_SHORT_EDGE_SIZE, cfg.PREPROC.MAX_SIZE),\n imgaug.Flip(horiz=True)])\n\n def __call__(self, roidb):\n fname, boxes, klass, is_crowd = roidb['file_name'], roidb['boxes'], roidb['class'], roidb['is_crowd']\n boxes = np.copy(boxes)\n im = cv2.imread(fname, cv2.IMREAD_COLOR)\n assert im is not None, fname\n im = im.astype('float32')\n height, width = im.shape[:2]\n # assume floatbox as input\n assert boxes.dtype == np.float32, \"Loader has to return floating point boxes!\"\n\n if not self.cfg.DATA.ABSOLUTE_COORD:\n boxes[:, 0::2] *= width\n boxes[:, 1::2] *= height\n\n # augmentation:\n im, params = self.aug.augment_return_params(im)\n points = box_to_point8(boxes)\n points = self.aug.augment_coords(points, params)\n boxes = point8_to_box(points)\n assert np.min(np_area(boxes)) > 0, \"Some boxes have zero area!\"\n\n ret = {'image': im}\n # Add rpn data to dataflow:\n try:\n if self.cfg.MODE_FPN:\n multilevel_anchor_inputs = self.get_multilevel_rpn_anchor_input(im, boxes, is_crowd)\n for i, (anchor_labels, anchor_boxes) in enumerate(multilevel_anchor_inputs):\n ret['anchor_labels_lvl{}'.format(i + 2)] = anchor_labels\n ret['anchor_boxes_lvl{}'.format(i + 2)] = anchor_boxes\n else:\n ret['anchor_labels'], ret['anchor_boxes'] = self.get_rpn_anchor_input(im, boxes, is_crowd)\n\n boxes = boxes[is_crowd == 0] # skip crowd boxes in training target\n klass = klass[is_crowd == 0]\n ret['gt_boxes'] = boxes\n ret['gt_labels'] = klass\n if not len(boxes):\n raise MalformedData(\"No valid gt_boxes!\")\n except MalformedData as e:\n log_once(\"Input {} is filtered for training: {}\".format(fname, str(e)), 'warn')\n return None\n\n if self.cfg.MODE_MASK:\n # augmentation will modify the polys in-place\n segmentation = copy.deepcopy(roidb['segmentation'])\n segmentation = [segmentation[k] for k in range(len(segmentation)) if not is_crowd[k]]\n assert len(segmentation) == len(boxes)\n\n # Apply augmentation on polygon coordinates.\n # And produce one image-sized binary mask per box.\n masks = []\n width_height = np.asarray([width, height], dtype=np.float32)\n for polys in segmentation:\n if not self.cfg.DATA.ABSOLUTE_COORD:\n polys = [p * width_height for p in polys]\n polys = [self.aug.augment_coords(p, params) for p in polys]\n masks.append(segmentation_to_mask(polys, im.shape[0], im.shape[1]))\n masks = np.asarray(masks, dtype='uint8') # values in {0, 1}\n ret['gt_masks'] = masks\n\n # from viz import draw_annotation, draw_mask\n # viz = draw_annotation(im, boxes, klass)\n # for mask in masks:\n # viz = draw_mask(viz, mask)\n # tpviz.interactive_imshow(viz)\n return ret\n\n def get_rpn_anchor_input(self, im, boxes, is_crowd):\n \"\"\"\n Args:\n im: an image\n boxes: nx4, floatbox, gt. shoudn't be changed\n is_crowd: n,\n\n Returns:\n The anchor labels and target boxes for each pixel in the featuremap.\n fm_labels: fHxfWxNA\n fm_boxes: fHxfWxNAx4\n NA will be NUM_ANCHOR_SIZES x NUM_ANCHOR_RATIOS\n \"\"\"\n boxes = boxes.copy()\n all_anchors = np.copy(get_all_anchors(\n stride=self.cfg.RPN.ANCHOR_STRIDE,\n sizes=self.cfg.RPN.ANCHOR_SIZES,\n ratios=self.cfg.RPN.ANCHOR_RATIOS,\n max_size=self.cfg.PREPROC.MAX_SIZE))\n # fHxfWxAx4 -> (-1, 4)\n featuremap_anchors_flatten = all_anchors.reshape((-1, 4))\n\n # only use anchors inside the image\n inside_ind, inside_anchors = filter_boxes_inside_shape(featuremap_anchors_flatten, im.shape[:2])\n # obtain anchor labels and their corresponding gt boxes\n anchor_labels, anchor_gt_boxes = self.get_anchor_labels(\n inside_anchors, boxes[is_crowd == 0], boxes[is_crowd == 1])\n\n # Fill them back to original size: fHxfWx1, fHxfWx4\n num_anchor = self.cfg.RPN.NUM_ANCHOR\n anchorH, anchorW = all_anchors.shape[:2]\n featuremap_labels = -np.ones((anchorH * anchorW * num_anchor, ), dtype='int32')\n featuremap_labels[inside_ind] = anchor_labels\n featuremap_labels = featuremap_labels.reshape((anchorH, anchorW, num_anchor))\n featuremap_boxes = np.zeros((anchorH * anchorW * num_anchor, 4), dtype='float32')\n featuremap_boxes[inside_ind, :] = anchor_gt_boxes\n featuremap_boxes = featuremap_boxes.reshape((anchorH, anchorW, num_anchor, 4))\n return featuremap_labels, featuremap_boxes\n\n def get_multilevel_rpn_anchor_input(self, im, boxes, is_crowd):\n \"\"\"\n Args:\n im: an image\n boxes: nx4, floatbox, gt. shoudn't be changed\n is_crowd: n,\n\n Returns:\n [(fm_labels, fm_boxes)]: Returns a tuple for each FPN level.\n Each tuple contains the anchor labels and target boxes for each pixel in the featuremap.\n\n fm_labels: fHxfWx NUM_ANCHOR_RATIOS\n fm_boxes: fHxfWx NUM_ANCHOR_RATIOS x4\n \"\"\"\n boxes = boxes.copy()\n anchors_per_level = get_all_anchors_fpn(\n strides=self.cfg.FPN.ANCHOR_STRIDES,\n sizes=self.cfg.RPN.ANCHOR_SIZES,\n ratios=self.cfg.RPN.ANCHOR_RATIOS,\n max_size=self.cfg.PREPROC.MAX_SIZE)\n flatten_anchors_per_level = [k.reshape((-1, 4)) for k in anchors_per_level]\n all_anchors_flatten = np.concatenate(flatten_anchors_per_level, axis=0)\n\n inside_ind, inside_anchors = filter_boxes_inside_shape(all_anchors_flatten, im.shape[:2])\n anchor_labels, anchor_gt_boxes = self.get_anchor_labels(\n inside_anchors, boxes[is_crowd == 0], boxes[is_crowd == 1])\n\n # map back to all_anchors, then split to each level\n num_all_anchors = all_anchors_flatten.shape[0]\n all_labels = -np.ones((num_all_anchors, ), dtype='int32')\n all_labels[inside_ind] = anchor_labels\n all_boxes = np.zeros((num_all_anchors, 4), dtype='float32')\n all_boxes[inside_ind] = anchor_gt_boxes\n\n start = 0\n multilevel_inputs = []\n for level_anchor in anchors_per_level:\n assert level_anchor.shape[2] == len(self.cfg.RPN.ANCHOR_RATIOS)\n anchor_shape = level_anchor.shape[:3] # fHxfWxNUM_ANCHOR_RATIOS\n num_anchor_this_level = np.prod(anchor_shape)\n end = start + num_anchor_this_level\n multilevel_inputs.append(\n (all_labels[start: end].reshape(anchor_shape),\n all_boxes[start: end, :].reshape(anchor_shape + (4,))\n ))\n start = end\n assert end == num_all_anchors, \"{} != {}\".format(end, num_all_anchors)\n return multilevel_inputs\n\n def get_anchor_labels(self, anchors, gt_boxes, crowd_boxes):\n \"\"\"\n Label each anchor as fg/bg/ignore.\n Args:\n anchors: Ax4 float\n gt_boxes: Bx4 float, non-crowd\n crowd_boxes: Cx4 float\n\n Returns:\n anchor_labels: (A,) int. Each element is {-1, 0, 1}\n anchor_boxes: Ax4. Contains the target gt_box for each anchor when the anchor is fg.\n \"\"\"\n # This function will modify labels and return the filtered inds\n def filter_box_label(labels, value, max_num):\n curr_inds = np.where(labels == value)[0]\n if len(curr_inds) > max_num:\n disable_inds = np.random.choice(\n curr_inds, size=(len(curr_inds) - max_num),\n replace=False)\n labels[disable_inds] = -1 # ignore them\n curr_inds = np.where(labels == value)[0]\n return curr_inds\n\n NA, NB = len(anchors), len(gt_boxes)\n assert NB > 0 # empty images should have been filtered already\n box_ious = np_iou(anchors, gt_boxes) # NA x NB\n ious_argmax_per_anchor = box_ious.argmax(axis=1) # NA,\n ious_max_per_anchor = box_ious.max(axis=1)\n ious_max_per_gt = np.amax(box_ious, axis=0, keepdims=True) # 1xNB\n # for each gt, find all those anchors (including ties) that has the max ious with it\n anchors_with_max_iou_per_gt = np.where(box_ious == ious_max_per_gt)[0]\n\n # Setting NA labels: 1--fg 0--bg -1--ignore\n anchor_labels = -np.ones((NA,), dtype='int32') # NA,\n\n # the order of setting neg/pos labels matter\n anchor_labels[anchors_with_max_iou_per_gt] = 1\n anchor_labels[ious_max_per_anchor >= self.cfg.RPN.POSITIVE_ANCHOR_THRESH] = 1\n anchor_labels[ious_max_per_anchor < self.cfg.RPN.NEGATIVE_ANCHOR_THRESH] = 0\n\n # label all non-ignore candidate boxes which overlap crowd as ignore\n if crowd_boxes.size > 0:\n cand_inds = np.where(anchor_labels >= 0)[0]\n cand_anchors = anchors[cand_inds]\n ioas = np_ioa(crowd_boxes, cand_anchors)\n overlap_with_crowd = cand_inds[ioas.max(axis=0) > self.cfg.RPN.CROWD_OVERLAP_THRESH]\n anchor_labels[overlap_with_crowd] = -1\n\n # Subsample fg labels: ignore some fg if fg is too many\n target_num_fg = int(self.cfg.RPN.BATCH_PER_IM * self.cfg.RPN.FG_RATIO)\n fg_inds = filter_box_label(anchor_labels, 1, target_num_fg)\n # Keep an image even if there is no foreground anchors\n # if len(fg_inds) == 0:\n # raise MalformedData(\"No valid foreground for RPN!\")\n\n # Subsample bg labels. num_bg is not allowed to be too many\n old_num_bg = np.sum(anchor_labels == 0)\n if old_num_bg == 0:\n # No valid bg in this image, skip.\n raise MalformedData(\"No valid background for RPN!\")\n target_num_bg = self.cfg.RPN.BATCH_PER_IM - len(fg_inds)\n filter_box_label(anchor_labels, 0, target_num_bg) # ignore return values\n\n # Set anchor boxes: the best gt_box for each fg anchor\n anchor_boxes = np.zeros((NA, 4), dtype='float32')\n fg_boxes = gt_boxes[ious_argmax_per_anchor[fg_inds], :]\n anchor_boxes[fg_inds, :] = fg_boxes\n # assert len(fg_inds) + np.sum(anchor_labels == 0) == self.cfg.RPN.BATCH_PER_IM\n return anchor_labels, anchor_boxes\n\n\ndef get_train_dataflow():\n \"\"\"\n Return a training dataflow. Each datapoint consists of the following:\n\n An image: (h, w, 3),\n\n 1 or more pairs of (anchor_labels, anchor_boxes):\n anchor_labels: (h', w', NA)\n anchor_boxes: (h', w', NA, 4)\n\n gt_boxes: (N, 4)\n gt_labels: (N,)\n\n If MODE_MASK, gt_masks: (N, h, w)\n \"\"\"\n\n roidbs = list(itertools.chain.from_iterable(DatasetRegistry.get(x).training_roidbs() for x in cfg.DATA.TRAIN))\n print_class_histogram(roidbs)\n\n # Valid training images should have at least one fg box.\n # But this filter shall not be applied for testing.\n num = len(roidbs)\n roidbs = list(filter(lambda img: len(img['boxes'][img['is_crowd'] == 0]) > 0, roidbs))\n logger.info(\"Filtered {} images which contain no non-crowd groudtruth boxes. Total #images for training: {}\".format(\n num - len(roidbs), len(roidbs)))\n\n ds = DataFromList(roidbs, shuffle=True)\n\n preprocess = TrainingDataPreprocessor(cfg)\n\n if cfg.DATA.NUM_WORKERS > 0:\n if cfg.TRAINER == 'horovod':\n buffer_size = cfg.DATA.NUM_WORKERS * 10 # one dataflow for each process, therefore don't need large buffer\n ds = MultiThreadMapData(ds, cfg.DATA.NUM_WORKERS, preprocess, buffer_size=buffer_size)\n # MPI does not like fork()\n else:\n buffer_size = cfg.DATA.NUM_WORKERS * 20\n ds = MultiProcessMapDataZMQ(ds, cfg.DATA.NUM_WORKERS, preprocess, buffer_size=buffer_size)\n else:\n ds = MapData(ds, preprocess)\n return ds\n\n\ndef get_eval_dataflow(name, shard=0, num_shards=1):\n \"\"\"\n Args:\n name (str): name of the dataset to evaluate\n shard, num_shards: to get subset of evaluation data\n \"\"\"\n roidbs = DatasetRegistry.get(name).inference_roidbs()\n logger.info(\"Found {} images for inference.\".format(len(roidbs)))\n\n num_imgs = len(roidbs)\n img_per_shard = num_imgs // num_shards\n img_range = (shard * img_per_shard, (shard + 1) * img_per_shard if shard + 1 < num_shards else num_imgs)\n\n # no filter for training\n ds = DataFromListOfDict(roidbs[img_range[0]: img_range[1]], ['file_name', 'image_id'])\n\n def f(fname):\n im = cv2.imread(fname, cv2.IMREAD_COLOR)\n assert im is not None, fname\n return im\n ds = MapDataComponent(ds, f, 0)\n # Evaluation itself may be multi-threaded, therefore don't add prefetch here.\n return ds\n\n\nif __name__ == '__main__':\n import os\n from tensorpack.dataflow import PrintData\n cfg.DATA.BASEDIR = os.path.expanduser('~/data/coco')\n ds = get_train_dataflow()\n ds = PrintData(ds, 100)\n TestDataSpeed(ds, 50000).start()\n ds.reset_state()\n for k in ds:\n pass\n"
] |
[
[
"numpy.amax",
"numpy.histogram",
"numpy.asarray",
"numpy.arange",
"numpy.ones",
"numpy.concatenate",
"numpy.ceil",
"numpy.copy",
"numpy.where",
"numpy.prod",
"numpy.array",
"numpy.meshgrid",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
]
] |
luochuankai-JHU/ndmg
|
[
"1307cc4dbaf84e33d61b13a6f83f9bcc4e5cfad6"
] |
[
"ndmg/utils/gen_utils.py"
] |
[
"# !/usr/bin/env python\n\n# Copyright 2016 NeuroData (http://neurodata.io)\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# gen_utils.py\n# Created by Will Gray Roncal on 2016-01-28.\n# Email: [email protected]\n# Edited by Eric Bridgeford.\n\nimport warnings\n\nwarnings.simplefilter(\"ignore\")\nfrom dipy.io import read_bvals_bvecs\nfrom dipy.core.gradients import gradient_table\nfrom subprocess import Popen, PIPE\nimport subprocess\nimport numpy as np\nimport nibabel as nib\nimport os\nimport os.path as op\nimport sys\nfrom nilearn.image import mean_img\nfrom scipy.sparse import lil_matrix\n\n\ndef check_dependencies():\n \"\"\"\n Check for the existence of FSL and AFNI.\n Stop the pipeline immediately if these dependencies are not installed.\n\n Raises\n ------\n AssertionError\n Raised if FSL is not installed.\n AssertionError\n Raised if AFNI is not installed.\n \"\"\"\n\n # Check for python version\n print(\"Python location : {}\".format(sys.executable))\n print(\"Python version : {}\".format(sys.version))\n if sys.version_info[0] < 3:\n warnings.warn(\n \"WARNING : Using python 2. This Python version is no longer maintained. Use at your own risk.\"\n )\n\n # Check FSL installation\n try:\n print(f\"Your fsl directory is located here: {os.environ['FSLDIR']}\")\n except KeyError:\n raise AssertionError(\n \"You do not have FSL installed! See installation instructions here: https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FslInstallation\"\n )\n\n # Check AFNI installation\n try:\n print(\n f\"Your AFNI directory is located here: {subprocess.check_output('which afni', shell=True, universal_newlines=True)}\"\n )\n except subprocess.CalledProcessError:\n raise AssertionError(\n \"You do not have AFNI installed! See installation instructions here: https://afni.nimh.nih.gov/pub/dist/doc/htmldoc/background_install/main_toc.html\"\n )\n\n\ndef show_template_bundles(final_streamlines, template_path, fname):\n \"\"\"Displayes the template bundles\n \n Parameters\n ----------\n final_streamlines : list\n Generated streamlines\n template_path : str\n Path to reference FA nii.gz file\n fname : str\n Path of the output file (saved as )\n \"\"\"\n import nibabel as nib\n from fury import actor, window\n\n renderer = window.Renderer()\n template_img_data = nib.load(template_path).get_data().astype(\"bool\")\n template_actor = actor.contour_from_roi(\n template_img_data, color=(50, 50, 50), opacity=0.05\n )\n renderer.add(template_actor)\n lines_actor = actor.streamtube(\n final_streamlines, window.colors.orange, linewidth=0.3\n )\n renderer.add(lines_actor)\n window.record(renderer, n_frames=1, out_path=fname, size=(900, 900))\n return\n\n\ndef execute_cmd(cmd, verb=False):\n \"\"\"\n Given a bash command, it is executed and the response piped back to the\n calling script\n \"\"\"\n if verb:\n print(\"Executing: {}\".format(cmd))\n\n p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)\n out, err = p.communicate()\n code = p.returncode\n if code:\n sys.exit(\"Error {}: {}\".format(code, err))\n return out, err\n\n\ndef name_tmps(basedir, basename, extension):\n return \"{}/tmp/{}{}\".format(basedir, basename, extension)\n\n\ndef get_braindata(brain_file):\n \"\"\"\n Opens a brain data series for a mask, mri image, or atlas.\n Returns a numpy.ndarray representation of a brain.\n **Positional Arguements**\n brain_file:\n - an object to open the data for a brain.\n Can be a string (path to a brain file),\n nibabel.nifti1.nifti1image, or a numpy.ndarray\n \"\"\"\n if type(brain_file) is np.ndarray: # if brain passed as matrix\n braindata = brain_file\n else:\n if type(brain_file) is str or type(brain_file) is str:\n brain = nib.load(str(brain_file))\n elif type(brain_file) is nib.nifti1.Nifti1Image:\n brain = brain_file\n else:\n raise TypeError(\n \"Brain file is type: {}\".format(type(brain_file))\n + \"; accepted types are numpy.ndarray, \"\n \"string, and nibabel.nifti1.Nifti1Image.\"\n )\n braindata = brain.get_data()\n return braindata\n\n\ndef get_filename(label):\n \"\"\"\n Given a fully qualified path gets just the file name, without extension\n \"\"\"\n return op.splitext(op.splitext(op.basename(label))[0])[0]\n\n\ndef get_slice(mri, volid, sli):\n \"\"\"\n Takes a volume index and constructs a new nifti image from\n the specified volume.\n **Positional Arguments:**\n mri:\n - the path to a 4d mri volume to extract a slice from.\n volid:\n - the index of the volume desired.\n sli:\n - the path to the destination for the slice.\n \"\"\"\n mri_im = nib.load(mri)\n data = mri_im.get_data()\n # get the slice at the desired volume\n vol = np.squeeze(data[:, :, :, volid])\n\n # Wraps volume in new nifti image\n head = mri_im.get_header()\n head.set_data_shape(head.get_data_shape()[0:3])\n out = nib.Nifti1Image(vol, affine=mri_im.get_affine(), header=head)\n out.update_header()\n # and saved to a new file\n nib.save(out, sli)\n\n\ndef make_gtab_and_bmask(fbval, fbvec, dwi_file, outdir):\n \"\"\"Takes bval and bvec files and produces a structure in dipy format while also using FSL commands\n \n Parameters\n ----------\n fbval : str\n b-value file\n fbvec : str\n b-vector file\n dwi_file : str\n dwi file being analyzed\n outdir : str\n output directory\n \n Returns\n -------\n GradientTable\n gradient table created from bval and bvec files\n str\n location of averaged b0 image file\n str\n location of b0 brain mask file\n \"\"\"\n\n # Use B0's from the DWI to create a more stable DWI image for registration\n nodif_B0 = \"{}/nodif_B0.nii.gz\".format(outdir)\n nodif_B0_bet = \"{}/nodif_B0_bet.nii.gz\".format(outdir)\n nodif_B0_mask = \"{}/nodif_B0_bet_mask.nii.gz\".format(outdir)\n\n # loading bvecs/bvals\n print(fbval)\n print(fbvec)\n bvals, bvecs = read_bvals_bvecs(fbval, fbvec)\n\n # Creating the gradient table\n gtab = gradient_table(bvals, bvecs, atol=1.0)\n\n # Correct b0 threshold\n gtab.b0_threshold = min(bvals)\n\n # Get B0 indices\n B0s = np.where(gtab.bvals == gtab.b0_threshold)[0]\n print(\"%s%s\" % (\"B0's found at: \", B0s))\n\n # Show info\n print(gtab.info)\n\n # Extract and Combine all B0s collected\n print(\"Extracting B0's...\")\n cmds = []\n B0s_bbr = []\n for B0 in B0s:\n print(B0)\n B0_bbr = \"{}/{}_B0.nii.gz\".format(outdir, str(B0))\n cmd = \"fslroi \" + dwi_file + \" \" + B0_bbr + \" \" + str(B0) + \" 1\"\n cmds.append(cmd)\n B0s_bbr.append(B0_bbr)\n\n for cmd in cmds:\n print(cmd)\n os.system(cmd)\n\n # Get mean B0\n B0s_bbr_imgs = []\n for B0 in B0s_bbr:\n B0s_bbr_imgs.append(nib.load(B0))\n\n mean_B0 = mean_img(B0s_bbr_imgs)\n nib.save(mean_B0, nodif_B0)\n\n # Get mean B0 brain mask\n cmd = \"bet \" + nodif_B0 + \" \" + nodif_B0_bet + \" -m -f 0.2\"\n os.system(cmd)\n return gtab, nodif_B0, nodif_B0_mask\n\n\ndef reorient_dwi(dwi_prep, bvecs, namer):\n \"\"\"Orients dwi data to the proper orientation (RAS+) using nibabel\n \n Parameters\n ----------\n dwi_prep : str\n Path to eddy corrected dwi file\n bvecs : str\n Path to the resaled b-vector file\n namer : name_resource\n name_resource variable containing relevant directory tree information\n \n Returns\n -------\n str\n Path to potentially reoriented dwi file\n str\n Path to b-vector file, potentially reoriented if dwi data was\n \"\"\"\n from ndmg.utils.reg_utils import normalize_xform\n\n fname = dwi_prep\n bvec_fname = bvecs\n out_bvec_fname = \"%s%s\" % (namer.dirs[\"output\"][\"prep_dwi\"], \"/bvecs_reor.bvec\")\n\n input_img = nib.load(fname)\n input_axcodes = nib.aff2axcodes(input_img.affine)\n reoriented = nib.as_closest_canonical(input_img)\n normalized = normalize_xform(reoriented)\n # Is the input image oriented how we want?\n new_axcodes = (\"R\", \"A\", \"S\")\n if normalized is not input_img:\n out_fname = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_dwi\"],\n \"/\",\n dwi_prep.split(\"/\")[-1].split(\".nii.gz\")[0],\n \"_reor_RAS.nii.gz\",\n )\n print(\"%s%s%s\" % (\"Reorienting \", dwi_prep, \" to RAS+...\"))\n\n # Flip the bvecs\n input_orientation = nib.orientations.axcodes2ornt(input_axcodes)\n desired_orientation = nib.orientations.axcodes2ornt(new_axcodes)\n transform_orientation = nib.orientations.ornt_transform(\n input_orientation, desired_orientation\n )\n bvec_array = np.loadtxt(bvec_fname)\n if bvec_array.shape[0] != 3:\n bvec_array = bvec_array.T\n if not bvec_array.shape[0] == transform_orientation.shape[0]:\n raise ValueError(\"Unrecognized bvec format\")\n output_array = np.zeros_like(bvec_array)\n for this_axnum, (axnum, flip) in enumerate(transform_orientation):\n output_array[this_axnum] = bvec_array[int(axnum)] * float(flip)\n np.savetxt(out_bvec_fname, output_array, fmt=\"%.8f \")\n else:\n out_fname = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_dwi\"],\n \"/\",\n dwi_prep.split(\"/\")[-1].split(\".nii.gz\")[0],\n \"_RAS.nii.gz\",\n )\n out_bvec_fname = bvec_fname\n\n normalized.to_filename(out_fname)\n\n return out_fname, out_bvec_fname\n\n\ndef reorient_img(img, namer):\n \"\"\"Reorients input image to RAS+\n \n Parameters\n ----------\n img : str\n Path to image being reoriented\n namer : name_resource\n name_resource object containing all revlevent pathing information for the pipeline\n \n Returns\n -------\n str\n Path to reoriented image\n \"\"\"\n from ndmg.utils.reg_utils import normalize_xform\n\n # Load image, orient as RAS\n orig_img = nib.load(img)\n reoriented = nib.as_closest_canonical(orig_img)\n normalized = normalize_xform(reoriented)\n\n # Image may be reoriented\n if normalized is not orig_img:\n print(\"%s%s%s\" % (\"Reorienting \", img, \" to RAS+...\"))\n out_name = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_anat\"],\n \"/\",\n img.split(\"/\")[-1].split(\".nii.gz\")[0],\n \"_reor_RAS.nii.gz\",\n )\n else:\n out_name = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_anat\"],\n \"/\",\n img.split(\"/\")[-1].split(\".nii.gz\")[0],\n \"_RAS.nii.gz\",\n )\n\n normalized.to_filename(out_name)\n\n return out_name\n\n\ndef match_target_vox_res(img_file, vox_size, namer, sens):\n \"\"\"Reslices input MRI file if it does not match the targeted voxel resolution. Can take dwi or t1w scans.\n \n Parameters\n ----------\n img_file : str\n path to file to be resliced\n vox_size : str\n target voxel resolution ('2mm' or '1mm')\n namer : name_resource\n name_resource variable containing relevant directory tree information\n sens : str\n type of data being analyzed ('dwi' or 'func')\n \n Returns\n -------\n str\n location of potentially resliced image\n \"\"\"\n from dipy.align.reslice import reslice\n\n # Check dimensions\n img = nib.load(img_file)\n data = img.get_fdata()\n affine = img.affine\n hdr = img.header\n zooms = hdr.get_zooms()[:3]\n if vox_size == \"1mm\":\n new_zooms = (1.0, 1.0, 1.0)\n elif vox_size == \"2mm\":\n new_zooms = (2.0, 2.0, 2.0)\n\n if (abs(zooms[0]), abs(zooms[1]), abs(zooms[2])) != new_zooms:\n print(\"Reslicing image \" + img_file + \" to \" + vox_size + \"...\")\n if sens == \"dwi\":\n img_file_res = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_dwi\"],\n \"/\",\n os.path.basename(img_file).split(\".nii.gz\")[0],\n \"_res.nii.gz\",\n )\n elif sens == \"t1w\":\n img_file_res = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_anat\"],\n \"/\",\n os.path.basename(img_file).split(\".nii.gz\")[0],\n \"_res.nii.gz\",\n )\n\n data2, affine2 = reslice(data, affine, zooms, new_zooms)\n img2 = nib.Nifti1Image(data2, affine=affine2)\n nib.save(img2, img_file_res)\n img_file = img_file_res\n else:\n print(\"Reslicing image \" + img_file + \" to \" + vox_size + \"...\")\n if sens == \"dwi\":\n img_file_nores = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_dwi\"],\n \"/\",\n os.path.basename(img_file).split(\".nii.gz\")[0],\n \"_nores.nii.gz\",\n )\n elif sens == \"t1w\":\n img_file_nores = \"%s%s%s%s\" % (\n namer.dirs[\"output\"][\"prep_anat\"],\n \"/\",\n os.path.basename(img_file).split(\".nii.gz\")[0],\n \"_nores.nii.gz\",\n )\n nib.save(img, img_file_nores)\n img_file = img_file_nores\n\n return img_file\n\n\ndef load_timeseries(timeseries_file, ts=\"roi\"):\n \"\"\"\n A function to load timeseries data. Exists to standardize\n formatting in case changes are made with how timeseries are\n saved in future versions.\n **Positional Arguments**\n timeseries_file: the file to load timeseries data from.\n \"\"\"\n if (ts == \"roi\") or (ts == \"voxel\"):\n timeseries = np.load(timeseries_file)[\"roi\"]\n return timeseries\n else:\n print(\n \"You have not selected a valid timeseries type.\"\n + \"options are ts='roi' or ts='voxel'.\"\n )\n pass\n\n\ndef name_tmps(basedir, basename, extension):\n return \"{}/tmp/{}{}\".format(basedir, basename, extension)\n\n\ndef parcel_overlap(parcellation1, parcellation2, outpath):\n \"\"\"\n A function to compute the percent composition of each parcel in\n parcellation 1 with the parcels in parcellation 2. Rows are indices\n in parcellation 1; cols are parcels in parcellation 2. Values are the\n percent of voxels in parcel (parcellation 1) that fall into parcel\n (parcellation 2). Implied is that each row sums to 1.\n **Positional Arguments:**\n parcellation1:\n - the path to the first parcellation.\n parcellation2:\n - the path to the second parcellation.\n outpath:\n - the path to produce the output.\n \"\"\"\n p1_dat = nib.load(parcellation1).get_data()\n p2_dat = nib.load(parcellation2).get_data()\n p1regs = np.unique(p1_dat)\n p1regs = p1regs[p1regs > 0]\n p2regs = np.unique(p2_dat)\n\n p1n = get_filename(parcellation1)\n p2n = get_filename(parcellation2)\n\n overlapdat = lil_matrix((p1regs.shape[0], p2regs.shape[0]), dtype=np.float32)\n for p1idx, p1reg in enumerate(p1regs):\n p1seq = p1_dat == p1reg\n N = p1seq.sum()\n poss_regs = np.unique(p2_dat[p1seq])\n for p2idx, p2reg in enumerate(p2regs):\n if p2reg in poss_regs:\n # percent overlap is p1seq and'd with the anatomical region voxelspace, summed and normalized\n pover = np.logical_and(p1seq, p2_dat == p2reg).sum() / float(N)\n overlapdat[p1idx, p2idx] = pover\n\n outf = op.join(outpath, \"{}_{}.csv\".format(p1n, p2n))\n with open(outf, \"w\") as f:\n p2str = [\"%s\" % x for x in p2regs]\n f.write(\"p1reg,\" + \",\".join(p2str) + \"\\n\")\n for idx, p1reg in enumerate(p1regs):\n datstr = [\"%.4f\" % x for x in overlapdat[idx,].toarray()[0,]]\n f.write(str(p1reg) + \",\" + \",\".join(datstr) + \"\\n\")\n f.close()\n return\n"
] |
[
[
"numpy.unique",
"numpy.squeeze",
"numpy.zeros_like",
"numpy.savetxt",
"numpy.load",
"numpy.logical_and",
"numpy.where",
"numpy.loadtxt",
"scipy.sparse.lil_matrix"
]
] |
AngusGLChen/qg
|
[
"3ebc5b94348a4c313829a6c71705fbc9dadd8181"
] |
[
"process/triviaqa.py"
] |
[
"'''\nCreated on Sep 11, 2017\n\n@author: Angus\n'''\n\nimport sys\nreload(sys) \nsys.setdefaultencoding('utf8')\n\nimport numpy\nimport matplotlib.pyplot as plt;\nplt.rcdefaults()\n\nfrom nltk.tokenize import sent_tokenize\n\ndef plot(array):\n n, bins, patches = plt.hist(array) \n plt.show()\n\ndef analyze(file_path, word_set, line_set):\n word_length_array = []\n sentence_length_array = []\n \n with open(file_path, \"r\") as file:\n lines = file.readlines()\n print(\"# records is:\\t %s\" % len(lines))\n for line in lines: \n line_set.add(line)\n \n # Number of words / line\n words = line.strip().split()\n word_length = 0\n for word in words:\n if word != \"\":\n word_set.add(word)\n word_length += 1\n word_length_array.append(word_length)\n \n # Number of sentences / line\n try:\n sentences = sent_tokenize(line)\n except Exception as e:\n # print(e)\n sentences = line.split(\".\")\n sentence_length_array.append(len(sentences))\n \n '''\n # Distribution of DINSTINC lines \n for line in line_set:\n words = line.strip().split()\n word_length = 0\n for word in words:\n if word != \"\":\n word_set.add(word)\n word_length += 1\n word_length_array.append(word_length)\n '''\n \n print(\"Vocabulary size is:\\t %s\" % len(word_set))\n print(\"# DISTINCT lines is:\\t %s\" % len(line_set))\n \n print(\"\")\n \n print(\"Avg. length of lines is:\\t %.2f\" % numpy.average(word_length_array))\n print(\"Shortest line is:\\t %s\" % min(word_length_array))\n print(\"Longest line is:\\t %s\" % max(word_length_array))\n \n # plot(word_length_array)\n \n print(\"\")\n \n print(\"Avg. # sentences is:\\t %.2f\" % numpy.average(sentence_length_array))\n print(\"The minimum # of sentences is:\\t %s\" % min(sentence_length_array))\n print(\"The maximum # of sentences is:\\t %s\" % max(sentence_length_array))\n \n # plot(sentence_length_array)\n \n \ndef main():\n word_set = set()\n \n train_line_set = set()\n dev_line_set = set()\n test_line_set = set()\n \n file_path = \"../data/squad/data/processed/para-train.txt\"\n analyze(file_path, word_set, train_line_set)\n print(\"***********************************\")\n \n file_path = \"../data/squad/data/processed/para-dev.txt\"\n analyze(file_path, word_set, dev_line_set)\n print(\"***********************************\")\n \n file_path = \"../data/squad/data/processed/para-test.txt\"\n analyze(file_path, word_set, test_line_set)\n print(\"***********************************\")\n \n print(\"To check whether there is overlap between the training & validation paragraphs\")\n dev_overlap_line = 0\n for line in dev_line_set:\n if line in train_line_set:\n dev_overlap_line += 1\n print(\"# dev overlap lines is:\\t %s\" % dev_overlap_line)\n \n print(\"To check whether there is overlap between the training & validation & testing paragraphs\")\n test_overlap_line = 0\n for line in test_line_set:\n if line in train_line_set or line in dev_line_set:\n test_overlap_line += 1\n print(\"# test overlap lines is:\\t %s\" % test_overlap_line)\n \nif __name__ == \"__main__\":\n main()\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n"
] |
[
[
"matplotlib.pyplot.rcdefaults",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"numpy.average"
]
] |
Mrutyu-1/malaria-liver-detection
|
[
"23506faff252ee34c1d0acc4163ebf6b200ce2bf"
] |
[
"app.py"
] |
[
"#Important Modules\nfrom flask import Flask,render_template, url_for ,flash , redirect\n#from forms import RegistrationForm, LoginForm\n#from sklearn.externals import joblib\nimport joblib\nfrom flask import request\nimport numpy as np\nimport tensorflow\n#from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Input, Flatten, SeparableConv2D\n#from flask_sqlalchemy import SQLAlchemy\n#from model_class import DiabetesCheck, CancerCheck\n\n#from tensorflow.keras.models import Sequential\n#from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Input, Flatten, SeparableConv2D\n#from tensorflow.keras.layers import GlobalMaxPooling2D, Activation\n#from tensorflow.keras.layers.normalization import BatchNormalization\n#from tensorflow.keras.layers.merge import Concatenate\n#from tensorflow.keras.models import Model\n\nimport os\nfrom flask import send_from_directory\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\nimport tensorflow as tf\n\n#from this import SQLAlchemy\napp=Flask(__name__,template_folder='template')\n\n\napp.config[\"SERVER_NAME\"]='192.168.0.106:1000'\n\napp.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nUPLOAD_FOLDER = 'uploads'\nSTATIC_FOLDER = 'static'\n\n\nfrom tensorflow.keras.models import load_model\nmodel55 = load_model('model111.h5')\n\n#FOR THE FIRST MODEL\n\n# call model to predict an image\ndef api(full_path):\n data = image.load_img(full_path, target_size=(50, 50, 3))\n data = np.expand_dims(data, axis=0)\n data = data * 1.0 / 255\n\n #with graph.as_default():\n predicted = model55.predict(data)\n return predicted\n#FOR THE SECOND MODEL\n\n# home page\n\n#@app.route('/')\n#def home():\n # return render_template('index.html')\n\n\n# procesing uploaded file and predict it\[email protected]('/upload', methods=['POST','GET'])\ndef upload_file():\n\n if request.method == 'GET':\n return render_template('index.html')\n else:\n try:\n file = request.files['image']\n full_name = os.path.join(UPLOAD_FOLDER, file.filename)\n file.save(full_name)\n\n indices = {0: 'PARASITIC', 1: 'Uninfected', 2: 'Invasive carcinomar', 3: 'Normal'}\n result = api(full_name)\n print(result)\n\n predicted_class = np.asscalar(np.argmax(result, axis=1))\n accuracy = round(result[0][predicted_class] * 100, 2)\n label = indices[predicted_class]\n return render_template('predict.html', image_file_name = file.filename, label = label, accuracy = accuracy)\n except:\n flash(\"Please select the image first !!\", \"danger\") \n return redirect(url_for(\"Malaria\"))\n\n\n\n\[email protected]('/uploads/<filename>')\ndef send_file(filename):\n return send_from_directory(UPLOAD_FOLDER, filename)\n\n\n\[email protected](\"/\")\n\[email protected](\"/home\")\ndef home():\n return render_template(\"home.html\")\n \n\n\[email protected](\"/about\")\ndef about():\n return render_template(\"about.html\")\n\n\n\n\n\n\[email protected](\"/liver\")\ndef liver():\n \n return render_template(\"liver.html\")\[email protected](\"/Malaria\")\ndef Malaria():\n return render_template(\"malaria.html\")\n\n\n\n\n\n\ndef ValuePredictor(to_predict_list, size):\n to_predict = np.array(to_predict_list).reshape(1,size)\n \n if(size==10):#liver\n loaded_model = joblib.load(\"model4555\")\n result = loaded_model.predict(to_predict)\n \n return result[0]\n\[email protected]('/result',methods = [\"POST\"])\ndef result():\n if request.method == 'POST':\n to_predict_list = request.form.to_dict()\n to_predict_list=list(to_predict_list.values())\n to_predict_list = list(map(float, to_predict_list))\n \n \n if(len(to_predict_list)==10):\n result = ValuePredictor(to_predict_list,10)\n if(int(result)==1):\n prediction='Sorry ! Suffering'\n else:\n prediction='Congrats ! you are Healthy' \n return(render_template(\"result.html\", prediction=prediction))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n"
] |
[
[
"tensorflow.keras.models.load_model",
"numpy.expand_dims",
"tensorflow.keras.preprocessing.image.load_img",
"numpy.argmax",
"numpy.array"
]
] |
CristiFati/rknn-toolkit
|
[
"a345d99be30c1ca84f56dd68a213c740450eeaa5"
] |
[
"examples/pytorch/resnet18/test.py"
] |
[
"import numpy as np\nimport cv2\nfrom rknn.api import RKNN\nimport torchvision.models as models\nimport torch\n\n\ndef export_pytorch_model():\n net = models.resnet18(pretrained=True)\n net.eval()\n trace_model = torch.jit.trace(net, torch.Tensor(1,3,224,224))\n trace_model.save('./resnet18.pt')\n\n\ndef show_outputs(output):\n output_sorted = sorted(output, reverse=True)\n top5_str = '\\n-----TOP 5-----\\n'\n for i in range(5):\n value = output_sorted[i]\n index = np.where(output == value)\n for j in range(len(index)):\n if (i + j) >= 5:\n break\n if value > 0:\n topi = '{}: {}\\n'.format(index[j], value)\n else:\n topi = '-1: 0.0\\n'\n top5_str += topi\n print(top5_str)\n\n\ndef show_perfs(perfs):\n perfs = 'perfs: {}\\n'.format(perfs)\n print(perfs)\n\n\ndef softmax(x):\n return np.exp(x)/sum(np.exp(x))\n\n\nif __name__ == '__main__':\n\n export_pytorch_model()\n\n model = './resnet18.pt'\n input_size_list = [[3, 224, 224]]\n\n # Create RKNN object\n rknn = RKNN()\n\n # pre-process config\n print('--> Config model')\n rknn.config(mean_values=[[123.675, 116.28, 103.53]], std_values=[[58.395, 58.395, 58.395]], reorder_channel='0 1 2')\n print('done')\n\n # Load Pytorch model\n print('--> Loading model')\n ret = rknn.load_pytorch(model=model, input_size_list=input_size_list)\n if ret != 0:\n print('Load Pytorch model failed!')\n exit(ret)\n print('done')\n\n # Build model\n print('--> Building model')\n ret = rknn.build(do_quantization=True, dataset='./dataset.txt')\n if ret != 0:\n print('Build model failed!')\n exit(ret)\n print('done')\n\n # Export RKNN model\n print('--> Export RKNN model')\n ret = rknn.export_rknn('./resnet_18.rknn')\n if ret != 0:\n print('Export resnet_18.rknn failed!')\n exit(ret)\n print('done')\n\n # ret = rknn.load_rknn('./resnet_18.rknn')\n\n # Set inputs\n img = cv2.imread('./space_shuttle_224.jpg')\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n # Init runtime environment\n print('--> Init runtime environment')\n ret = rknn.init_runtime()\n if ret != 0:\n print('Init runtime environment failed')\n exit(ret)\n print('done')\n\n # Inference\n print('--> Running model')\n outputs = rknn.inference(inputs=[img])\n show_outputs(softmax(np.array(outputs[0][0])))\n print('done')\n\n rknn.release()\n"
] |
[
[
"numpy.array",
"numpy.exp",
"numpy.where",
"torch.Tensor"
]
] |
SpearOfBayes/text_cnn_wiki
|
[
"4296ddb4c589a4caf3213dfde8a8142ee6a9e1ed"
] |
[
"data_helpers.py"
] |
[
"import numpy as np\nimport re\nimport jieba\nimport jieba.analyse\nfrom encode_table import labels\nfrom tqdm import *\n\nlabel_dic = {}\n\ndef clean_str(string):\n \"\"\"\n Tokenization/string cleaning for all datasets except for SST.\n Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n \"\"\"\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n # string = re.sub(r\"[\\u4E00-\\u9FA5]+\", \" \", string)\n return string.strip().lower()\n\ndef segmentation(word):\n\t# allowPos() : https://blog.csdn.net/hhtnan/article/details/77650128\n\tl = jieba.analyse.extract_tags(word, topK=20, withWeight=False, allowPOS=('nz', 'n', 'vn', 'v', 'a'))\n\ttmp = ' ' #指定连接字符\n\treturn tmp.join(l)\n\ndef onehot_encode(y):\n # for i in range(len(label_set)):\n # # label_dic是一个全局变量\n # label_dic[label_set[i]] = i\n # codes = map(lambda x: label_dic[x], y)\n codes = map(lambda x: labels[x], y)\n y_encoded = []\n length = len(labels) #获取标签集的长度\n # 为每一个数编码\n print('正在对标签进行one hot编码。。。。')\n for code in tqdm(codes):\n array = [0 for _ in range(length)]\n array[code] = 1\n y_encoded.append(array)\n return y_encoded\n\ndef load_data_and_labels(data_file):\n \"\"\"\n Loads MR polarity data from files, splits the data into words and generates labels.\n Returns split sentences and labels.\n \"\"\"\n # 从文件夹中加载数据\n # 首先讲文本文件里面的内容按行读取出来\n # 然后做成一个list形式\n # 接着trip去掉每一行首尾\n # positive_examples = list(open(positive_data_file, \"r\", encoding='utf-8').readlines())\n # positive_examples = [s.strip() for s in positive_examples]\n # negative_examples = list(open(negative_data_file, \"r\", encoding='utf-8').readlines())\n # negative_examples = [s.strip() for s in negative_examples]\n # x_text将两种分类的数据集合并\n # clean_str用于清除掉一些无用的字符,然后一律转化成小写\n # x_text = positive_examples + negative_examples\n # x_text = [clean_str(sent) for sent in x_text]\n # 创建标签\n # positive_labels = [[0, 1] for _ in positive_examples]\n # negative_labels = [[1, 0] for _ in negative_examples]\n # y = np.concatenate([positive_labels, negative_labels], 0)\n # y的结构是这样的:\n # [\n # [0 1]\n # [0 1]\n # [0 1]\n # ...\n # [1 0]\n # [1 0]\n # [1 0]\n # ]\n\n x_text = []\n y = []\n # 读取data_file中的所有数据记录\n f = open(data_file, \"r\", encoding='utf-8')\n # 掉第一行\n f.readline()\n while True:\n line = f.readline() #读取每行数据\n if not line:\n break\n item, label = line.split(',')\n #去掉末尾的'\\n'\n label = label.strip('\\n')\n # clean数据\n # item, label = clean_str(item), clean_str(label)\n # 加入数据集\n\n x_text.append(item)\n y.append(label)\n\n f.close()\n\n print('正在对商品名进行分词。。。。')\n for i in tqdm(range(len(x_text))):\n x_text[i] = segmentation(x_text[i])\n y = onehot_encode(y)\n y = np.array(y)\n\n return [x_text, y]\n\n\ndef batch_iter(data, batch_size, num_epochs, shuffle=True):\n \"\"\"\n 创建一个数据集的批量迭代器\n \"\"\"\n data = np.array(data)\n data_size = len(data)\n num_batches_per_epoch = int((len(data)-1)/batch_size) + 1\n for epoch in range(num_epochs):\n # 每一轮都打乱数据\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_data = data[shuffle_indices]\n else:\n shuffled_data = data\n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n yield shuffled_data[start_index:end_index]\n\ndef load_data_to_be_predicted(data_file):\n f = open(data_file, 'r')\n return f.read().split('\\n')\n\n\ndef get_label_name(index):\n for key in labels:\n if labels[key] == index:\n return key\n\n return 'not found'\n\ndef get_label_name_list(label_nums):\n label_names = []\n for i in range(len(label_nums)):\n label_names.append(get_label_name(int(label_nums[i])))\n return label_names\n \nif __name__ == '__main__':\n [x_text, y] = load_data_and_labels('./data/mini_train.csv')\n print(x_text[:10])\n print(y[:10])"
] |
[
[
"numpy.arange",
"numpy.array"
]
] |
andrjas/data_check
|
[
"12ba740fcf54261bed15f909290649e8350474da"
] |
[
"test/database/test_load_file.py"
] |
[
"from pathlib import Path\nimport pytest\nimport pandas as pd\nfrom pandas.testing import assert_frame_equal\nfrom sqlalchemy import Table, Column, String, Integer, MetaData, Date, Numeric, DateTime\nimport datetime\n\n\nfrom data_check import DataCheck # noqa E402\nfrom data_check.config import DataCheckConfig # noqa E402\nfrom data_check.sql import LoadMode # noqa E402\n\n# These tests should work on any database.\n# The tests are generic, but in integration tests each database uses specific SQL files.\n\n\[email protected](scope=\"module\", params=[\"csv\", \"xlsx\"])\ndef file_type(request) -> str:\n return request.param\n\n\[email protected]\ndef dc() -> DataCheck:\n config = DataCheckConfig().load_config().set_connection(\"test\")\n config.parallel_workers = 1\n _dc = DataCheck(config)\n _dc.load_template()\n _dc.output.configure_output(\n verbose=True,\n traceback=True,\n print_failed=True,\n print_format=\"json\",\n )\n return _dc\n\n\ndef create_test_table(table_name: str, schema: str, dc: DataCheck):\n if dc.sql.dialect == \"oracle\":\n dc.sql.run_sql(\n f\"create table {schema}.{table_name} (id number(10), data varchar2(10))\"\n )\n elif dc.sql.dialect == \"sqlite\":\n dc.sql.run_sql(\n f\"create table {schema}.{table_name} (id decimal, data varchar(10))\"\n )\n else:\n metadata = MetaData(dc.sql.get_engine())\n Table(\n table_name,\n metadata,\n Column(\"id\", Integer),\n Column(\"data\", String(10)),\n schema=schema,\n )\n metadata.create_all()\n\n\ndef create_test_table_with_date(table_name: str, schema: str, dc: DataCheck):\n if dc.sql.dialect == \"oracle\":\n dc.sql.run_sql(\n (\n f\"create table {schema}.{table_name} \"\n \"(id number(10), data varchar2(10), dat date)\"\n )\n )\n else:\n metadata = MetaData(dc.sql.get_engine())\n Table(\n table_name,\n metadata,\n Column(\"id\", Integer),\n Column(\"data\", String(10)),\n Column(\"dat\", Date),\n schema=schema,\n )\n metadata.create_all()\n\n\ndef create_test_table_with_datetime(table_name: str, schema: str, dc: DataCheck):\n if dc.sql.dialect == \"oracle\":\n dc.sql.run_sql(\n (\n f\"create table {schema}.{table_name} \"\n \"(id number(10), data varchar2(10), dat date)\"\n )\n )\n else:\n metadata = MetaData(dc.sql.get_engine())\n Table(\n table_name,\n metadata,\n Column(\"id\", Integer),\n Column(\"data\", String(10)),\n Column(\"dat\", DateTime),\n schema=schema,\n )\n metadata.create_all()\n\n\ndef create_test_table_with_decimal(table_name: str, schema: str, dc: DataCheck):\n if dc.sql.dialect == \"oracle\":\n dc.sql.run_sql(\n (\n f\"create table {schema}.{table_name} \"\n \"(id number(10), data varchar2(10), decim decimal(10, 4))\"\n )\n )\n elif dc.sql.dialect == \"sqlite\":\n dc.sql.run_sql(\n (\n f\"create table {schema}.{table_name} \"\n \"(id decimal, data varchar(10), decim decimal)\"\n )\n )\n else:\n metadata = MetaData(dc.sql.get_engine())\n Table(\n table_name,\n metadata,\n Column(\"id\", Integer),\n Column(\"data\", String(10)),\n Column(\"decim\", Numeric(10, 4)),\n schema=schema,\n )\n metadata.create_all()\n\n\ndef test_load_file_replace(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict({\"id\": [0, 1, 2], \"data\": [\"a\", \"b\", \"c\"]})\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_replace_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.REPLACE,\n )\n df = dc.sql.run_query(f\"select id, data from main.test_replace_{file_type}\")\n assert_frame_equal(data, df)\n\n\ndef test_load_file_replace_with_table(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict({\"id\": [0, 1, 2], \"data\": [\"a\", \"b\", \"c\"]})\n create_test_table(f\"test_replace2_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_replace2_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.REPLACE,\n )\n df = dc.sql.run_query(f\"select id, data from main.test_replace2_{file_type}\")\n assert_frame_equal(data, df)\n\n\ndef test_load_file_truncate(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict({\"id\": [0, 1, 2], \"data\": [\"a\", \"b\", \"c\"]})\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_truncate_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n df = dc.sql.run_query(f\"select id, data from main.test_truncate_{file_type}\")\n assert_frame_equal(data, df)\n\n\ndef test_load_file_truncate_with_table(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict({\"id\": [0, 1, 2], \"data\": [\"a\", \"b\", \"c\"]})\n create_test_table(f\"test_truncate2_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_truncate2_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n df = dc.sql.run_query(f\"select id, data from main.test_truncate2_{file_type}\")\n assert_frame_equal(data, df)\n\n\ndef test_load_file_append(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict({\"id\": [0, 1, 2], \"data\": [\"a\", \"b\", \"c\"]})\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_append_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_append_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.APPEND,\n )\n df = dc.sql.run_query(f\"select id, data from main.test_append_{file_type}\")\n check_data = pd.DataFrame.from_dict(\n {\"id\": [0, 1, 2, 0, 1, 2], \"data\": [\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]}\n )\n assert_frame_equal(check_data, df)\n assert len(df) == 6\n\n\ndef test_load_file_append_with_table(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict({\"id\": [0, 1, 2], \"data\": [\"a\", \"b\", \"c\"]})\n create_test_table(f\"test_append2_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_append2_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.APPEND,\n )\n df = dc.sql.run_query(f\"select id, data from main.test_append2_{file_type}\")\n assert_frame_equal(data, df)\n assert len(df) == 3\n\n\ndef test_load_file_date_type(dc: DataCheck, file_type: str):\n create_test_table_with_date(f\"test_date_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_date_{file_type}\",\n Path(f\"load_data/test_date.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n df = dc.sql.run_query(f\"select id, data, dat from main.test_date_{file_type}\")\n dat = df.dat\n assert not dat.empty\n\n\ndef test_load_file_date_type_huge_date(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict(\n {\n \"id\": [0, 1],\n \"data\": [\"a\", \"b\"],\n \"dat\": [datetime.datetime(2021, 1, 25), datetime.datetime(9999, 12, 31)],\n }\n )\n create_test_table_with_datetime(f\"test_date_huge_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_date_huge_{file_type}\",\n Path(f\"load_data/test_date_huge.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n df = dc.sql.run_query(f\"select id, data, dat from main.test_date_huge_{file_type}\")\n assert_frame_equal(data, df)\n\n\ndef test_load_file_datetime_type(dc: DataCheck, file_type: str):\n create_test_table_with_datetime(f\"test_datetime_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_datetime_{file_type}\",\n Path(f\"load_data/test_datetime.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n df = dc.sql.run_query(f\"select id, data, dat from main.test_datetime_{file_type}\")\n dat = df.dat\n assert not dat.empty\n\n\ndef test_load_file_date_with_existing_table_replace(dc: DataCheck, file_type: str):\n create_test_table_with_datetime(f\"test_date_replace_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_date_replace_{file_type}\",\n Path(f\"load_data/test_date.{file_type}\"),\n LoadMode.REPLACE,\n )\n df = dc.sql.run_query(\n f\"select id, data, dat from main.test_date_replace_{file_type}\"\n )\n if dc.sql.dialect == \"oracle\":\n # in Oracle this is a date type\n assert df.dat.dtype == \"<M8[ns]\"\n else:\n assert df.dat.dtype == \"datetime64[ns]\"\n\n\ndef test_load_file_decimal_type(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict(\n {\"id\": [0, 1], \"data\": [\"a\", \"b\"], \"decim\": [0.1, 0.2]}\n )\n create_test_table_with_decimal(f\"test_decimals_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_decimals_{file_type}\",\n Path(f\"load_data/test_decimals.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n df = dc.sql.run_query(f\"select id, data, decim from main.test_decimals_{file_type}\")\n assert_frame_equal(data, df)\n\n\ndef test_load_file_less_columns_in_file(dc: DataCheck, file_type: str):\n data = pd.DataFrame.from_dict(\n {\"id\": [0, 1, 2], \"data\": [\"a\", \"b\", \"c\"], \"decim\": [pd.NA, pd.NA, pd.NA]}\n )\n create_test_table_with_decimal(f\"test_less_columns_in_{file_type}\", \"main\", dc)\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_less_columns_in_{file_type}\",\n Path(f\"load_data/test.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n df = dc.sql.run_query(\n f\"select id, data, decim from main.test_less_columns_in_{file_type}\"\n )\n assert_frame_equal(data, df)\n\n\ndef test_load_file_more_columns_in_file(dc: DataCheck, file_type: str):\n create_test_table(f\"test_more_columns_in_{file_type}\", \"main\", dc)\n with pytest.raises(Exception):\n dc.sql.table_loader.load_table_from_file(\n f\"main.test_more_columns_in_{file_type}\",\n Path(f\"load_data/test_decimals.{file_type}\"),\n LoadMode.TRUNCATE,\n )\n\n\ndef test_table_exists(dc: DataCheck):\n create_test_table(\"test_table_exists\", \"main\", dc)\n assert dc.sql.table_loader.table_exists(\"test_table_exists\", \"main\")\n\n\ndef test_table_exists_non_existing(dc: DataCheck):\n assert not dc.sql.table_loader.table_exists(\n \"test_table_exists_non_existing\", \"main\"\n )\n\n\ndef test_drop_table_if_exists_with_existing_table(dc: DataCheck):\n create_test_table(\"test_drop_existing\", \"main\", dc)\n dc.sql.table_loader.drop_table_if_exists(\"test_drop_existing\", \"main\")\n with pytest.raises(Exception):\n dc.sql.run_query(\"select * from main.test_drop_existing\")\n\n\ndef test_drop_table_if_exists_with_non_existing_table(dc: DataCheck):\n dc.sql.table_loader.drop_table_if_exists(\"test_drop_non_existing\", \"main\")\n with pytest.raises(Exception):\n dc.sql.run_query(\"select * from temp.test_drop_non_existing\")\n"
] |
[
[
"pandas.testing.assert_frame_equal",
"pandas.DataFrame.from_dict"
]
] |
MarcelRG/semanai
|
[
"08a1ceb9f24b361fc155bf18526325aaf6769798"
] |
[
"Dia1/numpy2.py"
] |
[
"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport time\nimport uber_display\nfrom scipy import stats\n\n\"# Numpy and Pandas Tutorial\"\n\"### Semana i 2019\"\n\"Made in Streamlit\"\n\nif st.checkbox('Show Uber Data'):\n st.subheader('Uber data data')\n uber_display.main()\n\n\"\"\"# Numpy exercises \"\"\"\n\n\"- **Show numpy version**\"\nversion = np.__version__\nresult = \"Numpy version : {}\".format(version)\n\n#Answer\nresult\n\n\"- **Create the array :** \"\n\" *[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]*\"\n\n#Answer\nresult = np.array([0,1,2,3,4,5,6,7,])\n\"Answer\"\nresult\n\n\n\"- **Select the cell located in row 2 column 2 from this array**\"\n\narr = np.array(([21, 22, 23], [11, 22, 33], [43, 77, 89]))\n\"*Array*\"\narr\n\n#Answer\nresult = arr[1][1]\nresult\n\n\"- **Select the column with index 0**\"\narr = np.array(([21, 22, 23], [11, 22, 33], [43, 77, 89]))\narr\n\n#Answer\nresult = arr.T[0]\nresult\n\n\"- **Extract all the odd numbers in the next array**\"\n\" *[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]*\"\n\narr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])\narr = arr[arr % 2 == 1 ]\nresult = arr\nresult\n\n\"\"\"- **Replace de odd numbers with negative numbers in the next array**\"\"\"\n\" *[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]*\"\n\narr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n#Answer\nl = []\nfor x in range(len(arr)):\n if(arr[x] % 2 == 1):\n l.append(-arr[x])\n else:\n l.append(arr[x])\nresult = l\nresult\n\n\"- **Reshape the next array from 1D to 2D**\"\n\" *[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]*\"\narr = np.arange(10)\n#Answer\narr = arr.reshape([2,5])\nresult = arr\nresult\n\n\"- **Compute euclidian distance between A and B **\"\n\"A\"\na = np.array([1,2,3,4,5])\na\n\"B\"\nb = np.array([4,5,6,7,8])\nb\n#Answer\nresult = np.linalg.norm(a-b)\nresult\n\n\"- **Find the most frequent value of petal length (3rd column) in the [iris dataset](https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data)**\"\ndef downloadIrisDataset():\n url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\n iris = np.genfromtxt(url, delimiter=',', dtype='object')\n return iris\n\"*Dataset*\"\niris = downloadIrisDataset()\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\n#Answer\nmoda = stats.mode(iris.T[2])\nresult = moda[0][0]\nresult"
] |
[
[
"numpy.arange",
"numpy.linalg.norm",
"numpy.genfromtxt",
"scipy.stats.mode",
"numpy.array"
]
] |
cambridge-mlg/expressiveness-approx-bnns
|
[
"1d63a8671581bf388f1a84d0daf48990ebecb1e1"
] |
[
"inbetween/NNKernel.py"
] |
[
"import tensorflow as tf\nimport numpy as np\nimport gpflow\nfrom gpflow.base import Parameter\nfrom gpflow.utilities import positive\n\n\nclass ReLUKernel(gpflow.kernels.Kernel):\n \"\"\"\n Kernel such that the mean 0 GP with the corresponding covariance function is equal in distribution\n to an infinitely wide BNN prior with mean O and \"Neal scaling\" on the weights. The recursive equations used\n are from https://arxiv.org/abs/1711.00165.\n \"\"\"\n\n def __init__(self, prior_weight_std, prior_bias_std, depth):\n \"\"\"\n\n Args:\n prior_weight_std: non-negative float or tuple\n of length depth+1 of floats, corresponding BNN has prior variance prior_weight_std / sqrt(num_inputs)\n If tuple separate standard deviation for each layer\n prior_bias_std: non-negative float or tuple\n of length depth+1 of floats, corresponding BNN has prior variance prior_bias_std\n If tuple separate standard deviation for each layer\n depth: int, number of hidden layers in corresponding BNN\n \"\"\"\n\n super(ReLUKernel, self).__init__()\n if isinstance(prior_weight_std, float) or isinstance(prior_weight_std, int):\n prior_weight_std = prior_weight_std * np.ones(depth + 1)\n if isinstance(prior_bias_std, float) or isinstance(prior_bias_std, int):\n prior_bias_std = prior_bias_std * np.ones(depth + 1)\n assert len(prior_weight_std) == len(prior_bias_std) == depth + 1\n self.weight_variance = Parameter(prior_weight_std ** 2, transform=positive(1e-5))\n self.bias_variance = Parameter(prior_bias_std ** 2, transform=positive(1e-5))\n self.depth = depth\n\n def K(self, X, X2=None):\n \"\"\"\n Computes covariance matrix between k(X,X2), if X2 is None computes covariance matrix k(X,X)\n Args:\n X: [N,D] float\n X2: None or [N,D] float, if None X2=X\n\n Returns: [N,N] matrix k(X,X2)\n\n \"\"\"\n D = X.shape[1] # input dimension\n jitter = 1e-15 # jitter for arccosine for numerical reasons\n\n if X2 is None: # compute symmetric version\n X2 = X\n\n # base case for recursive formula\n Ki = self.bias_variance[0] + self.weight_variance[0] * tf.matmul(X, X2, transpose_b=True) / D\n KiX = self.bias_variance[0] + self.weight_variance[0] * tf.reduce_sum(tf.square(X), axis=1) / D\n KiX2 = self.bias_variance[0] + self.weight_variance[0] * tf.reduce_sum(tf.square(X2), axis=1) / D\n\n # flattened recursion\n for i in range(1, self.depth + 1):\n sqrt_term = tf.sqrt(KiX[:, None] * KiX2[None, :]) # outer product of norms\n theta = tf.acos(jitter + (1 - 2 * jitter) * Ki/sqrt_term) # angle, 'squash' for numerical stability\n J_term = tf.sin(theta) + (np.pi - theta) * tf.cos(theta)\n # update kernel matrices\n Ki = self.bias_variance[i] + self.weight_variance[i] / (2 * np.pi) * sqrt_term * J_term\n\n if i != self.depth: # these are only needed for the recursion, don't update on last call\n KiX = self.bias_variance[i] + KiX * self.weight_variance[i] / 2.\n KiX2 = self.bias_variance[i] + KiX2 * self.weight_variance[i] / 2.\n return Ki\n\n def K_diag(self, X):\n \"\"\"\n Computes diagonal entries of k(X,X)\n Args:\n X: [N,D] float\n\n Returns: [N] float. diag(k(X,X))\n\n \"\"\"\n D = X.shape[1] # input dimension\n KiX = self.bias_variance[0] + self.weight_variance[0] * tf.reduce_sum(tf.square(X), axis=1) / D\n for i in range(1, self.depth + 1):\n KiX = self.bias_variance[i] + KiX * self.weight_variance[i] / 2.\n return KiX\n"
] |
[
[
"tensorflow.matmul",
"tensorflow.sin",
"tensorflow.cos",
"numpy.ones",
"tensorflow.square",
"tensorflow.sqrt",
"tensorflow.acos"
]
] |
webbfontaine/fasttext-tensorflow
|
[
"fab3f3341862b4582d398939c7604752ba744902"
] |
[
"fasttext_model.py"
] |
[
"import inspect\nimport json\nimport os\nimport warnings\nfrom subprocess import (\n Popen,\n PIPE,\n STDOUT,\n)\n\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport tensorflow as tf\nimport tensorflow.compat.v1.logging as logging\n\nfrom utils import (\n load_graph,\n hash_,\n validate,\n handle_space_paths,\n copy_all,\n)\nfrom fasttext_utils import (\n get_all,\n parse_txt,\n next_batch,\n preprocess_data,\n get_accuracy_log_dir,\n)\n\nlogging.set_verbosity(logging.ERROR)\nwarnings.filterwarnings(\"ignore\")\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\n\nclass FastTextModel(object):\n def __init__(self, model_path, model_params_path, label_prefix=\"__label__\", preprocessing_function=None,\n use_gpu=True, gpu_fraction=0.5, hyperparams=None):\n \"\"\"\n :param model_path: str, path to pb file\n :param model_params_path: str, path to pb model_params.json\n :param label_prefix: list, prefix for labels\n :param preprocessing_function: function, function to apply on data\n :param use_gpu: bool, use gpu for training\n :param gpu_fraction: float, gpu fraction to allocate\n :param hyperparams: dict, all hyperparams for train_supervised\n :return: object, the trained model\n \"\"\"\n tf.reset_default_graph()\n self._graph = tf.Graph()\n self.label_prefix = label_prefix\n if hyperparams:\n self.hyperparams = hyperparams\n else:\n self.hyperparams = dict()\n self.info = {\"model_path\": os.path.abspath(model_path), \"model_params_path\": os.path.abspath(model_params_path)}\n with open(model_params_path, \"r\") as infile:\n model_params = json.load(infile)\n for key, value in model_params.items():\n self.info[key] = value\n if os.path.isfile(model_params[\"label_dict_path\"]):\n with open(model_params[\"label_dict_path\"], \"r\") as infile:\n self.label_dict = json.load(infile)\n else:\n new_path = os.path.join(os.path.dirname(model_params_path), \"label_dict.json\")\n print(\"{} not found, switching to model_params' path {}\".format(model_params[\"label_dict_path\"], new_path))\n with open(new_path, \"r\") as infile:\n self.label_dict = json.load(infile)\n self.info[\"label_dict_path\"] = os.path.abspath(new_path)\n if os.path.isfile(model_params[\"word_dict_path\"]):\n with open(model_params[\"word_dict_path\"], \"r\") as infile:\n self.word_dict = json.load(infile)\n else:\n new_path = os.path.join(os.path.dirname(model_params_path), \"word_dict.json\")\n print(\"{} not found, switching to model_params' path {}\".format(model_params[\"word_dict_path\"], new_path))\n with open(new_path, \"r\") as infile:\n self.word_dict = json.load(infile)\n self.info[\"word_dict_path\"] = os.path.abspath(new_path)\n self.preprocessing_function = preprocessing_function\n\n get_list = [\"input\", \"input_weights\", \"embeddings/embedding_matrix/read\",\n \"mean_sentence_embedding/sentence_embedding\", \"logits/kernel/read\", \"prediction\"]\n get_list = [i + \":0\" for i in get_list]\n\n self._device = \"/cpu:0\"\n config = tf.ConfigProto(device_count={\"GPU\": 0}, allow_soft_placement=True)\n if use_gpu:\n self._device = \"/gpu:0\"\n config = tf.ConfigProto(allow_soft_placement=True,\n gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction,\n allow_growth=True))\n self._input_matrix, self._output_matrix = None, None\n\n with tf.device(self._device):\n with self._graph.as_default():\n self._input_placeholder, self._weights_placeholder, self._input_matrix_tensor, self._sentence_vector, \\\n self._output_matrix_tensor, self._output = load_graph(model_path, get_list)\n\n self._sess = tf.Session(graph=self._graph, config=config)\n self._dim = self.get_dimension()\n _ = self.predict([\"\"] * 3, batch_size=3, show_progress=False) # warm up\n\n def __del__(self):\n with tf.device(self._device):\n self._sess.close()\n\n def get_dimension(self):\n \"\"\"\n Get the dimension (size) of a lookup vector (hidden layer).\n :return: int\n \"\"\"\n return int(self._sentence_vector.shape[1])\n\n def get_input_matrix(self):\n \"\"\"\n Get a copy of the full input matrix of a Model.\n :return: np.ndarray, size: word_count * dim\n \"\"\"\n if self._input_matrix is None:\n self._input_matrix = self._sess.run(self._input_matrix_tensor)\n return self._input_matrix\n\n def get_input_vector(self, index):\n \"\"\"\n Given an index, get the corresponding vector of the Input Matrix.\n :param index: int\n :return: np.ndarray, size: dim\n \"\"\"\n return self._input_matrix[index]\n\n def get_labels(self, include_freq=False):\n \"\"\"\n Get the entire list of labels of the dictionary optionally including the frequency of the individual labels.\n :param include_freq: bool, returns tuple with labels and their frequencies\n :return: list / tuple of lists\n \"\"\"\n labels = sorted(self.label_dict.keys())\n if include_freq:\n return labels, [self.label_dict[key][\"cnt\"] for key in labels]\n return labels\n\n def get_line(self, text):\n \"\"\"\n Preprocess the text and split it into words and labels. Labels must start with the prefix used to create the\n model (__label__ by default) and have been used in training.\n :param text: str\n :return: (list, list)\n \"\"\"\n tokens, labels = [\"__MEAN_EMBEDDING__\"], []\n for token in text.split():\n if token.startswith(self.label_prefix):\n label_clean = token[len(self.label_prefix):]\n if label_clean in self.label_dict:\n labels.append(label_clean)\n else:\n tokens.append(token)\n if self.preprocessing_function:\n tokens = self.preprocessing_function(\" \".join(tokens)).split()\n return tokens, labels\n\n def get_output_matrix(self):\n \"\"\"\n Get a copy of the full output matrix of a Model.\n :return: np.ndarray, size: dim * label_count\n \"\"\"\n if self._output_matrix is None:\n self._output_matrix = self._sess.run(self._output_matrix_tensor)\n return self._output_matrix\n\n def get_sentence_vector(self, text, batch_size=1000):\n \"\"\"\n Given a string or list of string, get its (theirs) vector represenation(s). This function applies\n preprocessing function on the strings.\n :param text: str or list/array\n :param batch_size: int\n :return: np.ndarray, size: dim\n \"\"\"\n\n if not isinstance(text, (list, str, np.ndarray, pd.Series)):\n raise ValueError(\"text should be string, list, numpy array or pandas series\")\n if isinstance(text, str):\n text = [text]\n embeddings = []\n\n for batch, batch_weights in self._batch_generator(text, batch_size):\n embeddings.extend(self._sess.run(self._sentence_vector,\n feed_dict={self._input_placeholder: batch,\n self._weights_placeholder: batch_weights}))\n return np.squeeze(embeddings)\n\n def get_subword_id(self, subword):\n \"\"\"\n Given a subword, get the word id within the dictionary. Returns -1 if word is not in the dictionary.\n :param subword:\n :return: int. Returns -1 if is not in vocabulary\n \"\"\"\n return self.word_dict[subword][\"id\"] if subword in self.word_dict else -1\n\n def get_subwords(self, word):\n word = word.replace(\"_\", \" \")\n word_splitted = word.split()\n if len(word_splitted) > self.info[\"word_ngrams\"]:\n return [], []\n else:\n subwords = [phrase for phrase in get_all(word_splitted, self.info[\"word_ngrams\"], self.info[\"sort_ngrams\"])\n if phrase in self.word_dict]\n return subwords, [self.get_word_id(subword) for subword in subwords]\n\n def get_word_id(self, word):\n if \" \" in word:\n word = word.replace(\" \", \"_\")\n return self.word_dict[word][\"id\"] if word in self.word_dict else -1\n\n def get_word_vector(self, word):\n \"\"\"\n Get the vector representation of word.\n :param word: str\n :return: np.ndarray, size: dim. returns 0s if not from vocabulary\n \"\"\"\n if self.preprocessing_function:\n word_dict = self.get_word_id(self.preprocessing_function(word))\n else:\n word_dict = self.get_word_id(word)\n return self.get_input_vector(word_dict) if word_dict != -1 else np.zeros(self._dim, dtype=np.float32)\n\n def get_words(self, include_freq=False):\n \"\"\"\n Get the entire list of words of the dictionary optionally including the frequency of the individual words.\n :param include_freq: bool, returns tuple with words and their frequencies\n :return: list / tuple of lists\n \"\"\"\n words = sorted(self.word_dict.keys())\n if include_freq:\n return words, [self.word_dict[key][\"cnt\"] for key in words]\n return words\n\n def _batch_generator(self, list_of_texts, batch_size, show_progress=False):\n \"\"\"\n Generate batch from list of texts\n :param list_of_texts: list/array\n :param batch_size: int\n :param show_progress: bool, show progress bar\n :return: batch word indices, batch word weights\n \"\"\"\n if self.preprocessing_function:\n list_of_texts = [self.preprocessing_function(str(text)) for text in list_of_texts]\n else:\n list_of_texts = [str(text) for text in list_of_texts]\n indices = np.arange(len(list_of_texts))\n remaining_indices, batch_indices = next_batch(indices, batch_size)\n\n if len(list_of_texts) <= batch_size:\n show_progress = False\n\n disable_progress_bar = not show_progress\n progress_bar = tqdm(total=int(np.ceil(len(list_of_texts) / batch_size)), disable=disable_progress_bar)\n\n while len(batch_indices) > 0:\n batch, batch_weights = [], []\n\n batch_descriptions = [list(get_all(list_of_texts[index].split(), self.info[\"word_ngrams\"],\n self.info[\"sort_ngrams\"])) for index in batch_indices]\n num_max_words = max([len(batch_description) for batch_description in batch_descriptions]) + 1\n\n for batch_description in batch_descriptions:\n initial_indices = [0] + [self.word_dict[phrase][\"id\"] for phrase in batch_description\n if phrase in self.word_dict]\n\n description_indices = np.array(initial_indices +\n [0 for _ in range(num_max_words - len(initial_indices))])\n description_weights = np.zeros_like(description_indices, dtype=np.float32)\n description_weights[:len(initial_indices)] = 1. / len(initial_indices)\n\n batch.append(description_indices)\n batch_weights.append(description_weights)\n remaining_indices, batch_indices = next_batch(remaining_indices, batch_size)\n\n progress_bar.update()\n yield batch, batch_weights\n\n progress_bar.close()\n\n def predict(self, list_of_texts, k=1, threshold=-0.1, batch_size=1000, show_progress=True):\n \"\"\"\n Predict top k predictions on given texts\n :param list_of_texts: list/array\n :param k: int, top k predictions\n :param threshold: float, from 0 to 1, default -0.1 meaining no threshold\n :param batch_size: int\n :param show_progress: bool, ignored if list of text is string or has smaller or equal length to batch size\n :return: top k predictions and probabilities\n \"\"\"\n if isinstance(list_of_texts, str):\n list_of_texts = [list_of_texts]\n\n labels = self.get_labels()\n predictions, probabilities = [], []\n\n for batch, batch_weights in self._batch_generator(list_of_texts, batch_size, show_progress):\n batch_probabilities = self._sess.run(self._output, feed_dict={self._input_placeholder: batch,\n self._weights_placeholder: batch_weights})\n\n top_k_probabilities, top_k_predictions = [], []\n for i in batch_probabilities:\n predictions_row, probabilities_row = [], []\n if k == -1:\n top_k_indices = np.argsort(i)[::-1]\n else:\n top_k_indices = np.argsort(i)[-k:][::-1]\n for index, probability in zip(top_k_indices, i[top_k_indices]):\n if probability > threshold:\n predictions_row.append(index)\n probabilities_row.append(probability)\n top_k_predictions.append([labels[i] for i in predictions_row])\n top_k_probabilities.append(probabilities_row)\n predictions.extend(top_k_predictions)\n probabilities.extend(top_k_probabilities)\n return predictions, probabilities\n\n def test(self, list_of_texts, list_of_labels, k=1, threshold=-0.1, batch_size=1000, show_progress=True):\n \"\"\"\n Predict top k predictions on given texts\n :param list_of_texts: list/array\n :param list_of_labels: list/array\n :param k: int, top k predictions\n :param threshold: float, from 0 to 1. Default is -0.1 meaining no threshold\n :param batch_size: int\n :param show_progress: bool\n :return: top k predictions and probabilities\n \"\"\"\n if len(list_of_texts) != len(list_of_labels):\n raise ValueError('the lengths of list_of_texts and list_of_labels must match')\n\n predictions, probabilities = self.predict(list_of_texts=list_of_texts, batch_size=batch_size, k=k,\n threshold=threshold, show_progress=show_progress)\n recall, precision = 0, 0\n all_labels, all_predictions = 0, 0\n for current_labels, current_predictions in zip(list_of_labels, predictions):\n if not isinstance(current_labels, list):\n current_labels = [current_labels]\n\n all_labels += len(current_labels)\n all_predictions += len(current_predictions)\n for current_label in current_labels:\n if current_label in current_predictions:\n recall += 1\n for current_prediction in current_predictions:\n if current_prediction in current_labels:\n precision += 1\n\n return len(list_of_texts), round(100 * precision / all_predictions, 2), round(100 * recall / all_labels, 2)\n\n def test_file(self, test_data_path, k=1, threshold=-0.1, batch_size=1000, show_progress=True):\n \"\"\"\n Predict top k predictions on given texts\n :param test_data_path: str, path to test file\n :param k: int, top k predictions\n :param threshold: float, from 0 to 1, default -0.1 meaining no threshold\n :param batch_size: int\n :param show_progress: bool\n :return: top k predictions and probabilities\n \"\"\"\n data, labels = parse_txt(test_data_path, label_prefix=self.label_prefix)\n return self.test(data, labels, batch_size=batch_size, k=k, threshold=threshold, show_progress=show_progress)\n\n def export_model(self, destination_path):\n \"\"\"\n Extract all the needed files for model loading to the specified destination.\n Also copies the training and validation files if available\n :param destination_path: str\n :return: None\n \"\"\"\n all_paths = [value for key, value in self.info.items() if \"path\" in key]\n if \"train_path\" in self.hyperparams:\n all_paths.append(self.hyperparams[\"train_path\"])\n\n if \"test_path\" in self.hyperparams:\n all_paths.append(self.hyperparams[\"test_path\"])\n\n if \"original_train_path\" in self.hyperparams:\n all_paths.append(self.hyperparams[\"original_train_path\"])\n all_paths.extend(self.hyperparams[\"additional_data_paths\"])\n\n copy_all(all_paths, destination_path)\n model_params_path = os.path.join(destination_path, \"model_params.json\")\n with open(model_params_path, \"r\") as infile:\n model_params = json.load(infile)\n for key, value in model_params.items():\n if key.endswith(\"path\"):\n model_params[key] = os.path.join(os.path.abspath(destination_path), value.split(\"/\")[-1])\n with open(model_params_path, \"w+\") as outfile:\n json.dump(model_params, outfile)\n\n\nclass train_supervised(FastTextModel):\n def __init__(self, train_path, test_path=None, additional_data_paths=None, hyperparams=None,\n preprocessing_function=None, log_dir=\"./\", use_gpu=False, gpu_fraction=0.5, verbose=True,\n remove_extra_labels=True, force=False):\n \"\"\"\n Train a supervised fasttext model\n :param train_path: str, path to train file\n :param test_path: str or None, path to test file, if None training will be done without test\n :param additional_data_paths: list of str, paths of fasttext format additional data to concat with train file\n :param hyperparams: dict, all hyperparams for train_supervised\n :param preprocessing_function: function, function to apply on text data before feeding into network\n :param log_dir: str, directory to save the training files and the model\n :param use_gpu: bool, use gpu for training\n :param gpu_fraction: float, gpu fraction to allocate\n :param remove_extra_labels: bool, remove data from additional paths, which have labels not contained in\n train.txt\n :param verbose: bool\n :param remove_extra_labels: bool, remove datapoints with labels which appear in additional_data_paths but not in\n train_data_path. Ignored if additional_data_paths is None\n :param force: bool, forced training\n :return: object, the trained model\n \"\"\"\n log_dir = validate(log_dir)\n\n # defualt hyperparams\n self.hyperparams = \\\n {\"train_path\": '',\n \"test_path\": '',\n \"label_prefix\": \"__label__\",\n \"data_fraction\": 1,\n \"seed\": 17,\n \"embedding_dim\": 100,\n \"num_epochs\": 10,\n \"word_ngrams\": 1,\n \"sort_ngrams\": 0,\n \"batch_size\": 4096,\n \"use_batch_norm\": 0,\n \"min_word_count\": 1,\n \"learning_rate\": 0.1,\n \"learning_rate_multiplier\": 0.8,\n \"dropout\": 0.5,\n \"l2_reg_weight\": 1e-06,\n \"batch_size_inference\": 4096,\n \"top_k\": 3,\n \"compare_top_k\": 0,\n \"save_all_models\": 0,\n \"use_test\": 0,\n \"use_gpu\": 0,\n \"gpu_fraction\": 0.5,\n \"cache_dir\": handle_space_paths(os.path.abspath(os.path.join(log_dir, \"cache\"))),\n \"log_dir\": handle_space_paths(os.path.abspath(os.path.join(log_dir, \"results\"))),\n \"force\": 0,\n \"progress_bar\": 1,\n \"flush\": 1}\n\n if not os.path.exists(train_path):\n raise FileNotFoundError(\"train_path is incorrect\")\n if test_path:\n if not os.path.exists(test_path):\n raise FileNotFoundError(\"test_path is incorrect\")\n\n if preprocessing_function and verbose:\n print(\"Preprocessing train data ...\")\n to_restore = dict()\n\n if hyperparams is None:\n hyperparams = dict()\n\n do_preprocessing = preprocessing_function is not None\n\n if len(hyperparams) != 0:\n for key, value in hyperparams.items():\n if key not in self.hyperparams:\n to_restore[key] = value\n print(\"WARNING! {} not in hyperparams, ignoring it\".format(key))\n else:\n if key in [\"cache_dir\", \"log_dir\"]:\n self.hyperparams[key] = handle_space_paths(value)\n else:\n self.hyperparams[key] = value\n train_path = os.path.abspath(train_path)\n if additional_data_paths:\n data_to_save = []\n paths_joined_hashed = hash_(\" \".join(additional_data_paths))\n concat_path = \"./tmp.txt\"\n joined_path = \"./{}.txt\".format(paths_joined_hashed)\n _, all_labels = parse_txt(train_path)\n unique_labels = np.unique(all_labels)\n if not isinstance(additional_data_paths, list):\n raise ValueError(\"Type of additional_data_paths should be list\")\n for additional_data_path in additional_data_paths:\n if not os.path.isfile(additional_data_path):\n raise FileNotFoundError(\"{} in additional data paths doesn't exist\".format(additional_data_path))\n current_data, current_labels = parse_txt(additional_data_path)\n if remove_extra_labels:\n needed_mask = np.in1d(current_labels, unique_labels)\n current_data = [data for data, needed in zip(current_data, needed_mask) if needed]\n current_labels = [data for data, needed in zip(current_labels, needed_mask) if needed]\n if do_preprocessing:\n data_to_save.extend([\"{}{} {}\".format(self.hyperparams[\"label_prefix\"], label,\n preprocessing_function(data)) for label, data\n in zip(current_labels, current_data)])\n else:\n data_to_save.extend([\"{}{} {}\".format(self.hyperparams[\"label_prefix\"], label, data) for label, data\n in zip(current_labels, current_data)])\n np.savetxt(concat_path, data_to_save, fmt=\"%s\")\n if do_preprocessing:\n prep_train_path = preprocess_data(train_path, preprocessing_function)\n os.system(\"cat {} {} > {}\".format(concat_path, prep_train_path, joined_path))\n to_restore[\"original_train_path\"] = prep_train_path\n else:\n os.system(\"cat {} {} > {}\".format(concat_path, train_path, joined_path))\n to_restore[\"original_train_path\"] = train_path\n self.hyperparams[\"train_path\"] = joined_path\n to_restore[\"additional_data_paths\"] = additional_data_paths\n else:\n if do_preprocessing:\n prep_train_path = preprocess_data(train_path, preprocessing_function)\n self.hyperparams[\"train_path\"] = prep_train_path\n else:\n self.hyperparams[\"train_path\"] = train_path\n\n if preprocessing_function and verbose:\n print(\"Done!\")\n\n if test_path is not None:\n test_path = os.path.abspath(test_path)\n self.hyperparams[\"use_test\"] = 1\n if do_preprocessing:\n prep_test_path = preprocess_data(test_path, preprocessing_function)\n to_restore[\"original_test_path\"] = test_path\n self.hyperparams[\"test_path\"] = prep_test_path\n else:\n self.hyperparams[\"test_path\"] = test_path\n\n if use_gpu:\n self.hyperparams[\"use_gpu\"] = 1\n self.hyperparams[\"gpu_fraction\"] = gpu_fraction\n\n if force:\n self.hyperparams[\"force\"] = 1\n\n # using Popen as calling the command from Jupyter doesn't deallocate GPU memory\n train_command = self._get_train_command()\n process = Popen(train_command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True)\n self.top_1_accuracy, self.top_k_accuracy, log_dir = \\\n get_accuracy_log_dir(process, self.hyperparams[\"top_k\"], verbose)\n\n for key, value in to_restore.items():\n self.hyperparams[key] = value\n super(train_supervised, self).__init__(model_path=os.path.join(log_dir, \"model_best.pb\"),\n model_params_path=os.path.join(log_dir, \"model_params.json\"),\n use_gpu=use_gpu, gpu_fraction=gpu_fraction, hyperparams=self.hyperparams,\n label_prefix=self.hyperparams[\"label_prefix\"],\n preprocessing_function=preprocessing_function)\n\n def _get_train_command(self):\n args = [\"--{} {}\".format(key, value) for key, value in self.hyperparams.items() if str(value)]\n current_directory = os.path.dirname(inspect.getfile(inspect.currentframe()))\n train_command = \" \".join([\"python3 {}\".format(os.path.join(current_directory, \"main.py\"))] + args)\n return train_command\n"
] |
[
[
"tensorflow.Graph",
"tensorflow.device",
"numpy.unique",
"numpy.squeeze",
"numpy.in1d",
"tensorflow.compat.v1.logging.set_verbosity",
"tensorflow.ConfigProto",
"tensorflow.reset_default_graph",
"numpy.zeros_like",
"tensorflow.GPUOptions",
"tensorflow.Session",
"numpy.savetxt",
"numpy.argsort",
"numpy.zeros"
]
] |
TanmayeeGujar/CP1_Calculus
|
[
"1a2c545299ac5fc355ba7f56b1ddc21fb81785a5"
] |
[
"UtilityFunctions/integrals.py"
] |
[
"import numpy as np\n\n\ndef simpson(f, a, b, n):\n \"\"\"Approximates the definite integral of f from a to b by\n the composite Simpson's rule, using n subintervals.\n From http://en.wikipedia.org/wiki/Simpson's_rule\n \n Args:\n f : function to integrate\n a,b : boundaries\n n : number of subintervals\n \n Return: integral\n \"\"\"\n h = (b - a) / n\n i = np.arange(0,n)\n \n s = f(a) + f(b) \n s += 4 * np.sum( f( a + i[1::2] * h ) )\n s += 2 * np.sum( f( a + i[2:-1:2] * h ) )\n \n return s * h / 3\n\ndef trapezoid(f, a, b, n):\n \"\"\"Approximates the definite integral of f from a to b by\n the composite trapezoidal rule, using n subintervals.\n From http://en.wikipedia.org/wiki/Trapezoidal_rule\n \n Args:\n f : function to integrate\n a,b : boundaries\n n : number of subintervals\n \n Return: integral\n \"\"\"\n h = (b - a) / n\n s = f(a) + f(b)\n i = np.arange(0,n)\n s += 2 * np.sum( f(a + i[1:] * h) )\n return s * h / 2\n\n\ndef adaptive_trapezoid(f, a, b, acc, output=False):\n \"\"\"\n Uses the adaptive trapezoidal method to compute the definite integral\n of f from a to b to desired accuracy acc. \n \n Args:\n f : function to integrate\n a,b : boundaries\n acc : desired accurarcy\n output : prints individual steps, default is False\n \n Return: integral\n \"\"\"\n old_s = np.inf\n h = b - a\n n = 1\n s = (f(a) + f(b)) * 0.5\n if output == True : \n print (\"N = \" + str(n+1) + \", Integral = \" + str( h*s ))\n while abs(h * (old_s - s*0.5)) > acc :\n old_s = s\n for i in np.arange(n) :\n s += f(a + (i + 0.5) * h)\n n *= 2.\n h *= 0.5\n if output == True :\n print (\"N = \" + str(n) + \", Integral = \" + str( h*s ))\n return h * s\n"
] |
[
[
"numpy.arange"
]
] |
ilivans/spaCy
|
[
"9ce059dd067ecc3f097d04023e3cfa0d70d35bb8"
] |
[
"spacy/tests/doc/test_token_api.py"
] |
[
"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport pytest\nimport numpy\nfrom spacy.attrs import IS_ALPHA, IS_DIGIT, IS_LOWER, IS_PUNCT, IS_TITLE, IS_STOP\nfrom spacy.symbols import VERB\nfrom spacy.vocab import Vocab\nfrom spacy.tokens import Doc\n\nfrom ..util import get_doc\n\n\[email protected]\ndef doc(en_tokenizer):\n # fmt: off\n text = \"This is a sentence. This is another sentence. And a third.\"\n heads = [1, 0, 1, -2, -3, 1, 0, 1, -2, -3, 0, 1, -2, -1]\n deps = [\"nsubj\", \"ROOT\", \"det\", \"attr\", \"punct\", \"nsubj\", \"ROOT\", \"det\",\n \"attr\", \"punct\", \"ROOT\", \"det\", \"npadvmod\", \"punct\"]\n # fmt: on\n tokens = en_tokenizer(text)\n return get_doc(tokens.vocab, words=[t.text for t in tokens], heads=heads, deps=deps)\n\n\ndef test_doc_token_api_strings(en_tokenizer):\n text = \"Give it back! He pleaded.\"\n pos = [\"VERB\", \"PRON\", \"PART\", \"PUNCT\", \"PRON\", \"VERB\", \"PUNCT\"]\n heads = [0, -1, -2, -3, 1, 0, -1]\n deps = [\"ROOT\", \"dobj\", \"prt\", \"punct\", \"nsubj\", \"ROOT\", \"punct\"]\n\n tokens = en_tokenizer(text)\n doc = get_doc(\n tokens.vocab, words=[t.text for t in tokens], pos=pos, heads=heads, deps=deps\n )\n assert doc[0].orth_ == \"Give\"\n assert doc[0].text == \"Give\"\n assert doc[0].text_with_ws == \"Give \"\n assert doc[0].lower_ == \"give\"\n assert doc[0].shape_ == \"Xxxx\"\n assert doc[0].prefix_ == \"G\"\n assert doc[0].suffix_ == \"ive\"\n assert doc[0].pos_ == \"VERB\"\n assert doc[0].dep_ == \"ROOT\"\n\n\ndef test_doc_token_api_flags(en_tokenizer):\n text = \"Give it back! He pleaded.\"\n tokens = en_tokenizer(text)\n assert tokens[0].check_flag(IS_ALPHA)\n assert not tokens[0].check_flag(IS_DIGIT)\n assert tokens[0].check_flag(IS_TITLE)\n assert tokens[1].check_flag(IS_LOWER)\n assert tokens[3].check_flag(IS_PUNCT)\n assert tokens[2].check_flag(IS_STOP)\n assert not tokens[5].check_flag(IS_STOP)\n # TODO: Test more of these, esp. if a bug is found\n\n\[email protected](\"text\", [\"Give it back! He pleaded.\"])\ndef test_doc_token_api_prob_inherited_from_vocab(en_tokenizer, text):\n word = text.split()[0]\n en_tokenizer.vocab[word].prob = -1\n tokens = en_tokenizer(text)\n assert tokens[0].prob != 0\n\n\[email protected](\"text\", [\"one two\"])\ndef test_doc_token_api_str_builtin(en_tokenizer, text):\n tokens = en_tokenizer(text)\n assert str(tokens[0]) == text.split(\" \")[0]\n assert str(tokens[1]) == text.split(\" \")[1]\n\n\ndef test_doc_token_api_is_properties(en_vocab):\n doc = Doc(en_vocab, words=[\"Hi\", \",\", \"my\", \"email\", \"is\", \"[email protected]\"])\n assert doc[0].is_title\n assert doc[0].is_alpha\n assert not doc[0].is_digit\n assert doc[1].is_punct\n assert doc[3].is_ascii\n assert not doc[3].like_url\n assert doc[4].is_lower\n assert doc[5].like_email\n\n\ndef test_doc_token_api_vectors():\n vocab = Vocab()\n vocab.reset_vectors(width=2)\n vocab.set_vector(\"apples\", vector=numpy.asarray([0.0, 2.0], dtype=\"f\"))\n vocab.set_vector(\"oranges\", vector=numpy.asarray([0.0, 1.0], dtype=\"f\"))\n doc = Doc(vocab, words=[\"apples\", \"oranges\", \"oov\"])\n assert doc.has_vector\n assert doc[0].has_vector\n assert doc[1].has_vector\n assert not doc[2].has_vector\n apples_norm = (0 * 0 + 2 * 2) ** 0.5\n oranges_norm = (0 * 0 + 1 * 1) ** 0.5\n cosine = ((0 * 0) + (2 * 1)) / (apples_norm * oranges_norm)\n assert doc[0].similarity(doc[1]) == cosine\n\n\ndef test_doc_token_api_ancestors(en_tokenizer):\n # the structure of this sentence depends on the English annotation scheme\n text = \"Yesterday I saw a dog that barked loudly.\"\n heads = [2, 1, 0, 1, -2, 1, -2, -1, -6]\n tokens = en_tokenizer(text)\n doc = get_doc(tokens.vocab, words=[t.text for t in tokens], heads=heads)\n assert [t.text for t in doc[6].ancestors] == [\"dog\", \"saw\"]\n assert [t.text for t in doc[1].ancestors] == [\"saw\"]\n assert [t.text for t in doc[2].ancestors] == []\n\n assert doc[2].is_ancestor(doc[7])\n assert not doc[6].is_ancestor(doc[2])\n\n\ndef test_doc_token_api_head_setter(en_tokenizer):\n # the structure of this sentence depends on the English annotation scheme\n text = \"Yesterday I saw a dog that barked loudly.\"\n heads = [2, 1, 0, 1, -2, 1, -2, -1, -6]\n tokens = en_tokenizer(text)\n doc = get_doc(tokens.vocab, words=[t.text for t in tokens], heads=heads)\n\n assert doc[6].n_lefts == 1\n assert doc[6].n_rights == 1\n assert doc[6].left_edge.i == 5\n assert doc[6].right_edge.i == 7\n\n assert doc[4].n_lefts == 1\n assert doc[4].n_rights == 1\n assert doc[4].left_edge.i == 3\n assert doc[4].right_edge.i == 7\n\n assert doc[3].n_lefts == 0\n assert doc[3].n_rights == 0\n assert doc[3].left_edge.i == 3\n assert doc[3].right_edge.i == 3\n\n assert doc[2].left_edge.i == 0\n assert doc[2].right_edge.i == 8\n\n doc[6].head = doc[3]\n\n assert doc[6].n_lefts == 1\n assert doc[6].n_rights == 1\n assert doc[6].left_edge.i == 5\n assert doc[6].right_edge.i == 7\n\n assert doc[3].n_lefts == 0\n assert doc[3].n_rights == 1\n assert doc[3].left_edge.i == 3\n assert doc[3].right_edge.i == 7\n\n assert doc[4].n_lefts == 1\n assert doc[4].n_rights == 0\n assert doc[4].left_edge.i == 3\n assert doc[4].right_edge.i == 7\n\n assert doc[2].left_edge.i == 0\n assert doc[2].right_edge.i == 8\n\n doc[0].head = doc[5]\n\n assert doc[5].left_edge.i == 0\n assert doc[6].left_edge.i == 0\n assert doc[3].left_edge.i == 0\n assert doc[4].left_edge.i == 0\n assert doc[2].left_edge.i == 0\n\n # head token must be from the same document\n doc2 = get_doc(tokens.vocab, words=[t.text for t in tokens], heads=heads)\n with pytest.raises(ValueError):\n doc[0].head = doc2[0]\n\n\ndef test_is_sent_start(en_tokenizer):\n doc = en_tokenizer(\"This is a sentence. This is another.\")\n assert doc[5].is_sent_start is None\n doc[5].is_sent_start = True\n assert doc[5].is_sent_start is True\n doc.is_parsed = True\n assert len(list(doc.sents)) == 2\n\ndef test_is_sent_end(en_tokenizer):\n doc = en_tokenizer(\"This is a sentence. This is another.\")\n assert doc[4].is_sent_end is None\n doc[5].is_sent_start = True\n assert doc[4].is_sent_end is True\n doc.is_parsed = True\n assert len(list(doc.sents)) == 2\n\n\ndef test_set_pos():\n doc = Doc(Vocab(), words=[\"hello\", \"world\"])\n doc[0].pos_ = \"NOUN\"\n assert doc[0].pos_ == \"NOUN\"\n doc[1].pos = VERB\n assert doc[1].pos_ == \"VERB\"\n\n\ndef test_tokens_sent(doc):\n \"\"\"Test token.sent property\"\"\"\n assert len(list(doc.sents)) == 3\n assert doc[1].sent.text == \"This is a sentence .\"\n assert doc[7].sent.text == \"This is another sentence .\"\n assert doc[1].sent.root.left_edge.text == \"This\"\n assert doc[7].sent.root.left_edge.text == \"This\"\n\n\ndef test_token0_has_sent_start_true():\n doc = Doc(Vocab(), words=[\"hello\", \"world\"])\n assert doc[0].is_sent_start is True\n assert doc[1].is_sent_start is None\n assert not doc.is_sentenced\n\ndef test_tokenlast_has_sent_end_true():\n doc = Doc(Vocab(), words=[\"hello\", \"world\"])\n assert doc[0].is_sent_end is None\n assert doc[1].is_sent_end is True\n assert not doc.is_sentenced\n\n\ndef test_token_api_conjuncts_chain(en_vocab):\n words = \"The boy and the girl and the man went .\".split()\n heads = [1, 7, -1, 1, -3, -1, 1, -3, 0, -1]\n deps = [\"det\", \"nsubj\", \"cc\", \"det\", \"conj\", \"cc\", \"det\", \"conj\", \"ROOT\", \"punct\"]\n doc = get_doc(en_vocab, words=words, heads=heads, deps=deps)\n assert [w.text for w in doc[1].conjuncts] == [\"girl\", \"man\"]\n assert [w.text for w in doc[4].conjuncts] == [\"boy\", \"man\"]\n assert [w.text for w in doc[7].conjuncts] == [\"boy\", \"girl\"]\n\n\ndef test_token_api_conjuncts_simple(en_vocab):\n words = \"They came and went .\".split()\n heads = [1, 0, -1, -2, -1]\n deps = [\"nsubj\", \"ROOT\", \"cc\", \"conj\", \"dep\"]\n doc = get_doc(en_vocab, words=words, heads=heads, deps=deps)\n assert [w.text for w in doc[1].conjuncts] == [\"went\"]\n assert [w.text for w in doc[3].conjuncts] == [\"came\"]\n\n\ndef test_token_api_non_conjuncts(en_vocab):\n words = \"They came .\".split()\n heads = [1, 0, -1]\n deps = [\"nsubj\", \"ROOT\", \"punct\"]\n doc = get_doc(en_vocab, words=words, heads=heads, deps=deps)\n assert [w.text for w in doc[0].conjuncts] == []\n assert [w.text for w in doc[1].conjuncts] == []\n"
] |
[
[
"numpy.asarray"
]
] |
neurospin/pySnpImpute
|
[
"133db33a43c9eb01b2538cb3f4e2f146d7e7a532"
] |
[
"pysnpimpute/utils.py"
] |
[
"# -*- coding: utf-8 -*-\n\n\"\"\"\nA set of common utility functions.\n\"\"\"\n\nimport os\nimport subprocess\nimport time\nimport argparse\nimport logging\nimport json\nimport glob\n\nfrom collections import OrderedDict\n\nimport numpy\nimport pandas\nimport pysnpimpute\n\nfrom pysnpimpute import (POSITIONS_OF_X_REGION_OF_BUILD,\n CENTROMERE_POSITIONS_OF_CHROMOSOME_OF_BUILD)\nfrom pysnpimpute.exceptions import (MissingSoftware,\n BadChromosomeName,\n BadGenomicBuildVersion,\n NotEnoughHaplotypes,\n AutosomeNotImputable)\n\n\ndef check_existence_of_paths(paths):\n \"\"\"\n Raise an exception if any of the path in 'paths' (file or dir) does\n not exist.\n \"\"\"\n for path in paths:\n if not os.path.exists(path):\n raise ValueError(\"File or directory does not exist: %s\" % path)\n\n\ndef check_chromosome_name(chromosome):\n \"\"\"\n Check that the chromosome name is handled.\n \"\"\"\n if chromosome not in pysnpimpute.CHROMOSOMES:\n raise BadChromosomeName(chromosome)\n\n\ndef check_genomic_build_version(genomic_build):\n \"\"\"\n Check that the passed <build_version> is handled.\n \"\"\"\n if genomic_build not in pysnpimpute.GENOMIC_BUILDS:\n raise BadGenomicBuildVersion(genomic_build)\n\n\ndef extract_chromosome(bfile, chromosome, build=None, outdir=None,\n basename=None, plink_exe=\"plink\", logger=None):\n \"\"\"\n Extract a chromosome or a X region from the dataset in Plink BED format.\n\n Parameters\n ----------\n chromosome: str\n Name of chromosome or X region to extract.\n Accepted names: \"1\", ..., \"22\", \"X_PAR1\", \"X_nonPAR\", \"X_PAR2\".\n bfile: str\n Path without extension to the dataset in PLINK BED format.\n build: str, default None\n Genomic build version of the <bfile> data (e.g. 'hg19'). Required if\n <chromosome> is a X region (the positions where to split depend of the\n genomic build).\n outdir: str, default None\n Path to directory where to output. By default in <bfile> directory.\n basename: str, default None\n Output filename without extension.\n By default input filename + \".<chromosome>\".\n plink_exe: str, default \"plink\"\n Path to the Plink executable or alias if it's in $PATH.\n logger: logging object, defaut None\n To activate logging, pass a logging object.\n \"\"\"\n\n # Check arguments and installation of required softwares\n check_chromosome_name(chromosome)\n if chromosome in pysnpimpute.X_REGIONS:\n check_genomic_build_version(build)\n check_installation_of_required_softwares(dict(Plink=plink_exe))\n\n # Output in <bfile> directory if <outdir> is not given.\n if outdir is None:\n outdir = os.path.dirname(bfile)\n\n # Check existence of input files\n paths_to_check = [bfile + \".bed\", bfile + \".bim\", bfile + \".fam\", outdir]\n check_existence_of_paths(paths_to_check)\n\n if basename is None:\n basename = os.path.basename(bfile) + \".chr%s\" % chromosome\n\n plink_chrom = \"X\" if chromosome in pysnpimpute.X_REGIONS else chromosome\n bfile_chrom = os.path.join(outdir, basename)\n cmd = [plink_exe,\n \"--bfile\", bfile,\n \"--chr\", plink_chrom,\n \"--make-bed\",\n \"--out\", bfile_chrom,\n \"--noweb\"]\n\n # If the chromosome is a X region, add the positions where to cut\n if chromosome in pysnpimpute.X_REGIONS:\n from_bp, to_bp = POSITIONS_OF_X_REGION_OF_BUILD[build][chromosome]\n cmd += [\"--from-bp\", str(from_bp), \"--to-bp\", str(to_bp)]\n\n # Run command with 'run_cmd' and not with 'run_cmd_and_check'\n # We check after the run if there are variants left\n run_cmd(cmd, logger=logger)\n\n # Determine the number of variants left: nb of lines of the .bim file\n path_bim = bfile_chrom + \".bim\"\n if os.path.isfile(path_bim):\n with open(path_bim) as f:\n nb_variants_left = sum(1 for _ in f)\n else:\n nb_variants_left = 0\n bfile_chrom = None\n\n return bfile_chrom, nb_variants_left\n\n\ndef chunk_positions(region, known_hap_positions, ref_panel_positions,\n chunksize_kb, N):\n \"\"\"\n Take 2 lists of positions, known and ref panel variant positions, and\n compute intervals that define chunks.\n These chunks should:\n - not overlap\n - contain all haplotype positions\n - have at least <N> known haplotypes\n - have a minimum size of <chunksize_kb> in Kb (NOT IN BASEPAIR)\n\n region: name of the region being chunked. Used to generate clear errors.\n e.g. 'first arm of chr1', 'X_PAR1' etc\n \"\"\"\n\n # Convert chunksize (Kb) to basepair\n chunksize = chunksize_kb * 1000\n\n known_hap_positions = numpy.asarray(known_hap_positions)\n ref_panel_positions = numpy.asarray(ref_panel_positions)\n\n nb_known_hap = len(known_hap_positions)\n if nb_known_hap < N:\n raise NotEnoughHaplotypes(region=region, nb_known=nb_known_hap,\n nb_required=N)\n\n # List of chunks, a chunk is a couple: (<start>, <end>)\n chunks = []\n ref_counts = []\n hap_counts = []\n\n while len(ref_panel_positions) > 0:\n\n start = ref_panel_positions[0]\n end = max(known_hap_positions[N-1], start + chunksize - 1)\n\n # Count the number of hap and ref hap in the chunk\n nb_hap = len(known_hap_positions[known_hap_positions <= end])\n nb_ref = len(ref_panel_positions[ref_panel_positions <= end])\n\n # Left to chunk\n ref_panel_positions = ref_panel_positions[ref_panel_positions > end]\n known_hap_positions = known_hap_positions[known_hap_positions > end]\n\n # If there is not enough variants left to create another chunk\n # merge with the current chunk\n nb_hap_left = len(known_hap_positions)\n nb_ref_left = len(ref_panel_positions)\n interval_left = ref_panel_positions[-1] - ref_panel_positions[0]\n if nb_hap_left < N or interval_left < chunksize:\n end = ref_panel_positions[-1]\n ref_panel_positions = []\n nb_hap += nb_hap_left\n nb_ref += nb_ref_left\n\n chunk = (start, end)\n chunks += [chunk]\n hap_counts += [nb_hap]\n ref_counts += [nb_ref]\n\n return chunks, hap_counts, ref_counts\n\n\ndef chromosome_segmentation(chromosome, known_hap, ref_legend, build,\n chunksize_kb=5000, N=200, logger=None):\n \"\"\"\n Compute intervals that define chromosome chunks to impute separately.\n These chunks should:\n - not overlap\n - contain all haplotype positions\n - not overlap with the centromere region of the chromosome\n - have at least <N> known haplotypes\n - have a minimum size of <chunksize_kb> Kb (NOT IN BASEPAIR)\n \"\"\"\n\n # Check input arguments\n check_chromosome_name(chromosome)\n check_genomic_build_version(build)\n check_existence_of_paths([known_hap, ref_legend])\n\n # Load the positions of the known haplotypes\n df_hap = pandas.read_csv(known_hap, sep=\" \", usecols=[2], header=None,\n names=[\"pos\"])\n\n # Load the positions of the reference haplotypes\n df_ref = pandas.read_csv(ref_legend, sep=\" \", usecols=[1], header=0,\n names=[\"pos\"])\n\n # For the X regions X_PAR1 and X_PAR2 there are no centromere to handle\n # The chunking is simpler.\n if chromosome in {pysnpimpute.X_PAR1, pysnpimpute.X_PAR2}:\n chunks, known_hap_counts, ref_hap_counts = \\\n chunk_positions(chromosome, df_hap[\"pos\"].tolist(),\n df_ref[\"pos\"].tolist(), chunksize_kb, N)\n\n else:\n # For chromosome or regions where there is a centromere to handle,\n # chunking is done separately for both sides of the centromere.\n\n # Start and end positions of the centromere\n # chromosome structure: arm 1 | centromere | arm 2\n c_start, c_end = \\\n CENTROMERE_POSITIONS_OF_CHROMOSOME_OF_BUILD[build][chromosome]\n\n # Dicts: Map <arm> -> list of haplotype positions\n known_hap_pos_of_arm = {\n \"arm 1\": df_hap[df_hap[\"pos\"] < c_start][\"pos\"].tolist(),\n \"arm 2\": df_hap[df_hap[\"pos\"] > c_end][\"pos\"].tolist()\n }\n\n ref_hap_pos_of_arm = {\n \"arm 1\": df_ref[df_ref[\"pos\"] < c_start][\"pos\"].tolist(),\n \"arm 2\": df_ref[df_ref[\"pos\"] > c_end][\"pos\"].tolist()\n }\n\n # Chunk both sides of the centromere separately\n\n # List to accumulate chunks and known/ref haplotype counts\n chunks, known_hap_counts, ref_hap_counts = [], [], []\n\n for arm in known_hap_pos_of_arm:\n region = \"%s of chromosome %s\" % (chromosome, arm)\n try:\n arm_chunks, arm_known_hap_counts, arm_ref_hap_counts = \\\n chunk_positions(region, known_hap_pos_of_arm[arm],\n ref_hap_pos_of_arm[arm], chunksize_kb, N)\n chunks.extend(arm_chunks)\n known_hap_counts.extend(arm_known_hap_counts)\n ref_hap_counts.extend(arm_ref_hap_counts)\n\n except NotEnoughHaplotypes as e:\n if logger is not None:\n logger.error(e.message)\n\n # If none of the chromosome arms have enough haplotypes\n if len(chunks) == 0:\n raise AutosomeNotImputable(chromosome)\n\n return chunks, known_hap_counts, ref_hap_counts\n\n\ndef load_ref_panel_description(ref_panel):\n \"\"\"\n Load the reference panel table as a Pandas DataFrame.\n\n Parameters\n ----------\n ref_panel: str\n Path to the table file describing the reference panel.\n It relates a chromosome name to 4 references files in Impute2 format:\n - reference haplotyples\n - reference legend\n - reference samples\n - recombination map\n The paths can be absolute or relative to the table file.\n File structure: one row per chromosome, tab-separated fields:\n <CHROM> <REF HAP> <REF LEGEND> <REF SAMPLE> <RECOMBINATION MAP>\n Only the following chromosome names are accepted:\n '1', ..., '22', 'X_PAR1', 'X_nonPAR' and 'X_PAR2'\n\n Return\n ------\n df_ref_panel: Pandas DataFrame, maps the 4 reference files for each chrom.\n \"\"\"\n\n # Load the ref_panel txt file\n path_cols = [\"ref_hap\", \"ref_legend\", \"ref_sample\", \"recombination_map\"]\n df_ref_panel = pandas.read_csv(ref_panel, header=None, sep=\"\\t\", dtype=str,\n names=[\"chrom\"] + path_cols, index_col=0)\n # Force index to be of type str\n df_ref_panel.index = df_ref_panel.index.astype(str)\n\n # If the paths are relative, replace with absolute paths\n ref_dir = os.path.dirname(os.path.abspath(ref_panel))\n to_abs_path = lambda p: p if os.path.isabs(p) else os.path.join(ref_dir, p)\n df_ref_panel[path_cols] = df_ref_panel[path_cols].applymap(to_abs_path)\n\n return df_ref_panel\n\n\ndef create_phased_dataset_description(phasing_outdir):\n \"\"\"\n Create a \"phased_dataset.txt\" file in <phasing_outdir> mapping the paths\n to the phased data files to the corresponding chromosome names and sample\n files.\n It serves as input to the hopla_imputation.py script.\n \"\"\"\n\n path_desc = os.path.join(phasing_outdir, \"phased_dataset.txt\")\n with open(path_desc, \"w\") as f:\n for c in pysnpimpute.ORDERED_CHROMOSOMES:\n regex = os.path.join(phasing_outdir, \"chr%s/*.phased.hap.gz\" % c)\n paths = glob.glob(regex)\n\n if len(paths) == 0:\n continue\n if len(paths) > 1:\n raise ValueError(\"Multiple files maching %s .\" % regex)\n\n _, name_hap = os.path.split(paths[0])\n name_sample = name_hap[:-len(\".hap.gz\")] + \".sample\"\n\n l = [c, \"chr%s/%s\" % (c, name_hap), \"chr%s/%s\" % (c, name_sample)]\n f.write(\"\\t\".join(l) + \"\\n\")\n\n return path_desc\n\n\ndef load_phased_dataset_description(phased_dataset):\n \"\"\"\n Load the phased dataset table file as a Pandas DataFrame.\n\n Parameters\n ----------\n phased_dataset: str\n Path the table file describing the phased data to impute.\n It relates a chromosome name to 2 files:\n - phased haplotypes to impute in Impute2 format\n - samples to impute in Impute2 format\n The paths can be absolute or relative to the table file.\n File structure: one row per chromosome, tab-separated fields:\n <CHROM> <HAP> <SAMPLE>\n Only the following chromosome names are accepted:\n '1', ..., '22', 'X_PAR1', 'X_nonPAR' and 'X_PAR2'\n \"\"\"\n # Load the ref_panel txt file\n path_cols = [\"hap\", \"sample\"]\n df_dataset = pandas.read_csv(phased_dataset, header=None, sep=\"\\t\",\n dtype=str, names=[\"chrom\"] + path_cols,\n index_col=0)\n # Force index to be of type str\n df_dataset.index = df_dataset.index.astype(str)\n\n # If the paths are relative, replace with absolute paths\n ref_dir = os.path.dirname(os.path.abspath(phased_dataset))\n to_abs_path = lambda p: p if os.path.isabs(p) else os.path.join(ref_dir, p)\n df_dataset[path_cols] = df_dataset[path_cols].applymap(to_abs_path)\n\n return df_dataset\n\n\ndef is_file(filepath):\n \"\"\" Check file's existence. Used as 'type' with the argparse module.\n \"\"\"\n if not os.path.isfile(filepath):\n raise argparse.ArgumentError(\"File does not exist: %s\" % filepath)\n return filepath\n\n\ndef is_dir(dirpath):\n \"\"\" Check direcory's existence - argparse 'type' argument.\n \"\"\"\n if not os.path.isdir(dirpath):\n raise argparse.ArgumentError(\"Directory does not exist: %s\" % dirpath)\n return dirpath\n\n\ndef run_cmd(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, logger=None):\n \"\"\"\n cmd: list of str\n Subprocess-like command, e.g. [\"ls\", \"-l\"]\n \"\"\"\n # Command as a string for logging\n str_cmd = \" \".join(cmd)\n\n if logger is not None:\n logger.info('cmd = \"%s\"' % str_cmd)\n\n start = time.strftime(\"%Y-%m-%d_%H:%M:%S\")\n process = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)\n cout, cerr = process.communicate()\n exitcode = process.returncode\n end = time.strftime(\"%Y-%m-%d_%H:%M:%S\")\n\n # Error message is stored as a list of lines\n stderr_lines = cerr.split(\"\\n\")\n\n couples = [(\"cmd\", str_cmd), (\"exitcode\", exitcode),\n (\"start\", start), (\"end\", end), (\"stderr\", stderr_lines)]\n exec_metadata = OrderedDict(couples)\n\n if logger is not None:\n logger.info(\"exec_metadata = %s\" % json.dumps(exec_metadata, indent=4))\n\n return exec_metadata\n\n\ndef run_cmd_and_check(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n logger=None):\n \"\"\"\n cmd: list of str\n Subprocess-like command, e.g. [\"ls\", \"-l\"]\n \"\"\"\n exec_metadata = run_cmd(cmd, stdout=stdout, stderr=stderr, logger=logger)\n\n if exec_metadata[\"exitcode\"] != 0:\n raise Exception(\"Command failed: {} .\".format(\" \".join(cmd)))\n\n\ndef check_installation_of_required_softwares(exe_of_software):\n \"\"\"\n Parameters\n ----------\n exe_of_software: dict\n Map name of required software to the path or alias of the executable.\n An alias is enough if the executable is in the $PATH.\n\n Raise an exception if at least one the executable is not available.\n \"\"\"\n for software_name in exe_of_software:\n exe_path_or_alias = exe_of_software[software_name]\n exec_metadata = run_cmd([\"which\", exe_path_or_alias])\n\n if exec_metadata[\"exitcode\"] != 0:\n raise MissingSoftware(software_name, exe_path_or_alias)\n\n\ndef create_logger(prefix, log_dir=None, logger_name=None):\n \"\"\"\n Create a logger with console logging (info level) + log file (debug level).\n If log_dir is None then logging directory is current directory.\n\n Log path is <log_dir>/<prefix>_%Y-%m-%d_%H:%M:%S.log\n \"\"\"\n\n if logger_name is None:\n logger_name = __name__\n\n logger = logging.getLogger(logger_name)\n\n # Stop here if logger already has handlers\n if len(logger.handlers) != 0:\n return logger\n\n logger.setLevel(logging.DEBUG)\n\n # Log path\n log_filename = \"%s_%s.log\" % (prefix, time.strftime(\"%Y-%m-%d_%H:%M:%S\"))\n if log_dir is not None:\n log_path = os.path.join(log_dir, log_filename)\n else:\n log_path = log_filename\n\n # File logger\n file_handler = logging.FileHandler(log_path)\n formatter = logging.Formatter('%(message)s')\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.DEBUG)\n logger.addHandler(file_handler)\n\n # Console logger\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.INFO)\n console_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n\n logger.info(\"Path to log file: %s\" % log_path)\n\n return logger\n"
] |
[
[
"numpy.asarray",
"pandas.read_csv"
]
] |
Danderson123/snip-public
|
[
"e464ffed8b76a102ae485ab12b44f0f3b5314ce4"
] |
[
"snip/network.py"
] |
[
"import tensorflow as tf\n\nfrom functools import reduce\nfrom helpers import static_size\n\n\ndef load_network(\n datasource, arch, num_classes,\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap,\n ):\n networks = {\n 'lenet300': lambda: LeNet300(\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap,\n ),\n 'lenet5': lambda: LeNet5(\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap),\n 'alexnet-v1': lambda: AlexNet(\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap,\n datasource, num_classes, k=1),\n 'alexnet-v2': lambda: AlexNet(\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap,\n datasource, num_classes, k=2),\n 'vgg-c': lambda: VGG(\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap,\n datasource, num_classes, version='C'),\n 'vgg-d': lambda: VGG(\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap,\n datasource, num_classes, version='D'),\n 'vgg-like': lambda: VGG(\n initializer_w_bp, initializer_b_bp, initializer_w_ap, initializer_b_ap,\n datasource, num_classes, version='like'),\n }\n return networks[arch]()\n\n\ndef get_initializer(initializer, dtype):\n if initializer == 'zeros':\n return tf.zeros_initializer(dtype=dtype)\n elif initializer == 'vs':\n return tf.variance_scaling_initializer(dtype=dtype)\n else:\n raise NotImplementedError\n\n\nclass LeNet300(object):\n def __init__(self,\n initializer_w_bp,\n initializer_b_bp,\n initializer_w_ap,\n initializer_b_ap,\n ):\n self.name = 'lenet300'\n self.input_dims = [28, 28, 1] # height, width, channel\n self.inputs = self.construct_inputs()\n self.weights_bp = self.construct_weights(initializer_w_bp, initializer_b_bp, False, 'bp')\n self.weights_ap = self.construct_weights(initializer_w_ap, initializer_b_ap, True, 'ap')\n self.num_params = sum([static_size(v) for v in self.weights_ap.values()])\n\n def construct_inputs(self):\n return {\n 'input': tf.placeholder(tf.float32, [None] + self.input_dims),\n 'label': tf.placeholder(tf.int32, [None]),\n }\n\n def construct_weights(self, initializer_w, initializer_b, trainable, scope):\n dtype = tf.float32\n w_params = {\n 'initializer': get_initializer(initializer_w, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n b_params = {\n 'initializer': get_initializer(initializer_b, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n weights = {}\n with tf.variable_scope(scope):\n weights['w1'] = tf.get_variable('w1', [784, 300], **w_params)\n weights['w2'] = tf.get_variable('w2', [300, 100], **w_params)\n weights['w3'] = tf.get_variable('w3', [100, 10], **w_params)\n weights['b1'] = tf.get_variable('b1', [300], **b_params)\n weights['b2'] = tf.get_variable('b2', [100], **b_params)\n weights['b3'] = tf.get_variable('b3', [10], **b_params)\n return weights\n\n def forward_pass(self, weights, inputs, is_train, trainable=True):\n inputs_flat = tf.reshape(inputs, [-1, reduce(lambda x, y: x*y, inputs.shape.as_list()[1:])])\n fc1 = tf.matmul(inputs_flat, weights['w1']) + weights['b1']\n fc1 = tf.nn.relu(fc1)\n fc2 = tf.matmul(fc1, weights['w2']) + weights['b2']\n fc2 = tf.nn.relu(fc2)\n fc3 = tf.matmul(fc2, weights['w3']) + weights['b3']\n return fc3\n\n\nclass LeNet5(object):\n def __init__(self,\n initializer_w_bp,\n initializer_b_bp,\n initializer_w_ap,\n initializer_b_ap,\n ):\n self.name = 'lenet5'\n self.input_dims = [28, 28, 1] # height, width, channel\n self.inputs = self.construct_inputs()\n self.weights_bp = self.construct_weights(initializer_w_bp, initializer_b_bp, False, 'bp')\n self.weights_ap = self.construct_weights(initializer_w_ap, initializer_b_ap, True, 'ap')\n self.num_params = sum([static_size(v) for v in self.weights_ap.values()])\n\n def construct_inputs(self):\n return {\n 'input': tf.placeholder(tf.float32, [None] + self.input_dims),\n 'label': tf.placeholder(tf.int32, [None]),\n }\n\n def construct_weights(self, initializer_w, initializer_b, trainable, scope):\n dtype = tf.float32\n w_params = {\n 'initializer': get_initializer(initializer_w, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n b_params = {\n 'initializer': get_initializer(initializer_b, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n weights = {}\n with tf.variable_scope(scope):\n weights['w1'] = tf.get_variable('w1', [5, 5, 1, 20], **w_params)\n weights['w2'] = tf.get_variable('w2', [5, 5, 20, 50], **w_params)\n weights['w3'] = tf.get_variable('w3', [800, 500], **w_params)\n weights['w4'] = tf.get_variable('w4', [500, 10], **w_params)\n weights['b1'] = tf.get_variable('b1', [20], **b_params)\n weights['b2'] = tf.get_variable('b2', [50], **b_params)\n weights['b3'] = tf.get_variable('b3', [500], **b_params)\n weights['b4'] = tf.get_variable('b4', [10], **b_params)\n return weights\n\n def forward_pass(self, weights, inputs, is_train, trainable=True):\n conv1 = tf.nn.conv2d(inputs, weights['w1'], [1, 1, 1, 1], 'VALID') + weights['b1']\n pool1 = tf.nn.max_pool(conv1, [1, 2, 2, 1], [1, 2, 2, 1], 'VALID')\n conv2 = tf.nn.conv2d(pool1, weights['w2'], [1, 1, 1, 1], 'VALID') + weights['b2']\n pool2 = tf.nn.max_pool(conv2, [1, 2, 2, 1], [1, 2, 2, 1], 'VALID')\n flatten = tf.reshape(pool2, [-1, reduce(lambda x, y: x*y, pool2.shape.as_list()[1:])])\n fc1 = tf.matmul(flatten, weights['w3']) + weights['b3']\n fc1 = tf.nn.relu(fc1)\n fc2 = tf.matmul(fc1, weights['w4']) + weights['b4'] # logits\n return fc2\n\n\nclass AlexNet(object):\n ''' Similar to Alexnet in terms of the total number of conv and fc layers.\n\n Conv layers:\n The size of kernels and the number of conv filters are the same as the original.\n Due to the smaller input size (CIFAR rather than IMAGENET) we use different strides.\n FC layers:\n The size of fc layers are controlled by k (multiplied by 1024).\n In the original Alexnet, k=4 making the size of largest fc layers to be 4096.\n '''\n def __init__(self,\n initializer_w_bp,\n initializer_b_bp,\n initializer_w_ap,\n initializer_b_ap,\n datasource,\n num_classes,\n k,\n ):\n self.datasource = datasource\n self.num_classes = num_classes\n self.k = k\n self.name = 'alexnet'\n self.input_dims = [64, 64, 3] if self.datasource == 'tiny-imagenet' else [32, 32, 3] # h,w,c\n self.inputs = self.construct_inputs()\n self.weights_bp = self.construct_weights(initializer_w_bp, initializer_b_bp, False, 'bp')\n self.weights_ap = self.construct_weights(initializer_w_ap, initializer_b_ap, True, 'ap')\n self.num_params = sum([static_size(v) for v in self.weights_ap.values()])\n\n def construct_inputs(self):\n return {\n 'input': tf.placeholder(tf.float32, [None] + self.input_dims),\n 'label': tf.placeholder(tf.int32, [None]),\n }\n\n def construct_weights(self, initializer_w, initializer_b, trainable, scope):\n dtype = tf.float32\n w_params = {\n 'initializer': get_initializer(initializer_w, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n b_params = {\n 'initializer': get_initializer(initializer_b, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n k = self.k\n weights = {}\n with tf.variable_scope(scope):\n weights['w1'] = tf.get_variable('w1', [11, 11, 3, 96], **w_params)\n weights['w2'] = tf.get_variable('w2', [5, 5, 96, 256], **w_params)\n weights['w3'] = tf.get_variable('w3', [3, 3, 256, 384], **w_params)\n weights['w4'] = tf.get_variable('w4', [3, 3, 384, 384], **w_params)\n weights['w5'] = tf.get_variable('w5', [3, 3, 384, 256], **w_params)\n weights['w6'] = tf.get_variable('w6', [256, 1024*k], **w_params)\n weights['w7'] = tf.get_variable('w7', [1024*k, 1024*k], **w_params)\n weights['w8'] = tf.get_variable('w8', [1024*k, self.num_classes], **w_params)\n weights['b1'] = tf.get_variable('b1', [96], **b_params)\n weights['b2'] = tf.get_variable('b2', [256], **b_params)\n weights['b3'] = tf.get_variable('b3', [384], **b_params)\n weights['b4'] = tf.get_variable('b4', [384], **b_params)\n weights['b5'] = tf.get_variable('b5', [256], **b_params)\n weights['b6'] = tf.get_variable('b6', [1024*k], **b_params)\n weights['b7'] = tf.get_variable('b7', [1024*k], **b_params)\n weights['b8'] = tf.get_variable('b8', [self.num_classes], **b_params)\n return weights\n\n def forward_pass(self, weights, inputs, is_train, trainable=True):\n bn_params = {\n 'training': is_train,\n 'trainable': trainable,\n }\n init_st = 4 if self.datasource == 'tiny-imagenet' else 2\n inputs = tf.nn.conv2d(inputs, weights['w1'], [1,init_st,init_st,1], 'SAME') + weights['b1']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.nn.conv2d(inputs, weights['w2'], [1, 2, 2, 1], 'SAME') + weights['b2']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.nn.conv2d(inputs, weights['w3'], [1, 2, 2, 1], 'SAME') + weights['b3']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.nn.conv2d(inputs, weights['w4'], [1, 2, 2, 1], 'SAME') + weights['b4']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.nn.conv2d(inputs, weights['w5'], [1, 2, 2, 1], 'SAME') + weights['b5']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.reshape(inputs, [-1, reduce(lambda x, y: x*y, inputs.shape.as_list()[1:])])\n inputs = tf.matmul(inputs, weights['w6']) + weights['b6']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.matmul(inputs, weights['w7']) + weights['b7']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.matmul(inputs, weights['w8']) + weights['b8'] # logits\n return inputs\n\n\nclass VGG(object):\n '''\n Similar to the original VGG.\n Available models:\n - VGG-C\n - VGG-D\n - VGG-like\n\n Differences:\n The number of parameters in conv layers are the same as the original.\n The number of parameters in fc layers are reduced to 512 (4096 -> 512).\n The number of total parameters are different, not just because of the size of fc layers,\n but also due to the fact that the first fc layer receives 1x1 image rather than 7x7 image\n because the input is CIFAR not IMAGENET.\n No dropout is used. Instead, batch norm is used.\n\n Other refereneces.\n (1) The original paper:\n - paper: https://arxiv.org/pdf/1409.1556.pdf\n - code: http://www.robots.ox.ac.uk/~vgg/research/very_deep/\n * Dropout between fc layers.\n * There is no BatchNorm.\n (2) VGG-like by Zagoruyko, adapted for CIFAR-10.\n - project and code: http://torch.ch/blog/2015/07/30/cifar.html\n * Differences to the original VGG-16 (1):\n - # of fc layers 3 -> 2, so there are 15 (learnable) layers in total.\n - size of fc layers 4096 -> 512.\n - use BatchNorm and add more Dropout.\n '''\n def __init__(self,\n initializer_w_bp,\n initializer_b_bp,\n initializer_w_ap,\n initializer_b_ap,\n datasource,\n num_classes,\n version,\n ):\n self.datasource = datasource\n self.num_classes = num_classes\n self.version = version\n self.name = 'VGG-{}'.format(version)\n self.input_dims = [64, 64, 3] if self.datasource == 'tiny-imagenet' else [32, 32, 3] # h,w,c\n self.inputs = self.construct_inputs()\n self.weights_bp = self.construct_weights(initializer_w_bp, initializer_b_bp, False, 'bp')\n self.weights_ap = self.construct_weights(initializer_w_ap, initializer_b_ap, True, 'ap')\n self.num_params = sum([static_size(v) for v in self.weights_ap.values()])\n\n def construct_inputs(self):\n return {\n 'input': tf.placeholder(tf.float32, [None] + self.input_dims),\n 'label': tf.placeholder(tf.int32, [None]),\n }\n\n def construct_weights(self, initializer_w, initializer_b, trainable, scope):\n dtype = tf.float32\n w_params = {\n 'initializer': get_initializer(initializer_w, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n b_params = {\n 'initializer': get_initializer(initializer_b, dtype),\n 'dtype': dtype,\n 'trainable': trainable,\n 'collections': [self.name, tf.GraphKeys.GLOBAL_VARIABLES],\n }\n weights = {}\n with tf.variable_scope(scope):\n weights['w1'] = tf.get_variable('w1', [3, 3, 3, 64], **w_params)\n weights['w2'] = tf.get_variable('w2', [3, 3, 64, 64], **w_params)\n weights['w3'] = tf.get_variable('w3', [3, 3, 64, 128], **w_params)\n weights['w4'] = tf.get_variable('w4', [3, 3, 128, 128], **w_params)\n weights['b1'] = tf.get_variable('b1', [64], **b_params)\n weights['b2'] = tf.get_variable('b2', [64], **b_params)\n weights['b3'] = tf.get_variable('b3', [128], **b_params)\n weights['b4'] = tf.get_variable('b4', [128], **b_params)\n if self.version == 'C':\n weights['w5'] = tf.get_variable('w5', [3, 3, 128, 256], **w_params)\n weights['w6'] = tf.get_variable('w6', [3, 3, 256, 256], **w_params)\n weights['w7'] = tf.get_variable('w7', [1, 1, 256, 256], **w_params)\n weights['w8'] = tf.get_variable('w8', [3, 3, 256, 512], **w_params)\n weights['w9'] = tf.get_variable('w9', [3, 3, 512, 512], **w_params)\n weights['w10'] = tf.get_variable('w10', [1, 1, 512, 512], **w_params)\n weights['w11'] = tf.get_variable('w11', [3, 3, 512, 512], **w_params)\n weights['w12'] = tf.get_variable('w12', [3, 3, 512, 512], **w_params)\n weights['w13'] = tf.get_variable('w13', [1, 1, 512, 512], **w_params)\n weights['b5'] = tf.get_variable('b5', [256], **b_params)\n weights['b6'] = tf.get_variable('b6', [256], **b_params)\n weights['b7'] = tf.get_variable('b7', [256], **b_params)\n weights['b8'] = tf.get_variable('b8', [512], **b_params)\n weights['b9'] = tf.get_variable('b9', [512], **b_params)\n weights['b10'] = tf.get_variable('b10', [512], **b_params)\n weights['b11'] = tf.get_variable('b11', [512], **b_params)\n weights['b12'] = tf.get_variable('b12', [512], **b_params)\n weights['b13'] = tf.get_variable('b13', [512], **b_params)\n elif self.version == 'D' or self.version == 'like':\n weights['w5'] = tf.get_variable('w5', [3, 3, 128, 256], **w_params)\n weights['w6'] = tf.get_variable('w6', [3, 3, 256, 256], **w_params)\n weights['w7'] = tf.get_variable('w7', [3, 3, 256, 256], **w_params)\n weights['w8'] = tf.get_variable('w8', [3, 3, 256, 512], **w_params)\n weights['w9'] = tf.get_variable('w9', [3, 3, 512, 512], **w_params)\n weights['w10'] = tf.get_variable('w10', [3, 3, 512, 512], **w_params)\n weights['w11'] = tf.get_variable('w11', [3, 3, 512, 512], **w_params)\n weights['w12'] = tf.get_variable('w12', [3, 3, 512, 512], **w_params)\n weights['w13'] = tf.get_variable('w13', [3, 3, 512, 512], **w_params)\n weights['b5'] = tf.get_variable('b5', [256], **b_params)\n weights['b6'] = tf.get_variable('b6', [256], **b_params)\n weights['b7'] = tf.get_variable('b7', [256], **b_params)\n weights['b8'] = tf.get_variable('b8', [512], **b_params)\n weights['b9'] = tf.get_variable('b9', [512], **b_params)\n weights['b10'] = tf.get_variable('b10', [512], **b_params)\n weights['b11'] = tf.get_variable('b11', [512], **b_params)\n weights['b12'] = tf.get_variable('b12', [512], **b_params)\n weights['b13'] = tf.get_variable('b13', [512], **b_params)\n weights['w14'] = tf.get_variable('w14', [512, 512], **w_params)\n weights['b14'] = tf.get_variable('b14', [512], **b_params)\n if not self.version == 'like':\n weights['w15'] = tf.get_variable('w15', [512, 512], **w_params)\n weights['w16'] = tf.get_variable('w16', [512, self.num_classes], **w_params)\n weights['b15'] = tf.get_variable('b15', [512], **b_params)\n weights['b16'] = tf.get_variable('b16', [self.num_classes], **b_params)\n else:\n weights['w15'] = tf.get_variable('w15', [512, self.num_classes], **w_params)\n weights['b15'] = tf.get_variable('b15', [self.num_classes], **b_params)\n return weights\n\n def forward_pass(self, weights, inputs, is_train, trainable=True):\n def _conv_block(inputs, bn_params, filt, st=1):\n inputs = tf.nn.conv2d(inputs, filt['w'], [1, st, st, 1], 'SAME') + filt['b']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n return inputs\n\n bn_params = {\n 'training': is_train,\n 'trainable': trainable,\n }\n init_st = 2 if self.datasource == 'tiny-imagenet' else 1\n\n inputs = _conv_block(inputs, bn_params, {'w': weights['w1'], 'b': weights['b1']}, init_st)\n inputs = _conv_block(inputs, bn_params, {'w': weights['w2'], 'b': weights['b2']})\n inputs = tf.nn.max_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n inputs = _conv_block(inputs, bn_params, {'w': weights['w3'], 'b': weights['b3']})\n inputs = _conv_block(inputs, bn_params, {'w': weights['w4'], 'b': weights['b4']})\n inputs = tf.nn.max_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n inputs = _conv_block(inputs, bn_params, {'w': weights['w5'], 'b': weights['b5']})\n inputs = _conv_block(inputs, bn_params, {'w': weights['w6'], 'b': weights['b6']})\n inputs = _conv_block(inputs, bn_params, {'w': weights['w7'], 'b': weights['b7']})\n inputs = tf.nn.max_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n inputs = _conv_block(inputs, bn_params, {'w': weights['w8'], 'b': weights['b8']})\n inputs = _conv_block(inputs, bn_params, {'w': weights['w9'], 'b': weights['b9']})\n inputs = _conv_block(inputs, bn_params, {'w': weights['w10'], 'b': weights['b10']})\n inputs = tf.nn.max_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n inputs = _conv_block(inputs, bn_params, {'w': weights['w11'], 'b': weights['b11']})\n inputs = _conv_block(inputs, bn_params, {'w': weights['w12'], 'b': weights['b12']})\n inputs = _conv_block(inputs, bn_params, {'w': weights['w13'], 'b': weights['b13']})\n inputs = tf.nn.max_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')\n\n assert reduce(lambda x, y: x*y, inputs.shape.as_list()[1:3]) == 1\n\n inputs = tf.reshape(inputs, [-1, reduce(lambda x, y: x*y, inputs.shape.as_list()[1:])])\n inputs = tf.matmul(inputs, weights['w14']) + weights['b14']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n if not self.version == 'like':\n inputs = tf.matmul(inputs, weights['w15']) + weights['b15']\n inputs = tf.layers.batch_normalization(inputs, **bn_params)\n inputs = tf.nn.relu(inputs)\n inputs = tf.matmul(inputs, weights['w16']) + weights['b16']\n else:\n inputs = tf.matmul(inputs, weights['w15']) + weights['b15']\n\n return inputs\n"
] |
[
[
"tensorflow.nn.relu",
"tensorflow.get_variable",
"tensorflow.matmul",
"tensorflow.layers.batch_normalization",
"tensorflow.nn.max_pool",
"tensorflow.zeros_initializer",
"tensorflow.placeholder",
"tensorflow.variance_scaling_initializer",
"tensorflow.variable_scope",
"tensorflow.nn.conv2d"
]
] |
JGoutin/skio
|
[
"6c6e433232eca7371b0e9d94b8a75354dae7adab"
] |
[
"skio/group.py"
] |
[
"\"\"\"'Group' dict-like class definition\"\"\"\n# TODO:\n# - Find how show parameters and doc-strings for .set()/.get().\n# - Orderable Group.\n# - Autocomplete __doc__ with _doc, _dtype, ... information for subclasses.\n# - Add unit information support with optional support of \"pint\" package.\n# store data in group values without unit (and convert on get or set)\n# - Support for data sample/uncertainty.\n# - Add _dtype arguments for numpy: shape (Fixed, min, max)\n# - Add _dtype arguments for pandas: nbcols, nbrows (Fixed, min, max)\n# - Custom _dtype args\n# - Write public name (\"Group.get(key, ...)\") in errors on advanced functions\n# produced by _customfunc in place of private '_get_key' like name. Also\n# include arguments if possible.\n# - .clear(): not remove inserted classes, but reset them\n# - in \"set\", make type support extensible and optional, starting with numpy\n\nfrom collections import Mapping\nfrom collections.abc import Iterable\nfrom contextlib import contextmanager\nfrom sys import getsizeof\nfrom inspect import isclass\nfrom copy import copy, deepcopy\nfrom numpy import ndarray, array, ma\nfrom itertools import chain\ntry:\n import pint\n UREG = pint.UnitRegistry()\nexcept ImportError:\n UREG = None\n from warnings import warn\n warn('Pint package required for advanced Units support')\n\n\nclass Group(Mapping):\n \"\"\"\n Advanced dict with optional features (See bellow).\n\n The aim of this class is to have a dict like data structure with more\n controls of data inside.\n\n This classe is intended to be subclassed and not to be used directly.\n\n Subclassing for activating features\n -----------------------------------\n Subclassing this class, overloading some class variables and create methods\n with specific names is needed for activating following features:\n\n Set default values: overloading the \"_default\" class variable\n If Key not find in subclass instance, default value is automatically\n returned.\n\n Overload the \"_default\" class variable with a dict containing the\n needed default value for each required key.\n\n Example: _default = {'key1': 1.2, 'key2': 3}\n\n Type values: overloading the \"_dtype\" class variable\n When value is set, value is automatically casted to specified type or\n error is raised. A \"None\" value is set as \"None\" directly for and may\n be used as no data.\n\n Overload the \"_dtype\" class variable with a dict containing the\n needed type for each required key.\n\n Example: _dtype = {'key1': float, 'key2': np.int16}\n\n This feature support also more advanced typing. It is possible to add\n named arguments for the specified type setting it with a tuple\n like : (type, {argname1: argvalue1, argname2: argvalue2})\n\n For numpy arrays, \"ndim\" int argument is added and return error if\n input array number of dimensions is not equal to \"ndim\".\n\n Example: _dtype = {'key1': (numpy.ndarray, {'ndim': 2, 'dtype':\n np.float64})}\n\n Documented keys: overloading the \"_doc\" class variable\n Return doc_string for a specified key with instance .doc(key) method.\n Keys docstrings are also appended to the end of the subclass docstring.\n\n Overload the \"_doc\" class variable with a dict containing the\n needed docstrings for each required key.\n\n Example: _dtype = {'key1': \"A float number\", 'key2': \"A integer\n number\"}\n\n Advanced Getter/Setter functions: Create functions with specific names\n Theses functions replace standards way to get and set the value linked\n to a key in subclass instances with possible more powerful functions\n and the ability to use them with more than one argument.\n\n Getter functions are called with the \".get(key, *args, **kwargs)\"\n method. The function must have possibility to be called with only one\n argument since value can also be got with usual dict way\n \"value = MyInstance[key]\". The function can have any number of\n optionals arguments.\n The function must return the value to get.\n\n If needed, you can access to the raw value (or default value if\n missing) as stored in the subclass directly with \"_get_raw()\" method.\n\n Setter functions are called with the \".set(key, *args, **kwargs)\"\n method. If the function must have possibility to be called with only\n one argument since value can also be set with usual dict way\n \"MyInstance[key] = value\". The function can have any number of\n optionals arguments.\n The function must return the value to set.\n\n For create a getter/setter function, simply create a method or a\n static method called \"_get_name\" (For the getter) and/or a method\n called \"_set_name\" (For the setter) with \"name\" replaced by the key.\n If key is not a string or is a non-python compatible name for a\n function, you can use the \"_funcbase\" class variable to link key and\n function (See below).\n\n It is also possible to overload the \"_funcbase\" class variable with a\n dict containing the alias function basename for each required key.\n The alias is used to name the getter/setter functions linked to the\n key. If \"_funcbase\" is not overloaded for a key, try to call function\n using directly the key.\n\n Example: _funcbase = {'key1,12': \"k112\"}; for the key 'key1,12' key,\n setter will be \"_set_k112\" and getter \"_get_k112\".\n\n \"_funcbase\" can also be used to redirect many key getter/setter on a\n same function.\n\n Example: _funcbase = {'key1': \"root\", 'key2': \"root\"}\n\n Inserting other Groups or classes as Key and auto-instantiate them:\n For adding groups, simply write your Group subclass definition inside\n the File Subclass directly. The class method must be \"_Keyname\" with\n \"name\" the key name to find in File.keys().\n\n Once File is instantiated, all classes inside it starting with a\n \"_Keyname\" name will be automatically instantiated and will be\n available in File dictionary interface.\n\n Example: for \"_keyname\" class defined inside File, instance access\n with \"FileInstance['name']\". File instance is available from Group\n instance with the \"prt\" or \"parent\" attribute.\n\n The \"_Keyname\" mechanic also work with classes that are not Group.\n\n The added class is added to Default values and not on registered\n values. So it not count for len(), iter(), ...\n\n Writing limitation: overloading \"_readonly\" or \"_nonewkey\" class variable\n If \"_readonly\" is True, the subclass will be read only.\n\n If \"_nonewkey\" is True, creation of new keys is forbidden.\n Values for keys that already have default values can still be modified.\n\n All of theses values are False by default.\n\n You can use the \"_writeenabled\" context manager to temporally\n re-enable writing.\n\n Overloading \"__init__()\" method:\n The default \"__init__()\" only write values from \"mapping\" parameter\n inside instance.\n\n So, \"__init__()\" can safely be overloaded without calling\n \"Group.__init__(self, mapping)\" in subclasses.\n\n Parameters\n ----------\n Parameters with the default \"__init__()\" method of Group.\n\n mapping : dict compatible, optional\n Used to populate instance with data. See dict documentation.\n Empty by default.\n \"\"\"\n # Overridable class variables\n _default = {} # Default values dict (Used if no registered value)\n _dtype = {} # Values types\n _funcbase = {} # Setter/getter functions basename\n _doc = {} # Help/doc strings\n _readonly = False # Read only flag\n _nonewkey = False # New key limitation flag\n\n def __new__(cls, *args, **kwargs):\n \"\"\"\n Group Instanciation.\n \"\"\"\n # Create instance\n self = Mapping.__new__(cls)\n\n # Set default Parent value: in case not called by another Group\n self._parent = None\n self._values = {}\n self._iterdefault = False\n self._name = cls.__name__\n\n # Performance: Alias dotted names\n clsdict = cls.__dict__\n clsdtype = cls._dtype\n clsdoc = cls._doc\n values = self._values\n\n # Instantiate attributes-classes\n module = (\"{0}['{1}']\".format(cls.__module__, cls.__name__))\n for key in clsdict.keys():\n attr = clsdict[key]\n\n # Only for classes starting with '_Key'\n if not isclass(attr):\n continue\n name = attr.__name__\n if not name.startswith('_Key'):\n continue\n\n # Update attribute-class information\n name = name[len('_Key'):]\n attr.__name__ = name\n attr.__module__ = module\n\n # Instantiate attribute-class\n instance = attr()\n\n # If attribute-class is Group, add information\n if isinstance(instance, Group):\n setattr(instance, '_parent', self)\n if name not in clsdtype:\n clsdtype[name] = Group\n\n # Add doc to current class _doc\n if name not in clsdoc:\n clsdoc[name] = attr.__doc__\n\n # Add instance in default value dict\n values[name] = instance\n\n # Return instance\n return self\n\n def __init__(self, mapping=None):\n if mapping:\n self._values.update(mapping)\n\n @property\n def parent(self):\n \"\"\"\n Parent of this instance. Can be any object.\n \"\"\"\n return self._parent\n\n prt = parent # Alias for \"parent\" property\n\n def _customfunc(self, key, action, *args, **kwargs):\n \"\"\"\n Return result of an advanced function for the specified key.\n Key and function basename should be registered in \"_funcbase\" class\n variable (if not, key is used directly to search function name).\n\n Parameters\n ----------\n key : object\n key.\n action : str\n Action to do. Can be \"get\" or \"set\".\n *args, **kwargs :\n Arguments to pass to the function.\n \"\"\"\n name = '_{0}_{1}'.format(action, self._funcbase.get(key, key))\n func = getattr(self, name, None)\n\n # No function to return\n if func is None:\n raise _NoFunctionFoundError\n\n # Return function\n return func(*args, **kwargs)\n\n def set(self, key, *args, **kwargs):\n \"\"\"\n Set the value for key.\n\n Parameters\n ----------\n key : object\n key.\n *args, **kwargs : optional\n Value and/or other arguments (Specific to each key).\n \"\"\"\n if isinstance(self._values.get(key), Group):\n raise PermissionError('Groups are not overridable')\n if self._readonly:\n raise PermissionError('{} is read only'.format(self._name))\n if self._nonewkey and key not in self.keys_all():\n raise PermissionError('New key creation is forbidden')\n\n try:\n # Use function with full set of args\n newvalue = self._customfunc(key, 'set', *args, **kwargs)\n except _NoFunctionFoundError:\n # Try other ways\n newvalue = args[0]\n\n # Get data type\n dtype = self._dtype.get(key, object)\n if isinstance(dtype, Iterable):\n # Advanced typing\n kwargs = dtype[1]\n dtype = dtype[0]\n else:\n # Classic typing\n kwargs = {}\n\n if newvalue is None:\n # no data\n pass\n\n elif dtype is object:\n # Everything is object\n pass\n\n elif issubclass(dtype, ndarray):\n # Special case of ndarray\n npkwargs = deepcopy(kwargs)\n\n if 'copy' not in npkwargs:\n # Reference by default\n npkwargs['copy'] = False\n\n if 'ndim' in npkwargs:\n # For number of dimensions check\n ndim = npkwargs['ndim']\n del npkwargs['ndim']\n else:\n ndim = 0\n\n if dtype is ndarray:\n newvalue = array(newvalue, **npkwargs)\n else:\n newvalue = dtype(newvalue, **npkwargs)\n\n if ndim > newvalue.ndim:\n # Check number of dimensions\n raise ValueError('Array of {} dimensions needed'.format(ndim))\n elif kwargs:\n # Set type with advanced typing\n newvalue = dtype(newvalue, **kwargs)\n\n elif not isinstance(newvalue, dtype):\n # Check type and cast if not correct type\n newvalue = dtype(newvalue)\n\n self._values[key] = newvalue\n\n __setitem__ = set\n\n def get(self, key, *args, **kwargs):\n \"\"\"\n Return the value for key.\n\n Parameters\n ----------\n key : object\n key.\n *args, **kwargs : optional\n Other arguments (Specific to each key).\n \"\"\"\n try:\n # Use function with full set of args\n return self._customfunc(key, 'get', *args, **kwargs)\n except _NoFunctionFoundError:\n # Try other ways\n return self._get_raw(key)\n\n __getitem__ = get\n\n def _get_raw(self, key):\n \"\"\"\n Return the raw value for a key directly (or default raw value if\n missing).\n\n Parameters\n ----------\n key : object\n key.\n \"\"\"\n try:\n return self._values[key]\n except KeyError:\n try:\n return self._default[key]\n except KeyError:\n return self.__missing__(key)\n\n def __missing__(self, key):\n \"\"\"\n Raise error if key not registered and no default value.\n\n Parameters\n ----------\n key : object\n key.\n \"\"\"\n raise KeyError('No registered or default value for {0!r}'.format(key))\n\n def __contains__(self, key):\n \"\"\"\n Return True if key is registered.\n\n Parameters\n ----------\n key : object\n key.\n \"\"\"\n return key in self._values\n\n def __delitem__(self, key):\n \"\"\"\n Delete the registered value for key.\n\n Parameters\n ----------\n key : object\n key.\n \"\"\"\n if isinstance(self._values.get(key), Group):\n raise PermissionError('Groups are not overridable')\n if self._readonly:\n raise PermissionError('{} is read only'.format(self._name))\n\n del self._values[key]\n\n def clear(self):\n \"\"\"\n Remove all items.\n \"\"\"\n if self._readonly:\n raise PermissionError('{} is read only'.format(self._name))\n\n self._values.clear()\n\n def copy(self, deep=True):\n \"\"\"\n Return a copy of this object.\n\n Parameters\n ----------\n deep : bool, optional\n If True, create a deep copy.\n If False, create a shallow copy.\n\n Return\n ------\n Same type as this object.\n \"\"\"\n return deepcopy(self) if deep else copy(self)\n\n def update(self, source, deep=False):\n \"\"\"\n Update this object with the key/value pairs from source,\n overwriting existing keys.\n\n Parameters\n ----------\n source : dict like\n Source for update.\n deepcopy : bool, optional\n If True, updade with deep copies of source pairs.\n If False, updade with references of source pairs.\n \"\"\"\n if self._readonly:\n raise PermissionError('{} is read only'.format(self._name))\n\n for key, value in (deepcopy(source) if deep else source).items():\n try:\n self.set(key, value)\n except PermissionError:\n continue\n\n def keys(self):\n \"\"\"\n Return a list of registered keys.\n \"\"\"\n with self._iterall(False):\n return list(self)\n\n def keys_all(self):\n \"\"\"\n Return a list of registered keys and keys with default values.\n \"\"\"\n with self._iterall(True):\n return list(self)\n\n def values(self):\n \"\"\"\n Return a list of registered values.\n \"\"\"\n with self._iterall(False):\n getvalue = self.get\n return [getvalue(key) for key in self]\n\n def values_all(self):\n \"\"\"\n Return a list of registered and default values.\n \"\"\"\n with self._iterall(True):\n getvalue = self.get\n return [getvalue(key) for key in self]\n\n def values_raw(self, default=False):\n \"\"\"\n Return a list of registered values.\n\n Parameters\n ----------\n default : bool\n If True, include default values.\n \"\"\"\n # Raw registered + default values list\n if default:\n with self._iterall():\n getvalue = self._get_raw\n return [getvalue(key) for key in self]\n # Raw registered values list\n else:\n return list(self._values.values())\n\n def items(self):\n \"\"\"\n Return a list of registered items.\n \"\"\"\n with self._iterall(False):\n getvalue = self.get\n return [(key, getvalue(key)) for key in self]\n\n def items_all(self):\n \"\"\"\n Return a list of registered and default items.\n \"\"\"\n with self._iterall(True):\n getvalue = self.get\n return [(key, getvalue(key)) for key in self]\n\n def items_raw(self, default=False):\n \"\"\"\n Return a list of registered items.\n\n Parameters\n ----------\n default : bool\n If True, include unregistered items with default values.\n \"\"\"\n # Raw registered + default items list\n if default:\n with self._iterall():\n getvalue = self._get_raw\n return [(key, getvalue(key)) for key in self]\n\n # Raw registered items list\n else:\n return list(self._values.items())\n\n def default(self, key):\n \"\"\"\n Return the default value for a key.\n\n Parameters\n ----------\n key : object\n key.\n \"\"\"\n try:\n return self._default[key]\n except KeyError:\n raise KeyError(r'No default value found for {0!r}'.format(key))\n\n def dtype(self, key):\n \"\"\"\n Delete the required type for the value stored for key.\n\n Parameters\n ----------\n key : object\n key.\n \"\"\"\n dtype = self._dtype.get(key, object)\n if isinstance(dtype, Iterable):\n return dtype[0]\n return dtype\n\n def doc(self, key):\n \"\"\"\n Show the documentation for the specified key.\n\n Parameters\n ----------\n key : object\n key.\n \"\"\"\n return self._doc.get(key, '')\n\n def asdict(self, default=False, deep=False):\n \"\"\"\n Return a dictionary.\n\n Parameters\n ----------\n default : bool\n If True, include unregistered items with default values.\n deep : bool, optional\n If True, create a deep copy.\n If False, create a shallow copy.\n \"\"\"\n dictionnary = {}\n with self._iterall(default):\n getvalue = self.get\n for key in self:\n value = getvalue(key)\n if isinstance(value, Group):\n # Convert to dict Group inside this one\n value = value.asdict(default)\n if deep:\n value = deepcopy(value)\n key = deepcopy(key)\n dictionnary[key] = value\n return dictionnary\n\n def __repr__(self):\n \"\"\"\n Class representation : Group(Key <Type>: Value <Default>, ...)\n \"\"\"\n reprlist = [self._name,\n '(\\nKey <Value type>: Value preview <Default value flag>']\n\n # Performance: Alias dotted names\n getvalue = self.get\n gettype = self._dtype.get\n keys = self.keys()\n\n for key in self.keys_all():\n # Get value\n valuerepr = repr(getvalue(key))\n\n # Reduce value repr to one line of max 61 characters\n if valuerepr.find('\\n') > -1:\n valuelist = valuerepr.split('\\n')\n valuerepr = '[...]'.join((valuelist[0][:27].strip(),\n valuelist[-1][:27].strip()))\n elif len(valuerepr) > 61:\n valuerepr = '[...]'.join((valuerepr[:27].strip(),\n valuerepr[-27:].strip()))\n\n # Get type info\n dtype = gettype(key, object)\n if isinstance(dtype, Iterable):\n dtype, kwargs = dtype\n typename = dtype.__name__\n # Add more information for ndarrays\n if issubclass(dtype, ndarray):\n typelst = [typename]\n if 'dtype' in kwargs:\n typelst.append(\"dtype: {[dtype].__name__}\".\n format(kwargs))\n if 'ndim' in kwargs:\n typelst.append(\"dim: {[ndim]}\".format(kwargs))\n\n typename = ', '.join(typelst)\n else:\n typename = dtype.__name__\n\n # Show if value is default\n if not issubclass(dtype, Group) and key not in keys:\n default = ' <default>'\n else:\n default = ''\n\n # Write line\n reprlist.extend(['\\n', repr(key), ' <', typename, '>: ', valuerepr,\n default])\n reprlist.append(')')\n return ''.join(reprlist)\n\n def __iter__(self):\n \"\"\"\n Iterate over registered keys.\n \"\"\"\n if self._iterdefault:\n # Return keys from registered values and default values\n return iter(set(chain(self._values, self._default)))\n else:\n # Return keys from registered values only\n return iter(self._values)\n\n def __len__(self):\n \"\"\"\n Return len of registered values.\n \"\"\"\n return len(self._values)\n\n def __sizeof__(self):\n \"\"\"\n Return size in bytes of this object.\n \"\"\"\n # Initialize temporary variables\n seen = set()\n size = 0\n\n # Performance: Alias dotted names\n values = self._values\n cls_maskedarray = ma.core.MaskedArray\n see = seen.add\n\n for key in self:\n value = values[key]\n dtype = type(value)\n\n # Case of numpy based arrays\n if issubclass(dtype, ndarray):\n # List all arrays in object\n if issubclass(dtype, cls_maskedarray):\n # If Numpy masked array\n items = [value.data, value.mask]\n else:\n # Classic ndarray\n items = [value]\n\n # Return size for each sub-array\n for item in items:\n base = item.base\n itemid = id(item)\n baseid = id(item)\n nbytes = item.nbytes\n if ((base is None or baseid not in seen) and\n itemid not in seen and nbytes):\n see(itemid)\n if base is not None:\n see(baseid)\n size += nbytes\n\n # Case of other Python objects\n else:\n valueid = id(value)\n nbytes = getsizeof(value)\n if valueid not in seen and nbytes:\n see(valueid)\n size += nbytes\n\n return size\n\n @contextmanager\n def _writeenabled(self, nonewkey=False):\n \"\"\"\n This context manager temporary enable writing if _readonly and/or\n _nonewkey is set to True.\n\n Parameters\n ----------\n nonewkey : bool\n If True, _nonewkey is not temporally set to False.\n \"\"\"\n # Back up values\n readonly = self._readonly\n nonewkey = self._nonewkey\n\n # Enable write\n self._readonly = False\n self._nonewkey = nonewkey\n\n yield\n\n # Restore values\n self._readonly = readonly\n self._nonewkey = nonewkey\n\n @contextmanager\n def _iterall(self, default=True):\n \"\"\"\n This context manager make iteration over Group also yield default\n values.\n\n Parameters\n ----------\n default : bool\n If True, iterate also default values.\n \"\"\"\n self._iterdefault = default\n yield\n self._iterdefault = False\n\n\nclass _NoFunctionFoundError(Exception):\n \"\"\"Raised when no function found\"\"\"\n"
] |
[
[
"numpy.array"
]
] |
PeterouZh/pytorch-lightning
|
[
"6e32d00c8ca723c766ab6ff94adad1854bd89576"
] |
[
"pytorch_lightning/examples/new_project_templates/multi_node_cluster_template.py"
] |
[
"import os\nimport sys\nimport numpy as np\nfrom time import sleep\nimport torch\n\nfrom test_tube import HyperOptArgumentParser, Experiment, SlurmCluster\nfrom pytorch_lightning.models.trainer import Trainer\nfrom pytorch_lightning.utils.arg_parse import add_default_args\n\nfrom pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint\n\nSEED = 2334\ntorch.manual_seed(SEED)\nnp.random.seed(SEED)\n\n# ---------------------\n# DEFINE MODEL HERE\n# ---------------------\nfrom lightning_module_template import LightningTemplateModel\n# ---------------------\n\n\"\"\"\nAllows training by using command line arguments\nRun by:\n# TYPE YOUR RUN COMMAND HERE\n\"\"\"\n\n\ndef main_local(hparams):\n main(hparams, None, None)\n\n\ndef main(hparams, cluster, results_dict):\n \"\"\"\n Main training routine specific for this project\n :param hparams:\n :return:\n \"\"\"\n # ------------------------\n # 1 INIT LIGHTNING MODEL\n # ------------------------\n print('loading model...')\n model = LightningTemplateModel(hparams)\n print('model built')\n\n # ------------------------\n # 2 INIT TEST TUBE EXP\n # ------------------------\n # when using grid search, it's possible for all models to start at once\n # and use the same test tube experiment version\n relative_node_id = int(os.environ['SLURM_NODEID'])\n sleep(relative_node_id + 1)\n\n # init experiment\n exp = Experiment(\n name=hyperparams.experiment_name,\n save_dir=hyperparams.test_tube_save_path,\n autosave=False,\n description='test demo'\n )\n\n exp.argparse(hparams)\n exp.save()\n\n # ------------------------\n # 3 DEFINE CALLBACKS\n # ------------------------\n model_save_path = '{}/{}/{}'.format(hparams.model_save_path, exp.name, exp.version)\n early_stop = EarlyStopping(\n monitor='val_acc',\n patience=3,\n verbose=True,\n mode='max'\n )\n\n checkpoint = ModelCheckpoint(\n filepath=model_save_path,\n save_best_only=True,\n verbose=True,\n monitor='val_loss',\n mode='min'\n )\n\n # ------------------------\n # 4 INIT TRAINER\n # ------------------------\n trainer = Trainer(\n experiment=exp,\n cluster=cluster,\n checkpoint_callback=checkpoint,\n early_stop_callback=early_stop,\n gpus=hparams.gpus,\n nb_gpu_nodes=hyperparams.nb_gpu_nodes\n )\n\n # ------------------------\n # 5 START TRAINING\n # ------------------------\n trainer.fit(model)\n\n\ndef optimize_on_cluster(hyperparams):\n # enable cluster training\n # log all scripts to the test tube folder\n cluster = SlurmCluster(\n hyperparam_optimizer=hyperparams,\n log_path=hyperparams.slurm_log_path,\n )\n\n # email for cluster coms\n cluster.notify_job_status(email='add_email_here', on_done=True, on_fail=True)\n\n # configure cluster\n cluster.per_experiment_nb_gpus = hyperparams.per_experiment_nb_gpus\n cluster.per_experiment_nb_nodes = hyperparams.nb_gpu_nodes\n cluster.job_time = '2:00:00'\n cluster.gpu_type = 'volta'\n cluster.memory_mb_per_node = 0\n\n # any modules for code to run in env\n cluster.add_command('source activate lightning')\n\n # run only on 32GB voltas\n cluster.add_slurm_cmd(cmd='constraint', value='volta32gb', comment='use 32gb gpus')\n cluster.add_slurm_cmd(cmd='partition', value=hyperparams.gpu_partition, comment='use 32gb gpus')\n\n # run hopt\n # creates and submits jobs to slurm\n cluster.optimize_parallel_cluster_gpu(\n main,\n nb_trials=hyperparams.nb_hopt_trials,\n job_name=hyperparams.experiment_name\n )\n\n\nif __name__ == '__main__':\n\n # use default args\n root_dir = os.path.dirname(os.path.realpath(__file__))\n demo_log_dir = os.path.join(root_dir, 'pt_lightning_demo_logs')\n\n checkpoint_dir = os.path.join(demo_log_dir, 'model_weights')\n test_tube_dir = os.path.join(demo_log_dir, 'test_tube_data')\n slurm_out_dir = os.path.join(demo_log_dir, 'slurm_scripts')\n\n parent_parser = HyperOptArgumentParser(strategy='grid_search', add_help=False)\n\n # cluster args not defined inside the model\n parent_parser.add_argument('--gpu_partition', type=str, help='consult your cluster manual')\n\n # TODO: make 1 param\n parent_parser.add_argument('--per_experiment_nb_gpus', type=int, help='how many gpus to use in a node')\n parent_parser.add_argument('--gpus', type=str, default='-1', help='how many gpus to use in the node')\n\n parent_parser.add_argument('--nb_gpu_nodes', type=int, default=1, help='how many nodes to use in a cluster')\n parent_parser.add_argument('--test_tube_save_path', type=str, default=test_tube_dir, help='where to save logs')\n parent_parser.add_argument('--slurm_log_path', type=str, default=slurm_out_dir, help='where to save slurm meta')\n parent_parser.add_argument('--model_save_path', type=str, default=checkpoint_dir, help='where to save model')\n parent_parser.add_argument('--experiment_name', type=str, default='pt_lightning_exp_a', help='test tube exp name')\n parent_parser.add_argument('--nb_hopt_trials', type=int, default=1, help='how many grid search trials to run')\n\n # allow model to overwrite or extend args\n parser = LightningTemplateModel.add_model_specific_args(parent_parser, root_dir)\n hyperparams = parser.parse_args()\n\n # ---------------------\n # RUN TRAINING\n # ---------------------\n # run on HPC cluster\n print('RUNNING ON SLURM CLUSTER')\n optimize_on_cluster(hyperparams)\n"
] |
[
[
"torch.manual_seed",
"numpy.random.seed"
]
] |
sujay-vittal/color-identification-cot-purdur
|
[
"1959ceb4d1965743dab4cf3b72bdc76ae4e76255"
] |
[
"src/color_recognition_api/color_histogram_feature_extraction.py"
] |
[
"#!/usr/bin/python\n\nfrom PIL import Image\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import itemfreq\nfrom color_recognition_api import knn_classifier as knn_classifier\n\n\ndef color_histogram_of_test_image(test_src_image):\n\n # load the image\n image = test_src_image\n\n chans = cv2.split(image)\n colors = ('b', 'g', 'r')\n features = []\n feature_data = ''\n counter = 0\n for (chan, color) in zip(chans, colors):\n counter = counter + 1\n\n hist = cv2.calcHist([chan], [0], None, [256], [0, 256])\n features.extend(hist)\n\n # find the peak pixel values for R, G, and B\n elem = np.argmax(hist)\n\n if counter == 1:\n blue = str(elem)\n elif counter == 2:\n green = str(elem)\n elif counter == 3:\n red = str(elem)\n feature_data = red + ',' + green + ',' + blue\n # print(feature_data)\n\n with open('test.data', 'w') as myfile:\n myfile.write(feature_data)\n\n\ndef color_histogram_of_training_image(img_name):\n\n # detect image color by using image file name to label training data\n if 'red' in img_name:\n data_source = 'red'\n elif 'yellow' in img_name:\n data_source = 'yellow'\n elif 'green' in img_name:\n data_source = 'green'\n elif 'orange' in img_name:\n data_source = 'orange'\n elif 'white' in img_name:\n data_source = 'white'\n elif 'black' in img_name:\n data_source = 'black'\n elif 'blue' in img_name:\n data_source = 'blue'\n elif 'violet' in img_name:\n data_source = 'violet'\n\n # load the image\n image = cv2.imread(img_name)\n\n chans = cv2.split(image)\n colors = ('b', 'g', 'r')\n features = []\n feature_data = ''\n counter = 0\n for (chan, color) in zip(chans, colors):\n counter = counter + 1\n\n hist = cv2.calcHist([chan], [0], None, [256], [0, 256])\n features.extend(hist)\n\n # find the peak pixel values for R, G, and B\n elem = np.argmax(hist)\n\n if counter == 1:\n blue = str(elem)\n elif counter == 2:\n green = str(elem)\n elif counter == 3:\n red = str(elem)\n feature_data = red + ',' + green + ',' + blue\n\n with open('training.data', 'a') as myfile:\n myfile.write(feature_data + ',' + data_source + '\\n')\n\n\ndef training():\n\n # red color training images\n for f in os.listdir('./training_dataset/red'):\n color_histogram_of_training_image('./training_dataset/red/' + f)\n\n # yellow color training images\n for f in os.listdir('./training_dataset/yellow'):\n color_histogram_of_training_image('./training_dataset/yellow/' + f)\n\n # green color training images\n for f in os.listdir('./training_dataset/green'):\n color_histogram_of_training_image('./training_dataset/green/' + f)\n\n # orange color training images\n for f in os.listdir('./training_dataset/orange'):\n color_histogram_of_training_image('./training_dataset/orange/' + f)\n\n # white color training images\n for f in os.listdir('./training_dataset/white'):\n color_histogram_of_training_image('./training_dataset/white/' + f)\n\n # black color training images\n for f in os.listdir('./training_dataset/black'):\n color_histogram_of_training_image('./training_dataset/black/' + f)\n\n # blue color training images\n for f in os.listdir('./training_dataset/blue'):\n color_histogram_of_training_image('./training_dataset/blue/' + f)\t\t\n"
] |
[
[
"numpy.argmax"
]
] |
kajyuuen/pytorch-partial-crf
|
[
"bb368346544cb6241e425a8b4e1a3baee324ef0d"
] |
[
"pytorch_partial_crf/crf.py"
] |
[
"from typing import Optional\n\nimport torch\n\nfrom pytorch_partial_crf.base_crf import BaseCRF\nfrom pytorch_partial_crf.utils import log_sum_exp\n\nclass CRF(BaseCRF):\n \"\"\"Conditional random field.\n \"\"\"\n def __init__(self, num_tags: int, padding_idx: int = None) -> None:\n super().__init__(num_tags, padding_idx)\n\n def forward(self,\n emissions: torch.Tensor,\n tags: torch.LongTensor,\n mask: Optional[torch.ByteTensor] = None) -> torch.Tensor:\n if mask is None:\n mask = torch.ones_like(tags, dtype=torch.uint8)\n\n gold_score = self._numerator_score(emissions, tags, mask)\n forward_score = self._denominator_score(emissions, mask)\n return torch.sum(forward_score - gold_score)\n\n def _denominator_score(self,\n emissions: torch.Tensor,\n mask: torch.ByteTensor) -> torch.Tensor:\n \"\"\"\n Parameters:\n emissions: (batch_size, sequence_length, num_tags)\n mask: Show padding tags. 0 don't calculate score. (batch_size, sequence_length)\n Returns:\n scores: (batch_size)\n \"\"\"\n batch_size, sequence_length, num_tags = emissions.data.shape\n\n emissions = emissions.transpose(0, 1).contiguous()\n mask = mask.float().transpose(0, 1).contiguous()\n\n # Start transition score and first emissions score\n alpha = self.start_transitions.view(1, num_tags) + emissions[0]\n\n for i in range(1, sequence_length):\n # Emissions scores\n emissions_score = emissions[i].view(batch_size, 1, num_tags) # (batch_size, 1, num_tags)\n # Transition scores\n transition_scores = self.transitions.view(1, num_tags, num_tags) # (1, num_tags, num_tags)\n # Broadcast alpha\n broadcast_alpha = alpha.view(batch_size, num_tags, 1) # (batch_size, num_tags, 1)\n\n # Add all scores\n inner = broadcast_alpha + emissions_score + transition_scores # (batch_size, num_tags, num_tags)\n alpha = (log_sum_exp(inner, 1) * mask[i].view(batch_size, 1) +\n alpha * (1 - mask[i]).view(batch_size, 1))\n\n # Add end transition score\n stops = alpha + self.end_transitions.view(1, num_tags)\n\n return log_sum_exp(stops) # (batch_size,)\n\n def _numerator_score(self,\n emissions: torch.Tensor,\n tags: torch.LongTensor,\n mask: torch.ByteTensor) -> torch.Tensor:\n \"\"\"\n Parameters:\n emissions: (batch_size, sequence_length, num_tags)\n tags: (batch_size, sequence_length)\n mask: Show padding tags. 0 don't calculate score. (batch_size, sequence_length)\n Returns:\n scores: (batch_size)\n \"\"\"\n\n batch_size, sequence_length, _ = emissions.data.shape\n\n emissions = emissions.transpose(0, 1).contiguous()\n tags = tags.transpose(0, 1).contiguous()\n mask = mask.float().transpose(0, 1).contiguous()\n\n # Start transition score and first emission\n score = self.start_transitions.index_select(0, tags[0])\n \n for i in range(sequence_length - 1):\n current_tag, next_tag = tags[i], tags[i+1]\n # Emissions score for next tag\n emissions_score = emissions[i].gather(1, current_tag.view(batch_size, 1)).squeeze(1)\n # Transition score from current_tag to next_tag\n transition_score = self.transitions[current_tag.view(-1), next_tag.view(-1)]\n\n # Add all score\n score += transition_score * mask[i + 1] + emissions_score * mask[i]\n\n # Add end transition score\n last_tag_index = mask.sum(0).long() - 1\n last_tags = tags.gather(0, last_tag_index.view(1, batch_size)).squeeze(0)\n\n # Compute score of transitioning to STOP_TAG from each LAST_TAG\n last_transition_score = self.end_transitions.index_select(0, last_tags)\n\n last_inputs = emissions[-1] # (batch_size, num_tags)\n last_input_score = last_inputs.gather(1, last_tags.view(-1, 1)) # (batch_size, 1)\n last_input_score = last_input_score.squeeze() # (batch_size,)\n\n score = score + last_transition_score + last_input_score * mask[-1]\n\n return score\n"
] |
[
[
"torch.sum",
"torch.ones_like"
]
] |
junfengwen/DARN
|
[
"585fc99b9ed23b7c0835a2d47713016cf6333260"
] |
[
"load_data.py"
] |
[
"import os\n\nimport numpy as np\nfrom scipy.sparse import coo_matrix\n\n\ndef load_numpy_data(name,\n data_path,\n logger):\n\n if name == \"amazon\":\n\n data_names = [\"books\", \"dvd\", \"electronics\", \"kitchen\"]\n input_dim = 5000 # Number of features to be used in the experiment\n num_trains = 2000\n\n # Load & process the amazon dataset\n amazon = np.load(os.path.join(data_path,\n \"%s.npz\" % name))\n amazon_xx = coo_matrix((amazon['xx_data'], (amazon['xx_col'], amazon['xx_row'])),\n shape=amazon['xx_shape'][::-1]).tocsc()\n amazon_xx = amazon_xx[:, :input_dim]\n amazon_yy = amazon['yy']\n amazon_yy = (amazon_yy + 1) / 2 # from {-1, 1} to {0, 1}\n amazon_offset = amazon['offset'].flatten() # starting indices of the four domains\n\n # Partition the data into four domains and for each domain partition the data set into training and test set\n train_insts, train_labels, num_insts, test_insts, test_labels = [], [], [], [], []\n for i, dataset in enumerate(data_names):\n train_insts.append(amazon_xx[amazon_offset[i]: amazon_offset[i + 1]])\n train_labels.append(np.squeeze(amazon_yy[amazon_offset[i]: amazon_offset[i + 1]]))\n logger.info(\"%s with %d instances.\" % (dataset,\n amazon_offset[i + 1] - amazon_offset[i]))\n num_insts.append(amazon_offset[i + 1] - amazon_offset[i])\n # Random shuffle\n ridx = np.arange(num_insts[i])\n np.random.shuffle(ridx)\n test_insts.append(train_insts[i][ridx[num_trains:]].todense())\n test_labels.append(train_labels[i][ridx[num_trains:]].ravel())\n train_insts[i] = train_insts[i][ridx[:num_trains]].todense()\n train_labels[i] = train_labels[i][ridx[:num_trains]].ravel()\n\n configs = {\"input_dim\": input_dim,\n \"hidden_layers\": [1000, 500, 100],\n \"num_classes\": 2,\n \"drop_rate\": 0.7}\n\n elif name == \"digits\":\n\n data_names = [\"mnist\", \"mnist_m\", \"svhn\", \"synth_digits\"]\n num_trains = 20000\n num_tests = 9000\n input_dim = 2304 # number of features after CovNet\n\n train_insts, train_labels, test_insts, test_labels = [], [], [], []\n for dataset in data_names:\n data = np.load(os.path.join(data_path,\n dataset,\n \"%s.npz\" % dataset))\n logger.info(\"%s with %d training and %d test instances\" % (dataset,\n data['train_x'].shape[0],\n data['test_x'].shape[0]))\n # Shuffle and get training and test data\n ridx = np.arange(data['train_x'].shape[0])\n np.random.shuffle(ridx)\n train_insts.append(data['train_x'][ridx[:num_trains]])\n train_labels.append(data['train_y'][ridx[:num_trains]])\n\n ridx = np.arange(data['test_x'].shape[0])\n np.random.shuffle(ridx)\n test_insts.append(data['test_x'][ridx[:num_tests]])\n test_labels.append(data['test_y'][ridx[:num_tests]])\n\n configs = {\"input_dim\": input_dim,\n \"channels\": 3,\n \"conv_layers\": [64, 128, 256],\n \"cls_fc_layers\": [2048, 1024],\n \"dom_fc_layers\": [2048, 2048],\n \"num_classes\": 10,\n \"drop_rate\": 0.0}\n\n elif name == \"office_home\":\n\n data_names = ['Art', 'Clipart', 'Product', 'Real_World']\n num_trains = 2000\n\n train_insts, train_labels, num_insts, test_insts, test_labels = [], [], [], [], []\n for i, dataset in enumerate(data_names):\n data_file = os.path.join(data_path,\n 'office_home_%s.npz' % dataset.lower())\n data = np.load(data_file)\n\n train_insts.append(data['x'])\n train_labels.append(np.squeeze(data['y']))\n num_insts.append(train_insts[i].shape[0])\n\n logger.info(\"%s with %d instances.\" % (dataset,\n num_insts[i]))\n # Random shuffle.\n ridx = np.arange(num_insts[i])\n np.random.shuffle(ridx)\n\n test_insts.append(train_insts[i][ridx[num_trains:]])\n test_labels.append(train_labels[i][ridx[num_trains:]])\n\n train_insts[i] = train_insts[i][ridx[:num_trains]]\n train_labels[i] = train_labels[i][ridx[:num_trains]]\n\n configs = {\"input_dim\": 2048,\n \"hidden_layers\": [1000, 500, 100],\n \"num_classes\": 65,\n \"drop_rate\": 0.7}\n\n else:\n\n raise ValueError(\"Unknown dataset.\")\n\n return data_names, train_insts, train_labels, test_insts, test_labels, configs\n\n\ndef data_loader(inputs, targets, batch_size, shuffle=True):\n assert inputs.shape[0] == targets.shape[0]\n inputs_size = inputs.shape[0]\n if shuffle:\n random_order = np.arange(inputs_size)\n np.random.shuffle(random_order)\n inputs, targets = inputs[random_order, :], targets[random_order]\n num_blocks = int(inputs_size / batch_size)\n for i in range(num_blocks):\n yield inputs[i * batch_size: (i+1) * batch_size, :], targets[i * batch_size: (i+1) * batch_size]\n if num_blocks * batch_size != inputs_size:\n yield inputs[num_blocks * batch_size:, :], targets[num_blocks * batch_size:]\n\n\ndef multi_data_loader(inputs, targets, batch_size, shuffle=True):\n \"\"\"\n Both inputs and targets are list of numpy arrays, containing instances and labels from multiple sources.\n \"\"\"\n assert len(inputs) == len(targets)\n input_sizes = [data.shape[0] for data in inputs]\n max_input_size = max(input_sizes)\n num_domains = len(inputs)\n if shuffle:\n for i in range(num_domains):\n r_order = np.arange(input_sizes[i])\n np.random.shuffle(r_order)\n inputs[i], targets[i] = inputs[i][r_order], targets[i][r_order]\n num_blocks = int(max_input_size / batch_size)\n for j in range(num_blocks):\n xs, ys = [], []\n for i in range(num_domains):\n ridx = np.random.choice(input_sizes[i], batch_size)\n xs.append(inputs[i][ridx])\n ys.append(targets[i][ridx])\n yield xs, ys\n\n\ndef loader_gen(loader, mode='inf'):\n # https://github.com/pytorch/pytorch/issues/1917#issuecomment-479482530\n while True:\n for images, targets in loader:\n yield images, targets\n if mode != 'inf':\n break\n"
] |
[
[
"scipy.sparse.coo_matrix",
"numpy.random.choice",
"numpy.arange",
"numpy.squeeze",
"numpy.random.shuffle",
"numpy.load"
]
] |
ialab-puc/pytorch-segmentation-toolbox
|
[
"cc52d5ff7a41bae1f47ebe76b2908a84723fda93"
] |
[
"predict.py"
] |
[
"import argparse\nimport scipy\nfrom scipy import ndimage\nimport cv2\nimport numpy as np\nimport sys\nimport json\n\nimport torch\n\nfrom torch.autograd import Variable\nimport torchvision.models as models\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nfrom torch.utils import data\nimport networks\nfrom dataset.datasets import CSDataTestSet\nfrom collections import OrderedDict\nimport os\nimport scipy.ndimage as nd\nfrom math import ceil\nfrom PIL import Image as PILImage\nfrom utils.pyt_utils import load_model\nfrom evaluate import get_palette, predict_multiscale, predict_sliding, get_confusion_matrix, predict_whole\nfrom engine import Engine\nimport torch.nn as nn\n\nIMG_MEAN = np.array((104.00698793,116.66876762,122.67891434), dtype=np.float32)\n\nDATA_DIRECTORY = 'cityscapes'\nDATA_LIST_PATH = './dataset/list/cityscapes/val.lst'\nIGNORE_LABEL = 255\nNUM_CLASSES = 19\nNUM_STEPS = 500 # Number of images in the validation set.\nINPUT_SIZE = '340,480'\nRESTORE_FROM = './deeplab_resnet.ckpt'\nBATCH_SIZE = 2\n\ndef get_parser():\n \"\"\"Parse all the arguments provided from the CLI.\n \n Returns:\n A list of parsed arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description=\"DeepLabLFOV Network\")\n parser.add_argument(\"--data-dir\", type=str, default=DATA_DIRECTORY,\n help=\"Path to the directory containing the PASCAL VOC dataset.\")\n parser.add_argument(\"--data-list\", type=str, default=DATA_LIST_PATH,\n help=\"Path to the file listing the images in the dataset.\")\n parser.add_argument(\"--ignore-label\", type=int, default=IGNORE_LABEL,\n help=\"The index of the label to ignore during the training.\")\n parser.add_argument(\"--batch-size\", type=int, default=BATCH_SIZE,\n help=\"Number of images sent to the network in one step.\")\n parser.add_argument(\"--num-classes\", type=int, default=NUM_CLASSES,\n help=\"Number of classes to predict (including background).\")\n parser.add_argument(\"--restore-from\", type=str, default=RESTORE_FROM,\n help=\"Where restore model parameters from.\")\n parser.add_argument(\"--gpu\", type=str, default='0',\n help=\"choose gpu device.\")\n parser.add_argument(\"--recurrence\", type=int, default=1,\n help=\"choose the number of recurrence.\")\n parser.add_argument(\"--input-size\", type=str, default=INPUT_SIZE,\n help=\"Comma-separated string with height and width of images.\")\n parser.add_argument(\"--num-workers\", type=int, default=8,\n help=\"choose the number of recurrence.\")\n parser.add_argument(\"--whole\", type=bool, default=False,\n help=\"use whole input size.\")\n return parser\n\n\ndef main():\n \"\"\"Create the model and start the evaluation process.\"\"\"\n parser = get_parser()\n\n with Engine(custom_parser=parser) as engine:\n args = parser.parse_args()\n\n cudnn.benchmark = True\n h, w = map(int, args.input_size.split(','))\n input_size = (h, w)\n\n seg_model = networks.pspnet.Seg_Model(\n num_classes=args.num_classes\n )\n\n load_model(seg_model, args.restore_from)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n seg_model.to(device)\n\n model = engine.data_parallel(seg_model)\n model.eval()\n\n dataset = CSDataTestSet(args.data_dir, args.data_list, crop_size=input_size, mean=IMG_MEAN)\n test_loader, test_sampler = engine.get_test_loader(dataset)\n\n if engine.distributed:\n test_sampler.set_epoch(0)\n\n palette = get_palette(NUM_CLASSES)\n # interp = nn.Upsample(size=(1024, 2048), mode='bilinear', align_corners=True)\n\n if not os.path.exists('outputs'):\n os.makedirs('outputs')\n\n for index, batch in enumerate(test_loader):\n if index % 100 == 0:\n print('%d processd'%(index))\n image, name, size = batch\n size = size[0].numpy()\n with torch.no_grad():\n # output = predict_sliding(model, image.numpy(), input_size, args.num_classes, True, args.recurrence)\n output = predict_whole(model, image.numpy(), input_size, args.recurrence)\n seg_pred = np.asarray(np.argmax(output, axis=3), dtype=np.uint8)\n output_im = PILImage.fromarray(seg_pred[0])\n output_im.putpalette(palette)\n # output_im = output_im.crop((0, 0, w, h))\n output_im.save('outputs/'+name[0]+'.png')\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.array",
"torch.no_grad",
"numpy.argmax",
"torch.cuda.is_available"
]
] |
brandondong/osu-beatmap-generator
|
[
"7ca14793ef6a48a65cfd1a564f3b24d940a6051a"
] |
[
"osu/models/models_util.py"
] |
[
"from enum import Enum\nimport os\nimport pickle\n\nimport numpy as np\n\nTRAINING_METADATA_PATH = \"training_data/metadata/\"\n\nMODEL_SAVE_PATH = \"models/weights/\"\n\nclass MetadataPredictor(Enum):\n\tCS = \"cs\"\n\tDRAIN = \"drain\"\n\tACCURACY = \"accuracy\"\n\tAR = \"ar\"\n\ndef load_metadata_dataset():\n\t\"\"\"Loads the metadata training dataset into a (n, 7) numpy array.\"\"\"\n\n\tfiles = os.listdir(TRAINING_METADATA_PATH)\n\tnum_files = len(files)\n\n\t# Data rows are in the format of [difficulty_rating],[bpm],[total_length],[cs],[drain],[accuracy],[ar].\n\tdataset = np.zeros((num_files, 7))\n\n\tfor idx, f in enumerate(files):\n\t\tfilename = os.path.join(TRAINING_METADATA_PATH, f)\n\t\twith open(filename, encoding=\"utf-8\", mode=\"r\") as csv_file:\n\t\t\tcontents = csv_file.read()\n\t\tdata = contents.split(\",\")\n\t\tfor prop_idx, prop in enumerate(data):\n\t\t\tdataset[idx, prop_idx] = float(prop)\n\t\n\treturn dataset\n\t\ndef save_model(model, predictor):\n\t# Make sure the save directory exists.\n\tos.makedirs(MODEL_SAVE_PATH, exist_ok=True)\n\t\n\tfilename = os.path.join(MODEL_SAVE_PATH, predictor.value)\n\twith open(filename, mode=\"wb\") as file:\n\t\tpickle.dump(model, file)\n\t\ndef load_model(predictor):\n\tfilename = os.path.join(MODEL_SAVE_PATH, predictor.value)\n\twith open(filename, mode=\"rb\") as file:\n\t\treturn pickle.load(file)"
] |
[
[
"numpy.zeros"
]
] |
ercan-akar/chessboard-recognizer
|
[
"8ce2e782a400d2e5fb8c492442b0989741e996b3"
] |
[
"recognize.py"
] |
[
"#!/usr/bin/env python3\n\nimport sys\nfrom glob import glob\nfrom io import BytesIO\nfrom functools import reduce\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport tensorflow as tf\nfrom tensorflow.keras import models\nimport numpy as np\n\nfrom constants import (\n TILES_DIR, NN_MODEL_PATH, FEN_CHARS, USE_GRAYSCALE, DETECT_CORNERS\n)\nfrom utils import compressed_fen\nfrom train import image_data\nfrom chessboard_finder import get_chessboard_corners\nfrom chessboard_image import get_chessboard_tiles\n\nOUT_FILE = \"debug.html\"\n\ndef _chessboard_tiles_img_data(chessboard_img_path, options={}):\n \"\"\" Given a file path to a chessboard PNG image, returns a\n size-64 array of 32x32 tiles representing each square of a chessboard\n \"\"\"\n n_channels = 1 if USE_GRAYSCALE else 3\n tiles = get_chessboard_tiles(chessboard_img_path, use_grayscale=USE_GRAYSCALE)\n img_data_list = []\n for i in range(64):\n buf = BytesIO()\n tiles[i].save(buf, format='PNG')\n img_data = tf.image.decode_image(buf.getvalue(), channels=n_channels)\n img_data = tf.image.convert_image_dtype(img_data, tf.float32)\n img_data = tf.image.resize(img_data, [32, 32])\n img_data_list.append(img_data)\n return img_data_list\n\ndef _confidence_color(confidence):\n if confidence >= 0.999:\n return \"#00C176\"\n elif confidence > 0.99:\n return \"#88C100\"\n elif confidence > 0.95:\n return \"#FABE28\"\n elif confidence > 0.9:\n return \"#FF8A00\"\n else:\n return \"#FF003C\"\n\ndef _save_output_html(chessboard_img_path, fen, predictions, confidence):\n confidence_color = _confidence_color(confidence)\n html = '<h3>{}</h3>'.format(chessboard_img_path)\n html += '<div class=\"boards-row\">'\n html += '<img src=\"{}\" />'.format(chessboard_img_path)\n html += '<img src=\"http://www.fen-to-image.com/image/32/{}\"/>'.format(fen)\n html += '<div class=\"predictions-matrix\">'\n for i in range(8):\n html += '<div>'\n for j in range(8):\n c = predictions[i*8 + j]\n html += '<div class=\"prediction\" style=\"color: {}\">{}</div>'.format(\n _confidence_color(c),\n format(c, '.3f')\n )\n html += '</div>'\n html += '</div>'\n html += '</div>'\n html += '<br />'\n html += '<a href=\"https://lichess.org/editor/{}\" target=\"_blank\">{}</a>'.format(\n fen, fen\n )\n html += '<div style=\"color: {}\">{}</div>'.format(confidence_color, confidence)\n html += '<br /><br />'\n with open(OUT_FILE, \"a\") as f:\n f.write(html)\n\ndef predict_chessboard(chessboard_img_path, options={}):\n \"\"\" Given a file path to a chessboard PNG image,\n Returns a FEN string representation of the chessboard\n \"\"\"\n if not options.quiet:\n print(\"Predicting chessboard {}\".format(chessboard_img_path))\n img_data_list = _chessboard_tiles_img_data(chessboard_img_path, options)\n predictions = []\n confidence = 1\n for i in range(64):\n # a8, b8 ... g1, h1\n tile_img_data = img_data_list[i]\n (fen_char, probability) = predict_tile(tile_img_data)\n if not options.quiet:\n print((fen_char, probability))\n predictions.append((fen_char, probability))\n predicted_fen = compressed_fen(\n '/'.join(\n [''.join(r) for r in np.reshape([p[0] for p in predictions], [8, 8])]\n )\n )\n if not options.quiet:\n confidence = reduce(lambda x,y: x*y, [p[1] for p in predictions])\n print(\"Confidence: {}\".format(confidence))\n # if options.debug:\n print(\"https://lichess.org/editor/{}\".format(predicted_fen))\n _save_output_html(chessboard_img_path, predicted_fen, [p[1] for p in predictions], confidence)\n print(\"Saved {} prediction to {}\".format(chessboard_img_path, OUT_FILE))\n return predicted_fen\n\ndef predict_tile(tile_img_data):\n \"\"\" Given the image data of a tile, try to determine what piece\n is on the tile, or if it's blank.\n\n Returns a tuple of (predicted FEN char, confidence)\n \"\"\"\n probabilities = list(model.predict(np.array([tile_img_data]))[0])\n max_probability = max(probabilities)\n i = probabilities.index(max_probability)\n return (FEN_CHARS[i], max_probability)\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-q\", \"--quiet\", help=\"Only print recognized FEN position\",\n action=\"store_true\")\n parser.add_argument(\"-d\", \"--debug\", help=\"Saves debug output to debug.html\",\n action=\"store_true\")\n parser.add_argument(\"image_path\", help=\"Path/glob to PNG chessboard image(s)\")\n args = parser.parse_args()\n if not args.quiet:\n print('Tensorflow {}'.format(tf.version.VERSION))\n model = models.load_model(NN_MODEL_PATH)\n # tile_img_path = glob(TILES_DIR + '/*/*.png')[0]\n # print(tile_img_path)\n # print(predict_tile(image_data(tile_img_path)))\n if len(sys.argv) > 1:\n with open(OUT_FILE, \"w\") as f:\n f.write('<link rel=\"stylesheet\" href=\"./web/style.css\" />')\n for chessboard_image_path in sorted(glob(args.image_path)):\n print(predict_chessboard(chessboard_image_path, args))\n\n"
] |
[
[
"tensorflow.keras.models.load_model",
"numpy.reshape",
"tensorflow.image.resize",
"tensorflow.image.convert_image_dtype",
"numpy.array"
]
] |
yonip97/non-parametric-transformers
|
[
"f748b898a47b6dbd1ad1aa9aee9fc5b200e23030"
] |
[
"npt/utils/cv_utils.py"
] |
[
"\"\"\"Cross-validation utils.\"\"\"\n\nfrom collections import Counter\nfrom enum import IntEnum\n\nimport numpy as np\nfrom sklearn.model_selection import StratifiedKFold, train_test_split, KFold\n\n\nclass DatasetMode(IntEnum):\n \"\"\"Used in batching.\"\"\"\n TRAIN = 0\n VAL = 1\n TEST = 2\n\n\nDATASET_MODE_TO_ENUM = {\n 'train': DatasetMode.TRAIN,\n 'val': DatasetMode.VAL,\n 'test': DatasetMode.TEST\n}\n\nDATASET_ENUM_TO_MODE = {\n DatasetMode.TRAIN: 'train',\n DatasetMode.VAL: 'val',\n DatasetMode.TEST: 'test'\n}\n\n\ndef get_class_reg_train_val_test_splits(\n label_rows, c, should_stratify, fixed_test_set_index):\n \"\"\"\"Obtain train, validation, and test indices.\n num_data = len(label_rows)\n\n Stratify Logic:\n\n Perform stratified splits if the target is a single categorical column;\n else, (even if we have multiple categorical targets, for example)\n perform standard splits.\n\n If fixed_test_set_index is not None,\n use the index to perform the test split\n \"\"\"\n if should_stratify and label_rows.dtype == np.object:\n from sklearn.preprocessing import LabelEncoder\n # Encode the label column\n label_rows = LabelEncoder().fit_transform(label_rows)\n print('Detected an object dtype label column. Encoded to ints.')\n\n N = len(label_rows)\n n_cv_splits = get_n_cv_splits(c)\n\n if fixed_test_set_index:\n all_indices = np.arange(N)\n train_test_splits = [\n (all_indices[:fixed_test_set_index],\n all_indices[fixed_test_set_index:])]\n else:\n kf_class = StratifiedKFold if should_stratify else KFold\n kf = kf_class(\n n_splits=n_cv_splits, shuffle=True, random_state=c.np_seed)\n train_test_splits = kf.split(np.arange(N), label_rows)\n\n for train_val_indices, test_indices in train_test_splits:\n val_indices = []\n if c.exp_val_perc > 0:\n normed_val_perc = c.exp_val_perc / (1 - c.exp_test_perc)\n\n if should_stratify:\n train_val_label_rows = label_rows[train_val_indices]\n else:\n train_val_label_rows = None\n\n train_indices, val_indices = train_test_split(\n train_val_indices, test_size=normed_val_perc, shuffle=True,\n random_state=c.np_seed, stratify=train_val_label_rows)\n else:\n train_indices = train_val_indices\n\n train_perc = len(train_indices) / N\n val_perc = len(val_indices) / N\n test_perc = len(test_indices) / N\n print(\n f'Percentage of each group: Train {train_perc:.2f} '\n f'| {val_perc:.2f} | {test_perc:.2f}')\n\n if c.exp_show_empirical_label_dist:\n print('Empirical Label Distributions:')\n for split_name, split_indices in zip(\n ['train', 'val', 'test'],\n [train_indices, val_indices, test_indices]):\n num_elem = len(split_indices)\n class_counter = Counter(label_rows[split_indices])\n class_proportions = {\n key: class_counter[key] / num_elem\n for key in sorted(class_counter.keys())}\n print(f'{split_name}:')\n print(class_proportions)\n\n yield train_indices, val_indices, test_indices\n\n\ndef get_n_cv_splits(c):\n return int(1 / c.exp_test_perc) # Rounds down\n"
] |
[
[
"numpy.arange",
"sklearn.preprocessing.LabelEncoder",
"sklearn.model_selection.train_test_split"
]
] |
cuihaoleo/exercises
|
[
"401dc2f19b6474e84e357a79a53754684fc93784"
] |
[
"Schoolworks/ArtificialIntelligence/julei.py"
] |
[
"from types import SimpleNamespace\nfrom collections import Counter\nimport numpy as np\nimport pandas as pd\nfrom pandas.tools.plotting import andrews_curves, radviz, parallel_coordinates\nimport matplotlib.pyplot as plt\nimport argparse\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\nfrom scipy.spatial.distance import pdist, squareform\nfrom scipy.cluster.vq import kmeans2\n\n\ndef read_data(csv, config):\n with open(config) as fin:\n use = fin.readline().strip().split(',')\n ref = fin.readline().strip()\n\n with open(csv) as fin:\n header = fin.readline().strip().split(',')\n use.sort(key=lambda i: header.index(i))\n\n data_matrix = np.array([], dtype=np.float).reshape(0, len(use))\n ref_array = []\n\n ref_data = None\n for line in fin:\n entry = line.strip().split(',')\n use_data = []\n del ref_data\n\n for i, val in enumerate(entry):\n label = header[i]\n if label in use:\n use_data.append(np.log(float(val)))\n elif label == ref:\n ref_data = int(val)\n\n data_matrix = np.vstack((data_matrix, use_data))\n ref_array.append(ref_data)\n\n ret = SimpleNamespace()\n ret.data_header = use\n ret.data = data_matrix\n ret.flag = ref_array\n ret.samples = len(ref_array)\n\n return ret\n\n\ndef pca(sp, dimens):\n X_pca = PCA(n_components=dimens).fit_transform(sp.data)\n sp.data = X_pca\n sp.data_header = [\"F%d\" % i for i in range(dimens)]\n\n\ndef pandas_plot(sp, ref, function=radviz):\n data = np.copy(sp.data)\n data.reshape((-1, len(sp.data_header)))\n dict_data = {\n h: sp.data[:, i] for i, h in enumerate(sp.data_header)}\n\n dict_data[\"REF\"] = sp.flag\n df = pd.DataFrame(dict_data)\n\n dict_data[\"REF\"] = ref\n df2 = pd.DataFrame(dict_data)\n\n fig, axes = plt.subplots(nrows=1, ncols=2)\n function(df, 'REF', marker='.', ax=axes[0])\n function(df2, 'REF', marker='.', ax=axes[1])\n plt.show()\n\n\ndef kmeans(sp, n_clusters=None):\n K = len(set(sp.flag)) if n_clusters is None else n_clusters\n km = KMeans(n_clusters=K, init='k-means++', verbose=True, n_init=10)\n km.fit(sp.data)\n return km.labels_\n\n\ndef kmeans_np(sp, n_clusters=None):\n K = len(set(sp.flag)) if n_clusters is None else n_clusters\n centroid, mark = kmeans2(sp.data, K)\n return mark\n\n\ndef maxmin(sp, n_clusters=None):\n K = len(set(sp.flag)) if n_clusters is None else n_clusters\n samples = sp.samples\n\n centers = [np.random.randint(samples)]\n dist_table = np.array([], dtype=np.float).reshape((0, samples))\n\n while True:\n last_center = centers[-1]\n ndist = np.linalg.norm(sp.data - sp.data[last_center, :], axis=1)\n dist_table = np.vstack((dist_table, ndist))\n\n min_dist = dist_table.min(axis=0)\n\n if len(centers) >= K:\n break\n\n argmax = min_dist.argmax()\n if min_dist[argmax] != 0:\n centers.append(argmax)\n else:\n break\n\n mark = []\n for i in range(samples):\n if i in centers:\n mark.append(centers.index(i))\n else:\n mark.append(dist_table[:, i].argmin())\n\n return mark\n\n\ndef system_clustering(sp, n_clusters=None, distance=\"euclidean\",\n samples_threshold=np.inf):\n\n samples = sp.samples\n K = len(set(sp.flag)) if n_clusters is None else n_clusters\n\n clusters = [{i} for i in range(samples)]\n samples_dist_table = squareform(pdist(sp.data, distance))\n centers_dist_table = np.copy(samples_dist_table)\n\n while len(clusters) > K:\n np.fill_diagonal(centers_dist_table, np.inf)\n\n while True:\n min_dist = centers_dist_table.min()\n il, jl = np.where(centers_dist_table == min_dist)\n i, j = il[0], jl[0]\n if len(clusters[i]) + len(clusters[j]) > samples_threshold:\n centers_dist_table[i, j] = centers_dist_table[j, i] = np.inf\n else:\n break\n\n row_i = centers_dist_table[:, i]\n row_j = centers_dist_table[:, j]\n nr = np.maximum(row_i, row_j)\n centers_dist_table[:, i] = nr\n centers_dist_table[i, :] = nr\n\n centers_dist_table = np.delete(centers_dist_table, j, 1)\n centers_dist_table = np.delete(centers_dist_table, j, 0)\n\n clusters[i].update(clusters[j])\n clusters.pop(j)\n\n mark = [None for i in range(samples)]\n for i, c in enumerate(clusters):\n for j in c:\n mark[j] = i\n\n return mark\n\n\ndef main():\n method_list = {\n \"maxmin\": maxmin,\n \"system\": system_clustering,\n \"kmeans\": kmeans,\n \"kmeans_np\": kmeans_np,\n }\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\",\n help=\"path to the csv file\")\n parser.add_argument(\"config\",\n help=\"path to the config file\")\n parser.add_argument(\"-m\", \"--method\",\n type=lambda k: method_list[k],\n default=\"system\",\n help=\"clustering method\",)\n parser.add_argument(\"-p\", \"--pca\",\n type=int,\n default=0,\n help=\"PCA dimens\")\n parser.add_argument(\"-k\", \"--clusters\",\n type=int,\n default=None,\n help=\"PCA dimens\")\n args = parser.parse_args()\n\n sp = read_data(args.file, args.config)\n if args.pca > 0:\n pca(sp, args.pca)\n\n # clustering\n labels = args.method(sp, args.clusters)\n\n # guess what the real label is\n counter_dict = {}\n for label in set(labels):\n counter_dict[label] = Counter()\n\n for i, real_label in enumerate(sp.flag):\n counter_dict[labels[i]][real_label] += 1\n\n guess_map = {}\n for label in sorted(list(set(labels))):\n real_label, _ = counter_dict[label].most_common(1)[0]\n guess_map[label] = real_label\n\n result_labels = []\n correct = 0\n for i, real_label in enumerate(sp.flag):\n guess_label = guess_map[labels[i]]\n result_labels.append(guess_label)\n if guess_label == real_label:\n correct += 1\n\n # plot result\n print(\"Correct: %f\" % (correct / sp.samples))\n pandas_plot(sp, result_labels)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"scipy.cluster.vq.kmeans2",
"numpy.maximum",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"numpy.linalg.norm",
"numpy.copy",
"scipy.spatial.distance.pdist",
"numpy.delete",
"numpy.fill_diagonal",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.where",
"sklearn.decomposition.PCA",
"numpy.vstack",
"numpy.random.randint"
]
] |
tienln4/PaddleOCR-1
|
[
"786448503b3f23140798bdecde19e985027257b2"
] |
[
"tools/infer/utility.py"
] |
[
"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport os\nimport sys\nimport cv2\nimport numpy as np\nimport json\nfrom PIL import Image, ImageDraw, ImageFont\nimport math\nfrom paddle import inference\nimport time\nfrom ppocr.utils.logging import get_logger\n\n\ndef str2bool(v):\n return v.lower() in (\"true\", \"t\", \"1\")\n\n\ndef init_args():\n parser = argparse.ArgumentParser()\n # params for prediction engine\n parser.add_argument(\"--use_gpu\", type=str2bool, default=True)\n parser.add_argument(\"--ir_optim\", type=str2bool, default=True)\n parser.add_argument(\"--use_tensorrt\", type=str2bool, default=False)\n parser.add_argument(\"--min_subgraph_size\", type=int, default=15)\n parser.add_argument(\"--precision\", type=str, default=\"fp32\")\n parser.add_argument(\"--gpu_mem\", type=int, default=500)\n\n # params for text detector\n parser.add_argument(\"--image_dir\", type=str)\n parser.add_argument(\"--det_algorithm\", type=str, default='DB')\n parser.add_argument(\"--det_model_dir\", type=str)\n parser.add_argument(\"--det_limit_side_len\", type=float, default=960)\n parser.add_argument(\"--det_limit_type\", type=str, default='max')\n\n # DB parmas\n parser.add_argument(\"--det_db_thresh\", type=float, default=0.3)\n parser.add_argument(\"--det_db_box_thresh\", type=float, default=0.6)\n parser.add_argument(\"--det_db_unclip_ratio\", type=float, default=1.5)\n parser.add_argument(\"--max_batch_size\", type=int, default=10)\n parser.add_argument(\"--use_dilation\", type=str2bool, default=False)\n parser.add_argument(\"--det_db_score_mode\", type=str, default=\"fast\")\n # EAST parmas\n parser.add_argument(\"--det_east_score_thresh\", type=float, default=0.8)\n parser.add_argument(\"--det_east_cover_thresh\", type=float, default=0.1)\n parser.add_argument(\"--det_east_nms_thresh\", type=float, default=0.2)\n\n # SAST parmas\n parser.add_argument(\"--det_sast_score_thresh\", type=float, default=0.5)\n parser.add_argument(\"--det_sast_nms_thresh\", type=float, default=0.2)\n parser.add_argument(\"--det_sast_polygon\", type=str2bool, default=False)\n\n # params for text recognizer\n parser.add_argument(\"--rec_algorithm\", type=str, default='CRNN')\n parser.add_argument(\"--rec_model_dir\", type=str)\n parser.add_argument(\"--rec_image_shape\", type=str, default=\"3, 32, 320\")\n parser.add_argument(\"--rec_char_type\", type=str, default='ch')\n parser.add_argument(\"--rec_batch_num\", type=int, default=6)\n parser.add_argument(\"--max_text_length\", type=int, default=25)\n parser.add_argument(\"--rec_char_dict_path\", type=str, default=\"./benchmark/configs/vn_dict.txt\")\n parser.add_argument(\"--use_space_char\", type=str2bool, default=True)\n parser.add_argument(\n \"--vis_font_path\", type=str, default=\"./doc/fonts/simfang.ttf\")\n parser.add_argument(\"--drop_score\", type=float, default=0.5)\n\n # params for e2e\n parser.add_argument(\"--e2e_algorithm\", type=str, default='PGNet')\n parser.add_argument(\"--e2e_model_dir\", type=str)\n parser.add_argument(\"--e2e_limit_side_len\", type=float, default=768)\n parser.add_argument(\"--e2e_limit_type\", type=str, default='max')\n\n # PGNet parmas\n parser.add_argument(\"--e2e_pgnet_score_thresh\", type=float, default=0.5)\n parser.add_argument(\n \"--e2e_char_dict_path\", type=str, default=\"./ppocr/utils/ic15_dict.txt\")\n parser.add_argument(\"--e2e_pgnet_valid_set\", type=str, default='totaltext')\n parser.add_argument(\"--e2e_pgnet_polygon\", type=str2bool, default=True)\n parser.add_argument(\"--e2e_pgnet_mode\", type=str, default='fast')\n\n # params for text classifier\n parser.add_argument(\"--use_angle_cls\", type=str2bool, default=False)\n parser.add_argument(\"--cls_model_dir\", type=str)\n parser.add_argument(\"--cls_image_shape\", type=str, default=\"3, 48, 192\")\n parser.add_argument(\"--label_list\", type=list, default=['0', '180'])\n parser.add_argument(\"--cls_batch_num\", type=int, default=6)\n parser.add_argument(\"--cls_thresh\", type=float, default=0.9)\n\n parser.add_argument(\"--enable_mkldnn\", type=str2bool, default=False)\n parser.add_argument(\"--cpu_threads\", type=int, default=10)\n parser.add_argument(\"--use_pdserving\", type=str2bool, default=False)\n parser.add_argument(\"--warmup\", type=str2bool, default=True)\n\n # multi-process\n parser.add_argument(\"--use_mp\", type=str2bool, default=False)\n parser.add_argument(\"--total_process_num\", type=int, default=1)\n parser.add_argument(\"--process_id\", type=int, default=0)\n\n parser.add_argument(\"--benchmark\", type=str2bool, default=False)\n parser.add_argument(\"--save_log_path\", type=str, default=\"./log_output/\")\n\n parser.add_argument(\"--show_log\", type=str2bool, default=True)\n return parser\n\n\ndef parse_args():\n parser = init_args()\n return parser.parse_args()\n\n\ndef create_predictor(args, mode, logger):\n if mode == \"det\":\n model_dir = args.det_model_dir\n elif mode == 'cls':\n model_dir = args.cls_model_dir\n elif mode == 'rec':\n model_dir = args.rec_model_dir\n elif mode == 'table':\n model_dir = args.table_model_dir\n else:\n model_dir = args.e2e_model_dir\n\n if model_dir is None:\n logger.info(\"not find {} model file path {}\".format(mode, model_dir))\n sys.exit(0)\n model_file_path = model_dir + \"/inference.pdmodel\"\n params_file_path = model_dir + \"/inference.pdiparams\"\n if not os.path.exists(model_file_path):\n raise ValueError(\"not find model file path {}\".format(model_file_path))\n if not os.path.exists(params_file_path):\n raise ValueError(\"not find params file path {}\".format(\n params_file_path))\n\n config = inference.Config(model_file_path, params_file_path)\n\n if hasattr(args, 'precision'):\n if args.precision == \"fp16\" and args.use_tensorrt:\n precision = inference.PrecisionType.Half\n elif args.precision == \"int8\":\n precision = inference.PrecisionType.Int8\n else:\n precision = inference.PrecisionType.Float32\n else:\n precision = inference.PrecisionType.Float32\n\n if args.use_gpu:\n gpu_id = get_infer_gpuid()\n if gpu_id is None:\n raise ValueError(\n \"Not found GPU in current device. Please check your device or set args.use_gpu as False\"\n )\n config.enable_use_gpu(args.gpu_mem, 0)\n if args.use_tensorrt:\n config.enable_tensorrt_engine(\n precision_mode=precision,\n max_batch_size=args.max_batch_size,\n min_subgraph_size=args.min_subgraph_size)\n # skip the minmum trt subgraph\n if mode == \"det\":\n min_input_shape = {\n \"x\": [1, 3, 50, 50],\n \"conv2d_92.tmp_0\": [1, 120, 20, 20],\n \"conv2d_91.tmp_0\": [1, 24, 10, 10],\n \"conv2d_59.tmp_0\": [1, 96, 20, 20],\n \"nearest_interp_v2_1.tmp_0\": [1, 256, 10, 10],\n \"nearest_interp_v2_2.tmp_0\": [1, 256, 20, 20],\n \"conv2d_124.tmp_0\": [1, 256, 20, 20],\n \"nearest_interp_v2_3.tmp_0\": [1, 64, 20, 20],\n \"nearest_interp_v2_4.tmp_0\": [1, 64, 20, 20],\n \"nearest_interp_v2_5.tmp_0\": [1, 64, 20, 20],\n \"elementwise_add_7\": [1, 56, 2, 2],\n \"nearest_interp_v2_0.tmp_0\": [1, 256, 2, 2]\n }\n max_input_shape = {\n \"x\": [1, 3, 2000, 2000],\n \"conv2d_92.tmp_0\": [1, 120, 400, 400],\n \"conv2d_91.tmp_0\": [1, 24, 200, 200],\n \"conv2d_59.tmp_0\": [1, 96, 400, 400],\n \"nearest_interp_v2_1.tmp_0\": [1, 256, 200, 200],\n \"conv2d_124.tmp_0\": [1, 256, 400, 400],\n \"nearest_interp_v2_2.tmp_0\": [1, 256, 400, 400],\n \"nearest_interp_v2_3.tmp_0\": [1, 64, 400, 400],\n \"nearest_interp_v2_4.tmp_0\": [1, 64, 400, 400],\n \"nearest_interp_v2_5.tmp_0\": [1, 64, 400, 400],\n \"elementwise_add_7\": [1, 56, 400, 400],\n \"nearest_interp_v2_0.tmp_0\": [1, 256, 400, 400]\n }\n opt_input_shape = {\n \"x\": [1, 3, 640, 640],\n \"conv2d_92.tmp_0\": [1, 120, 160, 160],\n \"conv2d_91.tmp_0\": [1, 24, 80, 80],\n \"conv2d_59.tmp_0\": [1, 96, 160, 160],\n \"nearest_interp_v2_1.tmp_0\": [1, 256, 80, 80],\n \"nearest_interp_v2_2.tmp_0\": [1, 256, 160, 160],\n \"conv2d_124.tmp_0\": [1, 256, 160, 160],\n \"nearest_interp_v2_3.tmp_0\": [1, 64, 160, 160],\n \"nearest_interp_v2_4.tmp_0\": [1, 64, 160, 160],\n \"nearest_interp_v2_5.tmp_0\": [1, 64, 160, 160],\n \"elementwise_add_7\": [1, 56, 40, 40],\n \"nearest_interp_v2_0.tmp_0\": [1, 256, 40, 40]\n }\n min_pact_shape = {\n \"nearest_interp_v2_26.tmp_0\": [1, 256, 20, 20],\n \"nearest_interp_v2_27.tmp_0\": [1, 64, 20, 20],\n \"nearest_interp_v2_28.tmp_0\": [1, 64, 20, 20],\n \"nearest_interp_v2_29.tmp_0\": [1, 64, 20, 20]\n }\n max_pact_shape = {\n \"nearest_interp_v2_26.tmp_0\": [1, 256, 400, 400],\n \"nearest_interp_v2_27.tmp_0\": [1, 64, 400, 400],\n \"nearest_interp_v2_28.tmp_0\": [1, 64, 400, 400],\n \"nearest_interp_v2_29.tmp_0\": [1, 64, 400, 400]\n }\n opt_pact_shape = {\n \"nearest_interp_v2_26.tmp_0\": [1, 256, 160, 160],\n \"nearest_interp_v2_27.tmp_0\": [1, 64, 160, 160],\n \"nearest_interp_v2_28.tmp_0\": [1, 64, 160, 160],\n \"nearest_interp_v2_29.tmp_0\": [1, 64, 160, 160]\n }\n min_input_shape.update(min_pact_shape)\n max_input_shape.update(max_pact_shape)\n opt_input_shape.update(opt_pact_shape)\n elif mode == \"rec\":\n min_input_shape = {\"x\": [1, 3, 32, 10]}\n max_input_shape = {\"x\": [args.rec_batch_num, 3, 32, 2000]}\n opt_input_shape = {\"x\": [args.rec_batch_num, 3, 32, 320]}\n elif mode == \"cls\":\n min_input_shape = {\"x\": [1, 3, 48, 10]}\n max_input_shape = {\"x\": [args.rec_batch_num, 3, 48, 2000]}\n opt_input_shape = {\"x\": [args.rec_batch_num, 3, 48, 320]}\n else:\n min_input_shape = {\"x\": [1, 3, 10, 10]}\n max_input_shape = {\"x\": [1, 3, 1000, 1000]}\n opt_input_shape = {\"x\": [1, 3, 500, 500]}\n config.set_trt_dynamic_shape_info(min_input_shape, max_input_shape,\n opt_input_shape)\n\n else:\n config.disable_gpu()\n if hasattr(args, \"cpu_threads\"):\n config.set_cpu_math_library_num_threads(args.cpu_threads)\n else:\n # default cpu threads as 10\n config.set_cpu_math_library_num_threads(10)\n if args.enable_mkldnn:\n # cache 10 different shapes for mkldnn to avoid memory leak\n config.set_mkldnn_cache_capacity(10)\n config.enable_mkldnn()\n\n # enable memory optim\n config.enable_memory_optim()\n #config.disable_glog_info()\n\n config.delete_pass(\"conv_transpose_eltwiseadd_bn_fuse_pass\")\n if mode == 'table':\n config.delete_pass(\"fc_fuse_pass\") # not supported for table\n config.switch_use_feed_fetch_ops(False)\n config.switch_ir_optim(True)\n\n # create predictor\n predictor = inference.create_predictor(config)\n input_names = predictor.get_input_names()\n for name in input_names:\n input_tensor = predictor.get_input_handle(name)\n output_names = predictor.get_output_names()\n output_tensors = []\n for output_name in output_names:\n output_tensor = predictor.get_output_handle(output_name)\n output_tensors.append(output_tensor)\n return predictor, input_tensor, output_tensors, config\n\n\ndef get_infer_gpuid():\n cmd = \"nvidia-smi\"\n res = os.popen(cmd).readlines()\n if len(res) == 0:\n return None\n cmd = \"env | grep CUDA_VISIBLE_DEVICES\"\n env_cuda = os.popen(cmd).readlines()\n if len(env_cuda) == 0:\n return 0\n else:\n gpu_id = env_cuda[0].strip().split(\"=\")[1]\n return int(gpu_id[0])\n\n\ndef draw_e2e_res(dt_boxes, strs, img_path):\n src_im = cv2.imread(img_path)\n for box, str in zip(dt_boxes, strs):\n box = box.astype(np.int32).reshape((-1, 1, 2))\n cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)\n cv2.putText(\n src_im,\n str,\n org=(int(box[0, 0, 0]), int(box[0, 0, 1])),\n fontFace=cv2.FONT_HERSHEY_COMPLEX,\n fontScale=0.7,\n color=(0, 255, 0),\n thickness=1)\n return src_im\n\n\ndef draw_text_det_res(dt_boxes, img_path):\n src_im = cv2.imread(img_path)\n for box in dt_boxes:\n box = np.array(box).astype(np.int32).reshape(-1, 2)\n cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)\n return src_im\n\n\ndef resize_img(img, input_size=600):\n \"\"\"\n resize img and limit the longest side of the image to input_size\n \"\"\"\n img = np.array(img)\n im_shape = img.shape\n im_size_max = np.max(im_shape[0:2])\n im_scale = float(input_size) / float(im_size_max)\n img = cv2.resize(img, None, None, fx=im_scale, fy=im_scale)\n return img\n\n\ndef draw_ocr(image,\n boxes,\n txts=None,\n scores=None,\n drop_score=0.5,\n font_path=\"./doc/fonts/simfang.ttf\"):\n \"\"\"\n Visualize the results of OCR detection and recognition\n args:\n image(Image|array): RGB image\n boxes(list): boxes with shape(N, 4, 2)\n txts(list): the texts\n scores(list): txxs corresponding scores\n drop_score(float): only scores greater than drop_threshold will be visualized\n font_path: the path of font which is used to draw text\n return(array):\n the visualized img\n \"\"\"\n if scores is None:\n scores = [1] * len(boxes)\n box_num = len(boxes)\n for i in range(box_num):\n if scores is not None and (scores[i] < drop_score or\n math.isnan(scores[i])):\n continue\n box = np.reshape(np.array(boxes[i]), [-1, 1, 2]).astype(np.int64)\n image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)\n if txts is not None:\n img = np.array(resize_img(image, input_size=600))\n txt_img = text_visual(\n txts,\n scores,\n img_h=img.shape[0],\n img_w=600,\n threshold=drop_score,\n font_path=font_path)\n img = np.concatenate([np.array(img), np.array(txt_img)], axis=1)\n return img\n return image\n\n\ndef draw_ocr_box_txt(image,\n boxes,\n txts,\n scores=None,\n drop_score=0.5,\n font_path=\"./doc/simfang.ttf\"):\n h, w = image.height, image.width\n img_left = image.copy()\n img_right = Image.new('RGB', (w, h), (255, 255, 255))\n\n import random\n\n random.seed(0)\n draw_left = ImageDraw.Draw(img_left)\n draw_right = ImageDraw.Draw(img_right)\n for idx, (box, txt) in enumerate(zip(boxes, txts)):\n if scores is not None and scores[idx] < drop_score:\n continue\n color = (random.randint(0, 255), random.randint(0, 255),\n random.randint(0, 255))\n draw_left.polygon(box, fill=color)\n draw_right.polygon(\n [\n box[0][0], box[0][1], box[1][0], box[1][1], box[2][0],\n box[2][1], box[3][0], box[3][1]\n ],\n outline=color)\n box_height = math.sqrt((box[0][0] - box[3][0])**2 + (box[0][1] - box[3][\n 1])**2)\n box_width = math.sqrt((box[0][0] - box[1][0])**2 + (box[0][1] - box[1][\n 1])**2)\n if box_height > 2 * box_width:\n font_size = max(int(box_width * 0.9), 10)\n font = ImageFont.truetype(font_path, font_size, encoding=\"utf-8\")\n cur_y = box[0][1]\n for c in txt:\n char_size = font.getsize(c)\n draw_right.text(\n (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font)\n cur_y += char_size[1]\n else:\n font_size = max(int(box_height * 0.8), 10)\n font = ImageFont.truetype(font_path, font_size, encoding=\"utf-8\")\n draw_right.text(\n [box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font)\n img_left = Image.blend(image, img_left, 0.5)\n img_show = Image.new('RGB', (w * 2, h), (255, 255, 255))\n img_show.paste(img_left, (0, 0, w, h))\n img_show.paste(img_right, (w, 0, w * 2, h))\n return np.array(img_show)\n\n\ndef str_count(s):\n \"\"\"\n Count the number of Chinese characters,\n a single English character and a single number\n equal to half the length of Chinese characters.\n args:\n s(string): the input of string\n return(int):\n the number of Chinese characters\n \"\"\"\n import string\n count_zh = count_pu = 0\n s_len = len(s)\n en_dg_count = 0\n for c in s:\n if c in string.ascii_letters or c.isdigit() or c.isspace():\n en_dg_count += 1\n elif c.isalpha():\n count_zh += 1\n else:\n count_pu += 1\n return s_len - math.ceil(en_dg_count / 2)\n\n\ndef text_visual(texts,\n scores,\n img_h=400,\n img_w=600,\n threshold=0.,\n font_path=\"./doc/simfang.ttf\"):\n \"\"\"\n create new blank img and draw txt on it\n args:\n texts(list): the text will be draw\n scores(list|None): corresponding score of each txt\n img_h(int): the height of blank img\n img_w(int): the width of blank img\n font_path: the path of font which is used to draw text\n return(array):\n \"\"\"\n if scores is not None:\n assert len(texts) == len(\n scores), \"The number of txts and corresponding scores must match\"\n\n def create_blank_img():\n blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255\n blank_img[:, img_w - 1:] = 0\n blank_img = Image.fromarray(blank_img).convert(\"RGB\")\n draw_txt = ImageDraw.Draw(blank_img)\n return blank_img, draw_txt\n\n blank_img, draw_txt = create_blank_img()\n\n font_size = 20\n txt_color = (0, 0, 0)\n font = ImageFont.truetype(font_path, font_size, encoding=\"utf-8\")\n\n gap = font_size + 5\n txt_img_list = []\n count, index = 1, 0\n for idx, txt in enumerate(texts):\n index += 1\n if scores[idx] < threshold or math.isnan(scores[idx]):\n index -= 1\n continue\n first_line = True\n while str_count(txt) >= img_w // font_size - 4:\n tmp = txt\n txt = tmp[:img_w // font_size - 4]\n if first_line:\n new_txt = str(index) + ': ' + txt\n first_line = False\n else:\n new_txt = ' ' + txt\n draw_txt.text((0, gap * count), new_txt, txt_color, font=font)\n txt = tmp[img_w // font_size - 4:]\n if count >= img_h // gap - 1:\n txt_img_list.append(np.array(blank_img))\n blank_img, draw_txt = create_blank_img()\n count = 0\n count += 1\n if first_line:\n new_txt = str(index) + ': ' + txt + ' ' + '%.3f' % (scores[idx])\n else:\n new_txt = \" \" + txt + \" \" + '%.3f' % (scores[idx])\n draw_txt.text((0, gap * count), new_txt, txt_color, font=font)\n # whether add new blank img or not\n if count >= img_h // gap - 1 and idx + 1 < len(texts):\n txt_img_list.append(np.array(blank_img))\n blank_img, draw_txt = create_blank_img()\n count = 0\n count += 1\n txt_img_list.append(np.array(blank_img))\n if len(txt_img_list) == 1:\n blank_img = np.array(txt_img_list[0])\n else:\n blank_img = np.concatenate(txt_img_list, axis=1)\n return np.array(blank_img)\n\n\ndef base64_to_cv2(b64str):\n import base64\n data = base64.b64decode(b64str.encode('utf8'))\n data = np.fromstring(data, np.uint8)\n data = cv2.imdecode(data, cv2.IMREAD_COLOR)\n return data\n\n\ndef draw_boxes(image, boxes, scores=None, drop_score=0.5):\n if scores is None:\n scores = [1] * len(boxes)\n for (box, score) in zip(boxes, scores):\n if score < drop_score:\n continue\n box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)\n image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)\n return image\n\n\ndef get_rotate_crop_image(img, points):\n '''\n img_height, img_width = img.shape[0:2]\n left = int(np.min(points[:, 0]))\n right = int(np.max(points[:, 0]))\n top = int(np.min(points[:, 1]))\n bottom = int(np.max(points[:, 1]))\n img_crop = img[top:bottom, left:right, :].copy()\n points[:, 0] = points[:, 0] - left\n points[:, 1] = points[:, 1] - top\n '''\n assert len(points) == 4, \"shape of points must be 4*2\"\n img_crop_width = int(\n max(\n np.linalg.norm(points[0] - points[1]),\n np.linalg.norm(points[2] - points[3])))\n img_crop_height = int(\n max(\n np.linalg.norm(points[0] - points[3]),\n np.linalg.norm(points[1] - points[2])))\n pts_std = np.float32([[0, 0], [img_crop_width, 0],\n [img_crop_width, img_crop_height],\n [0, img_crop_height]])\n M = cv2.getPerspectiveTransform(points, pts_std)\n dst_img = cv2.warpPerspective(\n img,\n M, (img_crop_width, img_crop_height),\n borderMode=cv2.BORDER_REPLICATE,\n flags=cv2.INTER_CUBIC)\n dst_img_height, dst_img_width = dst_img.shape[0:2]\n if dst_img_height * 1.0 / dst_img_width >= 1.5:\n dst_img = np.rot90(dst_img)\n return dst_img\n\n\nif __name__ == '__main__':\n pass\n"
] |
[
[
"numpy.rot90",
"numpy.linalg.norm",
"numpy.ones",
"numpy.concatenate",
"numpy.max",
"numpy.fromstring",
"numpy.float32",
"numpy.array"
]
] |
zhouwubai/CarND-Term3
|
[
"096f11903ba15fac2cf1dd26984d20a672c8360c"
] |
[
"lectures/TrajectoryGenerator/helpers.py"
] |
[
"from math import sqrt, exp\nfrom matplotlib import pyplot as plt\n\n\nclass Vehicle(object):\n \"\"\"\n Helper class. Non-ego vehicles move w/ constant acceleration\n \"\"\"\n def __init__(self, start):\n self.start_state = start\n\n def state_in(self, t):\n s = self.start_state[:3]\n d = self.start_state[3:]\n state = [\n s[0] + (s[1] * t) + s[2] * t**2 / 2.0,\n s[1] + s[2] * t,\n s[2],\n d[0] + (d[1] * t) + d[2] * t**2 / 2.0,\n d[1] + d[2] * t,\n d[2],\n ]\n return state\n\n\ndef logistic(x):\n \"\"\"\n A function that returns a value between 0 and 1 for x in the\n range [0, infinity] and -1 to 1 for x in the range [-infinity, infinity].\n\n Useful for cost functions.\n \"\"\"\n return 2.0 / (1 + exp(-x)) - 1.0\n\n\ndef to_equation(coefficients):\n \"\"\"\n Takes the coefficients of a polynomial and creates a function of\n time from them.\n \"\"\"\n def f(t):\n total = 0.0\n for i, c in enumerate(coefficients):\n total += c * t ** i\n return total\n return f\n\n\ndef differentiate(coefficients):\n \"\"\"\n Calculates the derivative of a polynomial and returns\n the corresponding coefficients.\n \"\"\"\n new_cos = []\n for deg, prev_co in enumerate(coefficients[1:]):\n new_cos.append((deg + 1) * prev_co)\n return new_cos\n\n\ndef nearest_approach_to_any_vehicle(traj, vehicles):\n \"\"\"\n Calculates the closest distance to any vehicle during a trajectory.\n \"\"\"\n closest = 999999\n for v in vehicles.values():\n d = nearest_approach(traj, v)\n if d < closest:\n closest = d\n return closest\n\n\ndef nearest_approach(traj, vehicle):\n closest = 999999\n s_, d_, T = traj\n s = to_equation(s_)\n d = to_equation(d_)\n for i in range(100):\n t = float(i) / 100 * T\n cur_s = s(t)\n cur_d = d(t)\n targ_s, _, _, targ_d, _, _ = vehicle.state_in(t)\n dist = sqrt((cur_s - targ_s) ** 2 + (cur_d - targ_d) ** 2)\n if dist < closest:\n closest = dist\n return closest\n\n\ndef show_trajectory(s_coeffs, d_coeffs, T, vehicle=None):\n s = to_equation(s_coeffs)\n d = to_equation(d_coeffs)\n X = []\n Y = []\n if vehicle:\n X2 = []\n Y2 = []\n t = 0\n while t <= T + 0.01:\n X.append(s(t))\n Y.append(d(t))\n if vehicle:\n s_, _, _, d_, _, _ = vehicle.state_in(t)\n X2.append(s_)\n Y2.append(d_)\n t += 0.25\n plt.scatter(X, Y, color=\"blue\")\n if vehicle:\n plt.scatter(X2, Y2, color=\"red\")\n plt.show()\n\n\ndef get_f_and_N_derivatives(coeffs, N=3):\n functions = [to_equation(coeffs)]\n for i in range(N):\n coeffs = differentiate(coeffs)\n functions.append(to_equation(coeffs))\n return functions\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.scatter"
]
] |
flaxandteal/tablespy
|
[
"4918e7673802d15373b324ec719179f8565717e7"
] |
[
"tests/test_locode.py"
] |
[
"import pytest\nimport pandas as pd\nfrom tablespy.inspector import Inspector\n\nBLANK_COLS = 500\nBLANK_ROWS = 500\n\n\[email protected]\ndef blank_data():\n return [\n [''] * BLANK_COLS\n ] * BLANK_ROWS\n\[email protected]\ndef basic_df(blank_data):\n df = pd.DataFrame(blank_data)\n df.iloc[3, 11] = \"Test Title\"\n df.iloc[4:50, 11] = range(1, 47)\n df.iloc[4:50, 12] = 12\n df.iloc[4:50, 13:20] = 'A'\n return df\n\[email protected]\ndef double_df(basic_df):\n df = basic_df.copy()\n df.iloc[213, 11] = \"Other\"\n df.iloc[213, 12] = \"Title\"\n df.iloc[214:250, 11] = range(1, 37)\n df.iloc[214:250, 12] = 12\n df.iloc[220:250, 12] = ''\n df.iloc[214:250, 13:20] = 'A'\n df.iloc[214:250, 18] = ''\n\n # This leaves a single column isolated - too narrow to count as a table, hence double_df,\n # not triple\n\n return df\n\nclass TestInspector:\n def test_can_extract_simple_table(self, basic_df):\n inspector = Inspector()\n inspection = inspector.inspect_df(basic_df)\n\n assert list(inspection.regions.keys()) == [1]\n assert inspection.regions[1]['lower-left'] == (4, 11)\n assert inspection.regions[1]['upper-right'] == (49, 19)\n assert inspection.regions[1]['header-boundary'] == (4, 19)\n assert inspection.regions[1]['title']['loc'] == (3, 11, 1)\n assert inspection.regions[1]['title']['text'] == \"Test Title\"\n\n def test_can_extract_double_table(self, double_df):\n inspector = Inspector()\n inspection = inspector.inspect_df(double_df)\n\n assert list(inspection.regions.keys()) == [1, 2]\n\n first_key = [i for i, v in inspection.regions.items() if v['title']['text'] == 'Test Title'][0]\n second_key = 3 - first_key\n\n assert inspection.regions[first_key]['lower-left'] == (4, 11)\n assert inspection.regions[first_key]['upper-right'] == (49, 19)\n assert inspection.regions[first_key]['header-boundary'] == (4, 19)\n assert inspection.regions[first_key]['title']['loc'] == (3, 11, 1)\n assert inspection.regions[first_key]['title']['text'] == \"Test Title\"\n\n assert inspection.regions[second_key]['lower-left'] == (214, 11)\n assert inspection.regions[second_key]['upper-right'] == (249, 17)\n assert inspection.regions[second_key]['header-boundary'] == (214, 17)\n assert inspection.regions[second_key]['title']['loc'] == (213, 11, 2)\n assert inspection.regions[second_key]['title']['text'] == \"Other\\nTitle\"\n"
] |
[
[
"pandas.DataFrame"
]
] |
demmojo/ResampleAndInterpolate
|
[
"c7730cf42b6dd55cb5cef331885d9adeae91c500"
] |
[
"ResampleAndInterpolate.py"
] |
[
"# Copyright 2019 Blok-Z\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\"\"\"ResampleAndInterpolate changes the sampling rate of original data from every 1 hour to every 10 seconds and then\n applies linear interpolation to the missing data.\n\"\"\"\n\nimport pandas as pd\n\n# Assign spreadsheet filename to `file`\nfile = 'original.xlsx'\n\n# Load spreadsheet\nxl = pd.ExcelFile(file)\n\nindex = pd.date_range('2018-10-01', periods=17, freq='H') # creates a series of dates in hour intervals\n\n# pandas dataframes are used to store the original and interpolated data\noriginal_data = xl.parse(xl.sheet_names[0], usecols=['Value']) # store Actual Production values\noriginal_data.index = index # sets index to date series\noriginal_data.index.name = 'Date (Year-Month-Day Hour:Minute:Second'\ninterpolated_data = original_data.resample('10S').interpolate() # upsample data to every 10sec and linearly interpolate\n\n# Specify a writer for excel files\nwriter = pd.ExcelWriter('new.xlsx', engine='xlsxwriter')\n\n# Write your DataFrame to a file\ninterpolated_data.to_excel(writer, 'Sheet1')\n\n# Save the result\nwriter.save()\n\n\n"
] |
[
[
"pandas.ExcelWriter",
"pandas.ExcelFile",
"pandas.date_range"
]
] |
ishine/AttEncDecRNN
|
[
"d64e3e294cd8ccfc1118b8e607955019a61e0628"
] |
[
"model.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom beam import Beam\n\n\nclass EncoderRNN(nn.Module):\n \"\"\"\"encode the input sequence with Bi-GRU\"\"\"\n\n def __init__(self, num_input, num_hidden, num_token, padding_idx, emb_dropout, hid_dropout):\n super(EncoderRNN, self).__init__()\n self.num_hidden = num_hidden\n self.emb = nn.Embedding(num_token, num_input, padding_idx=padding_idx)\n self.bi_gru = nn.GRU(num_input, num_hidden, 1, batch_first=True, bidirectional=True)\n self.enc_emb_dp = nn.Dropout(emb_dropout)\n self.enc_hid_dp = nn.Dropout(hid_dropout)\n\n def init_hidden(self, batch_size):\n weight = next(self.parameters())\n h0 = weight.new_zeros(2, batch_size, self.num_hidden)\n return h0\n\n def forward(self, input, mask):\n hidden = self.init_hidden(input.size(0))\n input = self.enc_emb_dp(self.emb(input))\n length = mask.sum(1).tolist()\n total_length = mask.size(1)\n input = nn.utils.rnn.pack_padded_sequence(input, length, batch_first=True)\n output, hidden = self.bi_gru(input, hidden)\n output = torch.nn.utils.rnn.pad_packed_sequence(\n output, batch_first=True, total_length=total_length\n )[0]\n output = self.enc_hid_dp(output)\n hidden = torch.cat([hidden[0], hidden[1]], dim=-1)\n return output, hidden\n\n\nclass Attention(nn.Module):\n \"\"\"Attention Mechanism\"\"\"\n\n def __init__(self, num_hidden, ncontext, natt):\n super(Attention, self).__init__()\n self.h2s = nn.Linear(num_hidden, natt)\n self.s2s = nn.Linear(ncontext, natt)\n self.a2o = nn.Linear(natt, 1)\n\n def forward(self, hidden, mask, context):\n shape = context.size()\n attn_h = self.s2s(context.view(-1, shape[2]))\n attn_h = attn_h.view(shape[0], shape[1], -1)\n attn_h += self.h2s(hidden).unsqueeze(1).expand_as(attn_h)\n logit = self.a2o(torch.tanh(attn_h)).view(shape[0], shape[1])\n if mask.any():\n logit.data.masked_fill_(~mask, -float(\"inf\"))\n softmax = F.softmax(logit, dim=1)\n output = torch.bmm(softmax.unsqueeze(1), context).squeeze(1)\n return output\n\n\nclass DecoderRNN(nn.Module):\n def __init__(self, num_input, num_hidden, enc_ncontext, natt, nreadout, readout_dropout):\n super(DecoderRNN, self).__init__()\n self.gru1 = nn.GRUCell(num_input, num_hidden)\n self.gru2 = nn.GRUCell(enc_ncontext, num_hidden)\n self.enc_attn = Attention(num_hidden, enc_ncontext, natt)\n self.embedding2out = nn.Linear(num_input, nreadout)\n self.hidden2out = nn.Linear(num_hidden, nreadout)\n self.c2o = nn.Linear(enc_ncontext, nreadout)\n self.readout_dp = nn.Dropout(readout_dropout)\n\n def forward(self, emb, hidden, enc_mask, enc_context):\n hidden = self.gru1(emb, hidden)\n attn_enc = self.enc_attn(hidden, enc_mask, enc_context)\n hidden = self.gru2(attn_enc, hidden)\n output = torch.tanh(self.embedding2out(emb) + self.hidden2out(hidden) + self.c2o(attn_enc))\n output = self.readout_dp(output)\n return output, hidden\n\n\nclass AttEncDecRNN(nn.Module):\n def __init__(self, opt):\n super(AttEncDecRNN, self).__init__()\n self.dec_num_hidden = opt.dec_num_hidden\n self.dec_sos = opt.dec_sos\n self.dec_eos = opt.dec_eos\n self.dec_pad = opt.dec_pad\n self.enc_pad = opt.enc_pad\n\n self.emb = nn.Embedding(opt.dec_num_token, opt.dec_num_input, padding_idx=opt.dec_pad)\n self.encoder = EncoderRNN(\n opt.enc_num_input,\n opt.enc_num_hidden,\n opt.enc_num_token,\n opt.enc_pad,\n opt.enc_emb_dropout,\n opt.enc_hid_dropout,\n )\n self.decoder = DecoderRNN(\n opt.dec_num_input,\n opt.dec_num_hidden,\n 2 * opt.enc_num_hidden,\n opt.dec_natt,\n opt.nreadout,\n opt.readout_dropout,\n )\n self.affine = nn.Linear(opt.nreadout, opt.dec_num_token)\n self.init_affine = nn.Linear(2 * opt.enc_num_hidden, opt.dec_num_hidden)\n self.dec_emb_dp = nn.Dropout(opt.dec_emb_dropout)\n\n def forward(self, src, src_mask, f_trg, f_trg_mask, b_trg=None, b_trg_mask=None):\n enc_context, _ = self.encoder(src, src_mask)\n enc_context = enc_context.contiguous()\n\n avg_enc_context = enc_context.sum(1)\n enc_context_len = src_mask.sum(1).unsqueeze(-1).expand_as(avg_enc_context)\n avg_enc_context = avg_enc_context / enc_context_len\n\n attn_mask = src_mask.bool()\n\n hidden = torch.tanh(self.init_affine(avg_enc_context))\n\n loss = 0\n for i in range(f_trg.size(1) - 1):\n output, hidden = self.decoder(\n self.dec_emb_dp(self.emb(f_trg[:, i])), hidden, attn_mask, enc_context\n )\n loss += (\n F.cross_entropy(self.affine(output), f_trg[:, i + 1], reduction=\"none\")\n * f_trg_mask[:, i + 1]\n )\n w_loss = loss.sum() / f_trg_mask[:, 1:].sum()\n loss = loss.mean()\n return loss.unsqueeze(0), w_loss.unsqueeze(0)\n\n def beamsearch(\n self, src, src_mask, beam_size=10, normalize=False, max_len=None, min_len=None\n ):\n max_len = src.size(1) * 3 if max_len is None else max_len\n min_len = src.size(1) / 2 if min_len is None else min_len\n\n enc_context, _ = self.encoder(src, src_mask)\n enc_context = enc_context.contiguous()\n\n avg_enc_context = enc_context.sum(1)\n enc_context_len = src_mask.sum(1).unsqueeze(-1).expand_as(avg_enc_context)\n avg_enc_context = avg_enc_context / enc_context_len\n\n attn_mask = src_mask.bool()\n\n hidden = torch.tanh(self.init_affine(avg_enc_context))\n\n prev_beam = Beam(beam_size)\n prev_beam.candidates = [[self.dec_sos]]\n prev_beam.scores = [0]\n f_done = lambda x: x[-1] == self.dec_eos\n\n valid_size = beam_size\n\n hyp_list = []\n for k in range(max_len):\n candidates = prev_beam.candidates\n input = src.new_tensor([cand[-1] for cand in candidates])\n input = self.dec_emb_dp(self.emb(input))\n output, hidden = self.decoder(input, hidden, attn_mask, enc_context)\n log_prob = F.log_softmax(self.affine(output), dim=1)\n if k < min_len:\n log_prob[:, self.dec_eos] = -float(\"inf\")\n if k == max_len - 1:\n eos_prob = log_prob[:, self.dec_eos].clone()\n log_prob[:, :] = -float(\"inf\")\n log_prob[:, self.dec_eos] = eos_prob\n next_beam = Beam(valid_size)\n done_list, remain_list = next_beam.step(-log_prob, prev_beam, f_done)\n hyp_list.extend(done_list)\n valid_size -= len(done_list)\n\n if valid_size == 0:\n break\n\n beam_remain_ix = src.new_tensor(remain_list)\n enc_context = enc_context.index_select(0, beam_remain_ix)\n attn_mask = attn_mask.index_select(0, beam_remain_ix)\n hidden = hidden.index_select(0, beam_remain_ix)\n prev_beam = next_beam\n score_list = [hyp[1] for hyp in hyp_list]\n hyp_list = [\n hyp[0][1 : hyp[0].index(self.dec_eos)]\n if self.dec_eos in hyp[0]\n else hyp[0][1:]\n for hyp in hyp_list\n ]\n if normalize:\n for k, (hyp, score) in enumerate(zip(hyp_list, score_list)):\n if len(hyp) > 0:\n score_list[k] = score_list[k] / len(hyp)\n score = hidden.new_tensor(score_list)\n sort_score, sort_ix = torch.sort(score)\n output = []\n for ix in sort_ix.tolist():\n output.append((hyp_list[ix], score[ix].item()))\n return output\n"
] |
[
[
"torch.nn.Dropout",
"torch.nn.functional.softmax",
"torch.cat",
"torch.nn.GRU",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.nn.Embedding",
"torch.tanh",
"torch.nn.Linear",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.sort",
"torch.nn.GRUCell"
]
] |
Pandinosaurus/pyts
|
[
"1e584877bc3f06194ceb530a156d8a10e32c12a5"
] |
[
"pyts/datasets/tests/test_make.py"
] |
[
"\"\"\"Testing for datatset generation.\"\"\"\n\n# Author: Johann Faouzi <[email protected]>\n# License: BSD-3-Clause\n\nimport numpy as np\nimport pytest\nimport re\nfrom pyts.datasets import make_cylinder_bell_funnel\n\n\[email protected](\n 'params, error, err_msg',\n [({'n_samples': '3'}, TypeError, \"'n_samples' must be an integer.\"),\n\n ({'n_samples': -1}, ValueError,\n \"'n_samples' must be a positive integer.\"),\n\n ({'weights': [1]}, ValueError,\n \"'weights' must be None or a list with 2 or 3 elements (got 1).\"),\n\n ({'weights': [1, 2, 3, 4]}, ValueError,\n \"'weights' must be None or a list with 2 or 3 elements (got 4).\"),\n\n ({'weights': [0.5, 1.5]}, ValueError,\n \"'sum(weights)' cannot be larger than 1 if len(weights) == 2 (got 2.0)\")]\n)\ndef test_parameter_check_make_cylinder_bell_funnel(params, error, err_msg):\n \"\"\"Test parameter validation.\"\"\"\n with pytest.raises(error, match=re.escape(err_msg)):\n make_cylinder_bell_funnel(**params)\n\n\[email protected](\n 'params, class_balance_desired',\n [({'n_samples': 9}, [3, 3, 3]),\n ({'n_samples': 90}, [30, 30, 30]),\n ({'n_samples': 10, 'weights': [0., 0.5, 0.5]}, [0, 5, 5]),\n ({'n_samples': 10, 'weights': [0., 1., 1.]}, [0, 10, 10]),\n ({'n_samples': 10, 'weights': [0., 1., 0.]}, [0, 10]),\n ({'n_samples': 10, 'weights': np.array([0., 0.5, 0.5])}, [0, 5, 5]),\n ({'n_samples': 10, 'weights': (0., 0.5, 0.5)}, [0, 5, 5]),\n ({'n_samples': 10, 'weights': (0.5, 0.5, 0.)}, [5, 5]),\n ({'n_samples': 10, 'weights': (0.5, 0.5)}, [5, 5]),\n ({'n_samples': 10, 'weights': (0.8, 0.2)}, [8, 2])]\n)\ndef test_class_balance_make_cylinder_bell_funnel(params,\n class_balance_desired):\n \"\"\"Test that the class balance is the expected one.\"\"\"\n X, y = make_cylinder_bell_funnel(**params)\n class_balance_actual = np.bincount(y)\n np.testing.assert_array_equal(class_balance_actual, class_balance_desired)\n\n\[email protected](\n 'params',\n [{},\n {'return_params': True},\n {'n_samples': 100, 'return_params': True}])\ndef test_return_params_make_cylinder_bell_funnel(params):\n \"\"\"Test the return objects.\"\"\"\n res = make_cylinder_bell_funnel(**params)\n assert isinstance(res[0], np.ndarray)\n assert isinstance(res[1], np.ndarray)\n if 'return_params' in params.keys() and params['return_params']:\n parameters = res[2]\n assert isinstance(parameters, dict)\n assert isinstance(parameters['a'], (int, np.integer))\n assert isinstance(parameters['b'], (int, np.integer))\n assert isinstance(parameters['eta'], (float, np.floating))\n assert isinstance(parameters['epsilon'], np.ndarray)\n if 'n_samples' in params:\n assert parameters['epsilon'].shape == (params['n_samples'], 128)\n else:\n assert parameters['epsilon'].shape == (30, 128)\n\n\[email protected]('params', [{}, {'shuffle': False}])\ndef test_shuffle_make_cylinder_bell_funnel(params):\n \"\"\"Test that shuffling works as expected.\"\"\"\n _, y = make_cylinder_bell_funnel(**params)\n arr_desired_no_shuffle = np.repeat(np.arange(3), 10)\n if 'shuffle' in params.keys() and (not params['shuffle']):\n np.testing.assert_array_equal(y, arr_desired_no_shuffle)\n else:\n assert not np.array_equal(y, arr_desired_no_shuffle)\n"
] |
[
[
"numpy.array_equal",
"numpy.arange",
"numpy.testing.assert_array_equal",
"numpy.bincount",
"numpy.array"
]
] |
GitPrakhar112/dsmp-pre-work
|
[
"6056e5d4b3c6efc84d0f14b57a595528f4e30fe5"
] |
[
"Probability-of-the-Loan-Defaulters/code.py"
] |
[
"# --------------\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load the dataframe\ndf = pd.read_csv(path)\n\n# probability of fico score greater than 700\n\np_a = df[df['fico'].astype(float) >700].shape[0]/df.shape[0]\nprint(p_a)\n\n\n# probability of purpose == debt_consolidation\np_b = df[df['purpose']== 'debt_consolidation'].shape[0]/df.shape[0]\nprint(p_b)\n\n# Create new dataframe for condition ['purpose']== 'debt_consolidation' \ndf1 = df[df['purpose']== 'debt_consolidation']\n\n# Calculate the P(A|B)\np_a_b = df1[df1['fico'].astype(float) >700].shape[0]/df1.shape[0]\nprint(p_a_b)\n# Check whether the P(A) and P(B) are independent from each other\nresult = (p_a == p_a_b)\nprint(result)\n\n\n# --------------\n# probability of paid_back_loan is Yes\nprob_lp = df[df['paid.back.loan'] == 'Yes'].shape[0] / df.shape[0]\nprint(prob_lp)\n\n# probability of the credit policy is Yes\nprob_cs = df[df['credit.policy'] == 'Yes'].shape[0] / df.shape[0]\nprint(prob_cs)\n# create new dataframe for paid.back.loan == 'Yes'\nnew_df = df[df['paid.back.loan'] == 'Yes']\n\n# Calculate the P(B|A)\nprob_pd_cs = new_df[new_df['credit.policy'] == 'Yes'].shape[0] / new_df.shape[0]\n\nprint(prob_pd_cs)\n\n# bayes theorem \n\nbayes = (prob_pd_cs * prob_lp)/ prob_cs\n\n# print bayes\nprint(bayes)\n\n\n# --------------\n# create bar plot for purpose\ndf.purpose.value_counts(normalize=True).plot(kind='bar')\nplt.title(\"Probability Distribution of Purpose\")\nplt.ylabel(\"Probability\")\nplt.xlabel(\"Number of Purpose\")\nplt.show()\n\n#create new dataframe for paid.back.loan == 'No'\ndf1= df[df['paid.back.loan'] == 'No']\n\n# plot the bar plot for 'purpose' where paid.back.loan == No \ndf1.purpose.value_counts(normalize=True).plot(kind='bar')\nplt.title(\"Probability Distribution of Purpose\")\nplt.ylabel(\"Probability\")\nplt.xlabel(\"Number of Purpose\")\nplt.show()\n\n\n# --------------\n\n# Calculate median \ninst_median = df['installment'].median()\ninst_mean = df['installment'].mean()\n\n\n# histogram for installment\ndf['installment'].hist(normed = True, bins=50)\nplt.axvline(x=inst_median,color='r')\nplt.axvline(x=inst_mean,color='g')\n\nplt.show()\n\n#histogram for log anual income\ndf['log.annual.inc'].hist(normed = True, bins=50)\nplt.show()\n\n\n"
] |
[
[
"pandas.read_csv",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
flo-maier/c3
|
[
"6bfd72d49fbe47c33038a73436f51f4e454f5ccb",
"6bfd72d49fbe47c33038a73436f51f4e454f5ccb"
] |
[
"c3/optimizers/optimizer.py",
"c3/generator/devices.py"
] |
[
"\"\"\"Optimizer object, where the optimal control is done.\"\"\"\n\nimport os\nimport time\nfrom typing import Callable, Union\nimport numpy as np\nimport tensorflow as tf\nimport json\nimport c3.libraries.algorithms as algorithms\nfrom c3.experiment import Experiment\n\n\nclass Optimizer:\n \"\"\"\n General optimizer class from which specific classes are inherited.\n\n Parameters\n ----------\n algorithm : callable\n From the algorithm library\n store_unitaries : boolean\n Store propagators as text and pickle\n \"\"\"\n\n def __init__(\n self,\n pmap,\n algorithm=None,\n store_unitaries=False,\n ):\n self.pmap = pmap\n self.optim_status = {}\n self.gradients = {}\n self.current_best_goal = 9876543210.123456789\n self.current_best_params = None\n self.evaluation = 0\n self.store_unitaries = store_unitaries\n self.created_by = None\n self.logname = None\n self.options = None\n self.__dir_path = None\n self.logdir = None\n self.set_algorithm(algorithm)\n\n def set_algorithm(self, algorithm: Callable) -> None:\n if algorithm:\n self.algorithm = algorithm\n else:\n print(\"C3:WARNING:No algorithm passed. Using default LBFGS\")\n self.algorithm = algorithms.lbfgs\n\n def replace_logdir(self, new_logdir):\n \"\"\"\n Specify a new filepath to store the log.\n\n Parameters\n ----------\n new_logdir\n\n \"\"\"\n old_logdir = self.logdir\n self.logdir = new_logdir\n\n if old_logdir is None:\n return\n\n try:\n os.remove(os.path.join(self.__dir_path, \"recent\"))\n except FileNotFoundError:\n pass\n # os.remove(self.__dir_path + self.string)\n\n try:\n os.rmdir(old_logdir)\n except OSError:\n pass\n\n def set_exp(self, exp: Experiment) -> None:\n self.exp = exp\n\n def set_created_by(self, config) -> None:\n \"\"\"\n Store the config file location used to created this optimizer.\n \"\"\"\n self.created_by = config\n\n def load_best(self, init_point) -> None:\n \"\"\"\n Load a previous parameter point to start the optimization from. Legacy wrapper.\n Method moved to Parametermap.\n\n Parameters\n ----------\n init_point : str\n File location of the initial point\n\n \"\"\"\n self.pmap.load_values(init_point)\n\n def start_log(self) -> None:\n \"\"\"\n Initialize the log with current time.\n\n \"\"\"\n self.start_time = time.time()\n start_time_str = str(f\"{time.asctime(time.localtime())}\\n\\n\")\n with open(self.logdir + self.logname, \"a\") as logfile:\n logfile.write(\"Starting optimization at \")\n logfile.write(start_time_str)\n logfile.write(\"Optimization parameters:\\n\")\n logfile.write(json.dumps(self.pmap.opt_map))\n logfile.write(\"\\n\")\n logfile.write(\"Units:\\n\")\n logfile.write(json.dumps(self.pmap.get_opt_units()))\n logfile.write(\"\\n\")\n logfile.write(\"Algorithm options:\\n\")\n logfile.write(json.dumps(self.options))\n logfile.write(\"\\n\")\n logfile.flush()\n\n def end_log(self) -> None:\n \"\"\"\n Finish the log by recording current time and total runtime.\n\n \"\"\"\n self.end_time = time.time()\n with open(self.logdir + self.logname, \"a\") as logfile:\n logfile.write(f\"Finished at {time.asctime(time.localtime())}\\n\")\n logfile.write(f\"Total runtime: {self.end_time-self.start_time}\\n\\n\")\n logfile.flush()\n\n def log_best_unitary(self) -> None:\n \"\"\"\n Save the best unitary in the log.\n \"\"\"\n with open(self.logdir + \"best_point_\" + self.logname, \"w\") as best_point:\n U_dict = self.exp.unitaries\n for gate, U in U_dict.items():\n best_point.write(\"\\n\")\n best_point.write(f\"Re {gate}: \\n\")\n best_point.write(f\"{np.round(np.real(U), 3)}\\n\")\n best_point.write(\"\\n\")\n best_point.write(f\"Im {gate}: \\n\")\n best_point.write(f\"{np.round(np.imag(U), 3)}\\n\")\n\n def log_parameters(self) -> None:\n \"\"\"\n Log the current status. Write parameters to log. Update the current best\n parameters. Call plotting functions as set up.\n\n \"\"\"\n if self.optim_status[\"goal\"] < self.current_best_goal:\n self.current_best_goal = self.optim_status[\"goal\"]\n self.current_best_params = self.optim_status[\"params\"]\n with open(self.logdir + \"best_point_\" + self.logname, \"w\") as best_point:\n best_dict = {\n \"opt_map\": self.pmap.opt_map,\n \"units\": self.pmap.get_opt_units(),\n \"optim_status\": self.optim_status,\n }\n best_point.write(json.dumps(best_dict))\n best_point.write(\"\\n\")\n if self.store_unitaries:\n self.exp.store_Udict(self.optim_status[\"goal\"])\n self.exp.store_unitaries_counter += 1\n with open(self.logdir + self.logname, \"a\") as logfile:\n logfile.write(\n f\"\\nFinished evaluation {self.evaluation} at {time.asctime()}\\n\"\n )\n # logfile.write(json.dumps(self.optim_status, indent=2))\n logfile.write(json.dumps(self.optim_status))\n logfile.write(\"\\n\")\n logfile.flush()\n\n def goal_run(\n self, current_params: Union[np.ndarray, tf.constant]\n ) -> Union[np.ndarray, tf.constant]:\n \"\"\"\n Placeholder for the goal function. To be implemented by inherited classes.\n \"\"\"\n return 0\n\n def goal_run_with_grad(self, current_params):\n with tf.GradientTape() as t:\n t.watch(current_params)\n goal = self.goal_run(current_params)\n grad = t.gradient(goal, current_params)\n return goal, grad\n\n def lookup_gradient(self, x):\n \"\"\"\n Return the stored gradient for a given parameter set.\n\n Parameters\n ----------\n x : np.array\n Parameter set.\n\n Returns\n -------\n np.array\n Value of the gradient.\n \"\"\"\n key = str(x)\n gradient = self.gradients.pop(key)\n if np.any(np.isnan(gradient)) or np.any(np.isinf(gradient)):\n # TODO: is simply a warning sufficient?\n gradient[\n np.isnan(gradient)\n ] = 1e-10 # Most probably at boundary of Quantity\n gradient[\n np.isinf(gradient)\n ] = 1e-10 # Most probably at boundary of Quantity\n return gradient\n\n def fct_to_min(\n self, input_parameters: Union[np.ndarray, tf.constant]\n ) -> Union[np.ndarray, tf.constant]:\n \"\"\"\n Wrapper for the goal function.\n\n Parameters\n ----------\n x : [np.array, tf.constant]\n Vector of parameters in the optimizer friendly way.\n\n Returns\n -------\n [float, tf.constant]\n Value of the goal function. Float if input is np.array else tf.constant\n \"\"\"\n\n if isinstance(input_parameters, np.ndarray):\n current_params = tf.constant(input_parameters)\n goal = self.goal_run(current_params)\n self.log_parameters()\n goal = float(goal)\n return goal\n else:\n current_params = input_parameters\n goal = self.goal_run(current_params)\n self.log_parameters()\n return goal\n\n def fct_to_min_autograd(self, x):\n \"\"\"\n Wrapper for the goal function, including evaluation and storage of the\n gradient.\n\n Parameters\n ----------\n x : np.array\n Vector of parameters in the optimizer friendly way.\n\n Returns\n -------\n float\n Value of the goal function.\n \"\"\"\n current_params = tf.constant(x)\n goal, grad = self.goal_run_with_grad(current_params)\n if isinstance(grad, tf.Tensor):\n grad = grad.numpy()\n gradients = grad.flatten()\n self.gradients[str(current_params.numpy())] = gradients\n self.optim_status[\"gradient\"] = gradients.tolist()\n self.log_parameters()\n if isinstance(goal, tf.Tensor):\n goal = float(goal)\n return goal\n",
"import os\nimport tempfile\nimport hjson\nfrom typing import Callable, Dict, Any\nimport tensorflow as tf\nimport numpy as np\nfrom c3.signal.pulse import Envelope, Carrier\nfrom c3.signal.gates import Instruction\nfrom c3.c3objs import Quantity, C3obj\nfrom c3.utils.tf_utils import tf_convolve\n\ndevices = dict()\n\n\ndef dev_reg_deco(func: Callable) -> Callable:\n \"\"\"\n Decorator for making registry of functions\n \"\"\"\n devices[str(func.__name__)] = func\n return func\n\n\nclass Device(C3obj):\n \"\"\"A Device that is part of the stack generating the instruction signals.\n\n Parameters\n ----------\n resolution: np.float64\n Number of samples per second this device operates at.\n \"\"\"\n\n def __init__(self, **props):\n if \"inputs\" not in self.__dict__:\n self.inputs = props.pop(\"inputs\", 0)\n if \"outputs\" not in self.__dict__:\n self.outputs = props.pop(\"outputs\", 0)\n self.resolution = props.pop(\"resolution\", 0)\n name = props.pop(\"name\")\n desc = props.pop(\"desc\", \"\")\n comment = props.pop(\"comment\", \"\")\n\n # Because of legacy usage, we might have parameters given withing props iself\n # or in a \"params\" field. Here we combine them.\n params = props.pop(\"params\", {})\n params.update(props)\n super().__init__(name, desc, comment, params)\n self.signal = {}\n\n def write_config(self, filepath: str) -> None:\n \"\"\"\n Write dictionary to a HJSON file.\n \"\"\"\n with open(filepath, \"w\") as cfg_file:\n hjson.dump(self.asdict(), cfg_file)\n\n def asdict(self) -> Dict[str, Any]:\n params = {}\n for key, item in self.params.items():\n params[key] = item.asdict()\n return {\n \"c3type\": self.__class__.__name__,\n \"inputs\": self.inputs,\n \"outputs\": self.outputs,\n \"params\": params,\n \"resolution\": self.resolution,\n }\n\n def __str__(self) -> str:\n return hjson.dumps(self.asdict())\n\n def calc_slice_num(self, t_start: np.float64, t_end: np.float64) -> None:\n \"\"\"\n Effective number of time slices given start, end and resolution.\n\n Parameters\n ----------\n t_start: np.float64\n Starting time for this device.\n t_end: np.float64\n End time for this device.\n \"\"\"\n res = self.resolution\n self.slice_num = int(np.abs(t_start - t_end) * res)\n # return self.slice_num\n\n def create_ts(\n self, t_start: np.float64, t_end: np.float64, centered: bool = True\n ) -> tf.constant:\n \"\"\"\n Compute time samples.\n\n Parameters\n ----------\n t_start: np.float64\n Starting time for this device.\n t_end: np.float64\n End time for this device.\n centered: boolean\n Sample in the middle of an interval, otherwise at the beginning.\n \"\"\"\n if not hasattr(self, \"slice_num\"):\n self.calc_slice_num(t_start, t_end)\n dt = 1 / self.resolution\n # TODO This type of centering does not guarantee zeros at the ends\n if centered:\n offset = dt / 2\n num = self.slice_num\n else:\n offset = 0\n num = self.slice_num + 1\n t_start = tf.constant(t_start + offset, dtype=tf.float64)\n t_end = tf.constant(t_end - offset, dtype=tf.float64)\n # TODO: adjust the way we calculate the time slices for devices\n # ts = tf.range(t_start, t_end + 1e-16, dt)\n ts = tf.linspace(t_start, t_end, num)\n return ts\n\n\n@dev_reg_deco\nclass Readout(Device):\n \"\"\"Mimic the readout process by multiplying a state phase with a factor and offset.\n\n Parameters\n ----------\n factor: Quantity\n offset: Quantity\n \"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n if \"factor\" not in self.params:\n raise Exception(\"C3:ERROR: Readout device needs a 'factor' parameter.\")\n if \"offset\" not in self.params:\n raise Exception(\"C3:ERROR: Readout device needs an 'offset' parameter.\")\n\n def readout(self, phase):\n \"\"\"\n Apply the readout rescaling\n\n Parameters\n ----------\n phase: tf.float64\n Raw phase of a quantum state\n\n Returns\n -------\n tf.float64\n Rescaled readout value\n \"\"\"\n offset = self.params[\"offset\"].get_value()\n factor = self.params[\"factor\"].get_value()\n return phase * factor + offset\n\n\n@dev_reg_deco\nclass VoltsToHertz(Device):\n \"\"\"Convert the voltage signal to an amplitude to plug into the model Hamiltonian.\n\n Parameters\n ----------\n V_to_Hz: Quantity\n Conversion factor.\n offset: tf.float64\n Drive frequency offset.\n \"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n\n def process(\n self, instr: Instruction, chan: str, mixed_signal: Dict[str, Any]\n ) -> Dict[str, Any]:\n \"\"\"Transform signal from value of V to Hz.\n\n Parameters\n ----------\n mixed_signal: tf.Tensor\n Waveform as line voltages after IQ mixing\n\n Returns\n -------\n tf.Tensor\n Waveform as control amplitudes\n \"\"\"\n v2hz = self.params[\"V_to_Hz\"].get_value()\n self.signal[\"values\"] = mixed_signal[\"values\"] * v2hz\n self.signal[\"ts\"] = mixed_signal[\"ts\"]\n return self.signal\n\n\n@dev_reg_deco\nclass Crosstalk(Device):\n \"\"\"\n Device to phenomenologically include crosstalk in the model by explicitly mixing\n drive lines.\n\n Parameters\n ----------\n\n crosstalk_matrix: tf.constant\n Matrix description of how to mix drive channels.\n\n Examples\n --------\n .. code-block:: python\n\n xtalk = Crosstalk(\n name=\"crosstalk\",\n channels=[\"TC1\", \"TC2\"],\n crosstalk_matrix=Quantity(\n value=[[1, 0], [0, 1]],\n min_val=[[0, 0], [0, 0]],\n max_val=[[1, 1], [1, 1]],\n unit=\"\",\n ),\n )\n\n\n\n \"\"\"\n\n def __init__(self, **props):\n self.crossed_channels = props.pop(\"channels\", None)\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n self.params[\"crosstalk_matrix\"] = props.pop(\"crosstalk_matrix\", None)\n\n def process(self, signal: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Mix channels in the input signal according to a crosstalk matrix.\n\n Parameters\n ----------\n signal: Dict[str, Any]\n Dictionary of several signals identified by their channel as dict keys, e.g.\n\n .. code-block:: python\n\n signal = {\n \"TC1\": {\"values\": [0, 0.5, 1, 1, ...]},\n \"TC2\": {\"values\": [1, 1, 1, 1, ...],\n }\n\n\n\n Returns\n -------\n signal: Dict[str, Any]\n\n \"\"\"\n xtalk = self.params[\"crosstalk_matrix\"]\n signals = [signal[ch][\"values\"] for ch in self.crossed_channels]\n crossed_signals = xtalk.get_value() @ signals\n for indx, ch in enumerate(self.crossed_channels):\n signal[ch][\"values\"] = crossed_signals[indx]\n return signal\n\n\n@dev_reg_deco\nclass DigitalToAnalog(Device):\n \"\"\"Take the values at the awg resolution to the simulation resolution.\"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n self.ts = None\n self.sampling_method = props.pop(\"sampling_method\", \"nearest\")\n\n def process(\n self, instr: Instruction, chan: str, awg_signal: Dict[str, Any]\n ) -> Dict[str, Any]:\n \"\"\"Resample the awg values to higher resolution.\n\n Parameters\n ----------\n instr: Instruction\n The logical instruction or qubit operation for which the signal is\n generated.\n chan: str\n Specifies which channel is being processed if needed.\n awg_signal: dict\n Dictionary of several signals identified by their channel as dict keys.\n\n Returns\n -------\n dict\n Inphase and Quadrature compontent of the upsampled signal.\n \"\"\"\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n old_dim = awg_signal[\"inphase\"].shape[0]\n new_dim = ts.shape[0]\n # TODO add following zeros\n inphase = tf.reshape(\n tf.image.resize(\n tf.reshape(awg_signal[\"inphase\"], shape=[1, old_dim, 1]),\n size=[1, new_dim],\n method=self.sampling_method,\n ),\n shape=[new_dim],\n )\n inphase = tf.cast(inphase, tf.float64)\n quadrature = tf.reshape(\n tf.image.resize(\n tf.reshape(awg_signal[\"quadrature\"], shape=[1, old_dim, 1]),\n size=[1, new_dim],\n method=self.sampling_method,\n ),\n shape=[new_dim],\n )\n quadrature = tf.cast(quadrature, tf.float64)\n self.signal[\"ts\"] = ts\n self.signal[\"inphase\"] = inphase\n self.signal[\"quadrature\"] = quadrature\n return self.signal\n\n\n@dev_reg_deco\nclass Filter(Device):\n # TODO This can apply a general function to a signal.\n \"\"\"Apply a filter function to the signal.\"\"\"\n\n def __init__(self, **props):\n raise Exception(\"C3:ERROR Not yet implemented.\")\n self.filter_function: Callable = props[\"filter_function\"]\n super().__init__(**props)\n\n def process(\n self, instr: Instruction, chan: str, Hz_signal: Dict[str, Any]\n ) -> Dict[str, Any]:\n \"\"\"Apply a filter function to the signal.\"\"\"\n self.signal = self.filter_function(Hz_signal)\n return self.signal\n\n\n@dev_reg_deco\nclass FluxTuning(Device):\n \"\"\"\n Flux tunable qubit frequency.\n\n Parameters\n ----------\n phi_0 : Quantity\n Flux bias.\n phi : Quantity\n Current flux.\n omega_0 : Quantity\n Maximum frequency.\n\n \"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n for par in [\"phi_0\", \"phi\", \"omega_0\", \"anhar\"]:\n if par not in self.params:\n raise Exception(\n f\"C3:ERROR: {self.__class__} needs a '{par}' parameter.\"\n )\n\n def get_factor(self, phi):\n pi = tf.constant(np.pi, dtype=tf.float64)\n phi_0 = tf.cast(self.params[\"phi_0\"].get_value(), tf.float64)\n\n if \"d\" in self.params:\n d = self.params[\"d\"].get_value()\n factor = tf.sqrt(\n tf.sqrt(\n tf.cos(pi * phi / phi_0) ** 2\n + d ** 2 * tf.sin(pi * phi / phi_0) ** 2\n )\n )\n else:\n factor = tf.sqrt(tf.abs(tf.cos(pi * phi / phi_0)))\n return factor\n\n def get_freq(self, phi):\n # TODO: Check how the time dependency affects the frequency. (Koch et al. , 2007)\n omega_0 = self.params[\"omega_0\"].get_value()\n anhar = self.params[\"anhar\"].get_value()\n biased_freq = (omega_0 - anhar) * self.get_factor(phi) + anhar\n return biased_freq\n\n def process(self, instr: Instruction, chan: str, signal_in):\n \"\"\"\n Compute the qubit frequency resulting from an applied flux.\n\n Parameters\n ----------\n signal : tf.float64\n\n\n Returns\n -------\n tf.float64\n Qubit frequency.\n \"\"\"\n phi = self.params[\"phi\"].get_value()\n signal = signal_in[\"values\"]\n self.signal[\"ts\"] = signal_in[\"ts\"]\n freq = self.get_freq(phi + signal) - self.get_freq(phi)\n self.signal[\"values\"] = freq\n return self.signal\n\n\nclass FluxTuningLinear(Device):\n \"\"\"\n Flux tunable qubit frequency linear adjustment.\n\n Parameters\n ----------\n phi_0 : Quantity\n Flux bias.\n Phi : Quantity\n Current flux.\n omega_0 : Quantity\n Maximum frequency.\n\n \"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n for par in [\"phi_0\", \"Phi\", \"omega_0\"]:\n if par not in self.params:\n raise Exception(\n f\"C3:ERROR: {self.__class__} needs a '{par}' parameter.\"\n )\n self.freq = None\n\n def frequency(self, signal: tf.float64) -> tf.constant:\n \"\"\"\n Compute the qubit frequency resulting from an applied flux.\n\n Parameters\n ----------\n signal : tf.float64\n\n\n Returns\n -------\n tf.float64\n Qubit frequency.\n \"\"\"\n pi = tf.constant(np.pi, dtype=tf.float64)\n phi = self.params[\"phi\"].get_value()\n omega_0 = self.params[\"omega_0\"].get_value()\n # phi_0 = self.params[\"phi_0\"].get_value()\n if \"d\" in self.params:\n d = self.params[\"d\"].get_value()\n max_freq = omega_0\n min_freq = omega_0 * tf.sqrt(\n tf.sqrt(tf.cos(pi * 0.5) ** 2 + d ** 2 * tf.sin(pi * 0.5) ** 2)\n )\n else:\n max_freq = omega_0\n min_freq = tf.constant(0.0, dtype=tf.float64)\n self.freq = 2 * (signal - phi) * (min_freq - max_freq)\n return self.freq\n\n\n@dev_reg_deco\nclass Response(Device):\n \"\"\"Make the AWG signal physical by convolution with a Gaussian to limit bandwith.\n\n Parameters\n ----------\n rise_time : Quantity\n Time constant for the gaussian convolution.\n \"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n\n def convolve(self, signal: list, resp_shape: list):\n \"\"\"\n Compute the convolution with a function.\n\n Parameters\n ----------\n signal : list\n Potentially unlimited signal samples.\n resp_shape : list\n Samples of the function to model limited bandwidth.\n\n Returns\n -------\n tf.Tensor\n Processed signal.\n\n \"\"\"\n convolution = tf.zeros(0, dtype=tf.float64)\n signal = tf.concat(\n [\n tf.zeros(len(resp_shape), dtype=tf.float64),\n signal,\n tf.zeros(len(resp_shape), dtype=tf.float64),\n ],\n 0,\n )\n for p in range(len(signal) - 2 * len(resp_shape)):\n convolution = tf.concat(\n [\n convolution,\n tf.reshape(\n tf.math.reduce_sum(\n tf.math.multiply(\n signal[p : p + len(resp_shape)], resp_shape\n )\n ),\n shape=[1],\n ),\n ],\n 0,\n )\n return convolution\n\n def process(self, instr, chan, iq_signal):\n \"\"\"\n Apply a Gaussian shaped limiting function to an IQ signal.\n\n Parameters\n ----------\n iq_signal : dict\n I and Q components of an AWG signal.\n\n Returns\n -------\n dict\n Bandwidth limited IQ signal.\n\n \"\"\"\n n_ts = tf.floor(self.params[\"rise_time\"].get_value() * self.resolution)\n ts = tf.linspace(\n tf.constant(0.0, dtype=tf.float64),\n self.params[\"rise_time\"].get_value(),\n tf.cast(n_ts, tf.int32),\n )\n cen = tf.cast(\n (self.params[\"rise_time\"].get_value() - 1 / self.resolution) / 2, tf.float64\n )\n sigma = self.params[\"rise_time\"].get_value() / 4\n gauss = tf.exp(-((ts - cen) ** 2) / (2 * sigma * sigma))\n offset = tf.exp(-((-1 - cen) ** 2) / (2 * sigma * sigma))\n # TODO make sure ratio of risetime and resolution is an integer\n risefun = gauss - offset\n inphase = self.convolve(iq_signal[\"inphase\"], risefun / tf.reduce_sum(risefun))\n quadrature = self.convolve(\n iq_signal[\"quadrature\"], risefun / tf.reduce_sum(risefun)\n )\n self.signal = {\n \"inphase\": inphase,\n \"quadrature\": quadrature,\n \"ts\": self.create_ts(instr.t_start, instr.t_end, centered=True),\n }\n return self.signal\n\n\n@dev_reg_deco\nclass ResponseFFT(Device):\n \"\"\"Make the AWG signal physical by convolution with a Gaussian to limit bandwith.\n\n Parameters\n ----------\n rise_time : Quantity\n Time constant for the gaussian convolution.\n \"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n\n def process(self, instr, chan, iq_signal):\n \"\"\"\n Apply a Gaussian shaped limiting function to an IQ signal.\n\n Parameters\n ----------\n iq_signal : dict\n I and Q components of an AWG signal.\n\n Returns\n -------\n dict\n Bandwidth limited IQ signal.\n\n \"\"\"\n # print(tf.abs(1 / tf.math.reduce_mean(iq_signal['ts'][1] - iq_signal['ts'][0]) ),self.resolution)\n assert (\n tf.abs((iq_signal[\"ts\"][1] - iq_signal[\"ts\"][0]) - 1 / self.resolution)\n < 1e-15\n )\n n_ts = tf.floor(self.params[\"rise_time\"].get_value() * self.resolution)\n ts = tf.linspace(\n tf.constant(0.0, dtype=tf.float64),\n self.params[\"rise_time\"].get_value(),\n tf.cast(n_ts, tf.int32),\n )\n cen = tf.cast(\n (self.params[\"rise_time\"].get_value() - 1 / self.resolution) / 2, tf.float64\n )\n sigma = self.params[\"rise_time\"].get_value() / 4\n gauss = tf.exp(-((ts - cen) ** 2) / (2 * sigma * sigma))\n offset = tf.exp(-((-1 - cen) ** 2) / (2 * sigma * sigma))\n\n risefun = gauss - offset\n inphase = tf_convolve(iq_signal[\"inphase\"], risefun / tf.reduce_sum(risefun))\n quadrature = tf_convolve(\n iq_signal[\"quadrature\"], risefun / tf.reduce_sum(risefun)\n )\n\n inphase = tf.math.real(inphase)\n quadrature = tf.math.real(quadrature)\n self.signal = {\n \"inphase\": inphase,\n \"quadrature\": quadrature,\n \"ts\": iq_signal[\"ts\"],\n }\n return self.signal\n\n\nclass HighpassFilter(Device):\n \"\"\"Introduce a highpass filter\n\n Parameters\n ----------\n cutoff : Quantity\n cutoff frequency of highpass filter\n keep_mean : bool\n should the mean of the signal be restored\n \"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n self.signal = None\n\n def convolve(self, signal: list, resp_shape: list):\n \"\"\"\n Compute the convolution with a function.\n\n Parameters\n ----------\n signal : list\n Potentially unlimited signal samples.\n resp_shape : list\n Samples of the function to model limited bandwidth.\n\n Returns\n -------\n tf.Tensor\n Processed signal.\n\n \"\"\"\n convolution = tf.zeros(0, dtype=tf.float64)\n signal = tf.concat(\n [\n tf.zeros(int(len(resp_shape) // 2), dtype=tf.float64),\n signal,\n tf.zeros(int(len(resp_shape) * 3 / 2) + 1, dtype=tf.float64),\n ],\n 0,\n )\n for p in range(len(signal) - 2 * len(resp_shape)):\n convolution = tf.concat(\n [\n convolution,\n tf.reshape(\n tf.math.reduce_sum(\n tf.math.multiply(\n signal[p : p + len(resp_shape)], resp_shape\n )\n ),\n shape=[1],\n ),\n ],\n 0,\n )\n return convolution\n\n def process(self, instr, chan, iq_signal):\n \"\"\"\n Apply a highpass cutoff to an IQ signal.\n\n Parameters\n ----------\n iq_signal : dict\n I and Q components of an AWG signal.\n\n Returns\n -------\n dict\n Filtered IQ signal.\n\n \"\"\"\n fc = self.params[\"cutoff\"].get_value() / self.resolution\n\n if self.params[\"rise_time\"]:\n tb = self.params[\"rise_time\"].get_value() / self.resolution\n else:\n tb = fc / 2\n\n # fc = 1e7 / self.resolution\n # tb = fc / 2\n\n N_ts = tf.cast(tf.math.ceil(4 / tb), tf.int32)\n N_ts += 1 - tf.math.mod(N_ts, 2) # make n_ts odd\n if N_ts > len(iq_signal[\"inphase\"] * 100):\n self.signal = iq_signal\n return self.signal\n\n pi = tf.cast(np.pi, tf.double)\n\n n = tf.cast(tf.range(N_ts), tf.double)\n\n x = 2 * fc * (n - (N_ts - 1) / 2)\n h = tf.sin(pi * x) / (pi * x)\n h = tf.where(tf.math.is_nan(h), tf.ones_like(h), h)\n w = tf.signal.hamming_window(N_ts)\n w = tf.cast(w, tf.double)\n h *= w\n h /= -tf.reduce_sum(h)\n h = tf.where(tf.cast(n, tf.int32) == (N_ts - 1) // 2, tf.ones_like(h), h)\n inphase = self.convolve(iq_signal[\"inphase\"], h)\n quadrature = self.convolve(iq_signal[\"quadrature\"], h)\n self.signal = {\n \"inphase\": inphase,\n \"quadrature\": quadrature,\n \"ts\": iq_signal[\"ts\"],\n }\n return self.signal\n\n\n@dev_reg_deco\nclass Mixer(Device):\n \"\"\"Mixer device, combines inputs from the local oscillator and the AWG.\"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 2)\n self.outputs = props.pop(\"outputs\", 1)\n\n def process(self, instr: Instruction, chan: str, in1: dict, in2: dict):\n \"\"\"Combine signal from AWG and LO.\n\n Parameters\n ----------\n lo_signal : dict\n Local oscillator signal.\n awg_signal : dict\n Waveform generator signal.\n\n Returns\n -------\n dict\n Mixed signal.\n \"\"\"\n i1 = in1[\"inphase\"]\n q1 = in1[\"quadrature\"]\n i2 = in2[\"inphase\"]\n q2 = in2[\"quadrature\"]\n self.signal = {\"values\": i1 * i2 + q1 * q2, \"ts\": in1[\"ts\"]}\n # See Engineer's Guide Eq. 88\n # TODO: Check consistency of the signs between Mixer, LO and AWG classes\n return self.signal\n\n\n@dev_reg_deco\nclass LONoise(Device):\n \"\"\"Noise applied to the local oscillator\"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n self.signal = None\n self.params[\"noise_perc\"] = props.pop(\"noise_perc\")\n\n def process(self, instr, chan, lo_signal):\n \"\"\"Distort signal by adding noise.\"\"\"\n noise_perc = self.params[\"noise_perc\"].get_value()\n cos, sin = lo_signal[\"values\"]\n cos = cos + noise_perc * np.random.normal(loc=0.0, scale=1.0, size=len(cos))\n sin = sin + noise_perc * np.random.normal(loc=0.0, scale=1.0, size=len(sin))\n lo_signal[\"values\"] = (cos, sin)\n self.signal = lo_signal\n return self.signal\n\n\n@dev_reg_deco\nclass Additive_Noise(Device):\n \"\"\"Noise applied to a signal\"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n self.signal = None\n self.params[\"noise_amp\"] = props.pop(\"noise_amp\")\n\n def get_noise(self, sig):\n noise_amp = self.params[\"noise_amp\"].get_value()\n return noise_amp * np.random.normal(size=tf.shape(sig), loc=0.0, scale=1.0)\n\n def process(self, instr, chan, signal):\n \"\"\"Distort signal by adding noise.\"\"\"\n noise_amp = self.params[\"noise_amp\"].get_value()\n out_signal = {\"ts\": signal[\"ts\"]}\n for k, sig in signal.items():\n if k != \"ts\" and \"noise\" not in k:\n if noise_amp < 1e-17:\n noise = tf.zeros_like(sig)\n else:\n noise = tf.constant(\n self.get_noise(sig), shape=sig.shape, dtype=tf.float64\n )\n noise_key = \"noise\" + (\"-\" + k if k != \"values\" else \"\")\n out_signal[noise_key] = noise\n\n out_signal[k] = sig + noise\n self.signal = out_signal\n return self.signal\n\n\n@dev_reg_deco\nclass DC_Noise(Additive_Noise):\n \"\"\"Add a random constant offset to the signals\"\"\"\n\n def get_noise(self, sig):\n noise_amp = self.params[\"noise_amp\"].get_value()\n return tf.ones_like(sig) * tf.constant(\n noise_amp * np.random.normal(loc=0.0, scale=1.0)\n )\n\n\n@dev_reg_deco\nclass Pink_Noise(Additive_Noise):\n \"\"\"Device creating pink noise, i.e. 1/f noise.\"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.params[\"bfl_num\"] = props.pop(\n \"bfl_num\", Quantity(value=5, min_val=1, max_val=10)\n )\n\n def get_noise(self, sig):\n noise_amp = self.params[\"noise_amp\"].get_value().numpy()\n bfl_num = np.int(self.params[\"bfl_num\"].get_value().numpy())\n noise = []\n bfls = 2 * np.random.randint(2, size=bfl_num) - 1\n num_steps = len(sig)\n flip_rates = np.logspace(\n 0, np.log(num_steps), num=bfl_num + 1, endpoint=True, base=10.0\n )\n for step in range(num_steps):\n for indx in range(bfl_num):\n if np.floor(np.random.random() * flip_rates[indx + 1]) == 0:\n bfls[indx] = -bfls[indx]\n noise.append(np.sum(bfls) * noise_amp)\n return noise\n\n\n@dev_reg_deco\nclass DC_Offset(Device):\n \"\"\"Noise applied to a signal\"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.inputs = props.pop(\"inputs\", 1)\n self.outputs = props.pop(\"outputs\", 1)\n self.signal = None\n self.params[\"offset_amp\"] = props.pop(\"offset_amp\")\n\n def process(self, instr, chan, signal):\n \"\"\"Distort signal by adding noise.\"\"\"\n offset_amp = self.params[\"offset_amp\"].get_value()\n if np.abs(offset_amp) < 1e-17:\n self.signal = signal\n return signal\n out_signal = {}\n if type(signal) is dict:\n for k, sig in signal.items():\n out_signal[k] = sig + offset_amp\n else:\n out_signal = signal + offset_amp\n self.signal = out_signal\n return self.signal\n\n\n@dev_reg_deco\nclass LO(Device):\n \"\"\"Local oscillator device, generates a constant oscillating signal.\"\"\"\n\n def __init__(self, **props):\n super().__init__(**props)\n self.outputs = props.pop(\"outputs\", 1)\n self.phase_noise = props.pop(\"phase_noise\", 0)\n self.freq_noise = props.pop(\"freq_noise\", 0)\n self.amp_noise = props.pop(\"amp_noise\", 0)\n\n def process(self, instr: Instruction, chan: str) -> dict:\n # TODO check somewhere that there is only 1 carrier per instruction\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n dt = ts[1] - ts[0]\n phase_noise = self.phase_noise\n amp_noise = self.amp_noise\n freq_noise = self.freq_noise\n components = instr.comps\n for comp in components[chan].values():\n if isinstance(comp, Carrier):\n cos, sin = [], []\n omega_lo = comp.params[\"freq\"].get_value()\n if amp_noise and freq_noise:\n print(\"amp and freq noise\")\n phi = omega_lo * ts[0]\n for _ in ts:\n A = np.random.normal(loc=1.0, scale=amp_noise)\n cos.append(A * np.cos(phi))\n sin.append(A * np.sin(phi))\n omega = omega_lo + np.random.normal(loc=0.0, scale=freq_noise)\n phi = phi + omega * dt\n elif amp_noise and phase_noise:\n print(\"amp and phase noise\")\n for t in ts:\n A = np.random.normal(loc=1.0, scale=amp_noise)\n phi = np.random.normal(loc=0.0, scale=phase_noise)\n cos.append(A * np.cos(omega_lo * t + phi))\n sin.append(A * np.sin(omega_lo * t + phi))\n elif amp_noise:\n print(\"amp noise\")\n for t in ts:\n A = np.random.normal(loc=1.0, scale=amp_noise)\n cos.append(A * np.cos(omega_lo * t))\n sin.append(A * np.sin(omega_lo * t))\n elif phase_noise:\n print(\"phase noise\")\n for t in ts:\n phi = np.random.normal(loc=0.0, scale=phase_noise)\n cos.append(np.cos(omega_lo * t + phi))\n sin.append(np.sin(omega_lo * t + phi))\n elif freq_noise:\n phi = omega_lo * ts[0]\n for _ in ts:\n cos.append(np.cos(phi))\n sin.append(np.sin(phi))\n omega = omega_lo + np.random.normal(loc=0.0, scale=freq_noise)\n phi = phi + omega * dt\n else:\n cos = tf.cos(omega_lo * ts)\n sin = tf.sin(omega_lo * ts)\n self.signal[\"inphase\"] = cos\n self.signal[\"quadrature\"] = sin\n self.signal[\"ts\"] = ts\n return self.signal\n\n\n# TODO real AWG has 16bits plus noise\n@dev_reg_deco\nclass AWG(Device):\n \"\"\"AWG device, transforms digital input to analog signal.\n\n Parameters\n ----------\n logdir : str\n Filepath to store generated waveforms.\n \"\"\"\n\n def __init__(self, **props):\n self.__options = \"\"\n self.logdir = props.pop(\n \"logdir\", os.path.join(tempfile.gettempdir(), \"c3logs\", \"AWG\")\n )\n self.logname = \"awg.log\"\n options = props.pop(\"options\", \"\")\n super().__init__(**props)\n self.outputs = props.pop(\"outputs\", 1)\n # TODO move the options pwc & drag to the instruction object\n self.amp_tot_sq = None\n self.process = self.create_IQ\n if options == \"drag\":\n self.enable_drag()\n elif options == \"drag_2\":\n self.enable_drag_2()\n self.centered_ts = True\n self.q_offset = props.pop(\"q_offset\", 0) # flo\n self.i_offset = props.pop(\"i_offset\", 0)\n self.q_phase_offset = props.pop(\"q_phase_offset\", 0)\n self.i_phase_offset = props.pop(\"i_phase_offset\", 0)\n self.q_factor = props.pop(\"q_factor\", 1)\n self.i_factor = props.pop(\"i_factor\", 1)\n\n def asdict(self) -> dict:\n awg_dict = super().asdict()\n awg_dict[\"options\"] = self.__options\n return awg_dict\n\n # TODO create DC function\n\n def set_q_offset(self, q_offset): # flo\n self.q_offset = q_offset\n #self.process = self.create_IQ_q_offset()\n\n # TODO make AWG take offset from the previous point\n def create_IQ(self, instr: Instruction, chan: str) -> dict:\n \"\"\"\n Construct the in-phase (I) and quadrature (Q) components of the signal.\n These are universal to either experiment or simulation.\n In the xperiment these will be routed to AWG and mixer\n electronics, while in the simulation they provide the shapes of the\n instruction fields to be added to the Hamiltonian.\n\n Parameters\n ----------\n channel : str\n Identifier for the selected drive line.\n components : dict\n Separate signals to be combined onto this drive line.\n t_start : float\n Beginning of the signal.\n t_end : float\n End of the signal.\n\n Returns\n -------\n dict\n Waveforms as I and Q components.\n\n \"\"\"\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n components = instr.comps\n self.ts = ts\n # dt = ts[1] - ts[0]\n # t_before = ts[0] - dt\n amp_tot_sq = 0.0\n inphase_comps = []\n quadrature_comps = []\n\n for comp in components[chan].values():\n if isinstance(comp, Envelope):\n\n amp = comp.params[\"amp\"].get_value()\n\n amp_tot_sq += amp ** 2\n\n xy_angle = comp.params[\"xy_angle\"].get_value()\n freq_offset = comp.params[\"freq_offset\"].get_value()\n phase = -xy_angle + freq_offset * ts\n env = comp.get_shape_values(ts)\n # TODO option to have t_before\n # env = comp.get_shape_values(ts, t_before)\n inphase_comps.append(amp * env * tf.cos(phase + self.i_phase_offset)) # flo\n # quadrature_comps.append(-amp * env * tf.sin(phase))\n quadrature_comps.append(-amp * env * tf.sin(phase + self.q_phase_offset)) # flo\n\n norm = tf.sqrt(tf.cast(amp_tot_sq, tf.float64))\n inphase = self.i_factor * tf.add_n(inphase_comps, name=\"inphase\") + self.i_offset # flo\n quadrature = self.q_factor * tf.add_n(quadrature_comps, name=\"quadrature\") + self.q_offset # flo\n\n self.amp_tot = norm\n self.signal[chan] = {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n return {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n\n\n def create_IQ_drag(self, instr: Instruction, chan: str) -> dict:\n \"\"\"\n Construct the in-phase (I) and quadrature (Q) components of the signal.\n These are universal to either experiment or simulation.\n In the xperiment these will be routed to AWG and mixer\n electronics, while in the simulation they provide the shapes of the\n instruction fields to be added to the Hamiltonian.\n\n Parameters\n ----------\n channel : str\n Identifier for the selected drive line.\n components : dict\n Separate signals to be combined onto this drive line.\n t_start : float\n Beginning of the signal.\n t_end : float\n End of the signal.\n\n Returns\n -------\n dict\n Waveforms as I and Q components.\n\n \"\"\"\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n components = instr.comps\n self.ts = ts\n dt = ts[1] - ts[0]\n t_before = ts[0] - dt\n amp_tot_sq = 0.0\n inphase_comps = []\n quadrature_comps = []\n\n for comp in components[chan].values():\n if isinstance(comp, Envelope):\n\n amp = comp.params[\"amp\"].get_value()\n amp_tot_sq += amp ** 2\n\n xy_angle = comp.params[\"xy_angle\"].get_value()\n freq_offset = comp.params[\"freq_offset\"].get_value()\n # TODO should we remove this redefinition?\n delta = -comp.params[\"delta\"].get_value()\n if self.__options == \"drag_2\":\n delta = delta * dt\n\n with tf.GradientTape() as t:\n t.watch(ts)\n env = comp.get_shape_values(ts, t_before)\n # TODO option to have t_before = 0\n # env = comp.get_shape_values(ts, t_before)\n\n denv = t.gradient(env, ts)\n if denv is None:\n denv = tf.zeros_like(ts, dtype=tf.float64)\n phase = -xy_angle + freq_offset * ts\n inphase_comps.append(\n amp * (env * tf.cos(phase+self.i_phase_offset) + denv * delta * tf.sin(phase+self.i_phase_offset)) # flo\n )\n quadrature_comps.append(\n amp * (denv * delta * tf.cos(phase+self.q_phase_offset) - env * tf.sin(phase+self.q_phase_offset)) #flo\n )\n norm = tf.sqrt(tf.cast(amp_tot_sq, tf.float64))\n inphase = self.i_factor * tf.add_n(inphase_comps, name=\"inphase\") + self.i_offset #flo\n quadrature = self.q_factor * tf.add_n(quadrature_comps, name=\"quadrature\") + self.i_offset\n\n self.amp_tot = norm\n self.signal[chan] = {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n return {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n\n def create_IQ_pwc(self, instr: Instruction, chan: str) -> dict:\n \"\"\"\n Construct the in-phase (I) and quadrature (Q) components of the signal.\n These are universal to either experiment or simulation.\n In the xperiment these will be routed to AWG and mixer\n electronics, while in the simulation they provide the shapes of the\n instruction fields to be added to the Hamiltonian.\n\n Parameters\n ----------\n channel : str\n Identifier for the selected drive line.\n components : dict\n Separate signals to be combined onto this drive line.\n t_start : float\n Beginning of the signal.\n t_end : float\n End of the signal.\n\n Returns\n -------\n dict\n Waveforms as I and Q components.\n\n \"\"\"\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n components = instr.comps\n self.ts = ts\n # dt = ts[1] - ts[0]\n amp_tot_sq = 0.0\n inphase_comps = []\n quadrature_comps = []\n\n amp_tot_sq = 0\n for comp in components[chan].values():\n if isinstance(comp, Envelope):\n amp_tot_sq += 1\n if comp.shape is None:\n inphase = comp.params[\"inphase\"].get_value()\n quadrature = comp.params[\"quadrature\"].get_value()\n else:\n shape = comp.get_shape_values(ts)\n inphase = tf.math.real(shape)\n quadrature = tf.math.imag(shape)\n xy_angle = comp.params[\"xy_angle\"].get_value()\n freq_offset = comp.params[\"freq_offset\"].get_value()\n phase = -xy_angle + freq_offset * ts\n\n if len(inphase) != len(quadrature):\n raise ValueError(\"inphase and quadrature are of different lengths.\")\n elif len(inphase) < len(ts):\n zeros = tf.constant(\n np.zeros(len(ts) - len(inphase)), dtype=inphase.dtype\n )\n inphase = tf.concat([inphase, zeros], axis=0)\n quadrature = tf.concat([quadrature, zeros], axis=0)\n\n inphase_comps.append(\n inphase * tf.cos(phase) + quadrature * tf.sin(phase)\n )\n quadrature_comps.append(\n quadrature * tf.cos(phase) - inphase * tf.sin(phase)\n )\n\n norm = tf.sqrt(tf.cast(amp_tot_sq, tf.float64))\n inphase = tf.add_n(inphase_comps, name=\"inphase\")\n quadrature = tf.add_n(quadrature_comps, name=\"quadrature\")\n\n self.amp_tot = norm\n self.signal[chan] = {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n return {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n\n def get_average_amp(self, line):\n \"\"\"\n Compute average and sum of the amplitudes. Used to estimate effective drive power for non-trivial shapes.\n\n Returns\n -------\n tuple\n Average and sum.\n \"\"\"\n In = self.get_I(line)\n Qu = self.get_Q(line)\n amp_per_bin = tf.sqrt(tf.abs(In) ** 2 + tf.abs(Qu) ** 2)\n av = tf.reduce_mean(amp_per_bin)\n sum = tf.reduce_sum(amp_per_bin)\n return av, sum\n\n def get_I(self, line):\n return self.signal[line][\"inphase\"] # * self.amp_tot\n\n def get_Q(self, line):\n return self.signal[line][\"quadrature\"] # * self.amp_tot\n\n def enable_drag(self):\n self.process = self.create_IQ_drag\n\n def enable_drag_2(self):\n self.process = self.create_IQ_drag\n self.__options = \"drag_2\"\n\n def enable_pwc(self):\n self.process = self.create_IQ_pwc\n\n def log_shapes(self):\n # TODO log shapes in the generator instead\n with open(self.logdir + self.logname, \"a\") as logfile:\n signal = {}\n for key in self.signal:\n signal[key] = self.signal[key].numpy().tolist()\n logfile.write(hjson.dumps(signal))\n logfile.write(\"\\n\")\n logfile.flush()\n\n\n@dev_reg_deco\nclass oldAWG(Device):\n \"\"\"AWG device, transforms digital input to analog signal.\n\n Parameters\n ----------\n logdir : str\n Filepath to store generated waveforms.\n \"\"\"\n\n def __init__(self, **props):\n self.__options = \"\"\n self.logdir = props.pop(\n \"logdir\", os.path.join(tempfile.gettempdir(), \"c3logs\", \"AWG\")\n )\n self.logname = \"awg.log\"\n options = props.pop(\"options\", \"\")\n super().__init__(**props)\n self.outputs = props.pop(\"outputs\", 1)\n # TODO move the options pwc & drag to the instruction object\n self.amp_tot_sq = None\n self.process = self.create_IQ\n if options == \"drag\":\n self.enable_drag()\n elif options == \"drag_2\":\n self.enable_drag_2()\n self.centered_ts = True\n\n def asdict(self) -> dict:\n awg_dict = super().asdict()\n awg_dict[\"options\"] = self.__options\n return awg_dict\n\n # TODO create DC function\n\n # TODO make AWG take offset from the previous point\n def create_IQ(self, instr: Instruction, chan: str) -> dict:\n \"\"\"\n Construct the in-phase (I) and quadrature (Q) components of the signal.\n These are universal to either experiment or simulation.\n In the xperiment these will be routed to AWG and mixer\n electronics, while in the simulation they provide the shapes of the\n instruction fields to be added to the Hamiltonian.\n\n Parameters\n ----------\n channel : str\n Identifier for the selected drive line.\n components : dict\n Separate signals to be combined onto this drive line.\n t_start : float\n Beginning of the signal.\n t_end : float\n End of the signal.\n\n Returns\n -------\n dict\n Waveforms as I and Q components.\n\n \"\"\"\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n components = instr.comps\n self.ts = ts\n # dt = ts[1] - ts[0]\n # t_before = ts[0] - dt\n amp_tot_sq = 0.0\n inphase_comps = []\n quadrature_comps = []\n\n for comp in components[chan].values():\n if isinstance(comp, Envelope):\n\n amp = comp.params[\"amp\"].get_value()\n\n amp_tot_sq += amp ** 2\n\n xy_angle = comp.params[\"xy_angle\"].get_value()\n freq_offset = comp.params[\"freq_offset\"].get_value()\n phase = -xy_angle + freq_offset * ts\n env = comp.get_shape_values(ts)\n # TODO option to have t_before\n # env = comp.get_shape_values(ts, t_before)\n inphase_comps.append(amp * env * tf.cos(phase))\n quadrature_comps.append(-amp * env * tf.sin(phase))\n\n norm = tf.sqrt(tf.cast(amp_tot_sq, tf.float64))\n inphase = tf.add_n(inphase_comps, name=\"inphase\")\n quadrature = tf.add_n(quadrature_comps, name=\"quadrature\")\n\n self.amp_tot = norm\n self.signal[chan] = {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n return {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n\n def create_IQ_drag(self, instr: Instruction, chan: str) -> dict:\n \"\"\"\n Construct the in-phase (I) and quadrature (Q) components of the signal.\n These are universal to either experiment or simulation.\n In the xperiment these will be routed to AWG and mixer\n electronics, while in the simulation they provide the shapes of the\n instruction fields to be added to the Hamiltonian.\n\n Parameters\n ----------\n channel : str\n Identifier for the selected drive line.\n components : dict\n Separate signals to be combined onto this drive line.\n t_start : float\n Beginning of the signal.\n t_end : float\n End of the signal.\n\n Returns\n -------\n dict\n Waveforms as I and Q components.\n\n \"\"\"\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n components = instr.comps\n self.ts = ts\n dt = ts[1] - ts[0]\n t_before = ts[0] - dt\n amp_tot_sq = 0.0\n inphase_comps = []\n quadrature_comps = []\n\n for comp in components[chan].values():\n if isinstance(comp, Envelope):\n\n amp = comp.params[\"amp\"].get_value()\n amp_tot_sq += amp ** 2\n\n xy_angle = comp.params[\"xy_angle\"].get_value()\n freq_offset = comp.params[\"freq_offset\"].get_value()\n # TODO should we remove this redefinition?\n delta = -comp.params[\"delta\"].get_value()\n if self.__options == \"drag_2\":\n delta = delta * dt\n\n with tf.GradientTape() as t:\n t.watch(ts)\n env = comp.get_shape_values(ts, t_before)\n # TODO option to have t_before = 0\n # env = comp.get_shape_values(ts, t_before)\n\n denv = t.gradient(env, ts)\n if denv is None:\n denv = tf.zeros_like(ts, dtype=tf.float64)\n phase = -xy_angle + freq_offset * ts\n inphase_comps.append(\n amp * (env * tf.cos(phase) + denv * delta * tf.sin(phase))\n )\n quadrature_comps.append(\n amp * (denv * delta * tf.cos(phase) - env * tf.sin(phase))\n )\n norm = tf.sqrt(tf.cast(amp_tot_sq, tf.float64))\n inphase = tf.add_n(inphase_comps, name=\"inphase\")\n quadrature = tf.add_n(quadrature_comps, name=\"quadrature\")\n\n self.amp_tot = norm\n self.signal[chan] = {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n return {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n\n def create_IQ_pwc(self, instr: Instruction, chan: str) -> dict:\n \"\"\"\n Construct the in-phase (I) and quadrature (Q) components of the signal.\n These are universal to either experiment or simulation.\n In the xperiment these will be routed to AWG and mixer\n electronics, while in the simulation they provide the shapes of the\n instruction fields to be added to the Hamiltonian.\n\n Parameters\n ----------\n channel : str\n Identifier for the selected drive line.\n components : dict\n Separate signals to be combined onto this drive line.\n t_start : float\n Beginning of the signal.\n t_end : float\n End of the signal.\n\n Returns\n -------\n dict\n Waveforms as I and Q components.\n\n \"\"\"\n ts = self.create_ts(instr.t_start, instr.t_end, centered=True)\n components = instr.comps\n self.ts = ts\n # dt = ts[1] - ts[0]\n amp_tot_sq = 0.0\n inphase_comps = []\n quadrature_comps = []\n\n for comp in components[chan].values():\n if isinstance(comp, Envelope):\n amp_tot_sq += 1\n if comp.shape is None:\n inphase = comp.params[\"inphase\"].get_value()\n quadrature = comp.params[\"quadrature\"].get_value()\n else:\n shape = comp.get_shape_values(ts)\n inphase = tf.math.real(shape)\n quadrature = tf.math.imag(shape)\n xy_angle = comp.params[\"xy_angle\"].get_value()\n freq_offset = comp.params[\"freq_offset\"].get_value()\n phase = -xy_angle + freq_offset * ts\n\n if len(inphase) != len(quadrature):\n raise ValueError(\"inphase and quadrature are of different lengths.\")\n elif len(inphase) < len(ts):\n zeros = tf.constant(\n np.zeros(len(ts) - len(inphase)), dtype=inphase.dtype\n )\n inphase = tf.concat([inphase, zeros], axis=0)\n quadrature = tf.concat([quadrature, zeros], axis=0)\n\n inphase_comps.append(\n inphase * tf.cos(phase) + quadrature * tf.sin(phase)\n )\n quadrature_comps.append(\n quadrature * tf.cos(phase) - inphase * tf.sin(phase)\n )\n\n norm = tf.sqrt(tf.cast(amp_tot_sq, tf.float64))\n inphase = tf.add_n(inphase_comps, name=\"inphase\")\n quadrature = tf.add_n(quadrature_comps, name=\"quadrature\")\n\n self.amp_tot = norm\n self.signal[chan] = {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n return {\"inphase\": inphase, \"quadrature\": quadrature, \"ts\": ts}\n\n def get_average_amp(self, line):\n \"\"\"\n Compute average and sum of the amplitudes. Used to estimate effective drive power for non-trivial shapes.\n\n Returns\n -------\n tuple\n Average and sum.\n \"\"\"\n In = self.get_I(line)\n Qu = self.get_Q(line)\n amp_per_bin = tf.sqrt(tf.abs(In) ** 2 + tf.abs(Qu) ** 2)\n av = tf.reduce_mean(amp_per_bin)\n sum = tf.reduce_sum(amp_per_bin)\n return av, sum\n\n def get_I(self, line):\n return self.signal[line][\"inphase\"] # * self.amp_tot\n\n def get_Q(self, line):\n return self.signal[line][\"quadrature\"] # * self.amp_tot\n\n def enable_drag(self):\n self.process = self.create_IQ_drag\n\n def enable_drag_2(self):\n self.process = self.create_IQ_drag\n self.__options = \"drag_2\"\n\n def enable_pwc(self):\n self.process = self.create_IQ_pwc\n\n def log_shapes(self):\n # TODO log shapes in the generator instead\n with open(self.logdir + self.logname, \"a\") as logfile:\n signal = {}\n for key in self.signal:\n signal[key] = self.signal[key].numpy().tolist()\n logfile.write(hjson.dumps(signal))\n logfile.write(\"\\n\")\n logfile.flush()\n"
] |
[
[
"numpy.imag",
"tensorflow.constant",
"numpy.isnan",
"numpy.real",
"numpy.isinf",
"tensorflow.GradientTape"
],
[
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.linspace",
"tensorflow.add_n",
"numpy.random.randint",
"tensorflow.math.imag",
"numpy.sin",
"tensorflow.math.real",
"tensorflow.math.ceil",
"numpy.log",
"tensorflow.shape",
"tensorflow.exp",
"tensorflow.zeros_like",
"tensorflow.math.mod",
"tensorflow.signal.hamming_window",
"numpy.sum",
"tensorflow.GradientTape",
"tensorflow.sin",
"tensorflow.constant",
"numpy.abs",
"tensorflow.range",
"tensorflow.reduce_mean",
"tensorflow.cos",
"numpy.random.random",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.math.is_nan",
"numpy.cos",
"numpy.random.normal",
"tensorflow.abs"
]
] |
darthsuogles/mc-cnn
|
[
"f2c8aa67391ab9fbdae1102afbd1cb20f634d02c"
] |
[
"preprocess_mb.py"
] |
[
"#! /usr/bin/env python2\n# wget -r -np -A png,pfm,pgm,txt http://vision.middlebury.edu/stereo/data/scenes2014/datasets/\n# wget -r -np -A png,pfm,pgm,txt http://vision.middlebury.edu/stereo/data/scenes2006/FullSize/\n\nimport os\nimport re\nimport sys\nimport subprocess\n\nimport numpy as np\nimport cv2\n\ndef load_pfm(fname, downsample):\n if downsample:\n if not os.path.isfile(fname + '.H.pfm'):\n x, scale = load_pfm(fname, False)\n x = x / 2\n x_ = np.zeros((x.shape[0] // 2, x.shape[1] // 2), dtype=np.float32)\n for i in range(0, x.shape[0], 2):\n for j in range(0, x.shape[1], 2):\n tmp = x[i:i+2,j:j+2].ravel()\n x_[i // 2,j // 2] = np.sort(tmp)[1]\n save_pfm(fname + '.H.pfm', x_, scale)\n return x_, scale\n else:\n fname += '.H.pfm'\n color = None\n width = None\n height = None\n scale = None\n endian = None\n\n file = open(fname, encoding='latin-1')\n\n header = file.readline().rstrip()\n if header == 'PF':\n color = True\n elif header == 'Pf':\n color = False\n else:\n raise Exception('Not a PFM file.')\n\n dim_match = re.match(r'^(\\d+)\\s(\\d+)\\s$', file.readline())\n if dim_match:\n width, height = map(int, dim_match.groups())\n else:\n raise Exception('Malformed PFM header.')\n\n scale = float(file.readline().rstrip())\n if scale < 0: # little-endian\n endian = '<'\n scale = -scale\n else:\n endian = '>' # big-endian\n\n data = np.fromfile(file, endian + 'f')\n shape = (height, width, 3) if color else (height, width)\n return np.flipud(np.reshape(data, shape)), scale\n\ndef save_pfm(fname, image, scale=1):\n file = open(fname, 'w')\n color = None\n\n if image.dtype.name != 'float32':\n raise Exception('Image dtype must be float32.')\n\n if len(image.shape) == 3 and image.shape[2] == 3: # color image\n color = True\n elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale\n color = False\n else:\n raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')\n\n file.write('PF\\n' if color else 'Pf\\n')\n file.write('%d %d\\n' % (image.shape[1], image.shape[0]))\n\n endian = image.dtype.byteorder\n\n if endian == '<' or endian == '=' and sys.byteorder == 'little':\n scale = -scale\n\n file.write('%f\\n' % scale)\n\n np.flipud(image).tofile(file)\n\ndef read_im(fname, downsample):\n if downsample:\n if not os.path.exists(fname + '.H.png'):\n _sub_command = 'convert {} -resize 50% {}.H.png'.format(fname, fname)\n print('image convert with', _sub_command)\n subprocess.check_call(_sub_command.split())\n fname += '.H.png'\n\n print('reading image:', fname)\n _should_load_color_image = 1 if color == 'rgb' else 0\n _img = cv2.imread(fname, _should_load_color_image)\n x = _img.astype(np.float32)\n if color == 'rgb':\n x = cv2.cvtColor(x, cv2.COLOR_BGR2RGB)\n x = x.transpose(2, 0, 1)\n else:\n #x = cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)[None]\n x = x[None]\n x = (x - x.mean()) / x.std()\n return x[None]\n\ndef tofile(fname, x):\n if x is None:\n open(fname + '.dim', 'w').write('0\\n')\n open(fname, 'w')\n else:\n x.tofile(fname)\n open(fname + '.type', 'w').write(str(x.dtype))\n open(fname + '.dim', 'w').write('\\n'.join(map(str, x.shape)))\n\nrectification, color = sys.argv[1:]\nassert(rectification in set(['perfect', 'imperfect']))\nassert(color in set(['gray', 'rgb']))\noutput_dir = 'data.mb.{}_{}'.format(rectification, color)\nassert(os.path.isdir(output_dir))\n\nnum_channels = 3 if color == 'rgb' else 1\n\nX = []\ndispnoc = []\nmeta = []\nnnz_tr = []\nnnz_te = []\nte = np.arange(1, 11)\n\n### 2014 dataset ###\nbase1 = 'data.mb/unzip/vision.middlebury.edu/stereo/data/scenes2014/datasets'\nfor dir in sorted(os.listdir(base1)):\n if dir.endswith('imperfect'):\n print(dir.split('-')[0])\n\n base2_imperfect = os.path.join(base1, dir)\n base2_perfect = base2_imperfect.replace('imperfect', 'perfect')\n\n calib = open(os.path.join(base2_imperfect, 'calib.txt')).read()\n ndisp = int(re.search('ndisp=(.*)', calib).group(1)) / 2\n\n x0 = read_im(os.path.join(base2_imperfect, 'im0.png'), True)\n x1 = read_im(os.path.join(base2_imperfect, 'im1.png'), True)\n x1E = read_im(os.path.join(base2_imperfect, 'im1E.png'), True)\n x1L = read_im(os.path.join(base2_imperfect, 'im1L.png'), True)\n XX = [np.concatenate((x0, x1, x1E, x1L))]\n\n base3 = os.path.join(base2_perfect if rectification == 'perfect' else base2_imperfect, 'ambient')\n num_light = len(os.listdir(base3))\n\n num_exp = [], []\n for fname in os.listdir(base3 + '/L1'):\n num_exp[int(fname[2])].append(int(fname[4]) + 1)\n num_exp = min(max(num_exp[0]), max(num_exp[1]))\n rng = {\n 8: [1, 3, 5],\n 7: [1, 3, 5],\n 6: [0, 2, 4],\n 5: [0, 2, 4],\n 3: [0, 1, 2],\n 2: [0, 1],\n }\n for light in range(num_light):\n imgs = []\n base4 = os.path.join(base3, 'L{}'.format(light + 1))\n for exp in rng[num_exp]:\n for cam in range(2):\n im = read_im(base4 + '/im{}e{}.png'.format(cam, exp), True)\n imgs.append(im)\n _, _, height, width = imgs[0].shape\n XX.append(np.concatenate(imgs).reshape(len(imgs) // 2, 2, num_channels, height, width))\n\n disp0, scale0 = load_pfm(os.path.join(base2_imperfect, 'disp0.pfm'), True)\n disp1, scale1 = load_pfm(os.path.join(base2_imperfect, 'disp1.pfm'), True)\n disp0y, scale0y = load_pfm(os.path.join(base2_imperfect, 'disp0y.pfm'), True)\n\n save_pfm('tmp/disp0.pfm', disp0, 1)\n save_pfm('tmp/disp1.pfm', disp1, 1)\n save_pfm('tmp/disp0y.pfm', disp0y, 1)\n\n subprocess.check_output('computemask tmp/disp0.pfm tmp/disp0y.pfm tmp/disp1.pfm -1 tmp/mask.png'.split())\n\n mask = cv2.imread('tmp/mask.png', 0)\n disp0[mask != 255] = 0\n y, x = np.nonzero(mask == 255)\n\n X.append(XX)\n nnz = nnz_te if len(X) in te else nnz_tr\n nnz.append(np.column_stack((np.zeros_like(y) + len(X), y, x, disp0[y, x])).astype(np.float32))\n dispnoc.append(disp0.astype(np.float32))\n meta.append((x0.shape[2], x0.shape[3], ndisp))\n\nprint(np.vstack(nnz_tr).shape)\n\n### 2006 & 2005 dataset ###\nfor year in (2006, 2005):\n base1 = 'data.mb/unzip/vision.middlebury.edu/stereo/data/scenes{}/HalfSize'.format(year)\n for dir in sorted(os.listdir(base1)):\n base2 = os.path.join(base1, dir)\n if not os.path.isfile(base2 + '/disp1.png'):\n continue\n\n print(dir)\n\n XX = []\n XX.append(None) # there are no test images for this dataset\n for light in range(3):\n imgs = []\n for exp in (0, 1, 2):\n base3 = os.path.join(base2, 'Illum{}/Exp{}'.format(light + 1, exp))\n x0 = read_im(os.path.join(base3, 'view1.png'), False)\n x1 = read_im(os.path.join(base3, 'view5.png'), False)\n imgs.append(x0)\n imgs.append(x1)\n _, _, height, width = imgs[0].shape\n XX.append(np.concatenate(imgs).reshape(len(imgs) // 2, 2, num_channels, height, width))\n\n disp0 = cv2.imread(base2 + '/disp1.png', 0).astype(np.float32) / 2\n disp1 = cv2.imread(base2 + '/disp5.png', 0).astype(np.float32) / 2\n\n ndisp = int(np.ceil(disp0.max()))\n disp0[disp0 == 0] = np.inf\n disp1[disp1 == 0] = np.inf\n\n save_pfm('tmp/disp0.pfm', disp0, 1)\n save_pfm('tmp/disp1.pfm', disp1, 1)\n\n subprocess.check_output('computemask tmp/disp0.pfm tmp/disp1.pfm -1 tmp/mask.png'.split())\n\n mask = cv2.imread('tmp/mask.png', 0)\n disp0[mask != 255] = 0\n y, x = np.nonzero(mask == 255)\n\n X.append(XX)\n nnz_tr.append(np.column_stack((np.zeros_like(y) + len(X), y, x, disp0[y, x])).astype(np.float32))\n dispnoc.append(disp0.astype(np.float32))\n meta.append((x0.shape[2], x0.shape[3], ndisp))\n print(np.vstack(nnz_tr).shape)\n\n### 2003 dataset ###\nfor dir in ('conesH', 'teddyH'):\n print(dir)\n base1 = 'data.mb/unzip/vision.middlebury.edu/stereo/data/scenes2003/{}'.format(dir)\n\n XX = []\n XX.append(None)\n\n x0 = read_im(base1 + '/im2.ppm', False)\n x1 = read_im(base1 + '/im6.ppm', False)\n _, _, height, width = x0.shape\n XX.append(np.concatenate((x0, x1)).reshape(1, 2, num_channels, height, width))\n\n disp0 = cv2.imread(base1 + '/disp2.pgm', 0).astype(np.float32) / 2\n disp1 = cv2.imread(base1 + '/disp6.pgm', 0).astype(np.float32) / 2\n ndisp = int(np.ceil(disp0.max()))\n disp0[disp0 == 0] = np.inf\n disp1[disp1 == 0] = np.inf\n\n save_pfm('tmp/disp0.pfm', disp0, 1)\n save_pfm('tmp/disp1.pfm', disp1, 1)\n\n subprocess.check_output('computemask tmp/disp0.pfm tmp/disp1.pfm -1 tmp/mask.png'.split())\n\n mask = cv2.imread('tmp/mask.png', 0)\n disp0[mask != 255] = 0\n y, x = np.nonzero(mask == 255)\n\n X.append(XX)\n nnz_tr.append(np.column_stack((np.zeros_like(y) + len(X), y, x, disp0[y, x])).astype(np.float32))\n dispnoc.append(disp0.astype(np.float32))\n meta.append((x0.shape[2], x0.shape[3], ndisp))\n\nprint(np.vstack(nnz_tr).shape)\n\n### test ###\nfname_submit = []\n\nbase1 = 'data.mb/unzip/MiddEval3'\nfor dir1 in ['trainingH', 'testH']:\n base2 = os.path.join(base1, dir1)\n for dir2 in sorted(os.listdir(base2)):\n base3 = os.path.join(base2, dir2)\n print(os.path.join(dir1, dir2))\n\n calib = open(os.path.join(base3, 'calib.txt')).read()\n ndisp = int(re.search('ndisp=(.*)', calib).group(1))\n\n x0 = read_im(os.path.join(base3, 'im0.png'), False)\n x1 = read_im(os.path.join(base3, 'im1.png'), False)\n\n X.append([np.concatenate((x0, x1)).astype(np.float32)])\n meta.append((x0.shape[2], x0.shape[3], ndisp))\n fname_submit.append(os.path.join(dir1, dir2))\n\nmeta = np.array(meta, dtype=np.int32)\nnnz_tr = np.vstack(nnz_tr)\nnnz_te = np.vstack(nnz_te)\n\nsubprocess.check_call('rm -f {}/*.{{bin,dim,txt,type}} tmp/*'.format(output_dir), shell=True)\nfor i in range(len(X)):\n for j in range(len(X[i])):\n tofile('{}/x_{}_{}.bin'.format(output_dir, i + 1, j + 1), X[i][j])\n if i < len(dispnoc):\n tofile('{}/dispnoc{}.bin'.format(output_dir, i + 1), dispnoc[i])\ntofile('{}/meta.bin'.format(output_dir), meta)\ntofile('{}/nnz_tr.bin'.format(output_dir), nnz_tr)\ntofile('{}/nnz_te.bin'.format(output_dir), nnz_te)\ntofile('{}/te.bin'.format(output_dir), te)\nopen('{}/fname_submit.txt'.format(output_dir), 'w').write('\\n'.join(fname_submit))\n"
] |
[
[
"numpy.fromfile",
"numpy.nonzero",
"numpy.reshape",
"numpy.arange",
"numpy.flipud",
"numpy.sort",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
]
] |
lawrennd/ods
|
[
"16b5b577cfa6bbae52afac29f14083eadc963687"
] |
[
"pods/mocap.py"
] |
[
"# Copyright 2014 Open Data Science Initiative and other authors. See AUTHORS.txt\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\nimport os\nimport sys\nimport numpy as np\nimport math\n\n\nclass vertex:\n def __init__(self, name, id, parents=[], children=[], meta={}):\n self.name = name\n self.id = id\n self.parents = parents\n self.children = children\n self.meta = meta\n\n def __str__(self):\n return self.name + \"(\" + str(self.id) + \").\"\n\n\nclass tree:\n def __init__(self):\n self.vertices = []\n self.vertices.append(vertex(name=\"root\", id=0))\n\n def __str__(self):\n index = self.find_root()\n return self.branch_str(index)\n\n def branch_str(self, index, indent=\"\"):\n out = indent + str(self.vertices[index]) + \"\\n\"\n for child in self.vertices[index].children:\n out += self.branch_str(child, indent + \" \")\n return out\n\n def find_children(self):\n \"\"\"Take a tree and set the children according to the parents.\n\n Takes a tree structure which lists the parents of each vertex\n and computes the children for each vertex and places them in.\"\"\"\n for i in range(len(self.vertices)):\n self.vertices[i].children = []\n for i in range(len(self.vertices)):\n for parent in self.vertices[i].parents:\n if i not in self.vertices[parent].children:\n self.vertices[parent].children.append(i)\n\n def find_parents(self):\n \"\"\"Take a tree and set the parents according to the children\n\n Takes a tree structure which lists the children of each vertex\n and computes the parents for each vertex and places them in.\"\"\"\n for i in range(len(self.vertices)):\n self.vertices[i].parents = []\n for i in range(len(self.vertices)):\n for child in self.vertices[i].children:\n if i not in self.vertices[child].parents:\n self.vertices[child].parents.append(i)\n\n def find_root(self):\n \"\"\"Finds the index of the root node of the tree.\"\"\"\n self.find_parents()\n index = 0\n while len(self.vertices[index].parents) > 0:\n index = self.vertices[index].parents[0]\n return index\n\n def get_index_by_id(self, id):\n \"\"\"Give the index associated with a given vertex id.\"\"\"\n for i in range(len(self.vertices)):\n if self.vertices[i].id == id:\n return i\n raise ValueError(\"Reverse look up of id failed.\")\n\n def get_index_by_name(self, name):\n \"\"\"Give the index associated with a given vertex name.\n \n :param name: the name of a vertex.\n :type name: string\n :rval index: index of the vertex.\n :rtype int:\n \"\"\"\n for i in range(len(self.vertices)):\n if self.vertices[i].name == name:\n return i\n raise ValueError(\"Reverse look up of name failed.\")\n\n def order_vertices(self):\n \"\"\"Order vertices in the graph such that parents always have a lower index than children.\"\"\"\n\n ordered = False\n while ordered == False:\n for i in range(len(self.vertices)):\n ordered = True\n for parent in self.vertices[i].parents:\n if parent > i:\n ordered = False\n self.swap_vertices(i, parent)\n\n def swap_vertices(self, i, j):\n \"\"\"\n Swap two vertices in the tree structure array.\n swap_vertex swaps the location of two vertices in a tree structure array. \n\n :param tree: the tree for which two vertices are to be swapped.\n :param i: the index of the first vertex to be swapped.\n :param j: the index of the second vertex to be swapped.\n :rval tree: the tree structure with the two vertex locations swapped.\n\n \"\"\"\n store_vertex_i = self.vertices[i]\n store_vertex_j = self.vertices[j]\n self.vertices[j] = store_vertex_i\n self.vertices[i] = store_vertex_j\n for k in range(len(self.vertices)):\n for swap_list in [self.vertices[k].children, self.vertices[k].parents]:\n if i in swap_list:\n swap_list[swap_list.index(i)] = -1\n if j in swap_list:\n swap_list[swap_list.index(j)] = i\n if -1 in swap_list:\n swap_list[swap_list.index(-1)] = j\n\n\ndef rotation_matrix(xangle, yangle, zangle, order=\"zxy\", degrees=False):\n\n \"\"\"Compute the rotation matrix for an angle in each direction. This\n is a helper function for computing the rotation matrix for a given\n set of angles in a given order.\n\n :param xangle: rotation for x-axis.\n :param yangle: rotation for y-axis.\n :param zangle: rotation for z-axis.\n :param order: the order for the rotations.\n\n \"\"\"\n if degrees:\n xangle = math.radians(xangle)\n yangle = math.radians(yangle)\n zangle = math.radians(zangle)\n\n # Here we assume we rotate z, then x then y.\n c1 = math.cos(xangle) # The x angle\n c2 = math.cos(yangle) # The y angle\n c3 = math.cos(zangle) # the z angle\n s1 = math.sin(xangle)\n s2 = math.sin(yangle)\n s3 = math.sin(zangle)\n\n # see http://en.wikipedia.org/wiki/Rotation_matrix for\n # additional info.\n\n if order == \"zxy\":\n rot_mat = np.array(\n [\n [c2 * c3 - s1 * s2 * s3, c2 * s3 + s1 * s2 * c3, -s2 * c1],\n [-c1 * s3, c1 * c3, s1],\n [s2 * c3 + c2 * s1 * s3, s2 * s3 - c2 * s1 * c3, c2 * c1],\n ]\n )\n else:\n rot_mat = np.eye(3)\n for i in range(len(order)):\n if order[i] == \"x\":\n rot_mat = np.dot(\n np.array([[1, 0, 0], [0, c1, s1], [0, -s1, c1]]), rot_mat\n )\n elif order[i] == \"y\":\n rot_mat = np.dot(\n np.array([[c2, 0, -s2], [0, 1, 0], [s2, 0, c2]]), rot_mat\n )\n elif order[i] == \"z\":\n rot_mat = np.dot(\n np.array([[c3, s3, 0], [-s3, c3, 0], [0, 0, 1]]), rot_mat\n )\n\n return rot_mat\n\n\n# Motion capture data routines.\nclass skeleton(tree):\n def __init__(self):\n tree.__init__(self)\n\n def connection_matrix(self):\n connection = np.zeros((len(self.vertices), len(self.vertices)), dtype=bool)\n for i in range(len(self.vertices)):\n for j in range(len(self.vertices[i].children)):\n connection[i, self.vertices[i].children[j]] = True\n return connection\n\n def to_xyz(self, channels):\n raise NotImplementedError(\n \"this needs to be implemented to use the skeleton class\"\n )\n\n def finalize(self):\n \"\"\"After loading in a skeleton ensure parents are correct, vertex\n orders are correct and rotation matrices are correct.\"\"\"\n\n self.find_parents()\n self.order_vertices()\n self.set_rotation_matrices()\n\n def smooth_angle_channels(self, channels):\n \"\"\"Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions.\"\"\"\n for vertex in self.vertices:\n for col in vertex.meta[\"rot_ind\"]:\n if col:\n for k in range(1, channels.shape[0]):\n diff = channels[k, col] - channels[k - 1, col]\n if abs(diff + 360.0) < abs(diff):\n channels[k:, col] = channels[k:, col] + 360.0\n elif abs(diff - 360.0) < abs(diff):\n channels[k:, col] = channels[k:, col] - 360.0\n\n\n# class bvh_skeleton(skeleton):\n# def __init__(self):\n# skeleton.__init__(self)\n\n# def to_xyz(self, channels):\n\n\nclass acclaim_skeleton(skeleton):\n def __init__(self, file_name=None):\n skeleton.__init__(self)\n self.documentation = []\n self.angle = \"deg\"\n self.length = 1.0\n self.mass = 1.0\n self.type = \"acclaim\"\n self.vertices[0] = vertex(\n name=\"root\",\n id=0,\n parents=[0],\n children=[],\n meta={\n \"orientation\": [],\n \"axis\": [0.0, 0.0, 0.0],\n \"axis_order\": [],\n \"C\": np.eye(3),\n \"Cinv\": np.eye(3),\n \"channels\": [],\n \"bodymass\": [],\n \"confmass\": [],\n \"order\": [],\n \"rot_ind\": [],\n \"pos_ind\": [],\n \"limits\": [],\n \"xyz\": np.array([0.0, 0.0, 0.0]),\n \"rot\": np.eye(3),\n },\n )\n\n if file_name:\n self.load_skel(file_name)\n\n def to_xyz(self, channels):\n rot_val = list(self.vertices[0].meta[\"orientation\"])\n for i in range(len(self.vertices[0].meta[\"rot_ind\"])):\n rind = self.vertices[0].meta[\"rot_ind\"][i]\n if rind != -1:\n rot_val[i] += channels[rind]\n\n self.vertices[0].meta[\"rot\"] = rotation_matrix(\n rot_val[0],\n rot_val[1],\n rot_val[2],\n self.vertices[0].meta[\"axis_order\"],\n degrees=True,\n )\n # vertex based store of the xyz location\n self.vertices[0].meta[\"xyz\"] = list(self.vertices[0].meta[\"offset\"])\n\n for i in range(len(self.vertices[0].meta[\"pos_ind\"])):\n pind = self.vertices[0].meta[\"pos_ind\"][i]\n if pind != -1:\n self.vertices[0].meta[\"xyz\"][i] += channels[pind]\n\n for i in range(len(self.vertices[0].children)):\n ind = self.vertices[0].children[i]\n self.get_child_xyz(ind, channels)\n\n xyz = []\n for vertex in self.vertices:\n xyz.append(vertex.meta[\"xyz\"])\n return np.array(xyz)\n\n def get_child_xyz(self, ind, channels):\n\n parent = self.vertices[ind].parents[0]\n children = self.vertices[ind].children\n rot_val = np.zeros(3)\n for j in range(len(self.vertices[ind].meta[\"rot_ind\"])):\n rind = self.vertices[ind].meta[\"rot_ind\"][j]\n if rind != -1:\n rot_val[j] = channels[rind]\n else:\n rot_val[j] = 0\n tdof = rotation_matrix(\n rot_val[0],\n rot_val[1],\n rot_val[2],\n self.vertices[ind].meta[\"order\"],\n degrees=True,\n )\n\n torient = rotation_matrix(\n self.vertices[ind].meta[\"axis\"][0],\n self.vertices[ind].meta[\"axis\"][1],\n self.vertices[ind].meta[\"axis\"][2],\n self.vertices[ind].meta[\"axis_order\"],\n degrees=True,\n )\n\n torient_inv = rotation_matrix(\n -self.vertices[ind].meta[\"axis\"][0],\n -self.vertices[ind].meta[\"axis\"][1],\n -self.vertices[ind].meta[\"axis\"][2],\n self.vertices[ind].meta[\"axis_order\"][::-1],\n degrees=True,\n )\n\n self.vertices[ind].meta[\"rot\"] = np.dot(\n np.dot(np.dot(torient_inv, tdof), torient),\n self.vertices[parent].meta[\"rot\"],\n )\n\n self.vertices[ind].meta[\"xyz\"] = self.vertices[parent].meta[\"xyz\"] + np.dot(\n self.vertices[ind].meta[\"offset\"], self.vertices[ind].meta[\"rot\"]\n )\n\n for i in range(len(children)):\n cind = children[i]\n self.get_child_xyz(cind, channels)\n\n def load_channels(self, file_name):\n\n fid = open(file_name, \"r\")\n channels = self.read_channels(fid)\n fid.close()\n return channels\n\n def load_skel(self, file_name):\n\n \"\"\"\n Loads an ASF file into a skeleton structure.\n\n :param file_name: The file name to load in.\n\n \"\"\"\n\n fid = open(file_name, \"r\")\n self.read_skel(fid)\n fid.close()\n self.name = file_name\n\n def read_bonedata(self, fid):\n \"\"\"Read bone data from an acclaim skeleton file stream.\"\"\"\n\n bone_count = 0\n lin = self.read_line(fid)\n while lin[0] != \":\":\n parts = lin.split()\n if parts[0] == \"begin\":\n bone_count += 1\n self.vertices.append(\n vertex(\n name=\"\",\n id=np.NaN,\n meta={\n \"name\": [],\n \"id\": [],\n \"offset\": [],\n \"orientation\": [],\n \"axis\": [0.0, 0.0, 0.0],\n \"axis_order\": [],\n \"C\": np.eye(3),\n \"Cinv\": np.eye(3),\n \"channels\": [],\n \"bodymass\": [],\n \"confmass\": [],\n \"order\": [],\n \"rot_ind\": [],\n \"pos_ind\": [],\n \"limits\": [],\n \"xyz\": np.array([0.0, 0.0, 0.0]),\n \"rot\": np.eye(3),\n },\n )\n )\n lin = self.read_line(fid)\n\n elif parts[0] == \"id\":\n self.vertices[bone_count].id = int(parts[1])\n lin = self.read_line(fid)\n\n self.vertices[bone_count].children = []\n\n elif parts[0] == \"name\":\n self.vertices[bone_count].name = parts[1]\n lin = self.read_line(fid)\n\n elif parts[0] == \"direction\":\n direction = np.array(\n [float(parts[1]), float(parts[2]), float(parts[3])]\n )\n lin = self.read_line(fid)\n\n elif parts[0] == \"length\":\n lgth = float(parts[1])\n lin = self.read_line(fid)\n\n elif parts[0] == \"axis\":\n self.vertices[bone_count].meta[\"axis\"] = np.array(\n [float(parts[1]), float(parts[2]), float(parts[3])]\n )\n # order is reversed compared to bvh\n self.vertices[bone_count].meta[\"axis_order\"] = parts[-1][::-1].lower()\n lin = self.read_line(fid)\n\n elif parts[0] == \"dof\":\n order = []\n for i in range(1, len(parts)):\n if parts[i] == \"rx\":\n chan = \"Xrotation\"\n order.append(\"x\")\n elif parts[i] == \"ry\":\n chan = \"Yrotation\"\n order.append(\"y\")\n elif parts[i] == \"rz\":\n chan = \"Zrotation\"\n order.append(\"z\")\n elif parts[i] == \"tx\":\n chan = \"Xposition\"\n elif parts[i] == \"ty\":\n chan = \"Yposition\"\n elif parts[i] == \"tz\":\n chan = \"Zposition\"\n elif parts[i] == \"l\":\n chan = \"length\"\n self.vertices[bone_count].meta[\"channels\"].append(chan)\n # order is reversed compared to bvh\n self.vertices[bone_count].meta[\"order\"] = order[::-1]\n lin = self.read_line(fid)\n\n elif parts[0] == \"limits\":\n self.vertices[bone_count].meta[\"limits\"] = [\n [float(parts[1][1:]), float(parts[2][:-1])]\n ]\n\n lin = self.read_line(fid)\n\n while lin != \"end\":\n parts = lin.split()\n\n self.vertices[bone_count].meta[\"limits\"].append(\n [float(parts[0][1:]), float(parts[1][:-1])]\n )\n lin = self.read_line(fid)\n self.vertices[bone_count].meta[\"limits\"] = np.array(\n self.vertices[bone_count].meta[\"limits\"]\n )\n\n elif parts[0] == \"end\":\n self.vertices[bone_count].meta[\"offset\"] = direction * lgth\n lin = self.read_line(fid)\n\n return lin\n\n def read_channels(self, fid):\n \"\"\"Read channels from an acclaim file.\"\"\"\n bones = [[] for i in self.vertices]\n num_channels = 0\n for vertex in self.vertices:\n num_channels = num_channels + len(vertex.meta[\"channels\"])\n\n lin = self.read_line(fid)\n while lin != \":DEGREES\":\n lin = self.read_line(fid)\n if lin == \"\":\n raise ValueError(\"Could not find :DEGREES in \" + fid.name)\n\n counter = 0\n lin = self.read_line(fid)\n while lin:\n parts = lin.split()\n if len(parts) == 1:\n frame_no = int(parts[0])\n if frame_no:\n counter += 1\n if counter != frame_no:\n raise ValueError(\"Unexpected frame number.\")\n else:\n raise ValueError(\"Single bone name ...\")\n else:\n ind = self.get_index_by_name(parts[0])\n bones[ind].append(np.array([float(channel) for channel in parts[1:]]))\n lin = self.read_line(fid)\n\n num_frames = counter\n\n channels = np.zeros((num_frames, num_channels))\n\n end_val = 0\n for i in range(len(self.vertices)):\n vertex = self.vertices[i]\n if len(vertex.meta[\"channels\"]) > 0:\n start_val = end_val\n end_val = end_val + len(vertex.meta[\"channels\"])\n for j in range(num_frames):\n channels[j, start_val:end_val] = bones[i][j]\n self.resolve_indices(i, start_val)\n\n self.smooth_angle_channels(channels)\n return channels\n\n def read_documentation(self, fid):\n \"\"\"Read documentation from an acclaim skeleton file stream.\"\"\"\n\n lin = self.read_line(fid)\n while lin[0] != \":\":\n self.documentation.append(lin)\n lin = self.read_line(fid)\n return lin\n\n def read_hierarchy(self, fid):\n \"\"\"Read hierarchy information from acclaim skeleton file stream.\"\"\"\n\n lin = self.read_line(fid)\n\n while lin != \"end\":\n parts = lin.split()\n if lin != \"begin\":\n ind = self.get_index_by_name(parts[0])\n for i in range(1, len(parts)):\n self.vertices[ind].children.append(self.get_index_by_name(parts[i]))\n lin = self.read_line(fid)\n lin = self.read_line(fid)\n return lin\n\n def read_line(self, fid):\n \"\"\"Read a line from a file string and check it isn't either empty or commented before returning.\"\"\"\n lin = \"#\"\n while lin[0] == \"#\":\n lin = fid.readline().strip()\n if lin == \"\":\n return lin\n return lin\n\n def read_root(self, fid):\n \"\"\"Read the root node from an acclaim skeleton file stream.\"\"\"\n lin = self.read_line(fid)\n while lin[0] != \":\":\n parts = lin.split()\n if parts[0] == \"order\":\n order = []\n for i in range(1, len(parts)):\n if parts[i].lower() == \"rx\":\n chan = \"Xrotation\"\n order.append(\"x\")\n elif parts[i].lower() == \"ry\":\n chan = \"Yrotation\"\n order.append(\"y\")\n elif parts[i].lower() == \"rz\":\n chan = \"Zrotation\"\n order.append(\"z\")\n elif parts[i].lower() == \"tx\":\n chan = \"Xposition\"\n elif parts[i].lower() == \"ty\":\n chan = \"Yposition\"\n elif parts[i].lower() == \"tz\":\n chan = \"Zposition\"\n elif parts[i].lower() == \"l\":\n chan = \"length\"\n self.vertices[0].meta[\"channels\"].append(chan)\n # order is reversed compared to bvh\n self.vertices[0].meta[\"order\"] = order[::-1]\n\n elif parts[0] == \"axis\":\n # order is reversed compared to bvh\n self.vertices[0].meta[\"axis_order\"] = parts[1][::-1].lower()\n elif parts[0] == \"position\":\n self.vertices[0].meta[\"offset\"] = [\n float(parts[1]),\n float(parts[2]),\n float(parts[3]),\n ]\n elif parts[0] == \"orientation\":\n self.vertices[0].meta[\"orientation\"] = [\n float(parts[1]),\n float(parts[2]),\n float(parts[3]),\n ]\n lin = self.read_line(fid)\n return lin\n\n def read_skel(self, fid):\n \"\"\"Loads an acclaim skeleton format from a file stream.\"\"\"\n lin = self.read_line(fid)\n while lin:\n if lin[0] == \":\":\n if lin[1:] == \"name\":\n lin = self.read_line(fid)\n self.name = lin\n elif lin[1:] == \"units\":\n lin = self.read_units(fid)\n elif lin[1:] == \"documentation\":\n lin = self.read_documentation(fid)\n elif lin[1:] == \"root\":\n lin = self.read_root(fid)\n elif lin[1:] == \"bonedata\":\n lin = self.read_bonedata(fid)\n elif lin[1:] == \"hierarchy\":\n lin = self.read_hierarchy(fid)\n elif lin[1:8] == \"version\":\n lin = self.read_line(fid)\n continue\n else:\n if not lin:\n self.finalize()\n return\n lin = self.read_line(fid)\n else:\n raise ValueError(\"Unrecognised file format\")\n self.finalize()\n\n def read_units(self, fid):\n \"\"\"Read units from an acclaim skeleton file stream.\"\"\"\n lin = self.read_line(fid)\n while lin[0] != \":\":\n parts = lin.split()\n if parts[0] == \"mass\":\n self.mass = float(parts[1])\n elif parts[0] == \"length\":\n self.length = float(parts[1])\n elif parts[0] == \"angle\":\n self.angle = parts[1]\n lin = self.read_line(fid)\n return lin\n\n def resolve_indices(self, index, start_val):\n \"\"\"Get indices for the skeleton from the channels when loading in channel data.\"\"\"\n\n channels = self.vertices[index].meta[\"channels\"]\n base_channel = start_val\n rot_ind = -np.ones(3, dtype=int)\n pos_ind = -np.ones(3, dtype=int)\n for i in range(len(channels)):\n if channels[i] == \"Xrotation\":\n rot_ind[0] = base_channel + i\n elif channels[i] == \"Yrotation\":\n rot_ind[1] = base_channel + i\n elif channels[i] == \"Zrotation\":\n rot_ind[2] = base_channel + i\n elif channels[i] == \"Xposition\":\n pos_ind[0] = base_channel + i\n elif channels[i] == \"Yposition\":\n pos_ind[1] = base_channel + i\n elif channels[i] == \"Zposition\":\n pos_ind[2] = base_channel + i\n self.vertices[index].meta[\"rot_ind\"] = list(rot_ind)\n self.vertices[index].meta[\"pos_ind\"] = list(pos_ind)\n\n def set_rotation_matrices(self):\n \"\"\"Set the meta information at each vertex to contain the correct matrices C and Cinv as prescribed by the rotations and rotation orders.\"\"\"\n for i in range(len(self.vertices)):\n self.vertices[i].meta[\"C\"] = rotation_matrix(\n self.vertices[i].meta[\"axis\"][0],\n self.vertices[i].meta[\"axis\"][1],\n self.vertices[i].meta[\"axis\"][2],\n self.vertices[i].meta[\"axis_order\"],\n degrees=True,\n )\n # Todo: invert this by applying angle operations in reverse order\n self.vertices[i].meta[\"Cinv\"] = np.linalg.inv(self.vertices[i].meta[\"C\"])\n\n\n# Utilities for loading in x,y,z data.\ndef load_text_data(dataset, directory, centre=True):\n \"\"\"Load in a data set of marker points from the Ohio State University C3D motion capture files (http://accad.osu.edu/research/mocap/mocap_data.htm).\"\"\"\n\n points, point_names = parse_text(os.path.join(directory, dataset + \".txt\"))[0:2]\n # Remove markers where there is a NaN\n present_index = [\n i\n for i in range(points[0].shape[1])\n if not (\n np.any(np.isnan(points[0][:, i]))\n or np.any(np.isnan(points[0][:, i]))\n or np.any(np.isnan(points[0][:, i]))\n )\n ]\n\n point_names = point_names[present_index]\n for i in range(3):\n points[i] = points[i][:, present_index]\n if centre:\n points[i] = (points[i].T - points[i].mean(axis=1)).T\n\n # Concatanate the X, Y and Z markers together\n Y = np.concatenate((points[0], points[1], points[2]), axis=1)\n Y = Y / 400.0\n connect = read_connections(os.path.join(directory, \"connections.txt\"), point_names)\n return Y, connect\n\n\ndef parse_text(file_name):\n \"\"\"Parse data from Ohio State University text mocap files (http://accad.osu.edu/research/mocap/mocap_data.htm).\"\"\"\n\n # Read the header\n fid = open(file_name, \"r\")\n point_names = np.array(fid.readline().split())[2:-1:3]\n fid.close()\n for i in range(len(point_names)):\n point_names[i] = point_names[i][0:-2]\n\n # Read the matrix data\n S = np.loadtxt(file_name, skiprows=1)\n field = np.uint(S[:, 0])\n times = S[:, 1]\n S = S[:, 2:]\n\n # Set the -9999.99 markers to be not present\n S[S == -9999.99] = np.NaN\n\n # Store x, y and z in different arrays\n points = []\n points.append(S[:, 0:-1:3])\n points.append(S[:, 1:-1:3])\n points.append(S[:, 2:-1:3])\n\n return points, point_names, times\n\n\ndef read_connections(file_name, point_names):\n \"\"\"Read a file detailing which markers should be connected to which for motion capture data.\"\"\"\n\n connections = []\n fid = open(file_name, \"r\")\n line = fid.readline()\n while line:\n connections.append(np.array(line.split(\",\")))\n connections[-1][0] = connections[-1][0].strip()\n connections[-1][1] = connections[-1][1].strip()\n line = fid.readline()\n connect = np.zeros((len(point_names), len(point_names)), dtype=bool)\n for i in range(len(point_names)):\n for j in range(len(point_names)):\n for k in range(len(connections)):\n if (\n connections[k][0] == point_names[i]\n and connections[k][1] == point_names[j]\n ):\n\n connect[i, j] = True\n connect[j, i] = True\n break\n\n return connect\n\n\nskel = acclaim_skeleton()\n"
] |
[
[
"numpy.dot",
"numpy.linalg.inv",
"numpy.isnan",
"numpy.eye",
"numpy.uint",
"numpy.ones",
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.loadtxt"
]
] |
1asso/TOM-Net
|
[
"ba13bd3f1bac0fa50c6043290691d7be5c29f777"
] |
[
"train.py"
] |
[
"import torch\nimport utility\nimport logging\nimport os\nimport torch.nn as nn\nfrom torch import Tensor\nfrom typing import Type, Any, Callable, Union, List, Optional\nfrom torch.utils.data import DataLoader\nfrom models import CoarseNet, RefineNet\nfrom argparse import Namespace\nfrom checkpoint import CheckPoint\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import StepLR\nfrom torchvision.utils import save_image\n\n\nclass Trainer:\n def __init__(self, model: Union[CoarseNet.CoarseNet, RefineNet.RefineNet], \n opt: Namespace, optim_state: Optional[dict]) -> None:\n print('\\n\\n --> Initializing Trainer')\n self.opt = opt\n self.model = model.cuda()\n self.warping_module = self.setup_warping_module() \n self.multi_scale_data = self.setup_ms_data_module()\n self.optim_state = self.setup_solver(optim_state) \n self.setup_criterions()\n self.optimizer = torch.optim.Adam(self.model.parameters(), **(self.optim_state), \\\n weight_decay=0.01)\n self.scheduler = StepLR(self.optimizer, step_size=5, gamma=0.5)\n \n print('\\n\\n --> Total number of parameters in ETOM-Net: ' + str(sum(p.numel() for p in self.model.parameters())))\n\n self.input_image = None\n self.ref_images = None\n self.tar_images = None\n self.rhos = None\n self.masks = None\n self.flows = None\n \n def setup_ms_data_module(self) -> utility.CreateMultiScaleData:\n print('[Multi Scale] Setting up multi scale data module')\n ms_data_module = utility.CreateMultiScaleData(self.opt.ms_num)\n return ms_data_module\n\n def setup_warping_module(self) -> utility.CreateMultiScaleWarping:\n print('[Multi Scale] Setting up multi scale warping')\n warping_module = utility.CreateMultiScaleWarping(self.opt.ms_num)\n return warping_module\n\n def setup_criterions(self) -> None:\n print('\\n\\n --> Setting up criterion')\n\n print('[Flow Loss] Setting up EPELoss for flow')\n self.flow_criterion = utility.EPELoss\n\n print('[Rec Loss] Setting up MSELoss for reconstructed image')\n self.rec_criterion = nn.MSELoss\n \n print('[Mask Loss] Setting up CrossENtropyLoss for mask')\n self.mask_criterion = nn.CrossEntropyLoss\n\n print('[Rho Loss] Setting up MSELoss for rho')\n self.rho_criterion = nn.MSELoss\n\n def setup_solver(self, in_optim_state: dict) -> dict:\n optim_state = None\n if self.opt.solver == 'ADAM':\n print('[Solver] Using Adam solver')\n optim_state = in_optim_state or {\n 'lr': self.opt.lr_r if self.opt.refine else self.opt.lr,\n 'betas': (self.opt.beta_1, self.opt.beta_2)\n }\n else:\n logging.warning('Unknown optimization method')\n\n return optim_state\n\n def train(self, epoch: int, dataloader: DataLoader, split: str) -> float:\n gradient_accumulations = self.opt.ga\n\n num_batches = len(dataloader)\n print('\\n====================')\n print(self.optim_state)\n print(f'Training epoch # {epoch+1}, totaling mini batches {num_batches}')\n print('====================\\n')\n\n self.model.train()\n \n loss_iter = {} # loss every n iterations\n loss_epoch = {} # loss of the entire epoch\n eps = 1e-7\n\n # Zero gradients\n self.optimizer.zero_grad()\n\n if self.opt.refine:\n loss_iter['mask'] = 0\n loss_iter['flow'] = 0\n\n for iter, sample in enumerate(dataloader):\n input = self.setup_inputs(sample)\n \n torch.cuda.empty_cache()\n torch.autograd.set_detect_anomaly(True)\n\n output = self.model.forward(input) \n\n pred_images = self.single_flow_warping(output) # warp input image with flow\n\n flow_loss = self.opt.r_flow_w * self.flow_criterion()(output[0], self.flows, \\\n self.masks.unsqueeze(1), self.rhos.unsqueeze(1)) \n mask_loss = self.opt.r_mask_w * self.mask_criterion()(output[1] + eps, self.masks.squeeze(1).long()) \n\n loss = flow_loss + mask_loss\n \n loss_iter['mask'] += mask_loss.item() \n loss_iter['flow'] += flow_loss.item()\n\n # Perform a backward pass\n (loss / gradient_accumulations).backward()\n\n # Update the weights\n if (iter + 1) % gradient_accumulations == 0:\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n if (iter+1) % self.opt.train_display == 0:\n loss_epoch[iter] = self.display(epoch+1, iter+1, num_batches, loss_iter, split)\n loss_iter['mask'] = 0\n loss_iter['flow'] = 0\n\n if (iter+1) % self.opt.train_save == 0:\n self.save_results(epoch+1, iter+1, output, pred_images, split, 0)\n else:\n for i in range(self.opt.ms_num):\n loss_iter[f'Scale {i} mask'] = 0\n loss_iter[f'Scale {i} rho'] = 0\n loss_iter[f'Scale {i} flow'] = 0\n loss_iter[f'Scale {i} rec'] = 0\n\n\n for iter, sample in enumerate(dataloader):\n input = self.setup_inputs(sample)\n \n torch.cuda.empty_cache()\n torch.autograd.set_detect_anomaly(True)\n\n output = self.model.forward(input) \n\n pred_images = self.flow_warping(output) # warp input image with flow\n\n loss = None\n\n for i in range(self.opt.ms_num):\n \n mask_loss = self.opt.mask_w * self.mask_criterion()(output[i][1] + eps, \\\n self.multi_masks[i].squeeze(1).long()) * (1 / 2 ** (self.opt.ms_num - i - 1))\n rho_loss = self.opt.rho_w * self.rho_criterion()(output[i][2], \\\n self.multi_rhos[i]) * (1 / 2 ** (self.opt.ms_num - i - 1))\n flow_loss = self.opt.flow_w * self.flow_criterion()(output[i][0], \\\n self.multi_flows[i], self.multi_masks[i], self.multi_rhos[i]) * (1 / 2 ** (self.opt.ms_num - i - 1))\n mask = utility.get_mask(output[i][1]).expand(output[i][1].size(0), \\\n 3, output[i][1].size(2), output[i][1].size(3))\n final_pred = utility.get_final_pred(self.multi_ref_images[i], \\\n pred_images[i], mask, output[i][2])\n rec_loss = self.opt.img_w * self.rec_criterion()(final_pred, \\\n self.multi_tar_images[i]) * (1 / 2 ** (self.opt.ms_num - i - 1))\n \n if i == 0:\n loss = mask_loss + rho_loss + flow_loss + rec_loss\n else:\n loss += mask_loss + rho_loss + flow_loss + rec_loss\n \n loss_iter[f'Scale {i} mask'] += mask_loss.item() \n loss_iter[f'Scale {i} rho'] += rho_loss.item()\n loss_iter[f'Scale {i} flow'] += flow_loss.item()\n loss_iter[f'Scale {i} rec'] += rec_loss.item()\n\n # Perform a backward pass\n (loss / gradient_accumulations).backward()\n \n # Update the weights\n if (iter + 1) % gradient_accumulations == 0:\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n if (iter+1) % self.opt.train_display == 0:\n loss_epoch[iter] = self.display(epoch+1, iter+1, num_batches, loss_iter, split)\n for i in range(self.opt.ms_num):\n loss_iter[f'Scale {i} mask'] = 0\n loss_iter[f'Scale {i} rho'] = 0\n loss_iter[f'Scale {i} flow'] = 0\n loss_iter[f'Scale {i} rec'] = 0\n\n if (iter+1) % self.opt.train_save == 0:\n self.save_ms_results(epoch+1, iter+1, output, pred_images, split, 0)\n \n average_loss = utility.build_loss_string(utility.dict_of_dict_average(loss_epoch))\n print(f'\\n\\n --> Epoch: [{epoch+1}] Loss summary: \\n{average_loss}')\n self.scheduler.step()\n self.optim_state['lr'] = self.optimizer.param_groups[0]['lr']\n \n return average_loss\n\n def get_saving_name(self, log_dir: str, split: str, epoch: int, iter: int, id: int) -> str:\n f_path = f'{log_dir}/{split}/Images/'\n f_names = f'epoch:{epoch}_iter:{iter}_id:{id}'\n return os.path.join(f_path, f_names + '.png')\n\n def save_images(self, pred_images: Tensor, output: List[Tensor], count: int) -> int:\n for i in range(pred_images.size()[0]):\n print(count)\n os.makedirs(f'results/{count}')\n mask = torch.squeeze(utility.get_mask(output[1][i].unsqueeze(0))).expand(3, output[1].size(2), output[1].size(3))\n rho = output[2][i].repeat(3, 1, 1)\n final_img = utility.get_final_pred(self.ref_images[i], pred_images[i], mask, rho)\n save_image(final_img, f'results/{count}/in_rec.png')\n save_image(mask.float(), f'results/{count}/mask.png')\n save_image(rho, f'results/{count}/rho.png')\n utility.save_flow(f'results/{count}/flow.flo', output[0][i])\n\n save_image(self.ref_images[i], f'results/{count}/bg.png')\n save_image(self.masks[i], f'results/{count}/mask_gt.png')\n save_image(self.rhos[i], f'results/{count}/rho_gt.png')\n save_image(self.input_image[i], f'results/{count}/input.png')\n save_image(self.tar_images[i], f'results/{count}/tar.png')\n utility.save_flow(f'results/{count}/flow_gt.flo', self.flows[i][0:2, :, :])\n save_image(utility.flow_to_color(torch.mul(output[0][i], self.masks[i])), f'results/{count}/fcolor.png')\n save_image(utility.flow_to_color(self.flows[i]), f'results/{count}/fcolor_gt.png')\n count += 1\n return count\n\n def get_predicts(self, id: int, output: List[Tensor], pred_img: Tensor, m_scale: int) -> List[Tensor]:\n pred = [] \n if m_scale != None:\n gt_color_flow = utility.flow_to_color(self.multi_flows[m_scale][id])\n else:\n gt_color_flow = utility.flow_to_color(self.flows[id])\n pred.append(gt_color_flow)\n\n color_flow = utility.flow_to_color(output[0][id])\n pred.append(color_flow)\n mask = torch.squeeze(utility.get_mask(output[1][id].unsqueeze(0))).expand(3, output[1].size(2), output[1].size(3))\n pred.append(mask)\n rho = output[2][id].repeat(3, 1, 1)\n pred.append(rho)\n\n if m_scale != None:\n final_img = utility.get_final_pred(self.multi_ref_images[m_scale][id], pred_img[id], mask, rho)\n first_img = self.multi_tar_images[m_scale][id]\n else:\n final_img = utility.get_final_pred(self.ref_images[id], pred_img[id], mask, rho)\n first_img = self.tar_images[id]\n\n pred.insert(0, first_img)\n pred.insert(1, final_img)\n return pred\n\n def get_first_row(self, id: int) -> List[Union[bool, Tensor]]:\n first = []\n first.append(self.ref_images[id])\n first.append(self.tar_images[id])\n first.append(False)\n first.append(False)\n first.append(self.masks[id])\n first.append(self.rhos[id])\n return first\n\n def save_ms_results(\n self, \n epoch: int, \n iter: int, \n output: List[List[Tensor]], \n multi_pred_img: List[List[Tensor]], \n split: str, \n id: int\n ) -> None:\n id = id or 0\n scales = self.opt.ms_num\n results = []\n\n first_row = self.get_first_row(id)\n for val in first_row:\n results.append(val)\n \n for i in range(scales-1, -1, -1):\n sub_pred = self.get_predicts(id, output[i], multi_pred_img[i], i)\n for val in sub_pred:\n results.append(val)\n \n save_name = self.get_saving_name(self.opt.log_dir, split, epoch, iter, id)\n utility.save_compact_results(save_name, results, 6)\n print('\\n\\n --> Flow magnitude: Max {}, Min {}, Mean {}'.format(\n torch.max(output[scales-1][0][id]), torch.min(output[scales-1][0][id]), \n torch.mean(torch.abs(output[scales-1][0][id]))))\n\n def save_results(\n self, \n epoch: int, \n iter: int, \n output: List[Tensor], \n pred_img: Tensor, \n split: str, \n id: int\n ) -> None:\n id = id or 0\n results = []\n\n first_row = self.get_first_row(id)\n for val in first_row:\n results.append(val)\n \n sub_pred = self.get_predicts(id, output, pred_img, None)\n for val in sub_pred:\n results.append(val)\n \n save_name = self.get_saving_name(self.opt.log_dir, split, epoch, iter, id)\n utility.save_compact_results(save_name, results, 6)\n\n def flow_warping(self, output: List[List[Tensor]]) -> List[Tensor]:\n flows = []\n for i in range(self.opt.ms_num):\n flows.append(output[i][0])\n \n pred_images= self.warping_module([self.multi_ref_images, flows])\n return pred_images\n\n def single_flow_warping(self, output: List[Tensor]) -> Tensor:\n pred_images= utility.create_single_warping([self.ref_images, output[0]])\n return pred_images\n\n def test(self, epoch: int, dataloader: DataLoader, split: str) -> float:\n num_batches = len(dataloader)\n\n loss_iter = {}\n loss_epoch = {}\n\n print(f'\\n\\n===== Testing after {epoch+1} epochs =====')\n \n self.model.eval()\n \n rec_err = 0\n rho_err = 0\n flow_err = 0\n mask_err = 0\n size = 400\n\n def iou(pred, tar):\n intersection = torch.logical_and(tar, pred)\n union = torch.logical_or(tar, pred)\n iou_score = torch.true_divide(torch.sum(intersection), torch.sum(union))\n return iou_score\n\n def epe(mask_gt, flow_gt, flow):\n mask_gt = mask_gt.expand_as(flow_gt)\n flow = flow * mask_gt\n flow_gt = flow_gt * mask_gt\n return torch.norm(flow_gt-flow, dim=1).mean() / 100\n\n if self.opt.refine:\n loss_iter['mask'] = 0\n loss_iter['flow'] = 0\n\n count = 1\n\n for iter, sample in enumerate(dataloader):\n\n with torch.no_grad():\n input = self.setup_inputs(sample)\n \n torch.cuda.empty_cache()\n torch.autograd.set_detect_anomaly(True)\n\n output = self.model.forward(input) \n\n pred_images = self.single_flow_warping(output) # warp input image with flow\n \n if self.opt.save_images:\n count = self.save_images(pred_images, output, count)\n\n for i in range(output[0].size(0)):\n mask = torch.squeeze(utility.get_mask(output[1][i].unsqueeze(0))).expand(3, \\\n output[1][i].size(1), output[1][i].size(2))\n final_pred = utility.get_final_pred(self.ref_images[i], \\\n pred_images[i], mask, output[2][i]) \n rec_err += 100 * F.mse_loss(final_pred, self.tar_images[i])\n rho_err += 100 * F.mse_loss(output[2][i], self.rhos[i])\n flow_err += epe(self.masks[i], self.flows[i][0:2, :, :] * \\\n self.rhos[i], output[0][i] * self.rhos[i])\n mask_err += iou(mask, self.masks[i])\n\n flow_loss = self.opt.r_flow_w * self.flow_criterion()(output[0], self.flows, \\\n self.masks.unsqueeze(1), self.rhos.unsqueeze(1)) \n mask_loss = self.opt.r_mask_w * self.mask_criterion()(output[1], self.masks.squeeze(1).long()) \n \n loss_iter['mask'] += mask_loss.item() \n loss_iter['flow'] += flow_loss.item()\n\n if (iter+1) % self.opt.val_display == 0:\n loss_epoch[iter] = self.display(epoch+1, iter+1, num_batches, loss_iter, split)\n loss_iter['mask'] = 0\n loss_iter['flow'] = 0\n\n if (iter+1) % self.opt.val_save == 0:\n self.save_results(epoch+1, iter+1, output, pred_images, split, 0)\n else:\n for i in range(self.opt.ms_num):\n loss_iter[f'Scale {i} mask'] = 0\n loss_iter[f'Scale {i} rho'] = 0\n loss_iter[f'Scale {i} flow'] = 0\n loss_iter[f'Scale {i} rec'] = 0\n\n count = 1\n\n for iter, sample in enumerate(dataloader):\n\n with torch.no_grad():\n\n torch.cuda.empty_cache()\n\n input = self.setup_inputs(sample)\n torch.cuda.empty_cache()\n torch.autograd.set_detect_anomaly(True)\n\n output = self.model.forward(input)\n pred_images = self.flow_warping(output) # warp input image with flow\n\n if self.opt.save_images:\n count = self.save_images(pred_images[-1], output[-1], count)\n\n loss = None\n\n for i in range(output[-1][0].size(0)):\n mask = torch.squeeze(utility.get_mask(output[-1][1][i].unsqueeze(0))).expand(3, \\\n output[-1][1][i].size(1), output[-1][1][i].size(2))\n final_pred = utility.get_final_pred(self.multi_ref_images[-1][i], \\\n pred_images[-1][i], mask, output[-1][2][i])\n rec_err += 100 * F.mse_loss(final_pred, self.multi_tar_images[-1][i])\n rho_err += 100 * F.mse_loss(output[-1][2][i], self.multi_rhos[-1][i])\n flow_err += epe(self.multi_masks[-1][i], self.multi_flows[-1][i][0:2, :, :] * \\\n self.multi_rhos[-1][i], output[-1][0][i] * self.multi_rhos[-1][i])\n mask_err += iou(mask, self.multi_masks[-1][i])\n\n for i in range(self.opt.ms_num):\n\n mask_loss = self.opt.mask_w * self.mask_criterion()(output[i][1], \\\n self.multi_masks[i].squeeze(1).long()) * (1 / 2 ** (self.opt.ms_num - i - 1))\n rho_loss = self.opt.rho_w * self.rho_criterion()(output[i][2], \\\n self.multi_rhos[i]) * (1 / 2 ** (self.opt.ms_num - i - 1))\n flow_loss = self.opt.flow_w * self.flow_criterion()(output[i][0], \\\n self.multi_flows[i], self.multi_masks[i], self.multi_rhos[i]) * (1 / 2 ** (self.opt.ms_num - i - 1))\n mask = utility.get_mask(output[i][1]).expand(output[i][1].size(0), \\\n 3, output[i][1].size(2), output[i][1].size(3))\n final_pred = utility.get_final_pred(self.multi_ref_images[i], \\\n pred_images[i], mask, output[i][2])\n rec_loss = self.opt.img_w * self.rec_criterion()(final_pred, \\\n self.multi_tar_images[i]) * (1 / 2 ** (self.opt.ms_num - i - 1))\n\n loss_iter[f'Scale {i} mask'] += mask_loss.item() \n loss_iter[f'Scale {i} rho'] += rho_loss.item()\n loss_iter[f'Scale {i} flow'] += flow_loss.item()\n loss_iter[f'Scale {i} rec'] += rec_loss.item()\n\n if (iter+1) % self.opt.val_display == 0:\n loss_epoch[iter] = self.display(epoch+1, iter+1, num_batches, loss_iter, split)\n for i in range(self.opt.ms_num):\n loss_iter[f'Scale {i} mask'] = 0\n loss_iter[f'Scale {i} rho'] = 0\n loss_iter[f'Scale {i} flow'] = 0\n loss_iter[f'Scale {i} rec'] = 0\n\n if (iter+1) % self.opt.val_save == 0:\n self.save_ms_results(epoch+1, iter+1, output, pred_images, split, 0)\n\n rec_err /= size\n rho_err /= size\n flow_err /= size\n mask_err /= size\n eval_str = f'rec_err: {rec_err}\\nrho_err: {rho_err}\\nflow_err: {flow_err}\\nmask_err: {mask_err}\\n'\n \n average_loss = utility.build_loss_string(utility.dict_of_dict_average(loss_epoch))\n average_loss = eval_str + average_loss\n print(f'\\n\\n --> Epoch: [{epoch+1}] Loss summary: \\n{average_loss}')\n return average_loss\n\n def display(self, epoch: int, iter: int, num_batches: int, loss: dict, split: str) -> float:\n interval = (split == 'train') and self.opt.train_display or self.opt.val_display\n average_loss = utility.dict_divide(loss, interval)\n\n print(f'\\n\\n --> Epoch ({split}): [{epoch}][{iter}/{num_batches}]')\n print(utility.build_loss_string(average_loss))\n return average_loss\n\n def setup_inputs(self, sample: dict) -> Tensor:\n self.copy_inputs(sample)\n if not self.opt.refine:\n self.generate_ms_inputs(sample)\n network_input = self.input_image\n else:\n checkpoint = torch.load(self.opt.pred_dir)\n model = checkpoint['model']\n network_input = model.forward(self.input_image)[self.opt.ms_num-1]\n network_input.insert(0, nn.functional.interpolate(\n self.input_image, (512,512), mode='bicubic', align_corners=True))\n \n return network_input\n\n def copy_inputs(self, sample: dict) -> None:\n del self.ref_images\n del self.tar_images\n del self.masks\n del self.rhos\n del self.flows\n del self.input_image\n\n self.input_image = torch.cuda.FloatTensor()\n self.ref_images = torch.cuda.FloatTensor()\n self.tar_images = torch.cuda.FloatTensor()\n self.masks = torch.cuda.FloatTensor()\n self.rhos = torch.cuda.FloatTensor()\n self.flows = torch.cuda.FloatTensor()\n\n n, c, h, w = list(sample['images'].size())\n sh, sw = list(sample['input'].size()[2:])\n\n self.input_image.resize_(n, 3, sh, sw).copy_(sample['input'])\n self.ref_images.resize_(n, 3, h, w).copy_(sample['images'][:,:3,:,:])\n self.tar_images.resize_(n, 3, h, w).copy_(sample['images'][:,3:,:,:])\n self.masks.resize_(n, h, w).copy_(sample['masks'])\n self.rhos.resize_(n, h, w).copy_(sample['rhos'])\n self.flows.resize_(n, 3, h, w).copy_(sample['flows'])\n\n def generate_ms_inputs(self, sample: dict) -> None:\n multiscale_in = [self.ref_images, self.tar_images, self.rhos, self.masks, self.flows]\n\n multiscale_out = self.multi_scale_data(multiscale_in)\n self.multi_ref_images = multiscale_out[0]\n self.multi_tar_images = multiscale_out[1]\n self.multi_rhos = multiscale_out[2]\n self.multi_masks = multiscale_out[3]\n self.multi_flows = multiscale_out[4]\n\n for i in range(self.opt.ms_num):\n # rescale the loss weight for flow in different scale\n ratio = 2 ** (self.opt.ms_num - i - 1)\n self.multi_flows[i][:, 2, :] *= ratio\n\n self.multi_masks[i] = self.multi_masks[i].unsqueeze(1)\n self.multi_rhos[i] = self.multi_rhos[i].unsqueeze(1)\n"
] |
[
[
"torch.abs",
"torch.norm",
"torch.max",
"torch.autograd.set_detect_anomaly",
"torch.load",
"torch.min",
"torch.sum",
"torch.cuda.empty_cache",
"torch.cuda.FloatTensor",
"torch.nn.functional.mse_loss",
"torch.mul",
"torch.no_grad",
"torch.nn.functional.interpolate",
"torch.logical_and",
"torch.logical_or",
"torch.optim.lr_scheduler.StepLR"
]
] |
l11x0m7/insuranceQA_zh
|
[
"0ccad4416be5683145de944db309922c78bfa209"
] |
[
"data.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#===============================================================================\n#\n# Copyright (c) 2017 Hai Liang Wang<[email protected]> All Rights Reserved\n#\n#\n# File: /Users/hain/ai/InsuranceQA-Machine-Learning/deep_qa_1/network.py\n# Author: Hai Liang Wang\n# Date: 2017-08-08:18:32:05\n#\n#===============================================================================\n\n\"\"\"\n A data API for learning QA.\n \n \n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\n\n__copyright__ = \"Copyright (c) 2017 Hai Liang Wang. All Rights Reserved\"\n__author__ = \"Hai Liang Wang\"\n__modify__ = \"Xuming Lin\"\n__date__ = \"2017-08-08:18:32:05\"\n\n\nimport os\nimport sys\ncurdir = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0, os.path.dirname(curdir))\n\nif sys.version_info[0] < 3:\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n # raise \"Must be using Python 3\"\n\nimport random\nimport insuranceqa_data as insuranceqa\n\nimport numpy as np\n\n_train_data = insuranceqa.load_pairs_train()\n_test_data = insuranceqa.load_pairs_test()\n_valid_data = insuranceqa.load_pairs_valid()\n\n\n\n'''\nbuild vocab data with more placeholder\n'''\nvocab_data = insuranceqa.load_pairs_vocab()\nvocab_size = len(vocab_data['word2id'].keys())\nVOCAB_PAD_ID = vocab_size+1\nVOCAB_GO_ID = vocab_size+2\nvocab_data['word2id']['<PAD>'] = VOCAB_PAD_ID\nvocab_data['word2id']['<GO>'] = VOCAB_GO_ID\nvocab_data['id2word'][VOCAB_PAD_ID] = '<PAD>'\nvocab_data['id2word'][VOCAB_GO_ID] = '<GO>'\n\n\ndef combine_pos_and_neg_sample(data):\n '''\n combine the positive answers and negative samples with the same problem\n '''\n qa = dict()\n for x in data:\n qa.setdefault(x['qid'], [\"\", [], []])\n qa[x['qid']][0] = x['question']\n if x['label'] == [1, 0]:\n qa[x['qid']][1].append(x['utterance'])\n else:\n qa[x['qid']][2].append(x['utterance'])\n result = list()\n for qid in qa:\n question = qa[qid][0]\n for pos_a in qa[qid][1]:\n for neg_a in qa[qid][2]:\n result.append({'qid': qid, 'question': question, 'pos_utterance': pos_a, 'neg_utterance': neg_a})\n return result\n\n_train_data = combine_pos_and_neg_sample(_train_data)\n\ndef _get_corpus_metrics():\n '''\n max length of questions\n '''\n for cat, data in zip([\"valid\", \"test\", \"train\"], [_valid_data, _test_data, _train_data]):\n max_len_question = 0\n total_len_question = 0\n max_len_utterance = 0\n total_len_utterance = 0\n for x in data:\n total_len_question += len(x['question']) \n total_len_utterance += len(x['utterance'])\n if len(x['question']) > max_len_question: \n max_len_question = len(x['question'])\n if len(x['utterance']) > max_len_utterance: \n max_len_utterance = len(x['utterance'])\n print('max len of %s question : %d, average: %d' % (cat, max_len_question, total_len_question/len(data)))\n print('max len of %s utterance: %d, average: %d' % (cat, max_len_utterance, total_len_utterance/len(data)))\n # max length of answers\n\n\nclass BatchIter():\n '''\n Load data with mini-batch\n '''\n def __init__(self, data = None, batch_size = 100):\n assert data is not None, \"data should not be None.\"\n self.batch_size = batch_size\n self.data = data\n\n def next(self):\n random.shuffle(self.data)\n index = 0\n total_num = len(self.data)\n while index <= total_num:\n yield self.data[index:index + self.batch_size]\n index += self.batch_size\n\ndef padding(lis, pad, size):\n '''\n right adjust a list object\n '''\n if size > len(lis):\n lis += [pad] * (size - len(lis))\n else:\n lis = lis[0:size]\n return lis\n\ndef pack_question_n_utterance(q, p_u, n_u=None, q_length = 20, u_length = 99):\n '''\n combine question and utterance as input data for feed-forward network\n '''\n assert len(q) > 0 and len(p_u) > 0, \"question and utterance must not be empty\"\n q = padding(q, VOCAB_PAD_ID, q_length)\n p_u = padding(p_u, VOCAB_PAD_ID, u_length)\n assert len(q) == q_length, \"question should be pad to q_length\"\n assert len(p_u) == u_length, \"utterance should be pad to u_length\"\n if n_u is not None:\n assert len(n_u) > 0, \"negative utterance must not be empty\"\n n_u = padding(n_u, VOCAB_PAD_ID, u_length)\n assert len(n_u) == u_length, \"negative utterance should be pad to u_length\"\n return q, p_u, n_u\n return q, p_u\n\nscale_digit= lambda x: x*0.001\n\ndef __resolve_train_data(data, batch_size, question_max_length = 20, utterance_max_length = 99):\n '''\n resolve train data\n '''\n batch_iter = BatchIter(data = data, batch_size = batch_size)\n \n for mini_batch in batch_iter.next():\n qids = []\n questions = []\n pos_answers = []\n neg_answers = []\n for o in mini_batch:\n q, pu, nu = pack_question_n_utterance(o['question'], o['pos_utterance'], o['neg_utterance'], question_max_length, utterance_max_length)\n qids.append(o['qid'])\n questions.append(list(map(scale_digit, q)))\n pos_answers.append(list(map(scale_digit, pu)))\n neg_answers.append(list(map(scale_digit, nu)))\n if len(questions) > 0:\n yield qids, questions, pos_answers, neg_answers\n else:\n raise StopIteration\n\ndef __resolve_valid_data(data, batch_size, question_max_length = 20, utterance_max_length = 99):\n '''\n resolve valid data\n '''\n batch_iter = BatchIter(data = data, batch_size = batch_size)\n \n for mini_batch in batch_iter.next():\n qids = []\n questions = []\n answers = []\n labels = []\n for o in mini_batch:\n q, pu = pack_question_n_utterance(o['question'], o['utterance'], None, question_max_length, utterance_max_length)\n qids.append(o['qid'])\n questions.append(q)\n answers.append(pu)\n labels.append(np.argmax(o['label']))\n if len(questions) > 0:\n # print('data in batch:%d' % len(mini_batch))\n yield qids, questions, answers, labels\n else:\n raise StopIteration\n\n# export data\n\ndef load_train(batch_size = 100, question_max_length = 20, utterance_max_length = 99):\n '''\n load train data\n '''\n return __resolve_train_data(_train_data, batch_size, question_max_length, utterance_max_length)\n\ndef load_test(question_max_length = 20, utterance_max_length = 99):\n '''\n load test data\n '''\n questions = []\n utterances = []\n labels = []\n qids = []\n for o in _test_data:\n qid = o['qid']\n q, pu = pack_question_n_utterance(o['question'],\n o['utterance'],\n None,\n question_max_length,\n utterance_max_length)\n qids.append(qid)\n questions.append(list(map(scale_digit, q)))\n utterances.append(list(map(scale_digit, pu)))\n labels.append(0 if np.argmax(o['label']) == 1 else 1)\n return zip(qids, questions, utterances, labels)\n\ndef load_valid(batch_size = 100, question_max_length = 20, utterance_max_length = 99):\n '''\n load valid data\n '''\n return __resolve_valid_data(_valid_data, batch_size, question_max_length, utterance_max_length)\n\ndef test_batch():\n '''\n retrieve data with mini batch\n '''\n for mini_batch in zip(load_train()):\n for qid, q, pos_a, neg_a in mini_batch:\n print(q[0])\n print(pos_a[0])\n print(neg_a[0])\n break\n break\n for mini_batch in zip(load_valid()):\n for qid, q, pos_a, labels in mini_batch:\n print(q[0])\n print(pos_a[0])\n print(labels[0])\n break\n break\n for (qid, q, pos_a, label) in zip(*load_test()):\n print(q)\n print(pos_a)\n print(label)\n break\n\n print(\"VOCAB_PAD_ID\", VOCAB_PAD_ID)\n print(\"VOCAB_GO_ID\", VOCAB_GO_ID)\n\nif __name__ == '__main__':\n test_batch()\n\n"
] |
[
[
"numpy.argmax"
]
] |
masguit42/pytorch
|
[
"d1cbee7b2b1da94ff1a0fa880bd0173de27fb89f"
] |
[
"torch/testing/_internal/common_methods_invocations.py"
] |
[
"from functools import wraps, partial\nfrom itertools import product, chain\nimport itertools\nimport collections\nimport copy\nimport operator\nimport random\nimport numbers\n\nimport torch\nimport numpy as np\nfrom torch._six import inf\nimport collections.abc\n\nfrom typing import List, Sequence, Tuple, Union\n\nfrom torch.testing import \\\n (make_non_contiguous, floating_types, floating_types_and, complex_types,\n floating_and_complex_types, floating_and_complex_types_and,\n all_types_and_complex_and, all_types_and, all_types_and_complex,\n integral_types_and, all_types, double_types)\nfrom .._core import _dispatch_dtypes\nfrom torch.testing._internal.common_device_type import \\\n (expectedFailure, onlyOnCPUAndCUDA, skipIf, skipCUDAIfNoMagma, skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfNoCusolver,\n skipCPUIfNoLapack, skipCPUIfNoFFT, skipCUDAIfRocm, precisionOverride, toleranceOverride, tol)\nfrom torch.testing._internal.common_cuda import CUDA11OrLater, SM53OrLater, SM60OrLater\nfrom torch.testing._internal.common_utils import \\\n (is_iterable_of_tensors,\n random_symmetric_matrix, random_symmetric_psd_matrix,\n make_fullrank_matrices_with_distinct_singular_values,\n random_symmetric_pd_matrix, make_symmetric_matrices,\n make_symmetric_pd_matrices, random_square_matrix_of_rank,\n random_fullrank_matrix_distinct_singular_value,\n TEST_WITH_ROCM, IS_WINDOWS, IS_MACOS, make_tensor, TEST_SCIPY,\n torch_to_numpy_dtype_dict, TEST_WITH_ASAN,\n GRADCHECK_NONDET_TOL,)\nimport torch.testing._internal.opinfo_helper as opinfo_helper\n\nfrom setuptools import distutils\n\nif TEST_SCIPY:\n import scipy.special\n\n\nclass DecorateInfo(object):\n \"\"\"Describes which test, or type of tests, should be wrapped in the given\n decorators when testing an operator. Any test that matches all provided\n arguments will be decorated. The decorators will only be applied if the\n active_if argument is True.\"\"\"\n\n __slots__ = ['decorators', 'cls_name', 'test_name', 'device_type', 'dtypes', 'active_if']\n\n def __init__(self, decorators, cls_name=None, test_name=None, *,\n device_type=None, dtypes=None, active_if=True):\n self.decorators = list(decorators) if isinstance(decorators, collections.abc.Sequence) else [decorators]\n self.cls_name = cls_name\n self.test_name = test_name\n self.device_type = device_type\n self.dtypes = dtypes\n self.active_if = active_if\n\n def is_active(self, cls_name, test_name, device_type, dtype):\n return (\n self.active_if and\n (self.cls_name is None or self.cls_name == cls_name) and\n (self.test_name is None or self.test_name == test_name) and\n (self.device_type is None or self.device_type == device_type) and\n (self.dtypes is None or dtype in self.dtypes)\n )\n\n\nclass SkipInfo(DecorateInfo):\n \"\"\"Describes which test, or type of tests, should be skipped when testing\n an operator. Any test that matches all provided arguments will be skipped.\n The skip will only be checked if the active_if argument is True.\"\"\"\n\n def __init__(\n self, cls_name=None, test_name=None, *, device_type=None, dtypes=None, active_if=True,\n expected_failure=False):\n \"\"\"\n Args:\n cls_name: the name of the test class to skip\n test_name: the name of the test within the test class to skip\n device_type: the devices for which to skip the tests\n dtypes: the dtypes for which to skip the tests\n active_if: whether tests matching the above arguments should be skipped\n expected_failure: whether to assert that skipped tests fail\n \"\"\"\n decorator = expectedFailure(device_type) if expected_failure else skipIf(True, \"Skipped!\")\n super().__init__(decorators=decorator, cls_name=cls_name, test_name=test_name,\n device_type=device_type, dtypes=dtypes, active_if=active_if)\n\n\nclass SampleInput(object):\n \"\"\"Represents sample inputs to a function.\"\"\"\n\n __slots__ = ['input', 'args', 'kwargs', 'output_process_fn_grad', 'broadcasts_input', 'name']\n\n def __init__(self, input, *, args=tuple(), kwargs=None, output_process_fn_grad=lambda x: x, broadcasts_input=False, name=\"\"):\n # input is the first input to the op and must be either a Tensor or TensorList (Sequence[Tensor]).\n # This follows the typical pattern where for Tensor inputs op(t, ...) = t.op(...).\n # op with TensorList inputs do not support method or inplace variants.\n assert isinstance(input, torch.Tensor) or is_iterable_of_tensors(input)\n self.input: Union[torch.Tensor, Sequence[torch.Tensor]] = input\n self.args = args\n self.kwargs = kwargs if kwargs is not None else {}\n self.output_process_fn_grad = output_process_fn_grad\n self.name = name\n\n # Specifies if `self.input` is broadcasted or not,\n # given that the operator supports broadcasting.\n # This field is used to verify the behavior for inplace variant.\n #\n # If a SampleInput is marked with `broadcasts_input=True`,\n # it is verified that we get a `RuntimerError` with this sample,\n # and inplace variant. Also inplace grad{grad} tests are skipped,\n # for such inputs (as they will error out otherwise).\n self.broadcasts_input = broadcasts_input\n\n def _repr_helper(self, formatter):\n # Helper function to return the details of the SampleInput as `str`\n # It consolidates all the fields of SampleInput and allows,\n # formatting the fields like `input`, `args`, etc with `formatter`\n # callable to customize the representation.\n # Look at `summary` method for example.\n arguments = [\n f'input={formatter(self.input)}',\n f'args={formatter(self.args)}',\n f'kwargs={formatter(self.kwargs)}',\n f'output_process_fn_grad={self.output_process_fn_grad}',\n f'broadcasts_input={self.broadcasts_input}',\n f'name={repr(self.name)}']\n\n return f'SampleInput({\", \".join(a for a in arguments if a is not None)})'\n\n def __repr__(self):\n return self._repr_helper(lambda x: x)\n\n def summary(self):\n # Returns the SampleInput details in a more\n # friendly format.\n # It formats `Tensor` and `TensorList`\n # in a more condensed representation.\n def formatter(arg):\n # Format any instance of `Tensor` (standalone, in list, or in dict)\n # by Tensor[TensorShape]\n # Eg. Tensor with shape (3, 4) is formatted as Tensor[3, 4]\n if isinstance(arg, torch.Tensor):\n shape = str(tuple(arg.shape)).replace('(', '').replace(')', '')\n return f\"Tensor[{shape}]\"\n elif isinstance(arg, dict):\n return {k: formatter(v) for k, v in arg.items()}\n elif is_iterable_of_tensors(arg):\n return \"TensorList[\" + \", \".join(map(formatter, arg)) + \"]\"\n elif isinstance(arg, (list, tuple)): # Handle list, tuple\n return \"(\" + \",\".join(map(formatter, arg)) + \")\"\n\n return repr(arg)\n\n return self._repr_helper(formatter)\n\n # Returns the NumPy version of the sample input object in the form of a tuple: (input, args, kwargs)\n def numpy(self):\n # Converts tensors to ndarrays by calling .detach().cpu().numpy() on them\n # Numbers, strings, and bool are preserved as is\n # Lists, tuples and dicts are handled by calling this function recursively\n def to_numpy(x):\n def _np(t):\n return t.detach().cpu().numpy()\n\n if isinstance(x, torch.Tensor):\n return _np(x)\n elif isinstance(x, list):\n return list(map(to_numpy, x))\n elif isinstance(x, tuple):\n return tuple(map(to_numpy, x))\n elif isinstance(x, dict):\n return {k: to_numpy(v) for k, v in x.items()}\n elif isinstance(x, (numbers.Number, bool, str)):\n return x\n\n raise ValueError(\"Unknown type {0}!\".format(type(x)))\n\n sample_np_input, np_args, np_kwargs = to_numpy(self.input), to_numpy(self.args), to_numpy(self.kwargs)\n return (sample_np_input, np_args, np_kwargs)\n\nclass AliasInfo(object):\n \"\"\"Class holds alias information. For example, torch.abs ->\n torch.absolute, torch.Tensor.absolute, torch.Tensor.absolute_\n \"\"\"\n\n def __init__(self, alias_name):\n self.name = alias_name\n self.op = _getattr_qual(torch, alias_name)\n self.method_variant = getattr(torch.Tensor, alias_name, None)\n self.inplace_variant = getattr(torch.Tensor, alias_name + \"_\", None)\n\n def __call__(self, *args, **kwargs):\n return self.op(*args, **kwargs)\n\n\n_NOTHING = object() # Unique value to distinguish default from anything else\n\n\n# Extension of getattr to support qualified names\n# e.g. _getattr_qual(torch, 'linalg.norm') -> torch.linalg.norm\ndef _getattr_qual(obj, name, default=_NOTHING):\n try:\n for path in name.split('.'):\n obj = getattr(obj, path)\n return obj\n except AttributeError:\n if default is not _NOTHING:\n return default\n else:\n raise\n\n# Note [OpInfos]\n# ~~~~~~~~~~~~~~\n#\n# This note was written shortly after the PyTorch 1.9 release.\n# If you notice it's out-of-date or think it could be improved then please\n# file an issue.\n#\n# See also: the OpInfo tracker (https://github.com/pytorch/pytorch/issues/54261)\n# See also: \"Writing Test Templates\" in common_device_type.py to learn how to\n# parametrize a test template using OpInfos.\n#\n# An OpInfo is a collection of metadata related to a PyTorch operator. This\n# metadata is used to generate tests that validate properties of the operator,\n# like if it implements the correct gradient formula.\n#\n# WHY OPINFOS?\n# ~~~~~~~~~~~~\n#\n# OpInfos are principally intended to do two things:\n#\n# 1) to simplify testing an operator\n# 2) to allow systems (like autograd, torchscript, fx, nnc...) to test\n# against every PyTorch operator\n#\n# Both these goals are still a work in progress. Not every operator has an\n# OpInfo, and some operator tests still have to be written manually.\n#\n# The utility of OpInfos can also be motivated from a different perspective.\n# PyTorch is a complicated framework with many interrelated systems, too\n# many for any one person to keep track of. An OpInfo can be thought of as the\n# interface between an operator implementer and those other systems. Instead of\n# requiring the implementer of torch.foo understand how to test its forward\n# mode AD or NNC support that's typically handled automatically just by\n# defining an OpInfo. This is a helpful perspective to have, because it's often\n# surprising to OpInfo writers that just implementing an OpInfo typically can't\n# verify an operator is actually implemented correctly. \"If an OpInfo doesn't\n# validate my op works as expected, what's the point of it?\" But the point of\n# it is that it lets engineers focus on testing their operator logic instead\n# of having to write tests for how the operator interacts with each of\n# PyTorch's many systems. And, OK, sometimes it validates your op works\n# the way you want and all you have to do is write an OpInfo and you're done\n# testing... more on that below.\n#\n# WHAT'S AN OPINFO?\n# ~~~~~~~~~~~~~~~~~\n#\n# So what is an OpInfo? It's a Python class that describes an operator's properties,\n# like which dtypes it supports on the CPU and whether it has any aliases.\n# These properties can be divided into three categories:\n#\n# 1) Metadata describing the operator, like the operator's name and if it\n# \"supports\" the out kwarg.\n# 2) Test directives, like \"skips\" that tell the test suite to skip some\n# tests.\n# 3) A \"sample inputs\" function that generates valid inputs for the operator.\n#\n# OpInfo attributes are described in more detail below.\n#\n# THE SAMPLE INPUTS FUNCTION\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# The \"sample inputs\" function merits special elaboration. This function is\n# crucial to testing with OpInfos. A typical OpInfo test has to treat the operator\n# as a black box. There's no structure for the test to understand or exploit.\n# Without \"sample inputs\" it wouldn't even know how to call the OpInfo's\n# operator. The sample input function saves the day by providing different\n# \"SampleInputs\" that can be used to call the operator. A sample input\n# function should have the following signature:\n#\n# def sample_inputs_foo(op_info, device, dtype, requires_grad, **kwargs):\n#\n# And should return a list of SampleInputs (see the class description above).\n# Each SampleInput defines an \"input\", \"args\", \"kwargs\",\n# an \"output_process_fn_grad\" function, the \"broadcasts_input\" bool and\n# a \"name\".\n#\n# The \"input\" is the first argument to the operator, or the tensor that\n# the method or inplace variants of the operator should be called on, and\n# should be on the requested device, of the requested dtype, and its\n# requires_grad attribute should be set to the requires_grad argument.\n#\n# \"args\" should contain positional arguments, and \"kwargs\" keyword arguments.\n#\n# \"output_process_fn_grad\" has an interesting name. It's a function that maps\n# the operator's output (when given the input, args, and kwargs) to the\n# portion of the output to gradcheck. For example, consider an operator\n# like torch.linalg.slogdet\n# (https://pytorch.org/docs/master/generated/torch.linalg.slogdet.html).\n# This operator returns a tuple of two tensors, but the first tensor\n# cannot be backwarded through. Its \"output_process_fn_grad\" filters\n# this output tuple to just the second argument, which we can call backward\n# on. Functions that produce a single tensor can ignore this argument.\n#\n# \"broadcasts_input\" is a bool indicated if the SampleInput causes the operator\n# to broadcast the \"input\" argument. This is important for tests to understand\n# because inplace variants of operations throw a runtime error if they\n# would broadcast their input arguments, so tests that work with inplace\n# variants filter SampleInputs that broadcast their input.\n#\n# \"name\" is a string that's just used for debugging. It appears when printing\n# the SampleInput.\n#\n# OPINFO FILE ORGANIZATION\n# ~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# All OpInfos are currently defined in this file. Most OpInfo tests are defined\n# in test_ops.py, but some system-specific tests are defined in those\n# systems' test files, and subclass-specific tests are defined in the test\n# file that corresponds to that subclass (see the below).\n# Expect a reorganization in the future.\n#\n# WHAT'S TESTED?\n# ~~~~~~~~~~~~~~\n#\n# Every OpInfo in the op_db sequence has the following properties validated in\n# test_ops.py:\n#\n# - that its supported dtypes are specified correctly\n# - that it supports the out= argument properly (if it allows out=),\n# see https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-does-out-work-in-pytorch\n# - that it works with the conjugate view bit properly\n# - that its function, method, and inplace variants perform the same operation\n# (that is, that torch.add, torch.Tensor.add, and torch.Tensor.add_ all\n# do the same thing).\n# - that its inplace variant preserves the input's storage\n# - that its gradient formula is implemented correctly, and that it supports\n# gradgrad and complex grad and gradgrad and forward mode AD properly for\n# the op's function and inplace variants (method variants are skipped\n# to reduce test time).\n# - that the operation performs the same operation when traced or scripted\n# using the jit\n# - that the operation is autodifferentiated by the jit as expected\n# - that the operator's aliases, if any, perform the same operation and that\n# the jit understands the alias\n#\n# Additional OpInfo tests are in test_jit_fuser_te.py, test_fx_experimental.py,\n# and test_fx.py. These tests validate that operators work with NNC and FX\n# as expected.\n#\n# For performance, some of the above tests may only run on the first\n# SampleInput returned by an OpInfo's sample input function.\n#\n# In addition to these tests, some subclasses (discussed in the next section)\n# define additional tests.\n#\n# Critically, as mentioned above, what's not tested is that the operator\n# works as expected. When implementing an OpInfo an engineer must still\n# typically write one or more tests validating the operator's behavior.\n#\n# OPINFO (SUB)CLASSES\n# ~~~~~~~~~~~~~~~~~~~\n#\n# In addition to the OpInfo base class there are several specialized OpInfo\n# subclasses. For example, the UnaryUfuncInfo subclass is used for\n# unary elementwise operations. These operations have a common structure\n# that test_unary_ufuncs.py exploits with additional automated testing.\n# The automated testing in test_unary_ufuncs.py is so thorough, comparing\n# the operator to a NumPy reference function on a plethora of values, that\n# just implementing an OpInfo for a unary elementwise operation is often\n# sufficient testing.\n#\n# The ForeachFuncInfo is another OpInfo subclass that is hyper-specialized to a\n# very unique class of operations. These OpInfos aren't included in the\n# op_db sequence and have their own tests.\n#\n# Other OpInfo subclasses, like SpectralFuncInfo, are just for convenience\n# when writing OpInfos.\n#\n# TESTING A NEW OPERATOR\n# ~~~~~~~~~~~~~~~~~~~~~~\n#\n# If you're adding a new operator to the torch, torch.fft, torch.linalg,\n# or torch.special namespaces then you should add an OpInfo for it. As\n# mentioned a couple times above, implementing an OpInfo is not usually\n# sufficient testing (unless the operator is a unary elementwise operator).\n# The OpInfo will only test the properties described in the \"WHAT'S TESTED\"\n# section. It DOES NOT verify that the operator is implemented correctly.\n#\n# We are currently reviewing if operators in the torch.nn.functional namespace\n# will be added as OpInfos, but you are encouraged to add an OpInfo for\n# such operators, too.\n#\n# TIPS FOR WRITING AN OPINFO AND OPINFO TESTS\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Writing an OpInfo can be a little daunting. Since the point of an OpInfo is to\n# be consumed by a variety of systems it can be hard to understand how to\n# deal with test failures or how to set the OpInfo metadata properly.\n#\n# Before adding an OpInfo it helps to look at other OpInfos. A sample inputs\n# function must be defined, and the operator's dtypes must be specified.\n# Once that's done you should run the operator's tests in test_ops.py\n# (these can be filtered using the \"-k\" argument in pytest). Tests that\n# fail should provide an error message that describes what to change about\n# your OpInfo. You don't need to worry about changing an OpInfo's default\n# values unless a test yells at you.\n#\n# Similarly, if you're writing a test that consumes OpInfos then it's critical\n# your test provides a clear error message describing what to do when it\n# fails. You should not assume the OpInfo implementer is familiar with your\n# system.\n#\n# If you see a confusing error message while developing an OpInfo then please\n# file an issue describing what happened.\n#\n# This trial-and-error approach can be frustrating to writing an OpInfo can\n# be frustrating, but it's probably necessary as long as OpInfos don't require\n# learning about all the systems that consume them. One thing that can help\n# is the get_supported_dtypes() function defined in opinfo_helper.py. This\n# function can be used to programmatically specify the dtypes an operator\n# supports, and is especially useful if writing an OpInfo on a machine\n# without a CUDA device. See its documentation for more details.\n#\n# THE FUTURE OF OPINFOS AND OPINFO TESTING\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# In the future we expect OpInfo coverage to improve, particularly for the\n# torch, torch.fft, torch.linalg, and torch.special namespaces, and possibly\n# for the torch.nn.functional namespace, too. In addition an analogous class,\n# ModuleInfo, will be developed to improve module testing.\n#\n# We also expect at least two new OpInfo subclasses: BinaryUfuncInfo and\n# ReductionInfo. Both will have new automated tests for correctness, too,\n# which might make testing binary elementwise operations and reductions as\n# simple as testing unary elementwise operations today.\n\n# Classes and methods for the operator database\nclass OpInfo(object):\n \"\"\"Operator information and helper functions for acquiring it.\"\"\"\n\n def __init__(self,\n name, # the string name of the function\n *,\n ref=None, # An optional reference function that accepts ndarrays (AKA \"NumPy arrays\").\n # If given, the op will be compared with its reference on each of its sample inputs.\n # the following metadata describes the operator, its variants,\n # and its aliases, if any\n aliases=None, # iterable of aliases, e.g. (\"absolute\",) for torch.abs\n variant_test_name='', # additional string to include in the test name\n # this is useful when an op needs multiple OpInfos,\n # like divide does, often because it's really several\n # different ops behind the scenes\n op=None, # the function variant of the operation, populated as torch.<name> if None\n method_variant=_NOTHING, # explicitly specifies the method variant of the operator\n # if _NOTHING (default), the method variant will be autopopulated\n # if None, then the OpInfo specifies no method variant\n inplace_variant=_NOTHING, # explicitly specifies the inplace variant of the operator\n # if _NOTHING (default), the method variant will be autopopulated\n # if None, then the OpInfo specifies no method variant\n\n # the following metadata are test directives for skipping or\n # modifying tests and a pointer to the op's sample inputs function\n # this function lets the OpInfo generate valid inputs\n skips=tuple(), # information about which tests to skip\n decorators=tuple(), # decorators to apply to generated tests\n sample_inputs_func=None, # function to generate sample inputs\n\n # the following metadata relates to dtype support and is tested for correctness in test_ops.py\n dtypes=floating_types(), # dtypes this function is expected to work with\n # the following dtypesIf... options override the dtypes value\n # on their respective device types\n dtypesIfCPU=None, # dtypes this function is expected to work with on CPU\n dtypesIfCUDA=None, # dtypes this function is expected to work with on CUDA\n dtypesIfROCM=None, # dtypes this function is expected to work with on ROCM\n backward_dtypes=None, # backward dtypes this function is expected to work with\n backward_dtypesIfCPU=None, # backward dtypes this function is expected to work with on CPU\n backward_dtypesIfCUDA=None, # backward dtypes this function is expected to work with on CUDA\n backward_dtypesIfROCM=None, # backward dtypes this function is expected to work with on ROCM\n default_test_dtypes=None, # dtypes to test with by default. Tests are instantiated with\n # these dtypes for the op unless otherwise specified.\n # This is helpful in reducing the test matrix.\n # the following metadata describes the operators out= support\n supports_out=True, # whether the op supports the out kwarg\n # defaults to True, if the op does not allow the out kwarg or\n # supports it incorrectly then test_out in test_ops.py should fail\n safe_casts_outputs=False, # whether op allows safe casting when writing to out arguments\n\n # the following metadata relates to autograd support\n supports_autograd=True, # whether the operation supports gradient computations\n # if true, gradient correctness is tested in test_ops.py\n # using the op's sample inputs\n supports_gradgrad=True, # whether the op supports second order gradients\n # if true, gradgrad correctness is tested in test_ops.py\n # (this value is ignored if supports_autograd=False)\n supports_inplace_autograd=None, # whether the operation supports inplace autograd\n # if true, tested in test_ops.py\n # defaults to supports_autograd's value\n supports_forward_ad=False, # Whether the operation support forward mode AD\n # If the value is True, we check that the gradients are correct\n # If the value is False, we test that forward grad is not implemented\n gradcheck_wrapper=lambda op, *args, **kwargs: op(*args, **kwargs), # wrapper function for gradcheck\n check_batched_grad=True, # whether to check batched grad when doing gradcheck\n check_batched_gradgrad=True, # whether to check batched grad grad when doing gradgradcheck\n gradcheck_nondet_tol=0.0, # tolerance for nondeterminism while performing gradcheck\n gradcheck_fast_mode=None, # Whether to use the fast implmentation for gradcheck/gradgradcheck.\n # When set to None, defers to the default value provided by the wrapper\n # function around gradcheck (testing._internal.common_utils.gradcheck)\n\n # the following metadata relates to JIT support and is tested for correctness in test_ops.py\n aten_name=None, # name of the corresponding aten:: operator\n assert_autodiffed=False, # if a op's aten::node is expected to be symbolically autodiffed\n autodiff_nonfusible_nodes=None, # a list of strings with node names that are expected to be in a\n # DifferentiableGraph when autodiffed. Ex: ['aten::add', 'aten::mm'],\n # default is populated to be ['aten::(name of Python operator)']\n autodiff_fusible_nodes=None, # a list of strings with node names that are expected to be in FusionGroups\n # inside of DifferentiableGraphs when this operation is autodiffed.\n # Ex: ['aten::add', 'aten::mm'], defaults to an empty list\n # Note: currently no ops use fusible nodes\n\n # the following metadata relates to sparse support and is used in test_sparse.py\n supports_sparse=False, # whether the op supports sparse inputs\n\n # the following metadata relates to complex support and is checked in test_ops.py\n test_conjugated_samples=True,\n test_neg_view=True,\n assert_jit_shape_analysis=False, # assert that jit shape analysis fully propagates shape\n ):\n\n dtypes_args = (dtypes, dtypesIfCPU, dtypesIfCUDA, dtypesIfROCM)\n # Validates the dtypes are generated from the dispatch-related functions\n for dtype_list in dtypes_args:\n assert isinstance(dtype_list, (_dispatch_dtypes, type(None)))\n\n self.name = name\n self.ref = ref\n self.aten_name = aten_name if aten_name is not None else name\n self.variant_test_name = variant_test_name\n\n # Attribute to verify dynamic_dtypes are used.\n self.dynamic_dtypes = any(map(lambda dtypes: isinstance(\n dtypes, opinfo_helper._dynamic_dispatch_dtypes), dtypes_args))\n\n if self.dynamic_dtypes:\n # Make sure `dtyesIfCUDA` is dynamic, if dynamic dispatch is used for CPU\n # This is because, below we set dtypesIfCUDA to dtypes if they are None.\n assert isinstance(dtypesIfCUDA, opinfo_helper._dynamic_dispatch_dtypes), \\\n (f\"To use dynamic dypes for operator {name}, \"\n \"acquire the dtypes dynamically for argument `dtypesIfCUDA`.\"\n \"This is to ensure that CUDA dtypes are acquired correctly as they\"\n \"differ from CPU dtypes occasionally\")\n\n self.dtypes = set(dtypes)\n\n # NOTE: backward dtypes must be acquired before forward dtypes\n # since they fallback to explicit (not implicit!) specifications of\n # forward dtypes\n self.backward_dtypes = set(backward_dtypes) if backward_dtypes is not None else self.dtypes\n self.backward_dtypesIfCPU = set(backward_dtypesIfCPU) if backward_dtypesIfCPU is not None else (\n backward_dtypes if backward_dtypes is not None\n else dtypesIfCPU if dtypesIfCPU is not None\n else dtypes)\n self.backward_dtypesIfCUDA = set(backward_dtypesIfCUDA) if backward_dtypesIfCUDA is not None else (\n backward_dtypes if backward_dtypes is not None\n else dtypesIfCUDA if dtypesIfCUDA is not None\n else dtypes)\n self.backward_dtypesIfROCM = set(backward_dtypesIfROCM) if backward_dtypesIfROCM is not None else (\n backward_dtypesIfCUDA if backward_dtypesIfCUDA is not None\n else backward_dtypes if backward_dtypes is not None\n else dtypesIfROCM if dtypesIfROCM is not None\n else dtypesIfCUDA if dtypesIfCUDA is not None\n else dtypes)\n\n self.dtypesIfCPU = set(dtypesIfCPU) if dtypesIfCPU is not None else self.dtypes\n self.dtypesIfCUDA = set(dtypesIfCUDA) if dtypesIfCUDA is not None else self.dtypes\n self.dtypesIfROCM = set(dtypesIfROCM) if dtypesIfROCM is not None else self.dtypesIfCUDA\n\n self._default_test_dtypes = set(default_test_dtypes) if default_test_dtypes is not None else None\n\n # NOTE: if the op is unspecified it is assumed to be under the torch namespace\n self.op = op if op else _getattr_qual(torch, self.name)\n method_variant = getattr(torch.Tensor, name, None) if method_variant is _NOTHING else method_variant\n # attributes like real, imag are not callable\n self.method_variant = method_variant if callable(method_variant) else None\n inplace_name = name + \"_\"\n self.inplace_variant = getattr(torch.Tensor, inplace_name, None) \\\n if inplace_variant is _NOTHING else inplace_variant\n self.operator_variant = getattr(operator, name, None)\n\n self.supports_out = supports_out\n self.safe_casts_outputs = safe_casts_outputs\n\n self.decorators = (*decorators, *skips)\n self.sample_inputs_func = sample_inputs_func\n\n self.assert_autodiffed = assert_autodiffed\n self.autodiff_fusible_nodes = autodiff_fusible_nodes if autodiff_fusible_nodes else []\n if autodiff_nonfusible_nodes is None:\n self.autodiff_nonfusible_nodes = ['aten::' + self.name]\n else:\n self.autodiff_nonfusible_nodes = autodiff_nonfusible_nodes\n\n # autograd support\n self.supports_autograd = supports_autograd\n self.supports_inplace_autograd = supports_inplace_autograd\n if self.supports_inplace_autograd is None:\n self.supports_inplace_autograd = supports_autograd\n\n self.gradcheck_wrapper = gradcheck_wrapper\n self.supports_gradgrad = supports_gradgrad\n self.supports_forward_ad = supports_forward_ad\n self.check_batched_grad = check_batched_grad\n self.check_batched_gradgrad = check_batched_gradgrad\n self.gradcheck_nondet_tol = gradcheck_nondet_tol\n self.gradcheck_fast_mode = gradcheck_fast_mode\n\n self.supports_sparse = supports_sparse\n\n self.aliases = ()\n if aliases is not None:\n self.aliases = tuple(AliasInfo(a) for a in aliases) # type: ignore[assignment]\n\n self.assert_jit_shape_analysis = assert_jit_shape_analysis\n\n self.test_conjugated_samples = test_conjugated_samples\n self.test_neg_view = test_neg_view\n\n def __call__(self, *args, **kwargs):\n \"\"\"Calls the function variant of the operator.\"\"\"\n return self.op(*args, **kwargs)\n\n def get_op(self):\n \"\"\"Returns the function variant of the operator, torch.<op_name>.\"\"\"\n return self.op\n\n def get_method(self):\n \"\"\"Returns the method variant of the operator, torch.Tensor.<op_name>.\n Returns None if the operator has no method variant.\n \"\"\"\n return self.method_variant\n\n def get_inplace(self):\n \"\"\"Returns the inplace variant of the operator, torch.Tensor.<op_name>_.\n Returns None if the operator has no inplace variant.\n \"\"\"\n return self.inplace_variant\n\n def get_operator_variant(self):\n \"\"\"Returns operator variant of the operator, e.g. operator.neg\n Returns None if the operator has no operator variant.\n \"\"\"\n return self.operator_variant\n\n def conjugate_sample_inputs(self, device, dtype, requires_grad=False, **kwargs):\n \"\"\"Returns an iterable of SampleInputs but with the tensor input or first\n tensor in a sequence input conjugated.\n \"\"\"\n\n # TODO: Remove the try/except once all operators have sample_inputs_func with\n # **kwargs in their signature.\n try:\n samples = self.sample_inputs_func(self, device, dtype, requires_grad, **kwargs)\n except TypeError:\n samples = self.sample_inputs_func(self, device, dtype, requires_grad)\n\n conj_samples = list(samples)\n\n def conjugate(tensor):\n _requires_grad = tensor.requires_grad\n with torch.no_grad():\n tensor = tensor.conj()\n return tensor.requires_grad_(_requires_grad)\n\n for i in range(len(samples)):\n sample = conj_samples[i]\n # Note: it is assumed that the input here is either a tensor or tensorlist\n if isinstance(sample.input, torch.Tensor):\n sample.input = conjugate(sample.input)\n else:\n with torch.no_grad():\n sample.input[0] = conjugate(sample.input[0])\n\n return tuple(conj_samples)\n\n def sample_inputs(self, device, dtype, requires_grad=False, **kwargs):\n \"\"\"Returns an iterable of SampleInputs.\n\n These samples should be sufficient to test the function works correctly\n with autograd, TorchScript, etc.\n \"\"\"\n\n # TODO: Remove the try/except once all operators have sample_inputs_func with\n # **kwargs in their signature.\n try:\n samples = self.sample_inputs_func(self, device, dtype, requires_grad, **kwargs)\n except TypeError:\n samples = self.sample_inputs_func(self, device, dtype, requires_grad)\n\n if 'include_conjugated_inputs' in kwargs and kwargs.get('include_conjugated_inputs'):\n conj_samples = self.conjugate_sample_inputs(device, dtype, requires_grad, **kwargs)\n samples_list = list(samples)\n samples_list.extend(conj_samples)\n samples = tuple(samples_list)\n\n return samples\n\n def get_decorators(self, test_class, test_name, device, dtype):\n '''Returns the decorators targeting the given test.'''\n result = []\n for decorator in self.decorators:\n if isinstance(decorator, DecorateInfo):\n if decorator.is_active(test_class, test_name, device, dtype):\n result.extend(decorator.decorators)\n else:\n result.append(decorator)\n return result\n\n def supported_dtypes(self, device_type):\n if device_type == 'cpu':\n return self.dtypesIfCPU\n if device_type == 'cuda':\n return self.dtypesIfROCM if TEST_WITH_ROCM else self.dtypesIfCUDA\n else:\n return self.dtypes\n\n def supported_backward_dtypes(self, device_type):\n if not self.supports_autograd:\n return set()\n\n backward_dtypes = None\n if device_type == 'cpu':\n backward_dtypes = self.backward_dtypesIfCPU\n elif device_type == 'cuda':\n backward_dtypes = self.backward_dtypesIfROCM if TEST_WITH_ROCM else self.backward_dtypesIfCUDA\n else:\n backward_dtypes = self.backward_dtypes\n\n allowed_backward_dtypes = floating_and_complex_types_and(torch.bfloat16, torch.float16)\n return set(allowed_backward_dtypes).intersection(backward_dtypes)\n\n def supports_complex_autograd(self, device_type):\n if device_type == 'cpu':\n return any(dtype.is_complex for dtype in self.backward_dtypesIfCPU)\n if device_type == 'cuda':\n if TEST_WITH_ROCM:\n return any(dtype.is_complex for dtype in self.backward_dtypesIfROCM)\n else:\n return any(dtype.is_complex for dtype in self.backward_dtypesIfCUDA)\n else:\n return any(dtype.is_complex for dtype in self.backward_dtypes)\n\n def supports_dtype(self, dtype, device_type):\n return dtype in self.supported_dtypes(device_type)\n\n def default_test_dtypes(self, device_type):\n \"\"\"Returns the default dtypes used to test this operator on the device.\n\n Equal to the operator's default_test_dtypes filtered to remove dtypes\n not supported by the device.\n \"\"\"\n supported = self.supported_dtypes(device_type)\n return (supported if self._default_test_dtypes is None\n else supported.intersection(self._default_test_dtypes))\n\n\nL = 20\nM = 10\nS = 5\n\n\ndef sample_inputs_unary(op_info, device, dtype, requires_grad, **kwargs):\n low, high = op_info.domain\n low = low if low is None else low + op_info._domain_eps\n high = high if high is None else high - op_info._domain_eps\n\n return (SampleInput(make_tensor((L,), device=device, dtype=dtype,\n low=low, high=high,\n requires_grad=requires_grad)),\n SampleInput(make_tensor((), device=device, dtype=dtype,\n low=low, high=high,\n requires_grad=requires_grad)))\n\n# Metadata class for unary \"universal functions (ufuncs)\" that accept a single\n# tensor and have common properties like:\nclass UnaryUfuncInfo(OpInfo):\n \"\"\"Operator information for 'universal unary functions (unary ufuncs).'\n These are functions of a single tensor with common properties like:\n - they are elementwise functions\n - the input shape is the output shape\n - they typically have method and inplace variants\n - they typically support the out kwarg\n - they typically have NumPy or SciPy references\n See NumPy's universal function documentation\n (https://numpy.org/doc/1.18/reference/ufuncs.html) for more details\n about the concept of ufuncs.\n \"\"\"\n\n def __init__(self,\n name, # the string name of the function\n *,\n ref, # a reference function\n dtypes=floating_types(),\n dtypesIfCPU=None,\n dtypesIfCUDA=None,\n dtypesIfROCM=None,\n default_test_dtypes=(\n torch.uint8, torch.long, torch.half, torch.bfloat16,\n torch.float32, torch.cfloat), # dtypes which tests check by default\n domain=(None, None), # the [low, high) domain of the function\n handles_large_floats=True, # whether the op correctly handles large float values (like 1e20)\n handles_extremals=True, # whether the op correctly handles extremal values (like inf)\n handles_complex_extremals=True, # whether the op correct handles complex extremals (like inf -infj)\n supports_complex_to_float=False, # op supports casting from complex input to real output safely eg. angle\n sample_inputs_func=sample_inputs_unary,\n sample_kwargs=lambda device, dtype, input: ({}, {}),\n supports_sparse=False,\n **kwargs):\n super(UnaryUfuncInfo, self).__init__(name,\n dtypes=dtypes,\n dtypesIfCPU=dtypesIfCPU,\n dtypesIfCUDA=dtypesIfCUDA,\n dtypesIfROCM=dtypesIfROCM,\n default_test_dtypes=default_test_dtypes,\n sample_inputs_func=sample_inputs_func,\n supports_sparse=supports_sparse,\n **kwargs)\n self.ref = ref\n self.domain = domain\n self.handles_large_floats = handles_large_floats\n self.handles_extremals = handles_extremals\n self.handles_complex_extremals = handles_complex_extremals\n self.supports_complex_to_float = supports_complex_to_float\n\n # test_unary_ufuncs.py generates its own inputs to test the consistency\n # of the operator on sliced tensors, non-contig tensors, etc.\n # `sample_kwargs` is a utility function to provide kwargs\n # along with those inputs if required (eg. clamp).\n # It should return two dictionaries, first holding kwarg for\n # torch operator and second one for reference NumPy operator.\n self.sample_kwargs = sample_kwargs\n\n # Epsilon to ensure grad and gradgrad checks don't test values\n # outside a function's domain.\n self._domain_eps = 1e-5\n\ndef sample_inputs_tensor_split(op_info, device, dtype, requires_grad, **kwargs):\n make_input = partial(make_tensor, device=device, dtype=dtype,\n low=None, high=None, requires_grad=requires_grad)\n\n args_cases = (\n # Cases with tensor indices.\n (torch.tensor([1, 2, 3]),),\n (torch.tensor(1),),\n (torch.tensor([1, 2, 3]), 1),\n # Cases with list of indices.\n ((2, 4),),\n ((2, 4), 1),\n ((2, 4), -1),\n # Cases with integer section.\n (3,),\n (3, 1),\n (3, -1),\n )\n\n def generator():\n for args in args_cases:\n yield SampleInput(make_input((S, S, S)), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_linalg_det(op_info, device, dtype, requires_grad):\n kw = dict(device=device, dtype=dtype)\n inputs = [\n make_tensor((S, S), **kw),\n make_tensor((1, 1), **kw), # 1x1\n random_symmetric_matrix(S, **kw), # symmetric\n random_symmetric_psd_matrix(S, **kw), # symmetric_psd\n random_symmetric_pd_matrix(S, **kw), # symmetric_pd\n\n random_square_matrix_of_rank(S, S - 2, **kw), # dim2_null\n random_square_matrix_of_rank(S, 1, **kw), # rank1\n random_square_matrix_of_rank(S, 2, **kw), # rank2\n\n random_fullrank_matrix_distinct_singular_value(S, **kw), # distinct_singular_value\n make_tensor((3, 3, S, S), **kw), # batched\n make_tensor((3, 3, 1, 1), **kw), # batched_1x1\n random_symmetric_matrix(S, 3, **kw), # batched_symmetric\n random_symmetric_psd_matrix(S, 3, **kw), # batched_symmetric_psd\n random_symmetric_pd_matrix(S, 3, **kw), # batched_symmetric_pd\n random_fullrank_matrix_distinct_singular_value(S, 3, 3, **kw), # batched_distinct_singular_values\n make_tensor((0, 0), **kw),\n make_tensor((0, S, S), **kw),\n ]\n for t in inputs:\n t.requires_grad = requires_grad\n return [SampleInput(t) for t in inputs]\n\ndef sample_inputs_linalg_det_singular(op_info, device, dtype, requires_grad):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n def make_singular_matrix_batch_base(size, rank):\n assert size[-1] == size[-2]\n assert rank > 0 and rank <= size[-1]\n\n with torch.no_grad():\n n = size[-1]\n a = make_arg(size[:-2] + (n, rank)) / 10\n b = make_arg(size[:-2] + (rank, n)) / 10\n\n x = a @ b\n lu, pivs = x.lu()\n p, l, u = torch.lu_unpack(lu, pivs)\n u_diag_abs = u.diagonal(0, -2, -1).abs()\n u_diag_abs_largest = u_diag_abs.max(dim=-1, keepdim=True).values\n u_diag_abs_smallest_idxs = torch.topk(u_diag_abs, k=(n - rank), largest=False).indices\n u.diagonal(0, -2, -1).div_(u_diag_abs_largest)\n u.diagonal(0, -2, -1)[..., u_diag_abs_smallest_idxs] = torch.finfo(dtype).eps\n\n matrix = p @ l @ u\n\n assert (matrix.det().abs() < torch.finfo(dtype).eps * torch.linalg.matrix_norm(matrix)).all().item()\n\n matrix.requires_grad_(requires_grad)\n return matrix\n\n def sample_generator():\n for batch, size in product(((), (2,), (2, 2)), range(6)):\n shape = batch + (size, size)\n for rank in range(1, size):\n yield make_singular_matrix_batch_base(shape, rank)\n\n return [SampleInput(t) for t in sample_generator()]\n\n\ndef sample_inputs_linalg_matrix_power(op_info, device, dtype, requires_grad):\n # (<matrix_size>, (<batch_sizes, ...>))\n test_sizes = [\n (1, ()),\n (2, (0,)),\n (2, (2,)),\n ]\n\n inputs = []\n for matrix_size, batch_sizes in test_sizes:\n size = batch_sizes + (matrix_size, matrix_size)\n for n in (0, 3, 5):\n t = make_tensor(size, device, dtype, requires_grad=requires_grad)\n inputs.append(SampleInput(t, args=(n,)))\n for n in [-4, -2, -1]:\n t = random_fullrank_matrix_distinct_singular_value(matrix_size, *batch_sizes, device=device, dtype=dtype)\n t.requires_grad = requires_grad\n inputs.append(SampleInput(t, args=(n,)))\n\n return inputs\n\ndef sample_inputs_hsplit(op_info, device, dtype, requires_grad):\n return (SampleInput(make_tensor((6,), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(2,),),\n SampleInput(make_tensor((S, S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=([1, 2, 3],),),)\n\ndef sample_inputs_vsplit(op_info, device, dtype, requires_grad):\n return (SampleInput(make_tensor((6, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(2,),),\n SampleInput(make_tensor((S, S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=([1, 2, 3],),),)\n\ndef sample_inputs_dsplit(op_info, device, dtype, requires_grad):\n return (SampleInput(make_tensor((S, S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=([1, 2, 3],),),\n SampleInput(make_tensor((S, S, 6), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(2,),),)\n\ndef sample_inputs_linalg_multi_dot(op_info, device, dtype, requires_grad):\n # Each test case consists of the sizes in the chain of multiplications\n # e.g. [2, 3, 4, 5] generates matrices (2, 3) @ (3, 4) @ (4, 5)\n test_cases = [\n [1, 2, 1],\n [2, 0, 2],\n [0, 2, 2],\n [2, 2, 2, 2],\n [2, 3, 4, 5],\n [5, 4, 0, 2],\n [2, 4, 3, 5, 3, 2]\n ]\n\n result = []\n for sizes in test_cases:\n tensors = []\n for size in zip(sizes[:-1], sizes[1:]):\n t = make_tensor(size, device, dtype, requires_grad=requires_grad)\n tensors.append(t)\n result.append(SampleInput(tensors))\n\n return result\n\ndef sample_inputs_linalg_matrix_norm(op_info, device, dtype, requires_grad, **kwargs):\n sizes = ((2, 2), (2, 3, 2))\n ords = ('fro', 'nuc', inf, -inf, 1, -1, 2, -2)\n dims = ((-2, -1), (-1, 0))\n\n inputs: List[SampleInput] = []\n for size, ord, dim, keepdim in product(sizes, ords, dims, [True, False]):\n t = make_tensor(size, device, dtype, requires_grad=requires_grad)\n inputs.append(SampleInput(t, args=(ord, dim, keepdim)))\n\n return inputs\n\ndef sample_inputs_linalg_norm(op_info, device, dtype, requires_grad):\n test_sizes = [\n (S,),\n (0,),\n (S, S),\n (0, 0),\n (S, 0),\n (0, S),\n (S, S, S),\n (0, S, S),\n (S, 0, S),\n (0, 0, 0),\n ]\n\n vector_ords = (None, 0, 0.5, 1, 2, 3.5, inf, -0.5, -1, -2, -3.5, -inf)\n matrix_ords = (None, 'fro', 'nuc', 1, 2, inf, -1, -2, -inf)\n\n inputs = []\n\n for test_size in test_sizes:\n is_vector_norm = len(test_size) == 1\n is_matrix_norm = len(test_size) == 2\n\n for keepdim in [False, True]:\n inputs.append(SampleInput(\n make_tensor(\n test_size, device, dtype, low=None, high=None,\n requires_grad=requires_grad),\n kwargs=dict(\n keepdim=keepdim)))\n\n if not (is_vector_norm or is_matrix_norm):\n continue\n\n ords = vector_ords if is_vector_norm else matrix_ords\n\n for ord in ords:\n\n inputs.append(SampleInput(\n make_tensor(\n test_size, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(ord,),\n kwargs=dict(\n keepdim=keepdim)))\n\n if ord in ['nuc', 'fro']:\n inputs.append(SampleInput(\n make_tensor(\n test_size, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n kwargs=dict(\n ord=ord,\n keepdim=keepdim,\n dim=(0, 1))))\n return inputs\n\n\ndef sample_inputs_nn_activation_relu(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = (\n (()),\n ((S, )),\n ((S, S)),\n ((S, M, S))\n )\n\n def generator():\n for shape in cases:\n yield SampleInput(make_arg(shape))\n\n return list(generator())\n\ndef sample_inputs_norm(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = (\n ((S, S), (2,), '2'),\n ((S, S), (0,), '0'),\n ((S, S), (0.5,), '0_5'),\n ((S, S), (1,), '1'),\n ((S, S), (3,), '3'),\n ((S, S), (-1,), 'neg_1'),\n ((S, S), (-2,), 'neg_2'),\n ((S, S), (-0.5,), 'neg_0_5'),\n ((S, S), (-1.5,), 'neg_1_5'),\n )\n\n cases_nonzero_input = (\n ((S, S, S), (1.5,), '1_5_default'),\n ((S, S, S), (1.5, 1), '1_5_dim'),\n ((S, S, S), (1.5, -1), '1_5_neg_dim'),\n ((S, S, S), (1.5, 1, True), 'keepdim_1_5_dim'),\n ((S, S, S), (1.5, -1, True), 'keepdim_1_5_neg_dim'),\n )\n\n cases_negdim_base = (\n ((S, S), (-2, 1,), 'neg_2_2_dim'),\n ((S, S), (-1, 1,), 'neg_1_2_dim'),\n ((S, S), (0, 1,), '0_2_dim'),\n ((S, S), (1, 1,), '1_2_dim'),\n ((S, S), (2, 1,), '2_2_dim'),\n ((S, S), (3, 1,), '3_2_dim'),\n ((S, S, S), (2, 1), '2_dim'),\n ((S, S, S), (3, 1), '3_dim'),\n ((S, S, S), (2, 1, True), 'keepdim_2_dim'),\n ((S, S, S), (3, 1, True), 'keepdim_3_dim'),\n ((), (2, 0), '2_dim_scalar'),\n ((), (3, 0), '3_dim_scalar'),\n ((), (2, 0, True), 'keepdim_2_dim_scalar'),\n ((), (3, 0, True), 'keepdim_3_dim_scalar'),\n )\n\n cases_negdim = []\n for case in cases_negdim_base:\n cases_negdim.append(case)\n shape, args, name = case\n new_args = copy.deepcopy(list(args))\n new_args[1] *= -1\n cases_negdim.append((shape, tuple(new_args), name.replace(\"_dim\", \"_neg_dim\")))\n\n def generator():\n for shape, args, name in itertools.chain(cases, cases_negdim):\n yield SampleInput(make_arg(shape), args=args, name=name)\n\n for shape, args, name in cases_nonzero_input:\n yield SampleInput(make_arg(shape, exclude_zero=True), args=args, name=name)\n\n return list(generator())\n\n\ndef sample_inputs_norm_fro(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = (\n ((S, S), (), 'default'),\n ((S, S), ('fro',), 'fro_default'),\n ((S, S), ('fro', [0, 1],), 'fro'),\n )\n\n def generator():\n for shape, args, name in cases:\n yield SampleInput(make_arg(shape), args=args, name=name)\n\n return list(generator())\n\n\ndef sample_inputs_norm_nuc(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = (\n ((S, S), ('nuc',), 'nuc'),\n ((S, S, S), ('nuc', [1, 2]), 'nuc_batched'),\n )\n\n def generator():\n for shape, args, name in cases:\n yield SampleInput(make_arg(shape), args=args, name=name)\n\n return list(generator())\n\n\ndef sample_inputs_norm_inf(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = (\n ((S, S), (-inf,), '-inf'),\n ((S, S), (inf,), 'inf'),\n ((S, S), (inf, 1,), 'inf_2_dim'),\n ((S, S), (inf, -1,), 'inf_2_neg_dim'),\n )\n\n def generator():\n for shape, args, name in cases:\n yield SampleInput(make_arg(shape), args=args, name=name)\n\n return list(generator())\n\n\ndef sample_inputs_linalg_vector_norm(op_info, device, dtype, requires_grad, **kwargs):\n size_1D = (S,)\n size_2D = (2, 2)\n\n test_cases = [\n # input size, ord, dim args\n (size_1D, 2, None),\n (size_1D, 2, (0,)),\n (size_1D, 0, None),\n (size_1D, 0, (0,)),\n (size_1D, 0.9, None),\n (size_1D, 0.9, (0,)),\n (size_1D, 1, None),\n (size_1D, 1, (0,)),\n (size_1D, -2.1, None),\n (size_1D, -2.1, (0,)),\n (size_1D, inf, None),\n (size_1D, inf, (0,)),\n (size_1D, -inf, None),\n (size_1D, -inf, (0,)),\n\n (size_2D, 2, None),\n (size_2D, 2, (0,)),\n (size_2D, 2, (-1, 0)),\n (size_2D, 0, None),\n (size_2D, 0, (0,)),\n (size_2D, 0, (-1, 0)),\n (size_2D, 0.9, None),\n (size_2D, 0.9, (0,)),\n (size_2D, 0.9, (-1, 0)),\n (size_2D, 1, None),\n (size_2D, 1, (0,)),\n (size_2D, 1, (-1, 0)),\n (size_2D, -2.1, None),\n (size_2D, -2.1, (0,)),\n (size_2D, -2.1, (-1, 0)),\n (size_2D, inf, None),\n (size_2D, inf, (0,)),\n (size_2D, inf, (-1, 0)),\n (size_2D, -inf, None),\n (size_2D, -inf, (0,)),\n (size_2D, -inf, (-1, 0)),\n ]\n inputs = []\n\n for test_size, ord, dim in test_cases:\n for keepdim in [False, True]:\n inputs.append(SampleInput(\n make_tensor(\n test_size, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(ord,),\n kwargs=dict(\n keepdim=keepdim,\n dim=dim)))\n\n return inputs\n\n# In order to use the kwarg alpha, partials should be used in an OpInfo's sample_inputs_func\n# eg. sample_inputs_func=partial(sample_inputs_binary_pwise, alpha=2)\n# Then one sample input would also be generated corresponding to the value of alpha provided.\n# In the future, kwargs 'alpha_floating', 'alpha_integral' & 'alpha_complex' can be used to\n# specify scalars of floating, integral & complex types as values for \"alpha\".\n# Keyword argument `rhs_exclude_zero` is used to exclude zero values from rhs tensor argument\n# This is necessary for operations like `true_divide`, where divide by zero throws an exception.\ndef sample_inputs_binary_pwise(op_info, device, dtype, requires_grad, extra_kwargs=None, **kwargs):\n if extra_kwargs is None:\n extra_kwargs = {}\n\n scalar = 3.14 + 3.14j if dtype.is_complex else (3.14 if dtype.is_floating_point else 3)\n scalar = 1 if dtype is torch.bool else scalar\n tests_list = [\n ((S, S, S), (S, S, S), False),\n ((S, S, S), (S, S), False),\n ((), (), False),\n ((S, S, S), (), False),\n ((S, S, S), scalar, False),\n ((), scalar, False)\n ]\n tests_with_lhs_broadcasting = [\n ((S, S), (S, S, S), True),\n ((), (S, S, S), True),\n ((S, 1, S), (M, S), True),\n ]\n test_cases = tests_list + tests_with_lhs_broadcasting # type: ignore[operator]\n samples = []\n for first_shape, shape_or_scalar, broadcasts_input in test_cases:\n arg = shape_or_scalar\n\n if isinstance(shape_or_scalar, tuple):\n exclude_zero = kwargs.get('rhs_exclude_zero', False)\n arg = make_tensor(shape_or_scalar, device=device, dtype=dtype,\n requires_grad=requires_grad, exclude_zero=exclude_zero)\n samples.append(SampleInput(make_tensor(first_shape, device=device, dtype=dtype,\n requires_grad=requires_grad),\n args=(arg,), kwargs=extra_kwargs,\n broadcasts_input=broadcasts_input))\n # Adds an extra sample using \"alpha\" if it's passed in kwargs\n if 'alpha' in kwargs:\n a = make_tensor((S, S, S), device=device, dtype=dtype, requires_grad=requires_grad)\n b = make_tensor((S, S, S), device=device, dtype=dtype, requires_grad=requires_grad)\n extra_kwargs['alpha'] = kwargs['alpha']\n sample = SampleInput(a, args=(b,), kwargs=extra_kwargs)\n samples.append(sample)\n return tuple(samples)\n\n\ndef sample_inputs_t(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n return (SampleInput(make_arg((1, 2))),\n SampleInput(make_arg((2,))),\n SampleInput(make_arg(())))\n\n\ndef sample_inputs_mm(op_info, device, dtype, requires_grad, **kwargs):\n args_list = (\n ((S, M), (M, S)),\n )\n inputs = tuple(SampleInput(make_tensor(first_shape, device, dtype,\n requires_grad=requires_grad),\n args=(make_tensor(second_shape, device, dtype,\n requires_grad=requires_grad),))\n for first_shape, second_shape in args_list)\n return inputs\n\ndef sample_inputs_addmm(op_info, device, dtype, requires_grad, **kwargs):\n alpha_val = kwargs.get('alpha', 2 + 3j if dtype.is_complex else 0.6)\n beta_val = kwargs.get('beta', 1 + 2j if dtype.is_complex else 0.2)\n tests_list = [\n ((2, 3), (2, 2), (2, 3), False)\n ]\n tests_with_lhs_broadcasting = [\n ((1,), (2, 2), (2, 3), True),\n ((), (2, 2), (2, 3), True)\n ]\n test_cases = tests_list + tests_with_lhs_broadcasting # type: ignore[operator]\n inputs = tuple(SampleInput(make_tensor(shape_a, device, dtype, requires_grad=requires_grad),\n args=(make_tensor(shape_b, device, dtype,\n requires_grad=requires_grad),\n make_tensor(shape_c, device, dtype,\n requires_grad=requires_grad)),\n kwargs={'alpha': alpha_val, 'beta': beta_val},\n broadcasts_input=broadcasts_input)\n for shape_a, shape_b, shape_c, broadcasts_input in test_cases)\n return inputs\n\ndef sample_inputs_mv(self, device, dtype, requires_grad, **kwargs):\n return (\n SampleInput(\n make_tensor((S, M, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((M, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n )\n ),\n )\n\ndef sample_inputs_bmm(self, device, dtype, requires_grad, **kwargs):\n return (\n SampleInput(\n make_tensor((M, S, M, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((M, M, S, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n )\n ),\n )\n\ndef sample_inputs_dot_vdot(self, device, dtype, requires_grad, **kwargs):\n return (\n SampleInput(\n make_tensor((S, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((S, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n )\n ),\n )\n\ndef sample_inputs_addmv(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n test_cases = (((S,), (S, M), (M,), 1, 1, False),\n ((S,), (S, M), (M,), 0.2, 0.6, False),\n )\n\n test_cases_with_broadcast = (((1,), (S, M), (M,), 1, 1, True),\n ((1,), (S, M), (M,), 0.2, 0.6, True),\n ((), (S, M), (M,), 1, 1, True),\n ((), (S, M), (M,), 0.2, 0.6, True),\n )\n\n cases = test_cases + test_cases_with_broadcast\n\n def generator():\n # addmv performs: beta * M + alpha * (mat @ vec)\n for M, mat, vec, beta, alpha, broadcasts_input in cases:\n yield SampleInput(make_arg(M), args=(make_arg(mat), make_arg(vec)),\n kwargs=dict(beta=beta, alpha=alpha), broadcasts_input=broadcasts_input)\n\n return list(generator())\n\ndef sample_inputs_addbmm(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n # input_shape, batch1_shape, batch2_shape, beta_val, alpha_val, is_broadcasting\n test_cases = [((S, M), (S, S, S), (S, S, M), 1, 1, False),\n ((1,), (S, S, S), (S, S, M), 1, 1, True),\n ((S, M), (S, S, S), (S, S, M), 0.6, 0.2, False),\n ((1,), (S, S, S), (S, S, M), 0.6, 0.2, True),\n ((), (S, S, S), (S, S, M), 1, 1, True),\n ((), (S, S, S), (S, S, M), 0.6, 0.2, True),\n ]\n\n def generator():\n for input_shape, batch1_shape, batch2_shape, beta, alpha, is_broadcasting in test_cases:\n if dtype.is_complex:\n beta_complex, alpha_complex = beta * (1 + 2j), alpha * (2 + 3j)\n yield SampleInput(make_arg(input_shape), args=(make_arg(batch1_shape), make_arg(batch2_shape)),\n kwargs=dict(beta=beta_complex, alpha=alpha_complex), broadcasts_input=is_broadcasting)\n yield SampleInput(make_arg(input_shape), args=(make_arg(batch1_shape), make_arg(batch2_shape)),\n kwargs=dict(beta=beta, alpha=alpha), broadcasts_input=is_broadcasting)\n\n return list(generator())\n\ndef sample_inputs_addcmul_addcdiv(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = [(((S, S), (S, S), (S, S)), False),\n (((S, S), (S, 1), (1, S)), False),\n (((1,), (S, S, 1), (1, S)), True),\n (((), (), ()), False),\n (((S, S), (), ()), True),\n (((), (S, S, 1), (1, S)), True)\n ]\n\n sample_inputs = []\n for input_args, broadcasts_input in test_cases:\n args = tuple(make_tensor(arg, device, dtype, requires_grad=requires_grad) if isinstance(arg, tuple) else arg\n for arg in input_args)\n sample_inputs.append(SampleInput(args[0], args=args[1:], broadcasts_input=broadcasts_input))\n\n sample_inputs.append(SampleInput(args[0], args=args[1:], kwargs=dict(value=3.14), broadcasts_input=broadcasts_input))\n\n return tuple(sample_inputs)\n\ndef sample_inputs_baddbmm(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = [((S, S, M), (S, S, S), (S, S, M), 1, 1, False),\n ((1,), (S, S, S), (S, S, M), 1, 1, True),\n ((S, S, M), (S, S, S), (S, S, M), 0.6, 0.2, False),\n ((1,), (S, S, S), (S, S, M), 0.6, 0.2, True),\n ((), (S, S, S), (S, S, M), 1, 1, True),\n ((), (S, S, S), (S, S, M), 0.6, 0.2, True),\n ]\n sample_inputs = []\n for (input_shape, batch1_shape, batch2_shape, alpha, beta, broadcasts_input) in test_cases:\n args = (make_tensor(input_shape, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n make_tensor(batch1_shape, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n make_tensor(batch2_shape, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad))\n sample_inputs.append(SampleInput(args[0], args=(args[1], args[2]),\n kwargs=dict(beta=beta, alpha=alpha), broadcasts_input=broadcasts_input))\n if dtype.is_complex:\n sample_inputs.append(SampleInput(args[0], args=(args[1], args[2]),\n kwargs=dict(beta=beta * (1 + 2j), alpha=alpha * (2 + 3j)),\n broadcasts_input=broadcasts_input))\n return tuple(sample_inputs)\n\ndef sample_inputs_addr(op_info, device, dtype, requires_grad, **kwargs):\n input1 = SampleInput(\n make_tensor((S, M), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((S, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((M, ), device, dtype, low=None, high=None, requires_grad=requires_grad)))\n\n input2 = SampleInput(\n make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((S, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((M, ), device, dtype, low=None, high=None, requires_grad=requires_grad)),\n broadcasts_input=True)\n\n if dtype.is_complex:\n alpha, beta = 0.1 + 0.3j, 0.4 + 0.6j\n elif dtype.is_floating_point:\n alpha, beta = 0.2, 0.6\n else:\n alpha, beta = 2, 3\n\n input3 = SampleInput(\n make_tensor((S, M), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((S, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((M, ), device, dtype, low=None, high=None, requires_grad=requires_grad)),\n kwargs=dict(beta=beta, alpha=alpha))\n\n input4 = SampleInput(\n make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((S, ), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((M, ), device, dtype, low=None, high=None, requires_grad=requires_grad)),\n kwargs=dict(beta=beta, alpha=alpha),\n broadcasts_input=True)\n\n return (input1, input2, input3, input4)\n\ndef sample_inputs_xlogy(self, device, dtype, requires_grad, **kwargs):\n return (\n SampleInput(\n make_tensor((S, S), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n make_tensor((S, S), device, dtype, low=0, high=None, requires_grad=requires_grad),\n )\n ),\n )\n\n\ndef sample_inputs_xlog1py(self, device, dtype, requires_grad):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n def generator():\n # same shape\n yield SampleInput(make_arg((S, S)), args=(make_arg((S, S), low=-1),))\n # rhs broadcast\n yield SampleInput(make_arg((S, S)), args=(make_arg((S,), low=-1),))\n # all zero `x`\n with torch.no_grad():\n x = make_arg((S, S))\n x.fill_(0)\n yield SampleInput(x, args=(make_arg((S, S), low=-1),))\n\n # randomly zero-masked `x`\n x = make_arg((S, S))\n y = make_arg((S, S), low=-1)\n with torch.no_grad():\n x[torch.rand(x.shape) > 0.5] = 0\n yield SampleInput(x, args=(y,))\n\n # Scalar x\n # `input` has to be a tensor\n # yield SampleInput(0, args=(make_arg((S, S), low=-1),))\n # yield SampleInput(2.1, args=(make_arg((S, S), low=-1),))\n\n # Scalar y\n yield SampleInput(make_arg((S, S)), args=(-0.5,))\n yield SampleInput(make_arg((S, S)), args=(1.2,))\n\n return list(generator())\n\ndef sample_inputs_zero_(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = ((), (S, S, S), (S,))\n\n def generator():\n for shape in cases:\n yield(SampleInput(make_arg(shape)))\n\n return list(generator())\n\n\ndef sample_inputs_logsumexp(self, device, dtype, requires_grad):\n inputs = (\n ((), (0,), True),\n ((S, S), (1,), True),\n ((S, S), (1,), False)\n )\n samples = []\n\n for shape, dim, keepdim in inputs:\n t = make_tensor(shape, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad)\n samples.append(SampleInput(t, args=(dim, keepdim)))\n\n return tuple(samples)\n\ndef sample_inputs_logcumsumexp(self, device, dtype, requires_grad):\n inputs = (\n ((S, S, S), 0),\n ((S, S, S), 1),\n ((), 0),\n )\n samples = []\n\n for shape, dim in inputs:\n t = make_tensor(shape, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad)\n samples.append(SampleInput(t, args=(dim,)))\n\n return tuple(samples)\n\ndef sample_inputs_trace(self, device, dtype, requires_grad, **kwargs):\n return (SampleInput((make_tensor((S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad))),)\n\n\ndef sample_inputs_renorm(self, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n cases = (((S, S, S), (2, 1, 0.5)),\n ((S, S, S), (2, -1, 0.5)),\n ((S, S, S), (1, 2, 3)),\n ((S, S, S), (float('inf'), 2, 0.5)),\n )\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_transpose_swapdims(self, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n cases = (((1, 2, 3), (-1, -2)),\n ((1, 2, 3), (-1, 2)),\n ((1, 2, 3), (1, -2)),\n ((1, 2, 3), (1, 2)),\n ((), (0, 0)),\n ((1, ), (0, 0)),\n ((M, M), (0, 1)),\n ((S, S, S), (2, 0)), )\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad=False, **kwargs):\n \"\"\"\n This function generates always invertible input for linear algebra ops using\n random_fullrank_matrix_distinct_singular_value.\n The input is generated as the itertools.product of 'batches' and 'ns'.\n In total this function generates 8 SampleInputs\n 'batches' cases include:\n () - single input,\n (0,) - zero batched dimension,\n (2,) - batch of two matrices,\n (1, 1) - 1x1 batch of matrices\n 'ns' gives 0x0 and 5x5 matrices.\n Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.\n \"\"\"\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n batches = [(), (0, ), (2, ), (1, 1)]\n ns = [5, 0]\n out = []\n for batch, n in product(batches, ns):\n a = random_fullrank_matrix_distinct_singular_value(n, *batch, dtype=dtype, device=device)\n a.requires_grad = requires_grad\n out.append(SampleInput(a))\n return out\n\ndef sample_inputs_linalg_cond(op_info, device, dtype, requires_grad=False, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n # autograd is not supported for inputs with zero number of elements\n shapes = ((S, S),\n (2, S, S),\n (2, 1, S, S), )\n\n def generator():\n for shape in shapes:\n yield SampleInput(make_arg(shape))\n\n return list(generator())\n\ndef np_sinc_with_fp16_as_fp32(x):\n # Wraps numpy's sinc function so that fp16 values are promoted to fp32\n # before sinc is invoked. Context: numpy's sinc returns NaN when evaluated\n # at 0 for fp16.\n if x.dtype == np.float16:\n return np.sinc(x.astype(np.float32))\n else:\n return np.sinc(x)\n\ndef sample_inputs_broadcast_to(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = (\n ((S, 1, 1), (S, S, S)),\n ((S, 1, S), (S, S, S)),\n ((S, 1), (S, S, S)),\n ((1,), (S, S, S)),\n ((1, S), (1, 1, S)),\n ((), ()),\n ((), (1, 3, 2)),\n )\n\n return tuple(\n SampleInput(\n make_tensor(size, device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(shape,)) for size, shape in test_cases)\n\ndef sample_inputs_bitwise_shift(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = (\n (S, S, S),\n (S,),\n (),\n )\n\n sample_inputs = []\n for size in test_cases:\n tensor1 = make_tensor(size, device, dtype, low=-32, high=32, requires_grad=requires_grad)\n tensor2 = make_tensor(size, device, dtype, low=0, high=5, requires_grad=requires_grad)\n sample_inputs.append(SampleInput(tensor1, args=(tensor2,)))\n sample_inputs.append(SampleInput(tensor1, args=(2,)))\n\n return tuple(sample_inputs)\n\n\ndef sample_inputs_cdist(op_info, device, dtype, requires_grad, **kwargs):\n small_S = 2\n test_cases = (\n ((S, S, 2), (S, S + 1, 2)),\n ((S, S), (S, S)),\n ((S, S, S), (S, S, S)),\n ((3, 5), (3, 5)),\n ((2, 3, 5), (2, 3, 5)),\n ((1, 2, 3), (1, 2, 3)),\n ((1, 1), (S, 1)),\n ((0, 5), (4, 5)),\n ((4, 5), (0, 5)),\n ((0, 4, 5), (3, 5)),\n ((4, 5), (0, 3, 5)),\n ((0, 4, 5), (1, 3, 5)),\n ((1, 4, 5), (0, 3, 5)),\n # Using S here would make this one test take 9s\n ((small_S, small_S, small_S + 1, 2), (small_S, small_S, small_S + 2, 2)),\n ((small_S, 1, 1, small_S), (1, small_S, small_S)),\n ((1, 1, small_S), (small_S, 1, small_S, small_S)),\n )\n\n samples = []\n for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']:\n # FIXME add an override for JIT and revert 0. back to 0\n # since it's accepted by eager\n for p in [0., 1., 2., 3., 0.5, 1.5, 2.5, float(\"inf\")]:\n for t1_size, t2_size in test_cases:\n # The args should never be non-contiguous as this is not supported in the backward\n samples.append(SampleInput(\n make_tensor(t1_size, device, dtype, requires_grad=requires_grad, noncontiguous=False),\n args=(make_tensor(t2_size, device, dtype, requires_grad=requires_grad, noncontiguous=False), p, cm)))\n\n return samples\n\n\ndef sample_inputs_fill_(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype,\n low=None, high=None, requires_grad=requires_grad)\n\n cases = (((S, S, S), (1,)),\n ((), (1,)),\n # For requires_grad=False below,\n # check https://github.com/pytorch/pytorch/issues/59137\n ((S, S, S), (make_arg((), requires_grad=False),)))\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_comparison_ops(self, device, dtype, requires_grad, **kwargs):\n test_cases = (\n ((S, S, S), (S, S, S), False),\n ((S, S, S), (), False),\n ((S, S, S), (1,), False),\n ((S,), (1,), False),\n ((), (), False),\n )\n test_cases_lhs_broadcasting = (\n ((S, 1, S), (S, S, S), True),\n ((1,), (S, S, S), True),\n ((1, S), (1, 1, S), True),\n ((), (0,), True),\n ((), (S, S, S), True),\n )\n cases = test_cases + test_cases_lhs_broadcasting\n sample_inputs = list(SampleInput(make_tensor(first_shape, device, dtype,\n requires_grad=requires_grad),\n args=(make_tensor(second_shape, device, dtype,\n requires_grad=requires_grad),),\n broadcasts_input=broadcasts_input)\n for first_shape, second_shape, broadcasts_input in cases)\n equal_tensors_non_bool = (\n ([[[-8, 6], [9, 0]], [[0, 5], [5, 7]]]),\n ([[[6, 5]], [[1, -5]]]),\n ([[2], [-1]]),\n ([0, -6]),\n ([3],),\n )\n equal_tensors_bool = (\n ([[[1, 0], [0, 0]], [[0, 1], [1, 0]]]),\n ([[[1, 1]], [[1, 0]]]),\n ([[1], [0]]),\n ([0, 1]),\n ([1],),\n )\n more_cases = equal_tensors_bool if dtype is torch.bool else equal_tensors_non_bool\n more_inputs = list(SampleInput(torch.tensor(elements, device=device, dtype=dtype,\n requires_grad=requires_grad),\n args=(torch.tensor(elements, device=device, dtype=dtype,\n requires_grad=requires_grad),))\n for elements in more_cases)\n sample_inputs = [*sample_inputs, *more_inputs]\n return tuple(sample_inputs)\n\n\ndef sample_inputs_stack(op_info, device, dtype, requires_grad, **kwargs):\n tensors = [\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n ]\n\n return (SampleInput(tensors, args=(0,)),)\n\ndef sample_inputs_hstack_dstack_vstack(op_info, device, dtype, requires_grad, **kwargs):\n tensors = [\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n ]\n\n return (SampleInput(tensors),)\n\ndef sample_inputs_hypot(op_info, device, dtype, requires_grad):\n input = make_tensor((S, S), device, dtype, requires_grad=requires_grad)\n args = make_tensor((S, S), device, dtype, requires_grad=requires_grad)\n\n return (\n SampleInput(input, args=(args,)),\n )\n\ndef sample_inputs_gather(op_info, device, dtype, requires_grad, **kwargs):\n return (\n SampleInput(\n make_tensor((M, S), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(0, gather_variable((S, S), 1, M, True, device=device))),\n SampleInput(\n make_tensor((M, S), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(1, gather_variable((M, S // 2), 0, S, True, device=device))),\n SampleInput(\n make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(0, torch.tensor([0], dtype=torch.int64, device=device))),\n SampleInput(\n make_tensor((S,), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(0, torch.tensor(0, dtype=torch.int64, device=device))),\n SampleInput(\n make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(0, torch.tensor(0, dtype=torch.int64, device=device))),\n )\n\n\ndef sample_inputs_take_along_dim(op_info, device, dtype, requires_grad, **kwargs):\n return (SampleInput(make_tensor((S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(gather_variable((S, S), 1, S, True, device=device), 0)),\n\n # `indices` broadcast\n SampleInput(make_tensor((S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(gather_variable((1, S // 2), 0, S, True, device=device), 1)),\n\n # `self` broadcast\n SampleInput(make_tensor((1, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(gather_variable((S, S // 2), 0, S, True, device=device), 1)),\n\n # without `dim` arg\n SampleInput(make_tensor((S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(gather_variable((S, S // 2), 0, S, True, device=device), )),\n SampleInput(make_tensor((S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(gather_variable((S, S // 2), 0, S, True, device=device),)),\n )\n\n\ndef sample_inputs_amax_amin(op_info, device, dtype, requires_grad, **kwargs):\n # Ordered as (input shape, kwargs)\n test_cases: Tuple[tuple, dict] = ( # type: ignore[assignment]\n ((S, S, S), {}),\n ((S, S, S), {'dim': 1}),\n ((S, S, S), {'dim': (1, 2,)}),\n ((S, S, S), {'dim': 1, 'keepdim': True}),\n ((), {'dim': 0}),\n ((), {}),\n ((), {'dim': 0, 'keepdim': True}),\n )\n\n samples: List[SampleInput] = []\n for shape, kwargs in test_cases:\n samples.append(SampleInput(\n make_tensor(shape, device, dtype, requires_grad=requires_grad),\n kwargs=kwargs))\n\n return samples\n\n# TODO (@heitorschueroff) Once aminmax supports multiple dims this should\n# be combined with the above test.\ndef sample_inputs_aminmax(op_info, device, dtype, requires_grad, **kwargs):\n test_cases: Tuple[tuple, dict] = ( # type: ignore[assignment]\n ((S, S, S), {}),\n ((S, S, S), {'dim': 1}),\n ((S, S, S), {'dim': 1, 'keepdim': True}),\n ((), {'dim': 0}),\n ((), {}),\n ((), {'dim': 0, 'keepdim': True}),\n )\n\n samples: List[SampleInput] = []\n for shape, kwargs in test_cases:\n samples.append(SampleInput(\n make_tensor(shape, device, dtype, requires_grad=requires_grad),\n kwargs=kwargs))\n\n return samples\n\ndef sample_inputs_argmax_argmin(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = (\n ((2, 2, 2), ()),\n ((2, 2, 2), (0,)),\n ((2, 2, 2), (1,)),\n ((2, 2, 2), (2,)),\n ((2, 2, 2), (2, True,)),\n ((2, 2, 2), (None,)),\n ((), (0,)),\n ((), ()),\n ((), (None, True,)),\n ((1,), ()),\n ((1,), (0,)),\n ((1,), (0, True)),\n ((2,), ()),\n ((2,), (0,)),\n ((2,), (0, True)),\n ((2, 2, 3), ()),\n ((2, 2, 3), (0,)),\n ((2, 2, 3), (1,)),\n ((2, 2, 3), (None, True)),\n )\n return tuple(SampleInput((make_tensor(size, device, dtype,\n requires_grad=requires_grad)),\n args=args)\n for size, args in test_cases)\n\ndef sample_inputs_diff(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = (\n ((1,), 0, None, None),\n ((S,), 0, None, None),\n ((S, 1), 0, None, None),\n ((S, 1), 1, None, None),\n ((S, S), 0, None, None),\n ((S, S), 1, None, None),\n ((S, S), 0, (1, S), (2, S)),\n ((S, S), 0, None, (2, S)),\n ((S, S, S), 1, None, None),\n ((S, S, S), 1, (S, 1, S), (S, 1, S)),)\n\n sample_inputs = []\n for size, dim, size_prepend, size_append in test_cases:\n args = (make_tensor(size, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad), 1, dim,\n make_tensor(size_prepend, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad) if size_prepend else None,\n make_tensor(size_append, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad) if size_append else None)\n sample_inputs.append(SampleInput(args[0], args=args[1:]))\n\n return tuple(sample_inputs)\n\ndef sample_inputs_histogram(op_info, device, dtype, requires_grad):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n sizes = ((), (S,), (S, S), (S, S, S), (S, 1, S), (S, 0, S))\n\n sample_inputs = []\n for size, bin_ct, weighted, density in product(sizes, range(1, 5), [False, True], [False, True]):\n input_tensor = make_arg(size)\n weight_tensor = make_arg(size) if weighted else None\n\n sample_inputs.append(SampleInput(input_tensor, args=(bin_ct,),\n kwargs=dict(weight=weight_tensor, density=density)))\n\n bins_tensor = make_arg((bin_ct + 1,))\n sample_inputs.append(SampleInput(input_tensor, args=(bins_tensor,),\n kwargs=dict(weight=weight_tensor, density=density)))\n\n return sample_inputs\n\ndef sample_inputs_gradient(op_info, device, dtype, requires_grad):\n sample_inputs = []\n test_cases_float = (\n ((S,), None, None, 1),\n ((S,), 2., None, 1),\n ((S, S), None, None, 2),\n ((S, S), [2.0, 2.1], None, 1),\n ((S, S), [2.0, 2.1], (0, 1), 1),\n ((4, 4, 4), [2., 1.], (0, 1), 2),\n )\n for size, spacing, dim, edge_order in test_cases_float:\n t = make_tensor(size, device, dtype, low=None, high=None, requires_grad=requires_grad)\n sample_inputs.append(SampleInput(t, kwargs=dict(dim=dim, spacing=spacing, edge_order=edge_order)))\n\n test_cases_tensor = (\n ((3, 3, 3), ((1.1, 2.0, 3.5), (4.0, 2, 6.0)), (0, -1), 1),\n ((3, 3, 3), ((1.0, 3.0, 2.0), (8.0, 6.0, 1.0)), (0, 1), 2),\n )\n for size, coordinates, dim, edge_order in test_cases_tensor:\n t = make_tensor(size, device, dtype, low=None, high=None, requires_grad=requires_grad)\n coordinates_tensor_list = []\n for coords in coordinates:\n a = torch.tensor(coords, dtype=dtype, device=device)\n coordinates_tensor_list.append(a)\n sample_inputs.append(SampleInput(t, kwargs=dict(dim=dim, spacing=coordinates_tensor_list, edge_order=edge_order)))\n\n return tuple(sample_inputs)\n\ndef sample_inputs_index_select(op_info, device, dtype, requires_grad):\n return (\n SampleInput(\n make_tensor((S, S, S), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(0, index_variable(2, S, device=device))),\n SampleInput(\n make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(0, torch.tensor([0], dtype=torch.int64, device=device))),\n SampleInput(\n make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(0, torch.tensor(0, dtype=torch.int64, device=device))),\n )\n\ndef sample_inputs_getitem(op_info, device, dtype, requires_grad, **kwargs):\n test_args = [\n ([1, 2],),\n (slice(0, 3),),\n ([slice(0, 3), 1],),\n ([[0, 2, 3], [1, 3, 3], [0, 0, 2]],),\n ([[0, 0, 3], [1, 1, 3], [0, 0, 2]],),\n ([slice(None), slice(None), [0, 3]],),\n ([slice(None), [0, 3], slice(None)],),\n ([[0, 3], slice(None), slice(None)],),\n ([[0, 3], [1, 2], slice(None)],),\n ([[0, 3], ],),\n ([[0, 3], slice(None)],),\n ([[0, 3], Ellipsis],),\n ([[0, 2, 3], [1, 3, 3], torch.LongTensor([0, 0, 2])],),\n (index_variable(2, S, device=device),),\n (mask_not_all_zeros((S,)),),\n ]\n\n return tuple(SampleInput(\n make_tensor((S, S, S), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=args)\n for args in test_args)\n\ndef sample_inputs_index_put(op_info, device, dtype, requires_grad, **kwargs):\n inputs = []\n for accumulate in [False, True]:\n # Test with indices arg\n inputs.append(SampleInput(\n make_tensor((S, S,), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n (index_variable(2, S, device=device), ),\n make_tensor((2, S), device, dtype, low=None, high=None)),\n kwargs=dict(accumulate=accumulate)))\n\n # Test with mask arg\n mask = torch.zeros(S, dtype=torch.bool) if accumulate else mask_not_all_zeros((S,))\n inputs.append(SampleInput(\n make_tensor((S, S), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(\n (mask, ),\n make_tensor((S,), device, dtype, low=None, high=None),),\n kwargs=dict(accumulate=accumulate)))\n\n return inputs\n\n# Missing to test the nondeterminism of the operation\n# https://github.com/pytorch/pytorch/issues/53352\ndef sample_inputs_index_add(op_info, device, dtype, requires_grad, **kwargs):\n # These testa are pretty much the same as those from index_copy.\n # Perhaps merge?\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n t = make_arg((S, S))\n s = make_arg((S, S))\n # non-contiguous target\n t_nonctg = t.transpose(0, 1)\n # non-contiguous source\n s_nonctg = s.transpose(0, 1)\n\n idx = make_arg((S,), dtype=torch.int64, low=0, high=S)\n idx_nonctg = make_arg((S,), dtype=torch.int64, low=0, high=S, noncontiguous=True)\n samples = [SampleInput(tensor, args=(1, idx, source))\n for tensor, idx, source in product([t, t_nonctg], [idx, idx_nonctg], [s, s_nonctg])]\n samples.extend(SampleInput(tensor, args=(1, idx, source), kwargs=dict(alpha=a))\n for tensor, idx, source, a in product([t, t_nonctg], [idx, idx_nonctg], [s, s_nonctg], [-1, 0, 2]))\n\n # Add scalar cases\n scalar_sizes = [(), (1,)]\n ts = (make_arg(size) for size in scalar_sizes)\n idxs = (make_arg(size, dtype=torch.int64, low=0, high=1) for size in scalar_sizes)\n ss = (make_arg(size) for size in scalar_sizes)\n\n samples.extend(SampleInput(t, args=(0, idx, s)) for t, idx, s in product(ts, idxs, ss))\n samples.extend(SampleInput(t, args=(0, idx, s), kwargs=dict(alpha=a)) for t, idx, s, a in product(ts, idxs, ss, [-1, 0, 2]))\n return samples\n\ndef sample_inputs_sort(op_info, device, dtype, requires_grad, **kwargs):\n def apply_grad(t):\n if dtype in floating_types_and(torch.float16, torch.bfloat16):\n t.requires_grad_(requires_grad)\n\n def small_3d_unique(dtype, device):\n res = torch.randperm(S * S * S, dtype=torch.int64, device=device).view(S, S, S)\n res = res.to(dtype)\n apply_grad(res)\n return res\n\n def large_1d_unique(dtype, device):\n res = torch.randperm(L * L * L, dtype=torch.int64, device=device)\n res = res.to(dtype)\n apply_grad(res)\n return res\n\n samples = []\n # Test case for large tensor.\n largesample = SampleInput(large_1d_unique(dtype, device))\n samples.append(largesample)\n\n # Test cases for small 3d tensors.\n # Imitates legacy tests from test/test_torch.py\n t = small_3d_unique(dtype, device)\n dims = range(-3, 3)\n flag = [True, False]\n for dim, descending, stable in product(dims, flag, flag):\n # default schema without stable sort\n samples.append(SampleInput(t, args=(dim, descending)))\n # schema with stable sort, no CUDA support yet\n if torch.device(device).type == 'cpu':\n samples.append(\n SampleInput(t, kwargs=dict(dim=dim, descending=descending, stable=stable))\n )\n\n # Test cases for scalar tensor\n scalar = torch.tensor(1, dtype=dtype, device=device)\n apply_grad(scalar)\n samples.append(SampleInput(scalar))\n samples.append(SampleInput(scalar, args=(0,)))\n samples.append(SampleInput(scalar, args=(0, True)))\n\n # Test cases for stable sort\n samples.append(SampleInput(scalar, kwargs=dict(stable=True)))\n samples.append(SampleInput(scalar, kwargs=dict(dim=0, stable=True)))\n samples.append(SampleInput(scalar, kwargs=dict(dim=0, descending=True, stable=True)))\n return samples\n\ndef sample_inputs_index_fill(op_info, device, dtype, requires_grad, **kwargs):\n samples = []\n t = make_tensor((S, S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad)\n fill_val = torch.tensor(-1 + 1j if t.is_complex() else -1)\n # non-contiguous input\n t01 = t.transpose(0, 1)\n t02 = t.transpose(0, 2)\n t12 = t.transpose(1, 2)\n idx = index_variable(1, S, device=device)\n # non-contiguous index\n idx_nonctg = torch.empty_strided((S,), (2,), device=device, dtype=torch.int64)\n idx_nonctg.copy_(idx)\n for d in range(t.dim()):\n for tensor in [t, t01, t02, t12]:\n samples.append(SampleInput(tensor, args=(d, idx, fill_val)))\n samples.append(SampleInput(tensor, args=(d, -idx - 1, fill_val)))\n samples.append(SampleInput(tensor, args=(d, idx_nonctg, fill_val)))\n\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n index_tensor = partial(torch.tensor, device=device, dtype=torch.long)\n\n def unique_idx(numel, max_idx):\n # Generate unique random indices vector of `numel`\n # elements in range [0, max_idx).\n indices = random.sample(range(max_idx), numel)\n return index_tensor(indices)\n\n samples.append(SampleInput(make_arg((S, S)), args=(0, unique_idx(2, S), 2)))\n samples.append(SampleInput(make_arg((S, S)), args=(0, unique_idx(2, S), make_arg(()))))\n samples.append(SampleInput(make_arg((S, S)), args=(0, index_tensor(0), 2)))\n samples.append(SampleInput(make_arg(()), args=(0, index_tensor([0]), 2)))\n samples.append(SampleInput(make_arg(()), args=(0, index_tensor(0), 2)))\n\n # Duplicate indices\n samples.append(SampleInput(make_arg((S, S)), args=(0, index_tensor([0, 0]), 2)))\n samples.append(SampleInput(make_arg((S, S)), args=(0, index_tensor([0, 0, 2]), make_arg(()))))\n\n return samples\n\ndef sample_inputs_max_min_binary(op_info, device, dtype, requires_grad, **kwargs):\n inputs = []\n args_for_binary_op = (\n ((S, S, S), (S, S, S),),\n ((S, S, S), (S,),),\n ((S,), (S, S, S),),\n ((S, 1, S), (S, S),),\n ((S, S), (S, S),),\n ((), (),),\n ((S, S, S), (),),\n ((), (S, S, S),),\n )\n inputs = list((SampleInput(make_tensor(input_tensor, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=(make_tensor(other_tensor, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),),))\n for input_tensor, other_tensor in args_for_binary_op)\n return inputs\n\ndef sample_inputs_adaptive_avg_pool2d(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n # Ordered as (input shape, output size)\n cases = (\n ((1, 8, 8, 8), (5, 7)),\n ((2, 8, 8, 8), (None, 7)),\n ((1, 8, 4, 3), (5, None)),\n ((1, 8, 4, 3), (None, None)),\n ((1, 8, 4, 3), (5)),\n )\n\n def generator():\n for input_shape, output_size in cases:\n yield SampleInput(make_arg(input_shape), args=(output_size,))\n\n return list(generator())\n\ndef sample_inputs_normalize(self, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, low=-1, high=1, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases: Tuple[Tuple[int], dict] = ( # type: ignore[assignment]\n ((2, 1, 4, 5), {'p': 1., 'dim': 2}),\n ((2, 3, 4, 5), {'p': 2., 'dim': 1}),\n ((1, 2, 4, 5), {'p': 0.5, 'dim': 0}),\n ((1, 3, 4, 5), {'p': -1., 'dim': 1}),\n ((1, 3, 4, 5), {'p': 0., 'dim': -1}),\n ((), {'p': 1.2, 'dim': 0}),\n ((2, 3, 4, 5), {}),\n ((2, 3, 4, 5), {'eps': 1e-4}))\n\n def generator():\n for input_shape, kwargs in cases:\n yield SampleInput(make_arg(input_shape), kwargs=kwargs)\n\n return list(generator())\n\ndef sample_inputs_conv_transpose2d(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n # Ordered as shapes for input, weight, bias\n # and a dict of values of (stride, padding, output_padding, groups, dilation)\n cases: Tuple[Tuple[int], Tuple[int], Tuple[int], dict] = ( # type: ignore[assignment]\n ((1, 3, 4, 4), (3, 3, 3, 3), (3,),\n {'stride': (2, 2), 'padding': 2, 'output_padding': (1, 1), 'groups': 1}),\n ((2, 2, 4, 4), (2, 2, 4, 5), (4,),\n {'stride': (3, 2), 'padding': (1, 2), 'output_padding': (2, 3), 'groups': 2, 'dilation': (4, 4)}),\n ((1, 1, 4, 5), (1, 1, 4, 3), (1,),\n {'stride': 2, 'padding': 1, 'output_padding': 1, 'groups': 1, 'dilation': (2, 3)}),\n ((1, 1, 4, 3), (1, 2, 3, 4), None,\n {'stride': 2, 'padding': 1, 'output_padding': 1, 'groups': 1}),\n ((1, 4, 5, 5), (4, 8, 3, 3), None,\n {})\n )\n\n def generator():\n for input_shape, weight, bias, kwargs in cases:\n yield SampleInput(make_arg(input_shape), args=(\n make_arg(weight),\n make_arg(bias) if bias is not None else bias\n ), kwargs=kwargs)\n\n return list(generator())\n\ndef sample_inputs_hardswish(self, device, dtype, requires_grad):\n N = 5\n # make sure we are testing -3 -> 3 range. default is -10 -> 10 so maybe unnecessary ?\n tensors = [SampleInput(make_tensor((N * 2, N * 2), device=device, dtype=dtype,\n requires_grad=requires_grad, low=-5, high=5)) for _ in range(1, N)]\n return tensors\n\ndef sample_inputs_gelu(self, device, dtype, requires_grad):\n N = 5\n tensors = [SampleInput(make_tensor((N * 2, N * 2), device=device, dtype=dtype,\n requires_grad=requires_grad, low=-3, high=3)) for _ in range(1, N)]\n return tensors\n\ndef sample_inputs_max_min_reduction_with_dim(op_info, device, dtype, requires_grad, **kwargs):\n inputs = []\n args_for_reduction_with_dim = (\n ((S, S, S), (1,),),\n ((S, S, S), (1, True, ),),\n ((), (0,),),\n ((), (0, True,),),\n )\n inputs = list((SampleInput(make_tensor(input_tensor, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=args,))\n for input_tensor, args in args_for_reduction_with_dim)\n return inputs\n\ndef sample_inputs_max_min_reduction_no_dim(op_info, device, dtype, requires_grad, **kwargs):\n inputs = []\n inputs.append(SampleInput(make_tensor((S, S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),))\n inputs.append(SampleInput(make_tensor((), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),))\n return inputs\n\n# Generates input tensors for testing reduction ops\ndef _generate_reduction_inputs(device, dtype, requires_grad):\n yield make_tensor((), device, dtype, requires_grad=requires_grad)\n yield make_tensor((2,), device, dtype, requires_grad=requires_grad)\n yield make_tensor((2, 3), device, dtype, requires_grad=requires_grad, noncontiguous=True)\n yield make_tensor((3, 2, 1, 2, 2), device, dtype, requires_grad=requires_grad)\n\n# Generates a subset of possible dim and keepdim kwargs for a tensor\n# with ndim dims appropriate for testing. If supports_multiple_dims\n# is True (default) then dim kwarg can be a list of dims.\ndef _generate_reduction_kwargs(ndim, supports_multiple_dims=True):\n for keepdim in [True, False]:\n # Always test reducing inner and outer most dimensions\n yield {'dim': 0, 'keepdim': keepdim}\n yield {'dim': -1, 'keepdim': keepdim}\n\n # Also reduce middle dimension\n if ndim > 2:\n yield {'dim': ndim // 2, 'keepdim': keepdim}\n\n if supports_multiple_dims:\n # Always test reducing all dims\n yield {'dim': tuple(range(ndim)), 'keepdim': keepdim}\n\n # Test reducing both first and last dimensions\n if ndim > 1:\n yield {'dim': (0, ndim - 1), 'keepdim': keepdim}\n\n # Test reducing every other dimension starting with the second\n if ndim > 3:\n yield {'dim': tuple(range(1, ndim, 2)), 'keepdim': keepdim}\n\n# Wraps sample_inputs_reduction function to provide the additional supports_multiple_dims args\ndef sample_inputs_reduction_wrapper(supports_multiple_dims):\n # Generates sample inputs for reduction ops that contain the input tensor\n # and dim and keepdim kwargs. If a reduction op needs to test additional\n # args/kwargs then create a separate sample_inputs function\n def fn(op_info, device, dtype, requires_grad):\n inputs = []\n\n for t in _generate_reduction_inputs(device, dtype, requires_grad):\n # Add case without dim and keepdim kwargs\n inputs.append(SampleInput(t))\n for kwargs in _generate_reduction_kwargs(t.ndim, supports_multiple_dims):\n inputs.append(SampleInput(t, kwargs=kwargs))\n\n return inputs\n\n return fn\n\ndef sample_inputs_reduction_quantile(op_info, device, dtype, requires_grad):\n test_quantiles = (0.5, make_tensor((2,), device, dtype, low=0, high=1))\n test_interpolations = ['linear', 'midpoint']\n\n inputs = []\n for quantiles in test_quantiles:\n for t in _generate_reduction_inputs(device, dtype, requires_grad):\n # Add case without dim and keepdim kwargs\n inputs.append(SampleInput(t, args=(quantiles,)))\n for kwargs in _generate_reduction_kwargs(t.ndim, supports_multiple_dims=False):\n # Interpolation kwarg for now is only supported when providing both dim and keepdim\n for interpolation in test_interpolations:\n kwargs['interpolation'] = interpolation\n inputs.append(SampleInput(t, args=(quantiles,), kwargs=kwargs))\n\n return inputs\n\ndef sample_inputs_leaky_relu(op_info, device, dtype, requires_grad):\n N = 10\n tensors = [SampleInput(make_tensor((N, N), device=device, dtype=dtype,\n requires_grad=requires_grad)) for _ in range(1, N)]\n return tensors\n\ndef sample_inputs_avgpool2d(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n # Order: input_shape, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override\n cases = (((1, 3, 9, 9), 3, 1, 1, True, False, 2),\n ((1, 3, 9, 9), (4, 4), (2, 3), 1, True, False, 2),\n ((1, 3, 9, 9), (6, 6), (3, 3), (2, 3), True, True, 2),\n ((2, 3, 9, 9), (3, 3), (1, 1), (1, ), True, False, 2),\n ((1, 1, 4, 4), (2, 2), (), (0, ), False, True, -2),\n ((1, 2, 6, 6), (4, 4), (2, 2), (2, ), True, True, None))\n\n def generator():\n for input_shape, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override in cases:\n yield SampleInput(make_arg(input_shape),\n args=(kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override))\n # Case with just input_shape and kernel_size\n yield SampleInput(make_arg((1, 3, 9, 9)), args=((3, 3)))\n\n return list(generator())\n\ndef sample_inputs_topk(op_info, device, dtype, requires_grad, **kwargs):\n def get_tensor_input(size):\n return make_tensor(size, device, dtype, requires_grad=requires_grad)\n\n inputs = []\n inputs.append(SampleInput(get_tensor_input((S, M, S)), args=(3,)))\n inputs.append(SampleInput(get_tensor_input((S, M, S)), args=(3, 1)))\n inputs.append(SampleInput(get_tensor_input((S, M, S)), args=(3, -2)))\n inputs.append(SampleInput(get_tensor_input((S, M, S)), args=(3, 1, True)))\n inputs.append(SampleInput(get_tensor_input((S, M, S)), args=(3, -2, True)))\n inputs.append(SampleInput(get_tensor_input((S, M, S)), args=(3, 1, True, True)))\n inputs.append(SampleInput(get_tensor_input((S, M, S)), args=(3, -2, True, True)))\n\n inputs.append(SampleInput(get_tensor_input(()), args=(1,)))\n inputs.append(SampleInput(get_tensor_input(()), args=(1, 0)))\n inputs.append(SampleInput(get_tensor_input(()), args=(1, -1)))\n inputs.append(SampleInput(get_tensor_input(()), args=(1, 0, True)))\n inputs.append(SampleInput(get_tensor_input(()), args=(1, -1, True)))\n inputs.append(SampleInput(get_tensor_input(()), args=(1, 0, True, True)))\n inputs.append(SampleInput(get_tensor_input(()), args=(1, -1, True, True)))\n\n return inputs\n\ndef sample_inputs_outer(op_info, device, dtype, requires_grad, **kwargs):\n inputs = []\n arg_a = make_tensor((S,), device, dtype, requires_grad=requires_grad)\n arg_b = make_tensor((M,), device, dtype, requires_grad=requires_grad)\n inputs.append(SampleInput(arg_a, args=(arg_b,)))\n return inputs\n\ndef sample_inputs_dist(op_info, device, dtype, requires_grad):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n sizes = ((S, S, S), (S,), (S, 1, S), (), (S, S))\n ps = (2, 4)\n\n def generate_samples():\n for size_x, size_y, p in product(sizes, sizes, ps):\n yield SampleInput(make_arg(size_x), args=(make_arg(size_y), p))\n\n return list(generate_samples())\n\n# Missing to test the nondeterminism of the operation\n# https://github.com/pytorch/pytorch/issues/53352\ndef sample_inputs_index_copy(op_info, device, dtype, requires_grad, **kwargs):\n def make_arg(shape, low=None, high=None, dtype=dtype):\n return make_tensor(shape, device=device, dtype=dtype,\n low=low, high=high,\n requires_grad=requires_grad)\n\n t = make_arg((S, S))\n s = make_arg((S, S))\n # non-contiguous input\n t01 = t.transpose(0, 1)\n # non-contiguous input\n s01 = s.transpose(0, 1)\n\n # idx is a permutation of 0...S-1 for this function to be deterministic\n idx = torch.randperm(S, device=device, dtype=torch.int64)\n # non-contiguous index\n idx_nonctg = torch.repeat_interleave(idx, 2, dim=-1)[::2]\n # index_copy_ does not support negative indices\n # idx_neg = -idx - 1\n samples = [SampleInput(tensor, args=(1, idx, source))\n for tensor, idx, source in product([t, t01], [idx, idx_nonctg], [s, s01])]\n\n # Add scalar cases\n scalar_sizes = [(), (1,)]\n ts = (make_arg(size) for size in scalar_sizes)\n idxs = (make_arg(size, dtype=torch.int64, low=0, high=1) for size in scalar_sizes)\n ss = (make_arg(size) for size in scalar_sizes)\n\n samples.extend(SampleInput(t, args=(0, idx, s)) for t, idx, s in product(ts, idxs, ss))\n return samples\n\ndef sample_inputs_mode(op_info, device, dtype, requires_grad):\n inputs = []\n args = (\n ((S, S, S), (),),\n ((S, S, S), (1, ),),\n ((S, S, S), (1, True, ),),\n ((), (),),\n ((), (0,),),\n ((), (0, True,),),\n )\n inputs = list((SampleInput(make_tensor(input_tensor, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=args,))\n for input_tensor, args in args)\n return inputs\n\n# Missing to test the nondeterminism of the operation\n# https://github.com/pytorch/pytorch/issues/53352\ndef sample_inputs_put(op_info, device, dtype, requires_grad):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n make_idx = partial(make_tensor, low=0, dtype=torch.int64, device=device, requires_grad=False)\n\n S = 3\n\n def gen_inputs():\n # Generic inputs\n tgt_gen = (make_arg((S, S), noncontiguous=not ctg) for ctg in (True, False))\n src_gen = (make_arg((S,), noncontiguous=not ctg) for ctg in (True, False))\n idx = torch.randperm(S * S, device=device, dtype=torch.int64)[:S]\n idx_nonctg = torch.repeat_interleave(idx, 2, dim=-1)[::2]\n idx_neg = -idx - 1\n idx_list = [idx, idx_nonctg, idx_neg]\n for tgt, idx, src, acc in product(tgt_gen, idx_list, src_gen, (True, False)):\n yield SampleInput(input=tgt, args=(idx, src, acc))\n\n # Scalar cases\n scalar_sizes = [(), (1,)]\n tgt_gen = (make_arg(size) for size in scalar_sizes)\n idx_gen = (make_idx(size, high=1) for size in scalar_sizes)\n src_gen = (make_arg(size) for size in scalar_sizes)\n for tgt, idx, src, acc in product(tgt_gen, idx_gen, src_gen, (True, False)):\n yield SampleInput(input=tgt, args=(idx, src, acc))\n\n # Empty cases\n tgt_sizes = [(0,), (), (1,), (3, 2)]\n tgt_gen = (make_arg(size) for size in tgt_sizes)\n idx = make_idx((0,), high=1)\n src = make_arg((0,))\n for tgt, acc in product(tgt, (True, False)):\n yield SampleInput(input=tgt, args=(idx, src, acc))\n\n return list(gen_inputs())\n\ndef sample_inputs_take(op_info, device, dtype, requires_grad):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n make_idx = partial(make_tensor, low=0, dtype=torch.int64, device=device, requires_grad=False)\n\n S = 3\n\n def gen_inputs():\n # Generic inputs: take S elements out of S * S\n src_gen = (make_arg((S, S), noncontiguous=not ctg) for ctg in (True, False))\n idx = make_idx((S,), high=S * S)\n idx_nonctg = make_idx((S,), high=S * S, noncontiguous=True)\n idx_neg = -idx - 1\n idx_list = [idx, idx_nonctg, idx_neg]\n for src, idx in product(src_gen, idx_list):\n yield SampleInput(input=src, args=(idx,))\n\n # Scalar cases\n scalar_sizes = [(), (1,)]\n src_gen = (make_arg(size) for size in scalar_sizes)\n idx_gen = (make_idx(size, high=1) for size in scalar_sizes)\n for src, idx in product(src_gen, idx_gen):\n yield SampleInput(input=src, args=(idx,))\n\n # Empty cases\n src_sizes = [(0,), (), (1,), (3, 2)]\n src_gen = (make_arg(size) for size in src_sizes)\n idx = make_idx((0,), high=1)\n for src in src_gen:\n yield SampleInput(input=src, args=(idx,))\n\n return list(gen_inputs())\n\ndef sample_movedim_moveaxis(op_info, device, dtype, requires_grad):\n return (\n SampleInput(\n make_tensor((4, 3, 2, 1), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=([0, 1, 2, 3], [3, 2, 1, 0])),\n SampleInput(\n make_tensor((4, 3, 2, 1), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=([0, -1, -2, -3], [-3, -2, -1, -0]))\n )\n\n\ndef sample_repeat_tile(op_info, device, dtype, requires_grad, **kwargs):\n rep_dims = ((), (0, ), (1, ), (0, 2), (1, 1), (2, 3), (2, 3, 2), (0, 2, 3), (2, 1, 1, 1),)\n shapes = ((), (0,), (2,), (3, 0), (3, 2), (3, 0, 1))\n\n if requires_grad:\n # Tests for variant_consistency_jit, grad, gradgrad\n # are slower. Use smaller bags of `rep_dims` and `shapes`\n # in this case.\n rep_dims = ((), (0, ), (0, 2), (1, 1), (2, 3), (1, 3, 2), (3, 1, 1)) # type: ignore[assignment]\n shapes = ((), (0,), (2,), (3, 2)) # type: ignore[assignment]\n\n tensors = [make_tensor(shape, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad) for shape in shapes]\n\n samples = []\n for rep_dim, tensor in product(rep_dims, tensors):\n for t in (tensor, tensor.T):\n if op_info.name == 'repeat' and len(rep_dim) >= t.dim():\n # `torch.repeat` errors for `len(rep_dims) < t.dim()`,\n # so we filter such combinations.\n samples.append(SampleInput(t, args=(rep_dim,),))\n elif op_info.name == 'tile':\n samples.append(SampleInput(t, args=(rep_dim,),))\n\n return samples\n\n\ndef sample_inputs_narrow(op_info, device, dtype, requires_grad, **kwargs):\n shapes_and_args = (\n ((S, S, S), (1, 2, 2)),\n ((S, S, S), (-1, 2, 2)),\n ((S, S, S), (1, 0, 0)),\n ((S, S, S), (-1, 0, 0)),\n )\n\n def generator():\n for shape, args in shapes_and_args:\n tensor = make_tensor(shape, device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n yield SampleInput(tensor, args=args)\n\n return list(generator())\n\ndef sample_trapezoid(op_info, device, dtype, requires_grad, **kwargs):\n y_shape_x_shape_and_kwargs = [\n ((2, 3), (2, 3), {}),\n ((2, 3), (2, 3), {'dim': 1}),\n ((6,), (6,), {}),\n ((6,), None, {}),\n # When 'trapezoid' is called with an empty input, it does not produce an output with requires_grad\n # See Issue #{61619}\n # ((6,0), (6,0), {}),\n ((2, 3), (1, 3), {}),\n ((3, 3), (3, 3), {}),\n ((3, 3), (3, 3), {'dim': -2}),\n ((5,), None, {'dx': 2.0}),\n ((2, 2), None, {'dx': 3.0})\n ]\n samples = []\n for y_shape, x_shape, kwarg in y_shape_x_shape_and_kwargs:\n y_tensor = make_tensor(y_shape, device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n if x_shape is not None:\n x_tensor = make_tensor(x_shape, device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n samples.append(SampleInput(y_tensor, args=(x_tensor,), kwargs=kwarg))\n else:\n samples.append(SampleInput(y_tensor, kwargs=kwarg))\n return samples\n\ndef sample_cumulative_trapezoid(op_info, device, dtype, requires_grad, **kwargs):\n\n y_shape_x_shape_and_kwargs = [\n ((2, 3), (2, 3), {}),\n ((2, 3), (2, 3), {'dim': 1}),\n ((6,), (6,), {}),\n ((6,), None, {}),\n # When 'cumulative_trapezoid' is called with an empty input, it does not produce an output with requires_grad\n # See Issue #{61619}\n # ((6,0), (6,0), {}),\n ((2, 3), (1, 3), {}),\n ((3, 3), (3, 3), {}),\n ((3, 3), (3, 3), {'dim': -2}),\n ((5,), None, {'dx': 2.0}),\n ((2, 2), None, {'dx': 3.0})\n ]\n samples = []\n for y_shape, x_shape, kwarg in y_shape_x_shape_and_kwargs:\n y_tensor = make_tensor(y_shape, device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n if x_shape is not None:\n x_tensor = make_tensor(x_shape, device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n samples.append(SampleInput(y_tensor, args=(x_tensor,), kwargs=kwarg))\n else:\n samples.append(SampleInput(y_tensor, kwargs=kwarg))\n return samples\n\ndef sample_unsqueeze(op_info, device, dtype, requires_grad, **kwargs):\n shapes_and_axes = [\n ((3, 4, 5), 0),\n ((3, 4, 5), 1),\n ((3, 4, 5), 3),\n ((3, 4, 5), -1),\n ((3, 4, 5), -3),\n ((), 0)\n ]\n\n samples = []\n for shape, axis in shapes_and_axes:\n tensor = make_tensor(shape, device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n samples.append(SampleInput(tensor, args=(axis,),))\n\n return samples\n\n\ndef sample_inputs_nn_unfold(op_info, device, dtype, requires_grad, **kwargs):\n shapes = ((0, 1, 5, 5), (1, 1, 5, 5), (2, 3, 5, 5))\n kernel_sizes = (2, (2, 2), (3, 3))\n dilations = (1, 2, (1, 2))\n paddings = (0, 1, (1, 1))\n strides = (1, 2, (1, 2))\n\n def generator():\n cases = product(shapes, kernel_sizes, dilations, paddings, strides)\n for shape, kernel_size, dilation, padding, stride in cases:\n tensor = make_tensor(shape, device, dtype, requires_grad=requires_grad)\n yield SampleInput(tensor, args=(kernel_size, dilation, padding, stride))\n\n # With default args\n yield SampleInput(make_tensor((1, 1, 5, 5), device, dtype, requires_grad=requires_grad),\n args=((3, 3),))\n\n return list(generator())\n\n\ndef sample_inputs_squeeze(op_info, device, dtype, requires_grad, **kwargs):\n shapes_and_args = (\n ((S, 1, S, 1), ()),\n ((1, 1, 1, 1), ()),\n ((S, 1, S, 1), (1,)),\n ((S, 1, S, 1), (-1,)),\n ((S, 1, S, 1), (2,)),\n ((S, 1, S, 1), (-2,)),\n ((), (0, )),\n )\n\n def generator():\n for shape, args in shapes_and_args:\n tensor = make_tensor(shape, device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n\n yield SampleInput(tensor, args=args)\n\n return list(generator())\n\n\n# TODO: reconcile with torch.linalg.det and torch.linalg.slogdet\n# Creates matrices with a positive nonzero determinant\ndef sample_inputs_logdet(op_info, device, dtype, requires_grad, **kwargs):\n def make_nonzero_det(A, *, sign=1, min_singular_value=0.1, **kwargs):\n u, s, vh = torch.linalg.svd(A, full_matrices=False)\n s.clamp_(min=min_singular_value)\n A = (u * s.unsqueeze(-2)) @ vh\n det = A.det()\n if sign is not None:\n if A.dim() == 2:\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 samples = []\n\n # cases constructed using make_tensor()\n tensor_shapes = (\n (S, S),\n (1, 1),\n (3, 3, S, S),\n (3, 3, 1, 1)\n )\n\n for shape in tensor_shapes:\n t = make_tensor(shape, device=device, dtype=dtype)\n d = make_nonzero_det(t).requires_grad_(requires_grad)\n samples.append(SampleInput(d))\n\n # cases constructed using:\n # 1) make_symmetric_matrices\n # 2) make_symmetric_pd_matrices\n # 3) make_fullrank_matrices_with_distinct_singular_values\n symmetric_shapes = (\n (S, S),\n (3, S, S),\n )\n\n\n def _helper(constructor, *shape, **kwargs):\n t = constructor(*shape, device=device, dtype=dtype)\n d = make_nonzero_det(t, **kwargs).requires_grad_(requires_grad)\n samples.append(SampleInput(d))\n\n for shape in symmetric_shapes:\n _helper(make_symmetric_matrices, *shape)\n _helper(make_symmetric_pd_matrices, *shape)\n _helper(make_fullrank_matrices_with_distinct_singular_values, *shape, min_singular_value=0)\n\n return tuple(samples)\n\ndef np_unary_ufunc_integer_promotion_wrapper(fn):\n # Wrapper that passes PyTorch's default scalar\n # type as an argument to the wrapped NumPy\n # unary ufunc when given an integer input.\n # This mimicks PyTorch's integer->floating point\n # type promotion.\n #\n # This is necessary when NumPy promotes\n # integer types to double, since PyTorch promotes\n # integer types to the default scalar type.\n\n # Helper to determine if promotion is needed\n def is_integral(dtype):\n return dtype in [np.bool_, bool, np.uint8, np.int8, np.int16, np.int32, np.int64]\n\n @wraps(fn)\n def wrapped_fn(x):\n # As the default dtype can change, acquire it when function is called.\n # NOTE: Promotion in PyTorch is from integer types to the default dtype\n np_dtype = torch_to_numpy_dtype_dict[torch.get_default_dtype()]\n\n if is_integral(x.dtype):\n return fn(x.astype(np_dtype))\n return fn(x)\n\n return wrapped_fn\n\ndef sample_inputs_spectral_ops(self, device, dtype, requires_grad=False, **kwargs):\n nd_tensor = make_tensor((S, S + 1, S + 2), device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n tensor = make_tensor((31,), device, dtype, low=None, high=None,\n requires_grad=requires_grad)\n\n if self.ndimensional:\n return [\n SampleInput(nd_tensor, kwargs=dict(s=(3, 10), dim=(1, 2), norm='ortho')),\n SampleInput(nd_tensor, kwargs=dict(norm='ortho')),\n SampleInput(nd_tensor, kwargs=dict(s=(8,))),\n SampleInput(tensor),\n\n *(SampleInput(nd_tensor, kwargs=dict(dim=dim))\n for dim in [-1, -2, -3, (0, -1)]),\n ]\n else:\n return [\n SampleInput(nd_tensor, kwargs=dict(n=10, dim=1, norm='ortho')),\n SampleInput(nd_tensor, kwargs=dict(norm='ortho')),\n SampleInput(nd_tensor, kwargs=dict(n=7)),\n SampleInput(tensor),\n\n *(SampleInput(nd_tensor, kwargs=dict(dim=dim))\n for dim in [-1, -2, -3]),\n ]\n\n# Metadata class for Fast Fourier Transforms in torch.fft.\nclass SpectralFuncInfo(OpInfo):\n \"\"\"Operator information for torch.fft transforms. \"\"\"\n\n def __init__(self,\n name, # the string name of the function\n *,\n ref=None, # Reference implementation (probably in np.fft namespace)\n dtypes=floating_and_complex_types(),\n ndimensional: bool, # Whether dim argument can be a tuple\n sample_inputs_func=sample_inputs_spectral_ops,\n decorators=None,\n **kwargs):\n decorators = list(decorators) if decorators is not None else []\n decorators += [\n skipCPUIfNoFFT,\n skipCUDAIfRocm,\n ]\n\n super().__init__(name=name,\n dtypes=dtypes,\n decorators=decorators,\n sample_inputs_func=sample_inputs_func,\n **kwargs)\n self.ref = ref if ref is not None else _getattr_qual(np, name)\n self.ndimensional = ndimensional\n\n\nclass ShapeFuncInfo(OpInfo):\n \"\"\"Early version of a specialized OpInfo for Shape manipulating operations like tile and roll\"\"\"\n def __init__(self,\n name, # the string name of the function\n *,\n ref, # a reference function\n dtypes=floating_types(),\n dtypesIfCPU=None,\n dtypesIfCUDA=None,\n dtypesIfROCM=None,\n sample_inputs_func=None,\n **kwargs):\n super(ShapeFuncInfo, self).__init__(name,\n dtypes=dtypes,\n dtypesIfCPU=dtypesIfCPU,\n dtypesIfCUDA=dtypesIfCUDA,\n dtypesIfROCM=dtypesIfROCM,\n sample_inputs_func=sample_inputs_func,\n **kwargs)\n self.ref = ref\n\ndef sample_inputs_foreach(self, device, dtype, N, *, noncontiguous=False, same_size=False):\n if same_size:\n return [make_tensor((N, N), device, dtype, noncontiguous=noncontiguous) for _ in range(N)]\n else:\n return [make_tensor((N - i, N - i), device, dtype, noncontiguous=noncontiguous) for i in range(N)]\n\n\ndef get_foreach_method_names(name):\n # get torch inplace reference function\n op_name = \"_foreach_\" + name\n inplace_op_name = \"_foreach_\" + name + \"_\"\n\n op = getattr(torch, op_name, None)\n inplace_op = getattr(torch, inplace_op_name, None)\n\n ref = getattr(torch, name, None)\n ref_inplace = getattr(torch.Tensor, name + \"_\", None)\n return op, inplace_op, ref, ref_inplace\n\nclass ForeachFuncInfo(OpInfo):\n \"\"\"Early version of a specialized OpInfo for foreach functions\"\"\"\n def __init__(self,\n name,\n dtypes=floating_and_complex_types(),\n dtypesIfCPU=all_types_and_complex(),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half),\n dtypesIfROCM=None,\n safe_casts_outputs=True,\n supports_alpha_param=False,\n sample_inputs_func=sample_inputs_foreach,\n **kwargs):\n super().__init__(\n \"_foreach_\" + name,\n dtypes=dtypes,\n dtypesIfCPU=dtypesIfCPU,\n dtypesIfCUDA=dtypesIfCUDA,\n dtypesIfROCM=dtypesIfROCM,\n safe_casts_outputs=safe_casts_outputs,\n sample_inputs_func=sample_inputs_func,\n **kwargs\n )\n\n foreach_method, foreach_method_inplace, torch_ref_method, torch_ref_inplace = get_foreach_method_names(name)\n self.method_variant = foreach_method\n self.inplace_variant = foreach_method_inplace\n self.ref = torch_ref_method\n self.ref_inplace = torch_ref_inplace\n self.supports_alpha_param = supports_alpha_param\n\n\ndef sample_inputs_linalg_cholesky_inverse(op_info, device, dtype, requires_grad=False):\n # Generate Cholesky factors of positive-definite (non-singular) Hermitian (symmetric) matrices\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n inputs = (\n torch.zeros(0, 0, dtype=dtype, device=device), # 0x0 matrix\n torch.zeros(0, 2, 2, dtype=dtype, device=device), # zero batch of matrices\n random_hermitian_pd_matrix(S, dtype=dtype, device=device), # single matrix\n random_hermitian_pd_matrix(S, 2, dtype=dtype, device=device), # batch of matrices\n )\n test_cases = (torch.linalg.cholesky(a) for a in inputs)\n out = []\n for a in test_cases:\n a.requires_grad = requires_grad\n out.append(SampleInput(a))\n out.append(SampleInput(a, kwargs=dict(upper=True)))\n return out\n\ndef sample_inputs_linalg_lstsq(op_info, device, dtype, requires_grad=False, **kwargs):\n from torch.testing._internal.common_utils import random_well_conditioned_matrix\n out = []\n for batch in ((), (3,), (3, 3)):\n shape = batch + (3, 3)\n # NOTE: inputs are not marked with `requires_grad` since\n # linalg_lstsq is not differentiable\n a = random_well_conditioned_matrix(*shape, dtype=dtype, device=device)\n b = make_tensor(shape, device, dtype, low=None, high=None)\n out.append(SampleInput(a, args=(b,)))\n return out\n\ndef sample_inputs_householder_product(op_info, device, dtype, requires_grad, **kwargs):\n \"\"\"\n This function generates input for torch.linalg.householder_product (torch.orgqr).\n The first argument should be a square matrix or batch of square matrices, the second argument is a vector or batch of vectors.\n Empty, square, rectangular, batched square and batched rectangular input is generated.\n \"\"\"\n # Each column of the matrix is getting multiplied many times leading to very large values for\n # the Jacobian matrix entries and making the finite-difference result of grad check less accurate.\n # That's why gradcheck with the default range [-9, 9] fails and [-2, 2] is used here.\n samples = (\n SampleInput(make_tensor((S, S), device, dtype, low=-2, high=2, requires_grad=requires_grad),\n args=(make_tensor((S,), device, dtype, low=-2, high=2, requires_grad=requires_grad),)),\n\n SampleInput(make_tensor((S + 1, S), device, dtype, low=-2, high=2, requires_grad=requires_grad),\n args=(make_tensor((S,), device, dtype, low=-2, high=2, requires_grad=requires_grad),)),\n\n SampleInput(make_tensor((2, 1, S, S), device, dtype, low=-2, high=2, requires_grad=requires_grad),\n args=(make_tensor((2, 1, S,), device, dtype, low=-2, high=2, requires_grad=requires_grad),)),\n\n SampleInput(make_tensor((2, 1, S + 1, S), device, dtype, low=-2, high=2, requires_grad=requires_grad),\n args=(make_tensor((2, 1, S,), device, dtype, low=-2, high=2, requires_grad=requires_grad),)),\n\n SampleInput(make_tensor((0, 0), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(make_tensor((0,), device, dtype, low=None, high=None, requires_grad=requires_grad),)),\n\n SampleInput(make_tensor((S, S), device, dtype, low=-2, high=2, requires_grad=requires_grad),\n args=(make_tensor((0,), device, dtype, low=None, high=None, requires_grad=requires_grad),)),\n )\n\n return samples\n\ndef sample_inputs_ormqr(op_info, device, dtype, requires_grad):\n # create a helper function wrapping `make_tensor`\n make_input = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n def gen_inputs():\n batches = [(), (0, ), (2, ), (2, 1)]\n ns = [5, 2, 0]\n tf = [True, False]\n for batch, (m, n), left, transpose in product(batches, product(ns, ns), tf, tf):\n reflectors = make_input((*batch, m, n))\n tau = make_input((*batch, min(m, n)))\n other_matrix_shape = (m, n) if left else (n, m)\n other = make_input((*batch, *other_matrix_shape))\n kwargs = {\"left\": left, \"transpose\": transpose}\n yield SampleInput(reflectors, args=(tau, other,), kwargs=kwargs)\n\n return tuple(gen_inputs())\n\ndef sample_inputs_linalg_cholesky(op_info, device, dtype, requires_grad=False, **kwargs):\n \"\"\"\n This function generates always positive-definite input for torch.linalg.cholesky using\n random_hermitian_pd_matrix.\n The input is generated as the itertools.product of 'batches' and 'ns'.\n In total this function generates 8 SampleInputs\n 'batches' cases include:\n () - single input,\n (0,) - zero batched dimension,\n (2,) - batch of two matrices,\n (1, 1) - 1x1 batch of matrices\n 'ns' gives 0x0 and 5x5 matrices.\n Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.\n \"\"\"\n from torch.testing._internal.common_utils import random_hermitian_pd_matrix\n\n batches = [(), (0, ), (2, ), (1, 1)]\n ns = [5, 0]\n out = []\n for batch, n in product(batches, ns):\n a = random_hermitian_pd_matrix(n, *batch, dtype=dtype, device=device)\n a.requires_grad = requires_grad\n out.append(SampleInput(a))\n return out\n\ndef sample_inputs_symeig(op_info, device, dtype, requires_grad=False):\n out = sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad)\n\n for o in out:\n o.kwargs = {\"upper\": bool(np.random.choice([True, False])),\n \"eigenvectors\": True}\n # A gauge-invariant function\n o.output_process_fn_grad = lambda output: (output[0], abs(output[1]))\n return out\n\ndef sample_inputs_linalg_eig(op_info, device, dtype, requires_grad=False):\n \"\"\"\n This function generates input for torch.linalg.eigh with UPLO=\"U\" or \"L\" keyword argument.\n \"\"\"\n def out_fn(output):\n return output[0], abs(output[1])\n\n samples = sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad)\n for sample in samples:\n sample.output_process_fn_grad = out_fn\n\n return samples\n\ndef sample_inputs_linalg_eigh(op_info, device, dtype, requires_grad=False, **kwargs):\n \"\"\"\n This function generates input for torch.linalg.eigh/eigvalsh with UPLO=\"U\" or \"L\" keyword argument.\n \"\"\"\n def out_fn(output):\n if isinstance(output, tuple):\n # eigh function\n return output[0], abs(output[1])\n else:\n # eigvalsh function\n return output\n\n samples = sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad)\n for sample in samples:\n sample.kwargs = {\"UPLO\": np.random.choice([\"L\", \"U\"])}\n sample.output_process_fn_grad = out_fn\n\n return samples\n\n\ndef sample_inputs_linalg_slogdet(op_info, device, dtype, requires_grad=False):\n def out_fn(output):\n return output[1]\n\n samples = sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad)\n for sample in samples:\n sample.output_process_fn_grad = out_fn\n\n return samples\n\n\ndef sample_inputs_linalg_pinv_hermitian(op_info, device, dtype, requires_grad=False, **kwargs):\n \"\"\"\n This function generates input for torch.linalg.pinv with hermitian=True keyword argument.\n \"\"\"\n out = sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad, **kwargs)\n for o in out:\n o.kwargs = {\"hermitian\": True}\n return out\n\ndef sample_inputs_linalg_solve(op_info, device, dtype, requires_grad=False, vector_rhs_allowed=True, **kwargs):\n \"\"\"\n This function generates always solvable input for torch.linalg.solve\n Using random_fullrank_matrix_distinct_singular_value gives a non-singular (=invertible, =solvable) matrices 'a'.\n The first input to torch.linalg.solve is generated as the itertools.product of 'batches' and 'ns'.\n The second input is generated as the product of 'batches', 'ns' and 'nrhs'.\n In total this function generates 18 SampleInputs\n 'batches' cases include:\n () - single input,\n (0,) - zero batched dimension,\n (2,) - batch of two matrices.\n 'ns' gives 0x0 and 5x5 matrices.\n and 'nrhs' controls the number of vectors to solve for:\n () - using 1 as the number of vectors implicitly\n (1,) - same as () but explicit\n (3,) - solve for 3 vectors.\n Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.\n 'vector_rhs_allowed' controls whether to include nrhs = () to the list of SampleInputs.\n torch.solve / triangular_solve / cholesky_solve (opposed to torch.linalg.solve) do not allow\n 1D tensors (vectors) as the right-hand-side.\n Once torch.solve / triangular_solve / cholesky_solve and its testing are removed,\n 'vector_rhs_allowed' may be removed here as well.\n \"\"\"\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n batches = [(), (0, ), (2, )]\n ns = [5, 0]\n if vector_rhs_allowed:\n nrhs = [(), (1,), (3,)]\n else:\n nrhs = [(1,), (3,)]\n out = []\n for n, batch, rhs in product(ns, batches, nrhs):\n a = random_fullrank_matrix_distinct_singular_value(n, *batch, dtype=dtype, device=device)\n a.requires_grad = requires_grad\n b = torch.randn(*batch, n, *rhs, dtype=dtype, device=device)\n b.requires_grad = requires_grad\n out.append(SampleInput(a, args=(b,)))\n return out\n\n\ndef sample_inputs_legacy_solve(op_info, device, dtype, requires_grad=False, **kwargs):\n \"\"\"\n This function generates always solvable input for legacy solve functions\n (the ones that are not in torch.linalg module).\n The difference from sample_inputs_linalg_solve is that here the right-hand-side of A x = b equation\n should have b.ndim >= 2, vectors are not allowed.\n Also the arguments order is swapped.\n \"\"\"\n out = sample_inputs_linalg_solve(\n op_info, device, dtype, requires_grad=requires_grad, vector_rhs_allowed=False\n )\n\n # Reverses tensor order\n for sample in out:\n sample.input, sample.args = sample.args[0], (sample.input,)\n\n return out\n\n\ndef sample_inputs_lu(op_info, device, dtype, requires_grad=False, **kwargs):\n # not needed once OpInfo tests support Iterables\n def generate_samples():\n batch_shapes = ((), (3,), (3, 3))\n for batch_shape, get_infos in product(batch_shapes, (True, False)):\n shape = batch_shape + (S, S)\n input = make_tensor(shape, device, dtype, requires_grad=requires_grad, low=None, high=None)\n yield SampleInput(input, args=(True, get_infos))\n\n return list(generate_samples())\n\n\ndef sample_inputs_lu_solve(op_info, device, dtype, requires_grad=False, **kwargs):\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n batches = [(), (0, ), (2, )]\n ns = [5, 3, 0]\n nrhs = [0, 1, 6]\n\n def generate_samples():\n for n, batch, rhs in product(ns, batches, nrhs):\n a = random_fullrank_matrix_distinct_singular_value(n, *batch, dtype=dtype, device=device)\n requires_grad_options = (False,) if not requires_grad else (True, False)\n # we try all possible combinations of requires_grad for each input\n for lu_requires_grad, b_requires_grad in product(requires_grad_options, requires_grad_options):\n # when requires_grad == True, at least one input has to have requires_grad enabled\n if requires_grad and not lu_requires_grad and not b_requires_grad:\n continue\n # we run LU several times to guarantee that the produced SampleInputs are independent\n # this is especially important when setting different requries_grad for same tensors!\n lu, pivs = a.lu()\n lu.requires_grad = lu_requires_grad\n b = torch.randn(*batch, n, rhs, dtype=dtype, device=device)\n b.requires_grad = b_requires_grad\n yield SampleInput(b, args=(lu, pivs))\n\n return list(generate_samples())\n\n\ndef sample_inputs_lu_unpack(op_info, device, dtype, requires_grad=False, **kwargs):\n # not needed once OpInfo tests support Iterables\n def generate_samples():\n for lu_sample in sample_inputs_lu(op_info, device, dtype, requires_grad, **kwargs):\n lu_data, pivots = lu_sample.input.lu()\n yield SampleInput(lu_data, args=(pivots,))\n\n # generate rectangular inputs\n lu_data_shape = lu_data.shape\n batch_shape = lu_data_shape[:-2]\n n = lu_data_shape[-2]\n\n for shape_inc in ((1, 0), (0, 1)):\n lu_data, pivots = make_tensor(\n batch_shape + (n + shape_inc[0], n + shape_inc[1]),\n device, dtype,\n requires_grad=False,\n low=None, high=None\n ).lu()\n lu_data.requires_grad_(requires_grad)\n yield SampleInput(lu_data, args=(pivots,))\n\n return list(generate_samples())\n\n\ndef sample_inputs_roll(op_info, device, dtype, requires_grad=False, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n args = ((0, 0), (1, 2), (0, 2), (2, 0), (-1, 0), (10000, 1), (2,), ((1, 2, -1), (0, 1, 2)))\n\n def generator():\n for arg in args:\n yield SampleInput(make_arg((S, S, S)), args=arg)\n\n return list(generator())\n\n\ndef sample_inputs_rot90(op_info, device, dtype, requires_grad=False, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n args = ((1, (0, 1),),\n (1, (1, 2),),\n (1, (1, -1),),\n ())\n\n def generator():\n for arg in args:\n yield SampleInput(make_arg((S, S, S)), args=arg)\n\n return list(generator())\n\n\ndef sample_inputs_std_var(op_info, device, dtype, requires_grad, **kwargs):\n tensor_nd = make_tensor((S, S, S), device=device, dtype=dtype,\n low=None, high=None, requires_grad=requires_grad)\n tensor_1d = make_tensor((S,), device=device, dtype=dtype,\n low=None, high=None, requires_grad=requires_grad)\n\n return [\n SampleInput(tensor_nd),\n SampleInput(tensor_nd, kwargs=dict(dim=1)),\n SampleInput(tensor_nd, kwargs=dict(dim=1, unbiased=True, keepdim=True)),\n SampleInput(tensor_1d, kwargs=dict(dim=0, unbiased=True, keepdim=True)),\n SampleInput(tensor_1d, kwargs=dict(dim=0, unbiased=False, keepdim=False)),\n\n SampleInput(tensor_nd, kwargs=dict(dim=(1,), correction=S // 2)),\n SampleInput(tensor_nd, kwargs=dict(dim=None, correction=0, keepdim=True)),\n ]\n\n\ndef _generate_correlation_inputs(device, dtype, requires_grad):\n shapes = [(2,), (1, 2), (3, 2), (2, 3)]\n for shape in shapes:\n yield make_tensor(shape, device, dtype, requires_grad=requires_grad)\n\n\ndef sample_inputs_corrcoef(op_info, device, dtype, requires_grad, **kwargs):\n return [SampleInput(t) for t in _generate_correlation_inputs(device, dtype, requires_grad)]\n\n\ndef sample_inputs_cov(op_info, device, dtype, requires_grad, **kwargs):\n inputs = []\n for t in _generate_correlation_inputs(device, dtype, requires_grad):\n inputs.append(SampleInput(t))\n num_observations = t.numel() if t.ndimension() < 2 else t.size(1)\n fweights = make_tensor((num_observations,), device, torch.int, low=0, high=10, requires_grad=requires_grad)\n aweights = make_tensor((num_observations,), device, torch.float, low=0, high=1, requires_grad=requires_grad)\n for correction, fw, aw in product(range(num_observations), [None, fweights], [None, aweights]):\n inputs.append(SampleInput(t, kwargs={'correction': correction, 'fweights': fw, 'aweights': aw}))\n return inputs\n\n\ndef _sample_inputs_svd(op_info, device, dtype, requires_grad=False, is_linalg_svd=False):\n \"\"\"\n This function generates input for torch.svd with distinct singular values so that autograd is always stable.\n Matrices of different size:\n square matrix - S x S size\n tall marix - S x (S-2)\n wide matrix - (S-2) x S\n and batched variants of above are generated.\n Each SampleInput has a function 'output_process_fn_grad' attached to it that is applied on the output of torch.svd\n It is needed for autograd checks, because backward of svd doesn't work for an arbitrary loss function.\n \"\"\"\n from torch.testing._internal.common_utils import random_fullrank_matrix_distinct_singular_value\n\n # svd and linalg.svd returns V and V.conj().T, respectively. So we need to slice\n # along different dimensions when needed (this is used by\n # test_cases2:wide_all and wide_all_batched below)\n if is_linalg_svd:\n def slice_V(v):\n return v[..., :(S - 2), :]\n\n def uv_loss(usv):\n u00 = usv[0][0, 0]\n v00_conj = usv[2][0, 0]\n return u00 * v00_conj\n else:\n def slice_V(v):\n return v[..., :, :(S - 2)]\n\n def uv_loss(usv):\n u00 = usv[0][0, 0]\n v00_conj = usv[2][0, 0].conj()\n return u00 * v00_conj\n\n test_cases1 = ( # some=True (default)\n # loss functions for complex-valued svd have to be \"gauge invariant\",\n # i.e. loss functions shouldn't change when sigh of the singular vectors change.\n # the simplest choice to satisfy this requirement is to apply 'abs'.\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),\n lambda usv: usv[1]), # 'check_grad_s'\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),\n lambda usv: abs(usv[0])), # 'check_grad_u'\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),\n lambda usv: abs(usv[2])), # 'check_grad_v'\n # this test is important as it checks the additional term that is non-zero only for complex-valued inputs\n # and when the loss function depends both on 'u' and 'v'\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device),\n uv_loss), # 'check_grad_uv'\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:(S - 2)],\n lambda usv: (abs(usv[0]), usv[1], abs(usv[2][..., :, :(S - 2)]))), # 'wide'\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:, :(S - 2)],\n lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'tall'\n (random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device),\n lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'batched'\n (random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :(S - 2), :],\n lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'wide_batched'\n (random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :, :(S - 2)],\n lambda usv: (abs(usv[0]), usv[1], abs(usv[2]))), # 'tall_batched'\n )\n test_cases2 = ( # some=False\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:(S - 2)],\n lambda usv: (abs(usv[0]), usv[1], abs(slice_V(usv[2])))), # 'wide_all'\n (random_fullrank_matrix_distinct_singular_value(S, dtype=dtype).to(device)[:, :(S - 2)],\n lambda usv: (abs(usv[0][:, :(S - 2)]), usv[1], abs(usv[2]))), # 'tall_all'\n (random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :(S - 2), :],\n lambda usv: (abs(usv[0]), usv[1], abs(slice_V(usv[2])))), # 'wide_all_batched'\n (random_fullrank_matrix_distinct_singular_value(S, 2, dtype=dtype).to(device)[..., :, :(S - 2)],\n lambda usv: (abs(usv[0][..., :, :(S - 2)]), usv[1], abs(usv[2]))), # 'tall_all_batched'\n )\n\n out = []\n for a, out_fn in test_cases1:\n a.requires_grad = requires_grad\n if is_linalg_svd:\n kwargs = {'full_matrices': False}\n else:\n kwargs = {'some': True}\n out.append(SampleInput(a, kwargs=kwargs, output_process_fn_grad=out_fn))\n\n for a, out_fn in test_cases2:\n a.requires_grad = requires_grad\n if is_linalg_svd:\n kwargs = {'full_matrices': True}\n else:\n kwargs = {'some': False}\n out.append(SampleInput(a, kwargs=kwargs, output_process_fn_grad=out_fn))\n\n return out\n\n\ndef sample_inputs_permute(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = [((1, 2, 3, 4), (0, 2, 3, 1)),\n ((1, 2, 3, 4), (0, -2, -1, 1)),\n ((), ()),\n ((1, 2, 3, 4), (2, 1, 3, 0))]\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=(args,))\n\n return list(generator())\n\n\n# Based on erstwhile method_tests tests & some tensor_op_tests for pow\ndef sample_inputs_pow(op_info, device, dtype, requires_grad, **kwargs):\n samples = []\n\n if dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64]:\n test_cases = (\n ((2, 2), 0, 5, 1e-3, requires_grad, (2, 2), 0, 1, 0.1, requires_grad, False),\n ((2, 2), 0, 5, 1e-3, requires_grad, (1,), 0, 1, 0.1, requires_grad, False),\n ((), 1e-3, 1e-3 + 1, 0, requires_grad, (), 0.1, 1.1, 0, False, False),\n ((2, 2), 0, 5, 1e-3, requires_grad, (), 0.1, 1.1, 1, False, False),\n )\n tests_require_resizing = (\n ((1,), 0, 5, 1e-3, requires_grad, (2, 2), 0, 1, 0.1, requires_grad, requires_grad),\n ((2, 1, 2), 0, 5, 1e-3, requires_grad, (1, 2, 1), 0, 1, 0.1, requires_grad, requires_grad),\n ((), 1e-3, 1e-3 + 1, 0, requires_grad, (1, S, 1), 0, 1, 0.1, requires_grad, requires_grad),\n )\n cases = test_cases + tests_require_resizing\n samples = list(SampleInput(make_tensor(shape_b, low=low_b, high=high_b,\n requires_grad=b_grad, device=device,\n dtype=dtype) + additive_b,\n args=(make_tensor(shape_e, low=low_e, high=high_e,\n requires_grad=e_grad, device=device,\n dtype=dtype) + additive_e,),\n broadcasts_input=broadcasts_input)\n for shape_b, low_b, high_b, additive_b, b_grad, shape_e, low_e,\n high_e, additive_e, e_grad, broadcasts_input in cases)\n tensor_scalar_inputs = (\n ((2, 2), 0, 5, 1e-3, requires_grad, (3.14,)),\n ((), 1e-3, 1e-3 + 1, 0, requires_grad, (3.14,))\n )\n more_samples = list(SampleInput(make_tensor(shape, dtype=dtype, device=device,\n high=high, low=low,\n requires_grad=b_grad) + additive,\n args=exp)\n for shape, low, high, additive, b_grad, exp in tensor_scalar_inputs)\n samples = [*samples, *more_samples]\n elif dtype in [torch.complex64, torch.complex128]:\n args_tuple = (\n ((2, 2), 0, 5, requires_grad, (3.14,)),\n ((), 0, 1, requires_grad, (3.14,)),\n ((), 0, 1, requires_grad, (3.14j,))\n )\n samples = list(SampleInput(make_tensor(shape, dtype=dtype, device=device,\n high=high, low=low,\n requires_grad=b_grad) + 1e-3 * (1 + 1j),\n args=arg)\n for shape, low, high, b_grad, arg in args_tuple)\n elif dtype == torch.bool:\n arg_tuple = (0, 1, 1., 2.3)\n samples = list(SampleInput(make_tensor((2, 2), device=device, dtype=dtype,\n requires_grad=requires_grad),\n args=(arg,))\n for arg in arg_tuple)\n dtypes_list = [torch.float64, torch.float32, torch.int64, torch.int32]\n more_samples = list(SampleInput(make_tensor((2, 2), device, dtype=torch.bool,\n requires_grad=requires_grad),\n args=(make_tensor((2, 2), device, dtype=dtype,\n requires_grad=requires_grad),))\n for dtype in dtypes_list)\n samples = [*samples, *more_samples]\n samples.append(SampleInput(make_tensor((2, 2, 2), device, dtype=torch.bool,\n requires_grad=requires_grad),\n args=(make_tensor((2, 1), device, dtype=torch.float64,\n requires_grad=requires_grad),)))\n else:\n exp_tuple = (1, 2, 3)\n samples = list(SampleInput(make_tensor((2, 2), device, dtype,\n requires_grad=requires_grad),\n args=(arg,))\n for arg in exp_tuple)\n samples.append(SampleInput(make_tensor((2, 2), device, dtype,\n requires_grad=requires_grad),\n args=(make_tensor((2, 2), device, dtype,\n requires_grad=requires_grad),)))\n return tuple(samples)\n\ndef sample_inputs_svd(op_info, device, dtype, requires_grad=False, **kwargs):\n return _sample_inputs_svd(op_info, device, dtype, requires_grad, is_linalg_svd=False)\n\ndef sample_inputs_linalg_svd(op_info, device, dtype, requires_grad=False, **kwargs):\n return _sample_inputs_svd(op_info, device, dtype, requires_grad, is_linalg_svd=True)\n\ndef sample_inputs_linalg_svdvals(op_info, device, dtype, requires_grad=False, **kwargs):\n batches = [(), (0, ), (2, ), (1, 1)]\n ns = [5, 2, 0]\n samples = []\n for batch, (m, n) in product(batches, product(ns, ns)):\n a = make_tensor((*batch, m, n), device, dtype, low=None, high=None, requires_grad=requires_grad)\n samples.append(SampleInput(a))\n return samples\n\ndef sample_inputs_hardshrink_hardtanh(op_info, device, dtype, requires_grad=False, **kwargs):\n N = 10\n tensors = [SampleInput(make_tensor((N, N), device=device, dtype=dtype,\n requires_grad=requires_grad)) for _ in range(1, N)]\n return tensors\n\ndef sample_inputs_eig(op_info, device, dtype, requires_grad=False, **kwargs):\n eigvecs = make_tensor((S, S), device=device, dtype=dtype,\n low=None, high=None)\n eigvals = make_tensor((S,), device=device, dtype=dtype,\n low=None, high=None)\n # we produce only diagonazible inputs which do not have\n # complex eigenvalues for real inputs, as there is no\n # backward implementation for real inputs with complex\n # eigenvalues yet.\n input = (eigvecs * eigvals.unsqueeze(-2)) @ eigvecs.inverse()\n input.requires_grad_(requires_grad)\n\n def process_output(eigpair):\n eigvals, eigvecs = eigpair\n if dtype.is_complex:\n # eig produces eigenvectors which are normalized to 1 norm.\n # Note that if v is an eigenvector, so is v * e^{i \\phi},\n # and |v| = |v * e^{i \\phi}| = 1.\n # This, however, makes the eigenvector backward computation process\n # rather unstable unless the objective function is gauge-invariant,\n # that is if f(z) == f(|z|), for example.\n # Hence for complex inputs we ignore the phases and return only\n # the absolute values.\n return eigvals, eigvecs.abs()\n else:\n return eigvals, eigvecs\n\n return [\n SampleInput(\n input,\n kwargs=dict(eigenvectors=True),\n output_process_fn_grad=process_output\n ),\n ]\n\n\ndef sample_inputs_einsum(op_info, device, dtype, requires_grad=False, **kwargs):\n x = make_tensor((3,), device, dtype, requires_grad=requires_grad)\n y = make_tensor((4,), device, dtype, requires_grad=requires_grad)\n A = make_tensor((2, 3,), device, dtype, requires_grad=requires_grad, noncontiguous=True)\n B = make_tensor((1, 3,), device, dtype, requires_grad=requires_grad)\n C = make_tensor((1, 2, 3,), device, dtype, requires_grad=requires_grad)\n D = make_tensor((1, 3, 4,), device, dtype, requires_grad=requires_grad, noncontiguous=True)\n E = make_tensor((4, 4,), device, dtype, requires_grad=requires_grad)\n H = make_tensor((3, 3,), device, dtype, requires_grad=requires_grad, noncontiguous=True)\n I = make_tensor((1, 3, 1,), device, dtype, requires_grad=requires_grad)\n\n inputs = []\n\n # Vector operations\n inputs.append(SampleInput([x], args=('i->',))) # sum\n inputs.append(SampleInput([x, y], args=('i,j->ij',))) # outer\n\n # Matrix operations\n inputs.append(SampleInput([A], args=(\"ij->i\",))) # col sum\n inputs.append(SampleInput([A, B], args=(\"ij,kj->ik\",))) # matmul\n inputs.append(SampleInput([A, E], args=(\"ij,Ab->ijAb\",))) # matrix outer product\n\n # Tensor operations\n inputs.append(SampleInput([C, D], args=(\"aij,ajk->aik\",))) # batch matmul\n inputs.append(SampleInput([D, E], args=(\"aij,jk->aik\",))) # tensor matrix contraction\n inputs.append(SampleInput([C, B], args=(\"ijk,ik->j\",))) # non contiguous\n\n # Test diagonals\n inputs.append(SampleInput([I], args=('iji->j',))) # non-contiguous trace\n\n # Test ellipsis\n inputs.append(SampleInput([H], args=(\"i...->...\",)))\n inputs.append(SampleInput([C, x], args=('...ik, ...j -> ij',)))\n\n return inputs\n\n\ndef sample_inputs_linalg_qr(op_info, device, dtype, requires_grad=False, **kwargs):\n \"\"\"\n This function generates input for torch.linalg.qr\n The input is generated as the itertools.product of 'batches' and 'ns'.\n \"\"\"\n batches = [(), (0,), (2, ), (1, 1)]\n ns = [5, 2, 0]\n out = []\n for batch, (m, n) in product(batches, product(ns, ns)):\n a = torch.randn(*batch, m, n, dtype=dtype, device=device, requires_grad=requires_grad)\n out.append(SampleInput(a))\n return out\n\ndef sample_inputs_geqrf(op_info, device, dtype, requires_grad=False):\n batches = [(), (0, ), (2, ), (1, 1)]\n ns = [5, 2, 0]\n samples = []\n for batch, (m, n) in product(batches, product(ns, ns)):\n # TODO: CUDA path doesn't work with batched or empty inputs\n if torch.device(device).type == 'cuda' and (batch != () or m == 0 or n == 0):\n continue\n a = make_tensor((*batch, m, n), device, dtype, low=None, high=None, requires_grad=requires_grad)\n samples.append(SampleInput(a))\n return samples\n\ndef sample_inputs_flip(op_info, device, dtype, requires_grad):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n sizes = ((S, M, S), (S, 0, M))\n all_dims = ((0, 1, 2), (0,), (0, 2), (-1,), ())\n\n def gen_samples():\n for size, dims in product(sizes, all_dims):\n yield SampleInput(make_arg(size), kwargs={\"dims\": dims})\n\n return list(gen_samples())\n\ndef sample_inputs_fliplr_flipud(op_info, device, dtype, requires_grad, **kwargs):\n tensors = (\n make_tensor((S, M, S), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((S, 0, M), device, dtype, low=None, high=None, requires_grad=requires_grad)\n )\n return [SampleInput(tensor) for tensor in tensors]\n\ndef sample_inputs_fmod_remainder(op_info, device, dtype, requires_grad, *, autodiffed=False, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n if autodiffed:\n samples = (\n ((S, S, S), 1.5, False),\n ((), 1.5, False),\n )\n else:\n cases = (\n ((S, S, S), (), False),\n ((S, S, S), (S, S, S), False),\n ((S, S, S), (S,), False),\n )\n\n # Sample inputs with scalars as torch tensors\n cases_with_tensor_scalar = (\n ((), torch.tensor(1, dtype=dtype, device=device, requires_grad=False), False),\n )\n\n # Sample inputs with broadcasting\n cases_with_broadcasting = (\n ((S,), (S, S, S), True),\n ((S, 1, S), (S, S, S), True),\n ((), (S, S, S), True),\n )\n\n samples = cases + cases_with_tensor_scalar + cases_with_broadcasting # type: ignore[assignment]\n\n def generator():\n for shape, arg_other, broadcasts_input in samples:\n if isinstance(arg_other, tuple):\n arg = make_arg(arg_other, requires_grad=False, exclude_zero=True)\n else:\n # shape_other is scalar or torch.tensor\n arg = arg_other\n yield(SampleInput(make_arg(shape), args=(arg,), broadcasts_input=broadcasts_input))\n\n return list(generator())\n\n# TODO: clamp shares tensors among its sample inputs --- we should prohibit this!\ndef sample_inputs_clamp(op_info, device, dtype, requires_grad, **kwargs):\n x = make_tensor((S, M, S), device, dtype, low=None, high=None, requires_grad=requires_grad)\n lb = make_tensor((S, M, S), device, dtype, low=None, high=None, requires_grad=requires_grad)\n ub = make_tensor((S, M, S), device, dtype, low=None, high=None, requires_grad=requires_grad)\n\n def detach(tensor):\n return tensor.clone().detach_().requires_grad_(requires_grad)\n\n return [\n SampleInput(detach(x), args=(lb, ub)),\n SampleInput(detach(x), args=(detach(lb[0]), detach(ub[0]))),\n SampleInput(detach(x), args=(detach(lb[:, :1]),)),\n ]\n\ndef sample_inputs_clamp_scalar(op_info, device, dtype, requires_grad):\n tensors = (\n make_tensor((2, 3, 2), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((2, 0, 3), device, dtype, low=None, high=None, requires_grad=requires_grad),\n )\n if dtype is torch.uint8:\n min_max_vals = ((2, 5), (3, 7))\n else:\n min_max_vals = ((0, 1), (-1, 1))\n output = [SampleInput(tensor, args=vals) for tensor, vals in product(tensors, min_max_vals)]\n output += [SampleInput(tensors[0], args=(0.5, None)), SampleInput(tensors[0], args=(None, 0.5))]\n empty_tensor = make_tensor((), device=device, dtype=dtype, low=None, high=None, requires_grad=requires_grad)\n output += [SampleInput(empty_tensor, args=(0.0, 1.0)), ]\n return output\n\ndef sample_kwargs_clamp_scalar(device, dtype, input):\n if dtype is torch.uint8:\n min_val, max_val = (random.randint(1, 3), random.randint(4, 8))\n elif dtype.is_floating_point:\n min_val, max_val = (random.uniform(-8, 0), random.uniform(1, 8)) # type: ignore[assignment]\n else:\n min_val, max_val = (random.randint(-8, 0), random.randint(1, 8))\n return {'min': min_val, 'max': max_val}, {'a_min': min_val, 'a_max': max_val}\n\ndef sample_inputs_cross(op_info, device, dtype, requires_grad, **kwargs):\n sample0 = SampleInput(make_tensor((S, 3), device=device, dtype=dtype, requires_grad=requires_grad),\n args=(make_tensor((S, 3), device=device, dtype=dtype, requires_grad=requires_grad),))\n sample1 = SampleInput(make_tensor((S, 3, S), device=device, dtype=dtype, requires_grad=requires_grad),\n args=(make_tensor((S, 3, S), device=device, dtype=dtype, requires_grad=requires_grad),),\n kwargs={'dim': 1})\n\n return (sample0, sample1)\n\ndef sample_inputs_cumprod(op_info, device, dtype, requires_grad, **kwargs):\n def make_arg(shape):\n # shrink values to be in the interval [-1, +1] for better precision in gradgradcheck\n return make_tensor(shape, device, dtype, low=-1, high=+1, requires_grad=requires_grad)\n\n def prod_zeros(dim_select):\n assert len(dim_select) == 2\n result = make_arg(3 * (S,))\n with torch.no_grad():\n result.narrow(dim_select[0], 0, 1).narrow(dim_select[1], 1, 1).zero_()\n result.narrow(dim_select[0], 2, 1).narrow(dim_select[1], 3, 1).zero_()\n result.narrow(dim_select[0], 4, 1).narrow(dim_select[1], 3, 1).zero_()\n return result\n\n # will not be needed once OpInfo tests suport Iterables\n def sample_generator():\n for dim in range(3):\n yield SampleInput(make_arg((S, S, S)), args=(dim,))\n # Scalar tensors and empty tensor\n for size in [(), (1,), (0,)]:\n yield SampleInput(make_arg(size), args=(0,))\n\n yield SampleInput(prod_zeros([0, 1]), args=(1,))\n yield SampleInput(prod_zeros([0, 2]), args=(1,))\n yield SampleInput(prod_zeros([1, 2]), args=(1,))\n\n # test dtype kwarg\n yield SampleInput(prod_zeros([1, 2]), args=(1,), kwargs={'dtype': dtype})\n\n return list(sample_generator())\n\ndef sample_inputs_view_as_complex(op_info, device, dtype, requires_grad, **kwargs):\n return [SampleInput(make_tensor((S, 2), device, dtype, requires_grad=requires_grad),)]\n\ndef sample_inputs_view_as_real(op_info, device, dtype, requires_grad, **kwargs):\n tensors = (\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n make_tensor((), device, dtype, requires_grad=requires_grad)\n )\n return [SampleInput(tensor) for tensor in tensors]\n\ndef sample_inputs_copysign(op_info, device, dtype, requires_grad, **kwargs):\n def _make_tensor(*shape, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n cases = [\n # no broadcast\n ((S, S, S), (S, S, S), False),\n # broadcast rhs\n ((S, S, S), (S, S), False),\n\n # scalar\n ((S, S), 3.14, False),\n # scalar positive zero\n ((S, S), 0.0, False),\n # scalar negative zero\n ((S, S), -0.0, False),\n ]\n\n # broadcast lhs\n cases.append(((S, S), (S, S, S), True))\n # broadcast all\n cases.append(((S, 1, S), (M, S), True))\n\n def generator():\n for input_shape, arg_val, broadcasts_input in cases:\n if isinstance(arg_val, tuple):\n arg = _make_tensor(*arg_val)\n else:\n # arg_val is scalar\n arg = arg_val\n\n yield SampleInput(_make_tensor(*input_shape), args=(arg, ), broadcasts_input=broadcasts_input)\n\n return list(generator())\n\ndef sample_inputs_prod(op_info, device, dtype, requires_grad):\n def make_arg(shape):\n # shrink values to be in the interval [-1, +1] for better precision in gradgradcheck\n return make_tensor(shape, device, dtype, low=-1, high=+1, requires_grad=requires_grad)\n\n def prod_single_zero():\n result = make_arg(2 * (S,))\n with torch.no_grad():\n result[0, 1] = 0\n return result\n\n # will not be needed once OpInfo tests support Iterables\n def sample_generator():\n for sample in sample_inputs_cumprod(op_info, device, dtype, requires_grad):\n yield SampleInput(sample.input) # only Tensor, ignore other inputs\n yield sample\n sample.kwargs['keepdim'] = True\n yield sample\n yield SampleInput(prod_single_zero())\n yield SampleInput(make_arg((3, 3, 3)), args=(1,))\n yield SampleInput(make_arg((3, 3, 3)), args=(1,), kwargs={'keepdim': True})\n\n # test zero scalar tensor\n zero = make_arg(())\n with torch.no_grad():\n zero.zero_()\n yield SampleInput(zero)\n yield SampleInput(zero, args=(0,))\n yield SampleInput(zero, args=(0,), kwargs={'keepdim': True})\n\n return list(sample_generator())\n\n\ndef sample_inputs_nextafter(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n cases = (\n ((S, S), (S, S), False),\n ((S, S), (S,), False),\n ((S, ), (S, S), True)\n )\n\n def generator():\n for shape, other_shape, broadcasts_input in cases:\n yield SampleInput(make_arg(shape), args=(make_arg(other_shape),), broadcasts_input=broadcasts_input)\n\n return list(generator())\n\n\ndef sample_inputs_diag(op_info, device, dtype, requires_grad, **kwargs):\n vec_sample = SampleInput(make_tensor((M, ), device, dtype, low=None, high=None, requires_grad=requires_grad))\n\n tensors = (\n make_tensor((M, M), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((3, 5), device, dtype, low=None, high=None, requires_grad=requires_grad),\n make_tensor((5, 3), device, dtype, low=None, high=None, requires_grad=requires_grad),\n )\n\n args = ((), (2,), (-2,), (1,), (2,))\n\n samples = []\n for tensor, arg in product(tensors, args):\n samples.append(SampleInput(tensor, args=arg))\n\n return samples + [vec_sample]\n\ndef sample_inputs_diagonal_diag_embed(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n # Shapes for 2D Tensors\n shapes_2d = ((M, M), (3, 5), (5, 3))\n\n # Shapes for 3D Tensors\n shapes_3d = ((M, M, M),)\n\n args_2d = ((), (2,), (-2,), (1,))\n args_3d = ((1, 1, 2), (2, 0, 1), (-2, 0, 1))\n\n def generator():\n for shape, arg in chain(product(shapes_2d, args_2d), product(shapes_3d, args_3d)):\n yield SampleInput(make_arg(shape), args=arg)\n\n return list(generator())\n\n\ndef sample_inputs_to_sparse(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n return (SampleInput(make_arg((S, S)), args=(), output_process_fn_grad=lambda x: x.to_dense()),\n SampleInput(make_arg((S, S)), args=(1,), output_process_fn_grad=lambda x: x.to_dense()),)\n\n\n# Used for both log_softmax and softmax\ndef sample_inputs_softmax_variant(op_info, device, dtype, requires_grad, with_dtype=False, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = [\n ((S, ), (0, )),\n ((S, S), (0, )),\n ((S, S), (1, )),\n ((S, S), (-1, )),\n ((S, M, S), (2, )),\n ]\n\n # PyTorch on XLA throws an error when passed with dim argument for 0d tensor.\n # See https://github.com/pytorch/xla/issues/3061 for more details.\n if torch.device(device).type != 'xla':\n cases.append(((), (0, )))\n\n return [\n SampleInput(make_arg(shape), args=dim, kwargs=dict(dtype=torch.float64) if with_dtype else None)\n for shape, dim in cases\n ]\n\n\ndef sample_inputs_logit(op_info, device, dtype, requires_grad, **kwargs):\n low, high = op_info.domain\n\n # Note: Operator is very sensitive at points near the\n # start and end of domain and leads to NaN for float16\n # if domain_eps is 1e-5.\n domain_eps = op_info._domain_eps if dtype != torch.float16 else 3e-2\n\n low = low + domain_eps\n high = high - domain_eps\n\n samples = (\n SampleInput(make_tensor((S, S, S), device, dtype, low=low, high=high, requires_grad=requires_grad)),\n SampleInput(make_tensor((S, S, S), device, dtype, low=low,\n high=high, requires_grad=requires_grad), args=(0.2,)),\n SampleInput(make_tensor((), device, dtype, low=low, high=high, requires_grad=requires_grad)),\n SampleInput(make_tensor((), device, dtype, low=low,\n high=high, requires_grad=requires_grad), args=(0.2,)),\n )\n\n return samples\n\ndef sample_inputs_floor_divide(op_info, device, dtype, requires_grad, **kwargs):\n lhs = make_tensor((S, S, S), device, dtype, low=None, high=None, requires_grad=requires_grad)\n rhs = make_tensor((S, S, S), device, dtype, low=None, high=None, requires_grad=requires_grad)\n # Avoid integer divide by 0\n if not (dtype.is_floating_point or dtype.is_complex):\n rhs[rhs == 0] = 1\n\n return [\n SampleInput(lhs, args=(rhs,)),\n SampleInput(lhs, args=(rhs[0],)),\n SampleInput(lhs, args=(3.14,)),\n ]\n\ndef sample_inputs_isin(op_info, device, dtype, requires_grad):\n element = make_tensor((L,), device, dtype, low=None, high=None, requires_grad=requires_grad)\n indices = torch.randint(0, L, size=[S])\n test_elements = element[indices].clone()\n return [\n SampleInput(element, args=(test_elements,))\n ]\n\ndef sample_inputs_masked_scatter(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n def samples_generator():\n yield SampleInput(make_arg((S, S)), args=(torch.randn(S, S, device=device) > 0, make_arg((S, S))))\n yield SampleInput(make_arg((S, S)), args=(torch.randn((S,), device=device) > 0, make_arg((S, S))))\n yield SampleInput(make_arg((S, S)), args=(bernoulli_scalar().to(device), make_arg((S, S))))\n yield SampleInput(make_arg((S,)),\n args=(torch.randn(S, S, device=device) > 0, make_arg((S, S))),\n broadcasts_input=True)\n\n samples = tuple(samples_generator())\n return samples\n\n\ndef sample_inputs_masked_fill(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n def sample_generator():\n yield SampleInput(make_arg((S, S)), args=(torch.randn(S, S, device=device) > 0, 10))\n yield SampleInput(make_arg((S, S)), args=(torch.randn(S, S, device=device) > 0, make_arg(())))\n yield SampleInput(make_arg((S, S)), args=(torch.randn(S, device=device) > 0, 10))\n yield SampleInput(make_arg(()), args=(torch.randn((), device=device) > 0, 10))\n yield SampleInput(make_arg(()), args=(torch.randn((), device=device) > 0, make_arg(())))\n yield SampleInput(make_arg((S, S)), args=(torch.randn((), device=device) > 0, 10))\n\n yield SampleInput(make_arg((S,)),\n args=(torch.randn(S, S, device=device) > 0, make_arg(())),\n broadcasts_input=True)\n yield SampleInput(make_arg((S,)),\n args=(torch.randn(S, S, device=device) > 0, 10),\n broadcasts_input=True)\n\n samples = tuple(sample_generator())\n return samples\n\ndef sample_inputs_masked_select(op_info, device, dtype, requires_grad, **kwargs):\n samples = (\n SampleInput(make_tensor((M, M), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(torch.randn(M, M, device=device) > 0,)),\n\n SampleInput(make_tensor((M, M), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(torch.randn((M,), device=device) > 0,)),\n\n SampleInput(make_tensor((M,), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(torch.randn((M, M), device=device) > 0,)),\n\n SampleInput(make_tensor((M, 1, M), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(torch.randn((M, M), device=device) > 0,)),\n\n SampleInput(make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(torch.tensor(1, device=device, dtype=torch.bool),)),\n\n SampleInput(make_tensor((M, M), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(torch.tensor(1, device=device, dtype=torch.bool),)),\n\n SampleInput(make_tensor((), device, dtype, low=None, high=None, requires_grad=requires_grad),\n args=(torch.randn((M, M), device=device) > 0,)),\n )\n\n return samples\n\ndef sample_inputs_matrix_exp(op_info, device, dtype, requires_grad, **kwargs):\n samples = (\n SampleInput(make_tensor((S, S), device, dtype, requires_grad=requires_grad)),\n SampleInput(make_tensor((S, S, S), device, dtype, requires_grad=requires_grad)),\n )\n\n return samples\n\ndef sample_inputs_matmul(op_info, device, dtype, requires_grad):\n test_cases = (((L,), (L,)),\n ((S, M), (M,)),\n ((M,), (M, S)),\n ((S, M), (M, S)),\n ((S, S, M), (M,)),\n ((S, S, M), (M, S)),\n ((M,), (S, M, S)),\n ((S, M), (S, M, S)),\n ((S, S, M, M), (S, S, M, S)),\n ((S, S, M, M), (M,)),\n ((M,), (S, S, M, S)))\n sample_inputs = []\n for lhs_shape, rhs_shape in test_cases:\n lhs = make_tensor(lhs_shape, device, dtype, low=None, high=None, requires_grad=requires_grad)\n rhs = make_tensor(rhs_shape, device, dtype, low=None, high=None, requires_grad=requires_grad)\n if op_info.name == 'matmul':\n sample_inputs.append(SampleInput(lhs, args=(rhs,)))\n elif op_info.name == '__rmatmul__':\n sample_inputs.append(SampleInput(rhs, args=(lhs,)))\n else:\n raise RuntimeError(\"`op_info.name` must be 'matmul' or '__rmatmul__'\")\n return tuple(sample_inputs)\n\n\ndef sample_inputs_polar(op_info, device, dtype, requires_grad, **kwargs):\n def _make_tensor_helper(shape, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n samples = (\n SampleInput(_make_tensor_helper((S, S), low=0), args=(_make_tensor_helper((S, S)),)),\n SampleInput(_make_tensor_helper((), low=0), args=(_make_tensor_helper(()),)),\n )\n\n return samples\n\ndef sample_inputs_complex(op_info, device, dtype, requires_grad, **kwargs):\n def _make_tensor_helper(shape):\n return make_tensor(shape, device, dtype, requires_grad=requires_grad)\n\n samples = (\n SampleInput(_make_tensor_helper((S, S)), args=(_make_tensor_helper((S, S)),)),\n SampleInput(_make_tensor_helper(()), args=(_make_tensor_helper(()),)),\n )\n\n return samples\n\n\ndef sample_inputs_polygamma(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n tensor_shapes = ((S, S), ())\n ns = (1, 2, 3, 4, 5)\n\n def generator():\n for shape, n in product(tensor_shapes, ns):\n yield SampleInput(make_arg(shape), args=(n,))\n\n return list(generator())\n\n\ndef sample_inputs_mvlgamma(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n tensor_shapes = ((S, S), ())\n ns = (1, 2, 3, 4, 5)\n\n # Since the accepted lower bound for input\n # to mvlgamma depends on `p` argument,\n # the following function computes the lower bound\n # which we pass to `make_tensor`.\n def compute_min_val(p):\n return (p - 1.) / 2\n\n def generator():\n for shape, n in product(tensor_shapes, ns):\n min_val = compute_min_val(n)\n if not dtype.is_floating_point:\n # Round-up minimum value for integral dtypes\n min_val += 1\n yield SampleInput(make_arg(shape, low=min_val), args=(n,))\n\n return list(generator())\n\n\n# Since `mvlgamma` has multiple entries,\n# there are multiple common skips for the additional\n# entries. Following function is a helper to that end.\ndef skips_mvlgamma(skip_redundant=False):\n skips = (\n # outside domain values are hard error for mvlgamma op.\n SkipInfo('TestUnaryUfuncs', 'test_float_domains'),\n )\n if skip_redundant:\n # Redundant tests\n skips = skips + ( # type: ignore[assignment]\n SkipInfo('TestGradients'),\n SkipInfo('TestJit'),\n SkipInfo('TestCommon'),\n )\n return skips\n\n\n# To test reference numerics against multiple values of argument `p`,\n# we make multiple OpInfo entries with each entry corresponding to different value of p.\n# We run the op tests from test_ops.py only for `p=1` to avoid redundancy in testing.\n# Class `MvlGammaInfo` already contains the basic information related to the operator,\n# it only takes arguments like `domain`, `skips` and `sample_kwargs`, which\n# differ between the entries.\nclass MvlGammaInfo(UnaryUfuncInfo):\n def __init__(self, variant_test_name, domain, skips, sample_kwargs):\n super(MvlGammaInfo, self).__init__(\n 'mvlgamma',\n ref=reference_mvlgamma if TEST_SCIPY else _NOTHING,\n aliases=('special.multigammaln',),\n variant_test_name=variant_test_name,\n domain=domain,\n decorators=(precisionOverride({torch.float16: 5e-2}),),\n dtypes=all_types(),\n dtypesIfCPU=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.half),\n sample_inputs_func=sample_inputs_mvlgamma,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n skips=skips,\n sample_kwargs=sample_kwargs)\n\n\ndef sample_inputs_entr(op_info, device, dtype, requires_grad, **kwargs):\n low, _ = op_info.domain\n\n if requires_grad:\n low = 0 + op_info._domain_eps\n\n return (SampleInput(make_tensor((L,), device, dtype,\n low=low,\n requires_grad=requires_grad)),\n SampleInput(make_tensor((), device, dtype,\n low=low,\n requires_grad=requires_grad)))\n\n\ndef sample_inputs_zeta(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n samples = (SampleInput(make_arg((S,), low=1, requires_grad=requires_grad),\n args=(make_arg((S,), low=2, requires_grad=False),)),\n SampleInput(make_arg((S,), low=1, requires_grad=requires_grad),\n args=(3.,)),\n )\n\n return samples\n\n\n# TODO: Consolidate `i0e` with sample_inputs_unary when `make_tensor`,\n# supports `exclude` argument.\n# For more context: https://github.com/pytorch/pytorch/pull/56352#discussion_r633277617\ndef sample_inputs_i0_i1(op_info, device, dtype, requires_grad, **kwargs):\n\n samples = (SampleInput(make_tensor((S,), device, dtype,\n requires_grad=requires_grad)),\n SampleInput(make_tensor((), device, dtype,\n requires_grad=requires_grad)))\n\n if requires_grad and op_info.op == torch.special.i0e:\n # NOTE: `i0e`'s first-order gradient is not continous\n # at `0`, hence we don't test `i0e` with any input being `0`.\n # TODO: Remove this when `make_tensor` supports excluding `0`.\n with torch.no_grad():\n for sample in samples:\n t = sample.input\n t[t == 0] = torch.finfo(dtype).eps # type: ignore[index]\n elif requires_grad and op_info.op != torch.special.i0e:\n # Special Case for gradient\n # Sample with `0` in the input\n t = make_tensor((S,), device, dtype,\n requires_grad=requires_grad)\n\n with torch.no_grad():\n t[0] = 0\n\n samples += (SampleInput(t),) # type: ignore[assignment]\n\n return samples\n\n\ndef sample_inputs_rsub(op_info, device, dtype, requires_grad, variant='tensor', **kwargs):\n def _make_tensor_helper(shape, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n def _samples_with_alpha_helper(args, alphas, filter_fn=lambda arg_alpha: True):\n filtered_product = filter(filter_fn, product(args, alphas)) # type: ignore[var-annotated]\n return (SampleInput(input, args=(arg,), kwargs=dict(alpha=alpha))\n for (input, arg), alpha in filtered_product)\n\n int_alpha, float_alpha, complex_alpha = 2, 0.1, 1 + 0.6j\n\n if variant == 'tensor':\n samples = (\n SampleInput(_make_tensor_helper((S, S)), args=(_make_tensor_helper((S, S)),)),\n SampleInput(_make_tensor_helper((S, S)), args=(_make_tensor_helper((S,)),)),\n SampleInput(_make_tensor_helper((S,)), args=(_make_tensor_helper((S, S)),)),\n SampleInput(_make_tensor_helper(()), args=(_make_tensor_helper(()),)),\n SampleInput(_make_tensor_helper(()), args=(_make_tensor_helper((S,)),)),\n SampleInput(_make_tensor_helper((S,)), args=(_make_tensor_helper(()),)),\n )\n\n if dtype.is_complex:\n alphas = [int_alpha, float_alpha, complex_alpha]\n elif dtype.is_floating_point:\n alphas = [int_alpha, float_alpha]\n else:\n alphas = [int_alpha]\n\n args = ((_make_tensor_helper((S, S)), _make_tensor_helper((S, S))),\n (_make_tensor_helper((S, S)), _make_tensor_helper((S,))),\n (_make_tensor_helper(()), _make_tensor_helper(())))\n samples += tuple(_samples_with_alpha_helper(args, alphas)) # type: ignore[assignment]\n elif variant == 'scalar':\n # Scalar Other\n samples = (SampleInput(_make_tensor_helper((S, S)), args=(0.5,)),\n SampleInput(_make_tensor_helper(()), args=(0.5,)),\n SampleInput(_make_tensor_helper((S, S)), args=(1.5j,)),\n SampleInput(_make_tensor_helper(()), args=(1.5j,)),\n SampleInput(_make_tensor_helper((S, S)), args=(0.4 + 1.2j,)),\n SampleInput(_make_tensor_helper(()), args=(1.2 + 1.76j,)))\n\n scalar_args = [(_make_tensor_helper((S, S)), 0.5), (_make_tensor_helper(()), 0.5),\n (_make_tensor_helper((S, S)), 2.7j), (_make_tensor_helper(()), 2.7j),\n (_make_tensor_helper((S, S)), 1 - 2.7j), (_make_tensor_helper(()), 1 + 2.7j)]\n\n alphas = [int_alpha, float_alpha, complex_alpha]\n\n def filter_fn(arg_alpha):\n arg, alpha = arg_alpha\n if isinstance(alpha, complex):\n if dtype.is_complex or isinstance(arg[1], complex):\n return True\n else:\n # complex alpha is valid only if either `self` or `other` is complex\n return False\n\n # Non-Complex Alpha\n return True\n\n # Samples with alpha (scalar version) covers the following cases\n # self | other | alpha\n # -----------------------------------------\n # real | real | real (int and float)\n # real | complex | real and complex\n # complex | real | real and complex\n # complex | complex | real and complex\n #\n # It does not cover\n # real | real | complex\n # x = torch.randn(2, requires_grad=True, dtype=torch.float64)\n # torch.rsub(x, 1, alpha=1. + 1.6j)\n # RuntimeError: value cannot be converted to type double without overflow: (-1,-1.6)\n\n samples += tuple(_samples_with_alpha_helper(scalar_args, alphas, filter_fn=filter_fn)) # type: ignore[assignment]\n else:\n raise Exception(\"Invalid variant!\")\n\n return samples\n\ndef sample_inputs_cumulative_ops(op_info, device, dtype, requires_grad, supports_dtype_kwargs=True, **kwargs):\n def _make_tensor_helper(shape, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n samples = [\n SampleInput(_make_tensor_helper((S, S, S)), args=(0,)),\n SampleInput(_make_tensor_helper((S, S, S)), args=(1,)),\n SampleInput(_make_tensor_helper(()), args=(0,)),\n ]\n\n if supports_dtype_kwargs:\n # NOTE: if `dtype` is not same as input, then inplace variants fail with\n # `provided dtype must match the dtype of self tensor in cumsum`\n samples.append(SampleInput(_make_tensor_helper((S, S, S)), args=(1,), kwargs={'dtype': dtype}))\n\n return samples\n\n\ndef sample_inputs_unfold(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = (\n ((), (0, 1, 1)),\n ((S, S, S, S), (0, 3, 1)),\n ((S, S, S, S), (1, 3, 1)),\n ((S, S, S, S), (2, 3, 1)),\n ((S, S, S, S), (3, 3, 1)),\n ((S, S, S, S), (0, 3, 2)),\n ((S, S, S, S), (1, 3, 2)),\n ((S, S, S, S), (2, 3, 2)),\n ((S, S, S, S), (3, 3, 2)),\n ((S, S, S, S), (0, 4, 1)),\n ((S, S, S, S), (1, 4, 1)),\n ((S, S, S, S), (2, 4, 1)),\n ((S, S, S, S), (3, 4, 1)),\n ((M,), (0, 3, 1)),\n ((M,), (0, 3, 2)),\n ((M,), (0, 3, 3)),\n ((1000,), (0, 3, 11)),\n ((1000,), (0, 2, 27)),\n ((10, 10), (0, 1, 2)),\n ((10, 10), (1, 2, 3)),\n ((10, 10), (1, 2, 2)),\n ((S, S, S), (2, 3, 2)),\n )\n\n sample_inputs = []\n for shape, arguments in test_cases:\n sample_inputs += [SampleInput(make_tensor(shape, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n args=arguments)]\n return sample_inputs\n\n\ndef sample_inputs_atan2(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n cases = (\n ((S, S, S), (S, S, S), False),\n ((), (), False),\n ((S, S, S), (S,), False),\n ((S,), (S, S, S), True),\n ((S, 1, S), (S, S), True),\n )\n\n def generator():\n for x_shape, y_shape, broadcasts_input in cases:\n yield SampleInput(make_arg(x_shape), args=(make_arg(y_shape),),\n broadcasts_input=broadcasts_input)\n\n return list(generator())\n\n\ndef sample_inputs_split(op_info, device, dtype, requires_grad, *, list_args=False, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n if list_args:\n cases = (\n ((S, S, S), ([int(S / 3), S - int(S / 3) * 2, int(S / 3)],)),\n ((S, S, S), ([int(S / 2), S - int(S / 2) * 2, int(S / 2)], 2),),\n ((S, S, S), ([int(S / 2), S - int(S / 2) * 2, int(S / 2)], -2),)\n )\n else:\n cases = ( # type: ignore[assignment]\n ((S, S, S), (2,)),\n ((S, S, S), (S, 1)),\n )\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_split_with_sizes(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n cases = (((S, S, S), ([int(S / 3), S - int(S / 3) * 2, int(S / 3)],)),\n ((S, S, S), ([int(S / 3), S - int(S / 3), 0],)),\n ((S, S, S), ([int(S / 3), S - int(S / 3) * 2, int(S / 3)], 2)),\n ((S, S, S), ([int(S / 3), S - int(S / 3) * 2, int(S / 3)], -2)),\n )\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_msort(op_info, device, dtype, requires_grad):\n def apply_grad(t):\n if dtype in floating_types_and(torch.float16, torch.bfloat16):\n t.requires_grad_(requires_grad)\n\n def large_1d_unique(dtype, device):\n res = torch.randperm(L * L * L, dtype=torch.int64, device=device)\n res = res.to(dtype)\n apply_grad(res)\n return res\n\n samples = []\n # Test case for large tensor.\n largesample = SampleInput(large_1d_unique(dtype, device))\n\n sample = SampleInput(make_tensor((S, M, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad))\n\n return [largesample, sample]\n\ndef sample_inputs_lerp(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n samples = (\n # no broadcast\n SampleInput(make_arg((S, S)), args=(make_arg((S, S)), 0.4)),\n # broadcast rhs\n SampleInput(make_arg((S, S)), args=(make_arg((S,)), 0.4)),\n # scalar tensor\n SampleInput(make_arg(()), args=(make_arg(()), 0.4)),\n # broadcast rhs scalar-tensor\n SampleInput(make_arg((S, S)), args=(make_arg(()), 0.4)),\n # broadcast rhs with weight tensor\n SampleInput(make_arg((S, S)), args=(make_arg((S,)), make_arg((S, S)))),\n # broadcast rhs and weight tensor\n SampleInput(make_arg((S, S)), args=(make_arg((S, 1)), make_arg((S,)))),\n # broadcast_lhs\n SampleInput(make_arg((S,)), args=(make_arg((S, S)), 0.4), broadcasts_input=True),\n # scalar broadcast_lhs\n SampleInput(make_arg(()), args=(make_arg((S, S)), 0.4), broadcasts_input=True),\n # broadcast all\n SampleInput(make_arg((S, 1)), args=(make_arg((S, S)), 0.4), broadcasts_input=True),\n # tensor broadcast all\n SampleInput(make_arg((S, 1)), args=(make_arg((S, S)), make_arg((S, 1))),\n broadcasts_input=True),\n )\n\n if dtype.is_complex:\n samples = samples + ( # type: ignore[assignment]\n # no broadcast\n SampleInput(make_arg((S, S)), args=(make_arg((S, S)), 0.4j)),\n SampleInput(make_arg((S, S)), args=(make_arg((S, S)), 1.2 + 0.1j)),\n # broadcast rhs\n SampleInput(make_arg((S, S)), args=(make_arg((S,)), 0.4j)),\n SampleInput(make_arg((S, S)), args=(make_arg((S, S)), 5.4 + 9j)),\n # scalar tensor\n SampleInput(make_arg(()), args=(make_arg(()), 0.4j)),\n SampleInput(make_arg(()), args=(make_arg(()), 6.1 + 0.004j)),\n # broadcast rhs scalar-tensor\n SampleInput(make_arg((S, S)), args=(make_arg(()), 0.4j)),\n SampleInput(make_arg((S, S)), args=(make_arg(()), 1 + 2j)),\n )\n\n return samples\n\ndef sample_inputs_tensordot(self, device, dtype, requires_grad, **kwargs):\n cases = (\n ((2, 2, 2), (2, 2, 2), (2)),\n ((2, 2, 1), (2, 1, 2), ([0, 1], [2, 0])),\n )\n samples = []\n for first_shape, second_shape, dims in cases:\n samples.append(SampleInput(make_tensor(first_shape, device, dtype,\n requires_grad=requires_grad),\n args=(make_tensor(second_shape, device, dtype,\n requires_grad=requires_grad),),\n kwargs=dict(dims=dims,)))\n return tuple(samples)\n\ndef sample_inputs_kron(op_info, device, dtype, requires_grad):\n test_cases = (\n ((S, S), (M, L)),\n )\n\n sample_inputs = []\n for input_shape, other_shape in test_cases:\n input = make_tensor(input_shape, device, dtype, low=None, high=None, requires_grad=requires_grad)\n other = make_tensor(other_shape, device, dtype, low=None, high=None, requires_grad=requires_grad)\n sample = SampleInput(input, args=(other,))\n sample_inputs.append(sample)\n return tuple(sample_inputs)\n\ndef sample_inputs_inner(self, device, dtype, requires_grad, **kwargs):\n return (\n SampleInput(\n make_tensor((S, ), device, dtype, requires_grad=requires_grad),\n args=(\n make_tensor((S, ), device, dtype, requires_grad=requires_grad),\n )\n ),\n SampleInput(\n make_tensor((), device, dtype, requires_grad=requires_grad),\n args=(\n make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n )\n ),\n )\n\ndef sample_inputs_scatter(op_info, device, dtype, requires_grad):\n def _tensor(shape, dtype=dtype, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n def _gather(shape, index_dim, max_indices):\n return gather_variable(shape, index_dim, max_indices, device=device)\n\n zero = torch.tensor(0, dtype=torch.long, device=device)\n test_cases = (\n (_tensor((M, S)), (0, _gather((S, S), 1, M), _tensor((S, S)))),\n (_tensor((M, S)), (1, _gather((S, S), 0, S), _tensor((S, S)))),\n (_tensor((M, S)), (-1, _gather((S, S), 0, S), _tensor((S, S)))),\n (_tensor((M, S)), (0, _gather((M, S // 2), 1, M), _tensor((M, S // 2)))),\n (_tensor((M, S)), (1, _gather((M, S // 2), 0, S), _tensor((M, S // 2)))),\n (_tensor((M, S)), (-1, _gather((M, S // 2), 0, S), _tensor((M, S // 2)))),\n (_tensor(()), (0, zero.clone().detach(), _tensor(()))),\n (_tensor(()), (0, zero.clone().detach(), 2.5)),\n )\n\n samples = []\n for tensor, args in test_cases:\n samples.append(SampleInput(tensor, args=args))\n\n if not requires_grad:\n samples.append(SampleInput(\n tensor.clone().detach(),\n args=args, kwargs={'reduce': 'add'}\n ))\n\n if dtype.is_floating_point:\n samples.append(SampleInput(\n tensor.clone().detach(),\n args=args, kwargs={'reduce': 'multiply'}\n ))\n\n return samples\n\ndef sample_inputs_scatter_add(op_info, device, dtype, requires_grad):\n def _tensor(shape, dtype=dtype, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n def _gather(shape, index_dim, max_indices):\n return gather_variable(shape, index_dim, max_indices, device=device)\n\n zero = torch.tensor(0, dtype=torch.long, device=device)\n test_cases = (\n (_tensor((M, S)), (0, _gather((S, S), 1, M), _tensor((S, S)))),\n (_tensor((M, S)), (1, _gather((S, S), 0, S), _tensor((S, S)))),\n (_tensor((M, S)), (-1, _gather((S, S), 0, S), _tensor((S, S)))),\n (_tensor((M, S)), (0, _gather((M, S // 2), 1, M), _tensor((M, S // 2)))),\n (_tensor((M, S)), (1, _gather((M, S // 2), 0, S), _tensor((M, S // 2)))),\n (_tensor((M, S)), (-1, _gather((M, S // 2), 0, S), _tensor((M, S // 2)))),\n (_tensor(()), (0, zero.clone().detach(), _tensor(()))),\n )\n\n return [SampleInput(tensor, args=args) for tensor, args in test_cases]\n\n\ndef sample_inputs_ravel(op_info, device, dtype, requires_grad, **kwargs):\n samples = (SampleInput(make_tensor((S, S, S), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad)),\n SampleInput(make_tensor((), device, dtype,\n low=None, high=None,\n requires_grad=requires_grad)),)\n\n return samples\n\n\ndef sample_inputs_tril_triu(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n cases = (((M, M), ()),\n ((M, M), (2,),),\n ((S, M, M), ()),\n ((S, M, M), (2,)),\n ((3, 3, S, S), ()),)\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_clone(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n def generator():\n yield SampleInput(make_arg((S, M, S)))\n yield SampleInput(make_arg(()))\n\n return list(generator())\n\n\ndef sample_inputs_contiguous(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n def generator():\n yield SampleInput(make_arg((S, S)))\n yield SampleInput(make_arg((S, S), noncontiguous=True))\n\n return list(generator())\n\n\ndef sample_inputs_resize_ops(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device)\n cases = (((S, S, S), (S * S, S)),\n ((), ()),\n ((), (1, 1, 1)),\n )\n\n def generator():\n for shape, args_or_shape in cases:\n # Update `args` based on operator\n if op_info.name == 'resize_':\n # resize_ takes shape/tuple of ints,\n args = (args_or_shape, )\n elif op_info.name == 'resize_as_':\n # resize_as_ takes another tensor\n args = (make_arg(shape, requires_grad=False), ) # type:ignore[assignment]\n else:\n raise ValueError(\"sample_inputs_resize_ops is being used with incorrect operator\")\n\n yield(SampleInput(make_arg(shape, requires_grad=requires_grad), args=args))\n\n return list(generator())\n\n\ndef sample_inputs_view_reshape(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n cases = (((S, S, S), (S * S, S)),\n ((S * S, S), (S, S, S)),\n ((S,), (S,)),\n ((), ()),\n ((), (1,)))\n\n def generator():\n for case in cases:\n shape, args = case\n inp = make_arg(shape, requires_grad=requires_grad)\n yield(SampleInput(inp, args=(args, )))\n\n if op_info.name != \"view\" and len(shape) >= 2:\n yield(SampleInput(inp.transpose(0, 1), args=(args, )))\n\n return list(generator())\n\n\ndef sample_inputs_view_as_reshape_as(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device)\n\n cases = (((S, S, S), (S * S, S)),\n ((), ()),\n ((), (1, 1)),\n )\n\n def generator():\n for case in cases:\n shape, shape_other = case\n inp = make_arg(shape, requires_grad=requires_grad)\n yield(SampleInput(inp, args=(make_arg(shape_other, requires_grad=False),)))\n\n if op_info.name != \"view_as\" and len(shape) >= 2:\n yield(SampleInput(inp.transpose(0, 1), args=(make_arg(shape_other, requires_grad=False),)))\n\n return list(generator())\n\n\ndef sample_inputs_select(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n cases = (((S, S, S), (1, 2)),\n ((S, S, S), (-1, 2)),\n ((S, S, S), (-1, -1)),\n ((S, S, S), (1, -1)),\n ((S,), (0, 2))\n )\n\n def generator():\n for shape, args in cases:\n yield SampleInput(make_arg(shape), args=args)\n\n return list(generator())\n\n\ndef sample_inputs_rbinops(op_info, device, dtype, requires_grad, supports_dtype_kwargs=True, **kwargs):\n def _make_tensor_helper(shape, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n scalar: Union[int, float, complex] = 3\n\n if dtype.is_floating_point:\n scalar = 3.14\n elif dtype.is_complex:\n scalar = 3.14j\n\n samples = [\n SampleInput(_make_tensor_helper((S, S, S)), args=(scalar,)),\n SampleInput(_make_tensor_helper(()), args=(scalar,)),\n ]\n\n return samples\n\n\ndef sample_inputs_expand(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n cases = (((S, 1, 1), (S, S, S)),\n ((S, 1, S), (S, S, S)),\n ((S, 1), (S, S, S)),\n ((1,), (S, S, S)),\n ((1, S), (1, 1, S)),\n ((), ()),\n ((), (1, 3, 2)),\n )\n\n def generator():\n for case in cases:\n shape, args = case\n yield(SampleInput(make_arg(shape), args=(args, )))\n\n return list(generator())\n\n\ndef sample_inputs_expand_as(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device)\n\n cases = (((S, 1, 1), (S, S, S)),\n ((), ()),\n ((), (1, 1)),\n )\n\n def generator():\n for shape, shape_other in cases:\n yield(SampleInput(make_arg(shape, requires_grad=requires_grad),\n args=(make_arg(shape_other, requires_grad=False), )))\n\n return list(generator())\n\n\ndef sample_inputs_where(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device, requires_grad=requires_grad)\n\n def make_bool_mask(shape):\n # Make sure atleast one element is nonzero,\n # except for empty tensor\n mask_t = make_tensor(shape, dtype=torch.bool, device=device, requires_grad=False)\n\n if mask_t.numel() == 0:\n return mask_t\n elif mask_t.numel() == 1:\n mask_t.fill_(True)\n return mask_t\n\n if mask_t.sum() == 0:\n def random_index(shape):\n return tuple(map(lambda max_idx: random.randint(0, max_idx), shape))\n\n mask_t[random_index(mask_t.shape)] = True\n return mask_t\n\n return mask_t\n\n cases = (((M, M), (M, M), (M, M), False),\n ((M, 1, M), (M, M), (M, M, 1), True),\n ((), (), (), False),\n ((M, 1, M), (), (M, M, 1), True),\n ((), (M, M), (), True),)\n\n def generator():\n for shape, mask_shape, other_shape, broadcasts_input in cases:\n yield SampleInput(make_arg(shape),\n args=(make_bool_mask(mask_shape), make_arg(other_shape)),\n broadcasts_input=broadcasts_input)\n\n return list(generator())\n\n\ndef sample_inputs_chunk(op_info, device, dtype, requires_grad, **kwargs):\n make_arg = partial(make_tensor, dtype=dtype, device=device)\n\n cases = (((S, S, S), (2,)),\n ((S, S, S), (S, 1)),\n ((S, S, S), (S, -1)))\n\n def generator():\n for case in cases:\n shape, args = case\n yield(SampleInput(make_arg(shape, requires_grad=requires_grad), args=args))\n\n return list(generator())\n\ndef sample_inputs_kthvalue(op_info, device, dtype, requires_grad, **kwargs):\n def _tensor(shape, dtype=dtype, low=None, high=None):\n return make_tensor(shape, device, dtype, low=low, high=high, requires_grad=requires_grad)\n\n test_cases = [\n (_tensor((S, S, S)), (2,)),\n (_tensor((S, S, S)), (2, 1,)),\n (_tensor((S, S, S)), (2, -1,)),\n (_tensor((S, S, S)), (2, 1, True,)),\n (_tensor((S, S, S)), (2, -1, True,)),\n (_tensor((S,)), (2, 0,)),\n (_tensor((S,)), (2, 0, True,)),\n (_tensor(()), (1,)),\n (_tensor(()), (1, 0,)),\n (_tensor(()), (1, 0, True))\n ]\n\n return [SampleInput(tensor, args=args) for tensor, args in test_cases]\n\ndef sample_inputs_one_hot(op_info, device, dtype, requires_grad, **kwargs):\n def make_input(shape, *, low, high):\n return make_tensor(shape, device=device, dtype=dtype, low=low, high=high, requires_grad=requires_grad)\n\n shapes = ((), (S,), (L, M, S))\n num_classess = (-1, 10)\n\n return [\n SampleInput(\n make_input(\n shape,\n low=0,\n high=10 if num_classes == -1 else num_classes // 2,\n ),\n kwargs=dict(num_classes=num_classes),\n )\n for shape, num_classes in itertools.product(shapes, num_classess)\n ]\n\ndef sample_inputs_softplus(op_info, device, dtype, requires_grad, **kwargs):\n make_input = partial(make_tensor, (S,), device=device, dtype=dtype, requires_grad=requires_grad)\n\n return [\n SampleInput(make_input()),\n SampleInput(make_input(), kwargs=dict(beta=3)),\n SampleInput(make_input(low=1), kwargs=dict(threshold=1)),\n ]\n\ndef sample_inputs_mse_loss(op_info, device, dtype, requires_grad, **kwargs):\n _make_tensor = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n shapes_and_kwargs = [\n ((), None),\n ((S,), dict(reduction=\"mean\")),\n ((S,), dict(reduction=\"sum\")),\n ((S,), dict(reduction=\"none\")),\n ((S, S), None),\n ((S, S, S), None),\n ]\n\n return [\n SampleInput(_make_tensor(shape), args=(_make_tensor(shape),), kwargs=kwargs)\n for shape, kwargs in shapes_and_kwargs\n ]\n\ndef sample_inputs_grid_sample(op_info, device, dtype, requires_grad, **kwargs):\n _make_tensor = partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)\n\n batch_size = 2\n num_channels = 3\n modes = (\"bilinear\", \"nearest\")\n align_cornerss = (False, True)\n padding_modes = (\"zeros\", \"border\", \"reflection\")\n\n sample_inputs = []\n for dim in (2, 3):\n input = _make_tensor((batch_size, num_channels, *[S] * dim))\n grid = _make_tensor((batch_size, *[S] * dim, dim))\n\n modes_ = (*modes, \"bicubic\") if dim == 2 else modes\n\n for mode, padding_mode, align_corners in itertools.product(modes_, padding_modes, align_cornerss):\n sample_inputs.append(\n SampleInput(\n input,\n args=(grid,),\n kwargs=dict(\n mode=mode,\n padding_mode=padding_mode,\n align_corners=align_corners,\n )\n )\n )\n\n return sample_inputs\n\nforeach_unary_op_db: List[OpInfo] = [\n ForeachFuncInfo('exp'),\n ForeachFuncInfo('acos'),\n ForeachFuncInfo('asin'),\n ForeachFuncInfo('atan'),\n ForeachFuncInfo('cos'),\n ForeachFuncInfo('cosh'),\n ForeachFuncInfo('log'),\n ForeachFuncInfo('log10'),\n ForeachFuncInfo('log2'),\n ForeachFuncInfo('tan'),\n ForeachFuncInfo('tanh'),\n ForeachFuncInfo('sin'),\n ForeachFuncInfo('sinh'),\n\n ForeachFuncInfo(\n 'neg',\n dtypes=all_types_and_complex(),\n dtypesIfCPU=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex(),\n sample_inputs_func=sample_inputs_foreach,\n safe_casts_outputs=False,\n ),\n\n ForeachFuncInfo(\n 'sqrt',\n dtypes=floating_types(),\n dtypesIfCPU=floating_and_complex_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half),\n ),\n\n ForeachFuncInfo(\n 'ceil',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'erf',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'erfc',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'expm1',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'floor',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'log1p',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half),\n ),\n\n ForeachFuncInfo(\n 'round',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'frac',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'reciprocal',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half),\n ),\n\n ForeachFuncInfo(\n 'sigmoid',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half),\n ),\n\n ForeachFuncInfo(\n 'trunc',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n ),\n\n ForeachFuncInfo(\n 'abs',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n dtypesIfCPU=all_types_and_complex_and(torch.bfloat16, torch.half),\n dtypesIfCUDA=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n safe_casts_outputs=False,\n supports_forward_ad=True,\n ),\n]\n\nforeach_binary_op_db: List[OpInfo] = [\n ForeachFuncInfo(\n \"add\",\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_alpha_param=True,\n ),\n ForeachFuncInfo(\n \"sub\",\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_alpha_param=True,\n ),\n ForeachFuncInfo(\n \"mul\",\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n ),\n ForeachFuncInfo(\n \"div\",\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n ),\n]\n\nforeach_pointwise_op_db: List[ForeachFuncInfo] = [\n ForeachFuncInfo(\n \"addcmul\",\n dtypesIfCPU=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.half, torch.bfloat16),\n ),\n ForeachFuncInfo(\n \"addcdiv\",\n dtypesIfCPU=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.half, torch.bfloat16),\n ),\n]\n\nforeach_minmax_op_db: List[ForeachFuncInfo] = [\n ForeachFuncInfo(\n \"maximum\",\n dtypesIfCPU=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bool),\n ),\n ForeachFuncInfo(\n \"minimum\",\n dtypesIfCPU=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bool),\n ),\n]\n\ndef reference_sign(x):\n if x.dtype == np.bool_:\n # `np.sign` doesn't support `bool`.\n # >>> np.sign(True)\n # ufunc 'sign' did not contain a loop\n # with signature matching types dtype('bool') -> dtype('bool')\n return np.sign(x, dtype=np.uint8).astype(np.bool_)\n return np.sign(x)\n\n\ndef reference_sgn(x):\n # NumPy doesn't have an equivalent to `torch.sgn` when the dtype is complex.\n # For complex inputs, `np.sign` returns sign(x.real) + 0j if x.real != 0 else sign(x.imag) + 0j.\n # while `torch.sgn` returns, 0 if abs(input) == 0 else input/abs(input)\n if x.dtype not in [np.complex64, np.complex128]:\n return reference_sign(x)\n\n out = (x / np.abs(x))\n if out.ndim == 0:\n # Handle x == 0 case\n if (x == 0):\n # Can't assign to np.complex object\n # So make a new one.\n return np.array(complex(0, 0), dtype=x.dtype)\n return out\n\n # Handle x == 0 case\n mask = (x == 0)\n out[mask] = complex(0, 0)\n return out\n\n\ndef reference_sigmoid(x):\n # 'scipy.special.expit' not supported for the input types\n if x.dtype in [np.complex64, np.complex128]:\n return (1 / (1 + np.exp(-x)))\n return scipy.special.expit(x)\n\n\ndef reference_logsigmoid(x):\n max_ = np.maximum(x.dtype.type(0), -x)\n z = np.exp(-max_) + np.exp(-x - max_)\n return -(max_ + np.log(z))\n\n\ndef reference_lgamma(x):\n # scipy.special.gammaln returns `-inf` when input is `-inf`.\n # While Pytorch, C and C++, all return `inf` when input is `-inf`.\n # Reference:\n # https://en.cppreference.com/w/cpp/numeric/math/lgamma\n # https://en.cppreference.com/w/c/numeric/math/lgamma\n\n # To handle the above discrepancy,\n # we replace -inf with inf so values\n # that were originally -inf map to inf as expected\n if x.dtype.kind == 'f':\n x = np.where(x == float('-inf'), np.array(float('inf'), dtype=x.dtype), x)\n\n out = scipy.special.gammaln(x)\n\n if x.dtype == np.float16:\n # `scipy.special.gammaln` returns output of float32 when input is float16,\n # while `torch.lgamma` preserves `float16`. But due to smaller range of float16,\n # Pytorch version outputs `inf` while SciPy returns finite values.\n out = out.astype(np.float16)\n\n return out\n\ndef reference_polygamma(x, n):\n # WEIRD `scipy.special.polygamma` behavior\n # >>> scipy.special.polygamma(0, np.array(501, dtype=np.float32)).dtype\n # dtype('float64')\n # >>> scipy.special.polygamma(0, np.array([501], dtype=np.float32)).dtype\n # dtype('float32')\n #\n # Thus we cast output to the default torch dtype.\n np_dtype = torch_to_numpy_dtype_dict[torch.get_default_dtype()]\n return scipy.special.polygamma(n, x).astype(np_dtype)\n\n\ndef reference_mvlgamma(x, d):\n if x.dtype == np.float16:\n return scipy.special.multigammaln(x, d).astype(np.float16)\n\n return scipy.special.multigammaln(x, d)\n\ndef reference_softplus(input, beta=1, threshold=20):\n non_linear = input * beta <= threshold\n output = input.copy()\n output[non_linear] = np.log(1 + np.exp(beta * input[non_linear])) / beta\n return output\n\n\ndef reference_one_hot(a: np.ndarray, num_classes: int = -1) -> np.ndarray:\n if num_classes == -1:\n num_classes = int(np.amax(a) + 1)\n\n idcs = a.reshape(-1) + np.arange(0, a.size, dtype=np.int64) * num_classes\n one_hot = np.zeros((a.size, num_classes), dtype=a.dtype)\n np.put(one_hot, idcs, 1)\n return one_hot.reshape(*a.shape, -1)\n\n\ndef reference_mse_loss(input, target, reduction=\"mean\"):\n se = (input - target) ** 2\n if reduction == \"mean\":\n return np.mean(se)\n elif reduction == \"sum\":\n return np.sum(se)\n else: # reduction == \"none\"\n return se\n\n\ndef gradcheck_wrapper_hermitian_input(op, input, *args, **kwargs):\n \"\"\"Gradcheck wrapper for functions that take Hermitian matrices as input.\n\n They require a modified function because the finite-difference algorithm\n for calculating derivatives does not preserve the Hermitian property of the input.\n \"\"\"\n return op(input + input.conj().transpose(-2, -1), *args, **kwargs)\n\n\ndef gradcheck_wrapper_triangular_input(op, input, *args, upper=False, **kwargs):\n \"\"\"Gradcheck wrpper for functions that take lower or upper triangular matrices as input.\n\n They require a modified function because the finite-difference algorithm\n for calculating derivatives does not preserve the triangular property of the input.\n \"\"\"\n return op(input.triu() if upper else input.tril(), upper)\n\n\n# Operator database (sorted alphabetically)\nop_db: List[OpInfo] = [\n UnaryUfuncInfo('abs',\n aliases=('absolute', ),\n ref=np.abs,\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat]),\n # Reference: https://github.com/pytorch/pytorch/issues/49224\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n dtypes=[torch.int8], active_if=TEST_WITH_ASAN),\n # TODO: Fix test_out_arg_all_dtypes as torch.empty_like(expected_output) where expected_output=op(input)\n # We can break the logic of the loop over all possible types but it is OK.\n # https://github.com/pytorch/pytorch/blob/master/test/test_unary_ufuncs.py#L440-L449\n SkipInfo('TestUnaryUfuncs', 'test_out_arg_all_dtypes',\n dtypes=[torch.cfloat, torch.cdouble]),\n ),\n supports_inplace_autograd=False,\n assert_autodiffed=True,\n supports_forward_ad=True),\n # NOTE: CPU complex acos produces incorrect outputs (https://github.com/pytorch/pytorch/issues/42952)\n UnaryUfuncInfo('acos',\n aliases=('arccos', ),\n ref=np.arccos,\n domain=(-1, 1),\n handles_complex_extremals=False,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n # \"rsqrt_cpu\" not implemented for 'BFloat16'\n backward_dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.float16: 1e-2,\n torch.bfloat16: 1e-1,\n torch.complex64: 1e-2}),),\n safe_casts_outputs=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestGradients', 'test_fn_grad',\n dtypes=[torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestGradients', 'test_method_grad',\n dtypes=[torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestGradients', 'test_inplace_grad',\n dtypes=[torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestGradients', 'test_forward_mode_AD',\n dtypes=[torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestGradients', 'test_inplace_forward_mode_AD',\n dtypes=[torch.cdouble], active_if=IS_WINDOWS),\n )),\n # NOTE: the derivative for inplace acosh is not implemented\n UnaryUfuncInfo('acosh',\n aliases=('arccosh', ),\n ref=np.arccosh,\n domain=(1, None),\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n # \"rsqrt_cuda\" not implemented for 'BFloat16'\n backward_dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n decorators=(precisionOverride({torch.bfloat16: 5e-2}),),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cuda', dtypes=[torch.cdouble],\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cuda', dtypes=[torch.cdouble],\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cuda', dtypes=[torch.cdouble],\n active_if=IS_WINDOWS),\n # Reference: https://github.com/pytorch/pytorch/issues/50692\n SkipInfo('TestGradients', 'test_fn_grad',\n device_type='cuda', dtypes=[torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestGradients', 'test_method_grad',\n device_type='cuda', dtypes=[torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestGradients', 'test_forward_mode_AD',\n dtypes=[torch.cdouble]),\n )),\n OpInfo('add',\n # NumPy has no builtin reference for the alpha kwarg, but it is easy enough to emulate\n ref=lambda input, other, *, alpha=1: np.add(input, np.multiply(alpha, other)),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n assert_autodiffed=True,\n sample_inputs_func=partial(sample_inputs_binary_pwise, alpha=2),\n supports_inplace_autograd=False,\n supports_forward_ad=True),\n OpInfo('mul',\n aliases=('multiply',),\n dtypes=all_types_and_complex_and(torch.float16, torch.bfloat16, torch.bool),\n assert_autodiffed=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_binary_pwise),\n OpInfo('sub',\n # NumPy has no builtin reference for the alpha kwarg, but it is easy enough to emulate\n ref=lambda input, other, *, alpha=1: np.subtract(input, np.multiply(alpha, other)),\n aliases=('subtract',),\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.float16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n sample_inputs_func=partial(sample_inputs_binary_pwise, alpha=2),\n supports_inplace_autograd=False),\n OpInfo('addmm',\n # This addmm OpInfo is for when alpha and beta are not both equal to 1.\n # alpha=beta=1 is tested in the following opinfo, because that special case will\n # trigger addmm being decomposed by a jit pass.\n dtypes=floating_and_complex_types_and(torch.float16),\n dtypesIfCPU=all_types_and_complex_and(torch.float16, torch.bfloat16),\n dtypesIfROCM=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n assert_autodiffed=True,\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n sample_inputs_func=sample_inputs_addmm),\n OpInfo('addmm',\n # When alpha=beta=1 as compile-time constants, JIT will decompose addmm into mm and add.\n variant_test_name='decomposed',\n dtypes=floating_and_complex_types_and(torch.float16),\n dtypesIfCPU=all_types_and_complex_and(torch.float16, torch.bfloat16),\n dtypesIfROCM=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n assert_autodiffed=True,\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n autodiff_nonfusible_nodes=['aten::add', 'aten::mm'],\n sample_inputs_func=partial(sample_inputs_addmm, alpha=1, beta=1)),\n OpInfo('addmv',\n dtypes=floating_types(),\n dtypesIfCPU=all_types_and_complex_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.float16, torch.complex64, torch.complex128,\n *[torch.bfloat16] if CUDA11OrLater else []),\n dtypesIfROCM=floating_types_and(torch.half),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_addmv),\n OpInfo('addbmm',\n ref=lambda M, batch1, batch2, beta=1, alpha=1: np.add(np.multiply(np.asarray(beta, dtype=M.dtype), M),\n np.multiply(np.asarray(alpha, dtype=batch1.dtype),\n np.sum(np.matmul(batch1, batch2), axis=0))),\n dtypes=floating_types(),\n dtypesIfCPU=all_types_and_complex_and(torch.float16, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n backward_dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if SM53OrLater else []),\n dtypesIfROCM=floating_types_and(torch.half),\n backward_dtypesIfROCM=floating_types_and(torch.half),\n supports_forward_ad=True,\n decorators=[\n DecorateInfo(\n toleranceOverride({torch.float32: tol(atol=1.3e-05, rtol=1.3e-05),\n torch.complex64: tol(atol=1e-05, rtol=1.2e-03)}),\n 'TestCommon', 'test_reference_testing')],\n skips=(\n # FIXME: bfloat16 backward support likely depends on CUDA11+\n # and SM53+\n SkipInfo('TestCommon', 'test_dtypes', active_if=IS_WINDOWS),\n # addbmm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n # https://github.com/pytorch/pytorch/issues/55907\n SkipInfo('TestCommon', 'test_variant_consistency_eager'),\n ),\n sample_inputs_func=sample_inputs_addbmm),\n OpInfo('baddbmm',\n dtypes=floating_types_and(torch.half),\n dtypesIfCPU=all_types_and_complex_and(torch.float16, torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.float16, torch.complex64, torch.complex128,\n *[torch.bfloat16] if CUDA11OrLater else []),\n backward_dtypesIfCUDA=floating_types_and(torch.float16,\n *[torch.bfloat16] if SM53OrLater else [],\n torch.complex64, torch.complex128),\n supports_forward_ad=True,\n skips=(\n # FIXME: bfloat16 backward support likely depends on CUDA11+\n # and SM53+\n SkipInfo('TestCommon', 'test_dtypes', active_if=IS_WINDOWS),\n # baddbmm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n ),\n sample_inputs_func=sample_inputs_baddbmm),\n OpInfo('dot',\n dtypes=all_types_and_complex_and(torch.float16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_dot_vdot,\n supports_forward_ad=True,\n ),\n OpInfo('vdot',\n dtypes=all_types_and_complex_and(torch.float16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n sample_inputs_func=sample_inputs_dot_vdot,\n supports_forward_ad=True,\n ),\n OpInfo('bmm',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.float16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n backward_dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if SM53OrLater else []),\n assert_autodiffed=True,\n supports_forward_ad=True,\n skips=(\n # FIXME: bfloat16 backward support likely depends on CUDA11+\n # and SM53+\n SkipInfo('TestCommon', 'test_dtypes', active_if=IS_WINDOWS),\n # bmm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n ),\n sample_inputs_func=sample_inputs_bmm),\n OpInfo('mv',\n dtypes=all_types_and_complex_and(torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n skips=(\n # bmm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),),\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_mv),\n OpInfo('addr',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n backward_dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n backward_dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n # Reference: https://github.com/pytorch/pytorch/issues/50747\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/50747\n SkipInfo('TestCommon', 'test_variant_consistency_eager',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16)),\n ),\n sample_inputs_func=sample_inputs_addr,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n OpInfo('addcmul',\n dtypes=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.float16, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n supports_inplace_autograd=False,\n skips=(\n # TODO: update sample inputs with for_inplace_variant kwarg to support this test\n SkipInfo('TestCommon', 'test_variant_consistency_eager'),),\n sample_inputs_func=sample_inputs_addcmul_addcdiv),\n OpInfo('addcdiv',\n dtypes=floating_and_complex_types(),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n skips=(\n # TODO: update sample inputs with for_inplace_variant kwarg to support this test\n SkipInfo('TestCommon', 'test_variant_consistency_eager'),),\n sample_inputs_func=sample_inputs_addcmul_addcdiv),\n OpInfo('amax',\n ref=lambda a, dim=None, keepdim=False, **kwargs: np.amax(a, axis=dim, keepdims=keepdim, **kwargs),\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_amax_amin,),\n OpInfo('amin',\n ref=lambda a, dim=None, keepdim=False, **kwargs: np.amin(a, axis=dim, keepdims=keepdim, **kwargs),\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_amax_amin),\n OpInfo('argmax',\n dtypes=all_types_and(torch.float16, torch.bfloat16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_argmax_argmin,),\n OpInfo('argmin',\n dtypes=all_types_and(torch.float16, torch.bfloat16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_argmax_argmin,),\n UnaryUfuncInfo('asin',\n aliases=('arcsin', ),\n ref=np.arcsin,\n domain=(-1, 1),\n supports_sparse=True,\n supports_forward_ad=True,\n safe_casts_outputs=True,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n decorators=[\n DecorateInfo(\n toleranceOverride({torch.float16: tol(atol=1e-05, rtol=1e-03)}),\n 'TestUnaryUfuncs', device_type='cuda'),\n precisionOverride({torch.bfloat16: 1e-2}),\n ],\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cuda', dtypes=[torch.cdouble],\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cuda', dtypes=[torch.cdouble],\n active_if=IS_WINDOWS),\n )),\n # NOTE: derivative for inplace asinh is not implemented\n UnaryUfuncInfo('asinh',\n aliases=('arcsinh', ),\n ref=np.arcsinh,\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n decorators=(precisionOverride({torch.bfloat16: 5e-2}),),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cuda', dtypes=[torch.cdouble],\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cuda', dtypes=[torch.cdouble],\n active_if=IS_WINDOWS),\n # Complex gradcheck tests asinh at points 0 + ix for x > 1 which are points\n # where asinh is not differentiable\n SkipInfo('TestGradients', 'test_forward_mode_AD',\n dtypes=complex_types()),\n )),\n UnaryUfuncInfo('atan',\n aliases=('arctan', ),\n ref=np.arctan,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 1e-2}),),\n safe_casts_outputs=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cuda', dtypes=[torch.cfloat, torch.cdouble],\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cuda', dtypes=[torch.cfloat, torch.cdouble],\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cuda', dtypes=[torch.cfloat, torch.cdouble],\n active_if=IS_WINDOWS),\n )),\n OpInfo('atan2',\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_atan2,\n ),\n UnaryUfuncInfo('atanh',\n aliases=('arctanh', ),\n ref=np.arctanh,\n domain=(-1, 1),\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n decorators=(precisionOverride({torch.bfloat16: 1e-2}),),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.cfloat]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cuda', dtypes=[torch.cfloat, torch.cdouble],\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cuda', dtypes=[torch.cfloat],\n active_if=IS_WINDOWS),\n )),\n OpInfo('broadcast_to',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_broadcast_to),\n OpInfo('bitwise_and',\n dtypes=integral_types_and(torch.bool),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_binary_pwise),\n UnaryUfuncInfo('bitwise_not',\n ref=np.bitwise_not,\n dtypes=integral_types_and(torch.bool),\n supports_autograd=False),\n OpInfo('bitwise_left_shift',\n op=torch.bitwise_left_shift,\n dtypesIfCPU=all_types(),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bfloat16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_bitwise_shift),\n OpInfo('bitwise_right_shift',\n op=torch.bitwise_right_shift,\n dtypesIfCPU=all_types(),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bfloat16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_bitwise_shift),\n OpInfo('cdist',\n dtypes=floating_types(),\n supports_out=False,\n supports_gradgrad=False,\n assert_autodiffed=False,\n sample_inputs_func=sample_inputs_cdist,\n ),\n UnaryUfuncInfo('ceil',\n ref=np.ceil,\n dtypes=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n supports_forward_ad=True,\n assert_autodiffed=True),\n OpInfo('cholesky',\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_cholesky,\n gradcheck_wrapper=gradcheck_wrapper_hermitian_input,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack],\n # RuntimeError: torch.cholesky: U(1,1) is zero, singular U.\n test_neg_view=False,\n skips=(\n # Gradcheck for complex generates invalid inputs for this function\n SkipInfo('TestGradients', 'test_forward_mode_AD', dtypes=complex_types()),)),\n OpInfo('cholesky_inverse',\n dtypes=floating_and_complex_types(),\n backward_dtypes=floating_types(),\n # TODO: RuntimeError: cholesky_inverse does not support automatic differentiation for outputs\n # with complex dtype.\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_cholesky_inverse,\n gradcheck_wrapper=gradcheck_wrapper_triangular_input,\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],\n skips=(\n # TODO: FIXME: cholesky_inverse throws an error in forward when requires_grad=True\n # for complex tensors\n SkipInfo('TestCommon', 'test_dtypes'),\n # cholesky_inverse does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),)),\n OpInfo('chunk',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n sample_inputs_func=sample_inputs_chunk,\n supports_out=False),\n OpInfo('clone',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n sample_inputs_func=sample_inputs_clone,\n supports_forward_ad=True,\n supports_out=False),\n OpInfo('contiguous',\n op=lambda x, *args, **kwargs: x.contiguous(*args, **kwargs),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n sample_inputs_func=sample_inputs_contiguous,\n supports_forward_ad=True,\n skips=(\n # JIT has issue when op is passed as lambda\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n supports_out=False),\n OpInfo('symeig',\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_symeig,\n gradcheck_wrapper=gradcheck_wrapper_hermitian_input,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n # NOTE: clamp has seperate opinfos for scalar min/max (unary op) vs. tensors\n OpInfo('clamp',\n aliases=('clip',),\n dtypes=all_types_and(torch.half, torch.bfloat16),\n dtypesIfCPU=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.half, torch.bfloat16),\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_clamp),\n UnaryUfuncInfo('clamp',\n variant_test_name='scalar',\n aliases=('clip', ),\n decorators=(precisionOverride({torch.bfloat16: 7e-2, torch.float16: 1e-2}),),\n ref=np.clip,\n dtypes=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.half, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/54841\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.bfloat16]),\n ),\n sample_kwargs=sample_kwargs_clamp_scalar,\n sample_inputs_func=sample_inputs_clamp_scalar),\n UnaryUfuncInfo('positive',\n ref=np.positive,\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n ),\n UnaryUfuncInfo('conj',\n ref=np.conj,\n dtypes=all_types_and_complex_and(torch.bool,\n torch.bfloat16, torch.half),\n supports_sparse=True,\n supports_forward_ad=True,\n supports_out=False),\n UnaryUfuncInfo('conj_physical',\n ref=np.conj,\n dtypes=all_types_and_complex_and(torch.bool,\n torch.bfloat16, torch.half),\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestJit', 'test_variant_consistency_jit', dtypes=(torch.float32, )),\n )),\n OpInfo('resolve_conj',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_view_as_real,\n supports_forward_ad=True,\n supports_out=False,\n ),\n OpInfo('resolve_neg',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_view_as_real,\n supports_forward_ad=True,\n supports_out=False,\n ),\n OpInfo('view_as_real',\n dtypes=complex_types(),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_view_as_real,\n test_conjugated_samples=False,\n ),\n OpInfo('view_as_complex',\n dtypes=floating_types_and(torch.half),\n supports_out=False,\n supports_forward_ad=True,\n test_neg_view=False,\n sample_inputs_func=sample_inputs_view_as_complex),\n OpInfo('complex',\n dtypes=floating_types(),\n sample_inputs_func=sample_inputs_complex,\n supports_forward_ad=True,\n ),\n OpInfo('copysign',\n dtypes=all_types_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_copysign,\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n ),\n OpInfo('corrcoef',\n dtypes=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.half, *[torch.bfloat16] if CUDA11OrLater else []),\n sample_inputs_func=sample_inputs_corrcoef,\n supports_out=False),\n UnaryUfuncInfo('cos',\n ref=np.cos,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n handles_large_floats=False,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 1e-2}),),\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.cfloat, torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal', device_type='cpu',\n dtypes=[torch.cfloat, torch.cdouble], active_if=IS_MACOS),\n )),\n UnaryUfuncInfo('cosh',\n ref=np_unary_ufunc_integer_promotion_wrapper(np.cosh),\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n assert_autodiffed=True,\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/48641\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.int8]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.cfloat, torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.cfloat, torch.cdouble], active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal', device_type='cpu',\n dtypes=[torch.cfloat, torch.cdouble], active_if=IS_MACOS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard', device_type='cpu',\n dtypes=[torch.cfloat, torch.cdouble], active_if=IS_MACOS),\n )),\n OpInfo('cov',\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.half, *[torch.bfloat16] if CUDA11OrLater else []),\n backward_dtypesIfCUDA=all_types_and_complex_and(torch.half, *[torch.bfloat16] if CUDA11OrLater else []),\n sample_inputs_func=sample_inputs_cov,\n supports_out=False,\n supports_forward_ad=True,\n # JIT test not working for tensor kwargs (https://github.com/pytorch/pytorch/issues/58507)\n skips=(SkipInfo('TestJit', 'test_variant_consistency_jit'),)),\n OpInfo('cross',\n dtypes=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.half),\n sample_inputs_func=sample_inputs_cross,\n supports_forward_ad=True,\n skips=(\n # AssertionError: UserWarning not triggered :\n # Resized a non-empty tensor but did not warn about it.\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('cumsum',\n dtypesIfCPU=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.half, torch.bfloat16),\n supports_forward_ad=True,\n skips=(\n # cumsum does not handle correctly out= dtypes\n SkipInfo('TestCommon', 'test_out'),\n ),\n sample_inputs_func=sample_inputs_cumulative_ops),\n OpInfo('cumprod',\n dtypes=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.float16, torch.bfloat16),\n supports_forward_ad=True,\n skips=(\n # cumprod does not handle correctly out= dtypes\n SkipInfo('TestCommon', 'test_out',\n dtypes=[torch.float32]),\n ),\n # gradgradcheck fails in fast_mode=True: #56275\n sample_inputs_func=sample_inputs_cumprod,\n gradcheck_fast_mode=False),\n OpInfo('cummax',\n dtypesIfCPU=all_types_and(torch.bool),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_cumulative_ops, supports_dtype_kwargs=False),\n supports_forward_ad=True,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n OpInfo('cummin',\n dtypesIfCPU=all_types_and(torch.bool),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_cumulative_ops, supports_dtype_kwargs=False),\n supports_forward_ad=True,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n UnaryUfuncInfo('deg2rad',\n ref=np.radians,\n decorators=(precisionOverride({torch.bfloat16: 7e-1,\n torch.float16: 7e-1}),),\n dtypes=all_types_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/pull/51283#issuecomment-770614273\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.bfloat16]),\n ),\n safe_casts_outputs=True),\n OpInfo('diff',\n op=torch.diff,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_diff),\n OpInfo('div',\n aliases=('divide',),\n variant_test_name='no_rounding_mode',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_binary_pwise, rhs_exclude_zero=True),\n supports_forward_ad=True,\n assert_autodiffed=True),\n OpInfo('div',\n aliases=('divide',),\n variant_test_name='trunc_rounding',\n dtypes=all_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_binary_pwise, extra_kwargs={\n \"rounding_mode\": 'trunc'}, rhs_exclude_zero=True),\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/59174\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n assert_autodiffed=True),\n OpInfo('div',\n aliases=('divide',),\n variant_test_name='floor_rounding',\n dtypes=all_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_binary_pwise, extra_kwargs={\n \"rounding_mode\": 'floor'}, rhs_exclude_zero=True),\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/59174\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n assert_autodiffed=True),\n OpInfo('true_divide',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=partial(sample_inputs_binary_pwise, rhs_exclude_zero=True)),\n UnaryUfuncInfo('exp',\n ref=np_unary_ufunc_integer_promotion_wrapper(np.exp),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n skips=(\n # Reference: https://github.com/pytorch/pytorch/pull/50093#pullrequestreview-561791547\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal', dtypes=[torch.bfloat16]),\n # Reference: https://github.com/pytorch/pytorch/issues/48010\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n ),\n assert_autodiffed=True,\n supports_forward_ad=True,\n safe_casts_outputs=True),\n OpInfo('expand',\n op=lambda self, shape: self.expand(shape),\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_expand,\n skips=(\n # Because expand does not have a function variant.\n SkipInfo('TestJit', 'test_variant_consistency_jit'),),\n supports_forward_ad=True,\n supports_out=False),\n OpInfo('expand_as',\n op=lambda self, other: self.expand_as(other),\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_expand_as,\n skips=(\n # Because expand_as does not have a function variant.\n SkipInfo('TestJit', 'test_variant_consistency_jit'),),\n supports_out=False),\n OpInfo('diag',\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCPU=all_types_and_complex_and(torch.bool),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_diag),\n OpInfo('diag_embed',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_diagonal_diag_embed),\n OpInfo('diagonal',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_out=False,\n sample_inputs_func=sample_inputs_diagonal_diag_embed),\n OpInfo('eq',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_comparison_ops),\n OpInfo('fmax',\n op=torch.fmax,\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_max_min_binary,),\n OpInfo('fmin',\n op=torch.fmin,\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_max_min_binary,),\n OpInfo('fmod',\n ref=np.fmod,\n dtypes=all_types_and(torch.float16),\n sample_inputs_func=sample_inputs_fmod_remainder),\n OpInfo('fmod',\n ref=np.fmod,\n variant_test_name='autodiffed',\n dtypes=all_types_and(torch.float16, torch.bool),\n assert_autodiffed=True,\n sample_inputs_func=partial(sample_inputs_fmod_remainder, autodiffed=True)),\n OpInfo('remainder',\n ref=np.remainder,\n dtypesIfCPU=all_types_and(torch.float16),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_fmod_remainder),\n OpInfo('remainder',\n ref=np.remainder,\n variant_test_name='autodiffed',\n dtypesIfCPU=all_types_and(torch.float16, torch.bool),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bool, torch.bfloat16),\n supports_forward_ad=True,\n assert_autodiffed=True,\n sample_inputs_func=partial(sample_inputs_fmod_remainder, autodiffed=True)),\n UnaryUfuncInfo('frac',\n ref=lambda x: np.modf(x)[0],\n dtypes=floating_types_and(torch.bfloat16, torch.float16),\n dtypesIfCUDA=floating_types_and(torch.float16, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n # Reference for disabling extremals\n # https://github.com/pytorch/pytorch/issues/51948\n handles_extremals=False),\n SpectralFuncInfo('fft.fft',\n aten_name='fft_fft',\n ref=np.fft.fft,\n ndimensional=False,\n dtypes=all_types_and_complex_and(torch.bool),\n default_test_dtypes=floating_and_complex_types()),\n SpectralFuncInfo('fft.fftn',\n aten_name='fft_fftn',\n ref=np.fft.fftn,\n ndimensional=True,\n dtypes=all_types_and_complex_and(torch.bool),\n default_test_dtypes=floating_and_complex_types(),\n decorators=[precisionOverride(\n {torch.float: 1e-4, torch.cfloat: 1e-4})],),\n SpectralFuncInfo('fft.hfft',\n aten_name='fft_hfft',\n ref=np.fft.hfft,\n ndimensional=False,\n dtypes=all_types_and_complex_and(torch.bool),\n default_test_dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False),\n SpectralFuncInfo('fft.rfft',\n aten_name='fft_rfft',\n ref=np.fft.rfft,\n ndimensional=False,\n dtypes=all_types_and(torch.bool),\n default_test_dtypes=floating_and_complex_types(),\n check_batched_grad=False,\n check_batched_gradgrad=False),\n SpectralFuncInfo('fft.rfftn',\n aten_name='fft_rfftn',\n ref=np.fft.rfftn,\n ndimensional=True,\n dtypes=all_types_and(torch.bool),\n default_test_dtypes=floating_and_complex_types(),\n check_batched_grad=False,\n check_batched_gradgrad=False,\n decorators=[precisionOverride({torch.float: 1e-4})],),\n SpectralFuncInfo('fft.ifft',\n aten_name='fft_ifft',\n ref=np.fft.ifft,\n ndimensional=False,\n dtypes=all_types_and_complex_and(torch.bool),\n default_test_dtypes=floating_and_complex_types()),\n SpectralFuncInfo('fft.ifftn',\n aten_name='fft_ifftn',\n ref=np.fft.ifftn,\n ndimensional=True,\n dtypes=all_types_and_complex_and(torch.bool),\n default_test_dtypes=floating_and_complex_types(),\n decorators=[\n DecorateInfo(\n precisionOverride({torch.float: 1e-4, torch.cfloat: 1e-4}),\n 'TestFFT', 'test_reference_nd')],\n ),\n SpectralFuncInfo('fft.ihfft',\n aten_name='fft_ihfft',\n ref=np.fft.ihfft,\n ndimensional=False,\n dtypes=all_types_and(torch.bool),\n default_test_dtypes=floating_types(),\n check_batched_grad=False),\n SpectralFuncInfo('fft.irfft',\n aten_name='fft_irfft',\n ref=np.fft.irfft,\n ndimensional=False,\n dtypes=all_types_and_complex_and(torch.bool),\n default_test_dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False),\n SpectralFuncInfo('fft.irfftn',\n aten_name='fft_irfftn',\n ref=np.fft.irfftn,\n ndimensional=True,\n dtypes=all_types_and_complex_and(torch.bool),\n default_test_dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n decorators=[\n DecorateInfo(\n precisionOverride({torch.float: 1e-4, torch.cfloat: 1e-4}),\n 'TestFFT', 'test_reference_nd')],\n ),\n UnaryUfuncInfo('floor',\n ref=np.floor,\n dtypes=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n supports_forward_ad=True,\n assert_autodiffed=True),\n OpInfo('flip',\n op=torch.flip,\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_flip,\n supports_forward_ad=True,\n supports_out=False),\n OpInfo('fliplr',\n op=torch.fliplr,\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_fliplr_flipud,\n supports_forward_ad=True,\n supports_out=False),\n OpInfo('flipud',\n op=torch.flipud,\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_fliplr_flipud,\n supports_forward_ad=True,\n supports_out=False),\n UnaryUfuncInfo('i0',\n ref=np_unary_ufunc_integer_promotion_wrapper(\n scipy.special.i0) if TEST_SCIPY else _NOTHING,\n aliases=('special.i0',),\n decorators=(precisionOverride({torch.bfloat16: 3e-1,\n torch.float16: 5e-1}),),\n backward_dtypesIfCPU=floating_types(),\n backward_dtypesIfCUDA=floating_types(),\n backward_dtypesIfROCM=floating_types(),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n sample_inputs_func=sample_inputs_i0_i1),\n UnaryUfuncInfo('special.i0e',\n aten_name='special_i0e',\n ref=scipy.special.i0e if TEST_SCIPY else _NOTHING,\n decorators=(precisionOverride({torch.bfloat16: 3e-1,\n torch.float16: 3e-1}),),\n backward_dtypesIfCPU=floating_types(),\n backward_dtypesIfCUDA=floating_types(),\n backward_dtypesIfROCM=floating_types(),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_i0_i1,\n safe_casts_outputs=True),\n UnaryUfuncInfo('special.i1',\n aten_name='special_i1',\n ref=np_unary_ufunc_integer_promotion_wrapper(scipy.special.i1) if TEST_SCIPY else _NOTHING,\n decorators=(precisionOverride({torch.float: 1e-4}),),\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool),\n dtypesIfCUDA=all_types_and(torch.bool),\n sample_inputs_func=sample_inputs_i0_i1,\n safe_casts_outputs=True),\n UnaryUfuncInfo('special.i1e',\n aten_name='special_i1e',\n ref=scipy.special.i1e if TEST_SCIPY else _NOTHING,\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool),\n dtypesIfCUDA=all_types_and(torch.bool),\n sample_inputs_func=sample_inputs_i0_i1,\n safe_casts_outputs=True),\n UnaryUfuncInfo('special.ndtr',\n aten_name='special_ndtr',\n decorators=(precisionOverride({torch.bfloat16: 5e-3,\n torch.float16: 5e-4}),),\n ref=scipy.special.ndtr if TEST_SCIPY else _NOTHING,\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.bfloat16, torch.float16),\n safe_casts_outputs=True),\n OpInfo('floor_divide',\n dtypes=all_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_floor_divide,\n supports_autograd=False,\n ),\n UnaryUfuncInfo('frexp',\n op=torch.frexp,\n ref=np.frexp,\n dtypes=floating_types_and(torch.half),\n # skip testing torch.frexp as it is not supported by ROCm platform yet\n decorators=[skipCUDAIfRocm],\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # skips below tests as torch.frexp returns tuple-like (mantissa, exponent) as outputs,\n # while theses tests currently requires output to a single tensor.\n SkipInfo('TestUnaryUfuncs', 'test_batch_vs_slicing'),\n SkipInfo('TestUnaryUfuncs', 'test_contig_vs_every_other'),\n SkipInfo('TestUnaryUfuncs', 'test_contig_vs_transposed'),\n SkipInfo('TestUnaryUfuncs', 'test_non_contig_expand'),\n SkipInfo('TestUnaryUfuncs', 'test_variant_consistency'),\n\n # skips test_reference_numerics due to error in Windows CI.\n # The np.frexp returns exponent as np.intc dtype on Windows platform,\n # and np.intc does not have the correspond torch dtype\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n active_if=IS_WINDOWS),\n )),\n OpInfo('ge',\n aliases=('greater_equal',),\n dtypes=all_types_and(torch.bool, torch.bfloat16, torch.float16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_comparison_ops),\n OpInfo('geqrf',\n dtypes=floating_and_complex_types(),\n dtypesIfCPU=floating_and_complex_types(),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_geqrf,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack],),\n OpInfo('gt',\n aliases=('greater',),\n dtypes=all_types_and(torch.bool, torch.bfloat16, torch.float16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_comparison_ops),\n UnaryUfuncInfo('imag',\n ref=np.imag,\n dtypes=complex_types(),\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # Skip since real and imag don't have out variants.\n SkipInfo('TestUnaryUfuncs', 'test_out_arg_all_dtypes'),\n )),\n OpInfo('gradient',\n dtypes=floating_and_complex_types_and(torch.int8, torch.int16,\n torch.int32, torch.int64,\n torch.bfloat16, torch.half),\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # following tests give a runtime error with undefined value tensor\n # see discussion : https://github.com/pytorch/pytorch/issues/56660\n SkipInfo('TestJit', 'test_variant_consistency_jit', dtypes=(torch.float32, torch.complex64)),\n ),\n supports_inplace_autograd=False,\n sample_inputs_func=sample_inputs_gradient),\n OpInfo('inverse',\n op=torch.inverse,\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n sample_inputs_func=sample_inputs_linalg_invertible,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('isin',\n dtypesIfCPU=all_types(),\n dtypesIfCUDA=all_types_and(torch.half),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_isin),\n OpInfo('kthvalue',\n dtypes=all_types(),\n dtypesIfCPU=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.float16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_kthvalue),\n OpInfo('le',\n aliases=('less_equal',),\n dtypes=all_types_and(torch.bool, torch.bfloat16, torch.float16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_comparison_ops),\n OpInfo('linalg.det',\n op=torch.linalg.det,\n aliases=('det', ),\n dtypes=floating_and_complex_types(),\n backward_dtypes=floating_and_complex_types(),\n aten_name='linalg_det',\n sample_inputs_func=sample_inputs_linalg_det,\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack, skipCUDAIfRocm],\n supports_inplace_autograd=False),\n OpInfo('linalg.det',\n op=torch.linalg.det,\n variant_test_name='singular',\n aliases=('det', ),\n dtypes=double_types(),\n backward_dtypes=double_types(),\n aten_name='linalg_det',\n sample_inputs_func=sample_inputs_linalg_det_singular,\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack, skipCUDAIfRocm],\n supports_inplace_autograd=False,\n skips=(\n # Will be removed once https://github.com/pytorch/pytorch/issues/62328 is fixed\n # Probable fix (open PR): https://github.com/pytorch/pytorch/pull/62570\n SkipInfo('TestGradients', 'test_fn_grad', device_type='cuda', dtypes=(torch.complex128,)),\n SkipInfo('TestCommon', 'test_dtypes'),\n SkipInfo('TestGradients', 'test_fn_gradgrad'),\n # This test fails because singular inputs cannot be reliably\n # generated unless we're using double types\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes'),\n SkipInfo('TestOpInfo', 'test_unsupported_backward',\n dtypes=(torch.float32, torch.complex64,)),\n )),\n OpInfo('linalg.cholesky',\n aten_name='linalg_cholesky',\n dtypes=floating_and_complex_types(),\n # TODO: RuntimeError: While computing batched gradients,\n # got: vmap: Calling Tensor.as_strided is not supported\n # unless the batch dims being vmapped over are at the front of the tensor (in memory layout).\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_cholesky,\n gradcheck_wrapper=gradcheck_wrapper_hermitian_input,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack],\n # RuntimeError: torch.linalg.cholesky: U(1,1) is zero, singular U.\n test_neg_view=False,\n skips=(\n # Gradcheck for complex generates invalid inputs for this function\n SkipInfo('TestGradients', 'test_forward_mode_AD', dtypes=complex_types()),),\n ),\n OpInfo('linalg.cholesky_ex',\n aten_name='linalg_cholesky_ex',\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_cholesky,\n gradcheck_wrapper=gradcheck_wrapper_hermitian_input,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.cond',\n aten_name='linalg_cond',\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_cond,\n check_batched_gradgrad=False,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack],\n ),\n OpInfo('linalg.eig',\n aten_name='linalg_eig',\n op=torch.linalg.eig,\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_eig,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.eigvals',\n aten_name='linalg_eigvals',\n op=torch.linalg.eigvals,\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_invertible,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.eigh',\n aten_name='linalg_eigh',\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_eigh,\n gradcheck_wrapper=gradcheck_wrapper_hermitian_input,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.eigvalsh',\n aten_name='linalg_eigvalsh',\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_eigh,\n gradcheck_wrapper=gradcheck_wrapper_hermitian_input,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack],),\n OpInfo('linalg.householder_product',\n aten_name='linalg_householder_product',\n op=torch.linalg.householder_product,\n aliases=('orgqr', ),\n dtypes=floating_and_complex_types(),\n # TODO: backward uses in-place operations that vmap doesn't like\n check_batched_grad=False,\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_householder_product,\n decorators=[skipCUDAIfNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.lstsq',\n aten_name='linalg_lstsq',\n op=torch.linalg.lstsq,\n dtypes=floating_and_complex_types(),\n supports_out=True,\n sample_inputs_func=sample_inputs_linalg_lstsq,\n supports_autograd=False,\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],\n skips=(\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n )),\n OpInfo('linalg.matrix_power',\n aliases=('matrix_power',),\n aten_name='linalg_matrix_power',\n dtypes=floating_and_complex_types(),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, skipCUDAIfRocm],\n sample_inputs_func=sample_inputs_linalg_matrix_power,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n OpInfo('linalg.multi_dot',\n # Need this lambda because gradcheck does not work with TensorList inputs\n aten_name='linalg_multi_dot',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=all_types_and_complex_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, *[torch.bfloat16] if CUDA11OrLater else []),\n supports_inplace_autograd=False,\n # Batched grad checks fail for empty input tensors (see https://github.com/pytorch/pytorch/issues/53407)\n check_batched_grad=False,\n check_batched_gradgrad=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_linalg_multi_dot,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n ),\n OpInfo('linalg.norm',\n op=torch.linalg.norm,\n dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],\n sample_inputs_func=sample_inputs_linalg_norm,\n aten_name='linalg_norm',\n skips=(\n # linalg.norm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('linalg.matrix_norm',\n aten_name='linalg_matrix_norm',\n dtypes=floating_and_complex_types(),\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],\n sample_inputs_func=sample_inputs_linalg_matrix_norm,\n skips=(\n # linalg.matrix_norm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('linalg.qr',\n aten_name='linalg_qr',\n op=torch.linalg.qr,\n dtypes=floating_and_complex_types(),\n # batched gradients do not work for empty inputs\n # https://github.com/pytorch/pytorch/issues/50743#issuecomment-767376085\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_qr,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.slogdet',\n aten_name='linalg_slogdet',\n op=torch.linalg.slogdet,\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_slogdet,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.vector_norm',\n op=torch.linalg.vector_norm,\n dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],\n sample_inputs_func=sample_inputs_linalg_vector_norm,\n aten_name='linalg_vector_norm',\n skips=(\n # linalg.vector_norm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n )),\n UnaryUfuncInfo('log',\n ref=np.log,\n domain=(0, None),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 5e-2}),),\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=IS_WINDOWS),\n )),\n UnaryUfuncInfo('log10',\n ref=np.log10,\n domain=(0, None),\n decorators=(precisionOverride({torch.bfloat16: 5e-2}),),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n assert_autodiffed=True,\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=IS_WINDOWS),\n )),\n UnaryUfuncInfo('log1p',\n ref=np.log1p,\n aliases=('special.log1p',),\n domain=(-1, None),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n decorators=(precisionOverride({torch.bfloat16: 1e-1}),),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n assert_autodiffed=True),\n UnaryUfuncInfo('log2',\n ref=np.log2,\n domain=(0, None),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 1e-1}),),\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n dtypes=[torch.cfloat, torch.cdouble]),\n )),\n OpInfo('logaddexp',\n dtypes=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.bfloat16),\n dtypesIfROCM=floating_types_and(torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=lambda op_info, device, dtype, requires_grad=False, **kwargs:\n (SampleInput(make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n args=(make_tensor((S, S), device, dtype, requires_grad=requires_grad),)),)),\n OpInfo('logaddexp2',\n dtypes=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.bfloat16),\n dtypesIfROCM=floating_types_and(torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=lambda op_info, device, dtype, requires_grad=False, **kwargs:\n (SampleInput(make_tensor((S, S), device, dtype, requires_grad=requires_grad),\n args=(make_tensor((S, S), device, dtype, requires_grad=requires_grad),)),)),\n UnaryUfuncInfo('logical_not',\n ref=np.logical_not,\n decorators=(precisionOverride({torch.bfloat16: 7e-1,\n torch.float16: 5e-1}),),\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n supports_autograd=False,\n skips=(\n # The function variant always returns BoolTensor\n # while the inplace variant preserves the input dtype.\n # >>> t = torch.randn(3)\n # >>> torch.logical_not(t)\n # tensor([False, False, False])\n # >>> torch.logical_not(t).dtype\n # torch.bool\n # >>> t.logical_not_().dtype\n # torch.float32\n SkipInfo('TestUnaryUfuncs', 'test_variant_consistency',\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16)),\n SkipInfo('TestCommon', 'test_variant_consistency_eager',\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16)),\n )),\n OpInfo('lt',\n aliases=('less',),\n dtypes=all_types_and(torch.bool, torch.bfloat16, torch.float16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_comparison_ops),\n OpInfo('lu',\n op=torch.lu,\n dtypes=floating_and_complex_types(),\n supports_inplace_autograd=False,\n check_batched_gradgrad=False,\n supports_out=False,\n sample_inputs_func=sample_inputs_lu,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack],\n skips=(\n # we skip jit tests because lu_backward is impelemented as autograd.Function,\n # which does not support autograd with scripting\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n # Skip operator schema test because this is a functional and not an operator\n SkipInfo('TestOperatorSignatures', 'test_get_torch_func_signature_exhaustive'),\n )),\n OpInfo('lu_solve',\n op=torch.lu_solve,\n dtypes=floating_and_complex_types(),\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_lu_solve,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('lu_unpack',\n op=torch.lu_unpack,\n dtypes=floating_and_complex_types(),\n supports_inplace_autograd=False,\n # we use in-place operations which cannot be avoided.\n # This cases vmap failures, hence we skip batched gradient checks\n check_batched_grad=False,\n supports_out=True,\n sample_inputs_func=sample_inputs_lu_unpack,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack],\n skips=(\n # cuda gradchecks are slow\n # see discussion https://github.com/pytorch/pytorch/pull/47761#issuecomment-747316775\n SkipInfo('TestGradients', 'test_fn_gradgrad', device_type='cuda'),\n )),\n OpInfo('masked_fill',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_masked_fill,\n supports_forward_ad=True,\n supports_out=False),\n OpInfo('masked_scatter',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_masked_scatter,\n supports_forward_ad=True,\n supports_out=False),\n OpInfo('masked_select',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_masked_select),\n OpInfo('matrix_exp',\n dtypesIfCPU=floating_and_complex_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n sample_inputs_func=sample_inputs_matrix_exp,\n supports_out=False,\n ),\n OpInfo('matmul',\n dtypes=floating_types(),\n dtypesIfCPU=all_types_and_complex(),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n dtypesIfROCM=floating_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCUDA=floating_and_complex_types_and(torch.float16,\n *[torch.bfloat16] if (SM60OrLater and CUDA11OrLater) else []),\n assert_autodiffed=True,\n assert_jit_shape_analysis=True,\n sample_inputs_func=sample_inputs_matmul,\n skips=(\n # matmul does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n SkipInfo('TestCommon', 'test_conj_view', device_type='cpu'),\n )),\n OpInfo('max',\n op=torch.max,\n variant_test_name='binary',\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_max_min_binary,\n supports_forward_ad=True,\n assert_autodiffed=True,),\n OpInfo('max',\n op=torch.max,\n variant_test_name='reduction_with_dim',\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_max_min_reduction_with_dim,\n supports_forward_ad=True,\n skips=(\n # max does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),)),\n OpInfo('max',\n op=torch.max,\n variant_test_name='reduction_no_dim',\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_max_min_reduction_no_dim,),\n OpInfo('median',\n dtypes=all_types(),\n dtypesIfCPU=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.float16),\n # TODO: some signatures of median do support out\n supports_out=False,\n sample_inputs_func=sample_inputs_reduction_wrapper(False)),\n OpInfo('nanmedian',\n dtypes=all_types(),\n dtypesIfCPU=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.float16),\n # TODO: some signatures of nanmedian do support out\n supports_out=False,\n sample_inputs_func=sample_inputs_reduction_wrapper(False)),\n OpInfo('var_mean',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=floating_and_complex_types_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_reduction_wrapper(False),\n backward_dtypes=floating_types_and(torch.half),\n backward_dtypesIfCPU=floating_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCUDA=floating_types_and(torch.half),\n # TODO: some signatures of var_mean do support out\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # TODO: FIXME: complex inputs requiring grad error in forward\n SkipInfo('TestCommon', 'test_dtypes'),\n # TODO: review with var_mean tests in test_autograd.py\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n SkipInfo('TestGradients', 'test_fn_grad'),\n SkipInfo('TestGradients', 'test_fn_gradgrad'),\n SkipInfo('TestGradients', 'test_forward_mode_AD'))),\n OpInfo('std_mean',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=floating_and_complex_types_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_reduction_wrapper(False),\n backward_dtypes=floating_types_and(torch.half),\n backward_dtypesIfCPU=floating_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCUDA=floating_types_and(torch.half),\n # TODO: some signatures of std_mean do support out\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # TODO: FIXME: complex inputs requiring grad error in forward\n SkipInfo('TestCommon', 'test_dtypes'),\n # TODO: fix along with var_mean autograd tests\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n SkipInfo('TestGradients', 'test_fn_grad'),\n SkipInfo('TestGradients', 'test_fn_gradgrad'),\n SkipInfo('TestGradients', 'test_forward_mode_AD'))),\n OpInfo('min',\n op=torch.min,\n variant_test_name='binary',\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_max_min_binary,\n supports_forward_ad=True,\n assert_autodiffed=True,),\n OpInfo('min',\n op=torch.min,\n variant_test_name='reduction_with_dim',\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_max_min_reduction_with_dim,\n supports_forward_ad=True,\n skips=(\n # min does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('min',\n op=torch.min,\n variant_test_name='reduction_no_dim',\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_max_min_reduction_no_dim,),\n OpInfo('sum',\n dtypes=all_types_and_complex_and(torch.float16, torch.bfloat16, torch.bool),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_reduction_wrapper(supports_multiple_dims=True)),\n OpInfo('nansum',\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_out=False,\n sample_inputs_func=sample_inputs_reduction_wrapper(supports_multiple_dims=True)),\n # TODO(@heitorschueroff) Add test for dtype kwarg\n OpInfo('mean',\n dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_reduction_wrapper(supports_multiple_dims=True),\n # Need to skip out test because one of the overload for mean does not support it\n # TODO(@heitorschueroff) fix this when implementing ReductionInfo\n skips=(SkipInfo('TestCommon', 'test_out'),)),\n OpInfo('quantile',\n dtypes=floating_types(),\n sample_inputs_func=sample_inputs_reduction_quantile),\n OpInfo('nanquantile',\n dtypes=floating_types(),\n sample_inputs_func=sample_inputs_reduction_quantile),\n OpInfo('maximum',\n op=torch.maximum,\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_max_min_binary,),\n OpInfo('minimum',\n op=torch.minimum,\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_max_min_binary,),\n # `softmax` supports different dtypes based on whether `dtype` argument,\n # is passed or not. Hence two OpInfo entries, one with dtype and other without.\n OpInfo('softmax',\n aliases=('nn.functional.softmax',),\n aten_name='softmax',\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_softmax_variant,\n assert_autodiffed=True,\n supports_out=False),\n OpInfo('softmax',\n aliases=('nn.functional.softmax',),\n variant_test_name=\"with_dtype\",\n aten_name='softmax',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_softmax_variant, with_dtype=True),\n assert_autodiffed=True,\n supports_out=False),\n OpInfo('nn.functional.normalize',\n dtypesIfCPU=floating_and_complex_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_normalize,\n skips=(\n # RuntimeError: aliasOp != torch::jit::getOperatorAliasMap().end()\n # INTERNAL ASSERT FAILED at \"../torch/csrc/jit/passes/utils/check_alias_annotation.cpp\":159,\n # please report a bug to PyTorch.\n SkipInfo('TestJit', 'test_variant_consistency_jit',),\n )),\n OpInfo('aminmax',\n ref=lambda x, dim=None, keepdim=False: (np.amin(x, axis=dim, keepdims=keepdim), np.amax(x, axis=dim, keepdims=keepdim)),\n dtypes=all_types_and(torch.bool),\n dtypesIfCUDA=all_types_and(torch.bool, torch.float16, torch.bfloat16),\n decorators=(onlyOnCPUAndCUDA,),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_aminmax,\n skips=(\n # FIXME: aminmax does not check for safe casting to output\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('nn.functional.adaptive_avg_pool2d',\n dtypes=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n skips=(\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n supports_out=False,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n sample_inputs_func=sample_inputs_adaptive_avg_pool2d),\n OpInfo('nn.functional.relu',\n aten_name=\"relu\",\n supports_autograd=True,\n dtypesIfCPU=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_nn_activation_relu,\n supports_out=False),\n OpInfo('nn.functional.conv_transpose2d',\n aten_name='conv_transpose2d',\n aliases=('conv_transpose2d',),\n dtypesIfCPU=floating_types_and(torch.int64),\n dtypesIfCUDA=floating_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n sample_inputs_func=sample_inputs_conv_transpose2d,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n skips=(\n # RuntimeError: !lhs.isAliasOf(rhs)INTERNAL ASSERT FAILED at\n # \"../torch/csrc/jit/passes/utils/check_alias_annotation.cpp\":104, please report a bug to PyTorch.\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n supports_out=False,),\n OpInfo('nn.functional.hardswish',\n aten_name=\"hardswish\",\n supports_autograd=True,\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_hardswish,\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n supports_gradgrad=False,\n supports_forward_ad=True,\n supports_out=False,\n autodiff_nonfusible_nodes=[\"aten::hardswish\"]),\n OpInfo('nn.functional.unfold',\n aten_name='im2col',\n dtypes=floating_types_and(torch.half),\n sample_inputs_func=sample_inputs_nn_unfold,\n skips=(\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n supports_out=False),\n OpInfo('nn.functional.leaky_relu',\n aliases=None,\n aten_name=\"leaky_relu\",\n dtypes=floating_types(),\n sample_inputs_func=sample_inputs_leaky_relu,\n dtypesIfCUDA=floating_types_and(torch.float16, torch.bfloat16),\n supports_autograd=True,\n assert_autodiffed=True,\n supports_gradgrad=True,\n supports_out=False,\n supports_forward_ad=True,\n autodiff_nonfusible_nodes=[\"aten::leaky_relu\"]),\n OpInfo('nn.functional.avg_pool2d',\n aten_name='avg_pool2d',\n supports_autograd=True,\n supports_out=False,\n dtypesIfCPU=floating_types_and(torch.int64),\n dtypesIfCUDA=floating_types_and(torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_avgpool2d),\n UnaryUfuncInfo(\n 'nn.functional.logsigmoid',\n aten_name=\"log_sigmoid\",\n ref=reference_logsigmoid,\n dtypes=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.float16),\n supports_autograd=True,\n assert_autodiffed=False,\n supports_gradgrad=True,\n supports_out=False,\n # autodiff_nonfusible_nodes=[\"aten::log_sigmoid\"],\n decorators=[\n DecorateInfo(\n precisionOverride({torch.float16: 1e-2}),\n 'TestUnaryUfuncs', 'test_reference_numerics_normal'),\n DecorateInfo(\n precisionOverride({torch.float16: 1e-2}),\n 'TestUnaryUfuncs', 'test_reference_numerics_hard'),\n DecorateInfo(\n precisionOverride({torch.float16: 1e-2}),\n 'TestUnaryUfuncs', 'test_reference_numerics_extremal'),\n ],\n ),\n OpInfo('nextafter',\n dtypes=floating_types_and(torch.bfloat16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_nextafter),\n OpInfo('topk',\n dtypes=all_types(),\n dtypesIfCPU=all_types_and(torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bfloat16, torch.float16),\n sample_inputs_func=sample_inputs_topk,\n skips=(\n # Topk is not raising a warning when the out is resized\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('nn.functional.hardshrink',\n aten_name=\"hardshrink\",\n dtypes=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.float16, torch.bfloat16),\n supports_autograd=True,\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_hardshrink_hardtanh,\n supports_gradgrad=True,\n supports_out=False,\n supports_forward_ad=True,\n autodiff_nonfusible_nodes=[\"aten::hardshrink\"]),\n OpInfo('nn.functional.hardtanh',\n aten_name=\"hardtanh\",\n dtypesIfCPU=floating_types_and(torch.int8, torch.int16, torch.int32, torch.int64, torch.bfloat16),\n backward_dtypesIfCPU=all_types(),\n dtypesIfCUDA=floating_types_and(torch.int8, torch.int16, torch.int32, torch.int64, torch.float16, torch.bfloat16),\n backward_dtypesIfCUDA=floating_types_and(torch.float16),\n supports_autograd=True,\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_hardshrink_hardtanh,\n supports_gradgrad=True,\n supports_out=False,\n supports_forward_ad=True,\n autodiff_nonfusible_nodes=[\"aten::hardtanh\"],\n ),\n OpInfo('nn.functional.gelu',\n aten_name=\"gelu\",\n supports_autograd=True,\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_gelu,\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n supports_gradgrad=True,\n supports_out=False,\n autodiff_nonfusible_nodes=[\"aten::gelu\"]),\n OpInfo('nn.functional.relu6',\n aten_name=\"relu6\",\n dtypes=all_types(),\n dtypesIfCPU=all_types_and(torch.bfloat16),\n backward_dtypesIfCPU=floating_types(),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bfloat16),\n backward_dtypesIfCUDA=floating_types_and(torch.float16),\n supports_autograd=True,\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_hardshrink_hardtanh,\n supports_gradgrad=True,\n supports_out=False,\n supports_forward_ad=True,\n autodiff_nonfusible_nodes=[\"aten::relu6\"]),\n OpInfo('mm',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=all_types_and_complex_and(torch.float16, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n assert_autodiffed=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_mm,\n skips=(\n # mm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('mode',\n op=torch.mode,\n dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_mode,),\n MvlGammaInfo(variant_test_name='mvlgamma_p_1',\n domain=(1, None),\n skips=skips_mvlgamma(),\n sample_kwargs=lambda device, dtype, input: ({'p': 1}, {'d': 1})),\n MvlGammaInfo(variant_test_name='mvlgamma_p_3',\n domain=(2, None),\n skips=skips_mvlgamma(skip_redundant=True) + (\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard', dtypes=(torch.float16,)),\n ),\n sample_kwargs=lambda device, dtype, input: ({'p': 3}, {'d': 3})),\n MvlGammaInfo(variant_test_name='mvlgamma_p_5',\n domain=(3, None),\n skips=skips_mvlgamma(skip_redundant=True) + (\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard', dtypes=(torch.float16,)),\n ),\n sample_kwargs=lambda device, dtype, input: ({'p': 5}, {'d': 5})),\n OpInfo('ne',\n aliases=('not_equal',),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_comparison_ops),\n OpInfo('narrow',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_narrow),\n UnaryUfuncInfo('neg',\n aliases=('negative', ),\n ref=np.negative,\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16),\n assert_autodiffed=True,),\n OpInfo('dist',\n op=torch.dist,\n dtypes=floating_and_complex_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_dist,\n skips=(\n # dist does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('outer',\n op=torch.outer,\n aliases=('ger', ),\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_outer,),\n OpInfo('ormqr',\n op=torch.ormqr,\n dtypes=floating_and_complex_types(),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_ormqr,\n decorators=[skipCUDAIfNoCusolver, skipCPUIfNoLapack]),\n OpInfo('permute',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n assert_autodiffed=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_permute),\n OpInfo('pow',\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool),\n # Due to AVX2 curently not being fully supported for Float16, log_vml_cpu can't be enabled\n # for Float16, causing this test to fail. pow's autograd for Float16 is thus currently\n # unsupported on CPU.\n backward_dtypes=all_types_and_complex_and(torch.bfloat16, torch.bool),\n backward_dtypesIfCUDA=all_types_and_complex_and(torch.bfloat16, torch.half),\n sample_inputs_func=sample_inputs_pow,\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n assert_autodiffed=True,\n ),\n OpInfo('float_power',\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_pow,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestMathBits', 'test_conj_view', device_type='cuda'),),),\n OpInfo('prod',\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n skips=(\n # prod does not support the (Tensor, *, out) overload\n SkipInfo('TestCommon', 'test_out',\n dtypes=[torch.float32]),\n ),\n sample_inputs_func=sample_inputs_prod,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n OpInfo('qr',\n op=torch.qr,\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_qr,\n # batched gradients do not work for empty inputs\n # https://github.com/pytorch/pytorch/issues/50743#issuecomment-767376085\n check_batched_gradgrad=False,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n UnaryUfuncInfo('rad2deg',\n ref=np.degrees,\n decorators=(precisionOverride({torch.bfloat16: 7e-1,\n torch.float16: 7e-1}),),\n dtypes=all_types_and(torch.bool, torch.half, torch.bfloat16),\n skips=(\n # Reference: https://github.com/pytorch/pytorch/pull/51283#issuecomment-770614273\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.bfloat16]),\n ),\n safe_casts_outputs=True),\n UnaryUfuncInfo('real',\n ref=np.real,\n dtypes=complex_types(),\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # Skip since real and imag don't have out variants.\n SkipInfo('TestUnaryUfuncs', 'test_out_arg_all_dtypes'),\n )),\n OpInfo('roll',\n ref=np.roll,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_roll),\n OpInfo('rot90',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_rot90),\n UnaryUfuncInfo('round',\n ref=np.round,\n aliases=('special.round',),\n dtypes=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n supports_forward_ad=True,\n assert_autodiffed=True,),\n UnaryUfuncInfo('sin',\n ref=np.sin,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n handles_large_floats=False,\n handles_complex_extremals=False,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 1e-2}),)),\n UnaryUfuncInfo('sinc',\n ref=np_sinc_with_fp16_as_fp32,\n aliases=('special.sinc',),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n handles_large_floats=False,\n handles_complex_extremals=False,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 1e-2,\n torch.float16: 1e-2}),),\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/49133\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n dtypes=[torch.cfloat]),\n )),\n UnaryUfuncInfo('sinh',\n ref=np_unary_ufunc_integer_promotion_wrapper(np.sinh),\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n assert_autodiffed=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.float16: 1e-2}),),\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n # Reference: https://github.com/pytorch/pytorch/issues/48641\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.int8]),\n )),\n UnaryUfuncInfo('sign',\n ref=reference_sign,\n dtypes=all_types_and(torch.bool, torch.bfloat16, torch.half),\n dtypesIfCUDA=all_types_and(torch.bool, torch.bfloat16, torch.half),\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/41245\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.bfloat16, torch.float16, torch.float32, torch.float64]),\n )),\n UnaryUfuncInfo('sgn',\n ref=reference_sgn,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half),\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/41245\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.bfloat16, torch.float16, torch.float32, torch.float64]),\n # Reference: https://github.com/pytorch/pytorch/issues/53958\n # Test fails in comparison on Nan as the `equal_nan` is True for\n # comparing the CPU tensors.\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.complex64, torch.complex128]),\n # Reference: https://github.com/pytorch/pytorch/issues/48486\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.complex64])\n )),\n OpInfo('split',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=partial(sample_inputs_split, list_args=False),\n supports_out=False,\n assert_autodiffed=True),\n OpInfo('split',\n variant_test_name='list_args',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=partial(sample_inputs_split, list_args=True),\n supports_out=False),\n OpInfo('split_with_sizes',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=sample_inputs_split_with_sizes,\n supports_out=False,\n assert_autodiffed=True),\n OpInfo('__radd__',\n op=torch.Tensor.__radd__,\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestJit', 'test_variant_consistency_jit',),),\n assert_autodiffed=True,\n supports_forward_ad=True,\n autodiff_nonfusible_nodes=['aten::add'],),\n OpInfo('__rdiv__',\n op=torch.Tensor.__rdiv__,\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestJit', 'test_variant_consistency_jit',),),\n supports_forward_ad=True,\n assert_autodiffed=True,\n autodiff_nonfusible_nodes=['aten::mul', 'aten::reciprocal'],),\n OpInfo('__rmul__',\n op=torch.Tensor.__rmul__,\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestJit', 'test_variant_consistency_jit',),),\n assert_autodiffed=True,\n supports_forward_ad=True,\n autodiff_nonfusible_nodes=['aten::mul'],),\n OpInfo('__rand__',\n op=torch.Tensor.__rand__,\n dtypes=integral_types_and(torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestCommon', 'test_variant_consistency_jit',),),\n supports_autograd=False,\n supports_forward_ad=True,),\n OpInfo('__ror__',\n op=torch.Tensor.__ror__,\n dtypes=integral_types_and(torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestCommon', 'test_variant_consistency_jit',),),\n supports_autograd=False,\n supports_forward_ad=True,),\n OpInfo('__rxor__',\n op=torch.Tensor.__rxor__,\n dtypes=integral_types_and(torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestCommon', 'test_variant_consistency_jit',),),\n supports_autograd=False,\n supports_forward_ad=True,),\n OpInfo('__rmatmul__',\n op=torch.Tensor.__rmatmul__,\n dtypes=floating_types(),\n dtypesIfCPU=all_types_and_complex(),\n dtypesIfCUDA=floating_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else [],\n torch.complex64, torch.complex128),\n backward_dtypesIfCUDA=floating_types_and(torch.float16,\n *[torch.bfloat16] if (SM60OrLater and CUDA11OrLater) else [],\n torch.complex64, torch.complex128),\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_matmul,\n supports_out=False,\n skips=(\n SkipInfo('TestJit', 'test_variant_consistency_jit',),\n )),\n OpInfo('__rmod__',\n op=torch.Tensor.__rmod__,\n dtypes=all_types_and(torch.bfloat16, torch.half),\n dtypesIfCPU=floating_types_and(torch.half,),\n dtypesIfCUDA=all_types_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestJit', 'test_variant_consistency_jit',),),\n # Support autograd after torch.remainder(Tensor, Tensor) supports\n # autograd of the second argument.\n # https://github.com/pytorch/pytorch/pull/58476/files#r637167630\n supports_autograd=False,\n assert_autodiffed=True,\n autodiff_nonfusible_nodes=['aten::remainder'],),\n OpInfo('__rpow__',\n op=torch.Tensor.__rpow__,\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n # Reference: https://github.com/pytorch/pytorch/issues/54774\n # \"log2\" \"_vml_cpu\" not implemented for Half\n backward_dtypesIfCPU=all_types_and_complex_and(torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestJit', 'test_variant_consistency_jit',),),\n assert_autodiffed=True,\n autodiff_nonfusible_nodes=['aten::pow'],),\n OpInfo('__rsub__',\n op=torch.Tensor.__rsub__,\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half),\n sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(SkipInfo('TestJit', 'test_variant_consistency_jit',),),\n assert_autodiffed=True,\n autodiff_nonfusible_nodes=['aten::rsub'],),\n OpInfo('rsub',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half),\n variant_test_name='rsub_tensor',\n supports_out=False,\n supports_inplace_autograd=False,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/53797\n # JIT doesn't understand complex literals\n SkipInfo('TestJit', 'test_variant_consistency_jit',\n dtypes=[torch.cfloat, torch.cdouble]),\n ),\n sample_inputs_func=partial(sample_inputs_rsub, variant='tensor'),),\n OpInfo('rsub',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half),\n variant_test_name='rsub_scalar',\n supports_out=False,\n supports_inplace_autograd=False,\n sample_inputs_func=partial(sample_inputs_rsub, variant='scalar'),\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/53797\n # JIT doesn't understand complex literals\n SkipInfo('TestJit', 'test_variant_consistency_jit',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half)),),\n assert_autodiffed=True,),\n OpInfo('select',\n dtypes=all_types_and_complex_and(torch.bfloat16, torch.half, torch.bool),\n sample_inputs_func=sample_inputs_select,\n supports_forward_ad=True,\n supports_out=False),\n UnaryUfuncInfo('signbit',\n ref=np.signbit,\n dtypes=all_types_and(torch.bool, torch.bfloat16, torch.half),\n supports_autograd=False,),\n OpInfo('solve',\n op=torch.solve,\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_legacy_solve,\n check_batched_gradgrad=False,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('std',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=floating_and_complex_types_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCPU=floating_and_complex_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_std_var,\n # TODO: std does support out in some signatures\n supports_out=False,\n assert_autodiffed=True,\n ),\n UnaryUfuncInfo('tan',\n ref=np.tan,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cuda', dtypes=[torch.float64],\n active_if=TEST_WITH_ROCM),\n )),\n UnaryUfuncInfo('tanh',\n ref=np.tanh,\n decorators=(precisionOverride({torch.bfloat16: 1e-2}),),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n # \"tanh_backward_cpu\" not implemented for 'BFloat16'\n backward_dtypesIfCPU=all_types_and_complex_and(torch.bool),\n assert_autodiffed=True,\n safe_casts_outputs=True,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=(IS_MACOS or IS_WINDOWS)),\n )),\n OpInfo('tensor_split',\n dtypes=all_types_and_complex_and(torch.bool),\n dtypesIfCPU=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_tensor_split,),\n OpInfo('hsplit',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_hsplit,),\n OpInfo('vsplit',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_vsplit,),\n OpInfo('dsplit',\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_dsplit,),\n OpInfo('triangular_solve',\n op=torch.triangular_solve,\n dtypes=floating_and_complex_types(),\n supports_out=False,\n sample_inputs_func=sample_inputs_legacy_solve,\n check_batched_gradgrad=False,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n UnaryUfuncInfo('trunc',\n aliases=('fix', ),\n ref=np.trunc,\n dtypes=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.float16, torch.bfloat16),\n supports_forward_ad=True,\n assert_autodiffed=True),\n UnaryUfuncInfo('exp2',\n aliases=('special.exp2', ),\n ref=np_unary_ufunc_integer_promotion_wrapper(np.exp2),\n dtypes=all_types_and(torch.bool, torch.half),\n dtypesIfCPU=all_types_and(torch.bool, torch.half, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n safe_casts_outputs=True),\n UnaryUfuncInfo('expm1',\n aliases=('special.expm1', ),\n ref=np_unary_ufunc_integer_promotion_wrapper(np.expm1),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n safe_casts_outputs=True,\n assert_autodiffed=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/pull/48926#issuecomment-739734774\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.bfloat16]),\n )),\n UnaryUfuncInfo('nan_to_num',\n ref=np.nan_to_num,\n dtypes=all_types_and(torch.half, torch.bool),\n dtypesIfCUDA=all_types_and(torch.half, torch.bool, torch.bfloat16),\n supports_forward_ad=True,\n # Passing numpy_kwargs via sample_kwargs, as numpy does comparison\n # with BFloat16 in float, since it currently doesn't support BFloat16.\n # Ref: https://github.com/pytorch/pytorch/issues/57982#issuecomment-839150556\n sample_kwargs=lambda device, dtype, input: ({},\n {'posinf': torch.finfo(torch.bfloat16).max,\n 'neginf': torch.finfo(torch.bfloat16).min})\n if dtype is torch.bfloat16 else ({}, {})),\n UnaryUfuncInfo('reciprocal',\n ref=np_unary_ufunc_integer_promotion_wrapper(np.reciprocal),\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n safe_casts_outputs=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/45690\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.cfloat, torch.cdouble]),\n # Reference: https://github.com/pytorch/pytorch/pull/49102#issuecomment-744604601\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n dtypes=[torch.bfloat16]),\n )),\n UnaryUfuncInfo('rsqrt',\n ref=lambda x: np.reciprocal(np.sqrt(x)),\n domain=(0, None),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n decorators=(precisionOverride({torch.half: 5e-2}),),\n safe_casts_outputs=True,\n assert_autodiffed=True,\n supports_forward_ad=True,\n handles_complex_extremals=False),\n UnaryUfuncInfo('sqrt',\n ref=np.sqrt,\n supports_sparse=True,\n domain=(0, None),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 7e-2}),),\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/47358\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble],\n active_if=IS_MACOS),\n # Reference: https://github.com/pytorch/pytorch/pull/47293#issuecomment-721774436\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.bfloat16])),\n safe_casts_outputs=True,\n handles_complex_extremals=False),\n UnaryUfuncInfo('square',\n ref=np.square,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n decorators=(precisionOverride({torch.complex64: 3e-4, torch.bfloat16: 3e-1}),),\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/52549\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.cfloat, torch.cdouble]),\n # >>> t = torch.tensor(complex(-0.01, float(\"inf\")))\n # >>> np.square(t.numpy())\n # (-inf-infj)\n # >>> t.square()\n # tensor(-inf-infj)\n # >>> t.cuda().square()\n # tensor(inf+nanj, device='cuda:0')\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cuda', dtypes=[torch.cfloat, torch.cdouble]),\n # Reference: https://github.com/pytorch/pytorch/pull/52551#issuecomment-782596181\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.bfloat16]),\n ),),\n OpInfo('lerp',\n dtypes=floating_and_complex_types(),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n dtypesIfROCM=floating_and_complex_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_lerp,\n supports_forward_ad=True,\n assert_autodiffed=True),\n OpInfo('linalg.inv',\n aten_name='linalg_inv',\n op=torch.linalg.inv,\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_invertible,\n check_batched_gradgrad=False,\n supports_forward_ad=True,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack],\n ),\n OpInfo('linalg.inv_ex',\n aten_name='linalg_inv_ex',\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_invertible,\n check_batched_gradgrad=False,\n supports_forward_ad=True,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack],\n ),\n UnaryUfuncInfo('angle',\n ref=np.angle,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool),\n decorators=(precisionOverride({torch.float16: 1e-2,\n torch.bfloat16: 1e-2}),),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n supports_complex_to_float=True),\n OpInfo('linalg.solve',\n aten_name='linalg_solve',\n op=torch.linalg.solve,\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_solve,\n check_batched_gradgrad=False,\n supports_forward_ad=True,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.matrix_rank',\n aten_name='linalg_matrix_rank',\n dtypes=floating_and_complex_types(),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_linalg_invertible,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.matrix_rank',\n aten_name='linalg_matrix_rank',\n variant_test_name='hermitian',\n dtypes=floating_and_complex_types(),\n supports_autograd=False,\n sample_inputs_func=sample_inputs_linalg_pinv_hermitian,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.pinv',\n aten_name='linalg_pinv',\n op=torch.linalg.pinv,\n dtypes=floating_and_complex_types(),\n check_batched_grad=False,\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_invertible,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('linalg.pinv',\n aten_name='linalg_pinv',\n variant_test_name='hermitian',\n dtypes=floating_and_complex_types(),\n check_batched_grad=False,\n check_batched_gradgrad=False,\n sample_inputs_func=sample_inputs_linalg_pinv_hermitian,\n gradcheck_wrapper=gradcheck_wrapper_hermitian_input,\n decorators=[skipCUDAIfNoMagma, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('eig',\n op=torch.eig,\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_eig,\n decorators=[\n skipCUDAIfNoMagma,\n skipCPUIfNoLapack,\n skipCUDAIfRocm\n ],),\n OpInfo('einsum',\n # we need this lambda because SampleInput expects tensor input as the first argument\n # TODO(@heitorschueroff) update SampleInput to handle such cases\n op=lambda tensors, equation: torch.einsum(equation, tensors),\n dtypes=all_types_and_complex_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, *[torch.bfloat16] if CUDA11OrLater else []),\n backward_dtypesIfCUDA=floating_and_complex_types_and(torch.half,\n *[torch.bfloat16] if (SM60OrLater and CUDA11OrLater) else []),\n supports_out=False,\n sample_inputs_func=sample_inputs_einsum,\n skips=(\n # test does not work with passing lambda for op\n # there's a test `test_einsum` in `test_jit.py` to handle this case\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n )),\n OpInfo('svd',\n op=torch.svd,\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_svd,\n decorators=[\n skipCUDAIfNoMagmaAndNoCusolver,\n skipCUDAIfRocm,\n skipCPUIfNoLapack,\n ]),\n OpInfo('linalg.svd',\n op=torch.linalg.svd,\n aten_name='linalg_svd',\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_svd,\n decorators=[\n skipCUDAIfNoMagmaAndNoCusolver,\n skipCUDAIfRocm,\n skipCPUIfNoLapack,\n ]),\n OpInfo('linalg.svdvals',\n op=torch.linalg.svdvals,\n aten_name='linalg_svdvals',\n dtypes=floating_and_complex_types(),\n sample_inputs_func=sample_inputs_linalg_svdvals,\n check_batched_gradgrad=False,\n decorators=[\n skipCUDAIfNoMagmaAndNoCusolver,\n skipCPUIfNoLapack]),\n OpInfo('polar',\n dtypes=floating_types(),\n sample_inputs_func=sample_inputs_polar),\n # TODO(@kshitij12345): Refactor similar to `mvlgamma` entries.\n # To test reference numerics against multiple values of argument `n`,\n # we make multiple OpInfo entries with each entry corresponding to different value of n (currently 0 to 4).\n # We run the op tests from test_ops.py only for `n=0` to avoid redundancy in testing.\n UnaryUfuncInfo('polygamma',\n op=lambda x, n, **kwargs: torch.polygamma(n, x, **kwargs),\n variant_test_name='polygamma_n_0',\n ref=reference_polygamma if TEST_SCIPY else _NOTHING,\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_polygamma,\n skips=(\n # Probably related to the way the function is\n # scripted for JIT tests (or maybe not).\n # RuntimeError:\n # Arguments for call are not valid.\n # The following variants are available:\n # aten::polygamma(int n, Tensor self) -> (Tensor):\n # Expected a value of type 'Tensor' for argument 'self' but instead found type 'int'.\n # aten::polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> (Tensor(a!)):\n # Expected a value of type 'Tensor' for argument 'self' but instead found type 'int'.\n # The original call is:\n # File \"<string>\", line 3\n # def the_method(i0):\n # return torch.polygamma(i0, 1)\n # ~~~~~~~~~~~~~~~ <--- HERE\n SkipInfo('TestJit', 'test_variant_consistency_jit'),),\n sample_kwargs=lambda device, dtype, input: ({'n': 0}, {'n': 0})),\n # A separate OpInfo entry for special.polygamma is needed to reorder the arguments\n # for the alias. See the discussion here: https://github.com/pytorch/pytorch/pull/59691#discussion_r650261939\n UnaryUfuncInfo('special.polygamma',\n op=lambda x, n, **kwargs: torch.special.polygamma(n, x, **kwargs),\n variant_test_name='special_polygamma_n_0',\n ref=reference_polygamma if TEST_SCIPY else _NOTHING,\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_polygamma,\n skips=(\n # Probably related to the way the function is\n # scripted for JIT tests (or maybe not).\n # RuntimeError:\n # Arguments for call are not valid.\n # The following variants are available:\n # aten::polygamma(int n, Tensor self) -> (Tensor):\n # Expected a value of type 'Tensor' for argument 'self' but instead found type 'int'.\n # aten::polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> (Tensor(a!)):\n # Expected a value of type 'Tensor' for argument 'self' but instead found type 'int'.\n # The original call is:\n # File \"<string>\", line 3\n # def the_method(i0):\n # return torch.polygamma(i0, 1)\n # ~~~~~~~~~~~~~~~ <--- HERE\n SkipInfo('TestJit', 'test_variant_consistency_jit'),),\n sample_kwargs=lambda device, dtype, input: ({'n': 0}, {'n': 0})),\n UnaryUfuncInfo('polygamma',\n op=lambda x, n, **kwargs: torch.polygamma(n, x, **kwargs),\n variant_test_name='polygamma_n_1',\n ref=reference_polygamma if TEST_SCIPY else _NOTHING,\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_polygamma,\n skips=(\n # Redundant tests\n SkipInfo('TestGradients'),\n SkipInfo('TestJit'),\n SkipInfo('TestCommon'),\n # Mismatch: https://github.com/pytorch/pytorch/issues/55357\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal'),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard'),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal'),\n ),\n sample_kwargs=lambda device, dtype, input: ({'n': 1}, {'n': 1})),\n UnaryUfuncInfo('polygamma',\n op=lambda x, n, **kwargs: torch.polygamma(n, x, **kwargs),\n variant_test_name='polygamma_n_2',\n ref=reference_polygamma if TEST_SCIPY else _NOTHING,\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_polygamma,\n skips=(\n # Redundant tests\n SkipInfo('TestGradients'),\n SkipInfo('TestJit'),\n SkipInfo('TestCommon'),\n # Mismatch: https://github.com/pytorch/pytorch/issues/55357\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal'),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n active_if=TEST_WITH_ROCM),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n active_if=TEST_WITH_ROCM),),\n sample_kwargs=lambda device, dtype, input: ({'n': 2}, {'n': 2})),\n UnaryUfuncInfo('polygamma',\n op=lambda x, n, **kwargs: torch.polygamma(n, x, **kwargs),\n variant_test_name='polygamma_n_3',\n ref=reference_polygamma if TEST_SCIPY else _NOTHING,\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_polygamma,\n skips=(\n # Redundant tests\n SkipInfo('TestGradients'),\n SkipInfo('TestJit'),\n SkipInfo('TestCommon'),\n # Mismatch: https://github.com/pytorch/pytorch/issues/55357\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal'),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n active_if=TEST_WITH_ROCM),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n active_if=TEST_WITH_ROCM),),\n sample_kwargs=lambda device, dtype, input: ({'n': 3}, {'n': 3})),\n UnaryUfuncInfo('polygamma',\n op=lambda x, n, **kwargs: torch.polygamma(n, x, **kwargs),\n variant_test_name='polygamma_n_4',\n ref=reference_polygamma if TEST_SCIPY else _NOTHING,\n decorators=(precisionOverride({torch.float16: 5e-4, torch.float32: 5e-4}),),\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_polygamma,\n skips=(\n # Redundant tests\n SkipInfo('TestGradients'),\n SkipInfo('TestJit'),\n SkipInfo('TestCommon'),\n # Mismatch: https://github.com/pytorch/pytorch/issues/55357\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal'),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n active_if=TEST_WITH_ROCM),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n active_if=TEST_WITH_ROCM),),\n sample_kwargs=lambda device, dtype, input: ({'n': 4}, {'n': 4})),\n OpInfo('ravel',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_ravel,\n ),\n OpInfo('reshape',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_view_reshape,\n supports_out=False,\n supports_forward_ad=True,\n ),\n OpInfo('reshape_as',\n op=lambda x, other: x.reshape_as(other),\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_view_as_reshape_as,\n supports_out=False,\n supports_forward_ad=True,\n ),\n OpInfo('view',\n op=lambda x, shape: x.view(shape),\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # Because view does not have a function variant.\n SkipInfo('TestJit', 'test_variant_consistency_jit'),),\n sample_inputs_func=sample_inputs_view_reshape,\n ),\n OpInfo('view_as',\n op=lambda x, other: x.view_as(other),\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # Because view_as does not have a function variant.\n SkipInfo('TestJit', 'test_variant_consistency_jit'),),\n sample_inputs_func=sample_inputs_view_as_reshape_as,\n ),\n OpInfo('pinverse',\n op=torch.pinverse,\n dtypes=floating_and_complex_types(),\n check_batched_grad=False,\n check_batched_gradgrad=False,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n supports_out=False,\n sample_inputs_func=sample_inputs_linalg_invertible,\n decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfRocm, skipCPUIfNoLapack]),\n OpInfo('gather',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_gather,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n supports_forward_ad=True,\n ),\n OpInfo('index_fill',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_inplace_autograd=False,\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_index_fill),\n OpInfo('index_copy',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_inplace_autograd=False,\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_index_copy,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n OpInfo('index_select',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_index_select,\n supports_forward_ad=True,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n OpInfo('index_add',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_index_add,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n OpInfo('__getitem__',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_inplace_autograd=False,\n op=torch.Tensor.__getitem__,\n sample_inputs_func=sample_inputs_getitem,\n skips=(SkipInfo('TestJit', 'test_variant_consistency_jit'),)),\n OpInfo('index_put',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_inplace_autograd=True,\n supports_forward_ad=True,\n test_neg_view=False,\n sample_inputs_func=sample_inputs_index_put,\n skips=(\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n )),\n OpInfo('sort',\n dtypes=all_types_and(torch.bool, torch.float16, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bfloat16),\n dtypesIfROCM=all_types_and(torch.float16),\n sample_inputs_func=sample_inputs_sort,\n skips=(\n # sort does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n )),\n OpInfo('put',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n check_batched_gradgrad=False, # vmap complains of the sizes\n sample_inputs_func=sample_inputs_put),\n OpInfo('take',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n check_batched_grad=False, # vmap complains of the sizes\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_take),\n OpInfo('scatter',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_scatter,),\n OpInfo('scatter_add',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_scatter_add,\n supports_out=False),\n OpInfo('stack',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_stack,\n assert_autodiffed=True,\n skips=(\n # stack does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),),),\n OpInfo('hstack',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_hstack_dstack_vstack,\n supports_forward_ad=True,\n skips=(\n # hstack does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),),),\n OpInfo('hypot',\n dtypes=floating_types(),\n dtypesIfCPU=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_hypot,\n ),\n OpInfo('histogram',\n dtypes=_dispatch_dtypes(), # histogram is only implemented on CPU\n dtypesIfCPU=floating_types(),\n sample_inputs_func=sample_inputs_histogram,\n supports_autograd=False,\n skips=(\n # JIT tests don't work with Tensor keyword arguments\n # https://github.com/pytorch/pytorch/issues/58507\n SkipInfo('TestJit', 'test_variant_consistency_jit'),),),\n OpInfo('vstack',\n aliases=('row_stack',),\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_hstack_dstack_vstack,\n supports_forward_ad=True,\n skips=(\n # vstack does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n # RuntimeError: _fn() Expected a value of type\n # 'Tensor (inferred)' for argument 't0' but instead found type 'tuple'.\n SkipInfo('TestJit', 'test_jit_alias_remapping'))),\n OpInfo('dstack',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_hstack_dstack_vstack,\n supports_forward_ad=True,\n skips=(\n # dstack does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),)),\n OpInfo('unfold',\n op=lambda x, *args: x.unfold(*args),\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n check_batched_gradgrad=False,\n skips=(\n # torch.unfold does not exist so we get a RuntimeError.\n SkipInfo('TestJit', 'test_variant_consistency_jit',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16)),\n # Skip operator schema test because this is a functional and not an operator\n SkipInfo('TestOperatorSignatures', 'test_get_torch_func_signature_exhaustive'),\n ),\n sample_inputs_func=sample_inputs_unfold),\n OpInfo('msort',\n dtypes=all_types_and(torch.bool, torch.float16, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bfloat16),\n dtypesIfROCM=all_types_and(torch.float16),\n check_batched_gradgrad=False,\n skips=(\n # msort does not correctly warn when resizing out= inputs.\n SkipInfo('TestCommon', 'test_out',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16)),\n ),\n sample_inputs_func=sample_inputs_msort),\n OpInfo('movedim',\n aliases=('moveaxis',),\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_movedim_moveaxis),\n OpInfo('renorm',\n dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_renorm),\n ShapeFuncInfo('repeat',\n op=lambda x, dims: x.repeat(dims),\n ref=np.tile,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # torch.repeat does not exist so we get a RuntimeError.\n SkipInfo('TestJit', 'test_variant_consistency_jit',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16)),\n ),\n sample_inputs_func=sample_repeat_tile),\n OpInfo('squeeze',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n assert_autodiffed=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_squeeze),\n OpInfo('fill_',\n op=lambda x, scalar: torch.fill_(x.clone(), scalar),\n method_variant=None,\n inplace_variant=torch.Tensor.fill_,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n skips=(\n # JIT has issue when op is passed as lambda\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n sample_inputs_func=sample_inputs_fill_),\n OpInfo('resize_',\n op=lambda x, shape: x.clone().resize_(shape),\n method_variant=None,\n inplace_variant=None,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_autograd=False,\n sample_inputs_func=sample_inputs_resize_ops),\n OpInfo('resize_as_',\n op=lambda x, other: torch.resize_as_(x.clone(), other),\n method_variant=None,\n inplace_variant=torch.Tensor.resize_as_,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_autograd=False,\n sample_inputs_func=sample_inputs_resize_ops),\n OpInfo('take_along_dim',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_take_along_dim,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL),\n ShapeFuncInfo('tile',\n ref=np.tile,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_repeat_tile),\n OpInfo('trapz', # TODO: in the future, 'trapz' should be made a proper alias of 'trapezoid'\n dtypes=all_types_and_complex_and(torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_trapezoid),\n OpInfo('trapezoid',\n dtypes=all_types_and_complex_and(torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_trapezoid),\n OpInfo('cumulative_trapezoid',\n dtypes=all_types_and_complex_and(),\n dtypesIfCUDA=all_types_and_complex_and(torch.bfloat16, torch.float16),\n supports_forward_ad=True,\n supports_out=False,\n sample_inputs_func=sample_cumulative_trapezoid),\n OpInfo('unsqueeze',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n assert_autodiffed=True,\n sample_inputs_func=sample_unsqueeze),\n OpInfo('var',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=floating_and_complex_types_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCPU=floating_and_complex_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_std_var,\n # TODO: revisit, some var signatures do support out (see std, too)\n supports_out=False,\n assert_autodiffed=True,\n ),\n OpInfo('xlogy',\n aliases=('special.xlogy',),\n dtypes=all_types_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n safe_casts_outputs=True,\n sample_inputs_func=sample_inputs_xlogy),\n OpInfo('zero_',\n op=lambda x: torch.zero_(x.clone()),\n method_variant=None,\n inplace_variant=torch.Tensor.zero_,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n supports_forward_ad=True,\n skips=(\n # JIT has issue when op is passed as lambda\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n sample_inputs_func=sample_inputs_zero_),\n OpInfo('special.xlog1py',\n aten_name='special_xlog1py',\n dtypes=all_types_and(torch.bool, torch.half, torch.bfloat16),\n backward_dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_xlog1py),\n OpInfo('special.zeta',\n aten_name='special_zeta',\n dtypes=all_types_and(torch.bool),\n supports_autograd=False,\n safe_casts_outputs=True,\n sample_inputs_func=sample_inputs_binary_pwise),\n # OpInfo entry to verify the gradient formula of `other`/`q`\n OpInfo('special.zeta',\n op=lambda q, x, **kwargs: torch.special.zeta(x, q, **kwargs),\n aten_name='special_zeta',\n variant_test_name='grad',\n dtypes=all_types_and(torch.bool),\n supports_autograd=True,\n safe_casts_outputs=True,\n skips=(\n # Lambda doesn't work in JIT test\n SkipInfo(\"TestJit\", \"test_variant_consistency_jit\"),\n ),\n sample_inputs_func=sample_inputs_zeta),\n OpInfo('logsumexp',\n aliases=('special.logsumexp',),\n dtypes=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.bfloat16, torch.half),\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_logsumexp),\n OpInfo('trace',\n dtypes=all_types_and_complex(),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n supports_inplace_autograd=False,\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_trace),\n OpInfo('transpose',\n aliases=('swapdims', 'swapaxes'),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half),\n supports_out=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_transpose_swapdims),\n OpInfo('tril',\n dtypes=all_types_and_complex_and(torch.bool, torch.half),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_tril_triu),\n OpInfo('triu',\n dtypes=all_types_and_complex_and(torch.bool, torch.half),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_tril_triu),\n OpInfo('kron',\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n supports_inplace_autograd=False,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_kron),\n OpInfo('inner',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=all_types_and_complex_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n dtypesIfROCM=floating_and_complex_types_and(torch.half, torch.bfloat16),\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_inner,\n ),\n OpInfo('tensordot',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCPU=all_types_and_complex_and(torch.half, torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, *[torch.bfloat16] if CUDA11OrLater else []),\n dtypesIfROCM=floating_and_complex_types_and(torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n sample_inputs_func=sample_inputs_tensordot,\n skips=(\n # Currently failing due to an INTERNAL_ASSERT_FAILED error.\n # Reference: https://github.com/pytorch/pytorch/issues/56314\n SkipInfo(\"TestJit\", \"test_variant_consistency_jit\", dtypes=[torch.float32]),\n # Skip operator schema test because this is a functional and not an operator.\n # Reference: https://github.com/pytorch/pytorch/issues/54574\n SkipInfo('TestOperatorSignatures', 'test_get_torch_func_signature_exhaustive'),\n )\n ),\n OpInfo('to_sparse',\n op=lambda x, *args: x.to_sparse(*args),\n sample_inputs_func=sample_inputs_to_sparse,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n backward_dtypes=floating_types(),\n backward_dtypesIfCUDA=floating_types_and(torch.float16, torch.bfloat16),\n supports_out=False,\n check_batched_grad=False,\n check_batched_gradgrad=False,\n skips=(\n # TODO: FIXME: complex inputs requiring grad error in forward\n SkipInfo('TestCommon', 'test_dtypes'),\n # JIT has issue when op is passed as lambda\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n )\n ),\n OpInfo('logcumsumexp',\n dtypes=floating_types_and(),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCUDA=floating_types_and(),\n skips=(\n # AssertionError: UserWarning not triggered : Resized a non-empty tensor but did not warn about it.\n SkipInfo('TestCommon', 'test_out', dtypes=(torch.float32,), device_type='cuda'),\n ),\n sample_inputs_func=sample_inputs_logcumsumexp),\n UnaryUfuncInfo('sigmoid',\n aliases=('special.expit', ),\n ref=reference_sigmoid if TEST_SCIPY else _NOTHING,\n decorators=(precisionOverride({torch.float16: 1e-2,\n torch.complex64: 1e-1,\n torch.bfloat16: 1e-2}),),\n skips=(\n # TODO: FIXME: sigmoid fails on complex inputs that require grad\n SkipInfo('TestCommon', 'test_dtypes'),\n # Reference: https://github.com/pytorch/pytorch/issues/56012\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cuda', dtypes=[torch.complex64]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cuda', dtypes=[torch.complex64]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.cfloat, torch.cdouble])),\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n supports_forward_ad=True,\n assert_autodiffed=True),\n UnaryUfuncInfo('digamma',\n ref=scipy.special.digamma if TEST_SCIPY else _NOTHING,\n aliases=('special.psi', 'special.digamma',),\n decorators=(precisionOverride({torch.float16: 5e-1}),),\n dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n supports_forward_ad=True,\n safe_casts_outputs=True),\n UnaryUfuncInfo('special.entr',\n ref=scipy.special.entr if TEST_SCIPY else _NOTHING,\n aten_name='special_entr',\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.float16: 1e-1,\n torch.bfloat16: 1e-1}),),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n skips=(\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.bfloat16, torch.float16]),\n ),\n supports_inplace_autograd=False,\n safe_casts_outputs=True,\n sample_inputs_func=sample_inputs_entr),\n UnaryUfuncInfo('special.ndtri',\n ref=scipy.special.ndtri if TEST_SCIPY else _NOTHING,\n domain=(0, 1),\n aten_name='special_ndtri',\n dtypes=all_types_and(torch.bool),\n safe_casts_outputs=True),\n UnaryUfuncInfo('erf',\n ref=scipy.special.erf if TEST_SCIPY else _NOTHING,\n aliases=('special.erf', ),\n decorators=(precisionOverride({torch.float16: 1e-2,\n torch.bfloat16: 1e-2}),),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n safe_casts_outputs=True),\n UnaryUfuncInfo('erfc',\n ref=scipy.special.erfc if TEST_SCIPY else _NOTHING,\n aliases=('special.erfc', ),\n decorators=(precisionOverride({torch.float16: 1e-2,\n torch.bfloat16: 1e-2}),),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n assert_autodiffed=True,\n safe_casts_outputs=True),\n UnaryUfuncInfo('erfinv',\n ref=scipy.special.erfinv if TEST_SCIPY else _NOTHING,\n aliases=('special.erfinv', ),\n decorators=(precisionOverride({torch.float16: 1e-2,\n torch.bfloat16: 1e-2,\n torch.float32: 1e-4}),),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n safe_casts_outputs=True,\n domain=(-1, 1),\n skips=(\n # Reference: https://github.com/pytorch/pytorch/pull/49155#issuecomment-742664611\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n active_if=TEST_SCIPY and distutils.version.LooseVersion(scipy.__version__) < \"1.4.0\"),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n active_if=TEST_SCIPY and distutils.version.LooseVersion(scipy.__version__) < \"1.4.0\"),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n active_if=TEST_SCIPY and distutils.version.LooseVersion(scipy.__version__) < \"1.4.0\"),\n )),\n UnaryUfuncInfo('lgamma',\n ref=reference_lgamma if TEST_SCIPY else _NOTHING,\n aliases=('special.gammaln', ),\n decorators=(precisionOverride({torch.float16: 7e-1}),),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half),\n supports_forward_ad=True,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/pull/50140#discussion_r552615345\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n device_type='cpu', dtypes=[torch.bfloat16]),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n device_type='cpu', dtypes=[torch.bfloat16]),\n # Reference: https://github.com/pytorch/pytorch/pull/50140#issuecomment-756150214\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_extremal',\n dtypes=[torch.float32, torch.float64], active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_hard',\n dtypes=[torch.float32, torch.float64], active_if=IS_WINDOWS),\n SkipInfo('TestUnaryUfuncs', 'test_reference_numerics_normal',\n dtypes=[torch.float32, torch.float64], active_if=IS_WINDOWS),\n ),\n safe_casts_outputs=True),\n OpInfo(\n 'logdet',\n supports_out=False,\n sample_inputs_func=sample_inputs_logdet,\n decorators=(skipCPUIfNoLapack, skipCUDAIfNoMagma, skipCUDAIfRocm)),\n # `log_softmax` supports different dtypes based on whether `dtype` argument,\n # is passed or not. Hence two OpInfo entries, one with dtype and other without.\n OpInfo(\n 'log_softmax',\n aliases=('special.log_softmax', 'nn.functional.log_softmax'),\n supports_out=False,\n dtypes=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_softmax_variant,\n assert_autodiffed=True),\n OpInfo(\n 'log_softmax',\n variant_test_name='dtype',\n aliases=('special.log_softmax', 'nn.functional.log_softmax'),\n supports_out=False,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_softmax_variant, with_dtype=True),\n assert_autodiffed=True),\n UnaryUfuncInfo('logit',\n ref=scipy.special.logit if TEST_SCIPY else _NOTHING,\n domain=(0, 1),\n aliases=('special.logit', ),\n supports_forward_ad=True,\n decorators=(precisionOverride({torch.bfloat16: 5e-1,\n torch.float16: 5e-1}),),\n dtypes=all_types_and(torch.bool, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n sample_inputs_func=sample_inputs_logit,\n safe_casts_outputs=True),\n OpInfo('where',\n # Currently only the `input` is tested in gradcheck.\n # If we pass `condition` first, none of the input which supports\n # autograd will be tested. Hence the following lambda.\n op=lambda self, condition, other: torch.where(condition, self, other),\n sample_inputs_func=sample_inputs_where,\n supports_out=False,\n skips=(\n # test does not work with passing lambda for op\n SkipInfo('TestJit', 'test_variant_consistency_jit'),\n ),\n dtypes=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16)),\n # `torch.norm` has multiple code paths depending on the value of `p`.\n # These paths have different dtype support. Also JIT supports,\n # most variants but not all of them. So we split the OpInfo entries,\n # for `norm` based on the code-paths and JIT support.\n OpInfo('norm',\n sample_inputs_func=sample_inputs_norm,\n dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n skips=(\n # RuntimeError not raised :\n # Expected RuntimeError when calling with input.device=cpu and out.device=cuda\n SkipInfo('TestCommon', 'test_out'),\n )\n ),\n OpInfo('norm',\n variant_test_name='nuc',\n sample_inputs_func=sample_inputs_norm_nuc,\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],\n dtypes=floating_and_complex_types(),\n dtypesIfCUDA=floating_and_complex_types(),\n skips=(\n # RuntimeError not raised :\n # Expected RuntimeError when calling with input.device=cpu and out.device=cuda\n SkipInfo('TestCommon', 'test_out'),\n # RuntimeError:\n # Arguments for call are not valid.\n SkipInfo('TestJit', 'test_variant_consistency_jit', dtypes=(torch.complex64,)),\n # RuntimeError: aliasOp != torch::jit::getOperatorAliasMap().end()\n # INTERNAL ASSERT FAILED at \"../torch/csrc/jit/passes/utils/check_alias_annotation.cpp\":157,\n # please report a bug to PyTorch.\n SkipInfo('TestJit', 'test_variant_consistency_jit', dtypes=(torch.float32,)),\n )\n ),\n OpInfo('norm',\n variant_test_name='fro',\n sample_inputs_func=sample_inputs_norm_fro,\n dtypes=floating_and_complex_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n skips=(\n # RuntimeError not raised :\n # Expected RuntimeError when calling with input.device=cpu and out.device=cuda\n SkipInfo('TestCommon', 'test_out'),\n # RuntimeError:\n # Arguments for call are not valid.\n SkipInfo('TestJit', 'test_variant_consistency_jit', dtypes=(torch.complex64,)),\n # RuntimeError: aliasOp != torch::jit::getOperatorAliasMap().end()\n # INTERNAL ASSERT FAILED at \"../torch/csrc/jit/passes/utils/check_alias_annotation.cpp\":157,\n # please report a bug to PyTorch.\n SkipInfo('TestJit', 'test_variant_consistency_jit', dtypes=(torch.float32,)),\n )\n ),\n OpInfo('norm',\n variant_test_name='inf',\n sample_inputs_func=sample_inputs_norm_inf,\n dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n backward_dtypesIfCPU=floating_and_complex_types_and(torch.float16, torch.bfloat16),\n skips=(\n # following 3 tests failed intermittenly\n SkipInfo('TestJit', 'test_variant_consistency_jit',\n device_type='cpu', dtypes=(torch.complex64,)),\n SkipInfo('TestGradients', 'test_fn_grad',\n device_type='cpu', dtypes=(torch.complex128,)),\n SkipInfo('TestGradients', 'test_fn_gradgrad',\n device_type='cpu', dtypes=(torch.complex128,)),\n )\n ),\n OpInfo('t',\n sample_inputs_func=sample_inputs_t,\n supports_out=False,\n supports_forward_ad=True,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n assert_autodiffed=True,),\n UnaryUfuncInfo('special.erfcx',\n ref=scipy.special.erfcx if TEST_SCIPY else _NOTHING,\n aten_name='special_erfcx',\n decorators=(toleranceOverride({torch.float32: tol(atol=0, rtol=4e-6), }),),\n dtypes=all_types_and(torch.bool),\n safe_casts_outputs=True),\n OpInfo(\n \"nn.functional.one_hot\",\n ref=reference_one_hot,\n supports_out=False,\n dtypes=_dispatch_dtypes((torch.int64,)),\n sample_inputs_func=sample_inputs_one_hot,\n ),\n OpInfo(\n \"nn.functional.softplus\",\n ref=reference_softplus,\n sample_inputs_func=sample_inputs_softplus,\n dtypesIfCPU=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.bfloat16, torch.float16),\n supports_out=False,\n skips=(\n SkipInfo(\n \"TestJit\",\n \"test_variant_consistency_jit\",\n dtypes=(torch.float32,),\n ),\n ),\n ),\n OpInfo(\n \"nn.functional.mse_loss\",\n ref=reference_mse_loss,\n sample_inputs_func=sample_inputs_mse_loss,\n supports_out=False,\n dtypesIfCPU=floating_types_and(torch.float16),\n backward_dtypesIfCPU=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.bfloat16, torch.float16),\n skips=(\n SkipInfo(\n \"TestJit\",\n \"test_variant_consistency_jit\",\n dtypes=(torch.float32,),\n ),\n ),\n ),\n OpInfo(\n \"nn.functional.grid_sample\",\n ref=_NOTHING,\n dtypesIfCPU=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.float16),\n supports_out=False,\n sample_inputs_func=sample_inputs_grid_sample,\n supports_gradgrad=False,\n gradcheck_nondet_tol=1e-15,\n skips=(\n SkipInfo(\n \"TestJit\",\n \"test_variant_consistency_jit\",\n dtypes=(torch.float32,),\n ),\n ),\n ),\n]\n\n# Common operator groupings\nunary_ufuncs = [op for op in op_db if isinstance(op, UnaryUfuncInfo)]\nspectral_funcs = [op for op in op_db if isinstance(op, SpectralFuncInfo)]\nsparse_unary_ufuncs = [op for op in op_db if isinstance(op, UnaryUfuncInfo) and op.supports_sparse is True]\nshape_funcs = [op for op in op_db if isinstance(op, ShapeFuncInfo)]\n\n# TODO: review porting these to make_tensor\ndef index_variable(shape, max_indices, device=torch.device('cpu')):\n if not isinstance(shape, tuple):\n shape = (shape,)\n index = torch.rand(*shape, dtype=torch.double, device=device).mul_(max_indices).floor_().long()\n return index\n\ndef gather_variable(shape, index_dim, max_indices, duplicate=False, device=torch.device('cpu')):\n assert len(shape) == 2\n assert index_dim < 2\n batch_dim = 1 - index_dim\n index = torch.zeros(*shape, dtype=torch.long, device=device)\n for i in range(shape[index_dim]):\n index.select(index_dim, i).copy_(\n torch.randperm(max_indices, device=device)[:shape[batch_dim]])\n if duplicate:\n index.select(batch_dim, 0).copy_(index.select(batch_dim, 1))\n return index\n\ndef bernoulli_scalar():\n return torch.tensor(0, dtype=torch.bool).bernoulli_()\n\ndef mask_not_all_zeros(shape):\n assert len(shape) > 0\n while True:\n result = torch.randn(shape).gt(0)\n if result.sum() > 0:\n return result\n\n\n# TODO: move all tri/tril/triu testing to tensor creation op test suite and remove\n# these from here\ndef _compare_trilu_indices(\n self, row, col, offset=0, dtype=torch.long, device='cpu'):\n if row == 0 or col == 0:\n # have to handle this separately as tril and triu does not take\n # empty matrix as input\n self.assertEqual(\n torch.empty(0, 2, dtype=dtype, device=device).transpose(0, 1),\n torch.tril_indices(row, col, offset, dtype=dtype, device=device))\n\n self.assertEqual(\n torch.empty(0, 2, dtype=dtype, device=device).transpose(0, 1),\n torch.triu_indices(row, col, offset, dtype=dtype, device=device))\n\n else:\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(\n torch.ones(row, col, device='cpu')\n .tril(offset).nonzero().to(dtype).transpose(0, 1),\n torch.tril_indices(row, col, offset, dtype=dtype, device=device))\n\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(\n torch.ones(row, col, device='cpu')\n .tril(offset).nonzero().to(dtype).transpose(0, 1),\n torch.tril_indices(row, col, offset, dtype=dtype, device=device))\n\n\ndef _compare_large_trilu_indices(\n self, row, col, offset=0, dtype=torch.long, device='cpu'):\n l = torch.ones(row, col, dtype=dtype, device='cpu').tril(offset) \\\n .nonzero()[-100:-1, :].transpose(0, 1).to(device)\n torch.cuda.empty_cache()\n\n r = torch.tril_indices(\n row, col, offset, dtype=dtype, device=device)[:, -100:-1]\n self.assertEqual(l, r)\n torch.cuda.empty_cache()\n\n l = torch.ones(row, col, dtype=dtype, device='cpu').triu(offset) \\\n .nonzero()[-100:-1, :].transpose(0, 1).to(device)\n torch.cuda.empty_cache()\n\n r = torch.triu_indices(\n row, col, offset, dtype=dtype, device=device)[:, -100:-1]\n self.assertEqual(l, r)\n torch.cuda.empty_cache()\n\n# (\n# row\n# col\n# offset (optional)\n# dtype (optional)\n# )\ntri_tests_args = [\n (1, 1),\n (3, 3),\n (3, 3, 1),\n (3, 3, 2),\n (3, 3, 200),\n (3, 3, -1),\n (3, 3, -2),\n (3, 3, -200),\n (0, 3, 0),\n (0, 3, 1),\n (0, 3, -1),\n (3, 0, 0),\n (3, 0, 1),\n (3, 0, -1),\n (0, 0, 0),\n (0, 0, 1),\n (0, 0, -1),\n (3, 6, 0),\n (3, 6, 1),\n (3, 6, 3),\n (3, 6, 9),\n (3, 6, -1),\n (3, 6, -3),\n (3, 6, -9),\n (6, 3, 0),\n (6, 3, 1),\n (6, 3, 3),\n (6, 3, 9),\n (6, 3, -1),\n (6, 3, -3),\n (6, 3, -9),\n (258, 253, 1, torch.float32),\n (257, 258, 1, torch.float64),\n (258, 258, 1, torch.short),\n (3, 513, 1, torch.long),\n (513, 3, 1, torch.int),\n (513, 0, 1, torch.double),\n (1024, 1024),\n (1024, 1024, 500, torch.float32),\n (1024, 1024, 1023),\n (1024, 1024, -500),\n (1023, 1025),\n (1025, 1023, 1022),\n (1024, 1024, -500),\n (3, 2028),\n (3, 2028, 1),\n (3, 2028, -1),\n (2028, 3),\n (2028, 1),\n (2028, 1, -1)\n]\n\ntri_large_tests_args: List[Tuple[int, ...]] = [\n # Large test cases below are deliberately commented out to speed up CI\n # tests and to avoid OOM error. When modifying implementations of\n # tril_indices and triu_indices, please enable these tests and make sure\n # they pass.\n #\n # (1, 268435455),\n # (5000, 5000),\n # (10000, 10000),\n # (268435455, 1),\n # (134217727, 2, 1),\n # (2, 134217727, 1),\n # (536870901, 1),\n # (1, 536870901),\n # (268435455, 2, 1),\n # (2, 268435455, 1)\n]\n\n\ndef run_additional_tri_tests(self, device):\n x = torch.ones(\n 3, 3, dtype=torch.long, device=device, layout=torch.strided)\n l = x.tril(0).nonzero().transpose(0, 1)\n u = x.triu(0).nonzero().transpose(0, 1)\n self.assertEqual(l, torch.tril_indices(3, 3, device=device))\n self.assertEqual(\n l, torch.tril_indices(3, 3, device=device, layout=torch.strided))\n\n self.assertEqual(u, torch.triu_indices(3, 3, device=device))\n self.assertEqual(\n u, torch.triu_indices(3, 3, device=device, layout=torch.strided))\n\n self.assertRaises(\n RuntimeError,\n lambda: torch.triu_indices(\n 1, 1, device=device, layout=torch.sparse_coo))\n\n self.assertRaises(\n RuntimeError,\n lambda: torch.tril_indices(\n 1, 1, device=device, layout=torch.sparse_coo))\n\n# TODO: move into common_utils.py or the test suite(s) that use this\ndef unpack_variables(args):\n if isinstance(args, tuple):\n return tuple(unpack_variables(elem) for elem in args)\n else:\n return args\n\n\nclass dont_convert(tuple):\n pass\n\n\nnon_differentiable = collections.namedtuple('non_differentiable', ['tensor'])\n\n\n# TODO: move into common_utils.py or the test suite(s) that use this\ndef create_input(call_args, requires_grad=True, non_contiguous=False, call_kwargs=None, dtype=torch.double, device=None):\n if not isinstance(call_args, tuple):\n call_args = (call_args,)\n\n def map_arg(arg):\n def maybe_non_contig(tensor):\n return tensor if not non_contiguous else make_non_contiguous(tensor)\n\n def conjugate(tensor):\n return tensor.conj()\n\n if isinstance(arg, torch.Size) or isinstance(arg, dont_convert):\n return arg\n elif isinstance(arg, tuple) and len(arg) == 0:\n var = conjugate(torch.randn((), dtype=dtype, device=device))\n var.requires_grad = requires_grad\n return var\n elif isinstance(arg, tuple) and not isinstance(arg[0], torch.Tensor):\n return conjugate(maybe_non_contig(torch.randn(*arg, dtype=dtype, device=device))).requires_grad_(requires_grad)\n # double check casting\n elif isinstance(arg, non_differentiable):\n if isinstance(arg.tensor, torch.Tensor):\n if arg.tensor.dtype == torch.float:\n return maybe_non_contig(arg.tensor.to(dtype=torch.double, device=device))\n if arg.tensor.dtype == torch.cfloat:\n return conjugate(maybe_non_contig(arg.tensor.to(dtype=torch.cdouble, device=device)))\n return conjugate(maybe_non_contig(arg.tensor.to(device=device)))\n return conjugate(maybe_non_contig(arg.tensor.to(device=device)))\n elif isinstance(arg, torch.Tensor):\n if arg.dtype == torch.float:\n arg = arg.double()\n if arg.dtype == torch.cfloat:\n arg = arg.to(torch.cdouble)\n if arg.is_complex() != dtype.is_complex:\n raise RuntimeError(\"User provided tensor is real for a test that runs with complex dtype, \",\n \"which is not supported for now\")\n # NOTE: We do clone() after detach() here because we need to be able to change size/storage of v afterwards\n v = conjugate(maybe_non_contig(arg)).detach().to(device=device).clone()\n v.requires_grad = requires_grad and (v.is_floating_point() or v.is_complex())\n return v\n elif callable(arg):\n return map_arg(arg(dtype=dtype, device=device))\n else:\n return arg\n args_out = tuple(map_arg(arg) for arg in call_args)\n kwargs_out = {k: map_arg(v) for k, v in call_kwargs.items()} if call_kwargs else {}\n return args_out, kwargs_out\n"
] |
[
[
"torch.testing._internal.common_utils.random_symmetric_pd_matrix",
"numpy.amax",
"torch.testing._internal.common_utils.random_symmetric_matrix",
"torch.randint",
"torch.lu_unpack",
"numpy.sqrt",
"torch.zeros",
"torch.randperm",
"torch.testing.all_types_and",
"numpy.asarray",
"torch.testing.floating_and_complex_types_and",
"torch.testing.all_types_and_complex_and",
"torch.repeat_interleave",
"torch.testing._internal.common_utils.random_symmetric_psd_matrix",
"numpy.mean",
"torch.no_grad",
"torch.empty_strided",
"torch.testing.floating_types",
"torch.device",
"torch.testing._internal.common_utils.random_square_matrix_of_rank",
"torch.testing._internal.common_utils.is_iterable_of_tensors",
"numpy.exp",
"torch.topk",
"torch.finfo",
"torch.where",
"torch.ones",
"numpy.sinc",
"torch.testing._internal.common_device_type.skipIf",
"torch.randn",
"numpy.arange",
"torch.einsum",
"numpy.matmul",
"torch.tensor",
"torch.testing._internal.common_utils.make_tensor",
"torch.testing.all_types",
"torch.testing._internal.common_utils.random_well_conditioned_matrix",
"torch.triu_indices",
"torch.rand",
"torch.special.polygamma",
"torch.get_default_dtype",
"numpy.zeros",
"torch.testing.integral_types_and",
"numpy.log",
"torch.linalg.cholesky",
"torch.LongTensor",
"torch.empty",
"numpy.multiply",
"numpy.random.choice",
"numpy.amin",
"torch.cuda.empty_cache",
"torch.testing.all_types_and_complex",
"numpy.modf",
"torch.testing.complex_types",
"torch.tril_indices",
"torch.testing._internal.common_utils.random_fullrank_matrix_distinct_singular_value",
"torch.testing.make_non_contiguous",
"numpy.sum",
"torch.testing.floating_and_complex_types",
"torch.testing.floating_types_and",
"torch.linalg.svd",
"torch.testing._internal.common_device_type.tol",
"numpy.abs",
"numpy.put",
"torch.testing.double_types",
"torch.special.zeta",
"torch.testing._internal.common_utils.random_hermitian_pd_matrix",
"numpy.sign",
"torch.testing._internal.common_device_type.expectedFailure",
"torch.linalg.matrix_norm",
"torch.polygamma",
"torch.testing._internal.common_device_type.precisionOverride"
]
] |
uabeysinghe/tensorflow
|
[
"c3ecdfa4f186d43c061a508d5f891e082ceb6640"
] |
[
"tensorflow/lite/python/lite.py"
] |
[
"# Lint as: python2, 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\"\"\"TensorFlow Lite tooling helper functionality.\"\"\"\n\nimport enum\nimport functools\nimport pprint\nimport shutil\nimport tempfile\nimport time\nimport warnings\n\nfrom absl import logging\nimport six\nfrom six import PY2\n\nfrom google.protobuf import text_format as _text_format\nfrom google.protobuf.message import DecodeError\nfrom tensorflow.core.framework import graph_pb2 as _graph_pb2\nfrom tensorflow.lite.experimental.microfrontend.python.ops import audio_microfrontend_op # pylint: disable=unused-import\nfrom tensorflow.lite.python import conversion_metadata_schema_py_generated as conversion_metdata_fb\nfrom tensorflow.lite.python import lite_constants as constants\nfrom tensorflow.lite.python.convert import convert_graphdef as _convert_graphdef\nfrom tensorflow.lite.python.convert import convert_graphdef_with_arrays as _convert_graphdef_with_arrays\nfrom tensorflow.lite.python.convert import convert_jax_hlo as _convert_jax_hlo\nfrom tensorflow.lite.python.convert import convert_saved_model as _convert_saved_model\nfrom tensorflow.lite.python.convert import ConverterError # pylint: disable=unused-import\nfrom tensorflow.lite.python.convert import deduplicate_readonly_buffers as _deduplicate_readonly_buffers\nfrom tensorflow.lite.python.convert import mlir_quantize as _mlir_quantize\nfrom tensorflow.lite.python.convert import mlir_sparsify as _mlir_sparsify\nfrom tensorflow.lite.python.convert import OpsSet\nfrom tensorflow.lite.python.convert import toco_convert # pylint: disable=unused-import\nfrom tensorflow.lite.python.convert_phase import Component\nfrom tensorflow.lite.python.convert_phase import convert_phase\nfrom tensorflow.lite.python.convert_phase import SubComponent\nfrom tensorflow.lite.python.convert_saved_model import freeze_saved_model as _freeze_saved_model\nfrom tensorflow.lite.python.interpreter import Interpreter # pylint: disable=unused-import\nfrom tensorflow.lite.python.interpreter import load_delegate # pylint: disable=unused-import\nfrom tensorflow.lite.python.interpreter import OpResolverType # pylint: disable=unused-import\nfrom tensorflow.lite.python.metrics import metrics\nfrom tensorflow.lite.python.op_hint import convert_op_hints_to_stubs # pylint: disable=unused-import\nfrom tensorflow.lite.python.op_hint import is_ophint_converted as _is_ophint_converted\nfrom tensorflow.lite.python.op_hint import OpHint # pylint: disable=unused-import\nfrom tensorflow.lite.python.optimize import calibrator as _calibrator\nfrom tensorflow.lite.python.util import _xla_computation\nfrom tensorflow.lite.python.util import build_debug_info_func as _build_debug_info_func\nfrom tensorflow.lite.python.util import convert_debug_info_func as _convert_debug_info_func\nfrom tensorflow.lite.python.util import freeze_graph as _freeze_graph\nfrom tensorflow.lite.python.util import get_debug_info as _get_debug_info\nfrom tensorflow.lite.python.util import get_grappler_config as _get_grappler_config\nfrom tensorflow.lite.python.util import get_sparsity_modes as _get_sparsity_modes\nfrom tensorflow.lite.python.util import get_tensor_name as _get_tensor_name\nfrom tensorflow.lite.python.util import get_tensors_from_tensor_names as _get_tensors_from_tensor_names\nfrom tensorflow.lite.python.util import get_tf_type_name as _get_tf_type_name\nfrom tensorflow.lite.python.util import is_frozen_graph as _is_frozen_graph\nfrom tensorflow.lite.python.util import model_input_signature as _model_input_signature\nfrom tensorflow.lite.python.util import modify_model_io_type as _modify_model_io_type\nfrom tensorflow.lite.python.util import populate_conversion_metadata as _populate_conversion_metadata\nfrom tensorflow.lite.python.util import run_graph_optimizations as _run_graph_optimizations\nfrom tensorflow.lite.python.util import set_tensor_shapes as _set_tensor_shapes\nfrom tensorflow.lite.python.util import trace_model_call as _trace_model_call\nfrom tensorflow.lite.tools.optimize.debugging.python.debugger import QuantizationDebugger # pylint: disable=unused-import\nfrom tensorflow.lite.tools.optimize.debugging.python.debugger import QuantizationDebugOptions # pylint: disable=unused-import\nfrom tensorflow.python import saved_model as _saved_model\nfrom tensorflow.python.client import session as _session\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function as _def_function\nfrom tensorflow.python.eager import function as _function\nfrom tensorflow.python.framework import convert_to_constants as _convert_to_constants\nfrom tensorflow.python.framework import dtypes as _dtypes\nfrom tensorflow.python.framework import ops as _ops\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.framework.errors_impl import NotFoundError as _NotFoundError\nfrom tensorflow.python.framework.importer import import_graph_def as _import_graph_def\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.saved_model import loader_impl as _loader_impl\nfrom tensorflow.python.saved_model import save_options as _save_options\nfrom tensorflow.python.saved_model import signature_constants as _signature_constants\nfrom tensorflow.python.saved_model import tag_constants as _tag_constants\nfrom tensorflow.python.saved_model.load import load as _load\nfrom tensorflow.python.saved_model.loader_impl import parse_saved_model_with_debug_info as _parse_saved_model_with_debug_info\nfrom tensorflow.python.util import deprecation as _deprecation\nfrom tensorflow.python.util import keras_deps\nfrom tensorflow.python.util.tf_export import tf_export as _tf_export\n\n\n@_tf_export(\"lite.Optimize\")\nclass Optimize(enum.Enum):\n \"\"\"Enum defining the optimizations to apply when generating a tflite model.\n\n DEFAULT\n Default optimization strategy that quantizes model weights. Enhanced\n optimizations are gained by providing a representative dataset that\n quantizes biases and activations as well.\n Converter will do its best to reduce size and latency, while minimizing\n the loss in accuracy.\n\n OPTIMIZE_FOR_SIZE\n Deprecated. Does the same as DEFAULT.\n\n OPTIMIZE_FOR_LATENCY\n Deprecated. Does the same as DEFAULT.\n\n EXPERIMENTAL_SPARSITY\n Experimental flag, subject to change.\n\n Enable optimization by taking advantage of the sparse model weights\n trained with pruning.\n\n The converter will inspect the sparsity pattern of the model weights and\n do its best to improve size and latency.\n The flag can be used alone to optimize float32 models with sparse weights.\n It can also be used together with the DEFAULT optimization mode to\n optimize quantized models with sparse weights.\n \"\"\"\n\n # Default optimization strategy that quantizes model weights. Enhanced\n # optimizations are gained by providing a representative dataset that\n # quantizes biases and activations as well.\n # Converter will do its best to reduce size and latency, while minimizing\n # the loss in accuracy.\n DEFAULT = \"DEFAULT\"\n\n # Deprecated. Does the same as DEFAULT.\n OPTIMIZE_FOR_SIZE = \"OPTIMIZE_FOR_SIZE\"\n\n # Deprecated. Does the same as DEFAULT.\n OPTIMIZE_FOR_LATENCY = \"OPTIMIZE_FOR_LATENCY\"\n\n # Experimental flag, subject to change.\n # Enable optimization by taking advantage of the sparse model weights trained\n # with pruning.\n #\n # The converter will inspect the sparsity pattern of the model weights and do\n # its best to improve size and latency.\n # The flag can be used alone to optimize float32 models with sparse weights.\n # It can also be used together with the DEFAULT optimization mode to optimize\n # quantized models with sparse weights.\n # TODO(b/161560631): Add log message when this optimization is applied.\n EXPERIMENTAL_SPARSITY = \"EXPERIMENTAL_SPARSITY\"\n\n def __str__(self):\n return str(self.value)\n\n\n# TODO(b/198099651): move converter implementation out of lite.py\n@_tf_export(\"lite.RepresentativeDataset\")\nclass RepresentativeDataset(object):\n \"\"\"Representative dataset used to optimize the model.\n\n This is a generator function that provides a small dataset to calibrate or\n estimate the range, i.e, (min, max) of all floating-point arrays in the model\n (such as model input, activation outputs of intermediate layers, and model\n output) for quantization. Usually, this is a small subset of a few hundred\n samples randomly chosen, in no particular order, from the training or\n evaluation dataset.\n \"\"\"\n\n def __init__(self, input_gen):\n \"\"\"Creates a representative dataset.\n\n Args:\n input_gen: A generator function that generates input samples for the\n model and has the same order, type and shape as the inputs to the model.\n Usually, this is a small subset of a few hundred samples randomly\n chosen, in no particular order, from the training or evaluation dataset.\n \"\"\"\n self.input_gen = input_gen\n\n\n@_tf_export(\"lite.TargetSpec\")\nclass TargetSpec(object):\n \"\"\"Specification of target device used to optimize the model.\n\n Attributes:\n supported_ops: Experimental flag, subject to change. Set of `tf.lite.OpsSet`\n options, where each option represents a set of operators supported by the\n target device. (default {tf.lite.OpsSet.TFLITE_BUILTINS}))\n supported_types: Set of `tf.dtypes.DType` data types supported on the target\n device. If initialized, optimization might be driven by the smallest type\n in this set. (default set())\n experimental_select_user_tf_ops: Experimental flag, subject to change. Set\n of user's TensorFlow operators' names that are required in the TensorFlow\n Lite runtime. These ops will be exported as select TensorFlow ops in the\n model (in conjunction with the tf.lite.OpsSet.SELECT_TF_OPS flag). This is\n an advanced feature that should only be used if the client is using TF ops\n that may not be linked in by default with the TF ops that are provided\n when using the SELECT_TF_OPS path. The client is responsible for linking\n these ops into the target runtime.\n experimental_supported_backends: Experimental flag, subject to change.\n Set containing names of supported backends. Currently only \"GPU\" is\n supported, more options will be available later.\n \"\"\"\n\n def __init__(self,\n supported_ops=None,\n supported_types=None,\n experimental_select_user_tf_ops=None,\n experimental_supported_backends=None):\n if supported_ops is None:\n supported_ops = {OpsSet.TFLITE_BUILTINS}\n self.supported_ops = supported_ops\n if supported_types is None:\n supported_types = set()\n self.supported_types = supported_types\n if experimental_select_user_tf_ops is None:\n experimental_select_user_tf_ops = set()\n self.experimental_select_user_tf_ops = experimental_select_user_tf_ops\n self.experimental_supported_backends = experimental_supported_backends\n self._experimental_custom_op_registerers = []\n # Hint for the supported accumulation type used for inference. Typically\n # used for fp16 post-training quantization, where some models can use fp16\n # accumulators instead of the typical fp32 type.\n # TODO(b/188185962): Provide full API and authoring support for\n # reduced precision accumulation types.\n self._experimental_supported_accumulation_type = None\n\n\nclass QuantizationMode(object):\n \"\"\"QuantizationMode determines the quantization type from user options.\"\"\"\n\n def __init__(self,\n optimizations,\n target_spec,\n representative_dataset,\n graph_def,\n disable_per_channel=False,\n experimental_new_dynamic_range_quantizer=False,\n experimental_low_bit_qat=False,\n full_integer_quantization_bias_type=None):\n self._optimizations = optimizations\n for deprecated_optimization in [\n Optimize.OPTIMIZE_FOR_SIZE, Optimize.OPTIMIZE_FOR_LATENCY\n ]:\n if deprecated_optimization in self._optimizations:\n logging.warning(\n \"Optimization option %s is deprecated, please use optimizations=\"\n \"[Optimize.DEFAULT] instead.\", deprecated_optimization)\n\n self._target_spec = target_spec\n self._representative_dataset = representative_dataset\n self._graph_def = graph_def\n\n self._validate_int8_required()\n self._disable_per_channel = disable_per_channel\n\n self._enable_new_dynamic_range_quantizer = (\n experimental_new_dynamic_range_quantizer)\n # Allow training with lower than 8 bit weights to be converted\n # to constants with trained scale.\n self._experimental_low_bit_qat = experimental_low_bit_qat\n\n self._full_integer_quantization_bias_type = full_integer_quantization_bias_type\n self._validate_full_integer_quantization_bias_type()\n\n def is_post_training_int8_only_quantization(self):\n return (self.is_any_optimization_enabled() and\n self._representative_dataset is not None and\n not self._is_int16x8_target_required() and\n not self.is_allow_float() and\n self._is_int8_target_required())\n\n def is_post_training_int8_quantization_with_float_fallback(self):\n return (self.is_any_optimization_enabled() and\n self._representative_dataset is not None and\n not self._is_int16x8_target_required() and\n self.is_allow_float() and\n self._smallest_supported_type() == _dtypes.int8)\n\n def is_post_training_int8_quantization(self):\n return (self.is_post_training_int8_only_quantization() or\n self.is_post_training_int8_quantization_with_float_fallback())\n\n def is_post_training_int16x8_only_quantization(self):\n return (self.is_any_optimization_enabled() and\n self._representative_dataset is not None and\n self._is_int16x8_target_required() and\n not self.is_allow_float())\n\n def is_post_training_int16x8_quantization_with_float_fallback(self):\n return (self.is_any_optimization_enabled() and\n self._representative_dataset is not None and\n self._is_int16x8_target_required() and\n self.is_allow_float())\n\n def is_post_training_int16x8_quantization(self):\n return (self.is_post_training_int16x8_only_quantization() or\n self.is_post_training_int16x8_quantization_with_float_fallback())\n\n def is_post_training_integer_quantization(self):\n return (self.is_post_training_int8_quantization() or\n self.is_post_training_int16x8_quantization())\n\n def is_low_bit_quantize_aware_training(self):\n return (self.is_any_optimization_enabled() and\n self.is_quantization_aware_trained_model() and\n self._experimental_low_bit_qat)\n\n def is_quantization_aware_training(self):\n return (self.is_any_optimization_enabled() and\n self.is_quantization_aware_trained_model() and\n not self.is_low_bit_quantize_aware_training())\n\n def is_integer_quantization(self):\n return (self.is_post_training_integer_quantization() or\n self.is_quantization_aware_training() or\n self.is_low_bit_quantize_aware_training())\n\n def is_post_training_dynamic_range_quantization(self):\n # Post-training dynamic range quantization is only enabled if post-training\n # int8 quantization and training time quantization was not done.\n return (self.is_any_optimization_enabled() and\n self._representative_dataset is None and\n not self.is_quantization_aware_trained_model() and\n self._smallest_supported_type() == _dtypes.int8)\n\n def is_post_training_float16_quantization(self):\n return (self.is_any_optimization_enabled() and\n self._smallest_supported_type().size == 2 and\n _dtypes.float16 in self._target_spec.supported_types)\n\n def is_bfloat16_quantization(self):\n return (self.is_any_optimization_enabled() and\n self._smallest_supported_type().size == 2 and\n _dtypes.bfloat16 in self._target_spec.supported_types)\n\n def activations_type(self):\n if self.is_integer_quantization():\n if self._is_int16x8_target_required():\n return _dtypes.int16\n else:\n return _dtypes.int8\n else:\n return _dtypes.float32\n\n def bias_type(self):\n if self._full_integer_quantization_bias_type:\n return self._full_integer_quantization_bias_type\n\n if self.activations_type() == _dtypes.int16:\n return _dtypes.int64\n elif self.activations_type() == _dtypes.int8:\n return _dtypes.int32\n else:\n return _dtypes.float32\n\n def converter_flags(self, inference_ty=None, inference_input_ty=None):\n \"\"\"Flags to the converter.\"\"\"\n\n if self.is_integer_quantization():\n is_low_bit_qat = self.is_low_bit_quantize_aware_training()\n return {\n \"inference_type\": (inference_ty if inference_ty is not None else\n self.activations_type()),\n \"inference_input_type\": _dtypes.float32,\n \"post_training_quantize\": False, # disable dynamic range quantization\n \"quantize_to_float16\": False, # disable float16 quantization\n \"disable_infer_tensor_range\": is_low_bit_qat,\n \"use_fake_quant_num_bits\": is_low_bit_qat,\n }\n elif self.is_post_training_dynamic_range_quantization():\n return {\n \"inference_type\": _dtypes.float32,\n \"inference_input_type\": _dtypes.float32,\n \"post_training_quantize\": True, # enable dynamic range quantization\n \"quantize_to_float16\": False, # disable float16 quantization\n # experimental: disable per-channel (per-axis) quantization.\n \"disable_per_channel_quantization\":\n self._disable_per_channel,\n \"enable_mlir_dynamic_range_quantizer\":\n self._enable_new_dynamic_range_quantizer\n }\n elif self.is_post_training_float16_quantization():\n return {\n \"inference_type\": _dtypes.float32,\n \"inference_input_type\": _dtypes.float32,\n \"post_training_quantize\": True,\n \"quantize_to_float16\": True, # enable float16 quantization\n \"accumulation_type\":\n self._target_spec._experimental_supported_accumulation_type, # pylint: disable=protected-access\n \"allow_bfloat16\":\n self.is_bfloat16_quantization(),\n \"enable_mlir_dynamic_range_quantizer\":\n self._enable_new_dynamic_range_quantizer\n }\n else:\n # Note this might still trigger (uint8) quantization to be compatible with\n # the old converter.\n return {\n \"inference_type\": (\n inference_ty if inference_ty is not None else _dtypes.float32),\n \"inference_input_type\": inference_input_ty,\n \"post_training_quantize\": False, # enable dynamic range quantization\n \"quantize_to_float16\": False, # disable float16 quantization\n \"allow_bfloat16\": self.is_bfloat16_quantization()\n }\n\n # Below are helpers for the above functions.\n\n def _validate_int8_required(self):\n \"\"\"Int8 mode requires certain parameters to exist and be compatible.\"\"\"\n if not self._is_int8_target_required():\n return\n\n # Validate target_spec attibute.\n if (set(self._target_spec.supported_ops) == {OpsSet.TFLITE_BUILTINS_INT8}\n and not (set(self._target_spec.supported_types) == set() or\n set(self._target_spec.supported_types) == {_dtypes.int8})):\n raise ValueError(\n \"As full integer quantization has been enabled by setting \"\n \"`target_spec.supported_ops`={tf.lite.OpsSet.TFLITE_BUILTINS_INT8}, \"\n \"thus `target_spec.supported_types` should be left uninitizalized \"\n \"or set to {tf.int8}.\")\n if set(self._target_spec.supported_types) == {_dtypes.int8}:\n self._target_spec.supported_ops = {OpsSet.TFLITE_BUILTINS_INT8}\n\n # Check if representative_dataset is specified.\n if (not self._representative_dataset and\n not self.is_quantization_aware_training()):\n raise ValueError(\"For full integer quantization, a \"\n \"`representative_dataset` must be specified.\")\n\n # Update represenative dataset to the expected format.\n if self._representative_dataset:\n if not isinstance(self._representative_dataset, RepresentativeDataset):\n self._representative_dataset = RepresentativeDataset(\n self._representative_dataset)\n\n def _validate_full_integer_quantization_bias_type(self):\n \"\"\"Validates bias type for full interger quantization.\"\"\"\n bias_type = self._full_integer_quantization_bias_type\n if not bias_type:\n return\n\n if self.activations_type() == _dtypes.float32:\n raise ValueError(\n \"`full_integer_quantization_bias_type` is only supported for full integer quantization.\"\n )\n\n if self.activations_type() == _dtypes.int8 and bias_type != _dtypes.int32:\n raise ValueError(\n f\"Expected bias type to be `dtypes.int32` for Int8Quant. \"\n f\"Current setting bias type: {bias_type}\")\n\n if self.activations_type(\n ) == _dtypes.int16 and bias_type != _dtypes.int32 and bias_type != _dtypes.int64:\n raise ValueError(\n f\"Expected bias type to be `dtypes.int32` or `dtypes.int64` for \"\n f\"Int16Quant. Current setting bias type: {bias_type}\")\n\n def _is_int8_target_required(self):\n return (OpsSet.TFLITE_BUILTINS_INT8 in set(\n self._target_spec.supported_ops)) or (set(\n self._target_spec.supported_types) == set([_dtypes.int8]))\n\n def _is_int16x8_target_required(self):\n return (OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8\n in set(self._target_spec.supported_ops))\n\n def is_allow_float(self):\n return (OpsSet.TFLITE_BUILTINS in set(\n self._target_spec.supported_ops)) or (OpsSet.SELECT_TF_OPS in set(\n self._target_spec.supported_ops))\n\n def is_any_optimization_enabled(self):\n return bool(\n set(self._optimizations).intersection([\n Optimize.OPTIMIZE_FOR_LATENCY, Optimize.OPTIMIZE_FOR_SIZE,\n Optimize.DEFAULT\n ]))\n\n def _smallest_supported_type(self):\n if self._target_spec.supported_types:\n return min(self._target_spec.supported_types, key=lambda x: x.size)\n else:\n # The default smallest supported type is INT8.\n return _dtypes.int8\n\n def is_quantization_aware_trained_model(self):\n \"\"\"Checks if the graph contains any training-time quantization ops.\"\"\"\n training_quant_ops = frozenset({\n \"FakeQuantWithMinMaxVars\",\n \"FakeQuantWithMinMaxVarsPerChannel\",\n \"FakeQuantWithMinMaxArgs\",\n \"QuantizeAndDequantizeV2\",\n \"QuantizeAndDequantizeV3\",\n })\n\n if self._graph_def:\n for node_def in self._graph_def.node:\n if node_def.op in training_quant_ops:\n return True\n for function in self._graph_def.library.function:\n for node_def in function.node_def:\n if node_def.op in training_quant_ops:\n return True\n return False\n\n\nclass TFLiteConverterBase(object):\n \"\"\"Converter subclass to share functionality between V1 and V2 converters.\"\"\"\n\n # Stores the original model type temporarily to transmit the information\n # from the factory class methods to TFLiteConverterBase init function.\n _original_model_type = conversion_metdata_fb.ModelType.NONE\n\n def __init__(self):\n self.optimizations = set()\n self.representative_dataset = None\n self.target_spec = TargetSpec()\n self.allow_custom_ops = False\n self.experimental_new_converter = True\n self.experimental_new_quantizer = True\n self.experimental_enable_resource_variables = True\n self._experimental_calibrate_only = False\n self._experimental_sparsify_model = False\n self._experimental_disable_per_channel = False\n self._debug_info = None # contains the stack traces of all the original\n # nodes in the `GraphDef` to the converter.\n self.saved_model_dir = None\n self._saved_model_tags = None\n self._saved_model_version = 0\n self._saved_model_exported_names = []\n self._tflite_metrics = metrics.TFLiteConverterMetrics()\n self._collected_converter_params = {}\n self._experimental_disable_batchmatmul_unfold = False\n self._experimental_lower_tensor_list_ops = True\n self._experimental_default_to_single_batch_in_tensor_list_ops = False\n self._experimental_unfold_large_splat_constant = False\n self._experimental_tf_quantization_mode = None\n # If unset, bias:int32 is by default except 16x8 quant.\n # For 16x8 quant, bias:int64 is used to prevent any overflow by default.\n self._experimental_full_integer_quantization_bias_type = None\n # Initializes conversion metadata.\n self.exclude_conversion_metadata = False\n self._metadata = conversion_metdata_fb.ConversionMetadataT()\n self._metadata.environment = conversion_metdata_fb.EnvironmentT()\n self._metadata.options = conversion_metdata_fb.ConversionOptionsT()\n self._metadata.environment.tensorflowVersion = versions.__version__\n self._metadata.environment.modelType = self._get_original_model_type()\n self._experimental_enable_dynamic_update_slice = False\n self._experimental_preserve_assert_op = False\n\n # When the value is true, the MLIR quantantizer triggers dynamic range\n # quantization in MLIR instead of the old quantizer. Used only if\n # experimental_new_quantizer is on.\n self.experimental_new_dynamic_range_quantizer = True\n # Experimental flag to enable low-bit QAT in 8 bit.\n self._experimental_low_bit_qat = False\n\n def _grappler_config(self, optimizers=None):\n \"\"\"Creates a tf.compat.v1.ConfigProto for configuring Grappler.\n\n Args:\n optimizers: List of strings that represents the list of optimizers.\n\n Returns:\n tf.ConfigProto.\n \"\"\"\n if not optimizers:\n optimizers = []\n # MLIR converter will take care of constant folding instead of grappler.\n if not self.experimental_new_converter:\n optimizers.append(\"constfold\")\n\n is_only_flex_enabled = (\n set([OpsSet.SELECT_TF_OPS]) == set(self.target_spec.supported_ops))\n if is_only_flex_enabled:\n # The layout optimizer turns NHCW to NCHW. This provides performance\n # optimizations when Flex mode is enabled. However, this is not compatible\n # with builtin ops.\n optimizers.append(\"layout\")\n return _get_grappler_config(optimizers)\n\n def _quantize(self, result, input_type, output_type, activations_type,\n bias_type, allow_float):\n \"\"\"Quantize the model.\"\"\"\n # pylint: disable=protected-access\n custom_op_registerers_by_name = [\n x for x in self.target_spec._experimental_custom_op_registerers\n if isinstance(x, str)\n ]\n custom_op_registerers_by_func = [\n x for x in self.target_spec._experimental_custom_op_registerers\n if not isinstance(x, str)\n ]\n # pylint: enable=protected-access\n if not isinstance(self.representative_dataset, RepresentativeDataset):\n self.representative_dataset = RepresentativeDataset(\n self.representative_dataset)\n\n # Add intermediate tensors to the model if needed.\n result = _calibrator.add_intermediate_tensors(result)\n calibrate_quantize = _calibrator.Calibrator(result,\n custom_op_registerers_by_name,\n custom_op_registerers_by_func)\n if self._experimental_calibrate_only or self.experimental_new_quantizer:\n calibrated = calibrate_quantize.calibrate(\n self.representative_dataset.input_gen)\n\n if self._experimental_calibrate_only:\n return calibrated\n elif self.experimental_new_quantizer and (\n activations_type != _dtypes.int16):\n # TODO(b/175659372): remove the activations_type restriction and enable\n # it for all the activation types.\n return _mlir_quantize(\n calibrated,\n self._experimental_disable_per_channel,\n input_data_type=input_type,\n output_data_type=output_type)\n else:\n return calibrate_quantize.calibrate_and_quantize(\n self.representative_dataset.input_gen,\n input_type,\n output_type,\n allow_float,\n activations_type,\n bias_type,\n disable_per_channel=self._experimental_disable_per_channel)\n\n def _is_unknown_shapes_allowed(self):\n # Unknown dimensions are only allowed with the new converter.\n return self.experimental_new_converter\n\n def _get_base_converter_args(self):\n \"\"\"Returns the base converter args.\n\n Returns:\n {key str: val}\n \"\"\"\n args = {\n \"input_format\":\n constants.TENSORFLOW_GRAPHDEF,\n \"allow_custom_ops\":\n self.allow_custom_ops,\n \"debug_info\":\n self._debug_info,\n \"target_ops\":\n self.target_spec.supported_ops,\n \"enable_mlir_converter\":\n self.experimental_new_converter,\n \"select_user_tf_ops\":\n self.target_spec.experimental_select_user_tf_ops,\n \"supported_backends\":\n self.target_spec.experimental_supported_backends,\n \"unfold_batchmatmul\":\n not self._experimental_disable_batchmatmul_unfold,\n \"lower_tensor_list_ops\":\n self._experimental_lower_tensor_list_ops,\n \"unfold_large_splat_constant\":\n self._experimental_unfold_large_splat_constant,\n \"default_to_single_batch_in_tensor_list_ops\":\n self._experimental_default_to_single_batch_in_tensor_list_ops,\n \"tf_quantization_mode\":\n self._experimental_tf_quantization_mode,\n \"experimental_enable_resource_variables\":\n self.experimental_enable_resource_variables,\n \"enable_dynamic_update_slice\":\n self._experimental_enable_dynamic_update_slice,\n \"preserve_assert_op\":\n self._experimental_preserve_assert_op,\n }\n\n if self.saved_model_dir:\n args.update({\n \"saved_model_dir\": self.saved_model_dir,\n \"saved_model_version\": self._saved_model_version,\n \"saved_model_tags\": self._saved_model_tags,\n \"saved_model_exported_names\": self._saved_model_exported_names,\n })\n\n return args\n\n def _contains_function_with_implements_attr(self, saved_model_proto):\n meta_graph = saved_model_proto.meta_graphs[0]\n for function in meta_graph.graph_def.library.function:\n if function.attr.get(\"_implements\", None) or function.attr.get(\n \"api_implements\", None):\n return True\n return False\n\n def _parse_saved_model_args(self, always_enable_saved_model_import=False):\n \"\"\"Parses SavedModel arguments from the given Keras/RNN SavedModel.\n\n Args:\n always_enable_saved_model_import: Bool. When the value is true, it enables\n MLIR saved model import path regardless of checking the conditions.\n \"\"\"\n if not self.experimental_new_converter:\n self.saved_model_dir = None\n return\n if self.saved_model_dir:\n try:\n saved_model_proto, _ = (\n _parse_saved_model_with_debug_info(self.saved_model_dir))\n except OSError:\n # If it fails to read the given saved model, it will fall back to the\n # frozen graph def path.\n self.saved_model_dir = None\n return\n if (not always_enable_saved_model_import and\n not self._contains_function_with_implements_attr(saved_model_proto)):\n self.saved_model_dir = None\n return\n\n if not self._saved_model_exported_names:\n self._saved_model_exported_names = []\n self._saved_model_version = saved_model_proto.saved_model_schema_version\n if self._saved_model_version == 0:\n self.saved_model_dir = None\n logging.warning(\"SavedModel schema version is zero.\")\n return\n if self._saved_model_version not in [1, 2]:\n raise ValueError(\"SavedModel file format({0}) is not supported\".format(\n self._saved_model_version))\n\n def _sparsify_model(self):\n return Optimize.EXPERIMENTAL_SPARSITY in self.optimizations\n\n def _increase_conversion_attempt_metric(self):\n self._tflite_metrics.increase_counter_converter_attempt()\n\n def _increase_conversion_success_metric(self):\n self._tflite_metrics.increase_counter_converter_success()\n\n @classmethod\n def _set_original_model_type(cls, model_type):\n \"\"\"Stores the original model type.\"\"\"\n if model_type == conversion_metdata_fb.ModelType.NONE:\n raise ValueError(\"The original model type should be specified.\")\n cls._original_model_type = model_type\n\n def _get_original_model_type(self):\n \"\"\"One-time getter to return original model type and set it to NONE.\"\"\"\n model_type = TFLiteConverterBase._original_model_type\n TFLiteConverterBase._original_model_type = conversion_metdata_fb.ModelType.NONE\n return model_type\n\n def _save_conversion_params_metric(self,\n graph_def=None,\n inference_type=None,\n inference_input_type=None):\n \"\"\"Set conversion parameter metrics.\"\"\"\n converter_kwargs = self._collected_converter_params\n converter_kwargs.update(self._get_base_converter_args())\n\n # Optimization parameters.\n quant_mode = QuantizationMode(\n self.optimizations, self.target_spec, self.representative_dataset,\n graph_def, self._experimental_disable_per_channel,\n self.experimental_new_dynamic_range_quantizer,\n self._experimental_low_bit_qat,\n self._experimental_full_integer_quantization_bias_type)\n converter_kwargs.update({\n \"tf_version\":\n self._metadata.environment.tensorflowVersion,\n \"api_version\":\n self._metadata.environment.apiVersion,\n \"original_model_format\":\n self._metadata.environment.modelType,\n \"optimization_default\":\n quant_mode.is_any_optimization_enabled(),\n \"optimization_post_training_dynamic_range\":\n quant_mode.is_post_training_dynamic_range_quantization(),\n \"optimization_post_training_float16\":\n quant_mode.is_post_training_float16_quantization(),\n \"optimization_post_training_integer_quantize\":\n quant_mode.is_post_training_integer_quantization(),\n \"optimization_qat\":\n quant_mode.is_quantization_aware_training(),\n \"optimization_low_bit_qat\":\n quant_mode.is_low_bit_quantize_aware_training(),\n \"optimization_sparsify\":\n self._sparsify_model(),\n \"activations_type\":\n quant_mode.activations_type()\n })\n converter_kwargs.update(\n quant_mode.converter_flags(inference_type, inference_input_type))\n\n # pylint: disable=protected-access\n if self.target_spec._experimental_supported_accumulation_type:\n converter_kwargs.update({\n \"accumulation_type\":\n self.target_spec._experimental_supported_accumulation_type\n })\n # pylint: enable=protected-access\n\n def format_element(elem):\n if isinstance(elem, enum.Enum):\n return str(elem.value)\n return pprint.pformat(elem)\n\n def format_param(param):\n if isinstance(param, (list, tuple, set)):\n if not param:\n return \"None\" # Return None if empty.\n string_list = [format_element(x) for x in param]\n return \",\".join(sorted(string_list))\n return format_element(param)\n\n for key, value in converter_kwargs.items():\n self._tflite_metrics.set_converter_param(key, format_param(value))\n self._tflite_metrics.set_export_required()\n\n # Set conversion option metadata.\n self._metadata.options.allowCustomOps = self.allow_custom_ops\n self._metadata.options.enableSelectTfOps = (\n OpsSet.SELECT_TF_OPS in self.target_spec.supported_ops)\n self._metadata.options.forceSelectTfOps = (\n set([OpsSet.SELECT_TF_OPS]) == set(self.target_spec.supported_ops))\n self._metadata.options.modelOptimizationModes = []\n\n if quant_mode.is_post_training_float16_quantization():\n self._metadata.options.modelOptimizationModes.append(\n conversion_metdata_fb.ModelOptimizationMode.PTQ_FLOAT16)\n\n if quant_mode.is_post_training_dynamic_range_quantization():\n self._metadata.options.modelOptimizationModes.append(\n conversion_metdata_fb.ModelOptimizationMode.PTQ_DYNAMIC_RANGE)\n\n if quant_mode.is_post_training_int8_quantization():\n self._metadata.options.modelOptimizationModes.append(\n conversion_metdata_fb.ModelOptimizationMode.PTQ_FULL_INTEGER)\n\n if quant_mode.is_post_training_int16x8_quantization():\n self._metadata.options.modelOptimizationModes.append(\n conversion_metdata_fb.ModelOptimizationMode.PTQ_INT16)\n\n if quant_mode.is_quantization_aware_training():\n self._metadata.options.modelOptimizationModes.append(\n conversion_metdata_fb.ModelOptimizationMode\n .QUANTIZATION_AWARE_TRAINING)\n\n def _set_conversion_latency_metric(self, value):\n self._tflite_metrics.set_converter_latency(value)\n\n @convert_phase(Component.OPTIMIZE_TFLITE_MODEL)\n def _optimize_tflite_model(self, model, quant_mode, quant_io=True):\n \"\"\"Apply optimizations on a TFLite model.\"\"\"\n\n if quant_mode.is_integer_quantization():\n in_type, out_type = self.inference_input_type, self.inference_output_type\n\n if quant_mode.is_post_training_integer_quantization():\n q_in_type = in_type if in_type and quant_io else _dtypes.float32\n q_out_type = out_type if out_type and quant_io else _dtypes.float32\n q_activations_type = quant_mode.activations_type()\n q_bias_type = quant_mode.bias_type()\n q_allow_float = quant_mode.is_allow_float()\n model = self._quantize(model, q_in_type, q_out_type, q_activations_type,\n q_bias_type, q_allow_float)\n\n m_in_type = in_type if in_type else _dtypes.float32\n m_out_type = out_type if out_type else _dtypes.float32\n # Skip updating model io types if MLIR quantizer already takes care of it\n if not (quant_mode.is_post_training_integer_quantization() and\n self.experimental_new_quantizer and quant_io and\n (m_in_type in [_dtypes.int8, _dtypes.uint8, _dtypes.float32]) and\n (m_out_type in [_dtypes.int8, _dtypes.uint8, _dtypes.float32])):\n model = _modify_model_io_type(model, m_in_type, m_out_type)\n\n if self._sparsify_model():\n model = _mlir_sparsify(model)\n\n try:\n model = _deduplicate_readonly_buffers(model)\n except Exception: # pylint: disable=broad-except\n # Skip buffer deduplication when flatbuffer library is not ready to be\n # utilized.\n logging.warning(\n \"Buffer deduplication procedure will be skipped when flatbuffer \"\n \"library is not properly loaded\")\n\n return model\n\n def _convert_and_export_metrics(self, convert_func, *args, **kwargs):\n \"\"\"Wraps around convert function to export metrics.\n\n Args:\n convert_func: The convert function to wrap.\n *args: Positional arguments of the convert function.\n **kwargs: The keyword arguments of the convert function.\n\n Returns:\n The decorator to wrap the convert function.\n \"\"\"\n self._increase_conversion_attempt_metric()\n self._save_conversion_params_metric()\n start_time = time.process_time()\n result = convert_func(self, *args, **kwargs)\n elapsed_time_ms = (time.process_time() - start_time) * 1000\n if result:\n self._increase_conversion_success_metric()\n self._set_conversion_latency_metric(round(elapsed_time_ms))\n self._tflite_metrics.export_metrics()\n # Populates the conversion metadata.\n # TODO(b/202090541): Collects sparsity block size information.\n sparsity_modes = _get_sparsity_modes(result)\n self._metadata.options.modelOptimizationModes.extend(sparsity_modes)\n if not self.exclude_conversion_metadata:\n result = _populate_conversion_metadata(result, self._metadata)\n return result\n\n\ndef _export_metrics(convert_func):\n \"\"\"The decorator around convert function to export metrics.\"\"\"\n @functools.wraps(convert_func)\n def wrapper(self, *args, **kwargs):\n # pylint: disable=protected-access\n return self._convert_and_export_metrics(convert_func, *args, **kwargs)\n # pylint: enable=protected-access\n\n return wrapper\n\n\nclass TFLiteConverterBaseV2(TFLiteConverterBase):\n \"\"\"Converter subclass to share functionality between V2 converters.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor for TFLiteConverter.\"\"\"\n super(TFLiteConverterBaseV2, self).__init__()\n self.inference_input_type = _dtypes.float32\n self.inference_output_type = _dtypes.float32\n self._metadata.environment.apiVersion = 2\n\n def _validate_inference_input_output_types(self, quant_mode):\n \"\"\"Validate inference_input_type and inference_output_type flags.\"\"\"\n default_types = [_dtypes.float32]\n # We support integer input/output for integer quantized models only.\n if quant_mode.is_integer_quantization():\n if quant_mode.is_post_training_int16x8_quantization():\n all_types = default_types + [_dtypes.int16]\n else:\n all_types = default_types + [_dtypes.int8, _dtypes.uint8]\n if (self.inference_input_type not in all_types or\n self.inference_output_type not in all_types):\n all_types_names = [\"tf.\" + t.name for t in all_types]\n raise ValueError(\"The inference_input_type and inference_output_type \"\n \"must be in {}.\".format(all_types_names))\n elif (self.inference_input_type not in default_types or\n self.inference_output_type not in default_types):\n raise ValueError(\"The inference_input_type and inference_output_type \"\n \"must be tf.float32.\")\n\n @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.LOAD_SAVED_MODEL)\n def _load_saved_model(self, saved_model_dir, saved_model_tags):\n \"\"\"Load graph_def from saved model with the default serving signature key.\n\n Args:\n saved_model_dir: Directory of the SavedModel.\n saved_model_tags: Set of tags identifying the MetaGraphDef within the\n SavedModel to analyze.\n\n Returns:\n graph_def: The loaded GraphDef.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n \"\"\"\n graph = _ops.Graph()\n saved_model = _loader_impl.SavedModelLoader(saved_model_dir)\n saved_model.load_graph(graph, tags=saved_model_tags)\n meta_graph = saved_model.get_meta_graph_def_from_tags(saved_model_tags)\n graph_def = meta_graph.graph_def\n signature_def = meta_graph.signature_def[\n _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n input_tensors = [\n graph.get_tensor_by_name(signature_def.inputs[key].name)\n for key in signature_def.inputs\n ]\n output_tensors = [\n graph.get_tensor_by_name(signature_def.outputs[key].name)\n for key in signature_def.outputs\n ]\n return graph_def, input_tensors, output_tensors\n\n @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.VALIDATE_INPUTS)\n def _validate_inputs(self, graph_def, input_tensors):\n \"\"\"Validate the input parameters.\n\n Args:\n graph_def: The TensorFlow GraphDef.\n input_tensors: List of input tensors.\n Raise:\n ValueError:\n Input shape is not specified.\n Invalid quantization parameters.\n \"\"\"\n # Update conversion params with graph_def.\n self._save_conversion_params_metric(graph_def)\n self._quant_mode = QuantizationMode(\n self.optimizations, self.target_spec, self.representative_dataset,\n graph_def, self._experimental_disable_per_channel,\n self.experimental_new_dynamic_range_quantizer,\n self._experimental_low_bit_qat,\n self._experimental_full_integer_quantization_bias_type)\n self._validate_inference_input_output_types(self._quant_mode)\n\n if not self._is_unknown_shapes_allowed():\n # Checks dimensions in input tensor.\n for tensor in input_tensors:\n # Note that shape_list might be empty for scalar shapes.\n shape_list = tensor.shape.as_list()\n if None in shape_list[1:]:\n raise ValueError(\n \"None is only supported in the 1st dimension. Tensor '{0}' has \"\n \"invalid shape '{1}'.\".format(\n _get_tensor_name(tensor), shape_list))\n elif shape_list and shape_list[0] is None:\n # Set the batch size to 1 if undefined.\n shape = tensor.shape.as_list()\n shape[0] = 1\n tensor.set_shape(shape)\n\n if (self._trackable_obj is None or\n not hasattr(self._trackable_obj, \"graph_debug_info\")):\n self._debug_info = _get_debug_info(\n _build_debug_info_func(self._funcs[0].graph), graph_def)\n else:\n self._debug_info = _get_debug_info(\n _convert_debug_info_func(self._trackable_obj.graph_debug_info),\n graph_def)\n\n @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.OPTIMIZE_TF_MODEL)\n def _optimize_tf_model(self, graph_def, input_tensors, output_tensors,\n frozen_func):\n \"\"\"Run a Grappler pass to optimize the TensorFlow graph.\n\n Args:\n graph_def: Frozen GraphDef to be optimized.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n frozen_func: TensorFlow Graph.\n\n Returns:\n The optimized TensorFlow graph.\n \"\"\"\n grappler_config = self._grappler_config()\n # Skip running grappler when there are no optimizers to run. If not,\n # grappler will run with the default optimizer set and it will lead to\n # causing an unexpected behavior.\n if grappler_config.graph_options.rewrite_options.optimizers:\n graph_def = _run_graph_optimizations(\n graph_def,\n input_tensors,\n output_tensors,\n config=grappler_config,\n graph=frozen_func.graph)\n return graph_def\n\n def _convert_from_saved_model(self, graph_def):\n \"\"\"Helper method that converts saved model.\n\n Args:\n graph_def: GraphDef object for the model, used only for stats.\n\n Returns:\n The converted TFLite model.\n \"\"\"\n # Update conversion params with graph_def.\n self._save_conversion_params_metric(graph_def)\n # Get quantization options and do some sanity checks.\n quant_mode = QuantizationMode(\n self.optimizations, self.target_spec, self.representative_dataset,\n graph_def, self._experimental_disable_per_channel,\n self.experimental_new_dynamic_range_quantizer,\n self._experimental_low_bit_qat,\n self._experimental_full_integer_quantization_bias_type)\n self._validate_inference_input_output_types(quant_mode)\n converter_kwargs = {\n \"enable_tflite_resource_variables\":\n self.experimental_enable_resource_variables\n }\n converter_kwargs.update(self._get_base_converter_args())\n converter_kwargs.update(quant_mode.converter_flags())\n\n result = _convert_saved_model(**converter_kwargs)\n return self._optimize_tflite_model(\n result, quant_mode, quant_io=self.experimental_new_quantizer)\n\n def convert(self, graph_def, input_tensors, output_tensors):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Args:\n graph_def: Frozen TensorFlow GraphDef.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n\n Returns:\n The converted data in serialized format.\n\n Raises:\n ValueError:\n No concrete functions is specified.\n Multiple concrete functions are specified.\n Input shape is not specified.\n Invalid quantization parameters.\n \"\"\"\n self._validate_inputs(graph_def, input_tensors)\n converter_kwargs = self._get_base_converter_args()\n converter_kwargs.update(self._quant_mode.converter_flags())\n if not self.experimental_new_converter:\n logging.warning(\n \"Please consider switching to the new converter by setting \"\n \"experimental_new_converter=True. \"\n \"The old converter is deprecated.\")\n else:\n logging.info(\"Using new converter: If you encounter a problem \"\n \"please file a bug. You can opt-out \"\n \"by setting experimental_new_converter=False\")\n\n # Converts model.\n result = _convert_graphdef(\n input_data=graph_def,\n input_tensors=input_tensors,\n output_tensors=output_tensors,\n **converter_kwargs)\n\n return self._optimize_tflite_model(\n result, self._quant_mode, quant_io=self.experimental_new_quantizer)\n\n\nclass TFLiteSavedModelConverterV2(TFLiteConverterBaseV2):\n \"\"\"Converts the given SavedModel into TensorFlow Lite model.\n\n Attributes:\n saved_model_dir: Directory of the SavedModel.\n \"\"\"\n\n def __init__(self,\n saved_model_dir,\n saved_model_tags=None,\n saved_model_exported_names=None,\n trackable_obj=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n saved_model_dir: Directory of the SavedModel.\n saved_model_tags: Set of tags identifying the MetaGraphDef within the\n SavedModel to analyze. All tags in the tag set must be present. (default\n {tf.saved_model.SERVING}).\n saved_model_exported_names: Names to be exported when the saved model\n import path is on.\n trackable_obj: tf.AutoTrackable object associated with `funcs`. A\n reference to this object needs to be maintained so that Variables do not\n get garbage collected since functions have a weak reference to\n Variables. This is only required when the tf.AutoTrackable object is not\n maintained by the user (e.g. `from_saved_model`).\n \"\"\"\n super(TFLiteSavedModelConverterV2, self).__init__()\n self.saved_model_dir = saved_model_dir\n self._saved_model_tags = saved_model_tags\n self._saved_model_exported_names = saved_model_exported_names\n self._trackable_obj = trackable_obj\n self._parse_saved_model_args(always_enable_saved_model_import=True)\n\n @_export_metrics\n def convert(self):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Returns:\n The converted data in serialized format.\n\n Raises:\n ValueError:\n No concrete functions is specified.\n Multiple concrete functions are specified.\n Input shape is not specified.\n Invalid quantization parameters.\n \"\"\"\n graph_def, input_tensors, output_tensors = self._load_saved_model(\n self.saved_model_dir, self._saved_model_tags)\n # If we can't use saved model importer, then fallback\n # to frozen graph conversion path.\n if self.saved_model_dir is None or not self.experimental_new_converter:\n graph_def, _, _, _ = _freeze_saved_model(\n self.saved_model_dir, None, None, None, self._saved_model_tags,\n _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY)\n # We make sure to clear the saved_model_dir as there is some\n # legacy code down in the caller that checks this.\n # TODO(b/162537905): Clean these indirect dependencies.\n self.saved_model_dir = None\n return super(TFLiteSavedModelConverterV2,\n self).convert(graph_def, input_tensors, output_tensors)\n\n if self._trackable_obj is None:\n self._debug_info = _get_debug_info(\n _build_debug_info_func(self._funcs[0].graph), graph_def)\n else:\n self._debug_info = _get_debug_info(\n _convert_debug_info_func(self._trackable_obj.graph_debug_info),\n graph_def)\n\n return self._convert_from_saved_model(graph_def)\n\n\nclass TFLiteKerasModelConverterV2(TFLiteConverterBaseV2):\n \"\"\"Converts the given Keras model into TensorFlow Lite model.\"\"\"\n\n def __init__(self, keras_model, trackable_obj=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n keras_model: tf.Keras.Model.\n trackable_obj: tf.AutoTrackable object associated with `funcs`. A\n reference to this object needs to be maintained so that Variables do not\n get garbage collected since functions have a weak reference to\n Variables. This is only required when the tf.AutoTrackable object is not\n maintained by the user (e.g. `from_saved_model`).\n \"\"\"\n super(TFLiteKerasModelConverterV2, self).__init__()\n self._keras_model = keras_model\n self._trackable_obj = trackable_obj\n self.experimental_lower_to_saved_model = True\n\n @convert_phase(Component.PREPARE_TF_MODEL,\n SubComponent.CONVERT_KERAS_TO_SAVED_MODEL)\n def _convert_keras_to_saved_model(self, output_dir):\n \"\"\"Save Keras model to the SavedModel format.\n\n Args:\n output_dir: The output directory to save the SavedModel.\n\n Returns:\n graph_def: The frozen GraphDef.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n \"\"\"\n try:\n _saved_model.save(\n self._keras_model,\n output_dir,\n options=_save_options.SaveOptions(save_debug_info=True))\n except Exception: # pylint: disable=broad-except\n # When storing the given keras model to a saved model is failed, let's\n # use original keras model conversion pipeline.\n return None, None, None\n self.saved_model_dir = output_dir\n self._saved_model_tags = set([_tag_constants.SERVING])\n self._saved_model_exported_names = [\n _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n ]\n self._parse_saved_model_args(\n always_enable_saved_model_import=self.experimental_lower_to_saved_model)\n if self.saved_model_dir:\n graph_def, input_tensors, output_tensors = self._load_saved_model(\n self.saved_model_dir, self._saved_model_tags)\n self._trackable_obj = _load(self.saved_model_dir, self._saved_model_tags)\n return graph_def, input_tensors, output_tensors\n return None, None, None\n\n @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.FREEZE_KERAS_MODEL)\n def _freeze_keras_model(self):\n \"\"\"Freeze Keras model to frozen graph.\n\n Returns:\n graph_def: The frozen GraphDef.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n frozen_func: The frozen ConcreteFunction.\n \"\"\"\n input_signature = None\n # If the model's call is not a `tf.function`, then we need to first get its\n # input signature from `model_input_signature` method. We can't directly\n # call `trace_model_call` because otherwise the batch dimension is set\n # to None.\n # Once we have better support for dynamic shapes, we can remove this.\n if not isinstance(self._keras_model.call, _def_function.Function):\n # Pass `keep_original_batch_size=True` will ensure that we get an input\n # signature including the batch dimension specified by the user.\n # TODO(b/169898786): Use the Keras public API when TFLite moves out of TF\n input_signature = _model_input_signature(\n self._keras_model, keep_original_batch_size=True)\n\n # TODO(b/169898786): Use the Keras public API when TFLite moves out of TF\n func = _trace_model_call(self._keras_model, input_signature)\n concrete_func = func.get_concrete_function()\n self._funcs = [concrete_func]\n\n frozen_func, graph_def = (\n _convert_to_constants.convert_variables_to_constants_v2_as_graph(\n self._funcs[0], lower_control_flow=False))\n\n input_tensors = [\n tensor for tensor in frozen_func.inputs\n if tensor.dtype != _dtypes.resource\n ]\n output_tensors = frozen_func.outputs\n return graph_def, input_tensors, output_tensors, frozen_func\n\n def _convert_as_saved_model(self):\n \"\"\"Converts a Keras model as a saved model.\n\n Returns:\n The converted data in serialized format.\n \"\"\"\n temp_dir = tempfile.mkdtemp()\n try:\n graph_def, input_tensors, output_tensors = (\n self._convert_keras_to_saved_model(temp_dir))\n if self.saved_model_dir:\n return super(TFLiteKerasModelConverterV2,\n self).convert(graph_def, input_tensors, output_tensors)\n finally:\n shutil.rmtree(temp_dir, True)\n\n @_export_metrics\n def convert(self):\n \"\"\"Converts a keras model based on instance variables.\n\n Returns:\n The converted data in serialized format.\n\n Raises:\n ValueError:\n Multiple concrete functions are specified.\n Input shape is not specified.\n Invalid quantization parameters.\n \"\"\"\n saved_model_convert_result = self._convert_as_saved_model()\n if saved_model_convert_result:\n return saved_model_convert_result\n\n graph_def, input_tensors, output_tensors, frozen_func = (\n self._freeze_keras_model())\n\n graph_def = self._optimize_tf_model(graph_def, input_tensors,\n output_tensors, frozen_func)\n\n return super(TFLiteKerasModelConverterV2,\n self).convert(graph_def, input_tensors, output_tensors)\n\n\nclass TFLiteFrozenGraphConverterV2(TFLiteConverterBaseV2):\n \"\"\"Converts the given frozen graph into TensorFlow Lite model.\"\"\"\n\n def __init__(self, funcs, trackable_obj=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n funcs: List of TensorFlow ConcreteFunctions. The list should not contain\n duplicate elements.\n trackable_obj: tf.AutoTrackable object associated with `funcs`. A\n reference to this object needs to be maintained so that Variables do not\n get garbage collected since functions have a weak reference to\n Variables. This is only required when the tf.AutoTrackable object is not\n maintained by the user (e.g. `from_saved_model`).\n \"\"\"\n super(TFLiteFrozenGraphConverterV2, self).__init__()\n self._funcs = funcs\n self._trackable_obj = trackable_obj\n self.experimental_lower_to_saved_model = True\n\n @convert_phase(Component.PREPARE_TF_MODEL,\n SubComponent.FREEZE_CONCRETE_FUNCTION)\n def _freeze_concrete_function(self):\n \"\"\"Convert the given ConcreteFunction to frozen graph.\n\n Returns:\n graph_def: The frozen GraphDef.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n frozen_func: The frozen ConcreteFunction.\n\n Raises:\n ValueError: none or multiple ConcreteFunctions provided.\n \"\"\"\n # TODO(b/130297984): Add support for converting multiple function.\n\n if len(self._funcs) == 0: # pylint: disable=g-explicit-length-test\n raise ValueError(\"No ConcreteFunction is specified.\")\n\n if len(self._funcs) > 1:\n raise ValueError(\"This converter can only convert a single \"\n \"ConcreteFunction. Converting multiple functions is \"\n \"under development.\")\n\n frozen_func, graph_def = (\n _convert_to_constants.convert_variables_to_constants_v2_as_graph(\n self._funcs[0], lower_control_flow=False))\n\n input_tensors = [\n tensor for tensor in frozen_func.inputs\n if tensor.dtype != _dtypes.resource\n ]\n output_tensors = frozen_func.outputs\n return graph_def, input_tensors, output_tensors, frozen_func\n\n @convert_phase(Component.PREPARE_TF_MODEL,\n SubComponent.CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL)\n def _convert_concrete_functions_to_saved_model(self, output_dir):\n \"\"\"Save concrete functions to the SavedModel format.\n\n Args:\n output_dir: The output directory to save the SavedModel.\n\n Returns:\n graph_def: The frozen GraphDef.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n \"\"\"\n if len(self._funcs) == 0: # pylint: disable=g-explicit-length-test\n raise ValueError(\"No ConcreteFunction is specified.\")\n\n if not self.experimental_lower_to_saved_model:\n return None, None, None\n\n # Without the provided trackable obj, it is not able to serialize the given\n # concrete functions as a saved model format. Also when trackable obj is\n # a function, use the original concrete function conversion pipline.\n if (not self._trackable_obj or\n isinstance(self._trackable_obj, (_function.ConcreteFunction,\n _def_function.Function))):\n return None, None, None\n\n signatures = {}\n signature_keys = []\n try:\n if len(self._funcs) == 1:\n signatures[_signature_constants\n .DEFAULT_SERVING_SIGNATURE_DEF_KEY] = self._funcs[0]\n signature_keys = [\n _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n ]\n else:\n for func in self._funcs:\n signatures[func.graph.name] = func\n signature_keys.append(func.graph.name)\n\n _saved_model.save(\n self._trackable_obj,\n output_dir,\n signatures=signatures,\n options=_save_options.SaveOptions(save_debug_info=True))\n except Exception: # pylint: disable=broad-except\n # When storing the given concrete function to a saved model is failed,\n # let's use original concrete function conversion pipeline.\n return None, None, None\n\n self.saved_model_dir = output_dir\n self._saved_model_tags = set([_tag_constants.SERVING])\n self._saved_model_exported_names = signature_keys\n self._parse_saved_model_args(always_enable_saved_model_import=True)\n if self.saved_model_dir:\n graph_def, input_tensors, output_tensors = self._load_saved_model(\n self.saved_model_dir, self._saved_model_tags)\n self._trackable_obj = _load(self.saved_model_dir, self._saved_model_tags)\n return graph_def, input_tensors, output_tensors\n return None, None, None\n\n def _convert_as_saved_model(self):\n \"\"\"Converts the given concrete functions as a saved model format.\n\n Returns:\n The converted data in serialized format.\n \"\"\"\n temp_dir = tempfile.mkdtemp()\n try:\n graph_def, input_tensors, _ = (\n self._convert_concrete_functions_to_saved_model(temp_dir))\n if self.saved_model_dir:\n self._validate_inputs(graph_def, input_tensors)\n return self._convert_from_saved_model(graph_def)\n finally:\n shutil.rmtree(temp_dir, True)\n return None\n\n @_export_metrics\n def convert(self):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Returns:\n The converted data in serialized format.\n\n Raises:\n ValueError:\n No concrete functions is specified.\n Multiple concrete functions are specified.\n Input shape is not specified.\n Invalid quantization parameters.\n \"\"\"\n if self.experimental_lower_to_saved_model:\n saved_model_convert_result = self._convert_as_saved_model()\n if saved_model_convert_result:\n return saved_model_convert_result\n\n graph_def, input_tensors, output_tensors, frozen_func = (\n self._freeze_concrete_function())\n\n graph_def = self._optimize_tf_model(graph_def, input_tensors,\n output_tensors, frozen_func)\n\n return super(TFLiteFrozenGraphConverterV2,\n self).convert(graph_def, input_tensors, output_tensors)\n\n\nclass TFLiteJaxConverterV2(TFLiteConverterBaseV2):\n \"\"\"Converts the given jax model into TensorFlow Lite model.\"\"\"\n\n def __init__(self, serving_funcs, inputs):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n serving_funcs: A list functions of the serving func of the jax module, the\n model params should already be inlined. (e.g., `serving_func =\n functools.partial(model, params=params)`)\n inputs: Array of input tensor placeholders tuple,s like `jnp.zeros`. For\n example, wrapped in an array like\n \"[('input1', input1), ('input2', input2)]]\".\n Jax function is polymorphic, for example:\n ```python\n def add(a, b):\n return a + b\n ```\n Will yield different computations if different input signatures are passed\n in: Pass `add(10.0, 20.0)` will yield a scalar `add` while pass\n `add(np.random((100, 1)), np.random(100, 100))` will yield a broadcasting\n add. We will need the input information to do tracing for the converter\n to properly convert the model. So it's important to pass in the desired\n `input placeholders` with the correct input shape/type.\n\n In the converted tflite model:\n Currently: the function name will be default to main, the output names will\n be the traced outputs. The output ordering shall match the serving function.\n \"\"\"\n super(TFLiteJaxConverterV2, self).__init__()\n self._serving_funcs = serving_funcs\n self._inputs = inputs\n\n @_export_metrics\n def convert(self):\n \"\"\"Converts a Jax serving func based on instance variables.\n\n Returns:\n The converted data in serialized format.\n\n Raises:\n ImportError:\n If cannot import the xla_computation from jax.\n ValueError:\n No serving function is specified.\n Input tensors are not specified.\n The truth value of an array with more than one element is ambiguous.\n Failed to convert the given Jax function to hlo.\n\n \"\"\"\n if not _xla_computation:\n raise ImportError(\"Cannot import xla_computation from jax.\")\n\n if not self._serving_funcs:\n raise ValueError(\"No serving func is specified.\")\n\n if not self._inputs:\n raise ValueError(\"Input tensors are not specified.\")\n\n if len(self._inputs) != len(self._serving_funcs):\n msg = (\"Input tensor mapping len {} does not match serving func len {}.\"\n .format(len(self._inputs), len(self._serving_funcs)))\n raise ValueError(msg)\n\n if not isinstance(self._inputs, (tuple, list)):\n raise ValueError(\n \"Input tensors should be pass in a tuple list wrapped in an array.\")\n\n # TODO(b/197690428): Support multiple functions.\n # Currently only support one serving function.\n if len(self._serving_funcs) > 1:\n raise ValueError(\"Currently only support single serving function.\")\n\n if not isinstance(self._inputs[0], (tuple, list)):\n raise ValueError(\"The input placeholders are not a dictionary.\")\n\n input_names = []\n ordered_inputs = []\n for input_name, tensor in self._inputs[0]:\n input_names.append(input_name)\n ordered_inputs.append(tensor)\n\n try:\n xla_compuation = _xla_computation(self._serving_funcs[0], backend=\"cpu\")\n hlo_proto = xla_compuation(\n *ordered_inputs).as_serialized_hlo_module_proto()\n except Exception: # pylint: disable=broad-except\n raise ValueError(\"Failed to convert the given Jax function to hlo.\")\n\n # We need to set the hlo proto, and here we use serialized proto format\n # since it's more compact.\n converter_kwargs = {\n \"input_content\": hlo_proto,\n \"input_names\": input_names,\n \"is_proto_format\": True\n }\n converter_kwargs.update(self._get_base_converter_args())\n\n # Get quantization options and do some checks.\n quant_mode = QuantizationMode(self.optimizations, self.target_spec,\n self.representative_dataset, None)\n self._validate_inference_input_output_types(quant_mode)\n converter_kwargs.update(quant_mode.converter_flags())\n result = _convert_jax_hlo(**converter_kwargs)\n\n return self._optimize_tflite_model(\n result, quant_mode, quant_io=self.experimental_new_quantizer)\n\n\n@_tf_export(\"lite.TFLiteConverter\", v1=[])\nclass TFLiteConverterV2(TFLiteFrozenGraphConverterV2):\n \"\"\"Converts a TensorFlow model into TensorFlow Lite model.\n\n Attributes:\n optimizations: Experimental flag, subject to change. Set of optimizations to\n apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a\n set of values of type `tf.lite.Optimize`)\n representative_dataset: A generator function used for integer quantization\n where each generated sample has the same order, type and shape as the\n inputs to the model. Usually, this is a small subset of a few hundred\n samples randomly chosen, in no particular order, from the training or\n evaluation dataset. This is an optional attribute, but required for full\n integer quantization, i.e, if `tf.int8` is the only supported type in\n `target_spec.supported_types`. Refer to `tf.lite.RepresentativeDataset`.\n (default None)\n target_spec: Experimental flag, subject to change. Specifications of target\n device, including supported ops set, supported types and a set of user's\n defined TensorFlow operators required in the TensorFlow Lite runtime.\n Refer to `tf.lite.TargetSpec`.\n inference_input_type: Data type of the input layer. Note that integer types\n (tf.int8 and tf.uint8) are currently only supported for post training\n integer quantization and quantization aware training. (default tf.float32,\n must be in {tf.float32, tf.int8, tf.uint8})\n inference_output_type: Data type of the output layer. Note that integer\n types (tf.int8 and tf.uint8) are currently only supported for post\n training integer quantization and quantization aware training. (default\n tf.float32, must be in {tf.float32, tf.int8, tf.uint8})\n allow_custom_ops: Boolean indicating whether to allow custom operations.\n When False, any unknown operation is an error. When True, custom ops are\n created for any op that is unknown. The developer needs to provide these\n to the TensorFlow Lite runtime with a custom resolver. (default False)\n exclude_conversion_metadata: Whether not to embed the conversion metadata\n into the converted model. (default False)\n experimental_new_converter: Experimental flag, subject to change. Enables\n MLIR-based conversion. (default True)\n experimental_new_quantizer: Experimental flag, subject to change. Enables\n MLIR-based quantization conversion instead of Flatbuffer-based conversion.\n (default True)\n experimental_enable_resource_variables: Experimental flag, subject to\n change. Enables resource variables to be converted by this converter. This\n is only allowed if from_saved_model interface is used. (default True)\n\n Example usage:\n\n ```python\n # Converting a SavedModel to a TensorFlow Lite model.\n converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)\n tflite_model = converter.convert()\n\n # Converting a tf.Keras model to a TensorFlow Lite model.\n converter = tf.lite.TFLiteConverter.from_keras_model(model)\n tflite_model = converter.convert()\n\n # Converting ConcreteFunctions to a TensorFlow Lite model.\n converter = tf.lite.TFLiteConverter.from_concrete_functions([func], model)\n tflite_model = converter.convert()\n\n # Converting a Jax model to a TensorFlow Lite model.\n converter = tf.lite.TFLiteConverter.experimental_from_jax([func], [[\n ('input1', input1), ('input2', input2)])\n tflite_model = converter.convert()\n ```\n \"\"\"\n\n # pylint: disable=useless-super-delegation\n def __init__(self, funcs, trackable_obj=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n funcs: List of TensorFlow ConcreteFunctions. The list should not contain\n duplicate elements.\n trackable_obj: tf.AutoTrackable object associated with `funcs`. A\n reference to this object needs to be maintained so that Variables do not\n get garbage collected since functions have a weak reference to\n Variables. This is only required when the tf.AutoTrackable object is not\n maintained by the user (e.g. `from_saved_model`).\n \"\"\"\n super(TFLiteConverterV2, self).__init__(funcs, trackable_obj)\n\n @classmethod\n def from_concrete_functions(cls, funcs, trackable_obj=None):\n \"\"\"Creates a TFLiteConverter object from ConcreteFunctions.\n\n Args:\n funcs: List of TensorFlow ConcreteFunctions. The list should not contain\n duplicate elements. Currently converter can only convert a single\n ConcreteFunction. Converting multiple functions is under development.\n trackable_obj: An `AutoTrackable` object (typically `tf.module`)\n associated with `funcs`. A reference to this object needs to be\n maintained so that Variables do not get garbage collected since\n functions have a weak reference to Variables.\n\n Returns:\n TFLiteConverter object.\n\n Raises:\n Invalid input type.\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.TF_CONCRETE_FUNCTIONS)\n # pylint: enable=protected-access\n if trackable_obj is None:\n logging.warning(\n \"Please consider providing the trackable_obj argument in the \"\n \"from_concrete_functions. Providing without the trackable_obj \"\n \"argument is deprecated and it will use the deprecated conversion \"\n \"path.\")\n for func in funcs:\n if not isinstance(func, _function.ConcreteFunction):\n message = \"This function takes in a list of ConcreteFunction.\"\n if isinstance(func, _def_function.Function):\n message += (\" To get the ConcreteFunction from a Function,\"\n \" call get_concrete_function.\")\n raise ValueError(message)\n return cls(funcs, trackable_obj)\n\n @classmethod\n def from_saved_model(cls, saved_model_dir, signature_keys=None, tags=None):\n \"\"\"Creates a TFLiteConverter object from a SavedModel directory.\n\n Args:\n saved_model_dir: SavedModel directory to convert.\n signature_keys: List of keys identifying SignatureDef containing inputs\n and outputs. Elements should not be duplicated. By default the\n `signatures` attribute of the MetaGraphdef is used. (default\n saved_model.signatures)\n tags: Set of tags identifying the MetaGraphDef within the SavedModel to\n analyze. All tags in the tag set must be present. (default\n {tf.saved_model.SERVING} or {'serve'})\n\n Returns:\n TFLiteConverter object.\n\n Raises:\n Invalid signature keys.\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.TF_SAVED_MODEL)\n # pylint: enable=protected-access\n # When run without eager enabled, this will return the legacy\n # TFLiteConverter.\n if not context.executing_eagerly():\n signature_key = None\n if signature_keys:\n if len(signature_keys) != 1:\n raise ValueError(\"Only support a single signature key.\")\n else:\n signature_key = signature_keys[0]\n logging.warning(\"Invoking the TF1 implementation of TFLiteConverter \"\n \"because eager is disabled. Consider enabling eager.\")\n return TFLiteConverter.from_saved_model(\n saved_model_dir, signature_key=signature_key, tag_set=tags)\n\n # Ensures any graphs created in Eager mode are able to run. This is required\n # in order to create a tf.estimator.Exporter that exports a TFLite model.\n if tags is None:\n tags = set([_tag_constants.SERVING])\n\n with context.eager_mode():\n saved_model = _load(saved_model_dir, tags)\n if not signature_keys:\n signature_keys = saved_model.signatures\n\n if not signature_keys:\n raise ValueError(\"Only support at least one signature key.\")\n\n funcs = []\n for key in signature_keys:\n if key not in saved_model.signatures:\n raise ValueError(\"Invalid signature key '{}' found. Valid keys are \"\n \"'{}'.\".format(key, \",\".join(saved_model.signatures)))\n funcs.append(saved_model.signatures[key])\n\n saved_model_converter = TFLiteSavedModelConverterV2(saved_model_dir, tags,\n signature_keys,\n saved_model)\n if saved_model_converter.saved_model_dir:\n return saved_model_converter\n\n return cls(funcs, saved_model)\n\n @classmethod\n def from_keras_model(cls, model):\n \"\"\"Creates a TFLiteConverter object from a Keras model.\n\n Args:\n model: tf.Keras.Model\n\n Returns:\n TFLiteConverter object.\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.KERAS_MODEL)\n # pylint: enable=protected-access\n return TFLiteKerasModelConverterV2(model)\n\n @classmethod\n def experimental_from_jax(cls, serving_funcs, inputs):\n # Experimental API, subject to changes.\n # TODO(b/197690428): Currently only support single function.\n \"\"\"Creates a TFLiteConverter object from a Jax model with its inputs.\n\n Args:\n serving_funcs: A array of Jax functions with all the weights applied\n already.\n inputs: A array of Jax input placeholders tuples list, e.g.,\n jnp.zeros(INPUT_SHAPE). Each tuple list should correspond with the\n serving function.\n\n Returns:\n TFLiteConverter object.\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.JAX)\n # pylint: enable=protected-access\n return TFLiteJaxConverterV2(serving_funcs, inputs)\n\n # pylint: disable=useless-super-delegation\n def convert(self):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Returns:\n The converted data in serialized format.\n\n Raises:\n ValueError:\n No concrete functions is specified.\n Multiple concrete functions are specified.\n Input shape is not specified.\n Invalid quantization parameters.\n \"\"\"\n return super(TFLiteConverterV2, self).convert()\n\n\nclass TFLiteConverterBaseV1(TFLiteConverterBase):\n \"\"\"Converter subclass to share functionality between V1 converters.\"\"\"\n\n def __init__(self, experimental_debug_info_func):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n experimental_debug_info_func: An experimental function to retrieve the\n graph debug info for a set of nodes from the `graph_def`.\n \"\"\"\n super(TFLiteConverterBaseV1, self).__init__()\n self.inference_type = _dtypes.float32\n self.inference_input_type = None\n self.inference_output_type = None\n self.output_format = constants.TFLITE\n self.quantized_input_stats = {}\n self.default_ranges_stats = None\n self.drop_control_dependency = True\n self.reorder_across_fake_quant = False\n self.change_concat_input_ranges = False\n self.dump_graphviz_dir = None\n self.dump_graphviz_video = False\n self.conversion_summary_dir = None\n self._debug_info_func = experimental_debug_info_func\n self._experimental_allow_all_select_tf_ops = False\n self._metadata.environment.apiVersion = 1\n\n def __setattr__(self, name, value):\n if name == \"post_training_quantize\":\n warnings.warn(\"Property %s is deprecated, \"\n \"please use optimizations=[Optimize.DEFAULT]\"\n \" instead.\" % name)\n if value:\n self.optimizations = [Optimize.DEFAULT]\n else:\n self.optimizations = []\n return\n if name == \"target_ops\":\n warnings.warn(\"Property %s is deprecated, please use \"\n \"target_spec.supported_ops instead.\" % name)\n self.target_spec.supported_ops = value\n return\n object.__setattr__(self, name, value)\n\n def __getattribute__(self, name):\n if name == \"post_training_quantize\":\n warnings.warn(\"Property %s is deprecated, \"\n \"please use optimizations=[Optimize.DEFAULT]\"\n \" instead.\" % name)\n return Optimize.DEFAULT in set(self.optimizations)\n if name == \"target_ops\":\n warnings.warn(\"Property %s is deprecated, please use \"\n \"target_spec.supported_ops instead.\" % name)\n return self.target_spec.supported_ops\n return object.__getattribute__(self, name)\n\n def _validate_quantized_input_stats(self, converter_kwargs, quant_mode):\n \"\"\"Ensure the `quantized_input_stats` flag is provided if required.\"\"\"\n\n quantized_types = frozenset({_dtypes.int8, _dtypes.uint8})\n\n requires_quantized_input_stats = (\n (converter_kwargs[\"inference_type\"] in quantized_types or\n converter_kwargs[\"inference_input_type\"] in quantized_types) and\n not quant_mode.is_post_training_integer_quantization())\n\n if (requires_quantized_input_stats and\n not converter_kwargs[\"quantized_input_stats\"]):\n raise ValueError(\n \"The `quantized_input_stats` flag must be defined when either \"\n \"`inference_type` flag or `inference_input_type` flag is set to \"\n \"tf.int8 or tf.uint8. Currently, `inference_type={}` and \"\n \"`inference_input_type={}`.\".format(\n _get_tf_type_name(converter_kwargs[\"inference_type\"]),\n _get_tf_type_name(converter_kwargs[\"inference_input_type\"])))\n\n @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.VALIDATE_INPUTS)\n def _validate_inputs(self, input_tensors, quantized_input_stats):\n \"\"\"Validate input parameters.\n\n Args:\n input_tensors: List of input tensors.\n quantized_input_stats: Map of input tensor names to a tuple of floats\n representing the mean and standard deviation of the training data.\n\n Raises:\n ValueError:\n Input shape is not specified.\n Quantization input stats is required but not provided.\n \"\"\"\n\n if (not self._is_unknown_shapes_allowed() and self._has_valid_tensors()):\n # Checks dimensions in input tensor.\n for tensor in input_tensors:\n shape = tensor.shape\n if not shape:\n raise ValueError(\"Provide an input shape for input array \"\n \"'{0}'.\".format(_get_tensor_name(tensor)))\n # Note that shape_list might be empty for scalar shapes.\n shape_list = shape.as_list()\n if None in shape_list[1:]:\n raise ValueError(\n \"None is only supported in the 1st dimension. Tensor '{0}' has \"\n \"invalid shape '{1}'.\".format(\n _get_tensor_name(tensor), shape_list))\n elif shape_list and shape_list[0] is None:\n self._set_batch_size(batch_size=1)\n\n # Get quantization stats. Ensures there is one stat per name if the stats\n # are specified.\n if quantized_input_stats:\n self._quantized_stats = []\n invalid_stats = []\n for name in self.get_input_arrays():\n if name in quantized_input_stats:\n self._quantized_stats.append(quantized_input_stats[name])\n else:\n invalid_stats.append(name)\n\n if invalid_stats:\n raise ValueError(\"Quantization input stats are not available for input \"\n \"tensors '{0}'.\".format(\",\".join(invalid_stats)))\n else:\n self._quantized_stats = None\n\n @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.OPTIMIZE_TF_MODEL)\n def _optimize_tf_model(self, graph_def, input_tensors, output_tensors,\n quant_mode):\n \"\"\"Run a Grappler pass to optimize the TensorFlow graph.\n\n Args:\n graph_def: Frozen GraphDef to be optimized.\n input_tensors: List of input tensors.\n output_tensors: List of output tensors.\n quant_mode: the quantization mode.\n\n Returns:\n The optimized TensorFlow graph.\n \"\"\"\n # Disable grappler constant folding if there are training quant ops.\n if self.saved_model_dir or quant_mode.is_quantization_aware_trained_model():\n return graph_def\n\n try:\n # TODO(b/150163103): Merge `disabling lower using switch merge' calls.\n # Grappler will also try to lower while loop into switch merge\n # representation which is undesired for Ophints, so we simply remove\n # those attributes to prevent Grappler from doing so.\n graph = _convert_to_constants.disable_lower_using_switch_merge(graph_def)\n # Run function inlining optimization to ensure any models generated\n # through the from_frozen_graph path have been inlined.\n optimized_graph = _run_graph_optimizations(\n graph,\n input_tensors,\n output_tensors,\n config=self._grappler_config([\"function\"]))\n return optimized_graph\n except Exception: # pylint: disable=broad-except\n return graph_def\n\n def convert(self):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Returns:\n The converted data in serialized format. Either a TFLite Flatbuffer or a\n Graphviz graph depending on value in `output_format`.\n\n Raises:\n ValueError:\n Input shape is not specified.\n None value for dimension in input_tensor.\n \"\"\"\n self._validate_inputs(self._input_tensors, self.quantized_input_stats)\n\n quant_mode = QuantizationMode(\n self.optimizations, self.target_spec, self.representative_dataset,\n self._graph_def, self._experimental_disable_per_channel,\n self.experimental_new_dynamic_range_quantizer,\n self._experimental_low_bit_qat,\n self._experimental_full_integer_quantization_bias_type)\n\n optimized_graph = self._optimize_tf_model(self._graph_def,\n self._input_tensors,\n self._output_tensors, quant_mode)\n\n self._debug_info = _get_debug_info(self._debug_info_func, optimized_graph)\n\n converter_kwargs = self._get_base_converter_args()\n converter_kwargs.update(\n quant_mode.converter_flags(self.inference_type,\n self.inference_input_type))\n converter_kwargs.update({\n \"output_format\": self.output_format,\n \"quantized_input_stats\": self._quantized_stats,\n \"default_ranges_stats\": self.default_ranges_stats,\n \"drop_control_dependency\": self.drop_control_dependency,\n \"reorder_across_fake_quant\": self.reorder_across_fake_quant,\n \"change_concat_input_ranges\": self.change_concat_input_ranges,\n \"dump_graphviz_dir\": self.dump_graphviz_dir,\n \"dump_graphviz_video\": self.dump_graphviz_video,\n \"conversion_summary_dir\": self.conversion_summary_dir,\n \"allow_all_select_tf_ops\": self._experimental_allow_all_select_tf_ops,\n })\n\n self._validate_quantized_input_stats(converter_kwargs, quant_mode)\n if not self.experimental_new_converter:\n logging.warning(\n \"Please consider switching to the new converter by setting \"\n \"experimental_new_converter=True. \"\n \"The old converter is deprecated.\")\n else:\n logging.info(\"Using experimental converter: If you encountered a problem \"\n \"please file a bug. You can opt-out \"\n \"by setting experimental_new_converter=False\")\n # Converts model.\n if self._has_valid_tensors():\n result = _convert_graphdef(\n input_data=optimized_graph,\n input_tensors=self._input_tensors,\n output_tensors=self._output_tensors,\n **converter_kwargs)\n else:\n result = _convert_graphdef_with_arrays(\n input_data=optimized_graph,\n input_arrays_with_shape=self._input_arrays_with_shape,\n output_arrays=self._output_arrays,\n control_output_arrays=self._control_output_arrays,\n **converter_kwargs)\n\n return self._optimize_tflite_model(\n result, quant_mode, quant_io=self.experimental_new_quantizer)\n\n def get_input_arrays(self):\n \"\"\"Returns a list of the names of the input tensors.\n\n Returns:\n List of strings.\n \"\"\"\n if self._has_valid_tensors():\n return [_get_tensor_name(tensor) for tensor in self._input_tensors]\n else:\n return [name for name, _ in self._input_arrays_with_shape]\n\n def _has_valid_tensors(self):\n \"\"\"Checks if the input and output tensors have been initialized.\n\n Returns:\n Bool.\n \"\"\"\n return self._input_tensors is not None and self._output_tensors\n\n def _set_batch_size(self, batch_size):\n \"\"\"Sets the first dimension of the input tensor to `batch_size`.\n\n Args:\n batch_size: Batch size for the model. Replaces the first dimension of an\n input size array if undefined. (default 1)\n\n Raises:\n ValueError: input_tensor is not defined.\n \"\"\"\n if not self._has_valid_tensors():\n raise ValueError(\"The batch size cannot be set for this model. Please \"\n \"use input_shapes parameter.\")\n\n for tensor in self._input_tensors:\n shape = tensor.shape.as_list()\n if shape[0] is None:\n shape[0] = batch_size\n tensor.set_shape(shape)\n\n def _is_unknown_shapes_allowed(self):\n # Ophint Converted nodes will need the shapes to be known.\n if _is_ophint_converted(self._graph_def):\n return False\n\n if not super(TFLiteConverterBaseV1, self)._is_unknown_shapes_allowed():\n return False\n\n # `conversion_summary_dir` calls the old converter. Unknown shapes are only\n # supported by the MLIR converter.\n if self.conversion_summary_dir:\n logging.warning(\n \"`conversion_summary_dir` does not work with unknown shapes. \"\n \"Graphs with unknown shapes might be different than when this flag \"\n \"is disabled.\")\n return False\n return True\n\n def _save_conversion_params_metric(self):\n self._collected_converter_params.update({\n \"output_format\": self.output_format,\n \"default_ranges_stats\": self.default_ranges_stats,\n \"drop_control_dependency\": self.drop_control_dependency,\n \"reorder_across_fake_quant\": self.reorder_across_fake_quant,\n \"change_concat_input_ranges\": self.change_concat_input_ranges,\n \"dump_graphviz_dir\": self.dump_graphviz_dir,\n \"dump_graphviz_video\": self.dump_graphviz_video,\n \"conversion_summary_dir\": self.conversion_summary_dir,\n })\n super(TFLiteConverterBaseV1,\n self)._save_conversion_params_metric(self._graph_def,\n self.inference_type,\n self.inference_input_type)\n\n\nclass TFLiteSavedModelConverter(TFLiteConverterBaseV1):\n \"\"\"Converts the given SavedModel into TensorFlow Lite model.\n\n Attributes:\n saved_model_dir: Directory of the SavedModel.\n \"\"\"\n\n def __init__(self,\n saved_model_dir,\n saved_model_tags,\n saved_model_exported_names,\n experimental_debug_info_func=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n saved_model_dir: Directory of the SavedModel.\n saved_model_tags: Set of tags identifying the MetaGraphDef within the\n SavedModel to analyze. All tags in the tag set must be present. (default\n {tf.saved_model.SERVING}).\n saved_model_exported_names: Names to be exported when the saved model\n import path is on.\n experimental_debug_info_func: An experimental function to retrieve the\n graph debug info for a set of nodes from the `graph_def`.\n\n Raises:\n ValueError: Invalid arguments.\n \"\"\"\n super(TFLiteSavedModelConverter,\n self).__init__(experimental_debug_info_func)\n self.saved_model_dir = saved_model_dir\n self._saved_model_tags = saved_model_tags\n self._saved_model_exported_names = saved_model_exported_names\n\n signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n\n if len(self._saved_model_exported_names) != 1:\n raise ValueError(\"Only support a single signature key.\")\n\n signature_key = self._saved_model_exported_names[0]\n\n result = _freeze_saved_model(self.saved_model_dir, None, None, None,\n self._saved_model_tags, signature_key)\n self._graph_def = result[0]\n self._input_tensors = result[1]\n self._output_tensors = result[2]\n self._parse_saved_model_args()\n\n @_export_metrics\n def convert(self):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Returns:\n The converted data in serialized format. Either a TFLite Flatbuffer or a\n Graphviz graph depending on value in `output_format`.\n\n Raises:\n ValueError:\n Input shape is not specified.\n None value for dimension in input_tensor.\n \"\"\"\n return super(TFLiteSavedModelConverter, self).convert()\n\n\nclass TFLiteKerasModelConverter(TFLiteConverterBaseV1):\n \"\"\"Converts the given SavedModel into TensorFlow Lite model.\"\"\"\n\n def __init__(self,\n model_file,\n input_arrays=None,\n input_shapes=None,\n output_arrays=None,\n custom_objects=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n model_file: Full filepath of HDF5 file containing the tf.keras model.\n input_arrays: List of input tensors to freeze graph with. Uses input\n arrays from SignatureDef when none are provided. (default None)\n input_shapes: Dict of strings representing input tensor names to list of\n integers representing input shapes (e.g., {\"foo\" : [1, 16, 16, 3]}).\n Automatically determined when input shapes is None (e.g., {\"foo\" :\n None}). (default None)\n output_arrays: List of output tensors to freeze graph with. Uses output\n arrays from SignatureDef when none are provided. (default None)\n custom_objects: Dict mapping names (strings) to custom classes or\n functions to be considered during model deserialization. (default None)\n\n Raises:\n ValueError: Invalid arguments.\n \"\"\"\n super(TFLiteKerasModelConverter,\n self).__init__(experimental_debug_info_func=None)\n # Handles Keras when Eager mode is enabled.\n if context.executing_eagerly():\n if input_arrays or output_arrays:\n raise ValueError(\"`input_arrays` and `output_arrays` are unsupported \"\n \"with Eager mode. If your model requires any of these \"\n \"parameters, please use disable_eager_execution().\")\n\n keras_model = keras_deps.get_load_model_function()(model_file,\n custom_objects)\n function = _trace_model_call(keras_model)\n concrete_func = function.get_concrete_function()\n\n frozen_func = _convert_to_constants.convert_variables_to_constants_v2(\n concrete_func, lower_control_flow=False)\n _set_tensor_shapes(frozen_func.inputs, input_shapes)\n self._keras_model = keras_model\n self._graph_def = frozen_func.graph.as_graph_def()\n self._input_tensors = frozen_func.inputs\n self._output_tensors = frozen_func.outputs\n self._debug_info_func = _build_debug_info_func(frozen_func.graph)\n return\n\n # Handles Keras when Eager mode is disabled.\n keras_deps.get_clear_session_function()()\n keras_model = keras_deps.get_load_model_function()(model_file,\n custom_objects)\n sess = keras_deps.get_get_session_function()()\n\n # Get input and output tensors.\n if input_arrays:\n input_tensors = _get_tensors_from_tensor_names(sess.graph, input_arrays)\n else:\n input_tensors = keras_model.inputs\n\n if output_arrays:\n output_tensors = _get_tensors_from_tensor_names(sess.graph, output_arrays)\n else:\n output_tensors = keras_model.outputs\n _set_tensor_shapes(input_tensors, input_shapes)\n\n graph_def = _freeze_graph(sess, input_tensors, output_tensors)\n self._keras_model = keras_model\n self._graph_def = graph_def\n self._input_tensors = input_tensors\n self._output_tensors = output_tensors\n self._debug_info_func = _build_debug_info_func(sess.graph)\n\n @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.FREEZE_KERAS_MODEL)\n def _freeze_keras_model(self, output_dir):\n \"\"\"Save Keras model to Saved Model format.\n\n Args:\n output_dir: The output directory to save the SavedModel.\n \"\"\"\n try:\n self._keras_model.save(output_dir, save_format=\"tf\")\n except Exception: # pylint: disable=broad-except\n # When storing the given keras model to a saved model is failed, let's\n # use original keras model conversion pipeline.\n return None\n tag_set = set([_tag_constants.SERVING])\n signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n graph_def, input_tensors, output_tensors, sess_graph = _freeze_saved_model(\n output_dir, None, None, None, tag_set, signature_key)\n\n self.saved_model_dir = output_dir\n self._saved_model_tags = tag_set\n self._saved_model_exported_names = [signature_key]\n self._parse_saved_model_args()\n if self.saved_model_dir:\n self._graph_def = graph_def\n self._input_tensors = input_tensors\n self._output_tensors = output_tensors\n self._debug_info_func = _build_debug_info_func(sess_graph)\n\n def _convert_as_saved_model(self):\n \"\"\"Converts a Keras model as a saved model.\n\n Returns:\n The converted data in serialized format.\n \"\"\"\n temp_dir = tempfile.mkdtemp()\n try:\n self._freeze_keras_model(temp_dir)\n if self.saved_model_dir:\n return super(TFLiteKerasModelConverter, self).convert()\n finally:\n shutil.rmtree(temp_dir, True)\n\n @_export_metrics\n def convert(self):\n \"\"\"Converts a Keras model based on instance variables.\n\n Returns:\n The converted data in serialized format. Either a TFLite Flatbuffer or a\n Graphviz graph depending on value in `output_format`.\n\n Raises:\n ValueError:\n Input shape is not specified.\n None value for dimension in input_tensor.\n \"\"\"\n saved_model_convert_result = self._convert_as_saved_model()\n if saved_model_convert_result:\n return saved_model_convert_result\n\n return super(TFLiteKerasModelConverter, self).convert()\n\n\nclass TFLiteFrozenGraphConverter(TFLiteConverterBaseV1):\n \"\"\"Converts the given frozen graph def into TensorFlow Lite model.\"\"\"\n\n def __init__(self,\n graph_def,\n input_tensors,\n output_tensors,\n input_arrays_with_shape=None,\n output_arrays=None,\n experimental_debug_info_func=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n graph_def: Frozen TensorFlow GraphDef.\n input_tensors: List of input tensors. Type and shape are computed using\n `foo.shape` and `foo.dtype`.\n output_tensors: List of output tensors (only .name is used from this).\n input_arrays_with_shape: Tuple of strings representing input tensor names\n and list of integers representing input shapes\n (e.g., [(\"foo\", [1, 16, 16, 3])]). Use only when graph cannot be loaded\n into TensorFlow and when `input_tensors` and `output_tensors` are\n None. (default None)\n output_arrays: List of output tensors to freeze graph with. Use only when\n graph cannot be loaded into TensorFlow and when `input_tensors` and\n `output_tensors` are None. (default None)\n experimental_debug_info_func: An experimental function to retrieve the\n graph debug info for a set of nodes from the `graph_def`.\n\n Raises:\n ValueError: Invalid arguments.\n \"\"\"\n super(TFLiteFrozenGraphConverter,\n self).__init__(experimental_debug_info_func)\n self._graph_def = graph_def\n self._input_tensors = input_tensors\n self._output_tensors = output_tensors\n self._control_output_arrays = None\n\n # Attributes are used by models that cannot be loaded into TensorFlow.\n if not self._has_valid_tensors():\n self._input_arrays_with_shape = input_arrays_with_shape\n self._output_arrays = output_arrays\n\n if input_tensors is not None and input_arrays_with_shape is not None:\n logging.warning(\"input_arrays_with_shape will be ignored when both the \"\n \"given input_tensors and input_arrays_with_shape are not \"\n \"None.\")\n\n if output_tensors is not None and output_arrays is not None:\n logging.warning(\"output_arrays will be ignored when both the given \"\n \"output_tensors and output_arrays are not None.\")\n\n @_export_metrics\n def convert(self):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Returns:\n The converted data in serialized format. Either a TFLite Flatbuffer or a\n Graphviz graph depending on value in `output_format`.\n\n Raises:\n ValueError:\n Input shape is not specified.\n None value for dimension in input_tensor.\n \"\"\"\n if not self._has_valid_tensors():\n if not self._input_arrays_with_shape or not (self._output_arrays or\n self._control_output_arrays):\n raise ValueError(\n \"If input_tensors and output_tensors are None, both \"\n \"input_arrays_with_shape and output_arrays|control_output_arrays \"\n \"must be defined.\")\n return super(TFLiteFrozenGraphConverter, self).convert()\n\n\n@_tf_export(v1=[\"lite.TFLiteConverter\"])\nclass TFLiteConverter(TFLiteFrozenGraphConverter):\n \"\"\"Convert a TensorFlow model into `output_format`.\n\n This is used to convert from a TensorFlow GraphDef, SavedModel or tf.keras\n model into either a TFLite FlatBuffer or graph visualization.\n\n Attributes:\n optimizations: Experimental flag, subject to change. Set of optimizations to\n apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a\n set of values of type `tf.lite.Optimize`)\n representative_dataset: A generator function used for integer quantization\n where each generated sample has the same order, type and shape as the\n inputs to the model. Usually, this is a small subset of a few hundred\n samples randomly chosen, in no particular order, from the training or\n evaluation dataset. This is an optional attribute, but required for full\n integer quantization, i.e, if `tf.int8` is the only supported type in\n `target_spec.supported_types`. Refer to `tf.lite.RepresentativeDataset`.\n (default None)\n target_spec: Experimental flag, subject to change. Specifications of target\n device, including supported ops set, supported types and a set of user's\n defined TensorFlow operators required in the TensorFlow Lite runtime.\n Refer to `tf.lite.TargetSpec`.\n inference_type: Data type of numeric arrays, excluding the input layer.\n (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8})\n inference_input_type: Data type of the numeric arrays in the input layer. If\n `inference_input_type` is in {tf.int8, tf.uint8}, then\n `quantized_input_stats` must be provided. (default is the value assigned\n to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8})\n inference_output_type: Data type of the numeric arrays in the output layer.\n (default is the value assigned to `inference_type`, must be in\n {tf.float32, tf.int8, tf.uint8})\n quantized_input_stats: Map of input tensor names to a tuple of floats\n representing the mean and standard deviation of the training data.\n (e.g., {\"foo\" : (0., 1.)}). Required if `inference_input_type` is tf.int8\n or tf.uint8. (default None)\n default_ranges_stats: Tuple of integers (min, max) representing range values\n for all numeric arrays without a specified range. Intended for\n experimenting with quantization via \"dummy quantization\". (default None)\n allow_custom_ops: Boolean indicating whether to allow custom operations.\n When False any unknown operation is an error. When True, custom ops are\n created for any op that is unknown. The developer will need to provide\n these to the TensorFlow Lite runtime with a custom resolver. (default\n False)\n drop_control_dependency: Boolean indicating whether to drop control\n dependencies silently. This is due to TFLite not supporting control\n dependencies. (default True)\n reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant\n nodes in unexpected locations. Used when the location of the FakeQuant\n nodes is preventing graph transformations necessary to convert the graph.\n Results in a graph that differs from the quantized training graph,\n potentially causing differing arithmetic behavior. (default False)\n change_concat_input_ranges: Boolean to change behavior of min/max ranges for\n inputs and outputs of the concat operator for quantized models. Changes\n the ranges of concat operator overlap when true. (default False)\n output_format: Output file format. (default\n tf.compat.v1.lite.constants.TFLITE, must be in\n {tf.compat.v1.lite.constants.TFLITE,\n tf.compat.v1.lite.constants.GRAPHVIZ_DOT})\n dump_graphviz_dir: Full filepath of folder to dump the graphs at various\n stages of processing GraphViz .dot files. Preferred over\n `output_format=tf.compat.v1.lite.constants.GRAPHVIZ_DOT` in order to keep\n the requirements of the output file. (default None)\n dump_graphviz_video: Boolean indicating whether to dump the GraphViz .dot\n files after every graph transformation. Requires the `dump_graphviz_dir`\n flag to be specified. (default False)\n conversion_summary_dir: Full path of the directory to store conversion logs.\n (default None)\n exclude_conversion_metadata: Whether not to embed the conversion metadata\n into the converted model. (default False)\n target_ops: Deprecated. Please use `target_spec.supported_ops` instead.\n post_training_quantize: Deprecated. Please use `optimizations` instead and\n set it to `{tf.lite.Optimize.DEFAULT}`. (default False)\n experimental_new_converter: Experimental flag, subject to change. Enables\n MLIR-based conversion. (default True)\n experimental_new_quantizer: Experimental flag, subject to change. Enables\n MLIR-based quantization conversion instead of Flatbuffer-based conversion.\n (default True)\n\n Example usage:\n\n ```python\n # Converting a GraphDef from session.\n converter = tf.compat.v1.lite.TFLiteConverter.from_session(\n sess, in_tensors, out_tensors)\n tflite_model = converter.convert()\n open(\"converted_model.tflite\", \"wb\").write(tflite_model)\n\n # Converting a GraphDef from file.\n converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(\n graph_def_file, input_arrays, output_arrays)\n tflite_model = converter.convert()\n open(\"converted_model.tflite\", \"wb\").write(tflite_model)\n\n # Converting a SavedModel.\n converter = tf.compat.v1.lite.TFLiteConverter.from_saved_model(\n saved_model_dir)\n tflite_model = converter.convert()\n open(\"converted_model.tflite\", \"wb\").write(tflite_model)\n\n # Converting a tf.keras model.\n converter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file(\n keras_model)\n tflite_model = converter.convert()\n open(\"converted_model.tflite\", \"wb\").write(tflite_model)\n ```\n \"\"\"\n\n # pylint: disable=useless-super-delegation\n def __init__(self,\n graph_def,\n input_tensors,\n output_tensors,\n input_arrays_with_shape=None,\n output_arrays=None,\n experimental_debug_info_func=None):\n \"\"\"Constructor for TFLiteConverter.\n\n Args:\n graph_def: Frozen TensorFlow GraphDef.\n input_tensors: List of input tensors. Type and shape are computed using\n `foo.shape` and `foo.dtype`.\n output_tensors: List of output tensors (only .name is used from this).\n input_arrays_with_shape: Tuple of strings representing input tensor names\n and list of integers representing input shapes\n (e.g., [(\"foo\" : [1, 16, 16, 3])]). Use only when graph cannot be loaded\n into TensorFlow and when `input_tensors` and `output_tensors` are\n None. (default None)\n output_arrays: List of output tensors to freeze graph with. Use only when\n graph cannot be loaded into TensorFlow and when `input_tensors` and\n `output_tensors` are None. (default None)\n experimental_debug_info_func: An experimental function to retrieve the\n graph debug info for a set of nodes from the `graph_def`.\n\n Raises:\n ValueError: Invalid arguments.\n \"\"\"\n super(TFLiteConverter,\n self).__init__(graph_def, input_tensors, output_tensors,\n input_arrays_with_shape, output_arrays,\n experimental_debug_info_func)\n\n @classmethod\n def from_session(cls, sess, input_tensors, output_tensors):\n \"\"\"Creates a TFLiteConverter class from a TensorFlow Session.\n\n Args:\n sess: TensorFlow Session.\n input_tensors: List of input tensors. Type and shape are computed using\n `foo.shape` and `foo.dtype`.\n output_tensors: List of output tensors (only .name is used from this).\n\n Returns:\n TFLiteConverter class.\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.TF_SESSION)\n # pylint: enable=protected-access\n graph_def = _freeze_graph(sess, input_tensors, output_tensors)\n return cls(\n graph_def,\n input_tensors,\n output_tensors,\n experimental_debug_info_func=_build_debug_info_func(sess.graph))\n\n @classmethod\n def from_frozen_graph(cls,\n graph_def_file,\n input_arrays,\n output_arrays,\n input_shapes=None):\n \"\"\"Creates a TFLiteConverter class from a file containing a frozen GraphDef.\n\n Args:\n graph_def_file: Full filepath of file containing frozen GraphDef.\n input_arrays: List of input tensors to freeze graph with.\n output_arrays: List of output tensors to freeze graph with.\n input_shapes: Dict of strings representing input tensor names to list of\n integers representing input shapes (e.g., {\"foo\" : [1, 16, 16, 3]}).\n Automatically determined when input shapes is None (e.g., {\"foo\" :\n None}). (default None)\n\n Returns:\n TFLiteConverter class.\n\n Raises:\n IOError:\n File not found.\n Unable to parse input file.\n ValueError:\n The graph is not frozen.\n input_arrays or output_arrays contains an invalid tensor name.\n input_shapes is not correctly defined when required\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.TF_GRAPH_DEF)\n # pylint: enable=protected-access\n with _ops.Graph().as_default():\n with _session.Session() as sess:\n # Read GraphDef from file.\n if not gfile.Exists(graph_def_file):\n raise IOError(\"File '{0}' does not exist.\".format(graph_def_file))\n with gfile.GFile(graph_def_file, \"rb\") as f:\n file_content = f.read()\n\n try:\n graph_def = _graph_pb2.GraphDef()\n graph_def.ParseFromString(file_content)\n except (_text_format.ParseError, DecodeError):\n try:\n print(\"Ignore 'tcmalloc: large alloc' warnings.\")\n\n if not isinstance(file_content, str):\n if PY2:\n file_content = six.ensure_binary(file_content, \"utf-8\")\n else:\n file_content = six.ensure_text(file_content, \"utf-8\")\n graph_def = _graph_pb2.GraphDef()\n _text_format.Merge(file_content, graph_def)\n except (_text_format.ParseError, DecodeError):\n raise IOError(\n \"Unable to parse input file '{}'.\".format(graph_def_file))\n\n # Handles models with custom TFLite ops that cannot be resolved in\n # TensorFlow.\n load_model_in_session = True\n try:\n _import_graph_def(graph_def, name=\"\")\n except _NotFoundError:\n load_model_in_session = False\n\n if load_model_in_session:\n # Check if graph is frozen.\n if not _is_frozen_graph(sess):\n raise ValueError(\"Please freeze the graph using freeze_graph.py.\")\n\n # Get input and output tensors.\n input_tensors = _get_tensors_from_tensor_names(\n sess.graph, input_arrays)\n output_tensors = _get_tensors_from_tensor_names(\n sess.graph, output_arrays)\n _set_tensor_shapes(input_tensors, input_shapes)\n\n return cls(sess.graph_def, input_tensors, output_tensors)\n else:\n if not input_shapes:\n raise ValueError(\"input_shapes must be defined for this model.\")\n if set(input_arrays) != set(input_shapes.keys()):\n raise ValueError(\"input_shapes must contain a value for each item \"\n \"in input_array.\")\n\n input_arrays_with_shape = [\n (name, input_shapes[name]) for name in input_arrays\n ]\n return cls(\n graph_def,\n input_tensors=None,\n output_tensors=None,\n input_arrays_with_shape=input_arrays_with_shape,\n output_arrays=output_arrays)\n\n @classmethod\n def from_saved_model(cls,\n saved_model_dir,\n input_arrays=None,\n input_shapes=None,\n output_arrays=None,\n tag_set=None,\n signature_key=None):\n \"\"\"Creates a TFLiteConverter class from a SavedModel.\n\n Args:\n saved_model_dir: SavedModel directory to convert.\n input_arrays: List of input tensors to freeze graph with. Uses input\n arrays from SignatureDef when none are provided. (default None)\n input_shapes: Dict of strings representing input tensor names to list of\n integers representing input shapes (e.g., {\"foo\" : [1, 16, 16, 3]}).\n Automatically determined when input shapes is None (e.g., {\"foo\" :\n None}). (default None)\n output_arrays: List of output tensors to freeze graph with. Uses output\n arrays from SignatureDef when none are provided. (default None)\n tag_set: Set of tags identifying the MetaGraphDef within the SavedModel to\n analyze. All tags in the tag set must be present. (default\n {tf.saved_model.SERVING})\n signature_key: Key identifying SignatureDef containing inputs and outputs.\n (default tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY)\n\n Returns:\n TFLiteConverter class.\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.TF_SAVED_MODEL)\n # pylint: enable=protected-access\n if tag_set is None:\n tag_set = set([_tag_constants.SERVING])\n if signature_key is None:\n signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n\n saved_model_converter = TFLiteSavedModelConverter(saved_model_dir, tag_set,\n [signature_key])\n if saved_model_converter.saved_model_dir:\n return saved_model_converter\n\n result = _freeze_saved_model(saved_model_dir, input_arrays, input_shapes,\n output_arrays, tag_set, signature_key)\n\n return cls(\n graph_def=result[0],\n input_tensors=result[1],\n output_tensors=result[2],\n experimental_debug_info_func=_build_debug_info_func(result[3]))\n\n @classmethod\n def from_keras_model_file(cls,\n model_file,\n input_arrays=None,\n input_shapes=None,\n output_arrays=None,\n custom_objects=None):\n \"\"\"Creates a TFLiteConverter class from a tf.keras model file.\n\n Args:\n model_file: Full filepath of HDF5 file containing the tf.keras model.\n input_arrays: List of input tensors to freeze graph with. Uses input\n arrays from SignatureDef when none are provided. (default None)\n input_shapes: Dict of strings representing input tensor names to list of\n integers representing input shapes (e.g., {\"foo\" : [1, 16, 16, 3]}).\n Automatically determined when input shapes is None (e.g., {\"foo\" :\n None}). (default None)\n output_arrays: List of output tensors to freeze graph with. Uses output\n arrays from SignatureDef when none are provided. (default None)\n custom_objects: Dict mapping names (strings) to custom classes or\n functions to be considered during model deserialization. (default None)\n\n Returns:\n TFLiteConverter class.\n \"\"\"\n # pylint: disable=protected-access\n TFLiteConverterBase._set_original_model_type(\n conversion_metdata_fb.ModelType.KERAS_MODEL)\n # pylint: enable=protected-access\n return TFLiteKerasModelConverter(model_file, input_arrays, input_shapes,\n output_arrays, custom_objects)\n\n # pylint: disable=useless-super-delegation\n def convert(self):\n \"\"\"Converts a TensorFlow GraphDef based on instance variables.\n\n Returns:\n The converted data in serialized format. Either a TFLite Flatbuffer or a\n Graphviz graph depending on value in `output_format`.\n\n Raises:\n ValueError:\n Input shape is not specified.\n None value for dimension in input_tensor.\n \"\"\"\n return super(TFLiteConverter, self).convert()\n\n\n@_tf_export(v1=[\"lite.TocoConverter\"])\nclass TocoConverter(object):\n \"\"\"Convert a TensorFlow model into `output_format`.\n\n This class has been deprecated. Please use `lite.TFLiteConverter` instead.\n \"\"\"\n\n @classmethod\n @_deprecation.deprecated(None,\n \"Use `lite.TFLiteConverter.from_session` instead.\")\n def from_session(cls, sess, input_tensors, output_tensors):\n \"\"\"Creates a TocoConverter class from a TensorFlow Session.\"\"\"\n return TFLiteConverter.from_session(sess, input_tensors, output_tensors)\n\n @classmethod\n @_deprecation.deprecated(\n None, \"Use `lite.TFLiteConverter.from_frozen_graph` instead.\")\n def from_frozen_graph(cls,\n graph_def_file,\n input_arrays,\n output_arrays,\n input_shapes=None):\n \"\"\"Creates a TocoConverter class from a file containing a frozen graph.\"\"\"\n return TFLiteConverter.from_frozen_graph(graph_def_file, input_arrays,\n output_arrays, input_shapes)\n\n @classmethod\n @_deprecation.deprecated(\n None, \"Use `lite.TFLiteConverter.from_saved_model` instead.\")\n def from_saved_model(cls,\n saved_model_dir,\n input_arrays=None,\n input_shapes=None,\n output_arrays=None,\n tag_set=None,\n signature_key=None):\n \"\"\"Creates a TocoConverter class from a SavedModel.\"\"\"\n return TFLiteConverter.from_saved_model(saved_model_dir, input_arrays,\n input_shapes, output_arrays,\n tag_set, signature_key)\n\n @classmethod\n @_deprecation.deprecated(\n None, \"Use `lite.TFLiteConverter.from_keras_model_file` instead.\")\n def from_keras_model_file(cls,\n model_file,\n input_arrays=None,\n input_shapes=None,\n output_arrays=None):\n \"\"\"Creates a TocoConverter class from a tf.keras model file.\"\"\"\n return TFLiteConverter.from_keras_model_file(model_file, input_arrays,\n input_shapes, output_arrays)\n"
] |
[
[
"tensorflow.lite.python.util.populate_conversion_metadata",
"tensorflow.lite.python.util.model_input_signature",
"tensorflow.lite.python.conversion_metadata_schema_py_generated.ConversionOptionsT",
"tensorflow.python.platform.gfile.GFile",
"tensorflow.python.framework.convert_to_constants.convert_variables_to_constants_v2",
"tensorflow.lite.python.util.freeze_graph",
"tensorflow.lite.python.convert_phase.convert_phase",
"tensorflow.lite.python.util.get_tf_type_name",
"tensorflow.python.platform.gfile.Exists",
"tensorflow.lite.python.util.build_debug_info_func",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.saved_model.save_options.SaveOptions",
"tensorflow.lite.python.conversion_metadata_schema_py_generated.EnvironmentT",
"tensorflow.lite.python.optimize.calibrator.add_intermediate_tensors",
"tensorflow.python.util.keras_deps.get_load_model_function",
"tensorflow.lite.python.util.is_frozen_graph",
"tensorflow.lite.python.util.get_tensor_name",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.lite.python.op_hint.is_ophint_converted",
"tensorflow.python.framework.convert_to_constants.disable_lower_using_switch_merge",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.lite.python.metrics.metrics.TFLiteConverterMetrics",
"tensorflow.python.eager.context.eager_mode",
"tensorflow.lite.python.convert_saved_model.freeze_saved_model",
"tensorflow.python.util.keras_deps.get_get_session_function",
"tensorflow.python.saved_model.loader_impl.parse_saved_model_with_debug_info",
"tensorflow.python.framework.importer.import_graph_def",
"tensorflow.lite.python.util.get_debug_info",
"tensorflow.lite.python.util.set_tensor_shapes",
"tensorflow.lite.python.convert.convert_graphdef_with_arrays",
"tensorflow.lite.python.util.get_sparsity_modes",
"tensorflow.lite.python.convert.convert_saved_model",
"tensorflow.python.client.session.Session",
"tensorflow.lite.python.convert.convert_graphdef",
"tensorflow.lite.python.util.get_grappler_config",
"tensorflow.lite.python.util.trace_model_call",
"tensorflow.python.saved_model.load.load",
"tensorflow.python.saved_model.loader_impl.SavedModelLoader",
"tensorflow.lite.python.convert.convert_jax_hlo",
"tensorflow.lite.python.util.get_tensors_from_tensor_names",
"tensorflow.python.util.keras_deps.get_clear_session_function",
"tensorflow.python.framework.ops.Graph",
"tensorflow.lite.python.util.run_graph_optimizations",
"tensorflow.lite.python.optimize.calibrator.Calibrator",
"tensorflow.lite.python.convert.deduplicate_readonly_buffers",
"tensorflow.python.framework.convert_to_constants.convert_variables_to_constants_v2_as_graph",
"tensorflow.lite.python.util._xla_computation",
"tensorflow.lite.python.convert.mlir_quantize",
"tensorflow.lite.python.util.convert_debug_info_func",
"tensorflow.lite.python.conversion_metadata_schema_py_generated.ConversionMetadataT",
"tensorflow.lite.python.convert.mlir_sparsify",
"tensorflow.core.framework.graph_pb2.GraphDef",
"tensorflow.lite.python.util.modify_model_io_type"
]
] |
msychung/FUSE-2020
|
[
"222225b9e18519e999e56b376895fcd407d5cfba"
] |
[
"analysis/Distance.py"
] |
[
"import BioLogic\nimport pandas as pd \nimport numpy as np \nimport glob\nimport os.path \nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom numpy import matlib\n\n'''\nUses the \"Distance\" method to find nucleation overpotential i.e. finds the point furthest away from a line drawn between the first and last points, equivalent to the \"knee\" point.\nplotGraphCut() and barComparison() functions used to plot results, calculation code found below.\n'''\n\n\n# Created variables to store different paths for easy switching \nNewAcH = \"C:\\\\Users\\\\Melissa\\\\OneDrive - Lancaster University\\\\Jobs & Internships\\\\FUSE 2020\\\\Data Analysis\\\\Analysis\\\\Analysis New\\\\AcH\\\\\"\nNewHCl = \"C:\\\\Users\\\\Melissa\\\\OneDrive - Lancaster University\\\\Jobs & Internships\\\\FUSE 2020\\\\Data Analysis\\\\Analysis\\\\Analysis New\\\\HCl\\\\\"\nNewRef = \"C:\\\\Users\\\\Melissa\\\\OneDrive - Lancaster University\\\\Jobs & Internships\\\\FUSE 2020\\\\Data Analysis\\\\Analysis\\\\Analysis New\\\\References\\\\\"\nOriginal = \"C:\\\\Users\\\\Melissa\\\\OneDrive - Lancaster University\\\\Jobs & Internships\\\\FUSE 2020\\\\Data Analysis\\\\Analysis\\\\Analysis Original\\\\\"\nOriginalTime = \"C:\\\\Users\\\\Melissa\\\\OneDrive - Lancaster University\\\\Jobs & Internships\\\\FUSE 2020\\\\Data Analysis\\\\Analysis\\\\Analysis Original Time\\\\\"\n\n\n'''Finds all files with file extension .mpr and appends them to a list called mpr_files. The sorted() function arranges them in alphabetical order.'''\nmpr_files = sorted(glob.glob(NewHCl + '*.mpr')) \n\n\ndef plotGraphCut():\n '''\n Plots graphs, cut to show only points of interest around the nucleation overpotential point. \n The plots draw a vertical dotted red line at the x co-ordinate (time) of the identified point, to identify its position more clearly.\n Use the \"Zoom to Rectangle\" tool on the output plots to gain a closer look at the values and data points around the nucleation overpotential.\n '''\n fig = plt.figure()\n fig.set_size_inches(14, 6)\n\n ax = fig.add_subplot(1, 1, 1) #1x1 grid, 1st subplot\n\n ax.scatter(np_data[:,3], np_data[:,1], color='black', marker='x', s=2)\n\n ax.set_xlabel('Time / min').set_style('italic') \n ax.set_ylabel('$E_{we} / V$').set_style('italic')\n\n Title = os.path.basename(eChemFile) \n plt.title(Title.strip('.mpr')).set_weight('bold')\n\n plt.grid(color=(.8, .8, .8)) #linestyle='-.', linewidth=0.7\n ax.spines['right'].set_color((.8, .8, .8))\n ax.spines['top'].set_color((.8, .8, .8))\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n ax.tick_params(axis='y', labelcolor='black')\n ax.axhline(y=0, color='black', linewidth=0.5)\n\n ax.axvline(x=np_data[:,3][idxOfBestPoint], color='red', linewidth=0.5, linestyle='--')\n\n plt.show()\n\n\ndef barComparison():\n '''\n Plots bar charts comparing the nucleation overpotentials of cells with HCl and AcH pre-treatments. Could probably find a way to automate this but did not have a large data pool to work from, so was easier at the time to manually input values. \n '''\n fig = plt.figure()\n fig.set_size_inches(10, 6)\n\n '''Subplot for the HCl treated cells'''\n fig.add_subplot(2, 1, 1)\n\n plt.subplots_adjust(hspace = 0.4)\n\n threshold = 0.0\n # above_threshold = np.maximum(values - threshold, 0)\n # below_threshold = np.minimum(values, threshold)\n\n CuHCl_Voltages = [-0.1373777985572815, -0.4336039125919342, 0.5475689172744751, -0.4431435167789459]\n CuHCl_Treatments = ['2V (Erratic)', '0.1V 0.1mAh', '2V Plating', '2V Plating 2']\n CuHCl_y_pos = np.arange(len(CuHCl_Treatments))\n\n plt.bar(CuHCl_y_pos, CuHCl_Voltages, width = 0.4, align='center', alpha=0.8)\n plt.xticks(CuHCl_y_pos, CuHCl_Treatments)\n plt.ylabel('Voltage').set_style('italic')\n plt.xlabel('Treatment').set_style('italic')\n plt.title('HCl Treatment').set_weight('bold')\n plt.axhline(y=threshold,linewidth=1, color='black')\n\n\n '''Subplot for the AcH treated cells'''\n fig.add_subplot(2, 1, 2)\n \n CuAcH_Voltages = [0.2820037603378296, 0.08628690987825394, -0.05377234145998955, 0.05000302195549011, -0.40689000487327576, -0.3836333453655243]\n CuAcH_Treatments = ['2V 0.1mAh', '1.3V 0.1mAh', '2V 0.01mAh', '2V Plating', '2V 1mAh', '2V 1mAh Plating']\n CuAcH_y_pos = np.arange(len(CuAcH_Treatments))\n\n plt.bar(CuAcH_y_pos, CuAcH_Voltages, width = 0.4, align='center', alpha=0.8)\n plt.xticks(CuAcH_y_pos, CuAcH_Treatments)\n plt.ylabel('Voltage').set_style('italic')\n plt.xlabel('Treatment').set_style('italic')\n plt.title('AcH Treatment').set_weight('bold')\n plt.axhline(y=threshold,linewidth=1, color='black')\n\n plt.show()\n\n\n'''MAIN'''\nfor i, eChemFile in enumerate(mpr_files):\n '''Read in .mpr files as pandas dataframes, then convert to numpy arrays'''\n mpr = BioLogic.MPRfile(eChemFile)\n df = pd.DataFrame(mpr.data)\n df = df.loc[:, df.columns.intersection(['time/s', 'Ewe/V'])]\n df['time/hr'] = df['time/s']/3600\n df['time/min'] = df['time/s']/60\n np_data = df.to_numpy()\n \n '''Identify point at which to 'cut' the graph, to 'zoom in' on points of interest, around nucleation overpotential.'''\n der_y = np.gradient(np_data[:,1], np_data[:,3]) \n \n for n in der_y:\n der_y = der_y[(der_y > -20)]\n\n cut = list(range(0, (len(np_data)-len(der_y)+1)))\n np_data_cut = np_data[(len(np_data)-len(der_y)):]\n\n ''' Calculate 'knee' point using the distance method.'''\n nPoints = len(np_data_cut[:,1])\n allCoord = np.vstack((range(nPoints), np_data_cut[:,1])).T\n np.array([range(nPoints), np_data_cut[:,1]])\n firstPoint = allCoord[0]\n lineVec = allCoord[-1] - allCoord[0]\n lineVecNorm = lineVec / np.sqrt(np.sum(lineVec**2))\n vecFromFirst = allCoord - firstPoint\n scalarProduct = np.sum(vecFromFirst * np.matlib.repmat(lineVecNorm, nPoints, 1), axis=1)\n vecFromFirstParallel = np.outer(scalarProduct, lineVecNorm)\n vecToLine = vecFromFirst - vecFromFirstParallel\n distToLine = np.sqrt(np.sum(vecToLine ** 2, axis=1))\n idxOfBestPoint = np.argmax(distToLine) #Returns index of the nucleation overpotential point within the numpy array\n\n '''Print the time and potential at the nucleation overpotential point.'''\n print(\"\\n \\n\" + os.path.basename(eChemFile))\n print(\"Time at nucleation overpotential:\", np_data[:,0][idxOfBestPoint]/60, \"min\")\n print(\"Nucleation overpotential:\", np_data[:,1][idxOfBestPoint], \"V\")\n\n '''Calls the plotting function. Comment this out to avoid viewing plots every time.'''\n plotGraphCut()\n\n '''Change number to restrict number file plots displayed when run.'''\n # if i + 1 == 10:\n # break\n\n'''Calls the bar comparison function. Comment this out to avoid viewing the comparison chart.'''\nbarComparison()"
] |
[
[
"numpy.matlib.repmat",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.title",
"numpy.gradient",
"pandas.DataFrame",
"matplotlib.pyplot.ylabel",
"numpy.argmax",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.grid",
"numpy.outer",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.figure"
]
] |
Kevin0624/HarDNeXt
|
[
"32cd7959af260fd7ede9514547907e187fb647a8"
] |
[
"src/main.py"
] |
[
"import argparse\nimport os\nimport random\nimport shutil\nimport time\nimport warnings\nimport sys\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.distributed as dist\nimport torch.optim\nimport torch.multiprocessing as mp\nimport torch.utils.data\nimport torch.utils.data.distributed\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\n#import torchvision.models as models\nimport torch.nn.init as init\n\nimport csv\n\n\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom models.hardnext import HarDNeXt\n\n\n\nmodel_names = ['hardnext']\n\narch_list = ['28', '32', '39', '50', '56']\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\nparser.add_argument('data', metavar='DIR', default='/dataset/imagenet/raw_data/',\n help='path to dataset')\nparser.add_argument('--model_name', default='HardneXt', choices=model_names)\nparser.add_argument('-a', '--arch', metavar='ARCH', default='50', choices=arch_list)\nparser.add_argument('-dw', '--depthwise', action='store_true')\n\nparser.add_argument('-j', '--workers', default=16, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\n\nparser.add_argument('--warmup', default=0, type=int, help='number of warmup epochs to run')\n\nparser.add_argument('--epochs', default=250, type=int, metavar='N',\n help='number of total epochs to run')\n\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\n\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('--lr', '--learning-rate', default=0.05, type=float,\n metavar='LR', help='initial learning rate', dest='lr')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--wd', '--weight-decay', default=6e-5, type=float,\n metavar='W', help='weight decay (default: 1e-4)',\n dest='weight_decay')\nparser.add_argument('-p', '--print-freq', default=10, type=int,\n metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n help='evaluate model on validation set')\nparser.add_argument('--pretrained', dest='pretrained', action='store_true',\n help='use pre-trained model')\nparser.add_argument('--world-size', default=-1, type=int,\n help='number of nodes for distributed training')\nparser.add_argument('--rank', default=-1, type=int,\n help='node rank for distributed training')\nparser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,\n help='url used to set up distributed training')\nparser.add_argument('--dist-backend', default='nccl', type=str,\n help='distributed backend')\nparser.add_argument('--seed', default=None, type=int,\n help='seed for initializing training. ')\nparser.add_argument('--gpu', default=None, type=int,\n help='GPU id to use.')\nparser.add_argument('--multiprocessing-distributed', action='store_true',\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\n\nbest_acc1 = 0\n\ntrain_epoch = 0\ntrain_acc1 = 0\ntrain_acc5 = 0\ntrain_loss = 0\n\nval_acc1 = 0\nval_acc5 = 0\nval_loss = 0\n\nlearning_rate = 0\nfull_model_name = \"\"\n\nwriter = SummaryWriter('tb-logs')\n\ndef main():\n\n global full_model_name\n\n #torch.backends.cudnn.enabled=False\n\n args = parser.parse_args()\n\n # tensorboard summarywriter\n \n\n #depth_wise = args.depthwise #'ds' in args.arch\n arch = int(args.arch) #int(args.arch[7:9])\n\n\n if args.depthwise:\n full_model_name = args.model_name+\"(\"+args.arch+\"DS)\"\n else:\n full_model_name = args.model_name+\"(\"+args.arch+\")\"\n \n print(full_model_name)\n\n # 開啟輸出的 CSV 檔案\n with open(full_model_name + '_'+str(args.epochs)+'_'+str(args.batch_size)+'_'+str(args.lr)+'_training_log.csv', 'w', newline='') as csvfile:\n # 建立CSV檔寫入器\n writer = csv.writer(csvfile)\n # 寫入一列資料\n writer.writerow(['Epoch', 'training_acc1','training_acc5', 'training_loss', 'val_acc1', 'val_acc5', 'val_loss'])\n\n\n \n\n if args.seed is not None:\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n cudnn.deterministic = True\n warnings.warn('You have chosen to seed training. '\n 'This will turn on the CUDNN deterministic setting, '\n 'which can slow down your training considerably! '\n 'You may see unexpected behavior when restarting '\n 'from checkpoints.')\n\n if args.gpu is not None:\n warnings.warn('You have chosen a specific GPU. This will completely '\n 'disable data parallelism.')\n\n if args.dist_url == \"env://\" and args.world_size == -1:\n args.world_size = int(os.environ[\"WORLD_SIZE\"])\n\n args.distributed = args.world_size > 1 or args.multiprocessing_distributed\n\n ngpus_per_node = torch.cuda.device_count()\n if args.multiprocessing_distributed:\n # Since we have ngpus_per_node processes per node, the total world_size\n # needs to be adjusted accordingly\n args.world_size = ngpus_per_node * args.world_size\n # Use torch.multiprocessing.spawn to launch distributed processes: the\n # main_worker process function\n mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))\n else:\n # Simply call main_worker function\n main_worker(args.gpu, ngpus_per_node, args)\n\n \n\ndef weights_init(m):\n for key in m.state_dict():\n if key.split('.')[-1] == 'weight':\n if 'conv' in key and 'norm' not in key:\n init.xavier_normal_(m.state_dict()[key])\n if 'bn' in key:\n m.state_dict()[key][...] = 1\n elif key.split('.')[-1] == 'bias':\n m.state_dict()[key][...] = 0\n\n\ndef main_worker(gpu, ngpus_per_node, args):\n global best_acc1\n args.gpu = gpu\n\n if args.gpu is not None:\n print(\"Use GPU: {} for training\".format(args.gpu))\n\n if args.distributed:\n if args.dist_url == \"env://\" and args.rank == -1:\n args.rank = int(os.environ[\"RANK\"])\n if args.multiprocessing_distributed:\n # For multiprocessing distributed training, rank needs to be the\n # global rank among all the processes\n args.rank = args.rank * ngpus_per_node + gpu\n dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,\n world_size=args.world_size, rank=args.rank)\n\n # create model\n #global full_model_name\n\n if args.pretrained:\n print(\"Not implemented !!! QQ\")\n \n else:\n model = HarDNeXt(arch=int(args.arch), depth_wise=args.depthwise)\n\n if args.distributed:\n # For multiprocessing distributed, DistributedDataParallel constructor\n # should always set the single device scope, otherwise,\n # DistributedDataParallel will use all available devices.\n if args.gpu is not None:\n torch.cuda.set_device(args.gpu)\n model.cuda(args.gpu)\n # When using a single GPU per process and per\n # DistributedDataParallel, we need to divide the batch size\n # ourselves based on the total number of GPUs we have\n args.batch_size = int(args.batch_size / ngpus_per_node)\n args.workers = int(args.workers / ngpus_per_node)\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])\n else:\n model.cuda()\n # DistributedDataParallel will divide and allocate batch_size to all\n # available GPUs if device_ids are not set\n model = torch.nn.parallel.DistributedDataParallel(model)\n elif args.gpu is not None:\n torch.cuda.set_device(args.gpu)\n model = model.cuda(args.gpu)\n else:\n # DataParallel will divide and allocate batch_size to all available GPUs\n if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):\n model.features = torch.nn.DataParallel(model.features)\n model.cuda()\n else:\n model = torch.nn.DataParallel(model).cuda()\n\n # define loss function (criterion) and optimizer\n criterion = nn.CrossEntropyLoss().cuda(args.gpu)\n\n optimizer = torch.optim.SGD(model.parameters(), args.lr,\n momentum=args.momentum,\n nesterov=True,\n weight_decay=args.weight_decay)\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_acc1 = checkpoint['best_acc1']\n if args.gpu is not None:\n # best_acc1 may be from a checkpoint from a different GPU\n best_acc1 = best_acc1.to(args.gpu)\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n elif not args.pretrained:\n model.apply(weights_init)\n \n total_params = sum(p.numel() for p in model.parameters())\n\n print( \"Parameters=\", total_params )\n cudnn.benchmark = True\n\n # Data loading code\n traindir = os.path.join(args.data, 'train')\n valdir = os.path.join(args.data, 'val')\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n train_dataset = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]))\n\n if args.distributed:\n train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)\n else:\n train_sampler = None\n\n train_loader = DataLoader(\n train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),\n num_workers=args.workers, pin_memory=True, sampler=train_sampler)\n\n val_loader = DataLoader(\n datasets.ImageFolder(valdir, transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ])),\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n\n if args.evaluate:\n validate(val_loader, model, criterion, args)\n return\n\n for epoch in range(args.start_epoch, args.epochs):\n if args.distributed:\n train_sampler.set_epoch(epoch)\n\n ''' for per epoch warmup'''\n # adjust learning rate\n adjust_learning_rate(optimizer, epoch, args)\n\n # train for one epoch\n train(train_loader, model, criterion, optimizer, epoch, args)\n \n\n \n\n # evaluate on validation set\n acc1 = validate(val_loader, model, criterion, args)\n\n # tensorboard summary write\n writer.add_scalars('Loss/',\n {'train_loss': train_loss,\n 'val___loss': val_loss}, epoch)\n \n writer.add_scalars('Top-1 Acc/',\n {'train_Acc': train_acc1,\n 'val___Acc': val_acc1}, epoch)\n \n writer.add_scalars('Top-5 Acc/',\n {'train_loss': train_acc5,\n 'val___loss': val_acc5}, epoch)\n \n writer.add_scalars('Learning Rate',\n {'lr': learning_rate}, epoch)\n\n \n\n # remember best acc@1 and save checkpoint\n is_best = acc1 > best_acc1\n best_acc1 = max(acc1, best_acc1)\n\n if not args.multiprocessing_distributed or (args.multiprocessing_distributed\n and args.rank % ngpus_per_node == 0):\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': model.state_dict(),\n 'best_acc1': best_acc1,\n 'optimizer' : optimizer.state_dict(),\n }, is_best)\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, args):\n batch_time = AverageMeter('Time', ':6.3f')\n #data_time = AverageMeter('Data', ':6.3f')\n losses = AverageMeter('Loss', ':.4e')\n top1 = AverageMeter('Acc@1', ':6.3f')\n top5 = AverageMeter('Acc@5', ':6.3f')\n lrm = ConstantMeter('lr')\n progress = ProgressMeter(len(train_loader), batch_time, losses, top1, top5, lrm,\n prefix=\"Epoch: [{}]\".format(epoch))\n\n # switch to train mode\n model.train()\n\n end = time.time()\n\n \n\n for i, (input, target) in enumerate(train_loader):\n # measure data loading time\n #data_time.update(time.time() - end)\n\n if args.gpu is not None:\n input = input.cuda(args.gpu, non_blocking=True)\n target = target.cuda(args.gpu, non_blocking=True)\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n top5.update(acc5[0], input.size(0))\n\n ''' for per batch warmup'''\n # # adjust learning rate\n # adjust_learning_rate(optimizer, epoch, args)\n\n\n lrm.update(optimizer.param_groups[0]['lr'])\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n \n optimizer.step()\n \n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n progress.print(i)\n\n\n global train_epoch \n train_epoch = epoch\n global train_acc1 \n train_acc1 = top1.avg.item()\n global train_acc5 \n train_acc5 = top5.avg.item()\n global train_loss \n train_loss = losses.avg\n\n \n\ndef validate(val_loader, model, criterion, args):\n\n global full_model_name\n \n print(train_epoch, train_acc1, train_acc5, train_loss)\n \n batch_time = AverageMeter('Time', ':6.3f', avg=False)\n losses = AverageMeter('Loss', ':.4e')\n top1 = AverageMeter('Acc@1', ':6.2f')\n top5 = AverageMeter('Acc@5', ':6.2f')\n progress = ProgressMeter(len(val_loader), batch_time, losses, top1, top5,\n prefix='Test: ')\n\n # switch to evaluate mode\n model.eval()\n\n with torch.no_grad():\n end = time.time()\n for i, (input, target) in enumerate(val_loader):\n if args.gpu is not None:\n input = input.cuda(args.gpu, non_blocking=True)\n target = target.cuda(args.gpu, non_blocking=True)\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n top5.update(acc5[0], input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n progress.print(i)\n\n # TODO: this should also be done with the ProgressMeter\n print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'\n .format(top1=top1, top5=top5))\n \n \n global val_acc1, val_acc5, val_loss\n\n val_acc1 = top1.avg.item()\n val_acc5 = top5.avg.item()\n val_loss = losses.avg\n \n # 開啟輸出的 CSV 檔案\n with open(full_model_name + '_'+str(args.epochs)+'_'+str(args.batch_size)+'_'+str(args.lr)+'_training_log.csv', 'a', newline='') as csvfile:\n # 建立CSV檔寫入器\n writer = csv.writer(csvfile)\n # 寫入一列資料\n writer.writerow([train_epoch, train_acc1, train_acc5, train_loss, top1.avg.item(), top5.avg.item(), losses.avg])\n\n return top1.avg\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'model_best.pth.tar')\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self, name, fmt=':f', avg=True):\n self.name = name\n self.fmt = fmt\n self.reset()\n self.display_avg = avg\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n #fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'\n if self.display_avg:\n fmtstr = '{name}: {avg' + self.fmt + '}'\n else:\n fmtstr = '{name}: {val' + self.fmt + '}'\n return fmtstr.format(**self.__dict__)\n\nclass ConstantMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self, name, fmt=':f'):\n self.name = name\n self.fmt = fmt\n self.reset()\n\n def reset(self):\n self.val = 0\n \n def update(self, val):\n self.val = val\n\n def __str__(self):\n fmtstr = '{name}: {val:f})'\n return fmtstr.format(**self.__dict__)\n\nclass ProgressMeter(object):\n def __init__(self, num_batches, *meters, prefix=\"\"):\n self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n self.meters = meters\n self.prefix = prefix\n\n def print(self, batch):\n entries = [self.prefix + self.batch_fmtstr.format(batch)]\n entries += [str(meter) for meter in self.meters]\n print('\\t'.join(entries))\n\n def _get_batch_fmtstr(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = '{:' + str(num_digits) + 'd}'\n return '[' + fmt + '/' + fmt.format(num_batches) + ']'\n\ninit_step = 0 # for warmup learning rate\ndecay_init_step = 0 # for the rest decay part\n\ndef adjust_learning_rate(optimizer, epoch, args):\n \n #Cosine learning rate decay\n ''' Per Batch warmup '''\n total_data = 1281167 # imageNet training data\n step = total_data // args.batch_size + 1 # drop_liat == False\n global init_step, decay_init_step, learning_rate\n\n total_warmup_step = args.warmup*step\n\n if epoch < args.warmup and args.warmup != 0:\n init_step += 1\n lr = (args.lr * init_step) /args.warmup\n\n else:\n \n \n\n # per epoch cosine decay (HarDNet original)\n lr = 0.5 * args.lr * (1 + np.cos(np.pi * (epoch-args.warmup)/ (args.epochs-args.warmup)))\n\n ## per batch cosine decay (me)\n # total_decay_step = (args.epochs-args.warmup)*step\n\n # lr = 0.5 * args.lr * (1 + np.cos(np.pi * (decay_init_step)/ (total_decay_step)))\n # decay_init_step += 1\n \n \n # lr = 0.5 * args.lr * (1 + np.cos(np.pi * (epoch)/ args.epochs ))\n\n learning_rate = lr\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.distributed.init_process_group",
"torch.multiprocessing.spawn",
"torch.utils.data.distributed.DistributedSampler",
"torch.cuda.set_device",
"torch.manual_seed",
"torch.load",
"torch.utils.data.DataLoader",
"numpy.cos",
"torch.nn.DataParallel",
"torch.no_grad",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.device_count",
"torch.nn.parallel.DistributedDataParallel",
"torch.save"
]
] |
tsunekoromochi/ssd
|
[
"0a081b957e90a8edd85c1ba7d96556ce929f9628"
] |
[
"get_data_from_XML.py"
] |
[
"import numpy as np\nimport os\nfrom xml.etree import ElementTree\n\nclass XML_preprocessor(object):\n\n def __init__(self, data_path):\n self.path_prefix = data_path\n self.num_classes = 2\n self.data = dict()\n self._preprocess_XML()\n\n def _preprocess_XML(self):\n filenames = os.listdir(self.path_prefix)\n for filename in filenames:\n tree = ElementTree.parse(self.path_prefix + filename)\n root = tree.getroot()\n bounding_boxes = []\n one_hot_classes = []\n size_tree = root.find('size')\n width = float(size_tree.find('width').text)\n height = float(size_tree.find('height').text)\n for object_tree in root.findall('object'):\n for bounding_box in object_tree.iter('bndbox'):\n xmin = float(bounding_box.find('xmin').text)/width\n ymin = float(bounding_box.find('ymin').text)/height\n xmax = float(bounding_box.find('xmax').text)/width\n ymax = float(bounding_box.find('ymax').text)/height\n bounding_box = [xmin,ymin,xmax,ymax]\n bounding_boxes.append(bounding_box)\n class_name = object_tree.find('name').text\n one_hot_class = self._to_one_hot(class_name)\n one_hot_classes.append(one_hot_class)\n image_name = root.find('filename').text\n bounding_boxes = np.asarray(bounding_boxes)\n one_hot_classes = np.asarray(one_hot_classes)\n image_data = np.hstack((bounding_boxes, one_hot_classes))\n self.data[image_name] = image_data\n\n def _to_one_hot(self,name):\n one_hot_vector = [0] * self.num_classes\n if name == 'jinkou':\n one_hot_vector[0] = 1\n elif name == 'sizen':\n one_hot_vector[1] = 1\n # elif name == 'camera':\n # one_hot_vector[2] = 1\n # elif name == 'boat':\n # one_hot_vector[3] = 1\n # elif name == 'bottle':\n # one_hot_vector[4] = 1\n # elif name == 'bus':\n # one_hot_vector[5] = 1\n # elif name == 'car':\n # one_hot_vector[6] = 1\n # elif name == 'cat':\n # one_hot_vector[7] = 1\n # elif name == 'chair':\n # one_hot_vector[8] = 1\n # elif name == 'cow':\n # one_hot_vector[9] = 1\n # elif name == 'diningtable':\n # one_hot_vector[10] = 1\n # elif name == 'dog':\n # one_hot_vector[11] = 1\n # elif name == 'horse':\n # one_hot_vector[12] = 1\n # elif name == 'motorbike':\n # one_hot_vector[13] = 1\n # elif name == 'person':\n # one_hot_vector[14] = 1\n # elif name == 'pottedplant':\n # one_hot_vector[15] = 1\n # elif name == 'sheep':\n # one_hot_vector[16] = 1\n # elif name == 'sofa':\n # one_hot_vector[17] = 1\n # elif name == 'train':\n # one_hot_vector[18] = 1\n # elif name == 'tvmonitor':\n # one_hot_vector[19] = 1\n else:\n print('unknown label: %s' %name)\n\n return one_hot_vector\n\n## example on how to use it\nimport pickle\ndata = XML_preprocessor('data/Annotations/').data\npickle.dump(data,open('supervised_data.pkl','wb'))\n"
] |
[
[
"numpy.asarray",
"numpy.hstack"
]
] |
Terminator-Creators/CS434_Assignment4
|
[
"736228191af71fdf0e8e6c892cd517cbd3d1bac5"
] |
[
"pa4_starter/src/decompose.py"
] |
[
"import numpy as np\nimport copy\n\n\nclass PCA():\n \"\"\"\n PCA. A class to reduce dimensions\n \"\"\"\n\n def __init__(self, retain_ratio):\n \"\"\"\n\n :param retain_ratio: percentage of the variance we maitain (see slide for definition)\n \"\"\"\n self.retain_ratio = retain_ratio\n\n @staticmethod\n def mean(x):\n \"\"\"\n returns mean of x\n :param x: matrix of shape (n, m)\n :return: mean of x of with shape (m,)\n \"\"\"\n return x.mean(axis=0)\n\n @staticmethod\n def cov(x):\n \"\"\"\n returns the covariance of x,\n :param x: input data of dim (n, m)\n :return: the covariance matrix of (m, m)\n \"\"\"\n return np.cov(x.T)\n\n @staticmethod\n def eig(c):\n \"\"\"\n returns the eigval and eigvec\n :param c: input matrix of dim (m, m)\n :return:\n eigval: a numpy vector of (m,)\n eigvec: a matrix of (m, m), column ``eigvec[:,i]`` is the eigenvector corresponding to the\n eigenvalue ``eigval[i]``\n Note: eigval is not necessarily ordered\n \"\"\"\n\n eigval, eigvec = np.linalg.eig(c)\n eigval = np.real(eigval)\n eigvec = np.real(eigvec)\n return eigval, eigvec\n\n\n def fit(self, x):\n \"\"\"\n fits the data x into the PCA. It results in self.eig_vecs and self.eig_values which will\n be used in the transform method\n :param x: input data of shape (n, m); n instances and m features\n :return:\n sets proper values for self.eig_vecs and eig_values\n \"\"\"\n\n self.eig_vals = None\n self.eig_vecs = None\n\n center = x - PCA.mean(x)\n cov_matrix = self.cov(center)\n \n (eigval, eigvec) = self.eig(cov_matrix)\n self.eig_vals = eigval\n self.eig_vecs = eigvec\n\n ########################################\n # YOUR CODE GOES HERE #\n ########################################\n\n\n def transform(self, x):\n \"\"\"\n projects x into lower dimension based on current eig_vals and eig_vecs\n :param x: input data of shape (n, m)\n :return: projected data with shape (n, len of eig_vals)\n \"\"\"\n\n if isinstance(x, np.ndarray):\n x = np.asarray(x)\n if self.eig_vecs is not None:\n return np.matmul(x, self.eig_vecs)\n else:\n return x\n"
] |
[
[
"numpy.asarray",
"numpy.linalg.eig",
"numpy.matmul",
"numpy.real",
"numpy.cov"
]
] |
newlikehalo/pytroch-ctpn-Retina
|
[
"5c80fa1c91fa55cd6e45490a51385cab3b3343b6"
] |
[
"predict.py"
] |
[
"# -*- coding:utf-8 -*-\n# '''\n# Created on 18-12-11 上午10:03\n#\n# @Author: Greg Gao(laygin)\n# '''\nimport os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = ''\nimport cv2\nimport numpy as np\nimport glob\nimport torch\nimport torch.nn.functional as F\nfrom ctpn_model import CTPN_Model\nfrom ctpn_utils import gen_anchor, bbox_transfor_inv, nms, clip_box, filter_bbox, TextProposalConnectorOriented\nfrom ctpn_utils import resize\nimport config\nimport ipdb\nimport time\nimport math\nfrom lib.text_proposal_connector import TextProposalConnector\nimport copy\n\n\n# from lib.fast_rcnn.nms_wrapper import nms\ndef cutstr(string):\n return string.split('/')[-1].split('.')[0]\n\n\ndef ifdir(dir): # 判断是不是有这个目录\n if not os.path.exists(dir):\n os.mkdir(dir)\n\n\nALL_DIR = \"/home/like/data/ctpnresult\"\nEPOCH = \"epoch_12_b\"\n\nEPOCH_DIR = os.path.join(ALL_DIR, EPOCH)\n\nnewepoch = os.path.join(EPOCH_DIR, str(config.IOU_SELECT))\nifdir(newepoch)\nEPOCH_IMAGE = os.path.join(newepoch, \"imageresult\")\nEPOCH_TXT = os.path.join(newepoch, \"pthfile\")\n\nifdir(EPOCH_DIR)\nifdir(EPOCH_IMAGE)\nifdir(EPOCH_TXT)\n\nprob_thresh = config.IOU_SELECT\nwidth = 600\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nweights = glob.glob(os.path.join(EPOCH_DIR, '*.tar'))[0]\n# torch.save(weights,weights)\nipdb.set_trace()\n# img_path = '/home/like/data/pic/image/without_label/37.JPG'\n# weights = \"/home/like/pytorch_ctpn/checkpoints/ctpn_ep02_0.0727_0.0568_0.1295.pth.tar\"\nipdb.set_trace()\nmodel = CTPN_Model()\nmodel.load_state_dict(torch.load(weights, map_location=device)['model_state_dict'])\nmodel.to(device)\nmodel.eval()\n\n\ndef dis(image):\n cv2.imshow('image', image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n# new work\ndef anaiou(line, inds):\n boxs = []\n\n for i in inds:\n bbox = line[i, :4]\n x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]\n boxs.append(bbox)\n newbox = copy.deepcopy(boxs)\n for i, mbox in enumerate(boxs):\n for j, nbox in enumerate(boxs):\n if i != j:\n\n marea = (mbox[2] - mbox[0]) * (mbox[3] - mbox[1])\n narea = (nbox[2] - nbox[0]) * (nbox[3] - nbox[1])\n # print(mbox,nbox,marea, narea)\n x1 = max(mbox[0], nbox[0])\n x2 = min(mbox[2], nbox[2])\n y1 = max(mbox[1], nbox[1])\n y2 = min(mbox[3], nbox[3])\n intersection = max(x2 - x1, 0) * max(y2 - y1, 0)\n\n if intersection / marea > 0.7:\n bx1 = min(mbox[0], nbox[0])\n bx2 = max(mbox[2], nbox[2])\n by1 = min(mbox[1], nbox[1])\n by2 = max(mbox[3], nbox[3])\n newbox[i] = [0, 0, 0, 0]\n newbox[j] = [bx1, by1, bx2, by2]\n elif intersection / narea > 0.7:\n bx1 = min(mbox[0], nbox[0])\n bx2 = max(mbox[2], nbox[2])\n by1 = min(mbox[1], nbox[1])\n by2 = max(mbox[3], nbox[3])\n newbox[j] = [0, 0, 0, 0]\n newbox[i] = [bx1, by1, bx2, by2]\n nnbox = []\n for i in newbox:\n if not (i[0] == 0 and i[1] == 0 and i[2] == 0 and i[3] == 0):\n # print(i)\n nnbox.append(i)\n else:\n print(\"1<i\")\n # ipdb.set_trace()\n return nnbox\n\n\ndef save_results(image_name, line, thresh):\n im = cv2.imread(image_name)\n inds = np.where(line[:, -1] >= thresh)[0]\n if len(inds) == 0:\n return\n newimage_name = image_name.split('/')[-1].split('.')[0]\n all_list = []\n nnbox = anaiou(line, inds)\n for bbox in nnbox:\n # bbox = line[i, :4]\n # score = line[i, -1]\n cv2.rectangle(\n im, (bbox[0], bbox[1]), (bbox[2], bbox[3]),\n color=(0, 0, 255),\n thickness=1)\n all_list.append([bbox[0], bbox[1], bbox[2], bbox[3]])\n save_path = os.path.join(EPOCH_TXT, newimage_name + '.txt')\n file = open(save_path, 'w')\n file.write(str(all_list))\n file.close()\n\n image_name = image_name.split('/')[-1]\n cv2.imwrite(os.path.join(EPOCH_IMAGE, image_name), im)\n\n\ndef connect_proposal(text_proposals, scores, im_size):\n cp = TextProposalConnector()\n line = cp.get_text_lines(text_proposals, scores, im_size)\n return line\n\n\ndef test(img_path):\n image = cv2.imread(img_path)\n\n \"\"\"gray\"\"\"\n\n\n\n isize = image.shape\n # ipdb.set_trace()\n image_c = image.copy()\n # h1,w1,c=image_c.shape\n # oddnumber=w1/width\n # image = resize(image, width=width)\n h, w = image.shape[:2]\n image = image.astype(np.float32) - config.IMAGE_MEAN\n image = torch.from_numpy(image.transpose(2, 0, 1)).unsqueeze(0).float()\n\n\n\n with torch.no_grad():\n image = image.to(device)\n cls, regr = model(image)\n cls_prob = F.softmax(cls, dim=-1).cpu().numpy()\n regr = regr.cpu().numpy()\n anchor = gen_anchor((math.ceil(h / 16), math.ceil(w / 16)), 16)\n bbox = bbox_transfor_inv(anchor, regr)\n bbox = clip_box(bbox, [h, w])\n fg = np.where(cls_prob[0, :, 1] > prob_thresh)[0]\n boxes = bbox[fg, :] # 可用的框格\n scores = cls_prob[0, fg, 1]\n\n select_anchor = boxes.astype(np.float32)\n\n keep_index = filter_bbox(select_anchor, 16)\n\n # nsm\n boxes = select_anchor[keep_index]\n scores = scores[keep_index]\n\n NMS_THRESH = 0.3\n dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32)\n\n keep = nms(dets, NMS_THRESH)\n dets = dets[keep, :]\n\n keep = np.where(dets[:, 4] >= 0.7)[0]\n dets = dets[keep, :]\n line = connect_proposal(dets[:, 0:4], dets[:, 4], isize)\n save_results(img_path, line, thresh=0.9)\n\n\nif __name__ == '__main__':\n DATA_DIR = \"/home/like/data/ctpnresult/testdata/pic\"\n im_names = glob.glob(os.path.join(DATA_DIR, '*.png')) + \\\n glob.glob(os.path.join(DATA_DIR, '*.jpg'))\n im_names.sort()\n start = time.time()\n # im_names=[\"/home/like/data/ctpnresult/testdata/111.png\"]\n for im_name in im_names:\n print(im_name)\n test(im_name)\n # ctpn(sess, net, im_name)\n end = time.time()\n print(end - start)\n"
] |
[
[
"numpy.hstack",
"torch.nn.functional.softmax",
"torch.load",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.where"
]
] |
MichalPitr/transformers
|
[
"8b26688e2e4b68a64f4710b3627439089947cb08"
] |
[
"src/transformers/models/distilbert/modeling_distilbert.py"
] |
[
"# coding=utf-8\n# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\n PyTorch DistilBERT model adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM) and in\n part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)\n\"\"\"\n\n\nimport copy\nimport math\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\n\nfrom ...activations import gelu\nfrom ...file_utils import (\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n replace_return_docstrings,\n)\nfrom ...modeling_outputs import (\n BaseModelOutput,\n MaskedLMOutput,\n MultipleChoiceModelOutput,\n QuestionAnsweringModelOutput,\n SequenceClassifierOutput,\n TokenClassifierOutput,\n)\nfrom ...modeling_utils import (\n PreTrainedModel,\n apply_chunking_to_forward,\n find_pruneable_heads_and_indices,\n prune_linear_layer,\n)\nfrom ...utils import logging\nfrom .configuration_distilbert import DistilBertConfig\n\n\nlogger = logging.get_logger(__name__)\n_CHECKPOINT_FOR_DOC = \"distilbert-base-uncased\"\n_CONFIG_FOR_DOC = \"DistilBertConfig\"\n_TOKENIZER_FOR_DOC = \"DistilBertTokenizer\"\n\nDISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"distilbert-base-uncased\",\n \"distilbert-base-uncased-distilled-squad\",\n \"distilbert-base-cased\",\n \"distilbert-base-cased-distilled-squad\",\n \"distilbert-base-german-cased\",\n \"distilbert-base-multilingual-cased\",\n \"distilbert-base-uncased-finetuned-sst-2-english\",\n # See all DistilBERT models at https://huggingface.co/models?filter=distilbert\n]\n\n\n# UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE #\n\n\ndef create_sinusoidal_embeddings(n_pos, dim, out):\n position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])\n out.requires_grad = False\n out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))\n out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))\n out.detach_()\n\n\nclass Embeddings(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)\n if config.sinusoidal_pos_embds:\n create_sinusoidal_embeddings(\n n_pos=config.max_position_embeddings, dim=config.dim, out=self.position_embeddings.weight\n )\n\n self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)\n self.dropout = nn.Dropout(config.dropout)\n\n def forward(self, input_ids):\n \"\"\"\n Parameters:\n input_ids: torch.tensor(bs, max_seq_length) The token ids to embed.\n\n Returns: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type\n embeddings)\n \"\"\"\n seq_length = input_ids.size(1)\n position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length)\n\n word_embeddings = self.word_embeddings(input_ids) # (bs, max_seq_length, dim)\n position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim)\n\n embeddings = word_embeddings + position_embeddings # (bs, max_seq_length, dim)\n embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim)\n embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim)\n return embeddings\n\n\nclass MultiHeadSelfAttention(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n self.n_heads = config.n_heads\n self.dim = config.dim\n self.dropout = nn.Dropout(p=config.attention_dropout)\n\n assert self.dim % self.n_heads == 0\n\n self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)\n self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)\n self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)\n self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)\n\n self.pruned_heads = set()\n\n def prune_heads(self, heads):\n attention_head_size = self.dim // self.n_heads\n if len(heads) == 0:\n return\n heads, index = find_pruneable_heads_and_indices(heads, self.n_heads, attention_head_size, self.pruned_heads)\n # Prune linear layers\n self.q_lin = prune_linear_layer(self.q_lin, index)\n self.k_lin = prune_linear_layer(self.k_lin, index)\n self.v_lin = prune_linear_layer(self.v_lin, index)\n self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)\n # Update hyper params\n self.n_heads = self.n_heads - len(heads)\n self.dim = attention_head_size * self.n_heads\n self.pruned_heads = self.pruned_heads.union(heads)\n\n def forward(self, query, key, value, mask, head_mask=None, output_attentions=False):\n \"\"\"\n Parameters:\n query: torch.tensor(bs, seq_length, dim)\n key: torch.tensor(bs, seq_length, dim)\n value: torch.tensor(bs, seq_length, dim)\n mask: torch.tensor(bs, seq_length)\n\n Returns:\n weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,\n seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`\n \"\"\"\n bs, q_length, dim = query.size()\n k_length = key.size(1)\n # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'\n # assert key.size() == value.size()\n\n dim_per_head = self.dim // self.n_heads\n\n mask_reshp = (bs, 1, 1, k_length)\n\n def shape(x):\n \"\"\"separate heads\"\"\"\n return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)\n\n def unshape(x):\n \"\"\"group heads\"\"\"\n return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)\n\n q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)\n k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)\n v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)\n\n q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)\n scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length)\n mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)\n scores.masked_fill_(mask, -float(\"inf\")) # (bs, n_heads, q_length, k_length)\n\n weights = nn.Softmax(dim=-1)(scores) # (bs, n_heads, q_length, k_length)\n weights = self.dropout(weights) # (bs, n_heads, q_length, k_length)\n\n # Mask heads if we want to\n if head_mask is not None:\n weights = weights * head_mask\n\n context = torch.matmul(weights, v) # (bs, n_heads, q_length, dim_per_head)\n context = unshape(context) # (bs, q_length, dim)\n context = self.out_lin(context) # (bs, q_length, dim)\n\n if output_attentions:\n return (context, weights)\n else:\n return (context,)\n\n\nclass FFN(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.dropout = nn.Dropout(p=config.dropout)\n self.chunk_size_feed_forward = config.chunk_size_feed_forward\n self.seq_len_dim = 1\n self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)\n self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)\n assert config.activation in [\"relu\", \"gelu\"], f\"activation ({config.activation}) must be in ['relu', 'gelu']\"\n self.activation = gelu if config.activation == \"gelu\" else nn.ReLU()\n\n def forward(self, input):\n return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)\n\n def ff_chunk(self, input):\n x = self.lin1(input)\n x = self.activation(x)\n x = self.lin2(x)\n x = self.dropout(x)\n return x\n\n\nclass TransformerBlock(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n assert config.dim % config.n_heads == 0\n\n self.attention = MultiHeadSelfAttention(config)\n self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)\n\n self.ffn = FFN(config)\n self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)\n\n def forward(self, x, attn_mask=None, head_mask=None, output_attentions=False):\n \"\"\"\n Parameters:\n x: torch.tensor(bs, seq_length, dim)\n attn_mask: torch.tensor(bs, seq_length)\n\n Returns:\n sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:\n torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.\n \"\"\"\n # Self-Attention\n sa_output = self.attention(\n query=x,\n key=x,\n value=x,\n mask=attn_mask,\n head_mask=head_mask,\n output_attentions=output_attentions,\n )\n if output_attentions:\n sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)\n else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples\n assert type(sa_output) == tuple\n sa_output = sa_output[0]\n sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)\n\n # Feed Forward Network\n ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)\n ffn_output = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)\n\n output = (ffn_output,)\n if output_attentions:\n output = (sa_weights,) + output\n return output\n\n\nclass Transformer(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.n_layers = config.n_layers\n\n layer = TransformerBlock(config)\n self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config.n_layers)])\n\n def forward(\n self, x, attn_mask=None, head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=None\n ): # docstyle-ignore\n \"\"\"\n Parameters:\n x: torch.tensor(bs, seq_length, dim) Input sequence embedded.\n attn_mask: torch.tensor(bs, seq_length) Attention mask on the sequence.\n\n Returns:\n hidden_state: torch.tensor(bs, seq_length, dim) Sequence of hidden states in the last (top)\n layer all_hidden_states: Tuple[torch.tensor(bs, seq_length, dim)]\n Tuple of length n_layers with the hidden states from each layer.\n Optional: only if output_hidden_states=True\n all_attentions: Tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]\n Tuple of length n_layers with the attention weights from each layer\n Optional: only if output_attentions=True\n \"\"\"\n all_hidden_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n\n hidden_state = x\n for i, layer_module in enumerate(self.layer):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_state,)\n\n layer_outputs = layer_module(\n x=hidden_state, attn_mask=attn_mask, head_mask=head_mask[i], output_attentions=output_attentions\n )\n hidden_state = layer_outputs[-1]\n\n if output_attentions:\n assert len(layer_outputs) == 2\n attentions = layer_outputs[0]\n all_attentions = all_attentions + (attentions,)\n else:\n assert len(layer_outputs) == 1\n\n # Add last layer\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_state,)\n\n if not return_dict:\n return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)\n return BaseModelOutput(\n last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions\n )\n\n\n# INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #\nclass DistilBertPreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = DistilBertConfig\n load_tf_weights = None\n base_model_prefix = \"distilbert\"\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights.\"\"\"\n if isinstance(module, nn.Linear):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.Embedding):\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n\n\nDISTILBERT_START_DOCSTRING = r\"\"\"\n\n This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic\n methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,\n pruning heads etc.)\n\n This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__\n subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to\n general usage and behavior.\n\n Parameters:\n config (:class:`~transformers.DistilBertConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model\n weights.\n\"\"\"\n\nDISTILBERT_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using :class:`~transformers.DistilBertTokenizer`. See\n :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for\n details.\n\n `What are input IDs? <../glossary.html#input-ids>`__\n attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`):\n Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):\n Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`({0}, hidden_size)`, `optional`):\n Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert :obj:`input_ids` indices into associated\n vectors than the model's internal embedding lookup matrix.\n output_attentions (:obj:`bool`, `optional`):\n Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned\n tensors for more detail.\n output_hidden_states (:obj:`bool`, `optional`):\n Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for\n more detail.\n return_dict (:obj:`bool`, `optional`):\n Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare DistilBERT encoder/transformer outputting raw hidden-states without any specific head on top.\",\n DISTILBERT_START_DOCSTRING,\n)\nclass DistilBertModel(DistilBertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.embeddings = Embeddings(config) # Embeddings\n self.transformer = Transformer(config) # Encoder\n\n self.init_weights()\n\n def get_input_embeddings(self):\n return self.embeddings.word_embeddings\n\n def set_input_embeddings(self, new_embeddings):\n self.embeddings.word_embeddings = new_embeddings\n\n def _prune_heads(self, heads_to_prune):\n \"\"\"\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n \"\"\"\n for layer, heads in heads_to_prune.items():\n self.transformer.layer[layer].attention.prune_heads(heads)\n\n @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format(\"batch_size, num_choices\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=BaseModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n\n if attention_mask is None:\n attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)\n\n # Prepare head mask if needed\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n if inputs_embeds is None:\n inputs_embeds = self.embeddings(input_ids) # (bs, seq_length, dim)\n return self.transformer(\n x=inputs_embeds,\n attn_mask=attention_mask,\n head_mask=head_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n\n@add_start_docstrings(\n \"\"\"DistilBert Model with a `masked language modeling` head on top. \"\"\",\n DISTILBERT_START_DOCSTRING,\n)\nclass DistilBertForMaskedLM(DistilBertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.distilbert = DistilBertModel(config)\n self.vocab_transform = nn.Linear(config.dim, config.dim)\n self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)\n self.vocab_projector = nn.Linear(config.dim, config.vocab_size)\n\n self.init_weights()\n\n self.mlm_loss_fct = nn.CrossEntropyLoss()\n\n def get_output_embeddings(self):\n return self.vocab_projector\n\n def set_output_embeddings(self, new_embeddings):\n self.vocab_projector = new_embeddings\n\n @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format(\"batch_size, num_choices\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=MaskedLMOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,\n config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored\n (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n dlbrt_output = self.distilbert(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = dlbrt_output[0] # (bs, seq_length, dim)\n prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)\n prediction_logits = gelu(prediction_logits) # (bs, seq_length, dim)\n prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)\n prediction_logits = self.vocab_projector(prediction_logits) # (bs, seq_length, vocab_size)\n\n mlm_loss = None\n if labels is not None:\n mlm_loss = self.mlm_loss_fct(prediction_logits.view(-1, prediction_logits.size(-1)), labels.view(-1))\n\n if not return_dict:\n output = (prediction_logits,) + dlbrt_output[1:]\n return ((mlm_loss,) + output) if mlm_loss is not None else output\n\n return MaskedLMOutput(\n loss=mlm_loss,\n logits=prediction_logits,\n hidden_states=dlbrt_output.hidden_states,\n attentions=dlbrt_output.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the\n pooled output) e.g. for GLUE tasks.\n \"\"\",\n DISTILBERT_START_DOCSTRING,\n)\nclass DistilBertForSequenceClassification(DistilBertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n self.config = config\n\n self.distilbert = DistilBertModel(config)\n self.pre_classifier = nn.Linear(config.dim, config.dim)\n self.classifier = nn.Linear(config.dim, config.num_labels)\n self.dropout = nn.Dropout(config.seq_classif_dropout)\n\n self.init_weights()\n\n @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=SequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,\n config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),\n If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n distilbert_output = self.distilbert(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_state = distilbert_output[0] # (bs, seq_len, dim)\n pooled_output = hidden_state[:, 0] # (bs, dim)\n pooled_output = self.pre_classifier(pooled_output) # (bs, dim)\n pooled_output = nn.ReLU()(pooled_output) # (bs, dim)\n pooled_output = self.dropout(pooled_output) # (bs, dim)\n logits = self.classifier(pooled_output) # (bs, num_labels)\n\n loss = None\n if labels is not None:\n if self.config.problem_type is None:\n if self.num_labels == 1:\n self.config.problem_type = \"regression\"\n elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n self.config.problem_type = \"single_label_classification\"\n else:\n self.config.problem_type = \"multi_label_classification\"\n\n if self.config.problem_type == \"regression\":\n loss_fct = MSELoss()\n if self.num_labels == 1:\n loss = loss_fct(logits.squeeze(), labels.squeeze())\n else:\n loss = loss_fct(logits, labels)\n elif self.config.problem_type == \"single_label_classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n elif self.config.problem_type == \"multi_label_classification\":\n loss_fct = BCEWithLogitsLoss()\n loss = loss_fct(logits, labels)\n\n if not return_dict:\n output = (logits,) + distilbert_output[1:]\n return ((loss,) + output) if loss is not None else output\n\n return SequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=distilbert_output.hidden_states,\n attentions=distilbert_output.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n DistilBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a\n linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n \"\"\",\n DISTILBERT_START_DOCSTRING,\n)\nclass DistilBertForQuestionAnswering(DistilBertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.distilbert = DistilBertModel(config)\n self.qa_outputs = nn.Linear(config.dim, config.num_labels)\n assert config.num_labels == 2\n self.dropout = nn.Dropout(config.qa_dropout)\n\n self.init_weights()\n\n @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING.format(\"batch_size, num_choices\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=QuestionAnsweringModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n start_positions=None,\n end_positions=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n distilbert_output = self.distilbert(\n input_ids=input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n hidden_states = distilbert_output[0] # (bs, max_query_len, dim)\n\n hidden_states = self.dropout(hidden_states) # (bs, max_query_len, dim)\n logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous() # (bs, max_query_len)\n end_logits = end_logits.squeeze(-1).contiguous() # (bs, max_query_len)\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + distilbert_output[1:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return QuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=distilbert_output.hidden_states,\n attentions=distilbert_output.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n DistilBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.\n for Named-Entity-Recognition (NER) tasks.\n \"\"\",\n DISTILBERT_START_DOCSTRING,\n)\nclass DistilBertForTokenClassification(DistilBertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.distilbert = DistilBertModel(config)\n self.dropout = nn.Dropout(config.dropout)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n @add_start_docstrings_to_model_forward(DISTILBERT_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels -\n 1]``.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.distilbert(\n input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = logits.view(-1, self.num_labels)\n active_labels = torch.where(\n active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)\n )\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n DistilBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and\n a softmax) e.g. for RocStories/SWAG tasks.\n \"\"\",\n DISTILBERT_START_DOCSTRING,\n)\nclass DistilBertForMultipleChoice(DistilBertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.distilbert = DistilBertModel(config)\n self.pre_classifier = nn.Linear(config.dim, config.dim)\n self.classifier = nn.Linear(config.dim, 1)\n self.dropout = nn.Dropout(config.seq_classif_dropout)\n\n self.init_weights()\n\n @add_start_docstrings_to_model_forward(\n DISTILBERT_INPUTS_DOCSTRING.format(\"batch_size, num_choices, sequence_length\")\n )\n @replace_return_docstrings(output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC)\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n labels=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for computing the multiple choice classification loss. Indices should be in ``[0, ...,\n num_choices-1]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See\n :obj:`input_ids` above)\n\n Returns:\n\n Examples::\n\n >>> from transformers import DistilBertTokenizer, DistilBertForMultipleChoice\n >>> import torch\n\n >>> tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-cased')\n >>> model = DistilBertForMultipleChoice.from_pretrained('distilbert-base-cased')\n\n >>> prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\"\n >>> choice0 = \"It is eaten with a fork and a knife.\"\n >>> choice1 = \"It is eaten while held in the hand.\"\n >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1\n\n >>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors='pt', padding=True)\n >>> outputs = model(**{k: v.unsqueeze(0) for k,v in encoding.items()}, labels=labels) # batch size is 1\n\n >>> # the linear classifier still needs to be trained\n >>> loss = outputs.loss\n >>> logits = outputs.logits\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]\n\n input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None\n attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None\n inputs_embeds = (\n inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))\n if inputs_embeds is not None\n else None\n )\n\n outputs = self.distilbert(\n input_ids,\n attention_mask=attention_mask,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)\n pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)\n pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)\n pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)\n pooled_output = self.dropout(pooled_output) # (bs * num_choices, dim)\n logits = self.classifier(pooled_output) # (bs * num_choices, 1)\n\n reshaped_logits = logits.view(-1, num_choices) # (bs, num_choices)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n\n if not return_dict:\n output = (reshaped_logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return MultipleChoiceModelOutput(\n loss=loss,\n logits=reshaped_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n"
] |
[
[
"torch.nn.Softmax",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"numpy.power",
"numpy.cos",
"torch.nn.Embedding",
"torch.nn.LayerNorm",
"numpy.sin",
"torch.nn.Linear",
"torch.matmul",
"torch.nn.BCEWithLogitsLoss",
"torch.tensor",
"torch.arange",
"torch.nn.ReLU",
"torch.nn.MSELoss"
]
] |
arjunbhagoji/network-data-sharing
|
[
"05a4965758e3a0de312fed27becba3eabf0cb8f0"
] |
[
"utils/data.py"
] |
[
"import numpy as np\nimport pandas as pd\n\ndef data_cleanup(X,y):\n inf_indices=np.where(X==np.inf)\n nan_indices=np.where(X!=X)\n mask = np.ones(len(X), dtype=bool)\n mask[np.union1d(inf_indices[0],nan_indices[0])] = False\n X_mod=X[mask,:]\n y_mod=y[mask]\n return X_mod,y_mod\n\ndef read_data(input_type,input_file,train_split,rng,attack_types=None):\n \n if input_type == 'CIC-IDS-2017':\n df=pd.read_csv(input_file,delimiter=',')\n df_np=df.to_numpy()\n df_np_perm=df_np[rng.permutation(len(df_np))]\n # Removing port from features\n X=df_np_perm[:,1:-2]\n y=df_np_perm[:,-1]\n\n y_mod=np.zeros(len(y))\n for i in range(len(attack_types)):\n y_mod[np.where(y==attack_types[i])]=i+1\n if input_type == 'nfdump-CIC-IDS-2017':\n df=pd.read_csv(input_file,delimiter=',')\n df_np=df.to_numpy()\n df_np_perm=df_np[rng.permutation(len(df_np))]\n # Removing index from features\n X=df_np_perm[:,1:-2]\n y=df_np_perm[:,-1]\n\n y_mod=np.zeros(len(y))\n for i in range(len(attack_types)):\n y_mod[np.where(y==attack_types[i])]=i+1\n elif input_type == 'CIC-IDS-2018':\n df=pd.read_csv(input_file,delimiter=',')\n df_np=df.to_numpy()\n df_np_perm=df_np[rng.permutation(len(df_np))]\n # Removing port, protocol and timestamp from features\n X=df_np_perm[:,3:-2]\n y=df_np_perm[:,-1]\n \n # Creating labeled data\n y_mod=np.zeros(len(y))\n for i in range(len(attack_types)):\n y_mod[np.where(y==attack_types[i])]=i+1\n elif input_type == 'iot':\n # To-do\n #input_dir = \"../../data/benign_attack/nfcapd.*.csv\"\n\n # input_data_file_list = glob.glob(input_dir)\n # li = []\n # print(\"reading dataframe\")\n # for filename in input_data_file_list:\n # df = pd.read_csv(filename, index_col=None, header=0)\n # li.append(df)\n # df = pd.concat(li, axis=0, ignore_index=True)\n df = pd.read_csv(args.input_csv, index_col=None, header=0)\n # filter out the last few lines that are aggregate stats and not flow records\n df = df[~pd.isna(df[\"pr\"])]\n \n X_clean,y_clean=data_cleanup(X,y_mod)\n \n train_len=int(train_split*len(X_clean))\n # Splitting into train and test\n X_train=X_clean[:train_len]\n X_test=X_clean[train_len:]\n\n y_train=y_clean[:train_len]\n y_test=y_clean[train_len:]\n \n train_mal_len=0\n for i in range(len(attack_types)):\n train_mal_len+=len(np.where(y_train==i+1)[0])\n\n test_mal_len=0\n for i in range(len(attack_types)):\n test_mal_len+=len(np.where(y_test==i+1)[0])\n \n print('Number of malicious samples in train set: %s' % train_mal_len)\n print('Total length of train set: %s' % len(y_train))\n \n print('Number of malicious samples in test set: %s' % test_mal_len)\n print('Total length of test set: %s' % len(y_test))\n \n return X_train, y_train, X_test, y_test\n \n \n\n"
] |
[
[
"pandas.isna",
"pandas.read_csv",
"numpy.where",
"numpy.union1d"
]
] |
kehannan/mlcourse
|
[
"e51b16ac1feaeb732a211b837746b70fc2fcee7b"
] |
[
"homework_working/hw7-backprop/code/test_utils.py"
] |
[
"\"\"\"Computation graph test utilities\n\nBelow are functions that can assist in testing the implementation of backward\nfor individual nodes, as well as the gradient computation in a\nComputationGraphFunction. The approach is to use the secant approximation to\ncompute the gradient numerically, and this is then compared to the gradient\ncomputed by the node or ComputationGraphFunction. Note that this is really only\nverifying that the gradient corresponds to the function value that is being\ncomputed. So this is only useful if you also check that the forward() is\ncorrect in nodes, and that the get_objective() is correct in the\nCopmputationGraphFunction.\n\nThis computation graph framework was designed and implemented by\nPhilipp Meerkamp, Pierre Garapon, and David Rosenberg.\nLicense: Creative Commons Attribution 4.0 International License\n\n\"\"\"\n\nimport logging\nimport graph\nimport numpy as np\nlogging.basicConfig(format='%(levelname)s: %(message)s',level=logging.DEBUG)\n\ndef relative_error(a,b):\n if a==0.0 and b==0.0:\n return 0.0\n # approach described here http://cs231n.github.io/neural-networks-3/\n rel_err = np.abs(a-b) / max(np.abs(a), np.abs(b))\n return rel_err\n\ndef test_node_backward(node, init_vals, delta=1e-7):\n\n for parent_node in node.get_predecessors():\n parent_node.out = init_vals[parent_node.node_name]\n\n out = graph.forward_graph(node) \n d_out = np.random.standard_normal(out.shape) # simulate a random derivative w.r.t. out\n node.d_out = d_out \n node.backward() # sets partials in parent.d_node for each parent\n\n # Numerically estimate partial derivative of J w.r.t. each entry of each parent_node.out,\n # Assuming partial of J w.r.t. node output is given by node.d_out.\n\n overall_max_rel_err = -1\n for parent in node.get_predecessors():\n parent_out = np.copy(parent.out) # save original parent.out\n it = np.nditer(parent_out, flags=['multi_index'])\n max_rel_err = -1\n while not it.finished:\n parent.out[it.multi_index] = parent_out[it.multi_index] + delta\n out_plus_delta = node.forward()\n parent.out[it.multi_index] = parent_out[it.multi_index] - delta\n out_minus_delta = node.forward()\n parent.out[it.multi_index] = parent_out[it.multi_index] # set it back to how it \n local_partial_est = (out_plus_delta - out_minus_delta) / (2.0 * delta)\n\n partial_est = np.sum(d_out * local_partial_est) # this is the chain rule\n partial_backward = parent.d_out[it.multi_index] # partial as computed by backward\n #pdb.set_trace()\n rel_err = relative_error(partial_est, partial_backward)\n max_rel_err = max(max_rel_err, rel_err)\n it.iternext()\n logging.debug(\"(Node %s) Max rel error for partial deriv w.r.t. %s is %s.\" % (node.node_name, parent.node_name, max_rel_err))\n overall_max_rel_err = max(max_rel_err, overall_max_rel_err)\n return overall_max_rel_err\n\n\ndef test_ComputationGraphFunction(graph, input_vals, outcome_vals, parameter_vals, delta=1e-7):\n graph.set_parameters(parameter_vals)\n _, gradients = graph.get_gradients(input_vals, outcome_vals)\n\n overall_max_rel_err = -1\n for param in parameter_vals:\n val = parameter_vals[param]\n it = np.nditer(val, flags=['multi_index'])\n max_rel_err = -1\n while not it.finished:\n step = np.zeros(val.shape)\n step[it.multi_index] = delta\n graph.increment_parameters({param:step})\n obj_plus_delta = graph.get_objective(input_vals, outcome_vals)\n step[it.multi_index] = -2 * delta #so a step of -delta from original value\n graph.increment_parameters({param:step})\n obj_minus_delta = graph.get_objective(input_vals, outcome_vals)\n step[it.multi_index] = delta #bring it back to original value\n graph.increment_parameters({param:step})\n\n partial_est = (obj_plus_delta - obj_minus_delta) / (2.0 * delta)\n partial_backprop = gradients[param][it.multi_index] # partial from ComputationGraphFunction\n rel_err = relative_error(partial_est, partial_backprop)\n max_rel_err = max(max_rel_err, rel_err)\n it.iternext()\n logging.debug(\"(Parameter %s) Max rel error for partial deriv %s.\" % (param, max_rel_err))\n overall_max_rel_err = max(overall_max_rel_err, max_rel_err)\n return overall_max_rel_err\n\n"
] |
[
[
"numpy.nditer",
"numpy.abs",
"numpy.random.standard_normal",
"numpy.copy",
"numpy.zeros",
"numpy.sum"
]
] |
jonandergomez/teaa_lab
|
[
"a5acf38b683b1d6feb1ff7e12dddfbc6352baf5e"
] |
[
"portal.dsic/examples/python/KNN_Classifier.py"
] |
[
"\"\"\"\n Author: Jon Ander Gomez Adrian ([email protected], http://personales.upv.es/jon)\n Version: 1.0\n Date: October 2021\n Universitat Politecnica de Valencia\n Technical University of Valencia TU.VLC\n\n\"\"\"\n\nimport sys\nimport time\nimport math\nimport numpy\n\ntry:\n from pyspark.rdd import RDD\nexcept:\n RDD = None\n\nfrom BallTree import BallTree\n\nclass KNN_Classifier:\n \"\"\"\n This class implements a classifier based on K-Nearest Neighbours.\n\n The purpose is to classify each sample according to the class with majority within the set of K-Nearest samples.\n\n \"\"\"\n \n def __init__(self, K = 5, num_classes = 2):\n self.num_classes = num_classes\n self.K = K\n self.balltree = None\n # ------------------------------------------------------------------------------\n\n def fit(self, X, y, min_samples_to_split = None):\n if RDD is not None and (isinstance(X, RDD) or isinstance(y, RDD)):\n raise Exception('RDD objects not supported for training')\n\n self.balltree = BallTree(min_samples_to_split = min_samples_to_split)\n self.balltree.fit(X, y)\n #\n return self\n # ------------------------------------------------------------------------------\n\n # ------------------------------------------------------------------------------\n def predict(self, sample):\n #\n if type(sample) == list or type(sample) == numpy.ndarray and len(sample.shape) >= 2:\n probs = self.predict_probs(sample)\n return probs.argmax(axis = 1)\n\n elif type(sample) == numpy.ndarray and len(sample.shape) == 1:\n probs = self.predict_probs(sample)\n return probs.argmax()\n\n elif RDD is not None and isinstance(sample, RDD):\n probs = sample.map(lambda t: (t[0], self.compute_probs_one_sample(t[1])))\n return probs.map(lambda t: (t[0], t[1].argmax())).collect()\n\n else:\n raise Exception(f'Not accepted data type: {type(sample)}')\n # ------------------------------------------------------------------------------\n\n def compute_probs_one_sample(self, x):\n if self.balltree is not None:\n if len(x.shape) == 2:\n y = numpy.zeros(self.num_classes)\n for n in range(len(x)):\n knn = self.balltree.get_knn(x[n], self.K)\n if len(knn) > self.K: knn = knn[:self.K]\n for t in knn: y[t[0]] += 1\n elif len(x.shape) == 1:\n knn = self.balltree.get_knn(x, self.K)\n if len(knn) > self.K: knn = knn[:self.K]\n y = numpy.zeros(self.num_classes)\n for t in knn: y[t[0]] += 1\n else:\n raise Exception(f'Unexpected shape of a sample {x.shape}')\n return y / (1.0e-6 + y.sum())\n\n def predict_probs(self, sample):\n #\n if type(sample) == list or type(sample) == numpy.ndarray and len(sample.shape) >= 2:\n densities = list()\n i = 1\n for x in sample:\n densities.append(self.compute_probs_one_sample(x))\n print(\"predicted %10d samples\" % i, end = '\\r')\n i += 1\n #\n return numpy.array(densities)\n\n elif type(sample) == numpy.ndarray and len(sample.shape) == 1:\n return self.compute_probs_one_sample(sample)\n\n elif RDD is not None and isinstance(sample, RDD):\n return sample.map(lambda t: (t[0], self.compute_probs_one_sample(t[1]))).collect()\n\n else:\n raise Exception(f'Not accepted data type: {type(sample)}')\n # ------------------------------------------------------------------------------\n"
] |
[
[
"numpy.array",
"numpy.zeros"
]
] |
deibraz-free/dsp_effects
|
[
"1ca1f1f400ea276755ede54d0b2d2a5d12cf61b7"
] |
[
"main.py"
] |
[
"'''\n\tCreated by Deividas Brazauskas 2020\n\n\t# Read in WAV file into Python Class\n\tsound1 = AudioProcessing('input.wav')\n\n\t# Set the speed of the audio\n\tsound1.set_audio_speed(0.5)\n\n\t# Set the pitch of the audio\n\tsound1.set_audio_pitch(2)\n\n\t# Reverse the content of the audio\n\tsound1.set_reverse()\n\n\t# Add an echo to the audio\n\tsound1.set_echo(1)\n\n\t# Applies a bandpass filter between the (<low>, <high>) range of frequencies\n\tsound.set_bandpass(50, 2600)\n\n\t# Save the resulting processed audio data into a file\n\tsound1.save_to_file('out.wav')\n'''\n\nimport sys, wave\nimport numpy as np\nfrom numpy import array, int16\nfrom scipy.signal import lfilter, butter\nfrom scipy.io.wavfile import read,write\nfrom scipy import signal\nimport random\n\nclass AudioProcessing(object):\n\t__slots__ = ('audio_data', 'sample_freq')\n\tdef __init__(self, input_audio_path):\n\t\tself.sample_freq, self.audio_data = read(input_audio_path)\n\t\t# self.audio_data = AudioProcessing.convert_to_mono_audio(self.audio_data)\n\n\tdef save_to_file(self, output_path):\n\t\t'''Writes a WAV file representation of the processed audio data'''\n\t\twrite(output_path, self.sample_freq, array(self.audio_data, dtype = int16))\n\n\tdef set_audio_speed(self, speed_factor):\n\t\t'''Sets the speed of the audio by a floating-point factor'''\n\t\tsound_index = np.round(np.arange(0, len(self.audio_data), speed_factor))\n\t\tself.audio_data = self.audio_data[sound_index[sound_index < len(self.audio_data)].astype(int)]\n\n\tdef set_echo(self, delay):\n\t\t'''Applies an echo that is 0...<input audio duration in seconds> seconds from the beginning'''\n\t\toutput_audio = np.zeros(len(self.audio_data))\n\t\toutput_delay = delay * self.sample_freq\n\n\t\tfor count, e in enumerate(self.audio_data):\n\t\t\toutput_audio[count] = e + self.audio_data[count - int(output_delay)]\n\n\t\tself.audio_data = output_audio\n\n\tdef set_volume(self, level):\n\t\t'''Sets the overall volume of the data via floating-point factor'''\n\t\toutput_audio = np.zeros(len(self.audio_data))\n\n\t\tfor count, e in enumerate(self.audio_data):\n\t\t\toutput_audio[count] = (e * level)\n\n\t\tself.audio_data = output_audio\n\n\tdef set_reverse(self):\n\t\t'''Reverses the audio'''\n\t\tself.audio_data = self.audio_data[::-1]\n\n\tdef set_audio_pitch(self, n, window_size=2**13, h=2**11):\n\t\t'''Sets the pitch of the audio to a certain threshold'''\n\t\tfactor = 2 ** (1.0 * n / 12.0)\n\t\tself._set_stretch(1.0 / factor, window_size, h)\n\t\tself.audio_data = self.audio_data[window_size:]\n\t\tself.set_audio_speed(factor)\n\n\tdef _set_stretch(self, factor, window_size, h):\n\t\tphase = np.zeros(window_size)\n\t\thanning_window = np.hanning(window_size)\n\t\tresult = np.zeros(int(len(self.audio_data) / factor + window_size))\n\n\t\tfor i in np.arange(0, len(self.audio_data) - (window_size + h), h*factor):\n\t\t\t# Two potentially overlapping subarrays\n\t\t\ta1 = self.audio_data[int(i): int(i + window_size)]\n\t\t\ta2 = self.audio_data[int(i + h): int(i + window_size + h)]\n\n\t\t\t# The spectra of these arrays\n\t\t\ts1 = np.fft.fft(hanning_window * a1)\n\t\t\ts2 = np.fft.fft(hanning_window * a2)\n\n\t\t\t# Rephase all frequencies\n\t\t\tphase = (phase + np.angle(s2/s1)) % 2*np.pi\n\n\t\t\ta2_rephased = np.fft.ifft(np.abs(s2)*np.exp(1j*phase))\n\t\t\ti2 = int(i / factor)\n\t\t\tresult[i2: i2 + window_size] += hanning_window*a2_rephased.real\n\n\t\t# normalize (16bit)\n\t\tresult = ((2 ** (16 - 4)) * result/result.max())\n\t\tself.audio_data = result.astype('int16')\n\n\tdef set_lowpass(self, cutoff_low, order=5):\n\t\t'''Applies a low pass filter'''\n\t\tnyquist = self.sample_freq / 2.0\n\t\tcutoff = cutoff_low / nyquist\n\t\tx, y = signal.butter(order, cutoff, btype='lowpass', analog=False)\n\t\tself.audio_data = signal.filtfilt(x, y, self.audio_data)\n\n\tdef set_highpass(self, cutoff_high, order=5):\n\t\t'''Applies a high pass filter'''\n\t\tnyquist = self.sample_freq / 2.0\n\t\tcutoff = cutoff_high / nyquist\n\t\tx, y = signal.butter(order, cutoff, btype='highpass', analog=False)\n\t\tself.audio_data = signal.filtfilt(x, y, self.audio_data)\n\n\tdef set_bandpass(self, cutoff_low, cutoff_high, order=5):\n\t\t'''Applies a band pass filter'''\n\t\tcutoff = np.zeros(2)\n\t\tnyquist = self.sample_freq / 2.0\n\t\tcutoff[0] = cutoff_low / nyquist\n\t\tcutoff[1] = cutoff_high / nyquist\n\t\tx, y = signal.butter(order, cutoff, btype='bandpass', analog=False)\n\t\tself.audio_data = signal.filtfilt(x, y, self.audio_data)\n\n\t@staticmethod\n\tdef convert_to_mono_audio(input_audio):\n\t\t'''Returns a numpy array that represents the mono version of a stereo input'''\n\t\toutput_audio = []\n\t\ttemp_audio = input_audio.astype(float)\n\n\t\tfor e in temp_audio:\n\t\t\toutput_audio.append((e[0] / 2) + (e[1] / 2))\n\n\t\treturn np.array(output_audio, dtype = 'int16')\n\n# Example\n# applyDSP_worsenRand(\"1.wav\", \"out.wav\")\ndef applyDSP_worsenRand(file_in, file_out):\n\tsound1 = AudioProcessing(file_in)\n\n\tvol = 1-random.randint(-5, 5)/100\n\techo = random.randint(3, 5)/100\n\tspeed = 1-random.randint(5, 5)/100\n\n\tsound1.set_volume(vol)\n\tif random.randint(0, 1) == 1:\n\t\tsound1.set_echo(echo) # can cause audio crackling\n\tsound1.set_audio_speed(speed)\n\n\tband_1 = random.randint(50, 200)\n\tband_2 = random.randint(3000, 10000)\n\thighpass = random.randint(10, 350)\n\n\tsound1.set_highpass(highpass)\n\tsound1.set_bandpass(band_1, band_2)\n\n\tsound1.save_to_file(file_out)\n"
] |
[
[
"scipy.signal.filtfilt",
"numpy.abs",
"numpy.fft.fft",
"scipy.signal.butter",
"numpy.hanning",
"numpy.exp",
"numpy.angle",
"numpy.array",
"numpy.zeros",
"scipy.io.wavfile.read"
]
] |
KshitijKarthick/animewreck
|
[
"494ac6ae3eb21c6c7641a51e368dc72b5d1279c5"
] |
[
"server/constants.py"
] |
[
"import torch\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nrandom_seed = 42\n\nnum_genres = 44\nmin_slice = 6\nmax_slice = 11\npast_anime_length = 10\nnum_users, num_anime = (108711, 6668)\ntrain_frac = 0.8\nencoded_values_for_rating = 11\nbatch_size = 512\nnum_workers_dataloader = 0\n\n\ngenre_embedding_size = 20\nlstm_hidden_dim = 256\nbidirectional = True\nlstm_layers = 1\n\npretrained_learner_fname = (\n \"lstm_anime_genre_learner_len_min5_max10_6rep_8cyc_1.785-1.752\"\n)\npretrained_anime_genre_embeddings_file = (\n \"model_resources/anime_with_genre_embeddings.wts\"\n)\nsliced_user_grouped_rating_file = (\n \"model_resources/ordered_sliced_user_grouped_rating_minlen5_maxlen10_rep6_small.pkl\"\n)\n"
] |
[
[
"torch.cuda.is_available"
]
] |
Sin-tel/spheremesh
|
[
"c9a8e14a8dbf2d8e6e1cf46eaae8b25492cd36ea"
] |
[
"example_remesh.py"
] |
[
"import spheremesh as sh\nimport igl\nimport numpy as np\n\nfilename = \"data/cell.obj\"\nl_max = 20\n\norig_v, faces = igl.read_triangle_mesh(filename)\n\n\nsphere_verts = sh.conformal_flow(orig_v, faces)\nsphere_verts = sh.mobius_center(orig_v,sphere_verts,faces)\n\norig_v, sphere_verts = sh.canonical_rotation(orig_v, sphere_verts, faces)\n\nweights, Y_mat = sh.IRF(orig_v, sphere_verts, faces, l_max)\n\nreconstruct = Y_mat.dot(weights)\n\n## construct icosphere mesh data\nico_v, ico_f = igl.read_triangle_mesh(\"spheremesh/icosphere/icosphere.obj\")\nico_v = sh.project_sphere(ico_v)\ntheta = np.arccos(ico_v[:,2])\nphi = np.arctan2(ico_v[:,1],ico_v[:,0])\n\nY_mat2 = []\n\n## make sh matrix\nfor l in range(0, l_max):\n\tfor m in range(-l,l+1):\n\t\ty = sh.sph_real(l, m, phi, theta)\n\t\tY_mat2.append(y)\n\nY_mat2 = np.vstack(Y_mat2).T\n\nico_reconstruct = Y_mat2.dot(weights)\n\n\n## plot\np = sh.plot.new()\nsh.plot.mesh(p, reconstruct, faces)\n\ndef update(value):\n\tglobal sphere_verts, reconstruct, faces, color, p\n\n\tif value:\n\t\tsh.plot.mesh(p,ico_reconstruct, ico_f)\n\telse:\n\t\tsh.plot.mesh(p,reconstruct, faces)\n\t\t\n\treturn\n\np.add_checkbox_button_widget(update)\np.show()"
] |
[
[
"numpy.arctan2",
"numpy.arccos",
"numpy.vstack"
]
] |
CameronKing/sympy
|
[
"3295b02c617a10ea8db0a070356cc0ba5a3b5121"
] |
[
"sympy/core/sympify.py"
] |
[
"\"\"\"sympify -- convert objects SymPy internal format\"\"\"\n\nfrom __future__ import print_function, division\n\nfrom inspect import getmro\n\nfrom .core import all_classes as sympy_classes\nfrom .compatibility import iterable, string_types, range\nfrom .evaluate import global_evaluate\n\n\nclass SympifyError(ValueError):\n def __init__(self, expr, base_exc=None):\n self.expr = expr\n self.base_exc = base_exc\n\n def __str__(self):\n if self.base_exc is None:\n return \"SympifyError: %r\" % (self.expr,)\n\n return (\"Sympify of expression '%s' failed, because of exception being \"\n \"raised:\\n%s: %s\" % (self.expr, self.base_exc.__class__.__name__,\n str(self.base_exc)))\n\nconverter = {} # See sympify docstring.\n\nclass CantSympify(object):\n \"\"\"\n Mix in this trait to a class to disallow sympification of its instances.\n\n Examples\n ========\n\n >>> from sympy.core.sympify import sympify, CantSympify\n\n >>> class Something(dict):\n ... pass\n ...\n >>> sympify(Something())\n {}\n\n >>> class Something(dict, CantSympify):\n ... pass\n ...\n >>> sympify(Something())\n Traceback (most recent call last):\n ...\n SympifyError: SympifyError: {}\n\n \"\"\"\n pass\n\n\ndef _convert_numpy_types(a, **sympify_args):\n \"\"\"\n Converts a numpy datatype input to an appropriate SymPy type.\n \"\"\"\n import numpy as np\n if not isinstance(a, np.floating):\n if np.iscomplex(a):\n return converter[complex](a.item())\n else:\n return sympify(a.item(), **sympify_args)\n else:\n try:\n from sympy.core.numbers import Float\n prec = np.finfo(a).nmant + 1\n # E.g. double precision means prec=53 but nmant=52\n # Leading bit of mantissa is always 1, so is not stored\n a = str(list(np.reshape(np.asarray(a),\n (1, np.size(a)))[0]))[1:-1]\n return Float(a, precision=prec)\n except NotImplementedError:\n raise SympifyError('Translation for numpy float : %s '\n 'is not implemented' % a)\n\n\ndef sympify(a, locals=None, convert_xor=True, strict=False, rational=False,\n evaluate=None):\n \"\"\"Converts an arbitrary expression to a type that can be used inside SymPy.\n\n For example, it will convert Python ints into instances of sympy.Integer,\n floats into instances of sympy.Float, etc. It is also able to coerce symbolic\n expressions which inherit from Basic. This can be useful in cooperation\n with SAGE.\n\n It currently accepts as arguments:\n - any object defined in SymPy\n - standard numeric python types: int, long, float, Decimal\n - strings (like \"0.09\" or \"2e-19\")\n - booleans, including ``None`` (will leave ``None`` unchanged)\n - dict, lists, sets or tuples containing any of the above\n\n .. warning::\n Note that this function uses ``eval``, and thus shouldn't be used on\n unsanitized input.\n\n If the argument is already a type that SymPy understands, it will do\n nothing but return that value. This can be used at the beginning of a\n function to ensure you are working with the correct type.\n\n >>> from sympy import sympify\n\n >>> sympify(2).is_integer\n True\n >>> sympify(2).is_real\n True\n\n >>> sympify(2.0).is_real\n True\n >>> sympify(\"2.0\").is_real\n True\n >>> sympify(\"2e-45\").is_real\n True\n\n If the expression could not be converted, a SympifyError is raised.\n\n >>> sympify(\"x***2\")\n Traceback (most recent call last):\n ...\n SympifyError: SympifyError: \"could not parse u'x***2'\"\n\n Locals\n ------\n\n The sympification happens with access to everything that is loaded\n by ``from sympy import *``; anything used in a string that is not\n defined by that import will be converted to a symbol. In the following,\n the ``bitcount`` function is treated as a symbol and the ``O`` is\n interpreted as the Order object (used with series) and it raises\n an error when used improperly:\n\n >>> s = 'bitcount(42)'\n >>> sympify(s)\n bitcount(42)\n >>> sympify(\"O(x)\")\n O(x)\n >>> sympify(\"O + 1\")\n Traceback (most recent call last):\n ...\n TypeError: unbound method...\n\n In order to have ``bitcount`` be recognized it can be imported into a\n namespace dictionary and passed as locals:\n\n >>> from sympy.core.compatibility import exec_\n >>> ns = {}\n >>> exec_('from sympy.core.evalf import bitcount', ns)\n >>> sympify(s, locals=ns)\n 6\n\n In order to have the ``O`` interpreted as a Symbol, identify it as such\n in the namespace dictionary. This can be done in a variety of ways; all\n three of the following are possibilities:\n\n >>> from sympy import Symbol\n >>> ns[\"O\"] = Symbol(\"O\") # method 1\n >>> exec_('from sympy.abc import O', ns) # method 2\n >>> ns.update(dict(O=Symbol(\"O\"))) # method 3\n >>> sympify(\"O + 1\", locals=ns)\n O + 1\n\n If you want *all* single-letter and Greek-letter variables to be symbols\n then you can use the clashing-symbols dictionaries that have been defined\n there as private variables: _clash1 (single-letter variables), _clash2\n (the multi-letter Greek names) or _clash (both single and multi-letter\n names that are defined in abc).\n\n >>> from sympy.abc import _clash1\n >>> _clash1\n {'C': C, 'E': E, 'I': I, 'N': N, 'O': O, 'Q': Q, 'S': S}\n >>> sympify('I & Q', _clash1)\n I & Q\n\n Strict\n ------\n\n If the option ``strict`` is set to ``True``, only the types for which an\n explicit conversion has been defined are converted. In the other\n cases, a SympifyError is raised.\n\n >>> print(sympify(None))\n None\n >>> sympify(None, strict=True)\n Traceback (most recent call last):\n ...\n SympifyError: SympifyError: None\n\n Evaluation\n ----------\n\n If the option ``evaluate`` is set to ``False``, then arithmetic and\n operators will be converted into their SymPy equivalents and the\n ``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will\n be denested first. This is done via an AST transformation that replaces\n operators with their SymPy equivalents, so if an operand redefines any\n of those operations, the redefined operators will not be used.\n\n >>> sympify('2**2 / 3 + 5')\n 19/3\n >>> sympify('2**2 / 3 + 5', evaluate=False)\n 2**2/3 + 5\n\n Extending\n ---------\n\n To extend ``sympify`` to convert custom objects (not derived from ``Basic``),\n just define a ``_sympy_`` method to your class. You can do that even to\n classes that you do not own by subclassing or adding the method at runtime.\n\n >>> from sympy import Matrix\n >>> class MyList1(object):\n ... def __iter__(self):\n ... yield 1\n ... yield 2\n ... return\n ... def __getitem__(self, i): return list(self)[i]\n ... def _sympy_(self): return Matrix(self)\n >>> sympify(MyList1())\n Matrix([\n [1],\n [2]])\n\n If you do not have control over the class definition you could also use the\n ``converter`` global dictionary. The key is the class and the value is a\n function that takes a single argument and returns the desired SymPy\n object, e.g. ``converter[MyList] = lambda x: Matrix(x)``.\n\n >>> class MyList2(object): # XXX Do not do this if you control the class!\n ... def __iter__(self): # Use _sympy_!\n ... yield 1\n ... yield 2\n ... return\n ... def __getitem__(self, i): return list(self)[i]\n >>> from sympy.core.sympify import converter\n >>> converter[MyList2] = lambda x: Matrix(x)\n >>> sympify(MyList2())\n Matrix([\n [1],\n [2]])\n\n Notes\n =====\n\n The keywords ``rational`` and ``convert_xor`` are only used\n when the input is a string.\n\n Sometimes autosimplification during sympification results in expressions\n that are very different in structure than what was entered. Until such\n autosimplification is no longer done, the ``kernS`` function might be of\n some use. In the example below you can see how an expression reduces to\n -1 by autosimplification, but does not do so when ``kernS`` is used.\n\n >>> from sympy.core.sympify import kernS\n >>> from sympy.abc import x\n >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1\n -1\n >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'\n >>> sympify(s)\n -1\n >>> kernS(s)\n -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1\n\n \"\"\"\n try:\n if a in sympy_classes:\n return a\n except TypeError: # Type of a is unhashable\n pass\n cls = getattr(a, \"__class__\", None)\n if cls is None:\n cls = type(a) # Probably an old-style class\n if cls in sympy_classes:\n return a\n\n if isinstance(a, CantSympify):\n raise SympifyError(a)\n\n try:\n return converter[cls](a)\n except KeyError:\n for superclass in getmro(cls):\n try:\n return converter[superclass](a)\n except KeyError:\n continue\n\n if cls is type(None):\n if strict:\n raise SympifyError(a)\n else:\n return a\n\n if evaluate is None:\n if global_evaluate[0] is False:\n evaluate = global_evaluate[0]\n else:\n evaluate = True\n\n # Support for basic numpy datatypes\n # Note that this check exists to avoid importing NumPy when not necessary\n if type(a).__module__ == 'numpy':\n import numpy as np\n if np.isscalar(a):\n return _convert_numpy_types(a, locals=locals,\n convert_xor=convert_xor, strict=strict, rational=rational,\n evaluate=evaluate)\n\n _sympy_ = getattr(a, \"_sympy_\", None)\n if _sympy_ is not None:\n try:\n return a._sympy_()\n # XXX: Catches AttributeError: 'SympyConverter' object has no\n # attribute 'tuple'\n # This is probably a bug somewhere but for now we catch it here.\n except AttributeError:\n pass\n\n if not strict:\n # Put numpy array conversion _before_ float/int, see\n # <https://github.com/sympy/sympy/issues/13924>.\n flat = getattr(a, \"flat\", None)\n if flat is not None:\n shape = getattr(a, \"shape\", None)\n if shape is not None:\n from ..tensor.array import Array\n return Array(a.flat, a.shape) # works with e.g. NumPy arrays\n\n if not isinstance(a, string_types):\n for coerce in (float, int):\n try:\n coerced = coerce(a)\n except (TypeError, ValueError):\n continue\n # XXX: AttributeError only needed here for Py2\n except AttributeError:\n continue\n try:\n return sympify(coerced)\n except SympifyError:\n continue\n\n if strict:\n raise SympifyError(a)\n\n if iterable(a):\n try:\n return type(a)([sympify(x, locals=locals, convert_xor=convert_xor,\n rational=rational) for x in a])\n except TypeError:\n # Not all iterables are rebuildable with their type.\n pass\n if isinstance(a, dict):\n try:\n return type(a)([sympify(x, locals=locals, convert_xor=convert_xor,\n rational=rational) for x in a.items()])\n except TypeError:\n # Not all iterables are rebuildable with their type.\n pass\n\n # At this point we were given an arbitrary expression\n # which does not inherit from Basic and doesn't implement\n # _sympy_ (which is a canonical and robust way to convert\n # anything to SymPy expression).\n #\n # As a last chance, we try to take \"a\"'s normal form via unicode()\n # and try to parse it. If it fails, then we have no luck and\n # return an exception\n try:\n from .compatibility import unicode\n a = unicode(a)\n except Exception as exc:\n raise SympifyError(a, exc)\n\n from sympy.parsing.sympy_parser import (parse_expr, TokenError,\n standard_transformations)\n from sympy.parsing.sympy_parser import convert_xor as t_convert_xor\n from sympy.parsing.sympy_parser import rationalize as t_rationalize\n\n transformations = standard_transformations\n\n if rational:\n transformations += (t_rationalize,)\n if convert_xor:\n transformations += (t_convert_xor,)\n\n try:\n a = a.replace('\\n', '')\n expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)\n except (TokenError, SyntaxError) as exc:\n raise SympifyError('could not parse %r' % a, exc)\n\n return expr\n\n\ndef _sympify(a):\n \"\"\"\n Short version of sympify for internal usage for __add__ and __eq__ methods\n where it is ok to allow some things (like Python integers and floats) in\n the expression. This excludes things (like strings) that are unwise to\n allow into such an expression.\n\n >>> from sympy import Integer\n >>> Integer(1) == 1\n True\n\n >>> Integer(1) == '1'\n False\n\n >>> from sympy.abc import x\n >>> x + 1\n x + 1\n\n >>> x + '1'\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'\n\n see: sympify\n\n \"\"\"\n return sympify(a, strict=True)\n\n\ndef kernS(s):\n \"\"\"Use a hack to try keep autosimplification from distributing a\n a number into an Add; this modification doesn't\n prevent the 2-arg Mul from becoming an Add, however.\n\n Examples\n ========\n\n >>> from sympy.core.sympify import kernS\n >>> from sympy.abc import x, y, z\n\n The 2-arg Mul distributes a number (or minus sign) across the terms\n of an expression, but kernS will prevent that:\n\n >>> 2*(x + y), -(x + 1)\n (2*x + 2*y, -x - 1)\n >>> kernS('2*(x + y)')\n 2*(x + y)\n >>> kernS('-(x + 1)')\n -(x + 1)\n\n If use of the hack fails, the un-hacked string will be passed to sympify...\n and you get what you get.\n\n XXX This hack should not be necessary once issue 4596 has been resolved.\n \"\"\"\n import string\n from random import choice\n from sympy.core.symbol import Symbol\n hit = False\n quoted = '\"' in s or \"'\" in s\n if '(' in s and not quoted:\n if s.count('(') != s.count(\")\"):\n raise SympifyError('unmatched left parenthesis')\n\n # strip all space from s\n s = ''.join(s.split())\n olds = s\n # now use space to represent a symbol that\n # will\n # step 1. turn potential 2-arg Muls into 3-arg versions\n # 1a. *( -> * *(\n s = s.replace('*(', '* *(')\n # 1b. close up exponentials\n s = s.replace('** *', '**')\n # 2. handle the implied multiplication of a negated\n # parenthesized expression in two steps\n # 2a: -(...) --> -( *(...)\n target = '-( *('\n s = s.replace('-(', target)\n # 2b: double the matching closing parenthesis\n # -( *(...) --> -( *(...))\n i = nest = 0\n assert target.endswith('(') # assumption below\n while True:\n j = s.find(target, i)\n if j == -1:\n break\n j += len(target) - 1\n for j in range(j, len(s)):\n if s[j] == \"(\":\n nest += 1\n elif s[j] == \")\":\n nest -= 1\n if nest == 0:\n break\n s = s[:j] + \")\" + s[j:]\n i = j + 2 # the first char after 2nd )\n if ' ' in s:\n # get a unique kern\n kern = '_'\n while kern in s:\n kern += choice(string.ascii_letters + string.digits)\n s = s.replace(' ', kern)\n hit = kern in s\n\n for i in range(2):\n try:\n expr = sympify(s)\n break\n except: # the kern might cause unknown errors, so use bare except\n if hit:\n s = olds # maybe it didn't like the kern; use un-kerned s\n hit = False\n continue\n expr = sympify(s) # let original error raise\n\n if not hit:\n return expr\n\n rep = {Symbol(kern): 1}\n def _clear(expr):\n if isinstance(expr, (list, tuple, set)):\n return type(expr)([_clear(e) for e in expr])\n if hasattr(expr, 'subs'):\n return expr.subs(rep, hack2=True)\n return expr\n expr = _clear(expr)\n # hope that kern is not there anymore\n return expr\n"
] |
[
[
"numpy.asarray",
"numpy.finfo",
"numpy.size",
"numpy.isscalar",
"numpy.iscomplex"
]
] |
diptanshumittal/FCO-ICML21
|
[
"4a9f4456cb7e1c3a0646c9b91a0926ba87fc6a48"
] |
[
"optimization/bin_lr/federated_bin_lr.py"
] |
[
"# Copyright 2021, Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Federated Binary Logistic Regression on Synthetic Dataset\"\"\"\n\nimport functools\nfrom typing import Callable, Optional\n\nfrom absl import flags\nfrom absl import logging\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom utils import training_loop\nfrom utils import training_utils\nfrom utils.datasets import synthetic_dataset\nfrom utils.models import bin_lr_models\n\nFLAGS = flags.FLAGS\n\ndef run_federated(\n iterative_process_builder: Callable[..., tff.templates.IterativeProcess],\n client_epochs_per_round: int,\n client_batch_size: int,\n clients_per_round: int,\n client_sample_pow: Optional[float] = 0.0,\n max_batches_per_client: Optional[int] = -1,\n client_datasets_random_seed: Optional[int] = None,\n total_rounds: Optional[int] = 1500,\n experiment_name: Optional[str] = 'federated_bin_lr',\n root_output_dir: Optional[str] = '/tmp/fed_opt',\n max_eval_batches: Optional[int] = None,\n dataset_name: Optional[str] = None,\n num_attr: Optional[int] = None,\n **kwargs):\n \"\"\"Runs an iterative process on the EMNIST character recognition task.\n\n This method will load and pre-process dataset and construct a model used for\n the task. It then uses `iterative_process_builder` to create an iterative\n process that it applies to the task, using\n `federated_research.utils.training_loop`.\n\n We assume that the iterative process has the following functional type\n signatures:\n\n * `initialize`: `( -> S@SERVER)` where `S` represents the server state.\n * `next`: `<S@SERVER, {B*}@CLIENTS> -> <S@SERVER, T@SERVER>` where `S`\n represents the server state, `{B*}` represents the client datasets,\n and `T` represents a python `Mapping` object.\n\n Moreover, the server state must have an attribute `model` of type\n `tff.learning.ModelWeights`.\n\n Args:\n iterative_process_builder: A function that accepts a no-arg `model_fn`, and\n returns a `tff.templates.IterativeProcess`. The `model_fn` must return a\n `tff.learning.Model`.\n client_epochs_per_round: An integer representing the number of epochs of\n training performed per client in each training round.\n client_batch_size: An integer representing the batch size used on clients.\n clients_per_round: An integer representing the number of clients\n participating in each round.\n max_batches_per_client: An optional int specifying the number of batches\n taken by each client at each round. If `-1`, the entire client dataset is\n used.\n client_datasets_random_seed: An optional int used to seed which clients are\n sampled at each round. If `None`, no seed is used.\n model: A string specifying the model used for character recognition.\n Can be one of `cnn` and `2nn`, corresponding to a CNN model and a densely\n connected 2-layer model (respectively).\n total_rounds: The number of federated training rounds.\n experiment_name: The name of the experiment being run. This will be appended\n to the `root_output_dir` for purposes of writing outputs.\n root_output_dir: The name of the root output directory for writing\n experiment outputs.\n max_eval_batches: If set to a positive integer, evaluation datasets are\n capped to at most that many batches. If set to None or a nonpositive\n integer, the full evaluation datasets are used.\n **kwargs: Additional arguments configuring the training loop. For details\n on supported arguments, see\n `federated_research/utils/training_utils.py`.\n \"\"\"\n train_ds, test_ds = synthetic_dataset.get_synthetic_datasets(\n dataset_name,\n client_batch_size,\n client_epochs_per_round,\n max_batches_per_client=max_batches_per_client,\n )\n\n centralized_train_ds, test_ds = \\\n synthetic_dataset.get_centralized_synthetic_datasets(\n dataset_name=dataset_name,\n train_batch_size=client_batch_size,\n max_test_batches=max_eval_batches,\n )\n\n input_spec = train_ds.element_type_structure\n\n model_builder = functools.partial(\n bin_lr_models.create_lr_model,\n num_attr=num_attr,\n )\n #\n\n loss_builder = tf.keras.losses.BinaryCrossentropy\n metrics_builder = lambda: [tf.keras.metrics.BinaryAccuracy()]\n\n def tff_model_fn() -> tff.learning.Model:\n return tff.learning.from_keras_model(\n keras_model=model_builder(),\n input_spec=input_spec,\n loss=loss_builder(),\n metrics=metrics_builder())\n\n training_process = iterative_process_builder(tff_model_fn)\n\n client_datasets_fn = training_utils.build_client_datasets_fn(\n train_dataset=train_ds,\n train_clients_per_round=clients_per_round,\n client_sample_pow=client_sample_pow,\n random_seed=client_datasets_random_seed)\n\n evaluate_fn = training_utils.build_evaluate_fn(\n eval_dataset=test_ds,\n model_builder=model_builder,\n loss_builder=loss_builder,\n metrics_builder=metrics_builder)\n\n train_evaluate_fn = training_utils.build_evaluate_fn(\n eval_dataset=centralized_train_ds,\n model_builder=model_builder,\n loss_builder=loss_builder,\n metrics_builder=metrics_builder)\n\n logging.info('Training model:')\n logging.info(model_builder().summary())\n\n training_loop.run(\n iterative_process=training_process,\n client_datasets_fn=client_datasets_fn,\n validation_fn=evaluate_fn,\n train_eval_fn=train_evaluate_fn,\n test_fn=evaluate_fn,\n total_rounds=total_rounds,\n experiment_name=experiment_name,\n root_output_dir=root_output_dir,\n **kwargs)\n"
] |
[
[
"tensorflow.keras.metrics.BinaryAccuracy"
]
] |
prolon-control-systems/dtu-smartlib-sensor-pi
|
[
"143f1d00cc0adadbdd0dc6ef3df3eaa0d27a7a68"
] |
[
"Python/grovepi.py"
] |
[
"#!/usr/bin/env python\n#\n# GrovePi Python library\n# v1.2.2\n#\n# This file provides the basic functions for using the GrovePi\n#\n# The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi\n#\n# Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi\n#\n'''\n## License\n\nThe MIT License (MIT)\n\nGrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.\nCopyright (C) 2017 Dexter Industries\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n'''\n# Initial Date: 13 Feb 2014\n# Last Updated: 11 Nov 2016\n# http://www.dexterindustries.com/\n# Author\tDate \t\tComments\n# Karan\t\t13 Feb 2014 \tInitial Authoring\n# \t\t\t11 Nov 2016\t\tI2C retries added for faster IO\n#\t\t\t\t\t\t\tDHT function updated to look for nan's\n\nimport sys\nimport time\nimport math\nimport struct\nimport numpy\n\ndebug = 0\n\nif sys.version_info<(3,0):\n\tp_version=2\nelse:\n\tp_version=3\n\nif sys.platform == 'uwp':\n\timport winrt_smbus as smbus\n\tbus = smbus.SMBus(1)\nelse:\n\timport smbus\n\timport RPi.GPIO as GPIO\n\trev = GPIO.RPI_REVISION\n\tif rev == 2 or rev == 3:\n\t\tbus = smbus.SMBus(1)\n\telse:\n\t\tbus = smbus.SMBus(0)\n\n# I2C Address of Arduino\naddress = 0x04\n\n# Command Format\n# digitalRead() command format header\ndRead_cmd = [1]\n# digitalWrite() command format header\ndWrite_cmd = [2]\n# analogRead() command format header\naRead_cmd = [3]\n# analogWrite() command format header\naWrite_cmd = [4]\n# pinMode() command format header\npMode_cmd = [5]\n# Ultrasonic read\nuRead_cmd = [7]\n# Get firmware version\nversion_cmd = [8]\n# Accelerometer (+/- 1.5g) read\nacc_xyz_cmd = [20]\n# RTC get time\nrtc_getTime_cmd = [30]\n# DHT Pro sensor temperature\ndht_temp_cmd = [40]\n\n# Grove LED Bar commands\n# Initialise\nledBarInit_cmd = [50]\n# Set orientation\nledBarOrient_cmd = [51]\n# Set level\nledBarLevel_cmd = [52]\n# Set single LED\nledBarSetOne_cmd = [53]\n# Toggle single LED\nledBarToggleOne_cmd = [54]\n# Set all LEDs\nledBarSet_cmd = [55]\n# Get current state\nledBarGet_cmd = [56]\n\n# Grove 4 Digit Display commands\n# Initialise\nfourDigitInit_cmd = [70]\n# Set brightness, not visible until next cmd\nfourDigitBrightness_cmd = [71]\n# Set numeric value without leading zeros\nfourDigitValue_cmd = [72]\n# Set numeric value with leading zeros\nfourDigitValueZeros_cmd = [73]\n# Set individual digit\nfourDigitIndividualDigit_cmd = [74]\n# Set individual leds of a segment\nfourDigitIndividualLeds_cmd = [75]\n# Set left and right values with colon\nfourDigitScore_cmd = [76]\n# Analog read for n seconds\nfourDigitAnalogRead_cmd = [77]\n# Entire display on\nfourDigitAllOn_cmd = [78]\n# Entire display off\nfourDigitAllOff_cmd = [79]\n\n# Grove Chainable RGB LED commands\n# Store color for later use\nstoreColor_cmd = [90]\n# Initialise\nchainableRgbLedInit_cmd = [91]\n# Initialise and test with a simple color\nchainableRgbLedTest_cmd = [92]\n# Set one or more leds to the stored color by pattern\nchainableRgbLedSetPattern_cmd = [93]\n# set one or more leds to the stored color by modulo\nchainableRgbLedSetModulo_cmd = [94]\n# sets leds similar to a bar graph, reversible\nchainableRgbLedSetLevel_cmd = [95]\n\n# Read the button from IR sensor\nir_read_cmd=[21]\n# Set pin for the IR reciever\nir_recv_pin_cmd=[22]\n\ndus_sensor_read_cmd=[10]\ndust_sensor_en_cmd=[14]\ndust_sensor_dis_cmd=[15]\nencoder_read_cmd=[11]\nencoder_en_cmd=[16]\nencoder_dis_cmd=[17]\nflow_read_cmd=[12]\nflow_disable_cmd=[13]\nflow_en_cmd=[18]\n# This allows us to be more specific about which commands contain unused bytes\nunused = 0\nretries = 10\n# Function declarations of the various functions used for encoding and sending\n# data from RPi to Arduino\n\n\n# Write I2C block\ndef write_i2c_block(address, block):\n\tfor i in range(retries):\n\t\ttry:\n\t\t\treturn bus.write_i2c_block_data(address, 1, block)\n\t\texcept IOError:\n\t\t\tif debug:\n\t\t\t\tprint (\"IOError\")\n\treturn -1\n\n# Read I2C byte\ndef read_i2c_byte(address):\n\tfor i in range(retries):\n\t\ttry:\n\t\t\treturn bus.read_byte(address)\n\t\texcept IOError:\n\t\t\tif debug:\n\t\t\t\tprint (\"IOError\")\n\treturn -1\n\n\n# Read I2C block\ndef read_i2c_block(address):\n\tfor i in range(retries):\n\t\ttry:\n\t\t\treturn bus.read_i2c_block_data(address, 1)\n\t\texcept IOError:\n\t\t\tif debug:\n\t\t\t\tprint (\"IOError\")\n\treturn -1\n\n# Arduino Digital Read\ndef digitalRead(pin):\n\twrite_i2c_block(address, dRead_cmd + [pin, unused, unused])\n\t# time.sleep(.1)\n\tn = read_i2c_byte(address)\n\treturn n\n\n# Arduino Digital Write\ndef digitalWrite(pin, value):\n\twrite_i2c_block(address, dWrite_cmd + [pin, value, unused])\n\treturn 1\n\n\n# Setting Up Pin mode on Arduino\ndef pinMode(pin, mode):\n\tif mode == \"OUTPUT\":\n\t\twrite_i2c_block(address, pMode_cmd + [pin, 1, unused])\n\telif mode == \"INPUT\":\n\t\twrite_i2c_block(address, pMode_cmd + [pin, 0, unused])\n\treturn 1\n\n\n# Read analog value from Pin\ndef analogRead(pin):\n\twrite_i2c_block(address, aRead_cmd + [pin, unused, unused])\n\tread_i2c_byte(address)\n\tnumber = read_i2c_block(address)\n\treturn number[1] * 256 + number[2]\n\n\n# Write PWM\ndef analogWrite(pin, value):\n\twrite_i2c_block(address, aWrite_cmd + [pin, value, unused])\n\treturn 1\n\n\n# Read temp in Celsius from Grove Temperature Sensor\ndef temp(pin, model = '1.0'):\n\t# each of the sensor revisions use different thermistors, each with their own B value constant\n\tif model == '1.2':\n\t\tbValue = 4250 # sensor v1.2 uses thermistor ??? (assuming NCP18WF104F03RC until SeeedStudio clarifies)\n\telif model == '1.1':\n\t\tbValue = 4250 # sensor v1.1 uses thermistor NCP18WF104F03RC\n\telse:\n\t\tbValue = 3975 # sensor v1.0 uses thermistor TTC3A103*39H\n\ta = analogRead(pin)\n\tresistance = (float)(1023 - a) * 10000 / a\n\tt = (float)(1 / (math.log(resistance / 10000) / bValue + 1 / 298.15) - 273.15)\n\treturn t\n\n\n# Read value from Grove Ultrasonic\ndef ultrasonicRead(pin):\n\twrite_i2c_block(address, uRead_cmd + [pin, unused, unused])\n\ttime.sleep(.06)\t#firmware has a time of 50ms so wait for more than that\n\tread_i2c_byte(address)\n\tnumber = read_i2c_block(address)\n\treturn (number[1] * 256 + number[2])\n\n\n# Read the firmware version\ndef version():\n\twrite_i2c_block(address, version_cmd + [unused, unused, unused])\n\ttime.sleep(.1)\n\tread_i2c_byte(address)\n\tnumber = read_i2c_block(address)\n\treturn \"%s.%s.%s\" % (number[1], number[2], number[3])\n\n\n# Read Grove Accelerometer (+/- 1.5g) XYZ value\ndef acc_xyz():\n\twrite_i2c_block(address, acc_xyz_cmd + [unused, unused, unused])\n\ttime.sleep(.1)\n\tread_i2c_byte(address)\n\tnumber = read_i2c_block(address)\n\tif number[1] > 32:\n\t\tnumber[1] = - (number[1] - 224)\n\tif number[2] > 32:\n\t\tnumber[2] = - (number[2] - 224)\n\tif number[3] > 32:\n\t\tnumber[3] = - (number[3] - 224)\n\treturn (number[1], number[2], number[3])\n\n\n# Read from Grove RTC\ndef rtc_getTime():\n\twrite_i2c_block(address, rtc_getTime_cmd + [unused, unused, unused])\n\ttime.sleep(.1)\n\tread_i2c_byte(address)\n\tnumber = read_i2c_block(address)\n\treturn number\n\n\n# Read and return temperature and humidity from Grove DHT Pro\ndef dht(pin, module_type):\n\twrite_i2c_block(address, dht_temp_cmd + [pin, module_type, unused])\n\n\t# Delay necessary for proper reading fron DHT sensor\n\ttime.sleep(.6)\n\ttry:\n\t\tread_i2c_byte(address)\n\t\tnumber = read_i2c_block(address)\n\t\ttime.sleep(.1)\n\t\tif number == -1:\n\t\t\treturn [-1,-1]\n\texcept (TypeError, IndexError):\n\t\treturn [-1,-1]\n\t# data returned in IEEE format as a float in 4 bytes\n\n\tif p_version==2:\n\t\th=''\n\t\tfor element in (number[1:5]):\n\t\t\th+=chr(element)\n\n\t\tt_val=struct.unpack('f', h)\n\t\tt = round(t_val[0], 2)\n\n\t\th = ''\n\t\tfor element in (number[5:9]):\n\t\t\th+=chr(element)\n\n\t\thum_val=struct.unpack('f',h)\n\t\thum = round(hum_val[0], 2)\n\telse:\n\t\tt_val=bytearray(number[1:5])\n\t\th_val=bytearray(number[5:9])\n\t\tt=round(struct.unpack('f',t_val)[0],2)\n\t\thum=round(struct.unpack('f',h_val)[0],2)\n\tif t > -100.0 and t <150.0 and hum >= 0.0 and hum<=100.0:\n\t\treturn [t, hum]\n\telse:\n\t\treturn [float('nan'),float('nan')]\n\n# after a list of numerical values is provided\n# the function returns a list with the outlier(or extreme) values removed\n# make the std_factor_threshold bigger so that filtering becomes less strict\n# and make the std_factor_threshold smaller to get the opposite\ndef statisticalNoiseReduction(values, std_factor_threshold = 2):\n\tif len(values) == 0:\n\t\treturn []\n\t\t\n\tmean = numpy.mean(values)\n\tstandard_deviation = numpy.std(values)\n\n\tif standard_deviation == 0:\n\t\treturn values\n\n\tfiltered_values = [element for element in values if element > mean - std_factor_threshold * standard_deviation]\n\tfiltered_values = [element for element in filtered_values if element < mean + std_factor_threshold * standard_deviation]\n\n\treturn filtered_values\n\n\n# Grove LED Bar - initialise\n# orientation: (0 = red to green, 1 = green to red)\ndef ledBar_init(pin, orientation):\n\twrite_i2c_block(address, ledBarInit_cmd + [pin, orientation, unused])\n\treturn 1\n\n# Grove LED Bar - set orientation\n# orientation: (0 = red to green, 1 = green to red)\ndef ledBar_orientation(pin, orientation):\n\twrite_i2c_block(address, ledBarOrient_cmd + [pin, orientation, unused])\n\treturn 1\n\n# Grove LED Bar - set level\n# level: (0-10)\ndef ledBar_setLevel(pin, level):\n\twrite_i2c_block(address, ledBarLevel_cmd + [pin, level, unused])\n\treturn 1\n\n# Grove LED Bar - set single led\n# led: which led (1-10)\n# state: off or on (0-1)\ndef ledBar_setLed(pin, led, state):\n\twrite_i2c_block(address, ledBarSetOne_cmd + [pin, led, state])\n\treturn 1\n\n# Grove LED Bar - toggle single led\n# led: which led (1-10)\ndef ledBar_toggleLed(pin, led):\n\twrite_i2c_block(address, ledBarToggleOne_cmd + [pin, led, unused])\n\treturn 1\n\n# Grove LED Bar - set all leds\n# state: (0-1023) or (0x00-0x3FF) or (0b0000000000-0b1111111111) or (int('0000000000',2)-int('1111111111',2))\ndef ledBar_setBits(pin, state):\n\tbyte1 = state & 255\n\tbyte2 = state >> 8\n\twrite_i2c_block(address, ledBarSet_cmd + [pin, byte1, byte2])\n\treturn 1\n\n# Grove LED Bar - get current state\n# state: (0-1023) a bit for each of the 10 LEDs\ndef ledBar_getBits(pin):\n\twrite_i2c_block(address, ledBarGet_cmd + [pin, unused, unused])\n\ttime.sleep(.2)\n\tread_i2c_byte(0x04)\n\tblock = read_i2c_block(0x04)\n\treturn block[1] ^ (block[2] << 8)\n\n\n# Grove 4 Digit Display - initialise\ndef fourDigit_init(pin):\n\twrite_i2c_block(address, fourDigitInit_cmd + [pin, unused, unused])\n\treturn 1\n\n# Grove 4 Digit Display - set numeric value with or without leading zeros\n# value: (0-65535) or (0000-FFFF)\ndef fourDigit_number(pin, value, leading_zero):\n\t# split the value into two bytes so we can render 0000-FFFF on the display\n\tbyte1 = value & 255\n\tbyte2 = value >> 8\n\t# separate commands to overcome current 4 bytes per command limitation\n\tif (leading_zero):\n\t\twrite_i2c_block(address, fourDigitValue_cmd + [pin, byte1, byte2])\n\telse:\n\t\twrite_i2c_block(address, fourDigitValueZeros_cmd + [pin, byte1, byte2])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove 4 Digit Display - set brightness\n# brightness: (0-7)\ndef fourDigit_brightness(pin, brightness):\n\t# not actually visible until next command is executed\n\twrite_i2c_block(address, fourDigitBrightness_cmd + [pin, brightness, unused])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove 4 Digit Display - set individual segment (0-9,A-F)\n# segment: (0-3)\n# value: (0-15) or (0-F)\ndef fourDigit_digit(pin, segment, value):\n\twrite_i2c_block(address, fourDigitIndividualDigit_cmd + [pin, segment, value])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove 4 Digit Display - set 7 individual leds of a segment\n# segment: (0-3)\n# leds: (0-255) or (0-0xFF) one bit per led, segment 2 is special, 8th bit is the colon\ndef fourDigit_segment(pin, segment, leds):\n\twrite_i2c_block(address, fourDigitIndividualLeds_cmd + [pin, segment, leds])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove 4 Digit Display - set left and right values (0-99), with leading zeros and a colon\n# left: (0-255) or (0-FF)\n# right: (0-255) or (0-FF)\n# colon will be lit\ndef fourDigit_score(pin, left, right):\n\twrite_i2c_block(address, fourDigitScore_cmd + [pin, left, right])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove 4 Digit Display - display analogRead value for n seconds, 4 samples per second\n# analog: analog pin to read\n# duration: analog read for this many seconds\ndef fourDigit_monitor(pin, analog, duration):\n\twrite_i2c_block(address, fourDigitAnalogRead_cmd + [pin, analog, duration])\n\ttime.sleep(duration + .05)\n\treturn 1\n\n# Grove 4 Digit Display - turn entire display on (88:88)\ndef fourDigit_on(pin):\n\twrite_i2c_block(address, fourDigitAllOn_cmd + [pin, unused, unused])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove 4 Digit Display - turn entire display off\ndef fourDigit_off(pin):\n\twrite_i2c_block(address, fourDigitAllOff_cmd + [pin, unused, unused])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove Chainable RGB LED - store a color for later use\n# red: 0-255\n# green: 0-255\n# blue: 0-255\ndef storeColor(red, green, blue):\n\twrite_i2c_block(address, storeColor_cmd + [red, green, blue])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove Chainable RGB LED - initialise\n# numLeds: how many leds do you have in the chain\ndef chainableRgbLed_init(pin, numLeds):\n\twrite_i2c_block(address, chainableRgbLedInit_cmd + [pin, numLeds, unused])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove Chainable RGB LED - initialise and test with a simple color\n# numLeds: how many leds do you have in the chain\n# testColor: (0-7) 3 bits in total - a bit for red, green and blue, eg. 0x04 == 0b100 (0bRGB) == rgb(255, 0, 0) == #FF0000 == red\n# ie. 0 black, 1 blue, 2 green, 3 cyan, 4 red, 5 magenta, 6 yellow, 7 white\ndef chainableRgbLed_test(pin, numLeds, testColor):\n\twrite_i2c_block(address, chainableRgbLedTest_cmd + [pin, numLeds, testColor])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove Chainable RGB LED - set one or more leds to the stored color by pattern\n# pattern: (0-3) 0 = this led only, 1 all leds except this led, 2 this led and all leds inwards, 3 this led and all leds outwards\n# whichLed: index of led you wish to set counting outwards from the GrovePi, 0 = led closest to the GrovePi\ndef chainableRgbLed_pattern(pin, pattern, whichLed):\n\twrite_i2c_block(address, chainableRgbLedSetPattern_cmd + [pin, pattern, whichLed])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove Chainable RGB LED - set one or more leds to the stored color by modulo\n# offset: index of led you wish to start at, 0 = led closest to the GrovePi, counting outwards\n# divisor: when 1 (default) sets stored color on all leds >= offset, when 2 sets every 2nd led >= offset and so on\ndef chainableRgbLed_modulo(pin, offset, divisor):\n\twrite_i2c_block(address, chainableRgbLedSetModulo_cmd + [pin, offset, divisor])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove Chainable RGB LED - sets leds similar to a bar graph, reversible\n# level: (0-10) the number of leds you wish to set to the stored color\n# reversible (0-1) when 0 counting outwards from GrovePi, 0 = led closest to the GrovePi, otherwise counting inwards\ndef chainableRgbLed_setLevel(pin, level, reverse):\n\twrite_i2c_block(address, chainableRgbLedSetLevel_cmd + [pin, level, reverse])\n\ttime.sleep(.05)\n\treturn 1\n\n# Grove - Infrared Receiver- get the commands received from the Grove IR sensor\ndef ir_read_signal():\n\ttry:\n\t\twrite_i2c_block(address,ir_read_cmd+[unused,unused,unused])\n\t\ttime.sleep(.1)\n\t\tdata_back= bus.read_i2c_block_data(address, 1)[0:21]\n\t\tif (data_back[1]!=255):\n\t\t\treturn data_back\n\t\treturn [-1]*21\n\texcept IOError:\n\t\treturn [-1]*21\n\n# Grove - Infrared Receiver- set the pin on which the Grove IR sensor is connected\ndef ir_recv_pin(pin):\n\twrite_i2c_block(address,ir_recv_pin_cmd+[pin,unused,unused])\n\ndef dust_sensor_en():\n\twrite_i2c_block(address, dust_sensor_en_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\ndef dust_sensor_dis():\n\twrite_i2c_block(address, dust_sensor_dis_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\ndef dustSensorRead():\n\twrite_i2c_block(address, dus_sensor_read_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\t#read_i2c_byte(address)\n\t#number = read_i2c_block(address)\n\t#return (number[1] * 256 + number[2])\n\tdata_back= bus.read_i2c_block_data(address, 1)[0:4]\n\t#print data_back[:4]\n\tif data_back[0]!=255:\n\t\tlowpulseoccupancy=(data_back[3]*256*256+data_back[2]*256+data_back[1])\n\t\t#print [data_back[0],lowpulseoccupancy]\n\t\treturn [data_back[0],lowpulseoccupancy]\n\telse:\n\t\treturn [-1,-1]\n\tprint (data_back)\n\ndef encoder_en():\n\twrite_i2c_block(address, encoder_en_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\ndef encoder_dis():\n\twrite_i2c_block(address, encoder_dis_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\ndef encoderRead():\n\twrite_i2c_block(address, encoder_read_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\tdata_back= bus.read_i2c_block_data(address, 1)[0:2]\n\t#print data_back\n\tif data_back[0]!=255:\n\t\treturn [data_back[0],data_back[1]]\n\telse:\n\t\treturn [-1,-1]\n\ndef flowDisable():\n\twrite_i2c_block(address, flow_disable_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\ndef flowEnable():\n\twrite_i2c_block(address, flow_en_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\ndef flowRead():\n\twrite_i2c_block(address, flow_read_cmd + [unused, unused, unused])\n\ttime.sleep(.2)\n\tdata_back= bus.read_i2c_block_data(address, 1)[0:3]\n\t#print data_back\n\tif data_back[0]!=255:\n\t\treturn [data_back[0],data_back[2]*256+data_back[1]]\n\telse:\n\t\treturn [-1,-1]\n"
] |
[
[
"numpy.std",
"numpy.mean"
]
] |
CnybTseng/YOLACT
|
[
"e8564b9f961dc99c740a58efc199243233c8cbfe"
] |
[
"core/layers/segmentation.py"
] |
[
"import torch\r\nimport torch.nn.functional as F\r\n\r\nclass MaskProducer(object):\r\n def __init__(self, interpolation_mode='bilinear', crop_mask=True, score_thresh=0):\r\n self.interpolation_mode = interpolation_mode\r\n self.crop_mask = crop_mask\r\n self.score_thresh = score_thresh\r\n \r\n def __call__(self, detout, imw, imh):\r\n for det in detout:\r\n keeps = det['clas'] > self.score_thresh\r\n for k, v in det.items():\r\n if k != 'prot':\r\n det[k] = det[k][keeps]\r\n \r\n det['mask'] = self._mkmask(det, imw, imh)\r\n x1, y1, x2, y2 = self._absbox(det['bbox'], imw, imh)\r\n det['bbox'] = torch.stack([x1, y1, x2, y2], dim=1).long()\r\n return detout\r\n \r\n def _mkmask(self, detout, imw, imh):\r\n bbox = detout['bbox']\r\n mask = detout['mask']\r\n prot = detout['prot']\r\n mask = prot @ mask.t()\r\n mask = torch.sigmoid(mask)\r\n if self.crop_mask:\r\n mask = self._crop(mask, bbox)\r\n mask = mask.permute(2, 0, 1).contiguous().unsqueeze(dim=0)\r\n mask = F.interpolate(mask, size=(imh, imw), mode=self.interpolation_mode, align_corners=False).squeeze(dim=0)\r\n mask.gt_(0.5)\r\n return mask\r\n \r\n def _crop(self, mask, bbox, padding=1):\r\n h, w, c = mask.size()\r\n x1, y1, x2, y2 = self._absbox(bbox, w, h, padding)\r\n rows = torch.arange(w, device=mask.device, dtype=x1.dtype).view(1, -1, 1).expand(h, w, c)\r\n cols = torch.arange(h, device=mask.device, dtype=x1.dtype).view(-1, 1, 1).expand(h, w, c)\r\n left = rows >= x1.view(1, 1, -1)\r\n right = rows < x2.view(1, 1, -1)\r\n top = cols >= y1.view(1, 1, -1)\r\n bottom = cols < y2.view(1, 1, -1)\r\n sel = left * right * top * bottom\r\n return mask * sel.float()\r\n\r\n def _absbox(self, bbox, w, h, padding=0):\r\n x1, x2 = bbox[:, 0] * w, bbox[:, 2] * w\r\n y1, y2 = bbox[:, 1] * h, bbox[:, 3] * h\r\n x1, x2 = self._calibrate_range(x1, x2, 0, w, padding)\r\n y1, y2 = self._calibrate_range(y1, y2, 0, h, padding)\r\n return x1, y1, x2, y2\r\n \r\n def _calibrate_range(self, x1, x2, min, max, padding=0):\r\n _x1 = torch.min(x1, x2) - padding\r\n _x2 = torch.max(x1, x2) + padding\r\n _x1 = torch.clamp(_x1, min=min)\r\n _x2 = torch.clamp(_x2, max=max)\r\n return _x1, _x2"
] |
[
[
"torch.sigmoid",
"torch.max",
"torch.min",
"torch.nn.functional.interpolate",
"torch.arange",
"torch.stack",
"torch.clamp"
]
] |
HannaCun/GoogleNet_Deploy
|
[
"4db38e97682b3982f2ca8db55b60ed32ef3ea2a5"
] |
[
"examples/simple/test.py"
] |
[
"# Copyright 2020 Lorna Authors. All Rights Reserved.\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\"\"\"\nIn this simple example, we load an image, pre-process it, and classify it\nwith a pretrained GoogLeNet.\n\"\"\"\nimport json\n\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\n\nfrom googlenet_pytorch import GoogLeNet\n\n# Open image\ninput_image = Image.open(\"img.jpg\")\n\n# Preprocess image\npreprocess = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n])\ninput_tensor = preprocess(input_image)\ninput_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model\n\n# Load class names\nlabels_map = json.load(open(\"labels_map.txt\"))\nlabels_map = [labels_map[str(i)] for i in range(1000)]\n\n# Classify with GoogLeNet\nmodel = GoogLeNet.from_pretrained(\"googlenet\")\nmodel.eval()\n\n# move the input and model to GPU for speed if available\nif torch.cuda.is_available():\n input_batch = input_batch.to(\"cuda\")\n model.to(\"cuda\")\n\nwith torch.no_grad():\n logits = model(input_batch)\npreds = torch.topk(logits, k=5).indices.squeeze(0).tolist()\n\nprint(\"-----\")\nfor idx in preds:\n label = labels_map[idx]\n prob = torch.softmax(logits, dim=1)[0, idx].item()\n print(f\"{label:<75} ({prob * 100:.2f}%)\")\n"
] |
[
[
"torch.topk",
"torch.softmax",
"torch.no_grad",
"torch.cuda.is_available"
]
] |
numericalalgorithmsgroup/pypop
|
[
"b8d0756f10bfb8db1466a2691c45ef9ed7c77194"
] |
[
"pypop/prv.py"
] |
[
"#!/usr/bin/env python\n# SPDX-License-Identifier: BSD-3-Clause-Clear\n# Copyright (c) 2019, The Numerical Algorithms Group, Ltd. All rights reserved.\n\n\"\"\"\\\nPRV Trace Loader\n----------------\n\nSupport for directly loading PRV trace data as Pandas dataframes\n\"\"\"\n\nimport pandas\nimport numpy\n\nfrom hashlib import sha1\nfrom warnings import warn\nfrom collections import OrderedDict\nfrom csv import writer as csvwriter\nfrom io import StringIO\n\nfrom pypop.utils.io import zipopen\nfrom pypop.utils.pandas import HDFStoreContext\nfrom pypop.utils.exceptions import WrongLoaderError\n\nfrom pypop.trace.tracemetadata import TraceMetadata\n\ntry:\n from tqdm.auto import tqdm\nexcept ImportError:\n from .utils import return_first_arg as tqdm\n\nimport pandas as pd\nimport numpy as np\n\n# Event states - hopefully these will not change(!)\nK_STATE_RUNNING = \"1\"\nK_EVENT_OMP_PARALLEL = 60000001\nK_EVENT_OMP_LOOP_FUNCTION = 60000018\nK_EVENT_OMP_TASK_FUNCTION = 60000023\nK_EVENT_OMP_LOOP_FILE_AND_LINE = 60000118\nK_EVENT_OMP_TASK_FILE_AND_LINE = 60000123\n\n\nclass PRV(object):\n\n _metadatakey = \"/PyPOPTraceMetadata\"\n _statekey = \"/PyPOPPRVStates\"\n _eventkey = \"/PyPOPPRVEvents\"\n _commkey = \"/PyPOPPRVComms\"\n _eventnamekey = \"/PyPOPPRVEventNames\"\n _eventvaluekey = \"/PyPOPPRVEventVals_\"\n _ompregionkey = \"/PyPOPPRVOMPRegionDetail\"\n\n _formatversionkey = \"/PyPOPPRVBinaryTraceFormatVersion\"\n _formatversion = 1\n\n record_types = OrderedDict([(1, \"state\"), (2, \"event\"), (3, \"comm\")])\n\n colnames = {\n \"state\": [\"task\", \"thread\", \"cpu\", \"time\", \"endtime\", \"state\"],\n \"event\": [\"task\", \"thread\", \"cpu\", \"time\", \"event\", \"value\"],\n \"comm\": None,\n }\n\n coltypes = {\n \"state\": {\n \"task\": np.int32,\n \"thread\": np.int32,\n \"cpu\": np.int32,\n \"begin\": np.int64,\n \"end\": np.int64,\n \"state\": np.int32,\n },\n \"event\": {\n \"task\": np.int32,\n \"thread\": np.int32,\n \"cpu\": np.int32,\n \"begin\": np.int64,\n \"event\": np.int32,\n \"value\": np.int,\n },\n \"comm\": None,\n }\n\n def __init__(self, prv_path, lazy_load=False, ignore_cache=False):\n\n self._prv_path = prv_path\n\n self.metadata = TraceMetadata(self)\n\n self._omp_region_data = None\n self.event_names = {}\n self.event_vals = {}\n\n # These go deliberately unset for JIT loading with __getattr__\n # self.state =\n # self.event =\n # self.comm =\n\n try:\n if ignore_cache:\n raise FileNotFoundError(\"Ignoring Cache\")\n self._load_binarycache()\n except (ValueError, FileNotFoundError):\n try:\n self._parse_pcf()\n if not lazy_load:\n self._parse_prv()\n except (ValueError, WrongLoaderError):\n raise ValueError(\"Not a valid prv or binary cache file\")\n\n def __getattr__(self, attr):\n \"\"\"Need to intercept attempts to access lazily-loaded data objects and ensure\n they are loaded just-in-time\n \"\"\"\n\n if attr in PRV.record_types.values():\n self._parse_prv()\n\n return super().__getattribute__(attr)\n\n @property\n def omp_region_data(self):\n if self._omp_region_data is None:\n self.profile_openmp_regions(no_progress=True)\n\n return self._omp_region_data\n\n @staticmethod\n def _generate_binaryfile_name(prvfile):\n return prvfile + \".bincache\"\n\n def reload(self):\n if self._no_prv:\n warn(\"Data loaded directly from cachefile, reload from PRV not possible\")\n return\n\n self._parse_pcf()\n self._parse_prv()\n\n def _parse_pcf(self):\n\n self.metadata = PRV._populate_metadata(self._prv_path, self.metadata)\n\n if self._prv_path.endswith(\".gz\"):\n pcf_path = \"\".join([self._prv_path[:-6], \"pcf\"])\n else:\n pcf_path = \"\".join([self._prv_path[:-3], \"pcf\"])\n\n try:\n with open(pcf_path, \"rt\") as fh:\n block_mode = None\n for line in fh:\n if not line.strip():\n continue\n if not line[0].isdigit():\n block_mode = line.split()[0]\n continue\n\n if block_mode == \"EVENT_TYPE\":\n linevals = line.strip().split(maxsplit=2)\n eventkey = int(linevals[1])\n self.event_names[eventkey] = linevals[2]\n self.event_vals[eventkey] = {}\n continue\n\n if block_mode == \"VALUES\":\n linevals = line.strip().split(maxsplit=1)\n valuekey = int(linevals[0])\n self.event_vals[eventkey][valuekey] = linevals[1]\n\n except FileNotFoundError:\n raise FileNotFoundError(\"No PCF file accompanying PRV - cannot continue\")\n\n def add_interpreted_names(self):\n\n if \"Event Name\" not in self.event:\n self.event[\"Event Name\"] = self.event[\"event\"].map(self.event_names)\n if \"Event Value\" not in self.event:\n self.event[\"Event Value\"] = self.event.apply(\n lambda x: self.event_vals.get(x[\"event\"], {}).get(\n x[\"value\"], str(x[\"value\"])\n ),\n axis=\"columns\",\n )\n\n def _parse_prv(self):\n\n self.state = None\n self.event = None\n self.comm = None\n\n temp_data = [StringIO() for _ in range(len(PRV.record_types))]\n temp_writers = [csvwriter(x) for x in temp_data]\n\n line_processors = {\n k: getattr(self, \"_process_{}line\".format(v))\n for k, v in PRV.record_types.items()\n }\n\n with zipopen(self._prv_path, \"rt\") as prv_fh:\n headerline = next(prv_fh)\n self.metadata = PRV._populate_metadata(headerline, self.metadata)\n\n # Skip the communicator lines for now\n try:\n skiplines = int(headerline[headerline.rfind(\"),\") + 2 :])\n except ValueError:\n skiplines = 0\n for i in range(skiplines):\n next(prv_fh)\n\n linecounter = 0\n for line in prv_fh:\n # Skip comment lines\n if line.startswith(\"#\"):\n continue\n line = [int(x) for x in line.split(\":\")]\n line_processors[line[0]](line, temp_writers[line[0] - 1])\n linecounter += 1\n if linecounter % 1000000 == 0:\n self._flush_prv_temp_data(temp_data)\n temp_data = [StringIO() for _ in range(len(PRV.record_types))]\n temp_writers = [csvwriter(x) for x in temp_data]\n self._flush_prv_temp_data(temp_data)\n\n for iattr, attrname in PRV.record_types.items():\n if getattr(self, attrname) is not None and not getattr(self, attrname).empty:\n getattr(self, attrname).set_index(\n [\"task\", \"thread\", \"time\"], inplace=True\n )\n getattr(self, attrname).sort_index(inplace=True)\n\n self._write_binarycache()\n\n def _flush_prv_temp_data(self, temp_data):\n for iattr, attrname in PRV.record_types.items():\n temp_data[iattr - 1].seek(0)\n try:\n newdata = pd.read_csv(\n temp_data[iattr - 1],\n names=PRV.colnames[attrname],\n dtype=PRV.coltypes[attrname],\n engine=\"c\",\n )\n except pd.errors.EmptyDataError:\n continue\n setattr(\n self, attrname, pd.concat([getattr(self, attrname), newdata]),\n )\n\n def _process_stateline(self, line, writer):\n writer.writerow([line[3], line[4], line[1], line[5], line[6], line[7]])\n\n def _process_eventline(self, line, writer):\n row_start = [line[3], line[4], line[1], line[5]]\n nrows = (len(line) - 6) // 2\n rows = [row_start + line[6 + 2 * x : 8 + 2 * x] for x in range(nrows)]\n writer.writerows(rows)\n\n def _process_commline(self, line, writer):\n pass\n\n def _write_binarycache(self):\n binaryfile = self._generate_binaryfile_name(self._prv_path)\n\n packed_metadata = self.metadata.pack_dataframe()\n\n packed_metadata[PRV._formatversionkey] = pandas.Series(\n data=PRV._formatversion, dtype=numpy.int32\n )\n\n with HDFStoreContext(binaryfile, mode=\"w\") as hdfstore:\n hdfstore.put(self._metadatakey, packed_metadata, format=\"t\")\n if self.state is not None and not self.state.empty:\n hdfstore.put(self._statekey, self.state, format=\"t\", complib=\"blosc\")\n if self.event is not None and not self.event.empty:\n hdfstore.put(self._eventkey, self.event, format=\"t\", complib=\"blosc\")\n if self.comm is not None and not self.comm.empty:\n hdfstore.put(self._commkey, self.comm, format=\"t\", complib=\"blosc\")\n if self._omp_region_data is not None and not self._omp_region_data.empty:\n hdfstore.put(\n self._ompregionkey,\n self._omp_region_data,\n format=\"t\",\n complib=\"blosc\",\n )\n\n hdfstore.put(self._eventnamekey, pd.Series(self.event_names), format=\"t\")\n\n for evtkey, evtvals in self.event_vals.items():\n hdfstore.put(\n \"\".join([self._eventvaluekey, str(evtkey)]),\n pd.Series(evtvals),\n format=\"t\",\n )\n\n def _load_binarycache(self):\n\n try:\n self._read_binarycache(self._prv_path)\n self._no_prv = True\n except:\n # This will raise either ValueError or FileNotFoundError to be trapped and\n # handled by calling function\n self._read_binarycache(self._generate_binaryfile_name(self._prv_path))\n\n def _read_binarycache(self, filename):\n\n # HDFStoreContext will raise perfectly sensible errors, no need to trap\n with HDFStoreContext(filename, mode=\"r\") as hdfstore:\n try:\n file_metadata = hdfstore[PRV._metadatakey]\n format_version = file_metadata[PRV._formatversionkey][0]\n except KeyError:\n raise ValueError(\"{} is not a binary event store\".format(filename))\n\n if format_version > PRV._formatversion:\n warn(\n \"Trace data was written with a newer PyPOP version. The \"\n \"format is intended to be backward compatible but you may wish \"\n \"to upgrade your installed PyPOP version to support all \"\n \"features.\"\n )\n\n try:\n self.metadata = TraceMetadata.unpack_dataframe(file_metadata)\n self.event_names = hdfstore[PRV._eventnamekey].to_dict()\n self.event_vals = {}\n for evtkey in (\n x for x in hdfstore.keys() if x.startswith(PRV._eventvaluekey)\n ):\n intkey = int(evtkey.replace(PRV._eventvaluekey, \"\"))\n self.event_vals[intkey] = hdfstore[evtkey].to_dict()\n except KeyError:\n raise ValueError(\"{} corrupted binary event cache\")\n\n try:\n self.state = hdfstore[PRV._statekey]\n except KeyError:\n self.state = None\n try:\n self.event = hdfstore[PRV._eventkey]\n except KeyError:\n self.event = None\n try:\n self.comm = hdfstore[PRV._commkey]\n except KeyError:\n self.comm = None\n try:\n self._omp_region_data = hdfstore[self._ompregionkey]\n except KeyError:\n self._omp_region_data = None\n\n def profile_openmp_regions(self, no_progress=False, ignore_cache=False):\n \"\"\"Profile OpenMP Region Info\n \"\"\"\n\n if self._omp_region_data is not None:\n return self._omp_region_data\n\n idx_master_threads = pd.IndexSlice[:, 1]\n\n # First generate appropriate event subsets grouped by rank\n rank_state_groups = self.state.query(\n \"state == {}\".format(K_STATE_RUNNING)\n ).groupby(\n level=\"task\"\n ) # State transitions\n rank_event_groups = (\n self.event.loc[idx_master_threads, :]\n .query(\"event == {}\".format(K_EVENT_OMP_PARALLEL))\n .droplevel(\"thread\")\n .groupby(level=\"task\")\n ) # OMP regions\n rank_func_groups = (\n self.event.query(\n \"event == {} or event == {}\".format(\n K_EVENT_OMP_TASK_FUNCTION, K_EVENT_OMP_LOOP_FUNCTION\n )\n )\n .query(\"value != 0\")\n .groupby(level=\"task\")\n ) # OMP Functions\n\n rank_func_loc_groups = (\n self.event.query(\n \"event == {} or event == {}\".format(\n K_EVENT_OMP_TASK_FILE_AND_LINE, K_EVENT_OMP_LOOP_FILE_AND_LINE\n )\n )\n .query(\"value != 0\")\n .groupby(level=\"task\")\n ) # OMP Functions\n\n # Now start collecting OMP regions\n rank_stats = {}\n for (\n (irank, rank_events),\n (_, rank_states),\n (_, rank_funcs),\n (_, rank_func_locs),\n ) in tqdm(\n zip(\n rank_event_groups,\n rank_state_groups,\n rank_func_groups,\n rank_func_loc_groups,\n ),\n total=self.metadata.num_processes,\n disable=no_progress,\n leave=None,\n ):\n\n # OpenMP events mark region start/end on master thread\n thread_events = rank_events.droplevel(\"task\")\n if not np.alltrue(np.diff(thread_events.index) >= 0):\n raise ValueError(\"Event timings are non-monotonic\")\n\n region_starts = thread_events.index[thread_events[\"value\"] != 0]\n region_ends = thread_events.index[thread_events[\"value\"] == 0]\n\n # First region start should be earlier than first region end\n if region_ends[0] <= region_starts[0]:\n warn(\n \"Incomplete OpenMP region found. This likely means the trace was \"\n \"cut through a region\"\n )\n while len(region_ends) > 0 and region_ends[0] <= region_starts[0]:\n region_ends = region_ends[1:]\n\n # Last region end should be after last region start\n if region_starts[-1] >= region_ends[-1]:\n warn(\n \"Incomplete OpenMP region found. This likely means the trace was \"\n \"cut through a region\"\n )\n while len(region_starts) > 0 and region_starts[-1] >= region_ends[-1]:\n region_starts = region_starts[:-1]\n\n # Now sanity check regions and try to repair issues caused by missing events:\n # Cut traces seem to have an extra end event injected by the cutter trying to\n # be \"helpful\" If this seems to be the case try trimming the end and post a\n # warning\n if len(region_ends) == len(region_starts) + 1:\n region_ends = region_ends[:-1]\n warn(\"Attempting to trim spurious events - cutter inserted?\")\n\n if np.any(region_starts > region_ends):\n raise ValueError(\"Unable to make sense of OpenMP region events.\")\n\n region_lengths = region_ends - region_starts\n region_computation_mean = np.zeros_like(region_starts)\n region_computation_max = np.zeros_like(region_starts)\n region_computation_sum = np.zeros_like(region_starts)\n\n regionintervals = pd.IntervalIndex.from_arrays(region_starts, region_ends)\n\n funcbins = pd.cut(\n rank_funcs.droplevel((\"task\", \"thread\")).index, regionintervals\n ).codes\n # Remove negative categories codes -> events not in any region interval\n cleaned_rfuncs = rank_funcs.droplevel((\"task\", \"thread\"))[funcbins >= 0]\n cleaned_fbins = funcbins[funcbins >= 0]\n region_funcs = cleaned_rfuncs.groupby(cleaned_fbins)\n region_fingerprints_func = region_funcs.apply(\n lambda x: \":\".join(\n [\n self.omp_function_by_value(int(y))\n for y in x[\"value\"].unique()\n ]\n )\n )\n\n funclocbins = pd.cut(\n rank_func_locs.droplevel((\"task\", \"thread\")).index, regionintervals\n ).codes\n cleaned_rflocs = rank_func_locs.droplevel((\"task\", \"thread\"))[\n funclocbins >= 0\n ]\n cleaned_flbins = funclocbins[funclocbins >= 0]\n region_func_locs = cleaned_rflocs.groupby(cleaned_flbins)\n region_fingerprints_loc = region_func_locs.apply(\n lambda x: \":\".join(\n [\n self.omp_location_by_value(int(y))\n for y in x[\"value\"].unique()\n ]\n )\n )\n\n # Iterate over threads to get max, average\n thread_state_groups = rank_states.droplevel(0).groupby(level=\"thread\")\n for thread, thread_states in tqdm(\n thread_state_groups,\n total=len(thread_state_groups),\n disable=no_progress,\n leave=None,\n ):\n\n thread_states = thread_states.droplevel(0)\n if not (\n np.alltrue(np.diff(thread_states.index) >= 0)\n and np.alltrue(np.diff(thread_states[\"endtime\"]) >= 0)\n ):\n raise ValueError(\"State timings are non-monotonic\")\n\n for idx in range(region_starts.shape[0]):\n # Extract useful states that exist within OMP region\n start_idx = thread_states[\"endtime\"].searchsorted(\n region_starts[idx] + 1\n )\n end_idx = thread_states.index.searchsorted(region_ends[idx])\n\n # Tiny dataframe with useful regions\n useful_state = thread_states.iloc[start_idx:end_idx]\n\n # Sum to get useful length on thread\n useful_length = np.asarray(\n useful_state[\"endtime\"] - useful_state.index\n ).sum()\n\n region_computation_mean[idx] += useful_length / len(\n thread_state_groups\n )\n region_computation_max[idx] = max(\n region_computation_max[idx], useful_length\n )\n\n region_computation_sum[idx] += useful_length\n\n if np.any(region_computation_max > region_lengths):\n raise ValueError(\"Oversized region\")\n\n region_load_balance = 1 - (\n (region_computation_max - region_computation_mean) / region_lengths\n )\n\n region_parallel_efficiency = 1 - (\n (region_lengths - region_computation_mean) / region_lengths\n )\n\n rank_stats[irank] = pd.DataFrame(\n {\n \"Rank\": np.full(region_starts.shape, irank),\n \"Region Start\": region_starts,\n \"Region End\": region_ends,\n \"Region Length\": region_lengths,\n \"Load Balance\": region_load_balance,\n \"Parallel Efficiency\": region_parallel_efficiency,\n \"Average Computation Time\": region_computation_mean,\n \"Maximum Computation Time\": region_computation_max,\n \"Computation Delay Time\": region_computation_max\n - region_computation_mean,\n \"Region Total Computation\": region_computation_sum,\n \"Region Delay Time\": region_lengths - region_computation_mean,\n \"Region Function Fingerprint\": region_fingerprints_func,\n \"Region Location Fingerprint\": region_fingerprints_loc,\n }\n )\n\n self._omp_region_data = pd.concat(rank_stats, names=[\"rank\", \"region\"])\n\n return self._omp_region_data\n\n def region_location_from_fingerprint(self, fingerprint):\n if self.event_vals:\n fpvals = fingerprint.split(\":\")\n fpstrings = [self.omp_location_by_value(fpk, \"MISSINGVAL\") for fpk in fpvals]\n return \":\".join(fpstrings)\n\n return fingerprint\n\n def omp_location_by_value(self, value, default=\"MISSINGVAL\"):\n value_dict = {\n **self.event_vals.get(K_EVENT_OMP_TASK_FILE_AND_LINE, {}),\n **self.event_vals.get(K_EVENT_OMP_LOOP_FILE_AND_LINE, {}),\n }\n\n return value_dict.get(value, default)\n\n def region_function_from_fingerprint(self, fingerprint):\n if self.event_vals:\n fpvals = fingerprint.split(\":\")\n fpstrings = [self.omp_function_by_value(fpk, \"MISSINGVAL\") for fpk in fpvals]\n return \":\".join(fpstrings)\n\n return fingerprint\n\n def omp_function_by_value(self, value, default=\"MISSINGVAL\"):\n value_dict = {\n **self.event_vals.get(K_EVENT_OMP_TASK_FUNCTION, {}),\n **self.event_vals.get(K_EVENT_OMP_LOOP_FUNCTION, {}),\n }\n\n return value_dict.get(value, default)\n\n def openmp_region_summary(self, by_location=False):\n \"\"\"Summarize OpenMP regions, grouped by either the function name or location\n (filename and line number) within the source.\n\n Parameters\n ----------\n by_location: bool\n If true, aggregate functions based on their location within the source,\n otherwise aggregate by function name alone.\n \"\"\"\n\n if by_location:\n fingerprint_key = \"Region Location Fingerprint\"\n else:\n fingerprint_key = \"Region Function Fingerprint\"\n\n runtime = self.metadata.elapsed_seconds * 1e9\n nproc = len(set(self.omp_region_data[\"Rank\"]))\n\n self.profile_openmp_regions()\n\n summary = self.omp_region_data.groupby(fingerprint_key).agg(\n **{\n \"Instances\": (\"Maximum Computation Time\", \"count\"),\n \"Total Parallel Inefficiency Contribution\": (\n \"Region Delay Time\",\n lambda x: np.sum(x) / (nproc * runtime),\n ),\n \"Total Load Imbalance Contribution\": (\n \"Computation Delay Time\",\n lambda x: np.sum(x) / (nproc * runtime),\n ),\n \"Average Parallel Efficiency\": (\n \"Parallel Efficiency\",\n lambda x: np.average(\n x, weights=self.omp_region_data.loc[x.index, \"Region Length\"]\n ),\n ),\n \"Average Load Balance\": (\n \"Load Balance\",\n lambda x: np.average(\n x, weights=self.omp_region_data.loc[x.index, \"Region Length\"],\n ),\n ),\n \"Accumulated Region Time\": (\"Region Length\", np.sum),\n \"Accumulated Computation Time\": (\"Region Total Computation\", np.sum),\n \"Average Computation Time\": (\"Average Computation Time\", np.average),\n \"Maximum Computation Time\": (\"Maximum Computation Time\", np.max),\n \"Region Functions\": (fingerprint_key, lambda x: x.iloc[0],),\n }\n )\n\n return summary.sort_values(\"Total Parallel Inefficiency Contribution\")\n\n @staticmethod\n def _populate_metadata(prv_file, metadata):\n\n if prv_file.startswith(\"#Paraver\"):\n headerline = prv_file\n else:\n try:\n with zipopen(prv_file, \"rt\") as fh:\n headerline = fh.readline().strip()\n except IsADirectoryError:\n raise WrongLoaderError(\"Not a valid prv file\")\n\n if not headerline.startswith(\"#Paraver\"):\n raise WrongLoaderError(\"Not a valid prv file\")\n\n elem = headerline.replace(\":\", \";\", 1).split(\":\", 4)\n\n metadata.capture_time = elem[0][\n elem[0].find(\"(\") + 1 : elem[0].find(\")\")\n ].replace(\";\", \":\")\n\n metadata.elapsed_seconds = float(elem[1][:-3]) * 1e-9\n\n metadata.num_nodes, metadata.cores_per_node = PRV._split_nodestring(elem[2])\n\n # elem 3 is the number of applications, currently only support 1\n if int(elem[3]) != 1:\n raise ValueError(\"Multi-application traces are not supported\")\n\n # elem 4 contains the application layout processes/threads\n (\n metadata.num_processes,\n metadata.threads_per_process,\n ) = PRV._split_layoutstring(elem[4])\n\n metadata.tracefile_name = prv_file\n\n hasher = sha1()\n hasher.update(headerline.encode())\n metadata.fingerprint = hasher.hexdigest()\n\n return metadata\n\n @staticmethod\n def _split_nodestring(prv_td):\n num_nodes, plist = prv_td.split(\"(\", 2)\n num_nodes = int(num_nodes)\n cores_per_node = tuple(int(x) for x in plist.rstrip(\",)\").split(\",\"))\n\n return (num_nodes, cores_per_node)\n\n @staticmethod\n def _split_layoutstring(prv_td):\n\n prv_td = prv_td.split(\")\")[0].strip()\n commsize, layoutstring = prv_td.split(\"(\")\n\n commsize = int(commsize)\n threads = [int(x.split(\":\")[0]) for x in layoutstring.split(\",\")]\n\n return (commsize, threads)\n"
] |
[
[
"pandas.IntervalIndex.from_arrays",
"pandas.concat",
"pandas.read_csv",
"pandas.Series",
"numpy.asarray",
"numpy.full",
"numpy.zeros_like",
"numpy.any",
"numpy.diff",
"numpy.average",
"numpy.sum"
]
] |
MC-Zealot/transformer
|
[
"581409b815326b21f303afafadae27f67e3b6e69"
] |
[
"train.py"
] |
[
"# -*- coding: utf-8 -*-\n#/usr/bin/python3\n'''\nFeb. 2019 by kyubyong park.\[email protected].\nhttps://www.github.com/kyubyong/transformer\n'''\nimport tensorflow as tf\n\nfrom model import Transformer\nfrom tqdm import tqdm\nfrom data_load import get_batch\nfrom utils import save_hparams, save_variable_specs, get_hypotheses, calc_bleu\nimport os\nfrom hparams import Hparams\nimport math\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\n\nlogging.info(\"# hparams\")\nhparams = Hparams()\nparser = hparams.parser\nhp = parser.parse_args()\nsave_hparams(hp, hp.logdir)\n\nlogging.info(\"# Prepare train/eval batches\")\ntrain_batches, num_train_batches, num_train_samples = get_batch(hp.train1, hp.train2,\n hp.maxlen1, hp.maxlen2,\n hp.vocab, hp.batch_size,\n shuffle=True)\neval_batches, num_eval_batches, num_eval_samples = get_batch(hp.eval1, hp.eval2,\n 100000, 100000,\n hp.vocab, hp.batch_size,\n shuffle=False)\n\n# create a iterator of the correct shape and type\niter = tf.data.Iterator.from_structure(train_batches.output_types, train_batches.output_shapes)\nxs, ys = iter.get_next()\n\ntrain_init_op = iter.make_initializer(train_batches)\neval_init_op = iter.make_initializer(eval_batches)\n\nlogging.info(\"# Load model\")\nm = Transformer(hp)\nloss, train_op, global_step, train_summaries = m.train(xs, ys)\ny_hat, eval_summaries = m.eval(xs, ys)\n# y_hat = m.infer(xs, ys)\n\nlogging.info(\"# Session\")\nsaver = tf.train.Saver(max_to_keep=hp.num_epochs)\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.6\nwith tf.Session(config=config) as sess:\n ckpt = tf.train.latest_checkpoint(hp.logdir)\n if ckpt is None:\n logging.info(\"Initializing from scratch\")\n sess.run(tf.global_variables_initializer())\n save_variable_specs(os.path.join(hp.logdir, \"specs\"))\n else:\n saver.restore(sess, ckpt)\n\n summary_writer = tf.summary.FileWriter(hp.logdir, sess.graph)\n\n sess.run(train_init_op)\n total_steps = hp.num_epochs * num_train_batches\n _gs = sess.run(global_step)\n for i in tqdm(range(_gs, total_steps+1)):\n _, _gs, _summary = sess.run([train_op, global_step, train_summaries])\n epoch = math.ceil(_gs / num_train_batches)\n summary_writer.add_summary(_summary, _gs)\n\n if _gs and _gs % num_train_batches == 0:\n logging.info(\"epoch {} is done\".format(epoch))\n _loss = sess.run(loss) # train loss\n\n logging.info(\"# test evaluation\")\n _, _eval_summaries = sess.run([eval_init_op, eval_summaries])\n summary_writer.add_summary(_eval_summaries, _gs)\n\n logging.info(\"# get hypotheses\")\n hypotheses = get_hypotheses(num_eval_batches, num_eval_samples, sess, y_hat, m.idx2token)\n\n logging.info(\"# write results\")\n model_output = \"iwslt2016_E%02dL%.2f\" % (epoch, _loss)\n if not os.path.exists(hp.evaldir): os.makedirs(hp.evaldir)\n translation = os.path.join(hp.evaldir, model_output)\n with open(translation, 'w') as fout:\n fout.write(\"\\n\".join(hypotheses))\n\n logging.info(\"# calc bleu score and append it to translation\")\n calc_bleu(hp.eval3, translation)\n\n logging.info(\"# save models\")\n ckpt_name = os.path.join(hp.logdir, model_output)\n saver.save(sess, ckpt_name, global_step=_gs)\n logging.info(\"after training of {} epochs, {} has been saved.\".format(epoch, ckpt_name))\n\n logging.info(\"# fall back to train mode\")\n sess.run(train_init_op)\n summary_writer.close()\n\n\nlogging.info(\"Done\")\n"
] |
[
[
"tensorflow.train.latest_checkpoint",
"tensorflow.summary.FileWriter",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.data.Iterator.from_structure",
"tensorflow.Session",
"tensorflow.train.Saver"
]
] |
nicoring/RoBonjwa
|
[
"7b42265a42c389964ddf3ff535dbfb9370863ac5"
] |
[
"roborl/ddpg/ddpg.py"
] |
[
"import os\nimport pickle\n\nimport numpy as np\nimport torch\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom tensorboardX import SummaryWriter\n\n\nfrom roborl.util.memory import ReplayMemory\nfrom roborl.util.exploration import ActionNoiseExploration, ParamNoiseExploration\n\n\nuse_cuda = torch.cuda.is_available()\nFloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\nTensor = FloatTensor\n\nclass DDPG:\n def __init__(self, env, actor_model, critic_model, memory=10000, batch_size=64, gamma=0.99, \n tau=0.001, actor_lr=1e-4, critic_lr=1e-3, critic_decay=1e-2, ou_theta=0.15,\n ou_sigma=0.2, render=None, save_path=None, save_every=10, render_every=10,\n num_trainings=100, exploration_type='action', param_noise_bs=32, train_every=1,\n evaluate_every=2000, run_name='', num_evaluations=1):\n self.writer = writer = SummaryWriter(comment=run_name)\n self.env = env\n self.actor = actor_model\n self.actor_target = actor_model.clone()\n self.critic = critic_model\n self.critic_target = critic_model.clone()\n if use_cuda:\n for net in [self.actor, self.actor_target, self.critic, self.critic_target]:\n net.cuda()\n self.memory = ReplayMemory(memory)\n self.batch_size = batch_size\n self.gamma = gamma\n self.tau = tau\n if exploration_type == 'action':\n self.exploration = ActionNoiseExploration(self.actor, env, ou_theta, ou_sigma)\n else:\n self.exploration = ParamNoiseExploration(self.actor, param_noise_bs, self.memory)\n self.optim_critic = optim.Adam(self.critic.parameters(), lr=critic_lr,\n weight_decay=critic_decay)\n self.optim_actor = optim.Adam(self.actor.parameters(), lr=actor_lr)\n self.render = render\n self.render_every = render_every\n self.save_path = save_path\n os.makedirs(self.save_path, exist_ok=True)\n self.save_every = save_every\n self.num_trainings = num_trainings\n self.train_every = train_every\n self.evaluate_every = evaluate_every\n self.num_evaluations = num_evaluations\n # state\n self.overall_step = 0\n self.overall_episode_number = 0\n self.running_reward = None\n self.reward_sums = []\n self.eval_reward_sums = []\n self.losses = []\n\n def add_graphs(self, actor, critic):\n sample_state = self.prep_state(np.random.uniform(size=self.env.observation_space.shape))\n sample_action = self.prep_state(np.random.uniform(size=self.env.action_space.shape))\n critic_input = [sample_state, sample_action]\n self.writer.add_graph(self.actor, sample_state)\n self.writer.add_graph(self.critic, critic_input)\n\n def update(self, target, source):\n zipped = zip(target.parameters(), source.parameters())\n for target_param, source_param in zipped:\n updated_param = target_param.data * (1 - self.tau) + \\\n source_param.data * self.tau\n target_param.data.copy_(updated_param)\n\n def train_models(self):\n if len(self.memory) < self.batch_size:\n return None, None\n mini_batch = self.memory.sample_batch(self.batch_size)\n actor_loss = self.train_actor(mini_batch)\n critic_loss = self.train_critic(mini_batch)\n self.update(self.actor_target, self.actor)\n self.update(self.critic_target, self.critic)\n return actor_loss.data[0], critic_loss.data[0]\n\n def mse(self, inputs, targets):\n return torch.mean((inputs - targets)**2)\n\n def train_critic(self, batch):\n # forward pass\n pred_actions = self.actor_target(batch.next_states)\n target_q = batch.rewards + batch.done * self.critic_target([batch.next_states, pred_actions]) * self.gamma\n pred_q = self.critic([batch.states, batch.actions])\n # backward pass\n loss = self.mse(pred_q, target_q)\n self.optim_critic.zero_grad()\n loss.backward(retain_graph=True)\n for param in self.critic.parameters():\n param.grad.data.clamp_(-1, 1)\n self.optim_critic.step()\n return loss\n\n def train_actor(self, batch): \n # forward pass\n pred_mu = self.actor(batch.states)\n pred_q = self.critic([batch.states, pred_mu])\n # backward pass\n loss = -pred_q.mean()\n self.optim_actor.zero_grad()\n loss.backward()\n self.optim_actor.step()\n return loss\n\n def prep_state(self, s):\n return Variable(torch.from_numpy(s).float().unsqueeze(0))\n\n\n def step(self, action):\n next_state, reward, done, _ = self.env.step(action.data.cpu().numpy()[0])\n next_state = self.prep_state(next_state)\n reward = FloatTensor([reward])\n return next_state, reward, done\n\n def warmup(self, num_steps):\n warmup_step = 0\n while warmup_step <= num_steps:\n done = False\n state = self.prep_state(self.env.reset())\n self.exploration.reset()\n while not done:\n warmup_step += 1\n action = self.exploration.select_action(state)\n next_state, reward, done = self.step(action)\n self.memory.add(state, action, reward, next_state, done)\n state = next_state\n\n def train(self, num_steps):\n simulation_step = 0 \n train_step = 0\n evaluation_num = 0\n\n while num_steps == None or simulation_step <= num_steps:\n self.overall_episode_number += 1\n done = False\n state = self.prep_state(self.env.reset())\n reward_sum = 0\n self.exploration.reset()\n while not done:\n self.overall_step += 1\n simulation_step += 1\n action = self.exploration.select_action(state)\n next_state, reward, done = self.step(action)\n self.memory.add(state, action, reward, next_state, done)\n state = next_state\n reward_sum += reward[0]\n if simulation_step % self.train_every == 0 and len(self.memory) >= self.batch_size:\n for _ in range(self.num_trainings):\n train_step += 1\n actor_loss, critic_loss = self.train_models()\n self.losses.append([actor_loss, critic_loss])\n self.writer.add_scalar('critic_loss', critic_loss, train_step)\n self.writer.add_scalar('actor_loss', actor_loss, train_step)\n if simulation_step % self.evaluate_every == 0:\n rewards = []\n for _ in range(self.num_evaluations):\n render_this_episode = self.render and (evaluation_num % self.render_every == 0)\n evaluation_reward = self.actor.run(self.env, render=render_this_episode)\n rewards.append(evaluation_reward)\n evaluation_num += 1\n evaluation_reward = np.mean(rewards)\n self.eval_reward_sums.append(evaluation_reward)\n msg = '---------- eval_episode: {} steps: {} eval reward: {:.4f}'\n print(msg.format(simulation_step // self.evaluate_every, self.overall_step, evaluation_reward))\n self.writer.add_scalar('eval_reward', evaluation_reward, self.overall_step)\n\n self.reward_sums.append(reward_sum)\n self.running_reward = reward_sum if self.running_reward is None \\\n else self.running_reward * 0.99 + reward_sum * 0.01\n self.writer.add_scalar('train_reward', reward_sum, self.overall_step)\n\n if self.save_path is not None and (self.overall_episode_number % self.save_every == 0):\n self.save(self.save_path)\n\n msg = 'episode: {} steps: {} running train reward: {:.4f}'\n print(msg.format(self.overall_episode_number, self.overall_step, self.running_reward))\n\n if self.save_path is not None:\n self.save(self.save_path)\n return self.reward_sums, self.eval_reward_sums, self.losses\n\n def load_state(self, path):\n filename = os.path.join(path, 'ddpg_state.pkl')\n with open(filename, 'rb') as f:\n state = pickle.load(f)\n self.__dict__.update(state)\n\n def load_memory(self, path):\n self.memory.load(path)\n\n def load_optim_dicts(self, path):\n critic_filename = os.path.join(path, 'critic.optim')\n actor_filename = os.path.join(path, 'actor.optim')\n self.optim_critic.load_state_dict(torch.load(critic_filename, map_location=lambda storage, loc: storage))\n self.optim_actor.load_state_dict(torch.load(actor_filename, map_location=lambda storage, loc: storage))\n\n def save(self, path):\n self.save_models(path)\n self.save_results(path, self.losses, self.reward_sums, self.eval_reward_sums)\n self.save_memory(path)\n self.save_optim_dicts(path)\n self.save_state(path)\n\n def save_optim_dicts(self, path):\n critic_filename = os.path.join(path, 'critic.optim')\n actor_filename = os.path.join(path, 'actor.optim')\n torch.save(self.optim_critic.state_dict(), critic_filename)\n torch.save(self.optim_actor.state_dict(), actor_filename)\n\n def save_state(self, path):\n params = ['overall_step', 'overall_episode_number', 'running_reward', 'reward_sums', 'losses']\n state = dict([(k, v) for k, v in self.__dict__.items() if k in params])\n filename = os.path.join(path, 'ddpg_state.pkl')\n with open(filename, 'wb') as f:\n pickle.dump(state, f)\n\n def save_models(self, path):\n self.actor.save(path)\n self.critic.save(path)\n\n def save_results(self, path, losses, train_rewards, eval_rewards):\n losses = np.array([l for l in losses if l[0] is not None])\n train_rewards, eval_rewards = np.array(train_rewards), np.array(eval_rewards)\n np.savetxt(os.path.join(path, 'losses.csv'), losses, delimiter=',', header='critic,actor', comments='')\n np.savetxt(os.path.join(path, 'train_rewards.csv'), train_rewards, delimiter=',')\n np.savetxt(os.path.join(path, 'eval_rewards.csv'), eval_rewards, delimiter=',')\n\n def save_memory(self, path):\n self.memory.save(path)\n"
] |
[
[
"torch.mean",
"torch.load",
"torch.from_numpy",
"numpy.mean",
"torch.cuda.is_available",
"numpy.random.uniform",
"numpy.array"
]
] |
NolanMP/statsmodels
|
[
"ca6b652188be2422061052f7e61dd7bf2da03d52"
] |
[
"statsmodels/regression/linear_model.py"
] |
[
"# TODO: Determine which tests are valid for GLSAR, and under what conditions\n# TODO: Fix issue with constant and GLS\n# TODO: GLS: add options Iterative GLS, for iterative fgls if sigma is None\n# TODO: GLS: default if sigma is none should be two-step GLS\n# TODO: Check nesting when performing model based tests, lr, wald, lm\n\"\"\"\nThis module implements standard regression models:\n\nGeneralized Least Squares (GLS)\nOrdinary Least Squares (OLS)\nWeighted Least Squares (WLS)\nGeneralized Least Squares with autoregressive error terms GLSAR(p)\n\nModels are specified with an endogenous response variable and an\nexogenous design matrix and are fit using their `fit` method.\n\nSubclasses that have more complicated covariance matrices\nshould write over the 'whiten' method as the fit method\nprewhitens the response by calling 'whiten'.\n\nGeneral reference for regression models:\n\nD. C. Montgomery and E.A. Peck. \"Introduction to Linear Regression\n Analysis.\" 2nd. Ed., Wiley, 1992.\n\nEconometrics references for regression models:\n\nR. Davidson and J.G. MacKinnon. \"Econometric Theory and Methods,\" Oxford,\n 2004.\n\nW. Green. \"Econometric Analysis,\" 5th ed., Pearson, 2003.\n\"\"\"\n\n\nfrom statsmodels.compat.python import lrange, lzip\nfrom statsmodels.compat.pandas import Appender\n\nimport numpy as np\nfrom scipy.linalg import toeplitz\nfrom scipy import stats\nfrom scipy import optimize\n\nfrom statsmodels.tools.tools import pinv_extended\nfrom statsmodels.tools.decorators import (cache_readonly,\n cache_writable)\nimport statsmodels.base.model as base\nimport statsmodels.base.wrapper as wrap\nfrom statsmodels.emplike.elregress import _ELRegOpts\nimport warnings\nfrom statsmodels.tools.sm_exceptions import InvalidTestWarning\nfrom statsmodels.tools.validation import string_like\n# need import in module instead of lazily to copy `__doc__`\nfrom statsmodels.regression._prediction import PredictionResults\nfrom . import _prediction as pred\n\n__docformat__ = 'restructuredtext en'\n\n__all__ = ['GLS', 'WLS', 'OLS', 'GLSAR', 'PredictionResults',\n 'RegressionResultsWrapper']\n\n\n_fit_regularized_doc =\\\n r\"\"\"\n Return a regularized fit to a linear regression model.\n\n Parameters\n ----------\n method : str\n Either 'elastic_net' or 'sqrt_lasso'.\n alpha : scalar or array_like\n The penalty weight. If a scalar, the same penalty weight\n applies to all variables in the model. If a vector, it\n must have the same length as `params`, and contains a\n penalty weight for each coefficient.\n L1_wt : scalar\n The fraction of the penalty given to the L1 penalty term.\n Must be between 0 and 1 (inclusive). If 0, the fit is a\n ridge fit, if 1 it is a lasso fit.\n start_params : array_like\n Starting values for ``params``.\n profile_scale : bool\n If True the penalized fit is computed using the profile\n (concentrated) log-likelihood for the Gaussian model.\n Otherwise the fit uses the residual sum of squares.\n refit : bool\n If True, the model is refit using only the variables that\n have non-zero coefficients in the regularized fit. The\n refitted model is not regularized.\n **kwargs\n Additional keyword arguments that contain information used when\n constructing a model using the formula interface.\n\n Returns\n -------\n statsmodels.base.elastic_net.RegularizedResults\n The regularized results.\n\n Notes\n -----\n The elastic net uses a combination of L1 and L2 penalties.\n The implementation closely follows the glmnet package in R.\n\n The function that is minimized is:\n\n .. math::\n\n 0.5*RSS/n + alpha*((1-L1\\_wt)*|params|_2^2/2 + L1\\_wt*|params|_1)\n\n where RSS is the usual regression sum of squares, n is the\n sample size, and :math:`|*|_1` and :math:`|*|_2` are the L1 and L2\n norms.\n\n For WLS and GLS, the RSS is calculated using the whitened endog and\n exog data.\n\n Post-estimation results are based on the same data used to\n select variables, hence may be subject to overfitting biases.\n\n The elastic_net method uses the following keyword arguments:\n\n maxiter : int\n Maximum number of iterations\n cnvrg_tol : float\n Convergence threshold for line searches\n zero_tol : float\n Coefficients below this threshold are treated as zero.\n\n The square root lasso approach is a variation of the Lasso\n that is largely self-tuning (the optimal tuning parameter\n does not depend on the standard deviation of the regression\n errors). If the errors are Gaussian, the tuning parameter\n can be taken to be\n\n alpha = 1.1 * np.sqrt(n) * norm.ppf(1 - 0.05 / (2 * p))\n\n where n is the sample size and p is the number of predictors.\n\n The square root lasso uses the following keyword arguments:\n\n zero_tol : float\n Coefficients below this threshold are treated as zero.\n\n The cvxopt module is required to estimate model using the square root\n lasso.\n\n References\n ----------\n .. [*] Friedman, Hastie, Tibshirani (2008). Regularization paths for\n generalized linear models via coordinate descent. Journal of\n Statistical Software 33(1), 1-22 Feb 2010.\n\n .. [*] A Belloni, V Chernozhukov, L Wang (2011). Square-root Lasso:\n pivotal recovery of sparse signals via conic programming.\n Biometrika 98(4), 791-806. https://arxiv.org/pdf/1009.5689.pdf\n \"\"\"\n\n\ndef _get_sigma(sigma, nobs):\n \"\"\"\n Returns sigma (matrix, nobs by nobs) for GLS and the inverse of its\n Cholesky decomposition. Handles dimensions and checks integrity.\n If sigma is None, returns None, None. Otherwise returns sigma,\n cholsigmainv.\n \"\"\"\n if sigma is None:\n return None, None\n sigma = np.asarray(sigma).squeeze()\n if sigma.ndim == 0:\n sigma = np.repeat(sigma, nobs)\n if sigma.ndim == 1:\n if sigma.shape != (nobs,):\n raise ValueError(\"Sigma must be a scalar, 1d of length %s or a 2d \"\n \"array of shape %s x %s\" % (nobs, nobs, nobs))\n cholsigmainv = 1/np.sqrt(sigma)\n else:\n if sigma.shape != (nobs, nobs):\n raise ValueError(\"Sigma must be a scalar, 1d of length %s or a 2d \"\n \"array of shape %s x %s\" % (nobs, nobs, nobs))\n cholsigmainv = np.linalg.cholesky(np.linalg.inv(sigma)).T\n return sigma, cholsigmainv\n\n\nclass RegressionModel(base.LikelihoodModel):\n \"\"\"\n Base class for linear regression models. Should not be directly called.\n\n Intended for subclassing.\n \"\"\"\n def __init__(self, endog, exog, **kwargs):\n super(RegressionModel, self).__init__(endog, exog, **kwargs)\n self._data_attr.extend(['pinv_wexog', 'weights'])\n\n def initialize(self):\n \"\"\"Initialize model components.\"\"\"\n self.wexog = self.whiten(self.exog)\n self.wendog = self.whiten(self.endog)\n # overwrite nobs from class Model:\n self.nobs = float(self.wexog.shape[0])\n\n self._df_model = None\n self._df_resid = None\n self.rank = None\n\n @property\n def df_model(self):\n \"\"\"\n The model degree of freedom.\n\n The dof is defined as the rank of the regressor matrix minus 1 if a\n constant is included.\n \"\"\"\n if self._df_model is None:\n if self.rank is None:\n self.rank = np.linalg.matrix_rank(self.exog)\n self._df_model = float(self.rank - self.k_constant)\n return self._df_model\n\n @df_model.setter\n def df_model(self, value):\n self._df_model = value\n\n @property\n def df_resid(self):\n \"\"\"\n The residual degree of freedom.\n\n The dof is defined as the number of observations minus the rank of\n the regressor matrix.\n \"\"\"\n\n if self._df_resid is None:\n if self.rank is None:\n self.rank = np.linalg.matrix_rank(self.exog)\n self._df_resid = self.nobs - self.rank\n return self._df_resid\n\n @df_resid.setter\n def df_resid(self, value):\n self._df_resid = value\n\n def whiten(self, x):\n \"\"\"\n Whiten method that must be overwritten by individual models.\n\n Parameters\n ----------\n x : array_like\n Data to be whitened.\n \"\"\"\n raise NotImplementedError(\"Subclasses must implement.\")\n\n def fit(self, method=\"pinv\", cov_type='nonrobust', cov_kwds=None,\n use_t=None, **kwargs):\n \"\"\"\n Full fit of the model.\n\n The results include an estimate of covariance matrix, (whitened)\n residuals and an estimate of scale.\n\n Parameters\n ----------\n method : str, optional\n Can be \"pinv\", \"qr\". \"pinv\" uses the Moore-Penrose pseudoinverse\n to solve the least squares problem. \"qr\" uses the QR\n factorization.\n cov_type : str, optional\n See `regression.linear_model.RegressionResults` for a description\n of the available covariance estimators.\n cov_kwds : list or None, optional\n See `linear_model.RegressionResults.get_robustcov_results` for a\n description required keywords for alternative covariance\n estimators.\n use_t : bool, optional\n Flag indicating to use the Student's t distribution when computing\n p-values. Default behavior depends on cov_type. See\n `linear_model.RegressionResults.get_robustcov_results` for\n implementation details.\n **kwargs\n Additional keyword arguments that contain information used when\n constructing a model using the formula interface.\n\n Returns\n -------\n RegressionResults\n The model estimation results.\n\n See Also\n --------\n RegressionResults\n The results container.\n RegressionResults.get_robustcov_results\n A method to change the covariance estimator used when fitting the\n model.\n\n Notes\n -----\n The fit method uses the pseudoinverse of the design/exogenous variables\n to solve the least squares minimization.\n \"\"\"\n if method == \"pinv\":\n if not (hasattr(self, 'pinv_wexog') and\n hasattr(self, 'normalized_cov_params') and\n hasattr(self, 'rank')):\n\n self.pinv_wexog, singular_values = pinv_extended(self.wexog)\n self.normalized_cov_params = np.dot(\n self.pinv_wexog, np.transpose(self.pinv_wexog))\n\n # Cache these singular values for use later.\n self.wexog_singular_values = singular_values\n self.rank = np.linalg.matrix_rank(np.diag(singular_values))\n\n beta = np.dot(self.pinv_wexog, self.wendog)\n\n elif method == \"qr\":\n if not (hasattr(self, 'exog_Q') and\n hasattr(self, 'exog_R') and\n hasattr(self, 'normalized_cov_params') and\n hasattr(self, 'rank')):\n Q, R = np.linalg.qr(self.wexog)\n self.exog_Q, self.exog_R = Q, R\n self.normalized_cov_params = np.linalg.inv(np.dot(R.T, R))\n\n # Cache singular values from R.\n self.wexog_singular_values = np.linalg.svd(R, 0, 0)\n self.rank = np.linalg.matrix_rank(R)\n else:\n Q, R = self.exog_Q, self.exog_R\n\n # used in ANOVA\n self.effects = effects = np.dot(Q.T, self.wendog)\n beta = np.linalg.solve(R, effects)\n else:\n raise ValueError('method has to be \"pinv\" or \"qr\"')\n\n if self._df_model is None:\n self._df_model = float(self.rank - self.k_constant)\n if self._df_resid is None:\n self.df_resid = self.nobs - self.rank\n\n if isinstance(self, OLS):\n lfit = OLSResults(\n self, beta,\n normalized_cov_params=self.normalized_cov_params,\n cov_type=cov_type, cov_kwds=cov_kwds, use_t=use_t)\n else:\n lfit = RegressionResults(\n self, beta,\n normalized_cov_params=self.normalized_cov_params,\n cov_type=cov_type, cov_kwds=cov_kwds, use_t=use_t,\n **kwargs)\n return RegressionResultsWrapper(lfit)\n\n def predict(self, params, exog=None):\n \"\"\"\n Return linear predicted values from a design matrix.\n\n Parameters\n ----------\n params : array_like\n Parameters of a linear model.\n exog : array_like, optional\n Design / exogenous data. Model exog is used if None.\n\n Returns\n -------\n array_like\n An array of fitted values.\n\n Notes\n -----\n If the model has not yet been fit, params is not optional.\n \"\"\"\n # JP: this does not look correct for GLMAR\n # SS: it needs its own predict method\n\n if exog is None:\n exog = self.exog\n\n return np.dot(exog, params)\n\n def get_distribution(self, params, scale, exog=None, dist_class=None):\n \"\"\"\n Construct a random number generator for the predictive distribution.\n\n Parameters\n ----------\n params : array_like\n The model parameters (regression coefficients).\n scale : scalar\n The variance parameter.\n exog : array_like\n The predictor variable matrix.\n dist_class : class\n A random number generator class. Must take 'loc' and 'scale'\n as arguments and return a random number generator implementing\n an ``rvs`` method for simulating random values. Defaults to normal.\n\n Returns\n -------\n gen\n Frozen random number generator object with mean and variance\n determined by the fitted linear model. Use the ``rvs`` method\n to generate random values.\n\n Notes\n -----\n Due to the behavior of ``scipy.stats.distributions objects``,\n the returned random number generator must be called with\n ``gen.rvs(n)`` where ``n`` is the number of observations in\n the data set used to fit the model. If any other value is\n used for ``n``, misleading results will be produced.\n \"\"\"\n fit = self.predict(params, exog)\n if dist_class is None:\n from scipy.stats.distributions import norm\n dist_class = norm\n gen = dist_class(loc=fit, scale=np.sqrt(scale))\n return gen\n\n\nclass GLS(RegressionModel):\n __doc__ = r\"\"\"\n Generalized Least Squares\n\n %(params)s\n sigma : scalar or array\n The array or scalar `sigma` is the weighting matrix of the covariance.\n The default is None for no scaling. If `sigma` is a scalar, it is\n assumed that `sigma` is an n x n diagonal matrix with the given\n scalar, `sigma` as the value of each diagonal element. If `sigma`\n is an n-length vector, then `sigma` is assumed to be a diagonal\n matrix with the given `sigma` on the diagonal. This should be the\n same as WLS.\n %(extra_params)s\n\n Attributes\n ----------\n pinv_wexog : ndarray\n `pinv_wexog` is the p x n Moore-Penrose pseudoinverse of `wexog`.\n cholsimgainv : ndarray\n The transpose of the Cholesky decomposition of the pseudoinverse.\n df_model : float\n p - 1, where p is the number of regressors including the intercept.\n of freedom.\n df_resid : float\n Number of observations n less the number of parameters p.\n llf : float\n The value of the likelihood function of the fitted model.\n nobs : float\n The number of observations n.\n normalized_cov_params : ndarray\n p x p array :math:`(X^{T}\\Sigma^{-1}X)^{-1}`\n results : RegressionResults instance\n A property that returns the RegressionResults class if fit.\n sigma : ndarray\n `sigma` is the n x n covariance structure of the error terms.\n wexog : ndarray\n Design matrix whitened by `cholsigmainv`\n wendog : ndarray\n Response variable whitened by `cholsigmainv`\n\n See Also\n --------\n WLS : Fit a linear model using Weighted Least Squares.\n OLS : Fit a linear model using Ordinary Least Squares.\n\n Notes\n -----\n If sigma is a function of the data making one of the regressors\n a constant, then the current postestimation statistics will not be correct.\n\n Examples\n --------\n >>> import statsmodels.api as sm\n >>> data = sm.datasets.longley.load(as_pandas=False)\n >>> data.exog = sm.add_constant(data.exog)\n >>> ols_resid = sm.OLS(data.endog, data.exog).fit().resid\n >>> res_fit = sm.OLS(ols_resid[1:], ols_resid[:-1]).fit()\n >>> rho = res_fit.params\n\n `rho` is a consistent estimator of the correlation of the residuals from\n an OLS fit of the longley data. It is assumed that this is the true rho\n of the AR process data.\n\n >>> from scipy.linalg import toeplitz\n >>> order = toeplitz(np.arange(16))\n >>> sigma = rho**order\n\n `sigma` is an n x n matrix of the autocorrelation structure of the\n data.\n\n >>> gls_model = sm.GLS(data.endog, data.exog, sigma=sigma)\n >>> gls_results = gls_model.fit()\n >>> print(gls_results.summary())\n \"\"\" % {'params': base._model_params_doc,\n 'extra_params': base._missing_param_doc + base._extra_param_doc}\n\n def __init__(self, endog, exog, sigma=None, missing='none', hasconst=None,\n **kwargs):\n # TODO: add options igls, for iterative fgls if sigma is None\n # TODO: default if sigma is none should be two-step GLS\n sigma, cholsigmainv = _get_sigma(sigma, len(endog))\n\n super(GLS, self).__init__(endog, exog, missing=missing,\n hasconst=hasconst, sigma=sigma,\n cholsigmainv=cholsigmainv, **kwargs)\n\n # store attribute names for data arrays\n self._data_attr.extend(['sigma', 'cholsigmainv'])\n\n def whiten(self, x):\n \"\"\"\n GLS whiten method.\n\n Parameters\n ----------\n x : array_like\n Data to be whitened.\n\n Returns\n -------\n ndarray\n The value np.dot(cholsigmainv,X).\n\n See Also\n --------\n GLS : Fit a linear model using Generalized Least Squares.\n \"\"\"\n x = np.asarray(x)\n if self.sigma is None or self.sigma.shape == ():\n return x\n elif self.sigma.ndim == 1:\n if x.ndim == 1:\n return x * self.cholsigmainv\n else:\n return x * self.cholsigmainv[:, None]\n else:\n return np.dot(self.cholsigmainv, x)\n\n def loglike(self, params):\n r\"\"\"\n Compute the value of the Gaussian log-likelihood function at params.\n\n Given the whitened design matrix, the log-likelihood is evaluated\n at the parameter vector `params` for the dependent variable `endog`.\n\n Parameters\n ----------\n params : array_like\n The model parameters.\n\n Returns\n -------\n float\n The value of the log-likelihood function for a GLS Model.\n\n Notes\n -----\n The log-likelihood function for the normal distribution is\n\n .. math:: -\\frac{n}{2}\\log\\left(\\left(Y-\\hat{Y}\\right)^{\\prime}\n \\left(Y-\\hat{Y}\\right)\\right)\n -\\frac{n}{2}\\left(1+\\log\\left(\\frac{2\\pi}{n}\\right)\\right)\n -\\frac{1}{2}\\log\\left(\\left|\\Sigma\\right|\\right)\n\n Y and Y-hat are whitened.\n \"\"\"\n # TODO: combine this with OLS/WLS loglike and add _det_sigma argument\n nobs2 = self.nobs / 2.0\n SSR = np.sum((self.wendog - np.dot(self.wexog, params))**2, axis=0)\n llf = -np.log(SSR) * nobs2 # concentrated likelihood\n llf -= (1+np.log(np.pi/nobs2))*nobs2 # with likelihood constant\n if np.any(self.sigma):\n # FIXME: robust-enough check? unneeded if _det_sigma gets defined\n if self.sigma.ndim == 2:\n det = np.linalg.slogdet(self.sigma)\n llf -= .5*det[1]\n else:\n llf -= 0.5*np.sum(np.log(self.sigma))\n # with error covariance matrix\n return llf\n\n def hessian_factor(self, params, scale=None, observed=True):\n \"\"\"\n Compute weights for calculating Hessian.\n\n Parameters\n ----------\n params : ndarray\n The parameter at which Hessian is evaluated.\n scale : None or float\n If scale is None, then the default scale will be calculated.\n Default scale is defined by `self.scaletype` and set in fit.\n If scale is not None, then it is used as a fixed scale.\n observed : bool\n If True, then the observed Hessian is returned. If false then the\n expected information matrix is returned.\n\n Returns\n -------\n ndarray\n A 1d weight vector used in the calculation of the Hessian.\n The hessian is obtained by `(exog.T * hessian_factor).dot(exog)`.\n \"\"\"\n\n if self.sigma is None or self.sigma.shape == ():\n return np.ones(self.exog.shape[0])\n elif self.sigma.ndim == 1:\n return self.cholsigmainv\n else:\n return np.diag(self.cholsigmainv)\n\n @Appender(_fit_regularized_doc)\n def fit_regularized(self, method=\"elastic_net\", alpha=0.,\n L1_wt=1., start_params=None, profile_scale=False,\n refit=False, **kwargs):\n if not np.isscalar(alpha):\n alpha = np.asarray(alpha)\n # Need to adjust since RSS/n term in elastic net uses nominal\n # n in denominator\n if self.sigma is not None:\n alpha = alpha * np.sum(1 / np.diag(self.sigma)) / len(self.endog)\n\n rslt = OLS(self.wendog, self.wexog).fit_regularized(\n method=method, alpha=alpha,\n L1_wt=L1_wt,\n start_params=start_params,\n profile_scale=profile_scale,\n refit=refit, **kwargs)\n\n from statsmodels.base.elastic_net import (\n RegularizedResults, RegularizedResultsWrapper)\n rrslt = RegularizedResults(self, rslt.params)\n return RegularizedResultsWrapper(rrslt)\n\n\nclass WLS(RegressionModel):\n __doc__ = \"\"\"\n Weighted Least Squares\n\n The weights are presumed to be (proportional to) the inverse of\n the variance of the observations. That is, if the variables are\n to be transformed by 1/sqrt(W) you must supply weights = 1/W.\n\n %(params)s\n weights : array_like, optional\n A 1d array of weights. If you supply 1/W then the variables are\n pre- multiplied by 1/sqrt(W). If no weights are supplied the\n default value is 1 and WLS results are the same as OLS.\n %(extra_params)s\n\n Attributes\n ----------\n weights : ndarray\n The stored weights supplied as an argument.\n\n See Also\n --------\n GLS : Fit a linear model using Generalized Least Squares.\n OLS : Fit a linear model using Ordinary Least Squares.\n\n Notes\n -----\n If the weights are a function of the data, then the post estimation\n statistics such as fvalue and mse_model might not be correct, as the\n package does not yet support no-constant regression.\n\n Examples\n --------\n >>> import statsmodels.api as sm\n >>> Y = [1,3,4,5,2,3,4]\n >>> X = range(1,8)\n >>> X = sm.add_constant(X)\n >>> wls_model = sm.WLS(Y,X, weights=list(range(1,8)))\n >>> results = wls_model.fit()\n >>> results.params\n array([ 2.91666667, 0.0952381 ])\n >>> results.tvalues\n array([ 2.0652652 , 0.35684428])\n >>> print(results.t_test([1, 0]))\n <T test: effect=array([ 2.91666667]), sd=array([[ 1.41224801]]), t=array([[ 2.0652652]]), p=array([[ 0.04690139]]), df_denom=5>\n >>> print(results.f_test([0, 1]))\n <F test: F=array([[ 0.12733784]]), p=[[ 0.73577409]], df_denom=5, df_num=1>\n \"\"\" % {'params': base._model_params_doc,\n 'extra_params': base._missing_param_doc + base._extra_param_doc}\n\n def __init__(self, endog, exog, weights=1., missing='none', hasconst=None,\n **kwargs):\n weights = np.array(weights)\n if weights.shape == ():\n if (missing == 'drop' and 'missing_idx' in kwargs and\n kwargs['missing_idx'] is not None):\n # patsy may have truncated endog\n weights = np.repeat(weights, len(kwargs['missing_idx']))\n else:\n weights = np.repeat(weights, len(endog))\n # handle case that endog might be of len == 1\n if len(weights) == 1:\n weights = np.array([weights.squeeze()])\n else:\n weights = weights.squeeze()\n super(WLS, self).__init__(endog, exog, missing=missing,\n weights=weights, hasconst=hasconst, **kwargs)\n nobs = self.exog.shape[0]\n weights = self.weights\n if weights.size != nobs and weights.shape[0] != nobs:\n raise ValueError('Weights must be scalar or same length as design')\n\n def whiten(self, x):\n \"\"\"\n Whitener for WLS model, multiplies each column by sqrt(self.weights).\n\n Parameters\n ----------\n x : array_like\n Data to be whitened.\n\n Returns\n -------\n array_like\n The whitened values sqrt(weights)*X.\n \"\"\"\n\n x = np.asarray(x)\n if x.ndim == 1:\n return x * np.sqrt(self.weights)\n elif x.ndim == 2:\n return np.sqrt(self.weights)[:, None] * x\n\n def loglike(self, params):\n r\"\"\"\n Compute the value of the gaussian log-likelihood function at params.\n\n Given the whitened design matrix, the log-likelihood is evaluated\n at the parameter vector `params` for the dependent variable `Y`.\n\n Parameters\n ----------\n params : array_like\n The parameter estimates.\n\n Returns\n -------\n float\n The value of the log-likelihood function for a WLS Model.\n\n Notes\n --------\n .. math:: -\\frac{n}{2}\\log SSR\n -\\frac{n}{2}\\left(1+\\log\\left(\\frac{2\\pi}{n}\\right)\\right)\n -\\frac{1}{2}\\log\\left(\\left|W\\right|\\right)\n\n where :math:`W` is a diagonal weight matrix matrix and\n :math:`SSR=\\left(Y-\\hat{Y}\\right)^\\prime W \\left(Y-\\hat{Y}\\right)` is\n the sum of the squared weighted residuals.\n \"\"\"\n nobs2 = self.nobs / 2.0\n SSR = np.sum((self.wendog - np.dot(self.wexog, params))**2, axis=0)\n llf = -np.log(SSR) * nobs2 # concentrated likelihood\n llf -= (1+np.log(np.pi/nobs2))*nobs2 # with constant\n llf += 0.5 * np.sum(np.log(self.weights))\n return llf\n\n def hessian_factor(self, params, scale=None, observed=True):\n \"\"\"\n Compute the weights for calculating the Hessian.\n\n Parameters\n ----------\n params : ndarray\n The parameter at which Hessian is evaluated.\n scale : None or float\n If scale is None, then the default scale will be calculated.\n Default scale is defined by `self.scaletype` and set in fit.\n If scale is not None, then it is used as a fixed scale.\n observed : bool\n If True, then the observed Hessian is returned. If false then the\n expected information matrix is returned.\n\n Returns\n -------\n ndarray\n A 1d weight vector used in the calculation of the Hessian.\n The hessian is obtained by `(exog.T * hessian_factor).dot(exog)`.\n \"\"\"\n\n return self.weights\n\n @Appender(_fit_regularized_doc)\n def fit_regularized(self, method=\"elastic_net\", alpha=0.,\n L1_wt=1., start_params=None, profile_scale=False,\n refit=False, **kwargs):\n # Docstring attached below\n if not np.isscalar(alpha):\n alpha = np.asarray(alpha)\n # Need to adjust since RSS/n in elastic net uses nominal n in\n # denominator\n alpha = alpha * np.sum(self.weights) / len(self.weights)\n\n rslt = OLS(self.wendog, self.wexog).fit_regularized(\n method=method, alpha=alpha,\n L1_wt=L1_wt,\n start_params=start_params,\n profile_scale=profile_scale,\n refit=refit, **kwargs)\n\n from statsmodels.base.elastic_net import (\n RegularizedResults, RegularizedResultsWrapper)\n rrslt = RegularizedResults(self, rslt.params)\n return RegularizedResultsWrapper(rrslt)\n\n\nclass OLS(WLS):\n __doc__ = \"\"\"\n Ordinary Least Squares\n\n %(params)s\n %(extra_params)s\n\n Attributes\n ----------\n weights : scalar\n Has an attribute weights = array(1.0) due to inheritance from WLS.\n\n See Also\n --------\n WLS : Fit a linear model using Weighted Least Squares.\n GLS : Fit a linear model using Generalized Least Squares.\n\n Notes\n -----\n No constant is added by the model unless you are using formulas.\n\n Examples\n --------\n >>> import statsmodels.api as sm\n >>> import numpy as np\n >>> duncan_prestige = sm.datasets.get_rdataset(\"Duncan\", \"carData\")\n >>> Y = duncan_prestige.data['income']\n >>> X = duncan_prestige.data['education']\n >>> X = sm.add_constant(X)\n >>> model = sm.OLS(Y,X)\n >>> results = model.fit()\n >>> results.params\n const 10.603498\n education 0.594859\n dtype: float64\n\n >>> results.tvalues\n const 2.039813\n education 6.892802\n dtype: float64\n\n >>> print(results.t_test([1, 0]))\n Test for Constraints\n ==============================================================================\n coef std err t P>|t| [0.025 0.975]\n ------------------------------------------------------------------------------\n c0 10.6035 5.198 2.040 0.048 0.120 21.087\n ==============================================================================\n\n >>> print(results.f_test(np.identity(2)))\n <F test: F=array([[159.63031026]]), p=1.2607168903696672e-20, df_denom=43, df_num=2>\n \"\"\" % {'params': base._model_params_doc,\n 'extra_params': base._missing_param_doc + base._extra_param_doc}\n\n def __init__(self, endog, exog=None, missing='none', hasconst=None,\n **kwargs):\n super(OLS, self).__init__(endog, exog, missing=missing,\n hasconst=hasconst, **kwargs)\n if \"weights\" in self._init_keys:\n self._init_keys.remove(\"weights\")\n\n def loglike(self, params, scale=None):\n \"\"\"\n The likelihood function for the OLS model.\n\n Parameters\n ----------\n params : array_like\n The coefficients with which to estimate the log-likelihood.\n scale : float or None\n If None, return the profile (concentrated) log likelihood\n (profiled over the scale parameter), else return the\n log-likelihood using the given scale value.\n\n Returns\n -------\n float\n The likelihood function evaluated at params.\n \"\"\"\n nobs2 = self.nobs / 2.0\n nobs = float(self.nobs)\n resid = self.endog - np.dot(self.exog, params)\n if hasattr(self, 'offset'):\n resid -= self.offset\n ssr = np.sum(resid**2)\n if scale is None:\n # profile log likelihood\n llf = -nobs2*np.log(2*np.pi) - nobs2*np.log(ssr / nobs) - nobs2\n else:\n # log-likelihood\n llf = -nobs2 * np.log(2 * np.pi * scale) - ssr / (2*scale)\n return llf\n\n def whiten(self, x):\n \"\"\"\n OLS model whitener does nothing.\n\n Parameters\n ----------\n x : array_like\n Data to be whitened.\n\n Returns\n -------\n array_like\n The input array unmodified.\n\n See Also\n --------\n OLS : Fit a linear model using Ordinary Least Squares.\n \"\"\"\n return x\n\n def score(self, params, scale=None):\n \"\"\"\n Evaluate the score function at a given point.\n\n The score corresponds to the profile (concentrated)\n log-likelihood in which the scale parameter has been profiled\n out.\n\n Parameters\n ----------\n params : array_like\n The parameter vector at which the score function is\n computed.\n scale : float or None\n If None, return the profile (concentrated) log likelihood\n (profiled over the scale parameter), else return the\n log-likelihood using the given scale value.\n\n Returns\n -------\n ndarray\n The score vector.\n \"\"\"\n\n if not hasattr(self, \"_wexog_xprod\"):\n self._setup_score_hess()\n\n xtxb = np.dot(self._wexog_xprod, params)\n sdr = -self._wexog_x_wendog + xtxb\n\n if scale is None:\n ssr = self._wendog_xprod - 2 * np.dot(self._wexog_x_wendog.T,\n params)\n ssr += np.dot(params, xtxb)\n return -self.nobs * sdr / ssr\n else:\n return -sdr / scale\n\n def _setup_score_hess(self):\n y = self.wendog\n if hasattr(self, 'offset'):\n y = y - self.offset\n self._wendog_xprod = np.sum(y * y)\n self._wexog_xprod = np.dot(self.wexog.T, self.wexog)\n self._wexog_x_wendog = np.dot(self.wexog.T, y)\n\n def hessian(self, params, scale=None):\n \"\"\"\n Evaluate the Hessian function at a given point.\n\n Parameters\n ----------\n params : array_like\n The parameter vector at which the Hessian is computed.\n scale : float or None\n If None, return the profile (concentrated) log likelihood\n (profiled over the scale parameter), else return the\n log-likelihood using the given scale value.\n\n Returns\n -------\n ndarray\n The Hessian matrix.\n \"\"\"\n\n if not hasattr(self, \"_wexog_xprod\"):\n self._setup_score_hess()\n\n xtxb = np.dot(self._wexog_xprod, params)\n\n if scale is None:\n ssr = self._wendog_xprod - 2 * np.dot(self._wexog_x_wendog.T,\n params)\n ssr += np.dot(params, xtxb)\n ssrp = -2*self._wexog_x_wendog + 2*xtxb\n hm = self._wexog_xprod / ssr - np.outer(ssrp, ssrp) / ssr**2\n return -self.nobs * hm / 2\n else:\n return -self._wexog_xprod / scale\n\n def hessian_factor(self, params, scale=None, observed=True):\n \"\"\"\n Calculate the weights for the Hessian.\n\n Parameters\n ----------\n params : ndarray\n The parameter at which Hessian is evaluated.\n scale : None or float\n If scale is None, then the default scale will be calculated.\n Default scale is defined by `self.scaletype` and set in fit.\n If scale is not None, then it is used as a fixed scale.\n observed : bool\n If True, then the observed Hessian is returned. If false then the\n expected information matrix is returned.\n\n Returns\n -------\n ndarray\n A 1d weight vector used in the calculation of the Hessian.\n The hessian is obtained by `(exog.T * hessian_factor).dot(exog)`.\n \"\"\"\n\n return np.ones(self.exog.shape[0])\n\n @Appender(_fit_regularized_doc)\n def fit_regularized(self, method=\"elastic_net\", alpha=0.,\n L1_wt=1., start_params=None, profile_scale=False,\n refit=False, **kwargs):\n\n # In the future we could add support for other penalties, e.g. SCAD.\n if method not in (\"elastic_net\", \"sqrt_lasso\"):\n msg = \"Unknown method '%s' for fit_regularized\" % method\n raise ValueError(msg)\n\n # Set default parameters.\n defaults = {\"maxiter\": 50, \"cnvrg_tol\": 1e-10,\n \"zero_tol\": 1e-8}\n defaults.update(kwargs)\n\n if method == \"sqrt_lasso\":\n from statsmodels.base.elastic_net import (\n RegularizedResults, RegularizedResultsWrapper\n )\n params = self._sqrt_lasso(alpha, refit, defaults[\"zero_tol\"])\n results = RegularizedResults(self, params)\n return RegularizedResultsWrapper(results)\n\n from statsmodels.base.elastic_net import fit_elasticnet\n\n if L1_wt == 0:\n return self._fit_ridge(alpha)\n\n # If a scale parameter is passed in, the non-profile\n # likelihood (residual sum of squares divided by -2) is used,\n # otherwise the profile likelihood is used.\n if profile_scale:\n loglike_kwds = {}\n score_kwds = {}\n hess_kwds = {}\n else:\n loglike_kwds = {\"scale\": 1}\n score_kwds = {\"scale\": 1}\n hess_kwds = {\"scale\": 1}\n\n return fit_elasticnet(self, method=method,\n alpha=alpha,\n L1_wt=L1_wt,\n start_params=start_params,\n loglike_kwds=loglike_kwds,\n score_kwds=score_kwds,\n hess_kwds=hess_kwds,\n refit=refit,\n check_step=False,\n **defaults)\n\n def _sqrt_lasso(self, alpha, refit, zero_tol):\n\n try:\n import cvxopt\n except ImportError:\n msg = 'sqrt_lasso fitting requires the cvxopt module'\n raise ValueError(msg)\n\n n = len(self.endog)\n p = self.exog.shape[1]\n\n h0 = cvxopt.matrix(0., (2*p+1, 1))\n h1 = cvxopt.matrix(0., (n+1, 1))\n h1[1:, 0] = cvxopt.matrix(self.endog, (n, 1))\n\n G0 = cvxopt.spmatrix([], [], [], (2*p+1, 2*p+1))\n for i in range(1, 2*p+1):\n G0[i, i] = -1\n G1 = cvxopt.matrix(0., (n+1, 2*p+1))\n G1[0, 0] = -1\n G1[1:, 1:p+1] = self.exog\n G1[1:, p+1:] = -self.exog\n\n c = cvxopt.matrix(alpha / n, (2*p + 1, 1))\n c[0] = 1 / np.sqrt(n)\n\n from cvxopt import solvers\n solvers.options[\"show_progress\"] = False\n\n rslt = solvers.socp(c, Gl=G0, hl=h0, Gq=[G1], hq=[h1])\n x = np.asarray(rslt['x']).flat\n bp = x[1:p+1]\n bn = x[p+1:]\n params = bp - bn\n\n if not refit:\n return params\n\n ii = np.flatnonzero(np.abs(params) > zero_tol)\n rfr = OLS(self.endog, self.exog[:, ii]).fit()\n params *= 0\n params[ii] = rfr.params\n\n return params\n\n def _fit_ridge(self, alpha):\n \"\"\"\n Fit a linear model using ridge regression.\n\n Parameters\n ----------\n alpha : scalar or array_like\n The penalty weight. If a scalar, the same penalty weight\n applies to all variables in the model. If a vector, it\n must have the same length as `params`, and contains a\n penalty weight for each coefficient.\n\n Notes\n -----\n Equivalent to fit_regularized with L1_wt = 0 (but implemented\n more efficiently).\n \"\"\"\n\n u, s, vt = np.linalg.svd(self.exog, 0)\n v = vt.T\n q = np.dot(u.T, self.endog) * s\n s2 = s * s\n if np.isscalar(alpha):\n sd = s2 + alpha * self.nobs\n params = q / sd\n params = np.dot(v, params)\n else:\n alpha = np.asarray(alpha)\n vtav = self.nobs * np.dot(vt, alpha[:, None] * v)\n d = np.diag(vtav) + s2\n np.fill_diagonal(vtav, d)\n r = np.linalg.solve(vtav, q)\n params = np.dot(v, r)\n\n from statsmodels.base.elastic_net import RegularizedResults\n return RegularizedResults(self, params)\n\n\nclass GLSAR(GLS):\n __doc__ = \"\"\"\n Generalized Least Squares with AR covariance structure\n\n %(params)s\n rho : int\n The order of the autoregressive covariance.\n %(extra_params)s\n\n Notes\n -----\n GLSAR is considered to be experimental.\n The linear autoregressive process of order p--AR(p)--is defined as:\n TODO\n\n Examples\n --------\n >>> import statsmodels.api as sm\n >>> X = range(1,8)\n >>> X = sm.add_constant(X)\n >>> Y = [1,3,4,5,8,10,9]\n >>> model = sm.GLSAR(Y, X, rho=2)\n >>> for i in range(6):\n ... results = model.fit()\n ... print(\"AR coefficients: {0}\".format(model.rho))\n ... rho, sigma = sm.regression.yule_walker(results.resid,\n ... order=model.order)\n ... model = sm.GLSAR(Y, X, rho)\n ...\n AR coefficients: [ 0. 0.]\n AR coefficients: [-0.52571491 -0.84496178]\n AR coefficients: [-0.6104153 -0.86656458]\n AR coefficients: [-0.60439494 -0.857867 ]\n AR coefficients: [-0.6048218 -0.85846157]\n AR coefficients: [-0.60479146 -0.85841922]\n >>> results.params\n array([-0.66661205, 1.60850853])\n >>> results.tvalues\n array([ -2.10304127, 21.8047269 ])\n >>> print(results.t_test([1, 0]))\n <T test: effect=array([-0.66661205]), sd=array([[ 0.31697526]]), t=array([[-2.10304127]]), p=array([[ 0.06309969]]), df_denom=3>\n >>> print(results.f_test(np.identity(2)))\n <F test: F=array([[ 1815.23061844]]), p=[[ 0.00002372]], df_denom=3, df_num=2>\n\n Or, equivalently\n\n >>> model2 = sm.GLSAR(Y, X, rho=2)\n >>> res = model2.iterative_fit(maxiter=6)\n >>> model2.rho\n array([-0.60479146, -0.85841922])\n \"\"\" % {'params': base._model_params_doc,\n 'extra_params': base._missing_param_doc + base._extra_param_doc}\n # TODO: Complete docstring\n\n def __init__(self, endog, exog=None, rho=1, missing='none', hasconst=None,\n **kwargs):\n # this looks strange, interpreting rho as order if it is int\n if isinstance(rho, (int, np.integer)):\n self.order = int(rho)\n self.rho = np.zeros(self.order, np.float64)\n else:\n self.rho = np.squeeze(np.asarray(rho))\n if len(self.rho.shape) not in [0, 1]:\n raise ValueError(\"AR parameters must be a scalar or a vector\")\n if self.rho.shape == ():\n self.rho.shape = (1,)\n self.order = self.rho.shape[0]\n if exog is None:\n # JP this looks wrong, should be a regression on constant\n # results for rho estimate now identical to yule-walker on y\n # super(AR, self).__init__(endog, add_constant(endog))\n super(GLSAR, self).__init__(endog, np.ones((endog.shape[0], 1)),\n missing=missing, hasconst=None,\n **kwargs)\n else:\n super(GLSAR, self).__init__(endog, exog, missing=missing,\n **kwargs)\n\n def iterative_fit(self, maxiter=3, rtol=1e-4, **kwargs):\n \"\"\"\n Perform an iterative two-stage procedure to estimate a GLS model.\n\n The model is assumed to have AR(p) errors, AR(p) parameters and\n regression coefficients are estimated iteratively.\n\n Parameters\n ----------\n maxiter : int, optional\n The number of iterations.\n rtol : float, optional\n Relative tolerance between estimated coefficients to stop the\n estimation. Stops if max(abs(last - current) / abs(last)) < rtol.\n **kwargs\n Additional keyword arguments passed to `fit`.\n\n Returns\n -------\n RegressionResults\n The results computed using an iterative fit.\n \"\"\"\n # TODO: update this after going through example.\n converged = False\n i = -1 # need to initialize for maxiter < 1 (skip loop)\n history = {'params': [], 'rho': [self.rho]}\n for i in range(maxiter - 1):\n if hasattr(self, 'pinv_wexog'):\n del self.pinv_wexog\n self.initialize()\n results = self.fit()\n history['params'].append(results.params)\n if i == 0:\n last = results.params\n else:\n diff = np.max(np.abs(last - results.params) / np.abs(last))\n if diff < rtol:\n converged = True\n break\n last = results.params\n self.rho, _ = yule_walker(results.resid,\n order=self.order, df=None)\n history['rho'].append(self.rho)\n\n # why not another call to self.initialize\n # Use kwarg to insert history\n if not converged and maxiter > 0:\n # maxiter <= 0 just does OLS\n if hasattr(self, 'pinv_wexog'):\n del self.pinv_wexog\n self.initialize()\n\n # if converged then this is a duplicate fit, because we did not\n # update rho\n results = self.fit(history=history, **kwargs)\n results.iter = i + 1\n # add last fit to history, not if duplicate fit\n if not converged:\n results.history['params'].append(results.params)\n results.iter += 1\n\n results.converged = converged\n\n return results\n\n def whiten(self, x):\n \"\"\"\n Whiten a series of columns according to an AR(p) covariance structure.\n\n Whitening using this method drops the initial p observations.\n\n Parameters\n ----------\n x : array_like\n The data to be whitened.\n\n Returns\n -------\n ndarray\n The whitened data.\n \"\"\"\n # TODO: notation for AR process\n x = np.asarray(x, np.float64)\n _x = x.copy()\n\n # the following loops over the first axis, works for 1d and nd\n for i in range(self.order):\n _x[(i + 1):] = _x[(i + 1):] - self.rho[i] * x[0:-(i + 1)]\n return _x[self.order:]\n\n\ndef yule_walker(x, order=1, method=\"adjusted\", df=None, inv=False,\n demean=True):\n \"\"\"\n Estimate AR(p) parameters from a sequence using the Yule-Walker equations.\n\n Adjusted or maximum-likelihood estimator (mle)\n\n Parameters\n ----------\n x : array_like\n A 1d array.\n order : int, optional\n The order of the autoregressive process. Default is 1.\n method : str, optional\n Method can be 'adjusted' or 'mle' and this determines\n denominator in estimate of autocorrelation function (ACF) at\n lag k. If 'mle', the denominator is n=X.shape[0], if 'adjusted'\n the denominator is n-k. The default is adjusted.\n df : int, optional\n Specifies the degrees of freedom. If `df` is supplied, then it\n is assumed the X has `df` degrees of freedom rather than `n`.\n Default is None.\n inv : bool\n If inv is True the inverse of R is also returned. Default is\n False.\n demean : bool\n True, the mean is subtracted from `X` before estimation.\n\n Returns\n -------\n rho : ndarray\n AR(p) coefficients computed using the Yule-Walker method.\n sigma : float\n The estimate of the residual standard deviation.\n\n See Also\n --------\n burg : Burg's AR estimator.\n\n Notes\n -----\n See https://en.wikipedia.org/wiki/Autoregressive_moving_average_model for\n further details.\n\n Examples\n --------\n >>> import statsmodels.api as sm\n >>> from statsmodels.datasets.sunspots import load\n >>> data = load(as_pandas=False)\n >>> rho, sigma = sm.regression.yule_walker(data.endog, order=4,\n ... method=\"mle\")\n\n >>> rho\n array([ 1.28310031, -0.45240924, -0.20770299, 0.04794365])\n >>> sigma\n 16.808022730464351\n \"\"\"\n # TODO: define R better, look back at notes and technical notes on YW.\n # First link here is useful\n # http://www-stat.wharton.upenn.edu/~steele/Courses/956/ResourceDetails/YuleWalkerAndMore.htm\n\n method = string_like(\n method, \"method\", options=(\"adjusted\", \"unbiased\", \"mle\")\n )\n if method == \"unbiased\":\n warnings.warn(\n \"unbiased is deprecated in factor of adjusted to reflect that the \"\n \"term is adjusting the sample size used in the autocovariance \"\n \"calculation rather than estimating an unbiased autocovariance. \"\n \"After release 0.13, using 'unbiased' will raise.\",\n FutureWarning,\n )\n method = \"adjusted\"\n\n if method not in (\"adjusted\", \"mle\"):\n raise ValueError(\"ACF estimation method must be 'adjusted' or 'MLE'\")\n x = np.array(x, dtype=np.float64)\n if demean:\n x -= x.mean()\n n = df or x.shape[0]\n\n # this handles df_resid ie., n - p\n adj_needed = method == \"adjusted\"\n\n if x.ndim > 1 and x.shape[1] != 1:\n raise ValueError(\"expecting a vector to estimate AR parameters\")\n r = np.zeros(order+1, np.float64)\n r[0] = (x ** 2).sum() / n\n for k in range(1, order+1):\n r[k] = (x[0:-k] * x[k:]).sum() / (n - k * adj_needed)\n R = toeplitz(r[:-1])\n\n rho = np.linalg.solve(R, r[1:])\n sigmasq = r[0] - (r[1:]*rho).sum()\n if inv:\n return rho, np.sqrt(sigmasq), np.linalg.inv(R)\n else:\n return rho, np.sqrt(sigmasq)\n\n\ndef burg(endog, order=1, demean=True):\n \"\"\"\n Compute Burg's AP(p) parameter estimator.\n\n Parameters\n ----------\n endog : array_like\n The endogenous variable.\n order : int, optional\n Order of the AR. Default is 1.\n demean : bool, optional\n Flag indicating to subtract the mean from endog before estimation.\n\n Returns\n -------\n rho : ndarray\n The AR(p) coefficients computed using Burg's algorithm.\n sigma2 : float\n The estimate of the residual variance.\n\n See Also\n --------\n yule_walker : Estimate AR parameters using the Yule-Walker method.\n\n Notes\n -----\n AR model estimated includes a constant that is estimated using the sample\n mean (see [1]_). This value is not reported.\n\n References\n ----------\n .. [1] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series\n and forecasting. Springer.\n\n Examples\n --------\n >>> import statsmodels.api as sm\n >>> from statsmodels.datasets.sunspots import load\n >>> data = load(as_pandas=True)\n >>> rho, sigma2 = sm.regression.linear_model.burg(data.endog, order=4)\n\n >>> rho\n array([ 1.30934186, -0.48086633, -0.20185982, 0.05501941])\n >>> sigma2\n 271.2467306963966\n \"\"\"\n # Avoid circular imports\n from statsmodels.tsa.stattools import levinson_durbin_pacf, pacf_burg\n\n endog = np.squeeze(np.asarray(endog))\n if endog.ndim != 1:\n raise ValueError('endog must be 1-d or squeezable to 1-d.')\n order = int(order)\n if order < 1:\n raise ValueError('order must be an integer larger than 1')\n if demean:\n endog = endog - endog.mean()\n pacf, sigma = pacf_burg(endog, order, demean=demean)\n ar, _ = levinson_durbin_pacf(pacf)\n return ar, sigma[-1]\n\n\nclass RegressionResults(base.LikelihoodModelResults):\n r\"\"\"\n This class summarizes the fit of a linear regression model.\n\n It handles the output of contrasts, estimates of covariance, etc.\n\n Parameters\n ----------\n model : RegressionModel\n The regression model instance.\n params : ndarray\n The estimated parameters.\n normalized_cov_params : ndarray\n The normalized covariance parameters.\n scale : float\n The estimated scale of the residuals.\n cov_type : str\n The covariance estimator used in the results.\n cov_kwds : dict\n Additional keywords used in the covariance specification.\n use_t : bool\n Flag indicating to use the Student's t in inference.\n **kwargs\n Additional keyword arguments used to initialize the results.\n\n Attributes\n ----------\n pinv_wexog\n See model class docstring for implementation details.\n cov_type\n Parameter covariance estimator used for standard errors and t-stats.\n df_model\n Model degrees of freedom. The number of regressors `p`. Does not\n include the constant if one is present.\n df_resid\n Residual degrees of freedom. `n - p - 1`, if a constant is present.\n `n - p` if a constant is not included.\n het_scale\n adjusted squared residuals for heteroscedasticity robust standard\n errors. Is only available after `HC#_se` or `cov_HC#` is called.\n See HC#_se for more information.\n history\n Estimation history for iterative estimators.\n model\n A pointer to the model instance that called fit() or results.\n params\n The linear coefficients that minimize the least squares\n criterion. This is usually called Beta for the classical\n linear model.\n \"\"\"\n\n _cache = {} # needs to be a class attribute for scale setter?\n\n def __init__(self, model, params, normalized_cov_params=None, scale=1.,\n cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs):\n super(RegressionResults, self).__init__(\n model, params, normalized_cov_params, scale)\n\n # Keep wresid since needed by predict\n self._data_in_cache.remove(\"wresid\")\n self._cache = {}\n if hasattr(model, 'wexog_singular_values'):\n self._wexog_singular_values = model.wexog_singular_values\n else:\n self._wexog_singular_values = None\n\n self.df_model = model.df_model\n self.df_resid = model.df_resid\n\n if cov_type == 'nonrobust':\n self.cov_type = 'nonrobust'\n self.cov_kwds = {\n 'description': 'Standard Errors assume that the ' +\n 'covariance matrix of the errors is correctly ' +\n 'specified.'}\n if use_t is None:\n use_t = True # TODO: class default\n self.use_t = use_t\n else:\n if cov_kwds is None:\n cov_kwds = {}\n if 'use_t' in cov_kwds:\n # TODO: we want to get rid of 'use_t' in cov_kwds\n use_t_2 = cov_kwds.pop('use_t')\n if use_t is None:\n use_t = use_t_2\n # TODO: warn or not?\n self.get_robustcov_results(cov_type=cov_type, use_self=True,\n use_t=use_t, **cov_kwds)\n for key in kwargs:\n setattr(self, key, kwargs[key])\n\n def conf_int(self, alpha=.05, cols=None):\n \"\"\"\n Compute the confidence interval of the fitted parameters.\n\n Parameters\n ----------\n alpha : float, optional\n The `alpha` level for the confidence interval. The default\n `alpha` = .05 returns a 95% confidence interval.\n cols : array_like, optional\n Columns to included in returned confidence intervals.\n\n Returns\n -------\n array_like\n The confidence intervals.\n\n Notes\n -----\n The confidence interval is based on Student's t-distribution.\n \"\"\"\n # keep method for docstring for now\n ci = super(RegressionResults, self).conf_int(alpha=alpha, cols=cols)\n return ci\n\n @cache_readonly\n def nobs(self):\n \"\"\"Number of observations n.\"\"\"\n return float(self.model.wexog.shape[0])\n\n @cache_readonly\n def fittedvalues(self):\n \"\"\"The predicted values for the original (unwhitened) design.\"\"\"\n return self.model.predict(self.params, self.model.exog)\n\n @cache_readonly\n def wresid(self):\n \"\"\"\n The residuals of the transformed/whitened regressand and regressor(s).\n \"\"\"\n return self.model.wendog - self.model.predict(\n self.params, self.model.wexog)\n\n @cache_readonly\n def resid(self):\n \"\"\"The residuals of the model.\"\"\"\n return self.model.endog - self.model.predict(\n self.params, self.model.exog)\n\n # TODO: fix writable example\n @cache_writable()\n def scale(self):\n \"\"\"\n A scale factor for the covariance matrix.\n\n The Default value is ssr/(n-p). Note that the square root of `scale`\n is often called the standard error of the regression.\n \"\"\"\n wresid = self.wresid\n return np.dot(wresid, wresid) / self.df_resid\n\n @cache_readonly\n def ssr(self):\n \"\"\"Sum of squared (whitened) residuals.\"\"\"\n wresid = self.wresid\n return np.dot(wresid, wresid)\n\n @cache_readonly\n def centered_tss(self):\n \"\"\"The total (weighted) sum of squares centered about the mean.\"\"\"\n model = self.model\n weights = getattr(model, 'weights', None)\n sigma = getattr(model, 'sigma', None)\n if weights is not None:\n mean = np.average(model.endog, weights=weights)\n return np.sum(weights * (model.endog - mean)**2)\n elif sigma is not None:\n # Exactly matches WLS when sigma is diagonal\n iota = np.ones_like(model.endog)\n iota = model.whiten(iota)\n mean = model.wendog.dot(iota) / iota.dot(iota)\n err = model.endog - mean\n err = model.whiten(err)\n return np.sum(err**2)\n else:\n centered_endog = model.wendog - model.wendog.mean()\n return np.dot(centered_endog, centered_endog)\n\n @cache_readonly\n def uncentered_tss(self):\n \"\"\"\n Uncentered sum of squares.\n\n The sum of the squared values of the (whitened) endogenous response\n variable.\n \"\"\"\n wendog = self.model.wendog\n return np.dot(wendog, wendog)\n\n @cache_readonly\n def ess(self):\n \"\"\"\n The explained sum of squares.\n\n If a constant is present, the centered total sum of squares minus the\n sum of squared residuals. If there is no constant, the uncentered total\n sum of squares is used.\n \"\"\"\n\n if self.k_constant:\n return self.centered_tss - self.ssr\n else:\n return self.uncentered_tss - self.ssr\n\n @cache_readonly\n def rsquared(self):\n \"\"\"\n R-squared of the model.\n\n This is defined here as 1 - `ssr`/`centered_tss` if the constant is\n included in the model and 1 - `ssr`/`uncentered_tss` if the constant is\n omitted.\n \"\"\"\n if self.k_constant:\n return 1 - self.ssr/self.centered_tss\n else:\n return 1 - self.ssr/self.uncentered_tss\n\n @cache_readonly\n def rsquared_adj(self):\n \"\"\"\n Adjusted R-squared.\n\n This is defined here as 1 - (`nobs`-1)/`df_resid` * (1-`rsquared`)\n if a constant is included and 1 - `nobs`/`df_resid` * (1-`rsquared`) if\n no constant is included.\n \"\"\"\n return 1 - (np.divide(self.nobs - self.k_constant, self.df_resid)\n * (1 - self.rsquared))\n\n @cache_readonly\n def mse_model(self):\n \"\"\"\n Mean squared error the model.\n\n The explained sum of squares divided by the model degrees of freedom.\n \"\"\"\n if np.all(self.df_model == 0.0):\n return np.full_like(self.ess, np.nan)\n return self.ess/self.df_model\n\n @cache_readonly\n def mse_resid(self):\n \"\"\"\n Mean squared error of the residuals.\n\n The sum of squared residuals divided by the residual degrees of\n freedom.\n \"\"\"\n if np.all(self.df_resid == 0.0):\n return np.full_like(self.ssr, np.nan)\n return self.ssr/self.df_resid\n\n @cache_readonly\n def mse_total(self):\n \"\"\"\n Total mean squared error.\n\n The uncentered total sum of squares divided by the number of\n observations.\n \"\"\"\n if np.all(self.df_resid + self.df_model == 0.0):\n return np.full_like(self.centered_tss, np.nan)\n if self.k_constant:\n return self.centered_tss / (self.df_resid + self.df_model)\n else:\n return self.uncentered_tss / (self.df_resid + self.df_model)\n\n @cache_readonly\n def fvalue(self):\n \"\"\"\n F-statistic of the fully specified model.\n\n Calculated as the mean squared error of the model divided by the mean\n squared error of the residuals if the nonrobust covariance is used.\n Otherwise computed using a Wald-like quadratic form that tests whether\n all coefficients (excluding the constant) are zero.\n \"\"\"\n if hasattr(self, 'cov_type') and self.cov_type != 'nonrobust':\n # with heteroscedasticity or correlation robustness\n k_params = self.normalized_cov_params.shape[0]\n mat = np.eye(k_params)\n const_idx = self.model.data.const_idx\n # TODO: What if model includes implicit constant, e.g. all\n # dummies but no constant regressor?\n # TODO: Restats as LM test by projecting orthogonalizing\n # to constant?\n if self.model.data.k_constant == 1:\n # if constant is implicit, return nan see #2444\n if const_idx is None:\n return np.nan\n\n idx = lrange(k_params)\n idx.pop(const_idx)\n mat = mat[idx] # remove constant\n if mat.size == 0: # see #3642\n return np.nan\n ft = self.f_test(mat)\n # using backdoor to set another attribute that we already have\n self._cache['f_pvalue'] = float(ft.pvalue)\n return float(ft.fvalue)\n else:\n # for standard homoscedastic case\n return self.mse_model/self.mse_resid\n\n @cache_readonly\n def f_pvalue(self):\n \"\"\"The p-value of the F-statistic.\"\"\"\n # Special case for df_model 0\n if self.df_model == 0:\n return np.full_like(self.fvalue, np.nan)\n return stats.f.sf(self.fvalue, self.df_model, self.df_resid)\n\n @cache_readonly\n def bse(self):\n \"\"\"The standard errors of the parameter estimates.\"\"\"\n return np.sqrt(np.diag(self.cov_params()))\n\n @cache_readonly\n def aic(self):\n r\"\"\"\n Akaike's information criteria.\n\n For a model with a constant :math:`-2llf + 2(df\\_model + 1)`. For a\n model without a constant :math:`-2llf + 2(df\\_model)`.\n \"\"\"\n return -2 * self.llf + 2 * (self.df_model + self.k_constant)\n\n @cache_readonly\n def bic(self):\n r\"\"\"\n Bayes' information criteria.\n\n For a model with a constant :math:`-2llf + \\log(n)(df\\_model+1)`.\n For a model without a constant :math:`-2llf + \\log(n)(df\\_model)`.\n \"\"\"\n return (-2 * self.llf + np.log(self.nobs) * (self.df_model +\n self.k_constant))\n\n @cache_readonly\n def eigenvals(self):\n \"\"\"\n Return eigenvalues sorted in decreasing order.\n \"\"\"\n if self._wexog_singular_values is not None:\n eigvals = self._wexog_singular_values ** 2\n else:\n eigvals = np.linalg.linalg.eigvalsh(np.dot(self.model.wexog.T,\n self.model.wexog))\n return np.sort(eigvals)[::-1]\n\n @cache_readonly\n def condition_number(self):\n \"\"\"\n Return condition number of exogenous matrix.\n\n Calculated as ratio of largest to smallest eigenvalue.\n \"\"\"\n eigvals = self.eigenvals\n return np.sqrt(eigvals[0]/eigvals[-1])\n\n # TODO: make these properties reset bse\n def _HCCM(self, scale):\n H = np.dot(self.model.pinv_wexog,\n scale[:, None] * self.model.pinv_wexog.T)\n return H\n\n def _abat_diagonal(self, a, b):\n # equivalent to np.diag(a @ b @ a.T)\n return np.einsum('ij,ik,kj->i', a, a, b)\n\n @cache_readonly\n def cov_HC0(self):\n \"\"\"\n Heteroscedasticity robust covariance matrix. See HC0_se.\n \"\"\"\n self.het_scale = self.wresid**2\n cov_HC0 = self._HCCM(self.het_scale)\n return cov_HC0\n\n @cache_readonly\n def cov_HC1(self):\n \"\"\"\n Heteroscedasticity robust covariance matrix. See HC1_se.\n \"\"\"\n self.het_scale = self.nobs/(self.df_resid)*(self.wresid**2)\n cov_HC1 = self._HCCM(self.het_scale)\n return cov_HC1\n\n @cache_readonly\n def cov_HC2(self):\n \"\"\"\n Heteroscedasticity robust covariance matrix. See HC2_se.\n \"\"\"\n wexog = self.model.wexog\n h = self._abat_diagonal(wexog, self.normalized_cov_params)\n self.het_scale = self.wresid**2/(1-h)\n cov_HC2 = self._HCCM(self.het_scale)\n return cov_HC2\n\n @cache_readonly\n def cov_HC3(self):\n \"\"\"\n Heteroscedasticity robust covariance matrix. See HC3_se.\n \"\"\"\n wexog = self.model.wexog\n h = self._abat_diagonal(wexog, self.normalized_cov_params)\n self.het_scale = (self.wresid / (1 - h))**2\n cov_HC3 = self._HCCM(self.het_scale)\n return cov_HC3\n\n @cache_readonly\n def HC0_se(self):\n \"\"\"\n White's (1980) heteroskedasticity robust standard errors.\n\n Notes\n -----\n Defined as sqrt(diag(X.T X)^(-1)X.T diag(e_i^(2)) X(X.T X)^(-1)\n where e_i = resid[i].\n\n When HC0_se or cov_HC0 is called the RegressionResults instance will\n then have another attribute `het_scale`, which is in this case is just\n resid**2.\n \"\"\"\n return np.sqrt(np.diag(self.cov_HC0))\n\n @cache_readonly\n def HC1_se(self):\n \"\"\"\n MacKinnon and White's (1985) heteroskedasticity robust standard errors.\n\n Notes\n -----\n Defined as sqrt(diag(n/(n-p)*HC_0).\n\n When HC1_se or cov_HC1 is called the RegressionResults instance will\n then have another attribute `het_scale`, which is in this case is\n n/(n-p)*resid**2.\n \"\"\"\n return np.sqrt(np.diag(self.cov_HC1))\n\n @cache_readonly\n def HC2_se(self):\n \"\"\"\n MacKinnon and White's (1985) heteroskedasticity robust standard errors.\n\n Notes\n -----\n Defined as (X.T X)^(-1)X.T diag(e_i^(2)/(1-h_ii)) X(X.T X)^(-1)\n where h_ii = x_i(X.T X)^(-1)x_i.T\n\n When HC2_se or cov_HC2 is called the RegressionResults instance will\n then have another attribute `het_scale`, which is in this case is\n resid^(2)/(1-h_ii).\n \"\"\"\n return np.sqrt(np.diag(self.cov_HC2))\n\n @cache_readonly\n def HC3_se(self):\n \"\"\"\n MacKinnon and White's (1985) heteroskedasticity robust standard errors.\n\n Notes\n -----\n Defined as (X.T X)^(-1)X.T diag(e_i^(2)/(1-h_ii)^(2)) X(X.T X)^(-1)\n where h_ii = x_i(X.T X)^(-1)x_i.T.\n\n When HC3_se or cov_HC3 is called the RegressionResults instance will\n then have another attribute `het_scale`, which is in this case is\n resid^(2)/(1-h_ii)^(2).\n \"\"\"\n return np.sqrt(np.diag(self.cov_HC3))\n\n @cache_readonly\n def resid_pearson(self):\n \"\"\"\n Residuals, normalized to have unit variance.\n\n Returns\n -------\n array_like\n The array `wresid` normalized by the sqrt of the scale to have\n unit variance.\n \"\"\"\n\n if not hasattr(self, 'resid'):\n raise ValueError('Method requires residuals.')\n eps = np.finfo(self.wresid.dtype).eps\n if np.sqrt(self.scale) < 10 * eps * self.model.endog.mean():\n # do not divide if scale is zero close to numerical precision\n warnings.warn(\n \"All residuals are 0, cannot compute normed residuals.\",\n RuntimeWarning\n )\n return self.wresid\n else:\n return self.wresid / np.sqrt(self.scale)\n\n def _is_nested(self, restricted):\n \"\"\"\n Parameters\n ----------\n restricted : Result instance\n The restricted model is assumed to be nested in the current\n model. The result instance of the restricted model is required to\n have two attributes, residual sum of squares, `ssr`, residual\n degrees of freedom, `df_resid`.\n\n Returns\n -------\n nested : bool\n True if nested, otherwise false\n\n Notes\n -----\n A most nests another model if the regressors in the smaller\n model are spanned by the regressors in the larger model and\n the regressand is identical.\n \"\"\"\n\n if self.model.nobs != restricted.model.nobs:\n return False\n\n full_rank = self.model.rank\n restricted_rank = restricted.model.rank\n if full_rank <= restricted_rank:\n return False\n\n restricted_exog = restricted.model.wexog\n full_wresid = self.wresid\n\n scores = restricted_exog * full_wresid[:, None]\n score_l2 = np.sqrt(np.mean(scores.mean(0) ** 2))\n # TODO: Could be improved, and may fail depending on scale of\n # regressors\n return np.allclose(score_l2, 0)\n\n def compare_lm_test(self, restricted, demean=True, use_lr=False):\n \"\"\"\n Use Lagrange Multiplier test to test a set of linear restrictions.\n\n Parameters\n ----------\n restricted : Result instance\n The restricted model is assumed to be nested in the\n current model. The result instance of the restricted model\n is required to have two attributes, residual sum of\n squares, `ssr`, residual degrees of freedom, `df_resid`.\n demean : bool\n Flag indicating whether the demean the scores based on the\n residuals from the restricted model. If True, the covariance of\n the scores are used and the LM test is identical to the large\n sample version of the LR test.\n use_lr : bool\n A flag indicating whether to estimate the covariance of the model\n scores using the unrestricted model. Setting the to True improves\n the power of the test.\n\n Returns\n -------\n lm_value : float\n The test statistic which has a chi2 distributed.\n p_value : float\n The p-value of the test statistic.\n df_diff : int\n The degrees of freedom of the restriction, i.e. difference in df\n between models.\n\n Notes\n -----\n The LM test examines whether the scores from the restricted model are\n 0. If the null is true, and the restrictions are valid, then the\n parameters of the restricted model should be close to the minimum of\n the sum of squared errors, and so the scores should be close to zero,\n on average.\n \"\"\"\n import statsmodels.stats.sandwich_covariance as sw\n from numpy.linalg import inv\n\n if not self._is_nested(restricted):\n raise ValueError(\"Restricted model is not nested by full model.\")\n\n wresid = restricted.wresid\n wexog = self.model.wexog\n scores = wexog * wresid[:, None]\n\n n = self.nobs\n df_full = self.df_resid\n df_restr = restricted.df_resid\n df_diff = (df_restr - df_full)\n\n s = scores.mean(axis=0)\n if use_lr:\n scores = wexog * self.wresid[:, None]\n demean = False\n\n if demean:\n scores = scores - scores.mean(0)[None, :]\n # Form matters here. If homoskedastics can be sigma^2 (X'X)^-1\n # If Heteroskedastic then the form below is fine\n # If HAC then need to use HAC\n # If Cluster, should use cluster\n\n cov_type = getattr(self, 'cov_type', 'nonrobust')\n if cov_type == 'nonrobust':\n sigma2 = np.mean(wresid**2)\n xpx = np.dot(wexog.T, wexog) / n\n s_inv = inv(sigma2 * xpx)\n elif cov_type in ('HC0', 'HC1', 'HC2', 'HC3'):\n s_inv = inv(np.dot(scores.T, scores) / n)\n elif cov_type == 'HAC':\n maxlags = self.cov_kwds['maxlags']\n s_inv = inv(sw.S_hac_simple(scores, maxlags) / n)\n elif cov_type == 'cluster':\n # cluster robust standard errors\n groups = self.cov_kwds['groups']\n # TODO: Might need demean option in S_crosssection by group?\n s_inv = inv(sw.S_crosssection(scores, groups))\n else:\n raise ValueError('Only nonrobust, HC, HAC and cluster are ' +\n 'currently connected')\n\n lm_value = n * (s @ s_inv @ s.T)\n p_value = stats.chi2.sf(lm_value, df_diff)\n return lm_value, p_value, df_diff\n\n def compare_f_test(self, restricted):\n \"\"\"\n Use F test to test whether restricted model is correct.\n\n Parameters\n ----------\n restricted : Result instance\n The restricted model is assumed to be nested in the\n current model. The result instance of the restricted model\n is required to have two attributes, residual sum of\n squares, `ssr`, residual degrees of freedom, `df_resid`.\n\n Returns\n -------\n f_value : float\n The test statistic which has an F distribution.\n p_value : float\n The p-value of the test statistic.\n df_diff : int\n The degrees of freedom of the restriction, i.e. difference in\n df between models.\n\n Notes\n -----\n See mailing list discussion October 17,\n\n This test compares the residual sum of squares of the two\n models. This is not a valid test, if there is unspecified\n heteroscedasticity or correlation. This method will issue a\n warning if this is detected but still return the results under\n the assumption of homoscedasticity and no autocorrelation\n (sphericity).\n \"\"\"\n\n has_robust1 = getattr(self, 'cov_type', 'nonrobust') != 'nonrobust'\n has_robust2 = (getattr(restricted, 'cov_type', 'nonrobust') !=\n 'nonrobust')\n\n if has_robust1 or has_robust2:\n warnings.warn('F test for comparison is likely invalid with ' +\n 'robust covariance, proceeding anyway',\n InvalidTestWarning)\n\n ssr_full = self.ssr\n ssr_restr = restricted.ssr\n df_full = self.df_resid\n df_restr = restricted.df_resid\n\n df_diff = (df_restr - df_full)\n f_value = (ssr_restr - ssr_full) / df_diff / ssr_full * df_full\n p_value = stats.f.sf(f_value, df_diff, df_full)\n return f_value, p_value, df_diff\n\n def compare_lr_test(self, restricted, large_sample=False):\n \"\"\"\n Likelihood ratio test to test whether restricted model is correct.\n\n Parameters\n ----------\n restricted : Result instance\n The restricted model is assumed to be nested in the current model.\n The result instance of the restricted model is required to have two\n attributes, residual sum of squares, `ssr`, residual degrees of\n freedom, `df_resid`.\n\n large_sample : bool\n Flag indicating whether to use a heteroskedasticity robust version\n of the LR test, which is a modified LM test.\n\n Returns\n -------\n lr_stat : float\n The likelihood ratio which is chisquare distributed with df_diff\n degrees of freedom.\n p_value : float\n The p-value of the test statistic.\n df_diff : int\n The degrees of freedom of the restriction, i.e. difference in df\n between models.\n\n Notes\n -----\n The exact likelihood ratio is valid for homoskedastic data,\n and is defined as\n\n .. math:: D=-2\\\\log\\\\left(\\\\frac{\\\\mathcal{L}_{null}}\n {\\\\mathcal{L}_{alternative}}\\\\right)\n\n where :math:`\\\\mathcal{L}` is the likelihood of the\n model. With :math:`D` distributed as chisquare with df equal\n to difference in number of parameters or equivalently\n difference in residual degrees of freedom.\n\n The large sample version of the likelihood ratio is defined as\n\n .. math:: D=n s^{\\\\prime}S^{-1}s\n\n where :math:`s=n^{-1}\\\\sum_{i=1}^{n} s_{i}`\n\n .. math:: s_{i} = x_{i,alternative} \\\\epsilon_{i,null}\n\n is the average score of the model evaluated using the\n residuals from null model and the regressors from the\n alternative model and :math:`S` is the covariance of the\n scores, :math:`s_{i}`. The covariance of the scores is\n estimated using the same estimator as in the alternative\n model.\n\n This test compares the loglikelihood of the two models. This\n may not be a valid test, if there is unspecified\n heteroscedasticity or correlation. This method will issue a\n warning if this is detected but still return the results\n without taking unspecified heteroscedasticity or correlation\n into account.\n\n This test compares the loglikelihood of the two models. This\n may not be a valid test, if there is unspecified\n heteroscedasticity or correlation. This method will issue a\n warning if this is detected but still return the results\n without taking unspecified heteroscedasticity or correlation\n into account.\n\n is the average score of the model evaluated using the\n residuals from null model and the regressors from the\n alternative model and :math:`S` is the covariance of the\n scores, :math:`s_{i}`. The covariance of the scores is\n estimated using the same estimator as in the alternative\n model.\n \"\"\"\n # TODO: put into separate function, needs tests\n\n # See mailing list discussion October 17,\n\n if large_sample:\n return self.compare_lm_test(restricted, use_lr=True)\n\n has_robust1 = (getattr(self, 'cov_type', 'nonrobust') != 'nonrobust')\n has_robust2 = (\n getattr(restricted, 'cov_type', 'nonrobust') != 'nonrobust')\n\n if has_robust1 or has_robust2:\n warnings.warn('Likelihood Ratio test is likely invalid with ' +\n 'robust covariance, proceeding anyway',\n InvalidTestWarning)\n\n llf_full = self.llf\n llf_restr = restricted.llf\n df_full = self.df_resid\n df_restr = restricted.df_resid\n\n lrdf = (df_restr - df_full)\n lrstat = -2*(llf_restr - llf_full)\n lr_pvalue = stats.chi2.sf(lrstat, lrdf)\n\n return lrstat, lr_pvalue, lrdf\n\n def get_robustcov_results(self, cov_type='HC1', use_t=None, **kwargs):\n \"\"\"\n Create new results instance with robust covariance as default.\n\n Parameters\n ----------\n cov_type : str\n The type of robust sandwich estimator to use. See Notes below.\n use_t : bool\n If true, then the t distribution is used for inference.\n If false, then the normal distribution is used.\n If `use_t` is None, then an appropriate default is used, which is\n `True` if the cov_type is nonrobust, and `False` in all other\n cases.\n **kwargs\n Required or optional arguments for robust covariance calculation.\n See Notes below.\n\n Returns\n -------\n RegressionResults\n This method creates a new results instance with the\n requested robust covariance as the default covariance of\n the parameters. Inferential statistics like p-values and\n hypothesis tests will be based on this covariance matrix.\n\n Notes\n -----\n The following covariance types and required or optional arguments are\n currently available:\n\n - 'fixed scale' uses a predefined scale\n\n ``scale``: float, optional\n Argument to set the scale. Default is 1.\n\n - 'HC0', 'HC1', 'HC2', 'HC3': heteroscedasticity robust covariance\n\n - no keyword arguments\n\n - 'HAC': heteroskedasticity-autocorrelation robust covariance\n\n ``maxlag`` : integer, required\n number of lags to use\n\n ``kernel`` : {callable, str}, optional\n kernels currently available kernels are ['bartlett', 'uniform'],\n default is Bartlett\n\n ``use_correction``: bool, optional\n If true, use small sample correction\n\n - 'cluster': clustered covariance estimator\n\n ``groups`` : array_like[int], required :\n Integer-valued index of clusters or groups.\n\n ``use_correction``: bool, optional\n If True the sandwich covariance is calculated with a small\n sample correction.\n If False the sandwich covariance is calculated without\n small sample correction.\n\n ``df_correction``: bool, optional\n If True (default), then the degrees of freedom for the\n inferential statistics and hypothesis tests, such as\n pvalues, f_pvalue, conf_int, and t_test and f_test, are\n based on the number of groups minus one instead of the\n total number of observations minus the number of explanatory\n variables. `df_resid` of the results instance is also\n adjusted. When `use_t` is also True, then pvalues are\n computed using the Student's t distribution using the\n corrected values. These may differ substantially from\n p-values based on the normal is the number of groups is\n small.\n If False, then `df_resid` of the results instance is not\n adjusted.\n\n - 'hac-groupsum': Driscoll and Kraay, heteroscedasticity and\n autocorrelation robust covariance for panel data\n # TODO: more options needed here\n\n ``time`` : array_like, required\n index of time periods\n ``maxlag`` : integer, required\n number of lags to use\n ``kernel`` : {callable, str}, optional\n The available kernels are ['bartlett', 'uniform']. The default is\n Bartlett.\n ``use_correction`` : {False, 'hac', 'cluster'}, optional\n If False the the sandwich covariance is calculated without small\n sample correction. If `use_correction = 'cluster'` (default),\n then the same small sample correction as in the case of\n `covtype='cluster'` is used.\n ``df_correction`` : bool, optional\n The adjustment to df_resid, see cov_type 'cluster' above\n\n - 'hac-panel': heteroscedasticity and autocorrelation robust standard\n errors in panel data. The data needs to be sorted in this case, the\n time series for each panel unit or cluster need to be stacked. The\n membership to a time series of an individual or group can be either\n specified by group indicators or by increasing time periods. One of\n ``groups`` or ``time`` is required. # TODO: we need more options here\n\n ``groups`` : array_like[int]\n indicator for groups\n ``time`` : array_like[int]\n index of time periods\n ``maxlag`` : int, required\n number of lags to use\n ``kernel`` : {callable, str}, optional\n Available kernels are ['bartlett', 'uniform'], default\n is Bartlett\n ``use_correction`` : {False, 'hac', 'cluster'}, optional\n If False the sandwich covariance is calculated without\n small sample correction.\n ``df_correction`` : bool, optional\n Adjustment to df_resid, see cov_type 'cluster' above\n\n **Reminder**: ``use_correction`` in \"hac-groupsum\" and \"hac-panel\" is\n not bool, needs to be in {False, 'hac', 'cluster'}.\n\n .. todo:: Currently there is no check for extra or misspelled keywords,\n except in the case of cov_type `HCx`\n \"\"\"\n import statsmodels.stats.sandwich_covariance as sw\n from statsmodels.base.covtype import normalize_cov_type, descriptions\n\n cov_type = normalize_cov_type(cov_type)\n\n if 'kernel' in kwargs:\n kwargs['weights_func'] = kwargs.pop('kernel')\n if 'weights_func' in kwargs and not callable(kwargs['weights_func']):\n kwargs['weights_func'] = sw.kernel_dict[kwargs['weights_func']]\n\n # TODO: make separate function that returns a robust cov plus info\n use_self = kwargs.pop('use_self', False)\n if use_self:\n res = self\n else:\n res = self.__class__(\n self.model, self.params,\n normalized_cov_params=self.normalized_cov_params,\n scale=self.scale)\n\n res.cov_type = cov_type\n # use_t might already be defined by the class, and already set\n if use_t is None:\n use_t = self.use_t\n res.cov_kwds = {'use_t': use_t} # store for information\n res.use_t = use_t\n\n adjust_df = False\n if cov_type in ['cluster', 'hac-panel', 'hac-groupsum']:\n df_correction = kwargs.get('df_correction', None)\n # TODO: check also use_correction, do I need all combinations?\n if df_correction is not False: # i.e. in [None, True]:\n # user did not explicitely set it to False\n adjust_df = True\n\n res.cov_kwds['adjust_df'] = adjust_df\n\n # verify and set kwargs, and calculate cov\n # TODO: this should be outsourced in a function so we can reuse it in\n # other models\n # TODO: make it DRYer repeated code for checking kwargs\n if cov_type in ['fixed scale', 'fixed_scale']:\n res.cov_kwds['description'] = descriptions['fixed_scale']\n\n res.cov_kwds['scale'] = scale = kwargs.get('scale', 1.)\n res.cov_params_default = scale * res.normalized_cov_params\n elif cov_type.upper() in ('HC0', 'HC1', 'HC2', 'HC3'):\n if kwargs:\n raise ValueError('heteroscedasticity robust covariance '\n 'does not use keywords')\n res.cov_kwds['description'] = descriptions[cov_type.upper()]\n res.cov_params_default = getattr(self, 'cov_' + cov_type.upper())\n elif cov_type.lower() == 'hac':\n # TODO: check if required, default in cov_hac_simple\n maxlags = kwargs['maxlags']\n res.cov_kwds['maxlags'] = maxlags\n weights_func = kwargs.get('weights_func', sw.weights_bartlett)\n res.cov_kwds['weights_func'] = weights_func\n use_correction = kwargs.get('use_correction', False)\n res.cov_kwds['use_correction'] = use_correction\n res.cov_kwds['description'] = descriptions['HAC'].format(\n maxlags=maxlags,\n correction=['without', 'with'][use_correction])\n\n res.cov_params_default = sw.cov_hac_simple(\n self, nlags=maxlags, weights_func=weights_func,\n use_correction=use_correction)\n elif cov_type.lower() == 'cluster':\n # cluster robust standard errors, one- or two-way\n groups = kwargs['groups']\n if not hasattr(groups, 'shape'):\n groups = np.asarray(groups).T\n\n if groups.ndim >= 2:\n groups = groups.squeeze()\n\n res.cov_kwds['groups'] = groups\n use_correction = kwargs.get('use_correction', True)\n res.cov_kwds['use_correction'] = use_correction\n if groups.ndim == 1:\n if adjust_df:\n # need to find number of groups\n # duplicate work\n self.n_groups = n_groups = len(np.unique(groups))\n res.cov_params_default = sw.cov_cluster(\n self, groups, use_correction=use_correction)\n\n elif groups.ndim == 2:\n if hasattr(groups, 'values'):\n groups = groups.values\n\n if adjust_df:\n # need to find number of groups\n # duplicate work\n n_groups0 = len(np.unique(groups[:, 0]))\n n_groups1 = len(np.unique(groups[:, 1]))\n self.n_groups = (n_groups0, n_groups1)\n n_groups = min(n_groups0, n_groups1) # use for adjust_df\n\n # Note: sw.cov_cluster_2groups has 3 returns\n res.cov_params_default = sw.cov_cluster_2groups(\n self, groups, use_correction=use_correction)[0]\n else:\n raise ValueError('only two groups are supported')\n res.cov_kwds['description'] = descriptions['cluster']\n\n elif cov_type.lower() == 'hac-panel':\n # cluster robust standard errors\n res.cov_kwds['time'] = time = kwargs.get('time', None)\n res.cov_kwds['groups'] = groups = kwargs.get('groups', None)\n # TODO: nlags is currently required\n # nlags = kwargs.get('nlags', True)\n # res.cov_kwds['nlags'] = nlags\n # TODO: `nlags` or `maxlags`\n res.cov_kwds['maxlags'] = maxlags = kwargs['maxlags']\n use_correction = kwargs.get('use_correction', 'hac')\n res.cov_kwds['use_correction'] = use_correction\n weights_func = kwargs.get('weights_func', sw.weights_bartlett)\n res.cov_kwds['weights_func'] = weights_func\n if groups is not None:\n groups = np.asarray(groups)\n tt = (np.nonzero(groups[:-1] != groups[1:])[0] + 1).tolist()\n nobs_ = len(groups)\n elif time is not None:\n time = np.asarray(time)\n # TODO: clumsy time index in cov_nw_panel\n tt = (np.nonzero(time[1:] < time[:-1])[0] + 1).tolist()\n nobs_ = len(time)\n else:\n raise ValueError('either time or groups needs to be given')\n groupidx = lzip([0] + tt, tt + [nobs_])\n self.n_groups = n_groups = len(groupidx)\n res.cov_params_default = sw.cov_nw_panel(self, maxlags, groupidx,\n weights_func=weights_func,\n use_correction=use_correction)\n res.cov_kwds['description'] = descriptions['HAC-Panel']\n\n elif cov_type.lower() == 'hac-groupsum':\n # Driscoll-Kraay standard errors\n res.cov_kwds['time'] = time = kwargs['time']\n # TODO: nlags is currently required\n # nlags = kwargs.get('nlags', True)\n # res.cov_kwds['nlags'] = nlags\n # TODO: `nlags` or `maxlags`\n res.cov_kwds['maxlags'] = maxlags = kwargs['maxlags']\n use_correction = kwargs.get('use_correction', 'cluster')\n res.cov_kwds['use_correction'] = use_correction\n weights_func = kwargs.get('weights_func', sw.weights_bartlett)\n res.cov_kwds['weights_func'] = weights_func\n if adjust_df:\n # need to find number of groups\n tt = (np.nonzero(time[1:] < time[:-1])[0] + 1)\n self.n_groups = n_groups = len(tt) + 1\n res.cov_params_default = sw.cov_nw_groupsum(\n self, maxlags, time, weights_func=weights_func,\n use_correction=use_correction)\n res.cov_kwds['description'] = descriptions['HAC-Groupsum']\n else:\n raise ValueError('cov_type not recognized. See docstring for ' +\n 'available options and spelling')\n\n if adjust_df:\n # Note: df_resid is used for scale and others, add new attribute\n res.df_resid_inference = n_groups - 1\n\n return res\n\n @Appender(pred.get_prediction.__doc__)\n def get_prediction(self, exog=None, transform=True, weights=None,\n row_labels=None, **kwargs):\n\n return pred.get_prediction(\n self, exog=exog, transform=transform, weights=weights,\n row_labels=row_labels, **kwargs)\n\n def summary(self, yname=None, xname=None, title=None, alpha=.05):\n \"\"\"\n Summarize the Regression Results.\n\n Parameters\n ----------\n yname : str, optional\n Name of endogenous (response) variable. The Default is `y`.\n xname : list[str], optional\n Names for the exogenous variables. Default is `var_##` for ## in\n the number of regressors. Must match the number of parameters\n in the model.\n title : str, optional\n Title for the top table. If not None, then this replaces the\n default title.\n alpha : float\n The significance level for the confidence intervals.\n\n Returns\n -------\n Summary\n Instance holding the summary tables and text, which can be printed\n or converted to various output formats.\n\n See Also\n --------\n statsmodels.iolib.summary.Summary : A class that holds summary results.\n \"\"\"\n from statsmodels.stats.stattools import (\n jarque_bera, omni_normtest, durbin_watson)\n\n jb, jbpv, skew, kurtosis = jarque_bera(self.wresid)\n omni, omnipv = omni_normtest(self.wresid)\n\n eigvals = self.eigenvals\n condno = self.condition_number\n\n # TODO: Avoid adding attributes in non-__init__\n self.diagn = dict(jb=jb, jbpv=jbpv, skew=skew, kurtosis=kurtosis,\n omni=omni, omnipv=omnipv, condno=condno,\n mineigval=eigvals[-1])\n\n # TODO not used yet\n # diagn_left_header = ['Models stats']\n # diagn_right_header = ['Residual stats']\n\n # TODO: requiring list/iterable is a bit annoying\n # need more control over formatting\n # TODO: default do not work if it's not identically spelled\n\n top_left = [('Dep. Variable:', None),\n ('Model:', None),\n ('Method:', ['Least Squares']),\n ('Date:', None),\n ('Time:', None),\n ('No. Observations:', None),\n ('Df Residuals:', None),\n ('Df Model:', None),\n ]\n\n if hasattr(self, 'cov_type'):\n top_left.append(('Covariance Type:', [self.cov_type]))\n\n rsquared_type = '' if self.k_constant else ' (uncentered)'\n top_right = [('R-squared' + rsquared_type + ':',\n [\"%#8.3f\" % self.rsquared]),\n ('Adj. R-squared' + rsquared_type + ':',\n [\"%#8.3f\" % self.rsquared_adj]),\n ('F-statistic:', [\"%#8.4g\" % self.fvalue]),\n ('Prob (F-statistic):', [\"%#6.3g\" % self.f_pvalue]),\n ('Log-Likelihood:', None),\n ('AIC:', [\"%#8.4g\" % self.aic]),\n ('BIC:', [\"%#8.4g\" % self.bic])\n ]\n\n diagn_left = [('Omnibus:', [\"%#6.3f\" % omni]),\n ('Prob(Omnibus):', [\"%#6.3f\" % omnipv]),\n ('Skew:', [\"%#6.3f\" % skew]),\n ('Kurtosis:', [\"%#6.3f\" % kurtosis])\n ]\n\n diagn_right = [('Durbin-Watson:',\n [\"%#8.3f\" % durbin_watson(self.wresid)]\n ),\n ('Jarque-Bera (JB):', [\"%#8.3f\" % jb]),\n ('Prob(JB):', [\"%#8.3g\" % jbpv]),\n ('Cond. No.', [\"%#8.3g\" % condno])\n ]\n\n if title is None:\n title = self.model.__class__.__name__ + ' ' + \"Regression Results\"\n\n # create summary table instance\n from statsmodels.iolib.summary import Summary\n smry = Summary()\n smry.add_table_2cols(self, gleft=top_left, gright=top_right,\n yname=yname, xname=xname, title=title)\n smry.add_table_params(self, yname=yname, xname=xname, alpha=alpha,\n use_t=self.use_t)\n\n smry.add_table_2cols(self, gleft=diagn_left, gright=diagn_right,\n yname=yname, xname=xname,\n title=\"\")\n\n # add warnings/notes, added to text format only\n etext = []\n if not self.k_constant:\n etext.append(\n \"R² is computed without centering (uncentered) since the \"\n \"model does not contain a constant.\"\n )\n if hasattr(self, 'cov_type'):\n etext.append(self.cov_kwds['description'])\n if self.model.exog.shape[0] < self.model.exog.shape[1]:\n wstr = \"The input rank is higher than the number of observations.\"\n etext.append(wstr)\n if eigvals[-1] < 1e-10:\n wstr = \"The smallest eigenvalue is %6.3g. This might indicate \"\n wstr += \"that there are\\n\"\n wstr += \"strong multicollinearity problems or that the design \"\n wstr += \"matrix is singular.\"\n wstr = wstr % eigvals[-1]\n etext.append(wstr)\n elif condno > 1000: # TODO: what is recommended?\n wstr = \"The condition number is large, %6.3g. This might \"\n wstr += \"indicate that there are\\n\"\n wstr += \"strong multicollinearity or other numerical \"\n wstr += \"problems.\"\n wstr = wstr % condno\n etext.append(wstr)\n\n if etext:\n etext = [\"[{0}] {1}\".format(i + 1, text)\n for i, text in enumerate(etext)]\n etext.insert(0, \"Notes:\")\n smry.add_extra_txt(etext)\n\n return smry\n\n def summary2(self, yname=None, xname=None, title=None, alpha=.05,\n float_format=\"%.4f\"):\n \"\"\"\n Experimental summary function to summarize the regression results.\n\n Parameters\n ----------\n yname : str\n The name of the dependent variable (optional).\n xname : list[str], optional\n Names for the exogenous variables. Default is `var_##` for ## in\n the number of regressors. Must match the number of parameters\n in the model.\n title : str, optional\n Title for the top table. If not None, then this replaces the\n default title.\n alpha : float\n The significance level for the confidence intervals.\n float_format : str\n The format for floats in parameters summary.\n\n Returns\n -------\n Summary\n Instance holding the summary tables and text, which can be printed\n or converted to various output formats.\n\n See Also\n --------\n statsmodels.iolib.summary2.Summary\n A class that holds summary results.\n \"\"\"\n # Diagnostics\n from statsmodels.stats.stattools import (jarque_bera,\n omni_normtest,\n durbin_watson)\n\n jb, jbpv, skew, kurtosis = jarque_bera(self.wresid)\n omni, omnipv = omni_normtest(self.wresid)\n dw = durbin_watson(self.wresid)\n eigvals = self.eigenvals\n condno = self.condition_number\n eigvals = np.sort(eigvals) # in increasing order\n diagnostic = dict([\n ('Omnibus:', \"%.3f\" % omni),\n ('Prob(Omnibus):', \"%.3f\" % omnipv),\n ('Skew:', \"%.3f\" % skew),\n ('Kurtosis:', \"%.3f\" % kurtosis),\n ('Durbin-Watson:', \"%.3f\" % dw),\n ('Jarque-Bera (JB):', \"%.3f\" % jb),\n ('Prob(JB):', \"%.3f\" % jbpv),\n ('Condition No.:', \"%.0f\" % condno)\n ])\n\n # Summary\n from statsmodels.iolib import summary2\n smry = summary2.Summary()\n smry.add_base(results=self, alpha=alpha, float_format=float_format,\n xname=xname, yname=yname, title=title)\n smry.add_dict(diagnostic)\n\n # Warnings\n if eigvals[-1] < 1e-10:\n warn = \"The smallest eigenvalue is %6.3g. This might indicate that\\\n there are strong multicollinearity problems or that the design\\\n matrix is singular.\" % eigvals[-1]\n smry.add_text(warn)\n if condno > 1000:\n warn = \"* The condition number is large (%.g). This might indicate \\\n strong multicollinearity or other numerical problems.\" % condno\n smry.add_text(warn)\n\n return smry\n\n\nclass OLSResults(RegressionResults):\n \"\"\"\n Results class for for an OLS model.\n\n Parameters\n ----------\n model : RegressionModel\n The regression model instance.\n params : ndarray\n The estimated parameters.\n normalized_cov_params : ndarray\n The normalized covariance parameters.\n scale : float\n The estimated scale of the residuals.\n cov_type : str\n The covariance estimator used in the results.\n cov_kwds : dict\n Additional keywords used in the covariance specification.\n use_t : bool\n Flag indicating to use the Student's t in inference.\n **kwargs\n Additional keyword arguments used to initialize the results.\n\n See Also\n --------\n RegressionResults\n Results store for WLS and GLW models.\n\n Notes\n -----\n Most of the methods and attributes are inherited from RegressionResults.\n The special methods that are only available for OLS are:\n\n - get_influence\n - outlier_test\n - el_test\n - conf_int_el\n \"\"\"\n\n def get_influence(self):\n \"\"\"\n Calculate influence and outlier measures.\n\n Returns\n -------\n OLSInfluence\n The instance containing methods to calculate the main influence and\n outlier measures for the OLS regression.\n\n See Also\n --------\n statsmodels.stats.outliers_influence.OLSInfluence\n A class that exposes methods to examine observation influence.\n \"\"\"\n from statsmodels.stats.outliers_influence import OLSInfluence\n return OLSInfluence(self)\n\n def outlier_test(self, method='bonf', alpha=.05, labels=None,\n order=False, cutoff=None):\n \"\"\"\n Test observations for outliers according to method.\n\n Parameters\n ----------\n method : str\n The method to use in the outlier test. Must be one of:\n\n - `bonferroni` : one-step correction\n - `sidak` : one-step correction\n - `holm-sidak` :\n - `holm` :\n - `simes-hochberg` :\n - `hommel` :\n - `fdr_bh` : Benjamini/Hochberg\n - `fdr_by` : Benjamini/Yekutieli\n\n See `statsmodels.stats.multitest.multipletests` for details.\n alpha : float\n The familywise error rate (FWER).\n labels : None or array_like\n If `labels` is not None, then it will be used as index to the\n returned pandas DataFrame. See also Returns below.\n order : bool\n Whether or not to order the results by the absolute value of the\n studentized residuals. If labels are provided they will also be\n sorted.\n cutoff : None or float in [0, 1]\n If cutoff is not None, then the return only includes observations\n with multiple testing corrected p-values strictly below the cutoff.\n The returned array or dataframe can be empty if t.\n\n Returns\n -------\n array_like\n Returns either an ndarray or a DataFrame if labels is not None.\n Will attempt to get labels from model_results if available. The\n columns are the Studentized residuals, the unadjusted p-value,\n and the corrected p-value according to method.\n\n Notes\n -----\n The unadjusted p-value is stats.t.sf(abs(resid), df) where\n df = df_resid - 1.\n \"\"\"\n from statsmodels.stats.outliers_influence import outlier_test\n return outlier_test(self, method, alpha, labels=labels,\n order=order, cutoff=cutoff)\n\n def el_test(self, b0_vals, param_nums, return_weights=0, ret_params=0,\n method='nm', stochastic_exog=1):\n \"\"\"\n Test single or joint hypotheses using Empirical Likelihood.\n\n Parameters\n ----------\n b0_vals : 1darray\n The hypothesized value of the parameter to be tested.\n param_nums : 1darray\n The parameter number to be tested.\n return_weights : bool\n If true, returns the weights that optimize the likelihood\n ratio at b0_vals. The default is False.\n ret_params : bool\n If true, returns the parameter vector that maximizes the likelihood\n ratio at b0_vals. Also returns the weights. The default is False.\n method : str\n Can either be 'nm' for Nelder-Mead or 'powell' for Powell. The\n optimization method that optimizes over nuisance parameters.\n The default is 'nm'.\n stochastic_exog : bool\n When True, the exogenous variables are assumed to be stochastic.\n When the regressors are nonstochastic, moment conditions are\n placed on the exogenous variables. Confidence intervals for\n stochastic regressors are at least as large as non-stochastic\n regressors. The default is True.\n\n Returns\n -------\n tuple\n The p-value and -2 times the log-likelihood ratio for the\n hypothesized values.\n\n Examples\n --------\n >>> import statsmodels.api as sm\n >>> data = sm.datasets.stackloss.load(as_pandas=False)\n >>> endog = data.endog\n >>> exog = sm.add_constant(data.exog)\n >>> model = sm.OLS(endog, exog)\n >>> fitted = model.fit()\n >>> fitted.params\n >>> array([-39.91967442, 0.7156402 , 1.29528612, -0.15212252])\n >>> fitted.rsquared\n >>> 0.91357690446068196\n >>> # Test that the slope on the first variable is 0\n >>> fitted.el_test([0], [1])\n >>> (27.248146353888796, 1.7894660442330235e-07)\n \"\"\"\n params = np.copy(self.params)\n opt_fun_inst = _ELRegOpts() # to store weights\n if len(param_nums) == len(params):\n llr = opt_fun_inst._opt_nuis_regress(\n [],\n param_nums=param_nums,\n endog=self.model.endog,\n exog=self.model.exog,\n nobs=self.model.nobs,\n nvar=self.model.exog.shape[1],\n params=params,\n b0_vals=b0_vals,\n stochastic_exog=stochastic_exog)\n pval = 1 - stats.chi2.cdf(llr, len(param_nums))\n if return_weights:\n return llr, pval, opt_fun_inst.new_weights\n else:\n return llr, pval\n x0 = np.delete(params, param_nums)\n args = (param_nums, self.model.endog, self.model.exog,\n self.model.nobs, self.model.exog.shape[1], params,\n b0_vals, stochastic_exog)\n if method == 'nm':\n llr = optimize.fmin(opt_fun_inst._opt_nuis_regress, x0,\n maxfun=10000, maxiter=10000, full_output=1,\n disp=0, args=args)[1]\n if method == 'powell':\n llr = optimize.fmin_powell(opt_fun_inst._opt_nuis_regress, x0,\n full_output=1, disp=0,\n args=args)[1]\n\n pval = 1 - stats.chi2.cdf(llr, len(param_nums))\n if ret_params:\n return llr, pval, opt_fun_inst.new_weights, opt_fun_inst.new_params\n elif return_weights:\n return llr, pval, opt_fun_inst.new_weights\n else:\n return llr, pval\n\n def conf_int_el(self, param_num, sig=.05, upper_bound=None,\n lower_bound=None, method='nm', stochastic_exog=True):\n \"\"\"\n Compute the confidence interval using Empirical Likelihood.\n\n Parameters\n ----------\n param_num : float\n The parameter for which the confidence interval is desired.\n sig : float\n The significance level. Default is 0.05.\n upper_bound : float\n The maximum value the upper limit can be. Default is the\n 99.9% confidence value under OLS assumptions.\n lower_bound : float\n The minimum value the lower limit can be. Default is the 99.9%\n confidence value under OLS assumptions.\n method : str\n Can either be 'nm' for Nelder-Mead or 'powell' for Powell. The\n optimization method that optimizes over nuisance parameters.\n The default is 'nm'.\n stochastic_exog : bool\n When True, the exogenous variables are assumed to be stochastic.\n When the regressors are nonstochastic, moment conditions are\n placed on the exogenous variables. Confidence intervals for\n stochastic regressors are at least as large as non-stochastic\n regressors. The default is True.\n\n Returns\n -------\n lowerl : float\n The lower bound of the confidence interval.\n upperl : float\n The upper bound of the confidence interval.\n\n See Also\n --------\n el_test : Test parameters using Empirical Likelihood.\n\n Notes\n -----\n This function uses brentq to find the value of beta where\n test_beta([beta], param_num)[1] is equal to the critical value.\n\n The function returns the results of each iteration of brentq at each\n value of beta.\n\n The current function value of the last printed optimization should be\n the critical value at the desired significance level. For alpha=.05,\n the value is 3.841459.\n\n To ensure optimization terminated successfully, it is suggested to do\n el_test([lower_limit], [param_num]).\n\n If the optimization does not terminate successfully, consider switching\n optimization algorithms.\n\n If optimization is still not successful, try changing the values of\n start_int_params. If the current function value repeatedly jumps\n from a number between 0 and the critical value and a very large number\n (>50), the starting parameters of the interior minimization need\n to be changed.\n \"\"\"\n r0 = stats.chi2.ppf(1 - sig, 1)\n if upper_bound is None:\n upper_bound = self.conf_int(.01)[param_num][1]\n if lower_bound is None:\n lower_bound = self.conf_int(.01)[param_num][0]\n\n def f(b0):\n return self.el_test(np.array([b0]), np.array([param_num]),\n method=method,\n stochastic_exog=stochastic_exog)[0] - r0\n\n lowerl = optimize.brenth(f, lower_bound,\n self.params[param_num])\n upperl = optimize.brenth(f, self.params[param_num],\n upper_bound)\n # ^ Seems to be faster than brentq in most cases\n return (lowerl, upperl)\n\n\nclass RegressionResultsWrapper(wrap.ResultsWrapper):\n\n _attrs = {\n 'chisq': 'columns',\n 'sresid': 'rows',\n 'weights': 'rows',\n 'wresid': 'rows',\n 'bcov_unscaled': 'cov',\n 'bcov_scaled': 'cov',\n 'HC0_se': 'columns',\n 'HC1_se': 'columns',\n 'HC2_se': 'columns',\n 'HC3_se': 'columns',\n 'norm_resid': 'rows',\n }\n\n _wrap_attrs = wrap.union_dicts(base.LikelihoodResultsWrapper._attrs,\n _attrs)\n\n _methods = {}\n\n _wrap_methods = wrap.union_dicts(\n base.LikelihoodResultsWrapper._wrap_methods,\n _methods)\n\n\nwrap.populate_wrapper(RegressionResultsWrapper,\n RegressionResults)\n"
] |
[
[
"numpy.diag",
"numpy.dot",
"numpy.sqrt",
"numpy.einsum",
"numpy.linalg.matrix_rank",
"numpy.asarray",
"numpy.all",
"scipy.optimize.fmin",
"numpy.mean",
"numpy.any",
"scipy.stats.f.sf",
"numpy.fill_diagonal",
"scipy.optimize.fmin_powell",
"numpy.linalg.qr",
"numpy.divide",
"numpy.linalg.svd",
"numpy.ones_like",
"numpy.allclose",
"numpy.unique",
"numpy.linalg.slogdet",
"numpy.eye",
"numpy.finfo",
"numpy.copy",
"numpy.outer",
"numpy.repeat",
"numpy.zeros",
"scipy.stats.chi2.ppf",
"numpy.log",
"numpy.nonzero",
"numpy.linalg.inv",
"numpy.full_like",
"numpy.delete",
"numpy.transpose",
"numpy.array",
"numpy.sum",
"numpy.linalg.solve",
"scipy.linalg.toeplitz",
"numpy.abs",
"scipy.optimize.brenth",
"numpy.sort",
"numpy.ones",
"numpy.isscalar",
"numpy.average",
"scipy.stats.chi2.sf"
]
] |
hgl71964/dagbo
|
[
"de198650268baee324bc495899e34531d10369e2"
] |
[
"tests/dag_unittest.py"
] |
[
"import os\nimport sys\nimport math\nimport warnings\nimport logging\nimport unittest\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom torch import Size, Tensor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\n\nimport gpytorch\nfrom gpytorch.models.exact_gp import ExactGP\nfrom gpytorch.likelihoods.gaussian_likelihood import GaussianLikelihood\nimport botorch\nfrom botorch.models import SingleTaskGP\nfrom botorch.sampling.samplers import SobolQMCNormalSampler\nfrom botorch.optim import optimize_acqf\nfrom botorch.posteriors.gpytorch import GPyTorchPosterior\nfrom botorch.models.utils import gpt_posterior_settings\n\nfrom dagbo.models.dag.dag import Dag, SO_Dag\nfrom dagbo.models.dag.node import SingleTaskGP_Node\nfrom dagbo.models.dag.sample_average_posterior import SampleAveragePosterior\nfrom dagbo.models.dag.dag_gpytorch_model import DagGPyTorchModel, direct_DagGPyTorchModel\nfrom dagbo.models.dag.fit_dag import fit_dag, fit_node_with_scipy, test_fit_node_with_scipy, fit_node_with_adam\nfrom dagbo.models.gp_factory import fit_gpr\n\n\nclass normal_gp_test(unittest.TestCase):\n \"\"\"\n test the sampling and inner loop of a standard gp model from gpytorch\n (as building block for dagbo)\n \"\"\"\n def setUp(self):\n np.random.seed(0), torch.manual_seed(0)\n\n class gp(SingleTaskGP_Node):\n def __init__(self, input_names, output_name, train_inputs,\n train_targets):\n super().__init__(input_names, output_name, train_inputs,\n train_targets)\n\n # expose posterior to print shape\n def posterior(self,\n X: Tensor,\n observation_noise=False,\n **kwargs) -> GPyTorchPosterior:\n self.eval() # make sure model is in eval mode\n with gpt_posterior_settings():\n mvn = self(X)\n print()\n print(\"X::: \", X.shape)\n print(X)\n print(\"mvn:::\")\n print(mvn)\n print(mvn.loc)\n print()\n #print(mvn.loc) # can verify identical mvn\n posterior = GPyTorchPosterior(mvn=mvn)\n return posterior\n\n # prepare input\n train_input_names = [\n \"x1\",\n \"x2\",\n \"x3\",\n ]\n train_target_names = [\n \"z1\",\n \"z2\",\n \"y\",\n ]\n num_init = 3\n\n # hand-craft data\n train_inputs = np.array([\n [0.1, 0.2, 0.3],\n [0.3, 0.2, 0.7],\n [0.4, 0.1, 0.9],\n ])\n\n # targets\n func = lambda x: np.sin(x[0] * (8 * math.pi)) + np.cos(x[1] * (\n 3 * math.pi)) + np.log(x[2] + 0.1) + 3\n train_targets = np.array([func(i) for i in train_inputs])\n train_targets = train_targets.reshape(num_init, 1)\n\n # format\n train_inputs = MinMaxScaler().fit_transform(train_inputs)\n train_targets = StandardScaler().fit_transform(train_targets)\n train_inputs = torch.from_numpy(train_inputs)\n train_targets = torch.from_numpy(train_targets)\n train_inputs = train_inputs.reshape(1, num_init, 3)\n train_targets = train_targets.reshape(1, num_init)\n\n self.model = gp([\"x1\", \"x2\", \"x3\"], \"t\", train_inputs, train_targets)\n\n #@unittest.skip(\"print sample shape\")\n def test_normal_gp_sampling_shape(self):\n fit_gpr(self.model)\n\n train_input_names = [\"x1\", \"x2\", \"x3\"]\n q = 1\n #new_input = torch.rand(self.batch_size, q, len(train_input_names))\n new_input = torch.rand(1, q, len(train_input_names))\n\n print()\n print(\"normal gp sampling:::\")\n print(\"input shape: \", new_input.shape)\n pst = self.model.posterior(new_input)\n\n print()\n print(\"posterior:::\")\n print(pst.mvn)\n sampler = SobolQMCNormalSampler(num_samples=4, seed=0)\n samples = sampler(pst)\n print()\n print(\"sampling from posterior:::\")\n print(\n samples.shape\n ) # [sampler's num_samples, batch_size of input, q, DAG's num_of_output]\n print(samples)\n\n @unittest.skip(\"print inner loop shape\")\n def test_normal_gp_inner_loop(self):\n \"\"\"\n NOTE: run this func can observe MC-gradient-descent in standard BO\n\n gp posterior only return one `deterministic` `posterior` object\n representing a gaussian posterior distribution\n this is ok for normal gp\n but our dagbo needs `approximate` posterior\n \"\"\"\n print()\n print(\"normal gp inner loop:::\")\n fit_gpr(self.model)\n q = 1\n num_restarts = 2 # create batch shape for optimise acquisition func\n raw_samples = 3 # this create initial batch shape for optimise acquisition func\n\n sampler = SobolQMCNormalSampler(num_samples=4, seed=0)\n acq = botorch.acquisition.monte_carlo.qExpectedImprovement(\n model=self.model,\n best_f=torch.tensor([1.]),\n sampler=sampler,\n objective=None, # use when model has multiple output\n )\n\n # inner loop\n candidates, val = botorch.optim.optimize_acqf(\n acq_function=acq,\n bounds=torch.tensor([\n [0, 0, 0],\n [1, 1, 1],\n ], dtype=torch.float64),\n q=q,\n num_restarts=num_restarts,\n raw_samples=raw_samples,\n sequential=False, # joint optimisation of q\n )\n query = candidates.detach()\n logging.info(\"candidates: \")\n print(query, val.detach())\n\n\nclass ross_dag_dummy_perf_model_test(unittest.TestCase):\n \"\"\"\n test ross' impl of sample average dagbo\n \"\"\"\n def setUp(self):\n np.random.seed(0), torch.manual_seed(0)\n\n # define dag direct_DagGPyTorchModel, DagGPyTorchModel\n class perf_model_DAG(SO_Dag, DagGPyTorchModel):\n def __init__(self, train_input_names: list[str],\n train_target_names: list[str], train_inputs: Tensor,\n train_targets: Tensor, num_samples: int):\n super().__init__(train_input_names, train_target_names,\n train_inputs, train_targets, \"cpu\")\n\n # required for all classes that extend SparkDag\n self.num_samples = num_samples\n\n def define_dag(self, batch_shape: Size = Size([])) -> None:\n x1 = self.register_input(\"x1\")\n x2 = self.register_input(\"x2\")\n x3 = self.register_input(\"x3\")\n y = self.register_metric(\"y\", [x1, x2, x3])\n\n # prepare input\n train_input_names = [\n \"x1\",\n \"x2\",\n \"x3\",\n ]\n train_target_names = [\n \"y\",\n ]\n num_init = 3\n num_samples = 2\n\n # hand-craft data\n train_inputs = np.array([\n [0.1, 0.2, 0.3],\n [0.3, 0.2, 0.7],\n [0.4, 0.1, 0.9],\n ])\n\n # targets\n func = lambda x: np.sin(x[0] * (8 * math.pi)) + np.cos(x[1] * (\n 3 * math.pi)) + np.log(x[2] + 0.1) + 3\n train_targets = np.array([func(i) for i in train_inputs])\n train_targets = train_targets.reshape(num_init, 1)\n\n # format\n train_inputs = MinMaxScaler().fit_transform(train_inputs)\n train_targets = StandardScaler().fit_transform(train_targets)\n train_inputs = torch.from_numpy(train_inputs)\n train_targets = torch.from_numpy(train_targets)\n train_inputs = train_inputs.reshape(1, num_init, 3)\n train_targets = train_targets.reshape(1, num_init, 1)\n\n self.dag = perf_model_DAG(train_input_names, train_target_names,\n train_inputs, train_targets, num_samples)\n\n #@unittest.skip(\"..\")\n def test_dag_posterior(self):\n print()\n print(\"dag sampling::::\")\n fit_dag(self.dag)\n train_input_names = [\"x1\", \"x2\", \"x3\"]\n q = 1\n new_input = torch.rand(1, q, len(train_input_names))\n print(\"input shape: \", new_input.shape)\n\n pst = self.dag.posterior(new_input)\n print()\n print(\"posterior:\")\n print(pst.mvn)\n sampler = SobolQMCNormalSampler(num_samples=4, seed=0)\n samples = sampler(pst)\n print()\n print(\"sampling from posterior\")\n print(\n samples.shape\n ) # [sampler's num_samples, batch_size of input, q, DAG's num_of_output]\n print(samples)\n\n @unittest.skip(\"..\")\n def test_dag_inner_loop(self):\n print()\n print(\"dag inner loop:::\")\n fit_dag(self.dag)\n q = 1\n num_restarts = 2 # create batch shape for optimise acquisition func\n raw_samples = 3 # this create initial batch shape for optimise acquisition func\n\n sampler = SobolQMCNormalSampler(num_samples=4, seed=0)\n acq = botorch.acquisition.monte_carlo.qExpectedImprovement(\n model=self.dag,\n best_f=torch.tensor([1.]),\n sampler=sampler,\n objective=None, # use when model has multiple output\n )\n\n # inner loop\n candidates, val = botorch.optim.optimize_acqf(\n acq_function=acq,\n bounds=torch.tensor([\n [0, 0, 0],\n [1, 1, 1],\n ], dtype=torch.float64),\n q=q,\n num_restarts=num_restarts,\n raw_samples=raw_samples,\n sequential=False, # joint optimisation of q\n )\n query = candidates.detach()\n logging.info(\"candidates: \")\n print(query, val.detach())\n\n\nclass ross_dag_test(unittest.TestCase):\n \"\"\"\n test ross' impl of sample average dagbo\n \"\"\"\n def setUp(self):\n np.random.seed(0), torch.manual_seed(0)\n\n # define dag\n class TREE_DAG(SO_Dag, DagGPyTorchModel):\n \"\"\"\n creation a simple tree-like DAG\n\n x1 x2 x3\n \\ / |\n z1 z2\n \\ /\n y\n \"\"\"\n def __init__(self, train_input_names: list[str],\n train_target_names: list[str], train_inputs: Tensor,\n train_targets: Tensor, num_samples: int):\n super().__init__(train_input_names, train_target_names,\n train_inputs, train_targets, \"cpu\")\n\n # required for all classes that extend SparkDag\n self.num_samples = num_samples\n\n def define_dag(self, batch_shape: Size = Size([])) -> None:\n x_1 = self.register_input(\"x1\")\n x_2 = self.register_input(\"x2\")\n x_3 = self.register_input(\"x3\")\n\n z_1 = self.register_metric(\"z1\", [x_1, x_2])\n z_2 = self.register_metric(\"z2\", [x_3])\n\n y = self.register_metric(\"y\", [z_1, z_2])\n\n # prepare input\n train_input_names = [\n \"x1\",\n \"x2\",\n \"x3\",\n ]\n train_target_names = [\n \"z1\",\n \"z2\",\n \"y\",\n ]\n batch_size = 1\n num_samples = 1000\n\n # create data\n #train_inputs = torch.linspace(0, 1, 7)\n train_inputs = torch.linspace(0, 2, 7)\n func = lambda x: torch.sin(x * (8 * math.pi)) + torch.cos(x * (\n 3 * math.pi)) + torch.log(x + 0.1) + 3\n #func = lambda x: torch.sin(x * math.pi)\n\n # reshape\n train_targets = func(train_inputs).reshape(-1, 1).expand(\n 1, 7, 2) # shape:[1, 7, 3]\n\n #print(train_targets[0])\n new_val = func(train_targets[..., -1].flatten()).reshape(1, 7, 1)\n train_targets = torch.cat([train_targets, new_val], dim=-1)\n #print(new_val)\n #print(train_targets[0])\n #raise ValueError(\"ok\")\n\n train_inputs = train_inputs.reshape(-1, 1).expand(1, 7,\n 3) # shape:[1, 7, 3]\n\n self.assertEqual(train_inputs.shape, torch.Size([1, 7, 3]))\n self.assertEqual(train_targets.shape, torch.Size([1, 7, 3]))\n\n self.func = func\n self.batch_size = batch_size\n self.num_samples = num_samples\n self.domain = (0, 2)\n self.simple_dag = TREE_DAG(train_input_names, train_target_names,\n train_inputs, train_targets, num_samples)\n\n @unittest.skip(\".\")\n def test_model_mro(self):\n print(\"model MRO\")\n print(TREE_DAG.__mro__)\n\n @unittest.skip(\"ok\")\n def test_dag_compare_fit(self):\n \"\"\"\n test fitting the dag from data, with different fit method\n each initialisation of DAG, it holds original data\n\n Results:\n fit_node_with_scipy tends to be more numerically stable, botorch's default fit\n fit_node_with_adam needs to choose epochs, lr, etc\n \"\"\"\n # fit\n #fit_dag(self.simple_dag, fit_node_with_adam, verbose=True)\n fit_dag(self.simple_dag, test_fit_node_with_scipy, verbose=True)\n\n for node in self.simple_dag.nodes_dag_order():\n print(\"Verifying: \", node.output_name)\n node.eval()\n\n if node.output_name == \"z2\":\n with torch.no_grad():\n test_x = torch.linspace(self.domain[0], self.domain[1],\n 100)\n test_y = self.func(test_x)\n\n pred = node.likelihood(node(test_x))\n mean = pred.mean\n lower, upper = pred.confidence_region()\n\n mean = mean.flatten()\n lower, upper = lower.flatten(), upper.flatten()\n\n after = mean_squared_error(test_y, mean)\n print(f\"MSE after fit: {after:.2f}\")\n\n @unittest.skip(\"ok\")\n def test_dag_posterior(self):\n \"\"\"\n test posterior returned by the DAG,\n as well as samplings from this posterior\n \"\"\"\n fit_dag(self.simple_dag, fit_node_with_scipy)\n\n train_input_names = [\"x1\", \"x2\", \"x3\"]\n q = 1\n #new_input = torch.rand(self.batch_size, q, len(train_input_names))\n new_input = torch.rand(1, q, len(train_input_names))\n\n print(\"input shape: \", new_input.shape)\n\n pst = self.simple_dag.posterior(new_input, **{\"verbose\": True})\n\n print()\n print(\"posterior:\")\n print(pst.mean, pst.event_shape)\n sampler = SobolQMCNormalSampler(num_samples=3, seed=1234)\n samples = sampler(pst)\n print()\n print(\"sampling from posterior\")\n print(\n samples.shape\n ) # [sampler's num_samples, batch_size of input, q, DAG's num_of_output]\n print(samples)\n\n @unittest.skip(\"..\")\n def test_dag_inner_loop(self):\n \"\"\"\n test optimise the acquisition function\n \"\"\"\n fit_dag(self.simple_dag, fit_node_with_scipy)\n q = 1\n num_restarts = 24 # create batch shape for optimise acquisition func\n raw_samples = 48 # this create initial batch shape for optimise acquisition func\n\n # --- Botorch's acquisition function input to posterior\n print()\n logging.info(\"Botorch input shape: \")\n sampler = SobolQMCNormalSampler(num_samples=2048, seed=1234)\n acq = botorch.acquisition.monte_carlo.qExpectedImprovement(\n model=self.simple_dag,\n best_f=torch.tensor([1.]),\n sampler=sampler,\n objective=None, # use when model has multiple output\n )\n\n # inner loop\n candidates, val = botorch.optim.optimize_acqf(\n acq_function=acq,\n bounds=torch.tensor([\n [0, 0, 0],\n [1, 1, 1],\n ], dtype=torch.float64),\n q=q,\n num_restarts=num_restarts,\n raw_samples=raw_samples,\n sequential=False, # joint optimisation of q\n )\n query = candidates.detach()\n logging.info(\"candidates: \")\n print(query, val.detach())\n\n\nclass direct_dag_test(unittest.TestCase):\n \"\"\"\n test my impl of sampling from dagbo's approx. posterior\n \"\"\"\n def setUp(self):\n np.random.seed(0), torch.manual_seed(0)\n\n # define dag\n class TREE_DAG(SO_Dag, direct_DagGPyTorchModel):\n \"\"\"\n creation a simple tree-like DAG\n\n x1 x2 x3\n \\ / |\n z1 z2\n \\ /\n y\n \"\"\"\n def __init__(self, train_input_names: list[str],\n train_target_names: list[str], train_inputs: Tensor,\n train_targets: Tensor, num_samples: int):\n super().__init__(train_input_names, train_target_names,\n train_inputs, train_targets, \"cpu\")\n\n # required for all classes that extend SparkDag\n self.num_samples = num_samples\n\n def define_dag(self, batch_shape: Size = Size([])) -> None:\n x_1 = self.register_input(\"x1\")\n x_2 = self.register_input(\"x2\")\n x_3 = self.register_input(\"x3\")\n\n z_1 = self.register_metric(\"z1\", [x_1, x_2])\n z_2 = self.register_metric(\"z2\", [x_3])\n\n y = self.register_metric(\"y\", [z_1, z_2])\n\n train_input_names = [\n \"x1\",\n \"x2\",\n \"x3\",\n ]\n train_target_names = [\n \"z1\",\n \"z2\",\n \"y\",\n ]\n batch_size = 1\n num_samples = 2\n\n # create data\n #train_inputs = torch.linspace(0, 1, 7)\n train_inputs = torch.linspace(0, 2, 7)\n func = lambda x: torch.sin(x * (8 * math.pi)) + torch.cos(x * (\n 3 * math.pi)) + torch.log(x + 0.1) + 3\n #func = lambda x: torch.sin(x * math.pi)\n\n # reshape\n train_targets = func(train_inputs).reshape(-1, 1).expand(\n 1, 7, 2) # shape:[1, 7, 3]\n\n #print(train_targets[0])\n new_val = func(train_targets[..., -1].flatten()).reshape(1, 7, 1)\n train_targets = torch.cat([train_targets, new_val], dim=-1)\n #print(new_val)\n #print(train_targets[0])\n #raise ValueError(\"ok\")\n\n train_inputs = train_inputs.reshape(-1, 1).expand(1, 7,\n 3) # shape:[1, 7, 3]\n\n self.assertEqual(train_inputs.shape, torch.Size([1, 7, 3]))\n self.assertEqual(train_targets.shape, torch.Size([1, 7, 3]))\n\n self.func = func\n self.batch_size = batch_size\n self.num_samples = num_samples\n self.domain = (0, 2)\n self.simple_dag = TREE_DAG(train_input_names, train_target_names,\n train_inputs, train_targets, num_samples)\n\n @unittest.skip(\".\")\n def test_dag_posterior(self):\n \"\"\"\n test posterior returned by the DAG,\n as well as samplings from this posterior\n \"\"\"\n fit_dag(self.simple_dag, fit_node_with_scipy)\n\n train_input_names = [\"x1\", \"x2\", \"x3\"]\n q = 1\n #new_input = torch.rand(self.batch_size, q, len(train_input_names))\n new_input = torch.rand(1, q, len(train_input_names))\n\n print(\"input shape: \", new_input.shape)\n\n pst = self.simple_dag.posterior(new_input, **{\"verbose\": True})\n\n print()\n print(\"full posterior:\")\n print(pst.mean, pst.variance, pst.event_shape)\n sampler = SobolQMCNormalSampler(num_samples=3, seed=1234)\n samples = sampler(pst)\n print()\n print(\"sampling from posterior\")\n print(\n samples.shape\n ) # [sampler's num_samples, batch_size of input, q, DAG's num_of_output]\n #print(samples)\n\n @unittest.skip(\".\")\n def test_dag_inner_loop(self):\n \"\"\"\n batch average MC grad!!!\n\n original input X: [b, q, dim]\n original output y: [b, q] # becuase the output dim is 1, it is squeezed\n (where b dim is used as `raw_sample` or `num_restarts` in innner loop)\n\n now I want to repeat original process many times and take the average\n (sampling from approx. posterior)\n\n I unsqueeze a new sampling dimension: X [n, b, q, dim]\n which gives a `batch` output y: [n, b, q]\n\n and then i take average y -> y' = [b, q]\n gpytorch's MultivariateNormal is treated specially\n \"\"\"\n print()\n print(\"full dagbo inner loop:::\")\n fit_dag(self.simple_dag, fit_node_with_scipy)\n q = 1\n num_restarts = 3 # create batch shape for optimise acquisition func\n raw_samples = 4 # this create initial batch shape for optimise acquisition func\n\n # --- Botorch's acquisition function input to posterior\n print()\n logging.info(\"Botorch input shape: \")\n sampler = SobolQMCNormalSampler(num_samples=8, seed=1234)\n acq = botorch.acquisition.monte_carlo.qExpectedImprovement(\n model=self.simple_dag,\n best_f=torch.tensor([1.]),\n sampler=sampler,\n objective=None, # use when model has multiple output\n )\n\n # inner loop\n candidates, val = botorch.optim.optimize_acqf(\n acq_function=acq,\n bounds=torch.tensor([\n [0, 0, 0],\n [1, 1, 1],\n ], dtype=torch.float64),\n q=q,\n num_restarts=num_restarts,\n raw_samples=raw_samples,\n sequential=False, # joint optimisation of q\n )\n query = candidates.detach()\n logging.info(\"candidates: \")\n print(query, val.detach())\n\n\nif __name__ == '__main__':\n\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n handler = logging.StreamHandler()\n\n # create formatter and add it to the handler\n formatter = logging.Formatter(\n '%(asctime)s - %(filename)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n # add the handler to the logger\n logger.addHandler(handler)\n\n unittest.main()\n"
] |
[
[
"torch.cos",
"torch.linspace",
"torch.Size",
"numpy.log",
"numpy.random.seed",
"torch.cat",
"torch.sin",
"torch.manual_seed",
"torch.from_numpy",
"numpy.cos",
"torch.tensor",
"sklearn.metrics.mean_squared_error",
"numpy.sin",
"torch.log",
"torch.no_grad",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"sklearn.preprocessing.MinMaxScaler"
]
] |
santacml/Malware-as-Video
|
[
"12dc3954f2237cb34857a44eadbb5ca76f8e97b5"
] |
[
"libraries/createVectorizedAssembly.py"
] |
[
"from assemblyVectorizor import Vectorizor\nfrom postVectorizeDataEditor import *\nimport csv\nimport random\nimport numpy as np\n \n# helper functions\n \ndef runThroughGenerator(gen, steps):\n for x in range(0, int(steps)):\n train_x, train_y = next(gen)\n print(\"done gen\", x)\n \n \ndef getOpcodes(fileLines):\n newFileLines = [[], fileLines[1]]\n # 0/0\n for row in fileLines[0]:\n if len(row) > 0:\n # print(row)\n newFileLines[0].append([row[0]])\n # print(newFileLines[0][-1])\n \n return newFileLines\n \ndef padEachLine(fileLines, maxLineLen):\n # maxLineLen = vectorizor.maxLineLen\n emptyLine = [0] * maxLineLen\n \n \n for line in fileLines[0]:\n for n in range(0,maxLineLen-len(line)): line.append(0)\n \n while len(fileLines[0]) % 2500 != 0: # CHANGE ME interval len\n fileLines[0].append(emptyLine)\n \n # print(fileLines[0])\n \n return fileLines\n \ndef reformatLines(fileLines, rowSize):\n # reformat to no padding\n \n # rowSize = 10\n \n emptyLine = [0] * rowSize\n \n fileASM = [item for sublist in fileLines[0] for item in sublist]\n # print(fileASM)\n \n # this is super inefficient\n # print(fileLines)\n # pool 10 \n while len(fileASM) % (rowSize*rowSize) != 0:\n fileASM.append(0)\n \n fileASM = np.asarray(fileASM)\n \n # print(fileASM.reshape((-1, 25)))\n fileLines[0] = fileASM.reshape((-1, rowSize)).tolist()\n # print(len(fileLines[0]))\n \n while len(fileLines[0]) % (rowSize*rowSize*10) != 0: # CHANGE ME interval len\n fileLines[0].append(emptyLine)\n \n # print(fileLines[0])\n \n # print(0/0)\n return fileLines\n \n \n \n# raw vectorize functions take in .asm files and turn them into .pklz numpy files\n \ndef createRawVectorizedWindows(folderPrefix, vectorizedFolder, watchOutForDB=True):\n files = []\n import glob, os, gzip\n files.extend(glob.glob(folderPrefix + r\"\\*.lst\"))\n\n # random.shuffle(files)\n # THIS IS EITHER M OR R!!!!!!!!!!!!!!!!\n\n #first, turn into tokens, then call vectorizor\n\n f = None\n vectorizor = Vectorizor()\n\n \n # vectorizor.maxLineLen = 18\n # vectorizor.maxFileLen = 2277766\n\n numScanned = 0\n for file in files:\n \n print(file)\n name = os.path.basename(file)[:-4] # get rid of .asm, better way, idc\n answer = [0]\n \n # watchOutForDB controls for the db error at end of lines\n toPickle = vectorizor.vectorize(file, answer, watchOutForDB=watchOutForDB) # WILL HAVE [NEWLINES, ANSWER]\n \n # every 100 files start a new thing. Results in 100 folders? I guess.\n if numScanned % 500 == 0:\n if f: f.close()\n f = gzip.open(vectorizedFolder + r\"\\tempAssemblyVectorized\" + str(numScanned) + '.pklz', 'w+b') # this should clear\n \n if vectorizor.files:\n # pickle.dump(padEachLine(toPickle, 10), f) # just dump the one file we've scanned\n pickle.dump(toPickle, f) # just dump the one file we've scanned\n else:\n print(\"ERROR file:\", file) # this will happen if there are no files :) good job past me\n \n vectorizor.files = [] # idk, whatever. ducktaaaaaaaaaaaape\n \n numScanned += 1\n \n f.close()\n \n\n\n print(\"FINAL LENGTHS:\")\n print(\"Num of files:\", vectorizor.numFilesScanned)\n print(\"Num of lines per file:\", vectorizor.maxFileLen)\n print(\"banned vars\", len(vectorizor.bannedVars))\n \ndef createRawVectorizedKaggle(folderPrefix, vectorizedFolder):\n files = []\n import glob, os, gzip\n files.extend(glob.glob(folderPrefix + r\"\\*.asm\"))\n\n\n f = None\n vectorizor = Vectorizor()\n\n\n # vectorizor.maxLineLen = 18\n # vectorizor.maxFileLen = 480941\n \n answers = {}\n with open(\"kaggleTrainLabels.csv\", \"r\") as f:\n reader = csv.reader(f)\n for row in reader:\n name = row[0]\n answer = [int(row[1])]\n answers[name] = answer\n \n\n # '''\n # this section is for reading the raw, raw data and vectorizing\n # outputs the tempAssemblyVectorized.pklz files\n # record the maxLineLen and maxFileLen above to use for future\n # no real reason to ever do this again\n\n numScanned = 0\n for file in files:\n # if numScanned < 0: \n # numScanned += 1\n # continue # us this to manual override to a count\n \n print(file)\n name = os.path.basename(file)[:-4] # get rid of .asm, better way, idc\n answer = answers[name]\n \n # lines = Scanner().scan(file)\n # vectorizor.vectorize(lines, answer)\n \n toPickle = vectorizor.vectorize(file, answer) # WILL HAVE [NEWLINES, ANSWER]\n # print(0/0)\n # print(vectorizor.files)\n \n # every 500 files start a new thing. \n if numScanned % 500 == 0:\n if f: f.close()\n # f = open('tempAssemblyVectorized' + str(numScanned) + '.pklz', 'wb').truncate() # clear file\n f = gzip.open(vectorizedFolder + r\"\\tempAssemblyVectorized\" + str(numScanned) + '.pklz', 'w+b') # this should clear\n # f.truncate() # not in gzip\n # vectorizor.dumpVocab()\n \n if vectorizor.files:\n # pickle.dump(vectorizor.files[0], f) # just dump the one file we've scanned\n pickle.dump(toPickle, f) # just dump the one file we've scanned\n else:\n print(\"ERROR file:\", file) # this will happen if there are no files :) good job past me\n \n vectorizor.files = [] # idk, whatever. ducktaaaaaaaaaaaape\n \n numScanned += 1\n \n f.close()\n \n \n print(\"FINAL LENGTHS:\")\n print(\"Num of files:\", vectorizor.numFilesScanned)\n print(\"Num of lines per file:\", vectorizor.maxFileLen)\n print(\"Vocab size\", len(vectorizor.vars))\n \n # '''\n \n stats = {\n \"numFiles\": vectorizor.numFilesScanned,\n \"maxFileLen\": vectorizor.maxFileLen,\n \"vocabSize\": len(vectorizor.vars),\n \"maxLineLen\": vectorizor.maxLineLen\n }\n \n \n \n return stats\n\n \n# final vectorize files turn raw vectorized into \n \ndef createFinalVectorizedKaggleOnly(fullAssemblyFileName, validFileName, rawVectorizedPrefix, stats, numSamplesTrain, padLines=True, cutoff=None):\n if cutoff: print(\"Using cutoff\", cutoff)\n if padLines: print(\"PADDING EACH LINE\")\n # '''\n writeMe = gzip.open(fullAssemblyFileName, 'w+b')\n \n maxLineLen = stats[\"maxLineLen\"]\n \n shortFilesCount = 0\n fileCount = 0\n classCounts = [0]*10\n for x in range(0,10500, 500):\n # I only want one copy of all these, keep it here\n zippedFile = rawVectorizedPrefix + str(x) + \".pklz\"\n readMe = gzip.open(zippedFile, \"r\")\n while True:\n try:\n # grab 700 data samples, 200 validation\n if fileCount == numSamplesTrain:\n # if fileCount == 342: #9*38=342\n writeMe = gzip.open(validFileName, 'w+b') # this should clear\\\n \n fileLines = pickle.load(readMe)\n \n \n # OPTIONS\n while cutoff and len(fileLines[0]) > cutoff:\n print(\"class\", fileLines[1][0], \"over cutoff, trying again\")\n fileLines = pickle.load(readMe)\n # continue DOES NOT WORK biases dataset :(\n if padLines:\n pickle.dump(padEachLine(fileLines, maxLineLen), writeMe)\n else:\n pickle.dump(reformatLines(fileLines), writeMe)\n # pickle.dump(padEachLineKeep11(fileLines), writeMe)\n \n \n \n fileCount += 1\n classCounts[fileLines[1][0]] += 1\n print(\"file:\", fileCount, \"len\", len(fileLines[0]), classCounts)\n except EOFError:\n print(\"starting next file\", x)\n break\n \ndef createFinalVectorizedKaggleAndWindows(fullAssemblyFileName, validFileName, numSamplesTrain, totalSamples, malwareRawPrefix, winexeRawPrefix, windllRawPrefix,\n binaryAnswers=True, padLines=True, cutoff=None, zeroDayClass=None, zeroDayFileName=None, opcodesonly=False):\n print(\"creating final vectorized kaggle and windows\")\n if cutoff: print(\"Using cutoff\", cutoff)\n if padLines: print(\"padding each line\")\n if zeroDayClass is not None and zeroDayFileName: \n print(\"using 0 day class\", zeroDayClass)\n writeMe0Day = gzip.open(zeroDayFileName, 'w+b')\n if opcodesonly: print (\"using only opcodes\")\n writeMe = gzip.open(fullAssemblyFileName, 'w+b')\n\n shortFilesCount = 0\n fileCount = 0\n classCounts = [0]*12\n\n \n # train_count = 7500\n # total_count = 9100\n \n '''\n dlls cnt\n max ffile len 8406217\n 3907 files\n 702 windows files\n \n do 9100 total malware + windows + dlls\n \n \n for 45k cutoff: runs out of files around 6249\n to be safe:\n \n 5000 train\n 1200 test\n \n '''\n\n # for x in range(0,10500, 500):\n # while fileCount < total_count:\n xMalware = 0\n xBenign1 = 0\n xBenign2 = 0 \n\n # I only want one copy of all these, keep it here\n zippedFileMalware = malwareRawPrefix + str(xMalware) + \".pklz\"\n readMeMalware = gzip.open(zippedFileMalware, \"r\")\n\n zippedFileBenign1 = winexeRawPrefix + str(xBenign1) + \".pklz\"\n readMeBenign1 = gzip.open(zippedFileBenign1, \"r\")\n \n zippedFileBenign2 = windllRawPrefix + str(xBenign2) + \".pklz\"\n readMeBenign2 = gzip.open(zippedFileBenign2, \"r\")\n \n \n doneWithExes = False\n \n zeroDayCnt = 0\n while True:\n try:\n readMeNum = random.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])\n \n # grabs dlls and malware 2x the rate of exes!!!\n readMe = [readMeMalware, \n readMeMalware, \n readMeMalware, \n readMeMalware, \n readMeMalware, \n readMeMalware, \n readMeBenign1, \n readMeBenign2, \n readMeBenign2, \n readMeBenign2, \n readMeBenign2, \n readMeBenign2\n ][readMeNum]\n \n \n if fileCount == numSamplesTrain:\n writeMe = gzip.open(validFileName, 'w+b') # this should clear\n if fileCount == totalSamples: \n break\n \n fileLines = pickle.load(readMe)\n \n \n while cutoff and len(fileLines[0]) > cutoff:\n # print(\"class\", readMeNum, \"over cutoff, trying again\")\n fileLines = pickle.load(readMe)\n \n # if opcodesonly:\n # fileLines = getOpcodes(fileLines)\n \n while readMeNum < 6 and zeroDayClass and fileLines[1][0] == zeroDayClass:\n print(\"found 0 day class, writing to 0day file and rereading\")\n fileLines[1] = 1\n # writeMe0Day\n if padLines:\n # MICHAEL - 18 is maxLineLen... idk\n pickle.dump(padEachLine(fileLines, 18), writeMe0Day)\n else:\n # rowSize = 10\n rowSize = 25\n # pickle.dump(reformatLines(getOpcodes(fileLines), rowSize), writeMe0Day)\n pickle.dump(reformatLines(fileLines, rowSize), writeMe0Day)\n \n zeroDayCnt += 1\n fileLines = pickle.load(readMe)\n \n\n if opcodesonly:\n fileLines = getOpcodes(fileLines)\n \n if binaryAnswers:\n if readMeNum < 6:\n # 0 malware\n fileLines[1] = 1 # set all malware to class 1!!!!!\n else:\n # 1 is benign\n fileLines[1] = 0 # make sure benign is 0 - I think it's 1 in assemblyVectorizor\n else:\n if readMeNum < 6:\n # malware\n pass\n fileLines[1] = fileLines[1][0]\n # leave fileLines alone\n elif readMeNum == 6:\n if not doneWithExes:\n fileLines[1] = 10\n else: \n fileLines[1] = 11\n print(\"we hit a exe randomly but no more exes left!\")\n else: \n # 3, 4\n \n fileLines[1] = 11\n \n \n if padLines:\n # MICHAEL - 18 is maxLineLen... idk\n pickle.dump(padEachLine(fileLines, 18), writeMe)\n else:\n # rowSize = 10\n rowSize = 25\n # I was worried for a second as this said writeMe0day\n # but that's because I copy pasted it\n # we gooooooooooooooooood\n pickle.dump(reformatLines(fileLines, rowSize), writeMe)\n \n classCounts[fileLines[1]] += 1\n fileCount += 1\n print(\"file:\", fileCount, \"len\", len(fileLines[0]), \"type\", readMeNum, \"answer\", fileLines[1], classCounts)\n except EOFError:\n print (\"Error reading num\", readMeNum, \"starting next file\")\n if readMeNum < 6:\n xMalware += 500\n zippedFileMalware = malwareRawPrefix + str(xMalware) + \".pklz\"\n readMeMalware = gzip.open(zippedFileMalware, \"r\")\n \n elif readMeNum == 6:\n # exes !!!\n if doneWithExes:\n xBenign2 += 500\n zippedFileBenign2 = windllRawPrefix + str(xBenign2) + \".pklz\"\n readMeBenign2 = gzip.open(zippedFileBenign2, \"r\")\n readMeBenign1 = readMeBenign2\n else:\n xBenign1 += 500\n if xBenign1 == 1000:\n doneWithExes = True\n \n if doneWithExes:\n # should only ever hit this once\n # catch up with the dlls here\n # then from then on, keep them in sync\n readMeBenign1 = readMeBenign2\n else:\n zippedFileBenign1 = winexeRawPrefix + str(xBenign1) + \".pklz\"\n readMeBenign1 = gzip.open(zippedFileBenign1, \"r\")\n \n else :\n xBenign2 += 500\n zippedFileBenign2 = windllRawPrefix + str(xBenign2) + \".pklz\"\n readMeBenign2 = gzip.open(zippedFileBenign2, \"r\")\n # 3 and 4\n # dlls!\n if doneWithExes:\n readMeBenign1 = readMeBenign2\n \n \n if zeroDayClass is not None and zeroDayFileName:\n return zeroDayCnt\n \ndef compileKaggleAndWindows():\n \n # filePrefix = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\Win10Home_x86_1803_dlls_disassembled\" \n # vectorizedFolder = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\opcodes_windowsdllvectorized\"\n # createRawVectorizedWindows(filePrefix, vectorizedFolder)\n \n # filePrefix = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\Win10Home_x86_1803_exes_disassembled\" \n # vectorizedFolder = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\opcodes_windowsvectorized\"\n # createRawVectorizedWindows(filePrefix, vectorizedFolder)\n \n # 0/0\n \n numSamplesTrain = 7500\n totalSamples = 9100\n numSamplesValid = totalSamples - numSamplesTrain\n \n fullAssemblyFileName = r\".\\datasets\\opcodes_windows_exe_dll_kaggle_nopad.pklz\"\n validFileName = r\".\\datasets\\opcodes_windows_exe_dll_kaggle_validation_nopad.pklz\"\n malwareRawPrefix = r\".\\datasets\\vectorized_kaggle\\tempAssemblyVectorized\"\n winexeRawPrefix = r\".\\datasets\\vectorized_windows\\tempAssemblyVectorized\"\n dllRawPrefix = r\".\\datasets\\vectorized_windows\\tempAssemblyVectorized\"\n \n createFinalVectorizedKaggleAndWindows(fullAssemblyFileName, validFileName, numSamplesTrain, totalSamples, malwareRawPrefix, winexeRawPrefix, dllRawPrefix,\n binaryAnswers=True, padLines=False, opcodesonly=True)\n \n fullAssemblyNamePooled = r\".\\datasets\\opcodes_windows_exe_dll_kaggle_nopad_pooled.pklz\"\n validFileNamePooled = r\".\\datasets\\opcodes_windows_exe_dll_kaggle_validation_nopad_pooled.pklz\"\n \n train_gen = loadDataGeneratorBatchesAndPoolBinary(fullAssemblyFileName, numSamplesTrain, fullAssemblyNamePooled)\n valid_gen = loadDataGeneratorBatchesAndPoolBinary(validFileName, numSamplesValid, validFileNamePooled)\n \n '''\n # train_gen = loadDataGeneratorBatchesAndSlideWindow(r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\trainASM_all_pooled.pklz\", numSamplesTrain,\n # r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\trainASM_all_pooled.pklz\"\n # )\n # valid_gen = loadDataGeneratorBatchesAndSlideWindow(r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\validASM_all_pooled.pklz\", numSamplesValid,\n # r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\validASM_all_pooled.pklz\"\n # )\n '''\n\n runThroughGenerator(train_gen, numSamplesTrain)\n runThroughGenerator(valid_gen, numSamplesValid)\n \ndef compileKaggleAndWindows50kCutoff():\n print(\"compiling kaggle and windows with 45k cutoff\")\n # numSamplesTrain = 5000\n # totalSamples = 6200\n numSamplesTrain = 4000\n totalSamples = 5000\n numSamplesValid = totalSamples - numSamplesTrain\n \n \n fullAssemblyFileName = r\".\\datasets\\kagglewindows\\no50k\\windows_exe_dll_kaggle_no50k.pklz\"\n validFileName = r\".\\datasets\\kagglewindows\\no50k\\windows_exe_dll_kaggle_validation_no50k.pklz\"\n malwareRawPrefix = r\".\\datasets\\vectorized_kaggle\\tempAssemblyVectorized\"\n winexeRawPrefix = r\".\\datasets\\vectorized_windows\\tempAssemblyVectorized\"\n dllRawPrefix = r\".\\datasets\\vectorized_windows\\tempAssemblyVectorized\"\n \n createFinalVectorizedKaggleAndWindows(fullAssemblyFileName, validFileName, numSamplesTrain, totalSamples, malwareRawPrefix, winexeRawPrefix, dllRawPrefix,\n binaryAnswers=True, cutoff=50000)\n \n fullAssemblyNamePooled = r\".\\datasets\\kagglewindows\\no50k\\windows_exe_dll_kaggle_no50k_pooled.pklz\"\n validFileNamePooled = r\".\\datasets\\kagglewindows\\no50k\\windows_exe_dll_kaggle_validation_no50k_pooled.pklz\"\n \n train_gen = loadDataGeneratorBatchesAndPoolBinary(fullAssemblyFileName, numSamplesTrain, fullAssemblyNamePooled)\n valid_gen = loadDataGeneratorBatchesAndPoolBinary(validFileName, numSamplesValid, validFileNamePooled)\n \n '''\n # train_gen = loadDataGeneratorBatchesAndSlideWindow(r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\trainASM_all_pooled.pklz\", numSamplesTrain,\n # r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\trainASM_all_pooled.pklz\"\n # )\n # valid_gen = loadDataGeneratorBatchesAndSlideWindow(r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\validASM_all_pooled.pklz\", numSamplesValid,\n # r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\validASM_all_pooled.pklz\"\n # )\n '''\n\n runThroughGenerator(train_gen, numSamplesTrain)\n runThroughGenerator(valid_gen, numSamplesValid)\n \ndef compileKaggleAndWindows0Day():\n \n # filePrefix = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\Win10Home_x86_1803_dlls_disassembled\" \n # vectorizedFolder = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\windowsdllvectorized\"\n # createRawVectorizedWindows(filePrefix, vectorizedFolder)\n \n # filePrefix = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\Win10Home_x86_1803_exes_disassembled\" \n # vectorizedFolder = r\"D:\\Research\\7_Windows_Malware_Detection\\dataset\\windows_dataset\\windowsvectorized\"\n # createRawVectorizedWindows(filePrefix, vectorizedFolder)\n \n # 0/0\n \n numSamplesTrain = 7500\n totalSamples = 9100\n numSamplesValid = totalSamples - numSamplesTrain\n \n fullAssemblyFileName = r\".\\datasets\\kagglewindows0day\\winkaggle_noclass8_nopad.pklz\"\n validFileName = r\".\\datasets\\kagglewindows0day\\winkaggle_noclass8_validation_nopad.pklz\"\n zeroDayClass = 8\n zeroDayFileName = r\".\\datasets\\kagglewindows0day\\winkaggle_onlyclass8_nopad.pklz\"\n \n malwareRawPrefix = r\".\\datasets\\vectorized_kaggle\\tempAssemblyVectorized\"\n winexeRawPrefix = r\".\\datasets\\vectorized_windows\\tempAssemblyVectorized\"\n dllRawPrefix = r\".\\datasets\\vectorized_windows\\tempAssemblyVectorized\"\n \n \n zeroDayCnt = createFinalVectorizedKaggleAndWindows(fullAssemblyFileName, validFileName, numSamplesTrain, totalSamples, malwareRawPrefix, winexeRawPrefix, dllRawPrefix,\n binaryAnswers=True, padLines=False, zeroDayClass=zeroDayClass, zeroDayFileName=zeroDayFileName)\n \n fullAssemblyNamePooled = r\".\\datasets\\kagglewindows0day\\winkaggle_noclass8_nopad_pooled.pklz\"\n validFileNamePooled = r\".\\datasets\\kagglewindows0day\\winkaggle_noclass8_validation_nopad_pooled.pklz\"\n zeroDayFileNamePooled = r\".\\datasets\\kagglewindows0day\\winkaggle_onlyclass8_nopad_pooled.pklz\"\n \n train_gen = loadDataGeneratorBatchesAndPoolBinary(fullAssemblyFileName, numSamplesTrain, fullAssemblyNamePooled)\n valid_gen = loadDataGeneratorBatchesAndPoolBinary(validFileName, numSamplesValid, validFileNamePooled)\n zero_gen = loadDataGeneratorBatchesAndPoolBinary(zeroDayFileName, zeroDayCnt, zeroDayFileNamePooled)\n \n '''\n # train_gen = loadDataGeneratorBatchesAndSlideWindow(r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\trainASM_all_pooled.pklz\", numSamplesTrain,\n # r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\trainASM_all_pooled.pklz\"\n # )\n # valid_gen = loadDataGeneratorBatchesAndSlideWindow(r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\validASM_all_pooled.pklz\", numSamplesValid,\n # r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\vectorized\\validASM_all_pooled.pklz\"\n # )\n '''\n\n runThroughGenerator(train_gen, numSamplesTrain)\n runThroughGenerator(valid_gen, numSamplesValid)\n runThroughGenerator(zero_gen, zeroDayCnt)\n \n print(\"zero day cnt\", zeroDayCnt)\n \n \n \n \ndef compileKaggle():\n # folderPrefix = r\"D:\\Research\\KAGGLE_FULL_DATASET\" \n # vectorizedFolder = r\"D:\\Research\\2_Malware_Detection\\kaggle_dataset\\tempAssemblyVectorized\"\n # stats = createRawVectorizedKaggle(folderPrefix, vectorizedFolder)\n \n stats = {\n \"numFiles\": 2375 + 8000,\n # \"maxLineLen\": 18\n }\n \n rawVectorizedPrefix = r\"\\datasets\\vectorized_kaggle\\tempAssemblyVectorized\"\n vectorizedPrefix = r\".\\datasets\\kaggle\"\n \n fullAssemblyFileName = vectorizedPrefix + r\"\\trainASM_all_nopad_250.pklz\"\n validFileName = vectorizedPrefix + r\"\\validASM_all_nopad_250.pklz\"\n \n fullAssemblyNamePooled = vectorizedPrefix + r\"\\trainASM_all_nopad_250_pooled.pklz\"\n validFileNamePooled = vectorizedPrefix + r\"\\validASM_all_nopad_250_pooled.pklz\"\n \n \n numSamplesTrain = 8000\n numSamplesValid = stats[\"numFiles\"] - numSamplesTrain\n \n # use following to pad lines!\n # createFinalVectorizedKaggleOnly(fullAssemblyFileName, validFileName, rawVectorizedPrefix, stats, numSamplesTrain)\n createFinalVectorizedKaggleOnly(fullAssemblyFileName, validFileName, rawVectorizedPrefix, stats, numSamplesTrain, padLines=False)\n \n train_gen = loadDataGeneratorBatchesAndPool(fullAssemblyFileName, numSamplesTrain, fullAssemblyNamePooled)\n valid_gen = loadDataGeneratorBatchesAndPool(validFileName, numSamplesValid, validFileNamePooled)\n \n runThroughGenerator(train_gen, numSamplesTrain)\n runThroughGenerator(valid_gen, numSamplesValid)\n \n # for overlapSize in [15, 20]:\n # print(\"DOING overlapSize\", overlapSize)\n # fullAssemblyNamePooledWindows = vectorizedPrefix + r\"\\trainASM_all_nopad_pooled_window\" + str(overlapSize) + r\".pklz\"\n # validFileNamePooledWindows = vectorizedPrefix + r\"\\validASM_all_nopad_pooled_window\" + str(overlapSize) + r\".pklz\"\n \n # train_gen = loadDataGeneratorBatchesAndSlideWindow(fullAssemblyNamePooled, numSamplesTrain,fullAssemblyNamePooledWindows,overlapSize)\n # valid_gen = loadDataGeneratorBatchesAndSlideWindow(validFileNamePooled, numSamplesValid,validFileNamePooledWindows,overlapSize)\n \n # runThroughGenerator(train_gen, numSamplesTrain)\n # runThroughGenerator(valid_gen, numSamplesValid)\n \n pass\n \ndef compileKaggle50kCutoff():\n \n # 8556 files under 45k\n # 6500 train, 2556 valid\n stats = {\n \"numFiles\": 2050 + 6500,\n \"maxLineLen\": 18\n }\n \n rawVectorizedPrefix = r\".\\datasets\\vectorized_kaggle\\tempAssemblyVectorized\"\n vectorizedPrefix = r\".\\datasets\\kaggle\"\n \n fullAssemblyFileName = vectorizedPrefix + r\"\\trainASM_no50k.pklz\"\n validFileName = vectorizedPrefix + r\"\\validASM_no50k.pklz\"\n \n fullAssemblyNamePooled = vectorizedPrefix + r\"\\trainASM_no50k_pooled.pklz\"\n validFileNamePooled = vectorizedPrefix + r\"\\validASM_no50k_pooled.pklz\"\n \n \n numSamplesTrain = 6500\n numSamplesValid = stats[\"numFiles\"] - numSamplesTrain\n \n createFinalVectorizedKaggleOnly(fullAssemblyFileName, validFileName, rawVectorizedPrefix, stats, numSamplesTrain, cutoff=50000)\n \n train_gen = loadDataGeneratorBatchesAndPool(fullAssemblyFileName, numSamplesTrain, fullAssemblyNamePooled)\n valid_gen = loadDataGeneratorBatchesAndPool(validFileName, numSamplesValid, validFileNamePooled)\n \n runThroughGenerator(train_gen, numSamplesTrain)\n runThroughGenerator(valid_gen, numSamplesValid)\n \n \n \nif __name__ == \"__main__\": \n # compileKaggle()\n \n # countFiles()\n \n # compileKaggleAndWindows0Day()\n compileKaggleAndWindows()\n import os\n # os.system(r'python D:\\Research\\6_MaV\\train.py')\n \n "
] |
[
[
"numpy.asarray"
]
] |
lakshika1064/covid19-prediction-using-SIR-model
|
[
"91c7445807e678dfb15c24056b5b7af40ca00afc"
] |
[
"COVID19--ZEPL.py"
] |
[
"conn = z.getDatasource(\"snowflake_CP99894apsouth1aws_faa2e8\")\n\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport requests\nimport io\nfrom datetime import datetime\nimport scipy\nimport operator\nfrom scipy.integrate import solve_ivp\nfrom scipy.integrate import odeint\n\nwarehouse = \"PC_ZEPL_WH\"\ndatabase = \"PC_ZEPL_DB\"\nstage_table = \"data_stage\"\n\n\ndef transp(data, file_name):\n data = data[data[\"Country/Region\"] == \"India\"]\n data = data.drop([\"Province/State\", \"Country/Region\", \"Lat\", \"Long\"], axis=1)\n data = data.T\n data.to_csv(file_name)\n\n\n# recovered people data\nread_csv = requests.get(\n \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv\").content\nrecovered_df = pd.read_csv(io.StringIO(read_csv.decode('utf-8')))\ntransp(recovered_df, \"recovered_timeseries.csv\")\nrecovered_df = pd.read_csv(\"recovered_timeseries.csv\")\nrecovered_df.columns = [\"Date\", \"Recover\"]\nrecovered_df[\"Date\"] = (pd.to_datetime(recovered_df[\"Date\"])).dt.strftime(\"%Y-%m-%d\")\nrecovered_df.to_csv(\"recovered_timeseries.csv\", index=False)\nrecovered_df = pd.read_csv(\"recovered_timeseries.csv\")\n\n# confirmed and deaths\nurl = \"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv\"\nread_csv = requests.get(url).content\naddress = pd.read_csv(io.StringIO(read_csv.decode('utf-8')))\naddress.to_csv(\"covid_data.csv\", index=False)\naddress = pd.read_csv(\"covid_data.csv\")\n\n\n# print(address.head())\n\n\ndef execute_result(connection, query):\n final_result = connection.execute(query).fetchall()\n return final_result\n\n\ntry:\n sql = 'use role {}'.format('PC_ZEPL_ROLE')\n conn.execute(sql)\n\n sql = 'use database {}'.format(database)\n conn.execute(sql)\n\n sql = 'use warehouse {}'.format(warehouse)\n conn.execute(sql)\n\n sql = 'use schema {}'.format('PUBLIC')\n conn.execute(sql)\n\n try:\n sql = 'alter warehouse {} resume'.format(warehouse)\n conn.execute(sql)\n except:\n pass\n\n try:\n sql = 'drop table covid_data'\n conn.execute(sql)\n print(\"6\")\n except:\n pass\n\n sql = 'create table covid_data(iso_code VARCHAR, ' \\\n 'continent VARCHAR ,location VARCHAR ,date DATE, total_cases INT ,new_cases Double, total_deaths INT,new_deaths INT,' \\\n 'total_cases_per_million DOUBLE, new_cases_per_million DOUBLE , total_deaths_per_million DOUBLE,' \\\n ' new_deaths_per_million DOUBLE,total_tests INT,new_tests INT,new_test_smoothed DOUBLE, total_tests_per_thousand DOUBLE,' \\\n 'new_tests_per_thousand DOUBLE ,new_test_smoothed_per_thousand DOUBLE, tests_units VARCHAR,stringency_index BIGINT,population DOUBLE ,population_density DOUBLE ,' \\\n 'median_age DOUBLE ,aged_65_older DOUBLE ,aged_70_older DOUBLE ,gdp_per_capita DOUBLE ,' \\\n 'extreme_poverty DOUBLE,cvd_death_rate DOUBLE ,diabetes_prevalence DOUBLE , female_smokers DOUBLE ' \\\n ',male_smokers DOUBLE ,handwashing_facilities DOUBLE , hospital_beds_per_100k DOUBLE)'\n conn.execute(sql)\n # print(\"7\")\n\n try:\n sql = 'drop stage if exists data_stage'\n conn.execute(sql)\n except:\n pass\n\n sql = \"\"\"create stage data_stage file_format = (type = \"csv\" field_delimiter = \",\" skip_header = 1 FIELD_OPTIONALLY_ENCLOSED_BY = '\"')\"\"\"\n conn.execute(sql)\n\n csv_file = 'covid_data.csv'\n sql = \"PUT file://\" + csv_file + \" @DATA_STAGE auto_compress=true\"\n conn.execute(sql)\n\n sql = \"\"\"copy into covid_data from @DATA_STAGE/covid_data.csv.gz file_format = (type = \"csv\" field_delimiter = \",\" skip_header = 1 FIELD_OPTIONALLY_ENCLOSED_BY = '\"' ERROR_ON_COLUMN_COUNT_MISMATCH = FALSE)\"\"\" \\\n \"\"\"ON_ERROR = \"ABORT_STATEMENT\" \"\"\"\n conn.execute(sql)\n # print(\"11\")\n\n try:\n sql = 'DROP TABLE INDIA_DATA'\n conn.execute(sql)\n # print(12)\n except:\n pass\n\n sql = \"CREATE TABLE INDIA_DATA AS SELECT * FROM COVID_DATA WHERE LOCATION = 'India' AND Date > '2020-01-30'\"\n conn.execute(sql)\n # print(13)\n\n try:\n sql = 'DROP TABLE RECOVERED_DATA'\n conn.execute(sql)\n # print(12)\n except:\n pass\n\n sql = \"CREATE TABLE RECOVERED_DATA(date DATE,recover INT)\"\n conn.execute(sql)\n print(\"8\")\n\n csv_file = 'recovered_timeseries.csv'\n sql = \"PUT file://\" + csv_file + \" @DATA_STAGE auto_compress=true\"\n conn.execute(sql)\n print(\"10\")\n\n sql = \"\"\"copy into RECOVERED_DATA from @DATA_STAGE/recovered_timeseries.csv.gz file_format = (type = \"csv\" field_delimiter = \",\" skip_header = 1 FIELD_OPTIONALLY_ENCLOSED_BY = '\"' ERROR_ON_COLUMN_COUNT_MISMATCH = FALSE)\"\"\" \\\n \"\"\"ON_ERROR = \"ABORT_STATEMENT\" \"\"\"\n conn.execute(sql)\n print(\"11\")\n\n sql = \"SELECT TOTAL_CASES+NEW_CASES FROM INDIA_DATA ORDER BY DATE DESC LIMIT 12\"\n res = execute_result(conn, sql)\n confirmed = [item for t in res for item in t]\n confirmed.sort()\n\n sql = \"SELECT RECOVER FROM RECOVERED_DATA ORDER BY DATE DESC LIMIT 1\"\n res = execute_result(conn, sql)\n recovered = [item for t in res for item in t]\n\n sql = \"SELECT DATE FROM RECOVERED_DATA ORDER BY DATE DESC LIMIT 1\"\n res = execute_result(conn, sql)\n start_date = [item for t in res for item in t]\n start_date = start_date[0]\n\n sql = \"SELECT TOTAL_DEATHS FROM INDIA_DATA ORDER BY DATE DESC LIMIT 1\"\n res = execute_result(conn, sql)\n deaths = [item for t in res for item in t]\n\n sql = \"select DISTINCT(POPULATION) from INDIA_DATA\"\n res = execute_result(conn, sql)\n population = [item for t in res for item in t]\n population = population[0]\n\n # model creation\n sigma = 4.4\n beta_sum = 0\n recovery_rate = 1 / 14\n for i in range(10):\n cases_day_1 = confirmed[i]\n cases_day_2 = confirmed[i + 1]\n cases_day_3 = confirmed[i + 2]\n infected_ratio_day_1 = cases_day_1 / population\n infected_ratio_day_2 = cases_day_2 / population\n infected_ratio_day_3 = cases_day_3 / population\n ej1 = (infected_ratio_day_2 - infected_ratio_day_1 + (recovery_rate * infected_ratio_day_1)) / sigma\n ej2 = (infected_ratio_day_3 - infected_ratio_day_2 + (recovery_rate * infected_ratio_day_2)) / sigma\n r1 = recovery_rate * infected_ratio_day_1\n s1 = 1 - (infected_ratio_day_1 + ej1 + r1)\n beta = (ej2 - ej1 + (sigma * ej1)) / (s1 * infected_ratio_day_1)\n beta_sum += beta\n\n contact_rate = beta_sum / 12\n\n Last_infected, Last_recovered = confirmed[-1], recovered[0] # Initial conditions for infected and recovered people\n Last_deaths = deaths[0]\n\n everyone_else = population - Last_infected - Last_recovered - Last_deaths # Initial conditions for everyone else.\n\n Current_condition = everyone_else, Last_infected, Last_recovered\n\n time = np.linspace(0, 8, num=8)\n\n\n def SIR(Current_condition, t, population, contact_rate, recovery_rate):\n S, I, R = Current_condition\n dS = -contact_rate * S * I / population\n dI = contact_rate * S * I / population - recovery_rate * I\n dR = recovery_rate * I\n return dS, dI, dR\n\n\n future_forecast_dates = []\n for i in range(9):\n future_forecast_dates.append((start_date + timedelta(days=i)).strftime(\"%m/%d/%Y\"))\n print(future_forecast_dates)\n result = odeint(SIR, Current_condition, time, args=(population, contact_rate, recovery_rate))\n S, I, R = result.T\n prediction = set(zip(future_forecast_dates[-10:], I, R))\n prediction = pd.DataFrame(prediction)\n prediction.columns = ['date', 'Infected', 'recovered']\n # print(prediction.head())\n minValue = prediction['date'].min()\n # prediction.sort_values(by=['date'],axis=1)\n # prediction.drop(prediction.index[[0]])\n # prediction= prediction.drop(prediction['date'].idxmin())\n prediction.drop(prediction[prediction['date'] == minValue].index, inplace=True)\n # print(prediction)\n\n sql = 'DELETE FROM TEMP_TABLE'\n conn.execute(sql)\n\n # sql = 'CREATE TABLE TEMP_TABLE(date DATE,infected DOUBLE , recovered DOUBLE)'\n # conn.execute(sql)\n\n prediction.to_csv(\"prediction_data.csv\", index=False)\n prediction = pd.read_csv(\"prediction_data.csv\")\n\n csv_file = 'prediction_data.csv'\n sql = \"PUT file://\" + csv_file + \" @DATA_STAGE auto_compress=true\"\n conn.execute(sql)\n\n sql = 'copy into TEMP_TABLE from @DATA_STAGE/prediction_data.csv.gz ' \\\n 'file_format = (type = \"csv\" field_delimiter = \",\" skip_header = 1)' \\\n 'ON_ERROR = \"ABORT_STATEMENT\" '\n conn.execute(sql)\n\n # UPDATE THE PREDICTION TABLE FOR INFECTED PERSON\n # sql = \"MERGE INTO PREDICTION P USING INDIA_DATA I ON (I.DATE = P.DATE) WHEN MATCHED THEN UPDATE SET P.INFECTED = I.TOTAL_CASES+I.NEW_CASES\"\n # conn.execute(sql)\n\n # UPDATE THE PREDICTION TABLE FOR PREDICTED DATA\n # sql = \"MERGE INTO PREDICTION P USING TEMP_TABLE T ON (P.DATE = T.DATE) WHEN MATCHED THEN UPDATE SET P.PREDICTION_INFECTED = T.INFECTED WHEN NOT MATCHED THEN INSERT(DATE,PREDICTION_INFECTED) VALUES (T.DATE,T.INFECTED)\"\n # conn.execute(sql)\n\n\n\nexcept Exception as e:\n print(e)\n\n"
] |
[
[
"pandas.read_csv",
"pandas.to_datetime",
"numpy.linspace",
"pandas.DataFrame",
"scipy.integrate.odeint"
]
] |
cbilodeau2/hgraph2graph
|
[
"cde0630b2de7f63125b3d296450409d45b62f4a8"
] |
[
"generate_augmented_pair_list.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport argparse\n\nfrom rdkit.Chem.Descriptors import ExactMolWt\nfrom rdkit import Chem\n\nfrom chemprop.data.scaffold import generate_scaffold\nfrom hgraph.pairing import *\n\n# SETTINGS:\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--gen_out', type=str, required=True) # Input: Pairs generated during generation step\nparser.add_argument('--gen_evaluated', type=str, required=True) # Input: Predictions generated for all molecules after generation step\nparser.add_argument('--datafile', type=str, required=True) # Output: Labeled data file\nparser.add_argument('--molfile', type=str, required=True) # Output: Mol file for next iteration\nparser.add_argument('--pairfile', type=str, required=True) # Output: Pair file for next iteration\nparser.add_argument('--threshold', type=float, default=0.78) # Molecules must improve by this much to be considered a successful translation\nparser.add_argument('--pairgen_cutoff', type=float, default=0.78) # Threshold used to generate new pairs\nparser.add_argument('--pairgen_sample', type=int, default=20) # Number of pairs to generate per molecule\nparser.add_argument('--min_mol_wt', type=float, default=50.0) # Lowest molecular weight to include for successful translation\nparser.add_argument('--target', type=str, default='Target') # Y column title (in gen_evaluated input file)\n\nargs = parser.parse_args()\n\npaired = pd.read_csv(args.gen_out,header=None,sep=' ')\nlabeled = pd.read_csv(args.gen_evaluated)\npaired = paired.rename(columns={0:'X',1:'Y'})\n\n# Remove molecules that don't improve enough:\npaired['Targetx']=paired['X'].apply(lambda x: labeled[labeled[labeled.columns[0]]==x][labeled.columns[1]].iloc[0])\npaired['Targety']=paired['Y'].apply(lambda x: labeled[labeled[labeled.columns[0]]==x][labeled.columns[1]].iloc[0])\npaired = paired[(paired['Targety']-paired['Targetx'])>args.threshold]\n\n# Remove Y molecules with low mw:\npaired['MolWt Y'] = paired['Y'].apply(lambda x: ExactMolWt(Chem.MolFromSmiles(x)))\npaired = paired[paired['MolWt Y']>args.min_mol_wt]\n\n# Remove molecules outside scaffold\npaired['Scaffoldx'] = paired['X'].apply(generate_scaffold)\npaired['Scaffoldy'] = paired['Y'].apply(generate_scaffold)\npaired = paired[paired['Scaffoldx']==paired['Scaffoldy']]\n\n# Make labeled dataset for input into next iteration:\nx_labeled = paired[['X','Targetx']].rename(columns={'X':'SMILES','Targetx':'Target'})\ny_labeled = paired[['Y','Targety']].rename(columns={'Y':'SMILES','Targety':'Target'})\nlabeled = pd.DataFrame(labeled.dropna().values,columns=['SMILES','Target'])\n\ndata_out = pd.concat([x_labeled,y_labeled,labeled]).drop_duplicates()\n\n# Save data.csv file\ndata_out.to_csv(args.datafile,index=False)\n\n# Generate new input files for next iteration (mols.txt, train_pairs.txt)\ngenerate_pairs(args.datafile,args.pairfile,args.molfile,'Target',args.pairgen_cutoff, args.pairgen_sample,remove_tails_flag=False)\n\n\n"
] |
[
[
"pandas.concat",
"pandas.read_csv"
]
] |
janursa/realtime_plotting
|
[
"936cde4e6d15b1a538712d77398f5c7052a0ce9b"
] |
[
"realtime/monitor.py"
] |
[
"\n\"\"\"This module is designed to visualize csv files on a browser in a real time fashion. \nAuthor: Jalil Nourisa\n\n\"\"\"\nimport sys, time, os\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport pandas as pd\nimport plotly\nimport numpy as np\nfrom copy import deepcopy\nfrom .buildin import plots\nimport copy\n\ndef _get_docs_index_path(): # returns dir of the documentation file\n docs_index = os.path.join('docs', 'build', 'html', 'index.html')\n return docs_index\ndef _docstring_parameter(*args, **kwargs): # addes keywords to the docstring\n def dec(obj):\n obj.__doc__ = obj.__doc__.format(*args, **kwargs)\n return obj\n return dec\n \nclass _externals:\n @staticmethod\n def get_stylesheets():\n return [ \"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css\"]\n @staticmethod\n def get_scripts():\n return ['https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js']\n\n\n@_docstring_parameter(_get_docs_index_path())\nclass watch:\n \"\"\"This is the main class to read the files, construct plots and monitor changes.\n \"\"\"\n colors = ['blue','green','red','black','purple']\n def __init__(self,info):\n \"\"\"Initialize the app by setting up the framework py::meth:`frame` and callback functions py::meth:`callbacks`.\n \n Args:\n info (dict): The specifications of the plots entered by the user.\n \"\"\"\n # generated FIGs tagged with the figure name\n self.FIGS = {} \n self.relayoutDatas = {} \n # database\n self.specs = info \n # class type for the arrangment of graphs\n self.cols = {}\n for key,spec in self.specs.items():\n if 'col' not in spec:\n if key == 'Cells':\n spec.update({'col':'col s6'})\n else:\n spec.update({'col':'col s3'})\n self.cols.update({key:spec['col']})\n \n self.color_map = {} # maps color to each type in scatter plots\n self.app = dash.Dash(__name__,\n external_stylesheets = _externals.get_stylesheets(),\n external_scripts = _externals.get_scripts())\n\n self.app.css.config.serve_locally = True\n self.app.scripts.config.serve_locally = True\n\n self.update_iteration = 0 # to keep the record that how many time graphs are updated\n self.initialize()\n def initialize(self):\n self.update_db()\n self.frame()\n self.callbacks()\n\n def postprocess(self,name,df,fig_type):\n \"\"\"\n This function catches errors in the input file as well as addes generic size and type columns in case they are not given in the file. \n For the case of custom plots, the process is skipped.\n For the case of scatter and scatter3, this function also categorize data based on given types.\n \n Args:\n df (DataFrame): Data read from the directory file. This data needs processing.\n fig_type (TYPE): The type of the plot, i.e. lines and scatter.\n \n Returns:\n DataFrame: The processed data.\n \"\"\"\n if \"Unnamed: 0\" in df.keys(): # processing some errors\n df = df.drop(\"Unnamed: 0\", axis=1)\n\n if fig_type == \"custom\": #custom plot is given\n pass\n else: # add these items if custom plot is not given\n # add size if it's not there\n if fig_type == \"scatter2\" or fig_type == \"scatter3\" or fig_type == 'map': #if it's a scatter plot, add missin items, i.e. size and type\n if \"size\" not in df.keys():\n fixed_size = np.ones(len(df[\"x\"]))\n df[\"size\"] = fixed_size\n \n if \"type\" not in df.keys():\n fixed_type = \"agent\"\n df[\"type\"] = fixed_type\n ## organizing data based on given type. This is used for scatter and scatter3 to prevent color swinging\n if fig_type == 'scatter2' or fig_type == 'scatter3':\n types = df['type']\n types_unique = set(types) # remove the repeated items\n indices = {} # indices of df for each type\n for t in types_unique: # initialize with empty vectors\n indices.update({t:[]})\n for i in range(len(types)): # detect which rows below to which types and add it to the relevent indices\n for t in types_unique:\n if types[i] == t:\n indices[t].append(i)\n break\n data_sorted = {} # sorted data based on types\n for t in types_unique:\n data_sorted.update({t:df.iloc[indices[t]]})\n df = data_sorted\n # add color map for the first time\n if name not in self.color_map: #first time\n self.color_map.update({name:{}})\n taken_colors = self.color_map[name].values()\n nontaken_colors = deepcopy(self.colors)\n for c in list(taken_colors):\n nontaken_colors.remove(c)\n\n ii = 0\n for t in types_unique:\n if t not in self.color_map[name]:\n self.color_map[name].update({t:nontaken_colors[ii]})\n ii+=1 \n # if fig_type == 'map':\n # print(df['color_range'])\n # if 'color_range' not in df:\n # types = df['type']\n # color_range = max(types)-min(types)\n # df['color_range'] = color_range\n\n\n return df\n def read(self,file_dir):\n \"\"\"Reads the data files in csv and converts them into pandas DataFrame.\n \n Args:\n file_dir (string): file directory\n \n Returns:\n DataFrame: content of the file\n\n \"\"\"\n try:\n data = pd.read_csv(file_dir)\n except FileNotFoundError:\n print(\"Given file directory {} is invalid\".format(file_dir))\n sys.exit()\n return data\n\n def update_db(self):\n \"\"\"Updates the global database in case there are changes in the files. \n It queries modification date of files and upon change in the modification date, it calles :py:meth:`read`,\n to import the new data and then :py:meth:`postprocess` to process. \n \n Returns:\n bool: if any changes occures, this flag will be true\n \"\"\"\n any_update_flag = False # if any of the files has changed\n for name in self.specs.keys(): # main keys such as plot names\n # add the missing settings here\n if \"col\" not in self.specs[name]:\n self.specs[name][\"col\"] = 'col s5'\n if self.specs[name]['graph_type'] == \"map\":\n if \"color_range\" not in self.specs[name]:\n self.specs[name][\"color_range\"] = None\n file = self.specs[name][\"graph_dir\"]\n last_moddate = os.stat(file)[8] # last modification time\n if \"moddate\" not in self.specs[name].keys() : # in this case, file is not upload for the first optimizer\n try:\n data = self.read(file)\n except pd.errors.EmptyDataError:\n print(\"No columns to parse from file\")\n continue\n data = self.postprocess(name,data,self.specs[name][\"graph_type\"])\n self.specs[name].update({\"data\":data})\n # self.specs[name].update({\"color_map\":color_map})\n self.specs[name].update({\"moddate\":last_moddate})\n any_update_flag = True\n elif self.specs[name][\"moddate\"] != last_moddate:# if the new date is different\n try:\n data = self.read(file)\n except pd.errors.EmptyDataError:\n print(\"No columns to parse from file\") ## to block a bug\n continue\n data = self.postprocess(name,data,self.specs[name][\"graph_type\"])\n\n self.specs[name].update({\"data\":data})\n self.specs[name].update({\"moddate\":last_moddate})\n any_update_flag = True\n\n else:\n continue\n return any_update_flag\n def frame(self):\n \"\"\"\n Lays out the HTML and defines holders\n \"\"\"\n layout_objects = []\n layout_objects.append(html.Div([\n html.H2('List of plots',\n style={'float': 'left',\n }),\n ]))\n layout_objects.append(dcc.Dropdown(id='list_of_plots',\n options=[{'label': s, 'value': s}\n for s in self.specs.keys()],\n value=[s for s in self.specs.keys()],\n multi=True\n ))\n layout_objects.append(dcc.Interval(\n id='time',\n interval=1000,\n n_intervals = 0))\n \n layout_objects.append(html.Div(html.Div(id=\"graphs\",children=self.generate_graphs(self.specs.keys())), className='row'))\n self.app.layout = html.Div(layout_objects, className=\"container\",style={'width':'98%','margin-left':10,'margin-right':10,'max-width':50000})\n\n def callbacks(self):\n \"\"\"\n Definition of callback functions are given here.\n \"\"\"\n states = []\n for key in self.specs.keys():\n states.append(dash.dependencies.State(key,'relayoutData'))\n \n @self.app.callback(\n dash.dependencies.Output('graphs','children'),\n [dash.dependencies.Input('time', 'n_intervals'),dash.dependencies.Input('list_of_plots', 'value')],\n states\n )\n def update_graph(n_intervals,graph_tags,*relayoutDatas):\n i = 0\n for key in self.specs.keys():\n relayoutData = relayoutDatas[i]\n if relayoutData:\n if 'xaxis.range[0]' in relayoutData or 'scene.camera' in relayoutData:\n self.relayoutDatas.update({key:relayoutData})\n i+=1\n\n any_update_flag = self.update_db()\n if self.update_iteration < 10:\n self.update_iteration +=1\n return self.generate_graphs(graph_tags)\n # return new_figure\n elif not any_update_flag:\n raise dash.exceptions.PreventUpdate()\n else:\n return self.generate_graphs(graph_tags)\n def generate_graphs(self,graph_tags):\n \"\"\"\n This function takes care of plot generation either using build-in plots or custom plots.\n \"\"\"\n graphs = []\n for graph_tag in graph_tags: # iterate through requested graph names\n\n if self.specs[graph_tag][\"graph_type\"] == \"custom\": # if the plot is given, just add it to the graph list\n figure_func = self.specs[graph_tag][\"figure\"]\n FIG = figure_func(self.specs[graph_tag][\"data\"])\n\n \n else:\n if self.specs[graph_tag][\"graph_type\"] == \"lines\":\n max_x = max(self.specs[graph_tag][\"data\"].index)\n if self.specs[graph_tag][\"x-axis-moves\"] == True:\n min_x = max_x - self.specs[graph_tag][\"x-axis-length\"]\n else:\n min_x = min(self.specs[graph_tag][\"data\"].index)\n x_range = [min_x,max_x]\n\n FIG = plots.lines(self.specs[graph_tag],graph_tag,x_range)\n \n\n elif self.specs[graph_tag][\"graph_type\"] == \"scatter2\":\n FIG = plots.scatter(self.specs[graph_tag],graph_tag,self.color_map[graph_tag])\n\n elif self.specs[graph_tag][\"graph_type\"] == \"scatter3\":\n FIG = plots.scatter3(self.specs[graph_tag],graph_tag,self.color_map[graph_tag])\n \n elif self.specs[graph_tag][\"graph_type\"] == \"map\":\n FIG = plots.map(self.specs[graph_tag][\"data\"],graph_tag,self.specs[graph_tag][\"color_range\"])\n\n else:\n print(self.specs[graph_tag][\"graph_type\"])\n print(\"Graph type is not defined. It should be either lines or scatter(3)\")\n sys.exit()\n\n if graph_tag in self.relayoutDatas:\n relayout_data = self.relayoutDatas[graph_tag]\n if relayout_data:\n watch.copy_graph_layout(relayout_data,FIG)\n self.FIGS.update({graph_tag:FIG})\n graphs = []\n for key in graph_tags:\n graphs.append(html.Div(dcc.Graph(\n id=key,\n figure=self.FIGS[key]\n ),className = self.cols[key])\n )\n return graphs\n @staticmethod\n def copy_graph_layout(relayout_data, FIG):\n if 'xaxis.range[0]' in relayout_data:\n FIG['layout']['xaxis']['range'] = [\n relayout_data['xaxis.range[0]'],\n relayout_data['xaxis.range[1]']\n ]\n if 'yaxis.range[0]' in relayout_data:\n FIG['layout']['yaxis']['range'] = [\n relayout_data['yaxis.range[0]'],\n relayout_data['yaxis.range[1]']\n ]\n if 'scene.camera' in relayout_data:\n FIG.update_layout(scene_camera = relayout_data['scene.camera'])\n def run(self,IP={}):\n \"\"\"\n Activate the server and map the graphs on the given IP.\n Args:\n IP (string): the IP where the graphs intended for plotting.\n \"\"\"\n if IP == {}:\n IP = '0.0.0.0'\n self.app.run_server(debug=True, host=IP)\n"
] |
[
[
"pandas.read_csv"
]
] |
Malavikka/ConvLab-2
|
[
"f2a0d251e4fab9e36e9d9f04df6308623d2d780c"
] |
[
"convlab2/policy/mdrg/multiwoz/train.py"
] |
[
"from __future__ import division, print_function, unicode_literals\n\nimport argparse\nimport json\nimport random\nimport time\nfrom io import open\nimport os\n\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\n\nfrom convlab2.policy.mdrg.multiwoz.utils import util\nfrom convlab2.policy.mdrg.multiwoz.model import Model\n\n\nparser = argparse.ArgumentParser(description='S2S')\nparser.add_argument('--batch_size', type=int, default=64, metavar='N', help='input batch size for training (default: 128)')\nparser.add_argument('--vocab_size', type=int, default=400, metavar='V')\n\nparser.add_argument('--use_attn', type=util.str2bool, nargs='?', const=True, default=False)\nparser.add_argument('--attention_type', type=str, default='bahdanau')\nparser.add_argument('--use_emb', type=util.str2bool, nargs='?', const=True, default=False)\n\nparser.add_argument('--emb_size', type=int, default=50)\nparser.add_argument('--hid_size_enc', type=int, default=150)\nparser.add_argument('--hid_size_dec', type=int, default=150)\nparser.add_argument('--hid_size_pol', type=int, default=150)\nparser.add_argument('--db_size', type=int, default=30)\nparser.add_argument('--bs_size', type=int, default=94)\n\nparser.add_argument('--cell_type', type=str, default='lstm')\nparser.add_argument('--depth', type=int, default=1, help='depth of rnn')\nparser.add_argument('--max_len', type=int, default=50)\n\nparser.add_argument('--optim', type=str, default='adam')\nparser.add_argument('--lr_rate', type=float, default=0.005)\nparser.add_argument('--lr_decay', type=float, default=0.0)\nparser.add_argument('--l2_norm', type=float, default=0.00001)\nparser.add_argument('--clip', type=float, default=5.0, help='clip the gradient by norm')\n\nparser.add_argument('--teacher_ratio', type=float, default=1.0, help='probability of using targets for learning')\nparser.add_argument('--dropout', type=float, default=0.0)\n\nparser.add_argument('--no_cuda', type=util.str2bool, nargs='?', const=True, default=True)\n\nparser.add_argument('--seed', type=int, default=0, metavar='S', help='random seed (default: 1)')\nparser.add_argument('--train_output', type=str, default='data/train_dials/', help='Training output dir path')\n\nparser.add_argument('--max_epochs', type=int, default=15)\nparser.add_argument('--early_stop_count', type=int, default=2)\nparser.add_argument('--model_dir', type=str, default='model/model/')\nparser.add_argument('--model_name', type=str, default='translate.ckpt')\n\nparser.add_argument('--load_param', type=util.str2bool, nargs='?', const=True, default=False)\nparser.add_argument('--epoch_load', type=int, default=0)\n\nparser.add_argument('--mode', type=str, default='train', help='training or testing: test, train, RL')\n\n\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\ntorch.manual_seed(args.seed)\ndevice = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\n\ndef train(print_loss_total,print_act_total, print_grad_total, input_tensor, target_tensor, bs_tensor, db_tensor, name=None):\n # create an empty matrix with padding tokens\n input_tensor, input_lengths = util.padSequence(input_tensor)\n target_tensor, target_lengths = util.padSequence(target_tensor)\n bs_tensor = torch.tensor(bs_tensor, dtype=torch.float, device=device)\n db_tensor = torch.tensor(db_tensor, dtype=torch.float, device=device)\n\n loss, loss_acts, grad = model.train(input_tensor, input_lengths, target_tensor, target_lengths, db_tensor,\n bs_tensor, name)\n\n #print(loss, loss_acts)\n print_loss_total += loss\n print_act_total += loss_acts\n print_grad_total += grad\n\n model.global_step += 1\n model.sup_loss = torch.zeros(1)\n\n return print_loss_total, print_act_total, print_grad_total\n\n\ndef trainIters(model, n_epochs=10, args=args):\n prev_min_loss, early_stop_count = 1 << 30, args.early_stop_count\n start = time.time()\n\n for epoch in range(1, n_epochs + 1):\n print_loss_total = 0; print_grad_total = 0; print_act_total = 0 # Reset every print_every\n start_time = time.time()\n # watch out where do you put it\n model.optimizer = Adam(lr=args.lr_rate, params=filter(lambda x: x.requires_grad, model.parameters()), weight_decay=args.l2_norm)\n model.optimizer_policy = Adam(lr=args.lr_rate, params=filter(lambda x: x.requires_grad, model.policy.parameters()), weight_decay=args.l2_norm)\n\n dials = list(train_dials.keys())\n random.shuffle(dials)\n input_tensor = [];target_tensor = [];bs_tensor = [];db_tensor = []\n for name in dials:\n val_file = train_dials[name]\n model.optimizer.zero_grad()\n model.optimizer_policy.zero_grad()\n\n input_tensor, target_tensor, bs_tensor, db_tensor = util.loadDialogue(model, val_file, input_tensor, target_tensor, bs_tensor, db_tensor)\n\n if len(db_tensor) > args.batch_size:\n print_loss_total, print_act_total, print_grad_total = train(print_loss_total, print_act_total, print_grad_total, input_tensor, target_tensor, bs_tensor, db_tensor)\n input_tensor = [];target_tensor = [];bs_tensor = [];db_tensor = [];\n\n print_loss_avg = print_loss_total / len(train_dials)\n print_act_total_avg = print_act_total / len(train_dials)\n print_grad_avg = print_grad_total / len(train_dials)\n print('TIME:', time.time() - start_time)\n print('Time since %s (Epoch:%d %d%%) Loss: %.4f, Loss act: %.4f, Grad: %.4f' % (util.timeSince(start, epoch / n_epochs),\n epoch, epoch / n_epochs * 100, print_loss_avg, print_act_total_avg, print_grad_avg))\n\n # VALIDATION\n valid_loss = 0\n for name, val_file in val_dials.items():\n input_tensor = []; target_tensor = []; bs_tensor = [];db_tensor = []\n input_tensor, target_tensor, bs_tensor, db_tensor = util.loadDialogue(model, val_file, input_tensor,\n target_tensor, bs_tensor,\n db_tensor)\n # create an empty matrix with padding tokens\n input_tensor, input_lengths = util.padSequence(input_tensor)\n target_tensor, target_lengths = util.padSequence(target_tensor)\n bs_tensor = torch.tensor(bs_tensor, dtype=torch.float, device=device)\n db_tensor = torch.tensor(db_tensor, dtype=torch.float, device=device)\n\n proba, _, _ = model.forward(input_tensor, input_lengths, target_tensor, target_lengths, db_tensor, bs_tensor)\n proba = proba.view(-1, model.vocab_size) # flatten all predictions\n loss = model.gen_criterion(proba, target_tensor.view(-1))\n valid_loss += loss.item()\n\n\n valid_loss /= len(val_dials)\n print('Current Valid LOSS:', valid_loss)\n\n model.saveModel(epoch)\n\n\ndef loadDictionaries():\n # load data and dictionaries\n with open(os.path.join(os.path.dirname(__file__), 'data/input_lang.index2word.json'), 'r') as f:\n input_lang_index2word = json.load(f)\n with open(os.path.join(os.path.dirname(__file__), 'data/input_lang.word2index.json'), 'r') as f:\n input_lang_word2index = json.load(f)\n with open(os.path.join(os.path.dirname(__file__), 'data/output_lang.index2word.json'), 'r') as f:\n output_lang_index2word = json.load(f)\n with open(os.path.join(os.path.dirname(__file__), 'data/output_lang.word2index.json'), 'r') as f:\n output_lang_word2index = json.load(f)\n\n return input_lang_index2word, output_lang_index2word, input_lang_word2index, output_lang_word2index\n\n\nif __name__ == '__main__':\n input_lang_index2word, output_lang_index2word, input_lang_word2index, output_lang_word2index = loadDictionaries()\n # Load training file list:\n with open(os.path.join(os.path.dirname(__file__),'data/train_dials.json'), 'r') as outfile:\n train_dials = json.load(outfile)\n\n # Load validation file list:\n with open(os.path.join(os.path.dirname(__file__), 'data/val_dials.json'), 'r') as outfile:\n val_dials = json.load(outfile)\n\n model = Model(args, input_lang_index2word, output_lang_index2word, input_lang_word2index, output_lang_word2index)\n if args.load_param:\n model.loadModel(args.epoch_load)\n\n trainIters(model, n_epochs=args.max_epochs, args=args)\n"
] |
[
[
"torch.zeros",
"torch.manual_seed",
"torch.tensor",
"torch.cuda.is_available",
"torch.device"
]
] |
ykkawana/probability
|
[
"65bfd91cf6e855674da8dd9976c067f79da46e90"
] |
[
"tensorflow_probability/python/distributions/linear_gaussian_ssm_test.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\"\"\"Linear Gaussian State Space Model.\"\"\"\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\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import _augment_sample_shape\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import backward_smoothing_update\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import BackwardPassState\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import build_backward_pass_step\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import build_kalman_cov_step\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import build_kalman_filter_step\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import build_kalman_mean_step\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import kalman_transition\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import KalmanFilterState\nfrom tensorflow_probability.python.distributions.linear_gaussian_ssm import linear_gaussian_update\n\nfrom tensorflow_probability.python.internal import test_case as tfp_test_case\n\nfrom tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import\n\ntfd = tfp.distributions\ntfl = tf.linalg\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass _IIDNormalTest(object):\n\n def setUp(self):\n pass\n\n def _build_iid_normal_model(self, num_timesteps, latent_size,\n observation_size, transition_variance,\n observation_variance):\n \"\"\"Build a model whose outputs are IID normal by construction.\"\"\"\n\n transition_variance = self._build_placeholder(transition_variance)\n observation_variance = self._build_placeholder(observation_variance)\n\n # Use orthogonal matrices to project a (potentially\n # high-dimensional) latent space of IID normal variables into a\n # low-dimensional observation that is still IID normal.\n random_orthogonal_matrix = lambda: np.linalg.qr(\n np.random.randn(latent_size, latent_size))[0][:observation_size, :]\n observation_matrix = self._build_placeholder(random_orthogonal_matrix())\n\n model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=num_timesteps,\n transition_matrix=self._build_placeholder(\n np.zeros([latent_size, latent_size])),\n transition_noise=tfd.MultivariateNormalDiag(\n scale_diag=tf.sqrt(transition_variance) *\n tf.ones([latent_size], dtype=self.dtype)),\n observation_matrix=observation_matrix,\n observation_noise=tfd.MultivariateNormalDiag(\n scale_diag=tf.sqrt(observation_variance) *\n tf.ones([observation_size], dtype=self.dtype)),\n initial_state_prior=tfd.MultivariateNormalDiag(\n scale_diag=tf.sqrt(transition_variance) *\n tf.ones([latent_size], dtype=self.dtype)),\n validate_args=True)\n\n return model\n\n def test_iid_normal_sample(self):\n num_timesteps = 10\n latent_size = 3\n observation_size = 2\n num_samples = 10000\n\n for transition_variance_val in [.3, 100.]:\n for observation_variance_val in [.6, 40.]:\n\n iid_latents = self._build_iid_normal_model(\n num_timesteps=num_timesteps,\n latent_size=latent_size,\n observation_size=observation_size,\n transition_variance=transition_variance_val,\n observation_variance=observation_variance_val)\n\n x = iid_latents.sample(num_samples)\n\n x_val = self.evaluate(x)\n result_shape = [num_timesteps, observation_size]\n marginal_variance = transition_variance_val + observation_variance_val\n\n stderr_mean = np.sqrt(num_samples * marginal_variance)\n stderr_variance = marginal_variance * np.sqrt(2./(num_samples-1))\n\n self.assertAllClose(np.mean(x_val, axis=0),\n np.zeros(result_shape),\n atol=5*stderr_mean)\n self.assertAllClose(np.var(x_val, axis=0),\n np.ones(result_shape) * marginal_variance,\n rtol=5*stderr_variance)\n\n def test_iid_normal_logprob(self):\n\n # In the case where the latent states are iid normal (achieved by\n # setting the transition matrix to zero, so there's no dependence\n # between timesteps), and observations are also independent\n # (achieved by using an orthogonal matrix as the observation model),\n # we can verify log_prob as a simple iid Gaussian log density.\n delta = 1e-4\n for transition_variance_val in [1., 1e-8]:\n for observation_variance_val in [1., 1e-8]:\n\n iid_latents = self._build_iid_normal_model(\n num_timesteps=10,\n latent_size=4,\n observation_size=2,\n transition_variance=transition_variance_val,\n observation_variance=observation_variance_val)\n\n x = iid_latents.sample([5, 3])\n lp_kalman = iid_latents.log_prob(x)\n\n marginal_variance = tf.convert_to_tensor(\n value=transition_variance_val + observation_variance_val,\n dtype=self.dtype)\n lp_iid = tf.reduce_sum(\n input_tensor=tfd.Normal(\n loc=tf.zeros([], dtype=self.dtype),\n scale=tf.sqrt(marginal_variance)).log_prob(x),\n axis=(-2, -1))\n\n lp_kalman_val, lp_iid_val = self.evaluate((lp_kalman, lp_iid))\n self.assertAllClose(lp_kalman_val,\n lp_iid_val,\n rtol=delta, atol=0.)\n\n def _build_placeholder(self, ndarray):\n \"\"\"Convert a numpy array to a TF placeholder.\n\n Args:\n ndarray: any object convertible to a numpy array via `np.asarray()`.\n\n Returns:\n placeholder: a TensorFlow `placeholder` with default value given by the\n provided `ndarray`, dtype given by `self.dtype`, and shape specified\n statically only if `self.use_static_shape` is `True`.\n \"\"\"\n\n ndarray = np.asarray(ndarray).astype(self.dtype)\n return tf.compat.v1.placeholder_with_default(\n input=ndarray, shape=ndarray.shape if self.use_static_shape else None)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass IIDNormalTestStatic32(_IIDNormalTest, tf.test.TestCase):\n use_static_shape = True\n dtype = np.float32\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass IIDNormalTestStatic64(_IIDNormalTest, tf.test.TestCase):\n use_static_shape = True\n dtype = np.float64\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass IIDNormalTestDynamic32(_IIDNormalTest, tf.test.TestCase):\n use_static_shape = False\n dtype = np.float32\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass SanityChecks(tf.test.TestCase):\n\n def test_deterministic_system(self):\n\n # Define a deterministic linear system\n num_timesteps = 5\n prior_mean = 17.\n step_coef = 1.3\n step_shift = -1.5\n observation_coef = 0.3\n observation_shift = -1.\n model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=num_timesteps,\n transition_matrix=[[step_coef]],\n transition_noise=tfd.MultivariateNormalDiag(loc=[step_shift],\n scale_diag=[0.]),\n observation_matrix=[[observation_coef]],\n observation_noise=tfd.MultivariateNormalDiag(loc=[observation_shift],\n scale_diag=[0.]),\n initial_state_prior=tfd.MultivariateNormalDiag(loc=[prior_mean],\n scale_diag=[0.]))\n\n # Manually compute expected output.\n expected_latents = [prior_mean]\n for _ in range(num_timesteps-1):\n expected_latents.append(step_coef * expected_latents[-1] + step_shift)\n expected_latents = np.asarray(expected_latents)\n expected_observations = (\n expected_latents * observation_coef + observation_shift)\n\n mean_, sample_ = self.evaluate([model.mean(), model.sample()])\n self.assertAllClose(mean_[..., 0], expected_observations)\n self.assertAllClose(sample_[..., 0], expected_observations)\n\n def test_variance(self):\n\n num_timesteps = 5\n prior_scale = 17.\n step_coef = 1.3\n step_scale = 0.5\n observation_coef = 20.0\n observation_scale = 1.9\n\n model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=num_timesteps,\n transition_matrix=[[step_coef]],\n transition_noise=tfd.MultivariateNormalDiag(\n loc=[0.], scale_diag=[step_scale]),\n observation_matrix=[[observation_coef]],\n observation_noise=tfd.MultivariateNormalDiag(\n loc=[0.], scale_diag=[observation_scale]),\n initial_state_prior=tfd.MultivariateNormalDiag(\n loc=[0.], scale_diag=[prior_scale]))\n\n # Manually compute the marginal variance at each step\n latent_variance = [prior_scale**2]\n for _ in range(num_timesteps-1):\n latent_variance.append(step_coef**2 * latent_variance[-1] + step_scale**2)\n latent_variance = np.asarray(latent_variance)\n observation_variance = (\n latent_variance * observation_coef**2 + observation_scale**2)\n\n variance_ = self.evaluate(model.variance())\n self.assertAllClose(variance_[..., 0], observation_variance)\n\n def test_time_varying_operators(self):\n\n num_timesteps = 5\n prior_mean = 1.3\n prior_scale = 1e-4\n transition_scale = 0.\n observation_noise_scale = 1e-4\n\n # Define time-varying transition and observation matrices.\n def transition_matrix(t):\n t = tf.cast(t, tf.float32)\n return tf.linalg.LinearOperatorFullMatrix([[t+1]])\n\n def observation_matrix(t):\n t = tf.cast(t, tf.float32)\n return tf.linalg.LinearOperatorFullMatrix([[tf.sqrt(t+1.)]])\n\n model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=num_timesteps,\n transition_matrix=transition_matrix,\n transition_noise=tfd.MultivariateNormalDiag(\n scale_diag=[transition_scale]),\n observation_matrix=observation_matrix,\n observation_noise=tfd.MultivariateNormalDiag(\n scale_diag=[observation_noise_scale]),\n initial_state_prior=tfd.MultivariateNormalDiag(\n loc=[prior_mean], scale_diag=[prior_scale]))\n\n mean_, sample_ = self.evaluate([model.mean(), model.sample()])\n\n # Manually compute the expected output of the model (i.e., the prior\n # mean). Since the model is near-deterministic, we expect any samples to\n # be close to this value, so we can also use this to test the `sample`\n # method.\n latent_means = [prior_mean]\n for t in range(0, num_timesteps-1):\n latent_means.append((t+1) * latent_means[-1])\n observation_means = [latent_means[t] * np.sqrt(t+1)\n for t in range(num_timesteps)]\n\n self.assertAllClose(observation_means, mean_[..., 0], atol=1e-4)\n self.assertAllClose(observation_means, sample_[..., 0], atol=3.)\n\n # this model is near-deterministic, so the log density of a sample will\n # be high (about 35) if computed using the correct model, and very low\n # (approximately -1e10) if there's an off-by-one-timestep error.\n lp_ = self.evaluate(model.log_prob(sample_))\n self.assertGreater(lp_, 0.)\n\n def test_time_varying_noise(self):\n\n num_timesteps = 5\n prior_mean = 0.\n prior_scale = 1.\n\n # Define time-varying transition and observation noise models.\n def transition_noise(t):\n t = tf.cast(t, tf.float32)\n return tfd.MultivariateNormalDiag(scale_diag=[t])\n\n def observation_noise(t):\n t = tf.cast(t, tf.float32)\n return tfd.MultivariateNormalDiag(scale_diag=[tf.math.log(t + 1.)])\n\n model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=num_timesteps,\n transition_matrix=[[1.]],\n transition_noise=transition_noise,\n observation_matrix=[[1.]],\n observation_noise=observation_noise,\n initial_state_prior=tfd.MultivariateNormalDiag(\n loc=[prior_mean], scale_diag=[prior_scale]))\n\n variance_ = self.evaluate(model.variance())\n\n # Manually compute the prior variance at each timestep.\n latent_variances = [prior_scale**2]\n for t in range(0, num_timesteps-1):\n latent_variances.append(latent_variances[t] + t**2)\n observation_variances = [latent_variances[t] + np.log(t+1)**2\n for t in range(num_timesteps)]\n\n self.assertAllClose(observation_variances, variance_[..., 0])\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass BatchTest(tf.test.TestCase):\n \"\"\"Test that methods broadcast batch dimensions for each parameter.\"\"\"\n\n def setUp(self):\n pass\n\n def _build_random_model(self,\n num_timesteps,\n latent_size,\n observation_size,\n prior_batch_shape=None,\n transition_matrix_batch_shape=None,\n transition_noise_batch_shape=None,\n observation_matrix_batch_shape=None,\n observation_noise_batch_shape=None):\n \"\"\"Builds a LGSSM with random normal ops of specified shape.\"\"\"\n\n prior_batch_shape = (\n [] if prior_batch_shape is None else prior_batch_shape)\n transition_matrix_batch_shape = ([] if transition_matrix_batch_shape is None\n else transition_matrix_batch_shape)\n transition_noise_batch_shape = ([] if transition_noise_batch_shape is None\n else transition_noise_batch_shape)\n observation_matrix_batch_shape = ([]\n if observation_matrix_batch_shape is None\n else observation_matrix_batch_shape)\n observation_noise_batch_shape = ([] if observation_noise_batch_shape is None\n else observation_noise_batch_shape)\n\n return tfd.LinearGaussianStateSpaceModel(\n num_timesteps=num_timesteps,\n transition_matrix=tf.random.normal(transition_matrix_batch_shape +\n [latent_size, latent_size]),\n transition_noise=tfd.MultivariateNormalDiag(\n scale_diag=tf.nn.softplus(\n tf.random.normal(transition_noise_batch_shape +\n [latent_size]))),\n observation_matrix=tf.random.normal(observation_matrix_batch_shape +\n [observation_size, latent_size]),\n observation_noise=tfd.MultivariateNormalDiag(\n scale_diag=tf.nn.softplus(\n tf.random.normal(observation_noise_batch_shape +\n [observation_size]))),\n initial_state_prior=tfd.MultivariateNormalDiag(\n scale_diag=tf.nn.softplus(\n tf.random.normal(prior_batch_shape + [latent_size]))),\n validate_args=True)\n\n def _sanity_check_shapes(self, model,\n batch_shape,\n event_shape,\n num_timesteps,\n latent_size,\n sample_shape=(2, 1)):\n\n # Lists can't be default arguments, but we'll want sample_shape to\n # be a list so we can concatenate with other shapes passed as\n # lists.\n sample_shape = list(sample_shape)\n\n self.assertEqual(model.event_shape.as_list(), event_shape)\n self.assertEqual(model.batch_shape.as_list(), batch_shape)\n\n y = model.sample(sample_shape)\n self.assertEqual(y.shape.as_list(),\n sample_shape + batch_shape + event_shape)\n\n lp = model.log_prob(y)\n self.assertEqual(lp.shape.as_list(), sample_shape + batch_shape)\n\n (posterior_means, posterior_covs) = model.posterior_marginals(y)\n self.assertEqual(posterior_means.shape.as_list(),\n sample_shape + batch_shape + [num_timesteps, latent_size])\n self.assertEqual(posterior_covs.shape.as_list(),\n batch_shape + [num_timesteps, latent_size, latent_size])\n\n # Try an argument with no batch shape to ensure we broadcast\n # correctly.\n unbatched_y = tf.random.normal(event_shape)\n lp = model.log_prob(unbatched_y)\n self.assertEqual(lp.shape.as_list(), batch_shape)\n\n self.assertEqual(model.mean().shape.as_list(),\n batch_shape + event_shape)\n self.assertEqual(model.variance().shape.as_list(),\n batch_shape + event_shape)\n\n (posterior_means, posterior_covs) = model.posterior_marginals(unbatched_y)\n self.assertEqual(posterior_means.shape.as_list(),\n batch_shape + [num_timesteps, latent_size])\n self.assertEqual(posterior_covs.shape.as_list(),\n batch_shape + [num_timesteps, latent_size, latent_size])\n\n def test_constant_batch_shape(self):\n \"\"\"Simple case where all components have the same batch shape.\"\"\"\n num_timesteps = 5\n latent_size = 3\n observation_size = 2\n batch_shape = [3, 4]\n event_shape = [num_timesteps, observation_size]\n\n model = self._build_random_model(num_timesteps,\n latent_size,\n observation_size,\n prior_batch_shape=batch_shape,\n transition_matrix_batch_shape=batch_shape,\n transition_noise_batch_shape=batch_shape,\n observation_matrix_batch_shape=batch_shape,\n observation_noise_batch_shape=batch_shape)\n\n # check that we get the basic shapes right\n self.assertEqual(model.latent_size, latent_size)\n self.assertEqual(model.observation_size, observation_size)\n self._sanity_check_shapes(model, batch_shape, event_shape,\n num_timesteps, latent_size)\n\n def test_broadcast_batch_shape(self):\n \"\"\"Broadcasting when only one component has batch shape.\"\"\"\n\n num_timesteps = 5\n latent_size = 3\n observation_size = 2\n batch_shape = [3, 4]\n event_shape = [num_timesteps, observation_size]\n\n # Test batching only over the prior\n model = self._build_random_model(num_timesteps,\n latent_size,\n observation_size,\n prior_batch_shape=batch_shape)\n self._sanity_check_shapes(model, batch_shape, event_shape,\n num_timesteps, latent_size)\n\n # Test batching only over the transition op\n model = self._build_random_model(num_timesteps,\n latent_size,\n observation_size,\n transition_matrix_batch_shape=batch_shape)\n self._sanity_check_shapes(model, batch_shape, event_shape,\n num_timesteps, latent_size)\n\n # Test batching only over the transition noise\n model = self._build_random_model(num_timesteps,\n latent_size,\n observation_size,\n transition_noise_batch_shape=batch_shape)\n self._sanity_check_shapes(model, batch_shape, event_shape,\n num_timesteps, latent_size)\n\n # Test batching only over the observation op\n model = self._build_random_model(num_timesteps,\n latent_size,\n observation_size,\n observation_matrix_batch_shape=batch_shape)\n self._sanity_check_shapes(model, batch_shape, event_shape,\n num_timesteps, latent_size)\n\n # Test batching only over the observation noise\n model = self._build_random_model(num_timesteps,\n latent_size,\n observation_size,\n observation_noise_batch_shape=batch_shape)\n self._sanity_check_shapes(model, batch_shape, event_shape,\n num_timesteps, latent_size)\n\n\nclass MissingObservationsTests(tfp_test_case.TestCase):\n\n def setUp(self):\n super(MissingObservationsTests, self).setUp()\n\n # Define a simple random-walk model.\n self.num_timesteps = 8\n self.transition_matrix = np.array([[1.]], dtype=np.float32)\n self.transition_noise = tfd.MultivariateNormalDiag(\n scale_diag=np.array([1.], dtype=np.float32))\n self.observation_matrix = np.array([[1.]], dtype=np.float32)\n self.observation_noise = tfd.MultivariateNormalDiag(\n scale_diag=np.array([0.5], dtype=np.float32))\n self.initial_state_prior = tfd.MultivariateNormalDiag(\n loc=np.zeros(shape=[1], dtype=np.float32),\n scale_diag=np.ones(shape=[1], dtype=np.float32))\n self.model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=self.num_timesteps,\n transition_matrix=self.transition_matrix,\n transition_noise=self.transition_noise,\n observation_matrix=self.observation_matrix,\n observation_noise=self.observation_noise,\n initial_state_prior=self.initial_state_prior,\n initial_step=0)\n\n def testForwardFilterWithMask(self):\n\n observed_time_series = np.array(\n [1.0, 2.0, -1000., 0.4, np.nan, 1000., 4.2, np.inf]).astype(np.float32)\n observed_time_series = observed_time_series[..., np.newaxis]\n observation_mask = np.array(\n [False, False, True, False, True, True, False, True]).astype(np.bool)\n\n # In a random walk, skipping a timestep just adds variance, so we can\n # construct a model of the four 'unmasked' timesteps by directly collapsing\n # out the masked timesteps. We test that the filtering distributions and\n # likelihoods from the masked model match those from the collapsed\n # model at observed timesteps.\n collapsed_transition_variances = tf.constant([1., 2., 3., 2.],\n dtype=np.float32)\n\n def collapsed_transition_noise_model(t):\n return tfd.MultivariateNormalDiag(\n scale_diag=[tf.sqrt(collapsed_transition_variances[t])])\n\n collapsed_model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=4,\n transition_matrix=self.transition_matrix,\n transition_noise=collapsed_transition_noise_model,\n observation_matrix=self.observation_matrix,\n observation_noise=self.observation_noise,\n initial_state_prior=self.initial_state_prior,\n initial_step=0)\n\n (log_likelihoods_, filtered_means_, filtered_covs_, predicted_means_,\n predicted_covs_, observation_means_, observation_covs_) = self.evaluate(\n self.model.forward_filter(\n x=observed_time_series, mask=observation_mask))\n\n (log_likelihoods_collapsed_, filtered_means_collapsed_,\n filtered_covs_collapsed_, predicted_means_collapsed_,\n predicted_covs_collapsed_, observation_means_collapsed_,\n observation_covs_collapsed_) = self.evaluate(\n collapsed_model.forward_filter(\n x=observed_time_series[~observation_mask]))\n\n self.assertAllClose(log_likelihoods_[~observation_mask],\n log_likelihoods_collapsed_)\n self.assertAllEqual(log_likelihoods_[observation_mask],\n np.zeros(log_likelihoods_[observation_mask].shape))\n self.assertAllClose(filtered_means_[~observation_mask],\n filtered_means_collapsed_)\n self.assertAllClose(filtered_covs_[~observation_mask],\n filtered_covs_collapsed_)\n\n # Check the predictive distributions over latents at the final timestep.\n # We don't bother checking the other timesteps because the collapsing\n # makes it nontrivial to compute which ones should match up.\n self.assertAllClose(predicted_means_[-1],\n predicted_means_collapsed_[-1])\n self.assertAllClose(predicted_covs_[-1],\n predicted_covs_collapsed_[-1])\n\n self.assertAllClose(observation_means_[~observation_mask],\n observation_means_collapsed_)\n self.assertAllClose(observation_covs_[~observation_mask],\n observation_covs_collapsed_)\n\n # Also test that auxiliary methods `log_prob` and `posterior_marginals`\n # pass the mask through correctly.\n lp_, lp_collapsed_ = self.evaluate((\n self.model.log_prob(observed_time_series, mask=observation_mask),\n collapsed_model.log_prob(observed_time_series[~observation_mask])))\n self.assertAllClose(lp_, lp_collapsed_)\n\n ((posterior_means_, posterior_covs_),\n (posterior_means_collapsed_, posterior_covs_collapsed_)) = self.evaluate((\n self.model.posterior_marginals(\n observed_time_series, mask=observation_mask),\n collapsed_model.posterior_marginals(\n observed_time_series[~observation_mask])))\n self.assertAllClose(posterior_means_[~observation_mask],\n posterior_means_collapsed_)\n self.assertAllClose(posterior_covs_[~observation_mask],\n posterior_covs_collapsed_)\n\n def testGradientsOfMaskedNaNsAreFinite(self):\n observed_time_series = np.array( # contains a (masked) NaN.\n [1.0, 2.0, -1000., 0.4, np.nan, 1000., 4.2, np.inf]).astype(np.float32)\n observed_time_series = observed_time_series[..., np.newaxis]\n observation_mask = np.array(\n [False, False, True, False, True, True, False, True]).astype(np.bool)\n\n # Check that we've avoided the NaN-gradient gotcha described in\n # https://github.com/tensorflow/tensorflow/issues/2540.\n log_likelihoods, _, _, _, _, _, _ = self.model.forward_filter(\n x=observed_time_series, mask=observation_mask)\n lp = tf.reduce_sum(input_tensor=log_likelihoods)\n grads_ = self.evaluate(\n tf.gradients(ys=lp, xs=self.transition_noise.scale.diag))\n self.assertAllFinite(grads_)\n\n def testMaskWhenModelHasBatchShape(self):\n # When the inputs (x, mask) have shape *smaller* than the model's batch\n # shape, they should be broadcast up so we return a result for each\n # model in the batch.\n num_timesteps = 8\n batch_shape = [4, 3]\n batch_model = tfd.LinearGaussianStateSpaceModel(\n num_timesteps=num_timesteps,\n transition_matrix=self.transition_matrix,\n transition_noise=self.transition_noise,\n observation_matrix=self.observation_matrix,\n observation_noise=self.observation_noise,\n initial_state_prior=tfd.MultivariateNormalDiag(\n scale_diag=np.random.randn(*(\n batch_shape + [1])).astype(np.float32)),\n initial_step=0)\n\n mask = np.random.randn(num_timesteps) > 0\n observed_time_series = np.random.randn(num_timesteps, 1).astype(np.float32)\n observed_time_series[mask[..., np.newaxis]] = np.inf\n\n (log_likelihoods, filtered_means, filtered_covs, _, _, _,\n _) = batch_model.forward_filter(\n x=observed_time_series, mask=mask)\n # Test that shapes are as expected, and are statically inferred.\n self.assertAllEqual(filtered_means.shape.as_list(),\n batch_shape + [num_timesteps, 1])\n self.assertAllEqual(filtered_covs.shape.as_list(),\n batch_shape + [num_timesteps, 1, 1])\n\n (log_likelihoods_, filtered_means_, filtered_covs_) = self.evaluate(\n (log_likelihoods, filtered_means, filtered_covs))\n self.assertTrue(np.all(np.isfinite(log_likelihoods_)))\n self.assertTrue(np.all(np.isfinite(filtered_means_)))\n self.assertTrue(np.all(np.isfinite(filtered_covs_)))\n\n def testMaskWhenTimeSeriesHasSampleShape(self):\n # When the inputs (x, mask) have shape *larger* than the model's batch\n # shape, we return means with a sample dimension for every sample dimension\n # in the observed time series `x`, and covariances with a sample dimension\n # for every sample dimension in the mask.\n sample_shape = [5, 2]\n mask_sample_shape = [2]\n\n mask = np.random.randn(*np.concatenate(\n [mask_sample_shape, [self.num_timesteps]], axis=0)) > 0\n observed_time_series = np.random.randn(*np.concatenate(\n [sample_shape, [self.num_timesteps, 1]], axis=0)).astype(\n np.float32)\n observed_time_series[:, mask[..., np.newaxis]] = np.inf\n\n (log_likelihoods, filtered_means, filtered_covs, _, _, _,\n _) = self.model.forward_filter(\n x=observed_time_series, mask=mask)\n self.assertAllEqual(filtered_means.shape.as_list(),\n sample_shape + [self.num_timesteps, 1])\n self.assertAllEqual(filtered_covs.shape.as_list(),\n mask_sample_shape + [self.num_timesteps, 1, 1])\n\n (log_likelihoods_, filtered_means_, filtered_covs_) = self.evaluate(\n (log_likelihoods, filtered_means, filtered_covs))\n self.assertTrue(np.all(np.isfinite(log_likelihoods_)))\n self.assertTrue(np.all(np.isfinite(filtered_means_)))\n self.assertTrue(np.all(np.isfinite(filtered_covs_)))\n\n big_mask = np.random.randn(*np.concatenate(\n [[1, 2, 3], sample_shape, [self.num_timesteps]], axis=0)) > 0\n with self.assertRaisesRegexp(ValueError,\n \"mask cannot have higher rank than x\"):\n (log_likelihoods, filtered_means, filtered_covs, _, _, _,\n _) = self.model.forward_filter(\n x=observed_time_series, mask=big_mask)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass KalmanSmootherTest(tf.test.TestCase):\n\n def build_kf(self):\n # Define a simple model with 3D latents and 2D observations.\n\n self.transition_matrix = np.array(\n [[1., 0.5, 0.], [-0.2, 0.3, 0.], [0.01, 0.02, 0.97]], dtype=np.float32)\n\n self.transition_noise = tfd.MultivariateNormalDiag(\n loc=np.array([-4.3, 0.9, 0.], dtype=np.float32),\n scale_diag=np.array([1., 1., 0.5], dtype=np.float32))\n\n self.observation_matrix = np.array(\n [[1., 1., 0.2], [0.3, -0.7, -0.2]], dtype=np.float32)\n self.observation_noise = tfd.MultivariateNormalDiag(\n loc=np.array([-0.9, 0.1], dtype=np.float32),\n scale_diag=np.array([0.3, 0.1], dtype=np.float32))\n\n self.initial_state_prior = tfd.MultivariateNormalDiag(\n loc=np.zeros(shape=[3,], dtype=np.float32),\n scale_diag=np.ones(shape=[3,], dtype=np.float32))\n\n return tfd.LinearGaussianStateSpaceModel(\n num_timesteps=5,\n transition_matrix=self.transition_matrix,\n transition_noise=self.transition_noise,\n observation_matrix=self.observation_matrix,\n observation_noise=self.observation_noise,\n initial_state_prior=self.initial_state_prior,\n initial_step=0)\n\n def testKalmanSmoother(self):\n obs = np.array(\n [[[1.36560337, 0.28252135],\n [-0.44638565, -0.76692033],\n [0.43440145, -1.65087236],\n [-0.96462844, -0.29173164],\n [-0.46593086, 0.23341251]]],\n dtype=np.float32)\n\n kf = self.build_kf()\n _, filtered_means, filtered_covs, _, _, _, _ = kf.forward_filter(obs)\n smoothed_means, smoothed_covs = kf.posterior_marginals(obs)\n\n # Numbers are checked against results from well-tested open source package.\n # In order to replicate the numbers below, one could run the following\n # script with PyKalman installed. https://pykalman.github.io with v.0.9.2.\n # \"\"\"\n # import numpy as np\n # import pykalman\n # kf = pykalman.KalmanFilter(\n # transition_matrices=np.array(\n # [[1., 0.5, 0.], [-0.2, 0.3, 0.], [0.01, 0.02, 0.97]],\n # . dtype=np.float32),\n # observation_matrices=np.array(\n # [[1., 1., 0.2], [0.3, -0.7, -0.2]], dtype=np.float32),\n # transition_covariance=np.diag(np.square([1., 1., 0.5])),\n # observation_covariance=np.diag(np.square([0.3, 0.1])),\n # transition_offsets=np.array([-4.3, 0.9, 0.], dtype=np.float32),\n # observation_offsets=np.array([-0.9, 0.1], dtype=np.float32),\n # initial_state_mean=np.zeros(shape=[3,], dtype=np.float32),\n # initial_state_covariance=np.diag(np.ones(shape=[3,],\n # . dtype=np.float32)),\n # n_dim_state=3, n_dim_obs=2)\n # x = np.array([[1.36560337, 0.28252135],\n # [-0.44638565, -0.76692033],\n # [0.43440145, -1.65087236],\n # [-0.96462844, -0.29173164],\n # [-0.46593086, 0.23341251]],\n # dtype=np.float32)\n # filtered_means, filtered_covs = kf.filter(x)\n # smoothed_means, smoothed_covs = kf.smooth(x)\n # \"\"\"\n\n self.assertAllClose(self.evaluate(filtered_means),\n [[[1.67493705, 0.46825252, 0.02124943],\n [-0.64631546, 1.00897487, -0.09965568],\n [-1.01912747, 2.20042742, -0.35873311],\n [-0.67203603, 0.65843169, -1.13269043],\n [0.08385944, 0.50706669, -2.05841075]]])\n self.assertAllClose(self.evaluate(filtered_covs),\n [[[0.05451537, -0.00583471, 0.05521206],\n [-0.00583471, 0.07889925, -0.23913612],\n [0.05521206, -0.23913612, 0.93451188]],\n [[0.05475972, -0.00706799, 0.05972831],\n [-0.00706799, 0.08838377, -0.27438752],\n [0.05972831, -0.27438752, 1.06529626]],\n [[0.05507039, -0.00857061, 0.06554467],\n [-0.00857061, 0.09565483, -0.30253237],\n [0.06554467, -0.30253237, 1.17423936]],\n [[0.05534107, -0.00984834, 0.07049446],\n [-0.00984834, 0.10168645, -0.3258982],\n [0.07049446, -0.3258982, 1.26475611]],\n [[0.05556491, -0.01090359, 0.07458252],\n [-0.01090359, 0.10666106, -0.34516996],\n [0.07458252, -0.34516996, 1.33941529]]])\n self.assertAllClose(self.evaluate(smoothed_means),\n [[[1.6779677, 0.85140403, -1.35974017],\n [-0.56246908, 1.46082297, -1.62395504],\n [-0.90536, 2.63540628, -1.83427299],\n [-0.47239553, 0.95851585, -2.01734974],\n [0.08385944, 0.50706669, -2.05841075]]])\n self.assertAllClose(self.evaluate(smoothed_covs),\n [[[0.05213916, -0.00658443, 0.05523982],\n [-0.00658443, 0.07103678, -0.21066964],\n [0.05523982, -0.21066964, 0.82790034]],\n [[0.05249696, -0.00812691, 0.06099242],\n [-0.00812691, 0.0799351, -0.24409068],\n [0.06099242, -0.24409068, 0.95324973]],\n [[0.05297552, -0.01009223, 0.06865306],\n [-0.01009223, 0.08801685, -0.27559063],\n [0.06865306, -0.27559063, 1.07602637]],\n [[0.05343939, -0.0120551, 0.07628306],\n [-0.0120551, 0.09641572, -0.30821036],\n [0.07628306, -0.30821036, 1.20272402]],\n [[0.05556491, -0.01090359, 0.07458252],\n [-0.01090359, 0.10666106, -0.34516996],\n [0.07458252, -0.34516996, 1.33941529]]])\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass _KalmanStepsTest(object):\n\n def setUp(self):\n # Define a simple model with 2D latents and 1D observations.\n\n self.transition_matrix = np.asarray([[1., .5], [-.2, .3]], dtype=np.float32)\n self.get_transition_matrix_for_timestep = (\n lambda t: tfl.LinearOperatorFullMatrix(self.transition_matrix))\n\n self.bias = np.asarray([-4.3, .9], dtype=np.float32)\n self.get_transition_noise_for_timestep = (\n lambda t: tfd.MultivariateNormalDiag(self.bias, [1., 1.]))\n\n self.observation_matrix = np.asarray([[1., 1.], [0.3, -0.7]],\n dtype=np.float32)\n self.get_observation_matrix_for_timestep = (\n lambda t: tfl.LinearOperatorFullMatrix(self.observation_matrix))\n\n self.observation_bias = np.asarray([-.9, .1], dtype=np.float32)\n self.observation_noise_scale_diag = np.asarray([1., 0.3], dtype=np.float32)\n def get_observation_noise_for_timestep(t):\n del t # unused\n return tfd.MultivariateNormalDiag(\n loc=self.observation_bias,\n scale_diag=self.observation_noise_scale_diag)\n self.get_observation_noise_for_timestep = get_observation_noise_for_timestep\n\n def testKalmanFilterStep(self):\n prev_mean = np.asarray([[-2], [.4]], dtype=np.float32)\n prev_cov = np.asarray([[.5, .1], [.2, .6]], dtype=np.float32)\n x_observed = np.asarray([[4.]], dtype=np.float32)\n\n prev_mean_tensor = self.build_tensor(prev_mean)\n prev_cov_tensor = self.build_tensor(prev_cov)\n x_observed_tensor = self.build_tensor(x_observed)\n\n filter_step = 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 initial_filter_state = KalmanFilterState(\n filtered_mean=None,\n filtered_cov=None,\n predicted_mean=prev_mean_tensor,\n predicted_cov=prev_cov_tensor,\n observation_mean=None,\n observation_cov=None,\n log_marginal_likelihood=self.build_tensor(0.),\n timestep=self.build_tensor(0))\n\n filter_state = self.evaluate(\n filter_step(initial_filter_state,\n x_observed_tensor))\n\n # Computed by running a believed-correct version of\n # the code.\n expected_filtered_mean = [[1.41887522], [-2.82712531]]\n expected_filtered_cov = [[0.27484685, 0.05869688],\n [0.06994689, 0.1369969]]\n expected_predicted_mean = [[-4.29468775], [-0.23191273]]\n expected_predicted_cov = [[1.37341797, -0.01930545],\n [-0.02380546, 1.01560497]]\n expected_observation_mean = [[-2.5], [-0.77999997]]\n expected_observation_cov = [[2.4000001, -0.28000003],\n [-0.28000003, 0.366]]\n expected_log_marginal_likelihood = -56.5381\n\n self.assertAllClose(filter_state.filtered_mean,\n expected_filtered_mean)\n self.assertAllClose(filter_state.filtered_cov,\n expected_filtered_cov)\n self.assertAllClose(filter_state.predicted_mean,\n expected_predicted_mean)\n self.assertAllClose(filter_state.predicted_cov,\n expected_predicted_cov)\n self.assertAllClose(filter_state.observation_mean,\n expected_observation_mean)\n self.assertAllClose(filter_state.observation_cov,\n expected_observation_cov)\n self.assertAllClose(filter_state.log_marginal_likelihood,\n expected_log_marginal_likelihood)\n self.assertAllClose(filter_state.timestep, 1)\n\n def testKalmanTransition(self):\n\n prev_mean = np.asarray([[-2], [.4]], dtype=np.float32)\n prev_cov = np.asarray([[.5, -.2], [-.2, .9]], dtype=np.float32)\n prev_mean_tensor = self.build_tensor(prev_mean)\n prev_cov_tensor = self.build_tensor(prev_cov)\n\n predicted_mean, predicted_cov = kalman_transition(\n prev_mean_tensor, prev_cov_tensor,\n self.get_transition_matrix_for_timestep(0),\n self.get_transition_noise_for_timestep(0))\n\n self.assertAllClose(self.evaluate(predicted_mean),\n np.dot(self.transition_matrix,\n prev_mean) + self.bias[:, np.newaxis])\n self.assertAllClose(self.evaluate(predicted_cov),\n np.dot(self.transition_matrix,\n np.dot(prev_cov,\n self.transition_matrix.T)) + np.eye(2))\n\n def testLinearGaussianObservation(self):\n prior_mean = np.asarray([[-2], [.4]], dtype=np.float32)\n prior_cov = np.asarray([[.5, -.2], [-.2, .9]], dtype=np.float32)\n x_observed = np.asarray([[4.], [-1.]], dtype=np.float32)\n\n prior_mean_tensor = self.build_tensor(prior_mean)\n prior_cov_tensor = self.build_tensor(prior_cov)\n x_observed_tensor = self.build_tensor(x_observed)\n\n observation_matrix = self.get_observation_matrix_for_timestep(0)\n observation_noise = self.get_observation_noise_for_timestep(0)\n (posterior_mean,\n posterior_cov,\n predictive_dist) = linear_gaussian_update(\n prior_mean_tensor, prior_cov_tensor,\n observation_matrix, observation_noise,\n x_observed_tensor)\n\n expected_posterior_mean = [[-0.373276], [1.65086186]]\n expected_posterior_cov = [[0.24379307, 0.02689655],\n [0.02689655, 0.13344827]]\n expected_predicted_mean = [-2.5, -0.77999997]\n expected_predicted_cov = [[1.99999988, -0.39999998],\n [-0.39999998, 0.65999997]]\n\n self.assertAllClose(self.evaluate(posterior_mean),\n expected_posterior_mean)\n self.assertAllClose(self.evaluate(posterior_cov),\n expected_posterior_cov)\n self.assertAllClose(self.evaluate(predictive_dist.mean()),\n expected_predicted_mean)\n self.assertAllClose(self.evaluate(predictive_dist.covariance()),\n expected_predicted_cov)\n\n def testBackwardSmoothingStep(self):\n filtered_mean = [[2.], [-3.]]\n filtered_cov = [[1.2, 0.4],\n [0.4, 2.3]]\n predicted_mean = [[2.1], [-2.7]]\n predicted_cov = [[1.1, 0.5],\n [0.5, 2.]]\n next_smoothed_mean = [[1.9], [-2.9]]\n next_smoothed_cov = [[1.4, 0.4],\n [0.4, 2.1]]\n transition_matrix = [[0.6, 0.3],\n [0.4, 0.7]]\n\n filtered_mean = self.build_tensor(filtered_mean)\n filtered_cov = self.build_tensor(filtered_cov)\n predicted_mean = self.build_tensor(predicted_mean)\n predicted_cov = self.build_tensor(predicted_cov)\n next_smoothed_mean = self.build_tensor(next_smoothed_mean)\n next_smoothed_cov = self.build_tensor(next_smoothed_cov)\n get_transition_matrix_for_timestep = (\n lambda t: tfl.LinearOperatorFullMatrix(transition_matrix))\n transition_matrix = get_transition_matrix_for_timestep(0)\n\n posterior_mean, posterior_cov = backward_smoothing_update(\n filtered_mean, filtered_cov,\n predicted_mean, predicted_cov,\n next_smoothed_mean, next_smoothed_cov,\n transition_matrix)\n\n # The expected results are calculated by analytical calculation.\n self.assertAllClose(self.evaluate(posterior_mean),\n [[1.824], [-3.252]])\n self.assertAllClose(self.evaluate(posterior_cov),\n [[1.30944, 0.45488],\n [0.45488, 2.35676]])\n\n def testBackwardPassStep(self):\n filtered_mean = [[2.], [-3.]]\n filtered_cov = [[1.2, 0.4],\n [0.4, 2.3]]\n predicted_mean = [[2.1], [-2.7]]\n predicted_cov = [[1.1, 0.5],\n [0.5, 2.]]\n next_smoothed_mean = [[1.9], [-2.9]]\n next_smoothed_cov = [[1.4, 0.4],\n [0.4, 2.1]]\n transition_matrix = [[0.6, 0.3],\n [0.4, 0.7]]\n\n filtered_mean = self.build_tensor(filtered_mean)\n filtered_cov = self.build_tensor(filtered_cov)\n predicted_mean = self.build_tensor(predicted_mean)\n predicted_cov = self.build_tensor(predicted_cov)\n next_smoothed_mean = self.build_tensor(next_smoothed_mean)\n next_smoothed_cov = self.build_tensor(next_smoothed_cov)\n get_transition_matrix_for_timestep = (\n lambda t: tfl.LinearOperatorFullMatrix(transition_matrix))\n\n smooth_step = build_backward_pass_step(\n get_transition_matrix_for_timestep)\n\n initial_backward_state = BackwardPassState(\n backward_mean=next_smoothed_mean,\n backward_cov=next_smoothed_cov,\n timestep=self.build_tensor(0))\n\n smoothed_state = self.evaluate(\n smooth_step(initial_backward_state,\n [filtered_mean,\n filtered_cov,\n predicted_mean,\n predicted_cov]))\n\n expected_posterior_mean = [[1.824], [-3.252]]\n expected_posterior_cov = [[1.30944, 0.45488],\n [0.45488, 2.35676]]\n\n self.assertAllClose(smoothed_state.backward_mean,\n expected_posterior_mean)\n self.assertAllClose(smoothed_state.backward_cov,\n expected_posterior_cov)\n self.assertAllClose(smoothed_state.timestep,\n -1)\n\n def testLinearGaussianObservationScalarPath(self):\n\n # Construct observed data with a scalar observation.\n prior_mean_tensor = self.build_tensor(\n np.asarray([[-2], [.4]], dtype=np.float32))\n prior_cov_tensor = self.build_tensor(\n np.asarray([[.5, -.2], [-.2, .9]], dtype=np.float32))\n x_observed_tensor = self.build_tensor(\n np.asarray([[4.]], dtype=np.float32))\n\n observation_matrix = tfl.LinearOperatorFullMatrix(\n self.build_tensor([[1., 1.]]))\n observation_noise = tfd.MultivariateNormalDiag(\n loc=self.build_tensor([-.9]), scale_diag=self.build_tensor([1.]))\n\n (posterior_mean,\n posterior_cov,\n predictive_dist) = linear_gaussian_update(\n prior_mean_tensor, prior_cov_tensor,\n observation_matrix, observation_noise,\n x_observed_tensor)\n\n # Ensure we take the scalar-optimized path when shape is static.\n if self.use_static_shape or tf.executing_eagerly():\n self.assertIsInstance(predictive_dist, tfd.Independent)\n else:\n self.assertIsInstance(predictive_dist, tfd.MultivariateNormalTriL)\n self.assertAllEqual(\n self.evaluate(predictive_dist.event_shape_tensor()), [1])\n self.assertAllEqual(\n self.evaluate(predictive_dist.batch_shape_tensor()), [])\n\n # Extend `x_observed` with an extra dimension to force the vector path.\n # The added dimension is non-informative, so we can check that the scalar\n # and vector paths yield the same posterior.\n observation_matrix_extended = tfl.LinearOperatorFullMatrix(\n self.build_tensor([[1., 1.], [0., 0.]]))\n observation_noise_extended = tfd.MultivariateNormalDiag(\n loc=self.build_tensor([-.9, 0.]),\n scale_diag=self.build_tensor([1., 1e15]))\n x_observed_extended_tensor = self.build_tensor(\n np.asarray([[4.], [0.]], dtype=np.float32))\n\n (posterior_mean_extended,\n posterior_cov_extended,\n predictive_dist_extended) = linear_gaussian_update(\n prior_mean_tensor, prior_cov_tensor,\n observation_matrix_extended, observation_noise_extended,\n x_observed_extended_tensor)\n\n # Ensure we took the vector path.\n self.assertIsInstance(predictive_dist_extended, tfd.MultivariateNormalTriL)\n self.assertAllEqual(\n self.evaluate(predictive_dist_extended.event_shape_tensor()), [2])\n self.assertAllEqual(\n self.evaluate(predictive_dist_extended.batch_shape_tensor()), [])\n\n # Test that the results are the same.\n self.assertAllClose(*self.evaluate((posterior_mean,\n posterior_mean_extended)))\n self.assertAllClose(*self.evaluate((posterior_cov,\n posterior_cov_extended)))\n self.assertAllClose(*self.evaluate((predictive_dist.mean(),\n predictive_dist_extended.mean()[:1])))\n self.assertAllClose(\n *self.evaluate((predictive_dist.covariance(),\n predictive_dist_extended.covariance()[:1, :1])))\n\n def testMeanStep(self):\n prev_mean = np.asarray([[-2], [.4]], dtype=np.float32)\n prev_mean_tensor = self.build_tensor(prev_mean)\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 new_mean, obs_mean = self.evaluate(mean_step((prev_mean_tensor, None), t=0))\n\n self.assertAllClose(new_mean,\n np.dot(self.transition_matrix, prev_mean) +\n self.bias[:, np.newaxis])\n self.assertAllClose(obs_mean,\n np.dot(self.observation_matrix, new_mean) +\n self.observation_bias[:, np.newaxis])\n\n def testCovStep(self):\n\n prev_cov = np.asarray([[.5, -.2], [-.2, .9]], dtype=np.float32)\n prev_cov_tensor = self.build_tensor(prev_cov)\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 new_cov, obs_cov = self.evaluate(cov_step((prev_cov_tensor, None), t=0))\n\n self.assertAllClose(new_cov,\n np.dot(self.transition_matrix,\n np.dot(prev_cov,\n self.transition_matrix.T)) + np.eye(2))\n self.assertAllClose(obs_cov,\n np.dot(self.observation_matrix,\n np.dot(new_cov, self.observation_matrix.T)) +\n np.diag(self.observation_noise_scale_diag**2))\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass KalmanStepsTestStatic(tf.test.TestCase, _KalmanStepsTest):\n\n use_static_shape = True\n\n def setUp(self):\n return _KalmanStepsTest.setUp(self)\n\n def build_tensor(self, tensor):\n return tf.convert_to_tensor(value=tensor)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass KalmanStepsTestDynamic(tf.test.TestCase, _KalmanStepsTest):\n\n use_static_shape = False\n\n def setUp(self):\n return _KalmanStepsTest.setUp(self)\n\n def build_tensor(self, tensor):\n return tf.compat.v1.placeholder_with_default(\n input=tf.convert_to_tensor(value=tensor), shape=None)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass _AugmentSampleShapeTest(object):\n\n def testAugmentsShape(self):\n\n full_batch_shape, dist = self.build_inputs([5, 4, 2, 3], [2, 3])\n\n sample_shape = _augment_sample_shape(dist, full_batch_shape,\n validate_args=True)\n\n self.assertAllEqual(self.maybe_evaluate(sample_shape), [5, 4])\n\n def testSameShape(self):\n\n full_batch_shape, dist = self.build_inputs([5, 4, 2, 3], [5, 4, 2, 3])\n sample_shape = _augment_sample_shape(dist, full_batch_shape,\n validate_args=True)\n\n self.assertAllEqual(self.maybe_evaluate(sample_shape), [])\n\n # We omit the eager-mode decorator for error handling checks,\n # because eager mode throws dynamic errors statically which confuses\n # the test harness.\n def testNotPrefixThrowsError(self):\n\n full_batch_shape, dist = self.build_inputs([5, 4, 2, 3], [1, 3])\n\n with self.assertRaisesError(\"Broadcasting is not supported\"):\n self.maybe_evaluate(\n _augment_sample_shape(dist, full_batch_shape,\n validate_args=True))\n\n def testTooManyDimsThrowsError(self):\n\n full_batch_shape, dist = self.build_inputs([5, 4, 2, 3], [6, 5, 4, 2, 3])\n\n with self.assertRaisesError(\n \"(Broadcasting is not supported|Cannot broadcast)\"):\n self.maybe_evaluate(\n _augment_sample_shape(dist, full_batch_shape,\n validate_args=True))\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass AugmentSampleShapeTestStatic(tf.test.TestCase, _AugmentSampleShapeTest):\n\n def assertRaisesError(self, msg):\n return self.assertRaisesRegexp(Exception, msg)\n\n def build_inputs(self, full_batch_shape, partial_batch_shape):\n\n full_batch_shape = np.asarray(full_batch_shape, dtype=np.int32)\n dist = tfd.Normal(tf.random.normal(partial_batch_shape), 1.)\n\n return full_batch_shape, dist\n\n def maybe_evaluate(self, x):\n return x\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass AugmentSampleShapeTestDynamic(tf.test.TestCase, _AugmentSampleShapeTest):\n\n def assertRaisesError(self, msg):\n if tf.executing_eagerly():\n return self.assertRaisesRegexp(Exception, msg)\n else:\n return self.assertRaisesOpError(msg)\n\n def build_inputs(self, full_batch_shape, partial_batch_shape):\n full_batch_shape = tf.compat.v1.placeholder_with_default(\n input=np.asarray(full_batch_shape, dtype=np.int32), shape=None)\n\n partial_batch_shape = tf.compat.v1.placeholder_with_default(\n input=np.asarray(partial_batch_shape, dtype=np.int32), shape=None)\n dist = tfd.Normal(tf.random.normal(partial_batch_shape), 1.)\n\n return full_batch_shape, dist\n\n def maybe_evaluate(self, x):\n return self.evaluate(x)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] |
[
[
"tensorflow.convert_to_tensor",
"numpy.dot",
"numpy.diag",
"numpy.sqrt",
"tensorflow.zeros",
"numpy.asarray",
"tensorflow.reduce_sum",
"tensorflow.cast",
"numpy.concatenate",
"numpy.random.randn",
"numpy.mean",
"numpy.var",
"tensorflow.compat.v1.placeholder_with_default",
"numpy.eye",
"tensorflow.gradients",
"tensorflow.test.main",
"numpy.zeros",
"numpy.log",
"tensorflow.executing_eagerly",
"tensorflow.linalg.LinearOperatorFullMatrix",
"numpy.array",
"tensorflow.constant",
"numpy.isfinite",
"tensorflow.ones",
"numpy.ones",
"tensorflow.math.log",
"tensorflow.sqrt",
"tensorflow.random.normal"
]
] |
ejarkm/model-analysis
|
[
"ff145c356c89a7bb421b86718a2f50f7c5c1f621"
] |
[
"tensorflow_model_analysis/eval_saved_model/exporter.py"
] |
[
"# 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\"\"\"`Exporter` class represents different flavors of model export.\"\"\"\n\nimport collections\nimport contextlib\nimport os\nimport types\nfrom typing import Callable, Dict, List, Optional, Union\n\nimport tensorflow as tf\n\nfrom tensorflow_model_analysis.eval_saved_model import export\nfrom tensorflow_model_analysis.utils import util as tfma_util\nfrom tensorflow.python.estimator import gc\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import tf_logging\n\n\n# Largely copied from tensorflow.python.estimator.exporter\nclass _EvalSavedModelExporter(tf.estimator.Exporter):\n \"\"\"This class exports the EvalSavedModel.\n\n This class provides a basic exporting functionality and serves as a\n foundation for specialized `Exporter`s.\n \"\"\"\n\n @tfma_util.kwargs_only\n def __init__(self,\n name: str,\n eval_input_receiver_fn: Callable[[],\n export.EvalInputReceiverType],\n serving_input_receiver_fn: Optional[Callable[\n [], tf.estimator.export.ServingInputReceiver]] = None,\n assets_extra: Optional[Dict[str, str]] = None):\n \"\"\"Create an `Exporter` to use with `tf.estimator.EvalSpec`.\n\n Args:\n name: Unique name of this `Exporter` that is going to be used in the\n export path.\n eval_input_receiver_fn: Eval input receiver function.\n serving_input_receiver_fn: (Optional) Serving input receiver function. We\n recommend that you provide this as well, so that the exported SavedModel\n also contains the serving graph. If not provided, the serving graph will\n not be included in the exported SavedModel.\n assets_extra: An optional dict specifying how to populate the assets.extra\n directory within the exported SavedModel. Each key should give the\n destination path (including the filename) relative to the assets.extra\n directory. The corresponding value gives the full path of the source\n file to be copied. For example, the simple case of copying a single\n file without renaming it is specified as\n `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.\n \"\"\"\n self._name = name\n self._eval_input_receiver_fn = eval_input_receiver_fn\n self._serving_input_receiver_fn = serving_input_receiver_fn\n self._assets_extra = assets_extra\n\n @property\n def name(self) -> str:\n return self._name\n\n def export(self, estimator: tf.estimator.Estimator, export_path: str,\n checkpoint_path: Optional[str], eval_result: Optional[bytes],\n is_the_final_export: bool) -> bytes:\n del is_the_final_export\n\n export_result = export.export_eval_savedmodel(\n estimator=estimator,\n export_dir_base=export_path,\n eval_input_receiver_fn=self._eval_input_receiver_fn,\n serving_input_receiver_fn=self._serving_input_receiver_fn,\n assets_extra=self._assets_extra,\n checkpoint_path=checkpoint_path,\n )\n\n return export_result\n\n\nclass FinalExporter(tf.estimator.Exporter):\n \"\"\"This class exports the EvalSavedModel in the end.\n\n This class performs a single export in the end of training.\n \"\"\"\n\n @tfma_util.kwargs_only\n def __init__(self,\n name: str,\n eval_input_receiver_fn: Callable[[],\n export.EvalInputReceiverType],\n serving_input_receiver_fn: Optional[Callable[\n [], tf.estimator.export.ServingInputReceiver]] = None,\n assets_extra: Optional[Dict[str, str]] = None):\n \"\"\"Create an `Exporter` to use with `tf.estimator.EvalSpec`.\n\n Args:\n name: Unique name of this `Exporter` that is going to be used in the\n export path.\n eval_input_receiver_fn: Eval input receiver function.\n serving_input_receiver_fn: (Optional) Serving input receiver function. We\n recommend that you provide this as well, so that the exported SavedModel\n also contains the serving graph. If not provided, the serving graph will\n not be included in the exported SavedModel.\n assets_extra: An optional dict specifying how to populate the assets.extra\n directory within the exported SavedModel. Each key should give the\n destination path (including the filename) relative to the assets.extra\n directory. The corresponding value gives the full path of the source\n file to be copied. For example, the simple case of copying a single\n file without renaming it is specified as\n `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.\n \"\"\"\n self._eval_saved_model_exporter = _EvalSavedModelExporter(\n name=name,\n eval_input_receiver_fn=eval_input_receiver_fn,\n serving_input_receiver_fn=serving_input_receiver_fn,\n assets_extra=assets_extra)\n\n @property\n def name(self) -> str:\n return self._eval_saved_model_exporter.name\n\n def export(self, estimator: tf.estimator.Estimator, export_path: str,\n checkpoint_path: Optional[str], eval_result: Optional[bytes],\n is_the_final_export: bool) -> Optional[bytes]:\n if not is_the_final_export:\n return None\n\n tf_logging.info('Performing the final export in the end of training.')\n\n return self._eval_saved_model_exporter.export(estimator, export_path,\n checkpoint_path, eval_result,\n is_the_final_export)\n\n\nclass LatestExporter(tf.estimator.Exporter):\n \"\"\"This class regularly exports the EvalSavedModel.\n\n In addition to exporting, this class also garbage collects stale exports.\n \"\"\"\n\n @tfma_util.kwargs_only\n def __init__(self,\n name: str,\n eval_input_receiver_fn: Callable[[],\n export.EvalInputReceiverType],\n serving_input_receiver_fn: Optional[Callable[\n [], tf.estimator.export.ServingInputReceiver]] = None,\n exports_to_keep: int = 5,\n assets_extra: Optional[Dict[str, str]] = None):\n \"\"\"Create an `Exporter` to use with `tf.estimator.EvalSpec`.\n\n Args:\n name: Unique name of this `Exporter` that is going to be used in the\n export path.\n eval_input_receiver_fn: Eval input receiver function.\n serving_input_receiver_fn: (Optional) Serving input receiver function. We\n recommend that you provide this as well, so that the exported SavedModel\n also contains the serving graph. If not provided, the serving graph will\n not be included in the exported SavedModel.\n exports_to_keep: Number of exports to keep. Older exports will be\n garbage-collected. Defaults to 5. Set to `None` to disable garbage\n collection.\n assets_extra: An optional dict specifying how to populate the assets.extra\n directory within the exported SavedModel. Each key should give the\n destination path (including the filename) relative to the assets.extra\n directory. The corresponding value gives the full path of the source\n file to be copied. For example, the simple case of copying a single\n file without renaming it is specified as\n `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.\n\n Raises:\n ValueError: if exports_to_keep is set to a non-positive value.\n \"\"\"\n self._eval_saved_model_exporter = _EvalSavedModelExporter(\n name=name,\n eval_input_receiver_fn=eval_input_receiver_fn,\n serving_input_receiver_fn=serving_input_receiver_fn,\n assets_extra=assets_extra)\n self._exports_to_keep = exports_to_keep\n if exports_to_keep is not None and exports_to_keep <= 0:\n raise ValueError(\n '`exports_to_keep`, if provided, must be positive number')\n\n @property\n def name(self) -> str:\n return self._eval_saved_model_exporter.name\n\n def export(self, estimator: tf.estimator.Estimator, export_path: str,\n checkpoint_path: Optional[str], eval_result: Optional[bytes],\n is_the_final_export: bool) -> bytes:\n export_result = self._eval_saved_model_exporter.export(\n estimator, export_path, checkpoint_path, eval_result,\n is_the_final_export)\n\n self._garbage_collect_exports(export_path)\n return export_result\n\n def _garbage_collect_exports(self, export_dir_base: str):\n \"\"\"Deletes older exports, retaining only a given number of the most recent.\n\n Export subdirectories are assumed to be named with monotonically increasing\n integers; the most recent are taken to be those with the largest values.\n\n Args:\n export_dir_base: the base directory under which each export is in a\n versioned subdirectory.\n \"\"\"\n if self._exports_to_keep is None:\n return\n\n def _export_version_parser(path):\n # create a simple parser that pulls the export_version from the directory.\n filename = os.path.basename(path.path)\n if not (len(filename) == 10 and filename.isdigit()):\n return None\n return path._replace(export_version=int(filename))\n\n # pylint: disable=protected-access\n keep_filter = gc._largest_export_versions(self._exports_to_keep)\n delete_filter = gc._negation(keep_filter)\n for p in delete_filter(\n gc._get_paths(export_dir_base, parser=_export_version_parser)):\n try:\n gfile.DeleteRecursively(p.path)\n except errors_impl.NotFoundError as e:\n tf_logging.warn('Can not delete %s recursively: %s', p.path, e)\n # pylint: enable=protected-access\n\n\[email protected]\ndef _remove_metrics(estimator: tf.estimator.Estimator,\n metrics_to_remove: Union[List[str], Callable[[str], bool]]):\n \"\"\"Modifies the Estimator to make its model_fn return less metrics in EVAL.\n\n Note that this only removes the metrics from the\n EstimatorSpec.eval_metric_ops. It does not remove them from the graph or\n undo any side-effects that they might have had (e.g. modifications to\n METRIC_VARIABLES collections).\n\n This is useful for when you use py_func, streaming metrics, or other metrics\n incompatible with TFMA in your trainer. To keep these metrics in your trainer\n (so they still show up in Tensorboard) and still use TFMA, you can call\n remove_metrics on your Estimator before calling export_eval_savedmodel.\n\n This is a context manager, so it can be used like:\n with _remove_metrics(estimator, ['streaming_auc']):\n tfma.export.export_eval_savedmodel(estimator, ...)\n\n Args:\n estimator: tf.estimator.Estimator to modify. Will be mutated in place.\n metrics_to_remove: List of names of metrics to remove.\n\n Yields:\n Nothing.\n \"\"\"\n old_call_model_fn = estimator._call_model_fn # pylint: disable=protected-access\n\n def wrapped_call_model_fn(unused_self, features, labels, mode, config):\n result = old_call_model_fn(features, labels, mode, config)\n if mode == tf.estimator.ModeKeys.EVAL:\n filtered_eval_metric_ops = {}\n for k, v in result.eval_metric_ops.items():\n if isinstance(metrics_to_remove, collections.Iterable):\n if k in metrics_to_remove:\n continue\n elif callable(metrics_to_remove):\n if metrics_to_remove(k):\n continue\n filtered_eval_metric_ops[k] = v\n result = result._replace(eval_metric_ops=filtered_eval_metric_ops)\n return result\n\n estimator._call_model_fn = types.MethodType( # pylint: disable=protected-access\n wrapped_call_model_fn, estimator)\n\n yield\n\n estimator._call_model_fn = old_call_model_fn # pylint: disable=protected-access\n\n\ndef adapt_to_remove_metrics(\n exporter: tf.estimator.Exporter, metrics_to_remove: Union[List[str],\n Callable[[str],\n bool]]\n) -> tf.estimator.Exporter:\n \"\"\"Modifies the given exporter to remove metrics before export.\n\n This is useful for when you use py_func, streaming metrics, or other metrics\n incompatible with TFMA in your trainer. To keep these metrics in your trainer\n (so they still show up in Tensorboard) and still use TFMA, you can call\n adapt_to_remove_metrics on your TFMA exporter.\n\n Args:\n exporter: Exporter to modify. Will be mutated in place.\n metrics_to_remove: Which metrics to remove. Either a list of names, or a\n callable that returns true for names that should be removed.\n\n Returns:\n The mutated exporter, which will be modified in place. We also return it\n so that this can be used in an expression.\n \"\"\"\n\n old_export = exporter.export\n\n def wrapped_export(unused_self, estimator: tf.estimator.Estimator,\n export_path: str, checkpoint_path: Optional[str],\n eval_result: Optional[bytes],\n is_the_final_export: bool) -> bytes:\n with _remove_metrics(estimator, metrics_to_remove):\n return old_export(estimator, export_path, checkpoint_path, eval_result,\n is_the_final_export)\n\n exporter.export = types.MethodType(wrapped_export, exporter)\n return exporter\n"
] |
[
[
"tensorflow.python.estimator.gc._largest_export_versions",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.platform.tf_logging.info",
"tensorflow.python.platform.gfile.DeleteRecursively",
"tensorflow.python.estimator.gc._negation",
"tensorflow.python.estimator.gc._get_paths"
]
] |
alekzieba/tensorflow-deeplab-v3-plus
|
[
"6562f25564e1c08a1732aeba53a8fa92beae1764"
] |
[
"inference.py"
] |
[
"\"\"\"Run inference a DeepLab v3 model using tf.estimator API.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\n\nimport tensorflow as tf\n\nimport deeplab_model\nfrom utils import preprocessing\nfrom utils import dataset_util\n\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.python import debug as tf_debug\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--data_dir', type=str, default='dataset/VOCdevkit/VOC2012/JPEGImages',\n help='The directory containing the image data.')\n\nparser.add_argument('--output_dir', type=str, default='./dataset/inference_output',\n help='Path to the directory to generate the inference results')\n\nparser.add_argument('--infer_data_list', type=str, default='./dataset/sample_images_list.txt',\n help='Path to the file listing the inferring images.')\n\nparser.add_argument('--model_dir', type=str, default='./model',\n help=\"Base directory for the model. \"\n \"Make sure 'model_checkpoint_path' given in 'checkpoint' file matches \"\n \"with checkpoint name.\")\n\nparser.add_argument('--base_architecture', type=str, default='resnet_v2_101',\n choices=['resnet_v2_50', 'resnet_v2_101'],\n help='The architecture of base Resnet building block.')\n\nparser.add_argument('--output_stride', type=int, default=16,\n choices=[8, 16],\n help='Output stride for DeepLab v3. Currently 8 or 16 is supported.')\n\nparser.add_argument('--debug', action='store_true',\n help='Whether to use debugger to track down bad values during training.')\n\nparser.add_argument('--psi_type', type=str, default='ZERO',\n help='Options: ZERO, ONES, GAUSSIAN, SOBEL')\n\nparser.add_argument('--psi_param', type=float, default=1.0,\n help='Sigma if GAUSSIAN.')\n\nparser.add_argument('--psi_scale', type=float, default=1.0,\n help='Scale of PSI function.')\n\n_NUM_CLASSES = 21\n\n\ndef main(unused_argv):\n # Using the Winograd non-fused algorithms provides a small performance boost.\n os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'\n\n pred_hooks = None\n if FLAGS.debug:\n debug_hook = tf_debug.LocalCLIDebugHook()\n pred_hooks = [debug_hook]\n\n model = tf.estimator.Estimator(\n model_fn=deeplab_model.deeplabv3_plus_model_fn,\n model_dir=FLAGS.model_dir,\n params={\n 'output_stride': FLAGS.output_stride,\n 'batch_size': 1, # Batch size must be 1 because the images' size may differ\n 'base_architecture': FLAGS.base_architecture,\n 'pre_trained_model': None,\n 'batch_norm_decay': None,\n 'num_classes': _NUM_CLASSES,\n 'psi_type': FLAGS.psi_type,\n 'psi_param': FLAGS.psi_param,\n 'psi_scale': FLAGS.psi_scale\n })\n\n examples = dataset_util.read_examples_list(FLAGS.infer_data_list)\n image_files = [os.path.join(FLAGS.data_dir, filename) for filename in examples]\n\n predictions = model.predict(\n input_fn=lambda: preprocessing.eval_input_fn(image_files),\n hooks=pred_hooks)\n\n output_dir = FLAGS.output_dir\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n for pred_dict, image_path in zip(predictions, image_files):\n image_basename = os.path.splitext(os.path.basename(image_path))[0]\n output_filename = image_basename + '_mask.png'\n path_to_output = os.path.join(output_dir, output_filename)\n\n print(\"generating:\", path_to_output)\n mask = pred_dict['decoded_labels']\n mask = Image.fromarray(mask)\n plt.axis('off')\n plt.imshow(mask)\n plt.savefig(path_to_output, bbox_inches='tight')\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"tensorflow.estimator.Estimator",
"matplotlib.pyplot.savefig",
"tensorflow.logging.set_verbosity",
"matplotlib.pyplot.axis",
"tensorflow.python.debug.LocalCLIDebugHook",
"tensorflow.app.run"
]
] |
Big-Fuzz/AS-MT
|
[
"85e24feb39608136429843ea02313e628225d72e"
] |
[
"NN_extended_32/perf_on_all_df.py"
] |
[
"from utils_tf2 import *\nimport numpy as np\nimport tensorflow as tf\nimport math\nimport pickle\nimport pandas as pd\n\n\n\ntf.compat.v1.disable_eager_execution()\ntf.compat.v1.reset_default_graph() # to be able to rerun the model without overwriting tf variables\n\n################################################################### Givens:\ndatas = [\"datasets/Data_with_header.csv\", \"datasets/Data_0_9.csv\", \"datasets/Data_NN_+_0_9.csv\", \"datasets/Data_1_6.csv\", \"datasets/Data_3_2.csv\", \"datasets/Data_32.csv\", \"datasets/Data_extended_all.csv\", \"datasets/Data_all.csv\"]\nnorm_mean = \"normalizations/s11_extended_32_dB_mean_value.pkl\"\nnorm_std = \"normalizations/s11_extended_32_dB_std_value.pkl\"\nparam = 'parameters/S11_extended_32_parameters_dB.pkl'\nactivations = [\"tanh\", \"tanh\", \"tanh\", \"tanh\", \"relu\"]\nlist_of_inputs = [ 'permittivity', 'patch_length','patch_width','substrate_height','feed_depth', 'feed_gap_width', 'resonance']\nlist_of_outputs = ['s11']\ndB = True # for dB values or Resonance\n\n#################################################################### Start\nfor i in datas:\n\ta_file = open(param, \"rb\")\n\tparameters = pickle.load(a_file)\n\ta_file.close()\n\tdf = pd.read_csv(i)\n\tdata_x, data_y = separate_dataset(df, list_of_inputs, list_of_outputs)\n\n\tif i == \"datasets/Data_with_header.csv\" and list_of_inputs[len(list_of_inputs)-1] == 'resonance':\n\t\tdata_x[len(list_of_inputs)-1] = data_x[len(list_of_inputs)-1]/(1000000000)\n\t\tprint(\"resonance\")\n\t\t\n\tif i == \"datasets/Data_with_header.csv\"and list_of_outputs[0] == 'resonance':\n\t\tdata_y = data_y / 10**9 \n\t\tprint(\"resonance\")\n\n\tdata_x = normalize_with_existing_wholedf(data_x, name_mean = norm_mean, name_std = norm_std)\n\n\tif list_of_outputs == ['s11'] and dB == False:\n\t\tdata_y = 10 ** (data_y / 20) \n\t\tprint(\"dB = False and S11\")\n\t\t\n\telif list_of_outputs != ['s11'] and dB == False:\n\t\tdata_y = 10 ** (data_y / 10) \n\t\tprint(\"dB = False and not S11\") \n\t\t\n\t(n_x, m) = data_x.shape # (n_x: input size, m : number of examples in the train set)\n\tn_y = data_y.shape[0] # n_y : output size\n\t\t\n\t# Create Placeholders of shape (n_x, n_y)\n\tX, Y = create_placeholders(n_x, n_y)\n\n\t# Forward propagation: Build the forward propagation in the tensorflow graph\n\tZ3 = forward_propagation(X, parameters, activations)\n\n\t# Initialize all the variables\n\tinit = tf.compat.v1.global_variables_initializer()\n\n\twith tf.compat.v1.Session() as sess:\n\t\t\n\t\t# Run the initialization\n\t\tsess.run(init)\n\t\t\n\t\tif list_of_outputs == ['s11'] and dB == False:\n\t\t accuracy_linear = tf.reduce_mean(1 - tf.math.divide(tf.abs(Z3 - Y),tf.abs(Y)))\n\t\t acc_linear = accuracy_linear.eval({X: data_x, Y: data_y})\n\t\t \n\t\t accuracy_log = tf.reduce_mean(1 - tf.math.divide(tf.abs(20 * log10(abs(Z3)) - 20 * log10(Y) ), tf.abs(20 * log10(Y) )))\n\t\t acc_log = accuracy_log.eval({X: data_x, Y: data_y})\n\t\t print(\"dB = False and S11\")\n\t\t \n\t\telif list_of_outputs != ['s11'] and dB == False:\n\t\t accuracy_linear = tf.reduce_mean(1 - tf.math.divide(tf.abs(Z3 - Y),tf.abs(Y)))\n\t\t acc_linear = accuracy_linear.eval({X: data_x, Y: data_y})\n\t\t \n\t\t accuracy_log = tf.reduce_mean(1 - tf.math.divide(tf.abs(10 * log10(abs(Z3)) - 10 * log10(Y) ), tf.abs(10 * log10(Y) )))\n\t\t acc_log = accuracy_log.eval({X: data_x, Y: data_y})\n\t\t print(\"dB = False and not S11\") \n\t\t\n\t\telif list_of_outputs == ['s11'] and dB == True:\n\t\t accuracy_log = tf.reduce_mean(1 - tf.math.divide(tf.abs(Z3 - Y),tf.abs(Y)))\n\t\t acc_log = accuracy_log.eval({X: data_x, Y: data_y}) \n\t\t \n\t\t accuracy_linear = tf.reduce_mean(1 - tf.math.divide(tf.abs(10 ** (Z3 / 20) - 10 ** (Y / 20) ), tf.abs(10 ** (Y / 20) )))\n\t\t acc_linear = accuracy_linear.eval({X: data_x, Y: data_y}) \n\t\t print(\"dB = True and S11 accuracy\") \n\t\t \n\t\telif list_of_outputs != ['s11'] and dB == True:\n\t\t accuracy_log = tf.reduce_mean(1 - tf.math.divide(tf.abs(Z3 - Y),tf.abs(Y)))\n\t\t acc_log = accuracy_log.eval({X: data_x, Y: data_y}) \n\t\t \n\t\t accuracy_linear = tf.reduce_mean(1 - tf.math.divide(tf.abs(10 ** (Z3 / 10) - 10 ** (Y / 10) ), tf.abs(10 ** (Y / 10) )))\n\t\t acc_linear = accuracy_linear.eval({X: data_x, Y: data_y}) \n\t\t print(\"dB = True and not S11\") \n\t\t\n\t\tif list_of_outputs == ['resonance']:\n\t\t print(\"Accuracy: \", acc_log)\n\t\t\n\t\telse: \n\t\t print(\"Linear accuracy: \", acc_linear,i) \n\t\t print(\"Log accuracy: \", acc_log,i)\n\n\n \n\n\n\n \n"
] |
[
[
"pandas.read_csv",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.compat.v1.reset_default_graph",
"tensorflow.abs"
]
] |
mathcoding/Programmazione2
|
[
"09a22ada68fad0797b14cd4776d05bf8a5613e39"
] |
[
"python/ann_minst.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 1 16:43:05 2017\n\n@author: gualandi\n\"\"\"\nimport time\nimport csv\nimport numpy as np\n\nfrom numpy import genfromtxt\nfrom matplotlib import plt\n\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import accuracy_score\n\n\ndef DrawDigit(A, label=''):\n \"\"\" Draw single digit as a greyscale matrix\"\"\"\n fig = plt.figure(figsize=(6,6))\n # Uso la colormap 'gray' per avere la schacchiera in bianco&nero\n img = plt.imshow(A, cmap='gray_r')\n plt.xlabel(label)\n plt.show()\n \ndef ElaborateTrainingSet(data):\n \"\"\" Elaborate training set \"\"\"\n X = []\n Y = [] \n for row in data:\n X.append(np.array(row[1:]))\n Y.append(int(row[0])) \n return X, Y\n\ndef ElaborateTestSet(data):\n \"\"\" Elaborate test set \"\"\"\n X = []\n for row in data:\n X.append(np.array(row))\n return X\n\ndef LearnANN(data):\n \"\"\" Learn an Artificial Neural Network and return the corresponding object \"\"\"\n x_train, y_train = ElaborateTrainingSet(data) \n \n # PRIMA DI FARE QUESTO ESERCIZIO, STUDIARE IL TUTORIAL:\n # http://scikit-learn.org/stable/modules/neural_networks_supervised.html\n #\n # ESERCIZIO DA FARE: PROVARE I DIVERSI PARAMETRI DI QUESTA CLASSE\n # http://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html\n ann = MLPClassifier(hidden_layer_sizes=(1), random_state=1)\n ann.fit(x_train, y_train)\n return ann\n\ndef TestANN(ann, x_test, y_test):\n \"\"\" Test the learned ANN on the given set of data \"\"\"\n y_pred = ann.predict(x_test)\n \n print(\"Accuracy: \", accuracy_score(y_test, y_pred), ' - Number of itertions:', ann.n_iter_)\n \n # Write the predictinos in a .csv file\n with open('solution.csv','w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',', lineterminator='\\n')\n writer.writerow(['ImageId','Label'])\n for i,p in enumerate(y_pred):\n writer.writerow([i+1,p])\n\n\ndef EvaluateANN(ann, x_test):\n \"\"\" Test the learned ANN and produce output for Kaggle \"\"\"\n start = time.time()\n \n y_pred = ann.predict(x_test)\n \n print('Evaluation time:', time.time()-start,'- size:', len(my_test)) \n print('Number of itertions:', ann.n_iter_)\n \n # Write the predictinos in a .csv file\n with open('solution.csv','w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',', lineterminator='\\n')\n writer.writerow(['ImageId','Label'])\n for i,p in enumerate(y_pred):\n writer.writerow([i+1,p])\n \n\n#------------------------------------------\n# MAIN ENTRY POINT\n#------------------------------------------\nif __name__ == \"__main__\":\n # Misura il tempo per le operazioni principali\n start = time.time()\n \n # Fase 1: Training\n # Read CSV from Numpy, Link:\n # https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html\n my_data = genfromtxt('Projects/MINST/train.csv', delimiter=',', skip_header=1) \n print('Reading time:', time.time()-start)\n start = time.time()\n\n # Cambia in True per plottare alcune immagine\n if False:\n for row in my_data[:9]:\n # Documentation for function 'reshape':\n # https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html\n A = np.array(row[1:]).reshape(28,28) \n DrawDigit(A, 'Digit: ' + str(int(row[0])))\n\n ann = LearnANN(my_data)\n \n print('Learning time:', time.time()-start, '- size:', len(my_data))\n \n # Fase 2: local test for learning of parameters\n # TODO\n \n # Fase 3: Evaluate on Kaggle test set\n my_test = genfromtxt('Projects/MINST/test.csv', delimiter=',', skip_header=1)\n x_test = ElaborateTestSet(my_test) \n EvaluateANN(ann, x_test)\n \n \n\n\n\n\n\n\n\n"
] |
[
[
"sklearn.neural_network.MLPClassifier",
"matplotlib.plt.xlabel",
"matplotlib.plt.imshow",
"numpy.genfromtxt",
"matplotlib.plt.figure",
"numpy.array",
"matplotlib.plt.show",
"sklearn.metrics.accuracy_score"
]
] |
IngeniousCoder/CPU-Monitor
|
[
"d44e64b73c5723764f412ff8b7dafda9cfc29dbe"
] |
[
"Use.py"
] |
[
"import os\r\nprint(\"Loading Dependencies\")\r\nos.system(\"pip install -U git+https://github.com/Rapptz/discord.py@rewrite\")\r\nos.system(\"pip install ast\")\r\nos.system(\"pip install matplotlib\")\r\nos.system(\"pip install numpy\")\r\nos.system(\"cls\")\r\nprint(\"Dependencies Loaded.\")\r\n\r\n\r\nimport discord\r\nfrom discord.ext import commands\r\nfrom time import localtime,strftime\r\nimport asyncio\r\nimport ast\r\nimport psutil\r\nimport json\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\nstarted_bef = False\r\n\r\nfile = open(\"config.txt\",\"r\")\r\nconfig = ast.literal_eval(file.read())\r\nfile.close()\r\n\r\nbot = commands.Bot(command_prefix=\"!\",description=\"\")\r\nbot.remove_command('help')\r\n\r\[email protected]\r\nasync def on_ready():\r\n global started_bef\r\n if started_bef == True:\r\n print(\"Bot Restarted.\")\r\n pass\r\n else:\r\n started_bef = True\r\n print(\"Started!\")\r\n await start()\r\n\r\n\r\n\r\n\r\n#@bot.command()\r\nasync def generate(ctx,*,time):\r\n fname = await gen_graph(time)\r\n file = open(f\"{fname}\",\"rb\")\r\n await ctx.send(file=discord.File(fp=file))\r\n file.close()\r\n\r\nasync def start():\r\n if True:\r\n tn = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n file = open(\"tempdata.txt\",\"w\")\r\n file.write(tn)\r\n file.close()\r\n tn = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n file = open(\"tempdata_2.txt\",\"w\")\r\n file.write(tn)\r\n file.close()\r\n local_10m = {}\r\n print(\"Log Start\")\r\n #start logging CPU\r\n global data_cpu\r\n i10m_mins = 0\r\n cpu_chart = []\r\n cpu_chart_hourly = []\r\n sec = 0\r\n cpu_chart_sec = 0\r\n while True:\r\n cpu = psutil.cpu_percent()\r\n sec += 1\r\n cpu_chart.append(cpu)\r\n cpu_chart_hourly.append(cpu)\r\n if sec == 2:\r\n sec = 0\r\n #System Logger\r\n #timenow = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n #data_cpu[timenow] = cpu\r\n #update_data()\r\n #Local Loggers\r\n timenow = strftime(\"%H:%M\",localtime())\r\n local_10m[timenow] = cpu\r\n i10m_mins += 1\r\n await asyncio.sleep(30)\r\n cpu_chart_sec += 30\r\n if i10m_mins == 10: ##default value 10\r\n i10_mins = 0\r\n #Generate Graph\r\n await gen_graph(local_10m)\r\n # os.unlink(f\"{timenow}\")\r\n # Reset\r\n local_10m = {}\r\n if cpu_chart_sec % 3600 == 0: #default value 3600\r\n if cpu_chart_sec == 43200:\r\n #Every 12 hours reset\r\n await gen_graph(cpu_chart)\r\n cpu_chart_sec = 0 \r\n tn = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n file = open(\"tempdata.txt\",\"w\")\r\n file.write(tn)\r\n file.close()\r\n cpu_chart = []\r\n print(\"Reset\")\r\n #Hourly\r\n else:\r\n await gen_graph(cpu_chart)\r\n #After that, generate the standard hourly graph.\r\n await gen_graph2(cpu_chart_hourly)\r\n tn = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n file = open(\"tempdata_2.txt\",\"w\")\r\n file.write(tn)\r\n file.close()\r\n cpu_chart_hourly = []\r\n print(\"Reset\")\r\n \r\nasync def gen_graph2(data):\r\n #Data is a dict where Value:x Axis, Key:y Axis\r\n # Return file name\r\n # If data is a list, list format must be [\"StartTime\",*percentages]\r\n if isinstance(data,list):\r\n #List of CPU Values to process in graph\r\n # The returned (sent) graph should be one where X asis only has start (list[0]) and end (timenow) values\r\n # Time now (LIST START) should be DD-MM-YY HH:MM\r\n # Do not process first data in passed list.\r\n file = open(\"tempdata_2.txt\",\"r\")\r\n start_time = file.read()\r\n file.close()\r\n y_axis = data\r\n x_axis = [start_time]\r\n for x in range(len(data)-2):\r\n x_axis.append(\" \"*x)\r\n tn = strftime(\"%m-%d_%H:%M\", localtime())\r\n tn2 = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n x_axis.append(f\"{tn2}\")\r\n fig = plt.figure()\r\n ax = plt.subplot(111)\r\n ax.plot(x_axis, y_axis, label='CPU Usage (%)')\r\n ave = sum(y_axis)/len(y_axis)\r\n hr = (len(y_axis)/2)/60\r\n plt.title(f'CPU Utilisation (Average = {str(ave)}, Time = {str(hr)} Hours)')\r\n ax.legend()\r\n #fn = f'graphs/{timenow}.png'\r\n fn = f'sent/{tn}.png'\r\n fig.savefig(fn)\r\n member = bot.get_user(config.get(\"USERID\"))\r\n file = open(fn,\"rb\")\r\n await member.send(file=discord.File(fp=file))\r\n file.close()\r\n \r\n\r\nasync def gen_graph(data):\r\n #Data is a dict where Value:x Axis, Key:y Axis\r\n # Return file name\r\n # If data is a list, list format must be [\"StartTime\",*percentages]\r\n if isinstance(data,dict):\r\n y_keys = []\r\n x_keys = []\r\n for key, value in data.items():\r\n y_keys.append(key)\r\n x_keys.append(value)\r\n timenow = strftime(\"%m%d %H%M\", localtime())\r\n timenow2 = strftime(\"%Y-%m-%d\", localtime())\r\n \r\n fig = plt.figure()\r\n ax = plt.subplot(111)\r\n ax.plot(y_keys, x_keys, label='CPU Usage (%)')\r\n plt.title('CPU Utilisation')\r\n ax.legend()\r\n #fn = f'graphs/{timenow}.png'\r\n fn = f'graphs/{timenow}.png'\r\n fig.savefig(fn)\r\n print(\"New Graph Added\")\r\n #member = bot.get_user(config.get(\"USERID\"))\r\n #file = open(fn,\"rb\")\r\n #await member.send(file=discord.File(fp=file))\r\n #file.close()\r\n return True\r\n if isinstance(data,list):\r\n #List of CPU Values to process in graph\r\n # The returned (sent) graph should be one where X asis only has start (list[0]) and end (timenow) values\r\n # Time now (LIST START) should be DD-MM-YY HH:MM\r\n # Do not process first data in passed list.\r\n file = open(\"tempdata.txt\",\"r\")\r\n start_time = file.read()\r\n file.close()\r\n y_axis = data\r\n x_axis = [start_time]\r\n for x in range(len(data)-2):\r\n x_axis.append(\" \"*x)\r\n tn = strftime(\"%m-%d_%H:%M\", localtime())\r\n tn2 = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n x_axis.append(f\"{tn2}\")\r\n fig = plt.figure()\r\n ax = plt.subplot(111)\r\n ax.plot(x_axis, y_axis, label='CPU Usage (%)')\r\n ave = sum(y_axis)/len(y_axis)\r\n hr = (len(y_axis)/2)/60\r\n plt.title(f'CPU Utilisation (Average = {str(ave)}, Time = {str(hr)} Hours)')\r\n ax.legend()\r\n #fn = f'graphs/{timenow}.png'\r\n fn = f'sent/{tn}.png'\r\n fig.savefig(fn)\r\n member = bot.get_user(config.get(\"USERID\"))\r\n file = open(fn,\"rb\")\r\n await member.send(file=discord.File(fp=file))\r\n file.close()\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nasync def start_legacy():\r\n local = {}\r\n #start logging CPU\r\n global data_cpu\r\n mins = 0\r\n while True:\r\n timenow = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n data_cpu[timenow] = psutil.cpu_percent()\r\n timenow = strftime(\"%H:%M\",localtime())\r\n local[timenow] = psutil.cpu_percent()\r\n update_data()\r\n print(\"Updated\")\r\n await asyncio.sleep(60)\r\n mins += 1\r\n if mins == 2:\r\n mins = 0\r\n #Generate Graph\r\n y_keys = []\r\n for key, value in local.items():\r\n y_keys.append(key)\r\n x_keys = []\r\n for key, value in local.items():\r\n x_keys.append(value)\r\n trace = go.Scatter(\r\n x = y_keys,\r\n y = x_keys\r\n )\r\n timenow = strftime(\"%Y-%m-%d %H:%M\", localtime())\r\n data = [trace]\r\n fig = go.Figure()\r\n # py.plot(data, filename=f'{timenow}')\r\n fig.add_scatter(x=y_keys,y=x_keys);plot(fig)\r\n if not os.path.exists('images'):\r\n os.mkdir('images')\r\n pio.write_image(fig, f'images/{timenow}.jpeg')\r\n member = bot.get_user(config.get(\"USERID\"))\r\n file = open(f\"images/{timenow}\",\"rb\")\r\n await member.send(file=discord.File(fp=file))\r\n file.close()\r\n os.unlink(f\"{timenow}\")\r\n # Reset\r\n # local = {}\r\n\r\n\r\ndef update_data():\r\n file = open(\"data.txt\",\"w\")\r\n file.write(str(data_cpu))\r\n file.close()\r\n\r\nbot.run(config.get(\"TOKEN\"))\r\n"
] |
[
[
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure"
]
] |
Basvanstein/BIAS
|
[
"5eed56d01803e455ef53afb278f630d5f3c85dc4"
] |
[
"BIAS/Create_RF.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport pickle\nimport glob\nimport matplotlib.pyplot as plt\nimport seaborn as sbs\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix, f1_score\nfrom sklearn.model_selection import train_test_split\n\ntest_names = ['1-spacing', '2-spacing', '3-spacing', 'ad', 'ad_transform', 'shapiro',\n 'jb', 'ddst', 'kurtosis', 'mmpd_min', 'mmpd_max', 'range', 'min', 'max',\n 'mdd_min', 'mdd_max', 'wasserstein', 'kolmogorov', 'CvM', 'Durbin',\n 'Kuiper', 'HG1', 'HG2', 'Greenwood', 'QM', 'RC', 'Moran', 'Cressie1',\n 'Cressie2', 'Vasicek', 'Swartz', 'Morales', 'Pardo', 'Marhuenda',\n 'Zhang1', 'Zhang2']\n\nreadable_label_dict = {\n 'gaps' : 'Gaps',\n 'cauchy' : 'Center', \n 'clusters' : 'Clusters',\n 'inv_cauchy' : 'Bounds',\n 'inv_norm' : 'Bounds',\n 'norm' : 'Center',\n 'part_unif' : 'Clusters',\n 'shifted_spikes' : 'Discretization',\n 'spikes' : 'Discretization',\n 'trunc_unif' : 'Center',\n 'bound_thing' : 'Bounds'\n}\n\ndef create_RF_rej(included_tests = test_names, plot_feat_importance = False, \n use_bias_labels = False, feature_order = None,\n rf_file_name = None):\n cols_to_get = included_tests + ['scen']\n dt_samples = pd.DataFrame()\n for sample_size in [30,50,100,600]:\n for f in glob.glob(f\"/mnt/e/Research/SB_DE/SB/S{sample_size}/*.csv\"):\n dt_temp = pd.read_csv(f)\n# print(len(dt_temp))\n if dt_temp['scen'][0] != 'unif':\n #Remove samples for which no tests reject (non-biased)\n try:\n if sample_size < 99:\n dt_rej_temp = pd.read_csv(f\"/mnt/e/Research/SB_DE/SB/Rejections/S{sample_size}_A0.01_Cnone_{f[29:]}\", index_col=0)\n else:\n dt_rej_temp = pd.read_csv(f\"/mnt/e/Research/SB_DE/SB/Rejections/S{sample_size}_A0.01_Cnone_{f[30:]}\", index_col=0)\n \n dt_test_only = dt_rej_temp[included_tests]\n idxs_save = np.where(dt_test_only.transpose().sum() > 0 )\n dt_samples = dt_samples.append(dt_rej_temp[cols_to_get].iloc[idxs_save])\n except:\n next\n X = dt_samples[included_tests]\n if use_bias_labels:\n Y = [readable_label_dict[x] for x in dt_samples['scen']]\n else:\n Y = dt_samples['scen']\n \n rf = RandomForestClassifier(oob_score=True, class_weight='balanced')\n \n rf.fit(X, Y)\n \n if plot_feat_importance:\n plt.figure(figsize=(19,10))\n if feature_order is None:\n sbs.barplot(x=included_tests, y=rf.feature_importances_)\n else:\n sbs.barplot(x=included_tests, y=rf.feature_importances_, order=feature_order) \n plt.xticks(rotation=90)\n plt.tight_layout()\n plt.savefig(f\"RF_feature_importance.pdf\")\n plt.show()\n \n \n print(rf.oob_score_)\n\n if rf_file_name is not None:\n with open(f\"{rf_file_name}.pkl\", \"wb\") as output_file:\n pickle.dump(rf, output_file)\n return rf"
] |
[
[
"matplotlib.pyplot.tight_layout",
"pandas.read_csv",
"sklearn.ensemble.RandomForestClassifier",
"pandas.DataFrame",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
jb803/tensorForm
|
[
"4d227caa88365d9b20cf65539c83c22560785f6d"
] |
[
"tensorForm/aux.py"
] |
[
"\"\"\"Module for eigenvalue problems.\n\nWe have an abstract base-class representing an eigensolver. This has a number of functions which must be overloaded\"\"\"\n\nfrom abc import ABC,abstractmethod\n\nfrom petsc4py import PETSc \nfrom slepc4py import SLEPc\n\nimport dolfin as dolf\n\nimport time\n\nimport numpy as np\n\nimport os\n\nimport gc\n\nclass EigenError(Exception):\n \"\"\"Error class for errors arising in eigenvalue problems\"\"\"\n def __init__(self,message):\n self.message=message\n\nclass Eigensolver(ABC):\n \"\"\"Abstract base class for an eigensolver.\n\n This abstract class implements some of the required grunt work in :py:meth:`_buildEPS`. The methods that need to\n be overloaded are:\n\n * :py:meth:`build` - builsd the matrices and SLEPc.EPS object needed for the eigensolve.\n * :py:meth:`validateEigenpair` - validates an eigenapair (some eigensolvers will introduce false solutions)\n * :py:meth:`getEigenpair` - returns an eigenpair.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self._defaultLogTime = 10.\n\n self.built = False\n \"\"\"Flag to indicate whether the matrices have been built\"\"\"\n\n def _resetTimes(self):\n \"\"\"Resets internal timers for the stop and logging during eps solves\"\"\"\n self._lastLog = time.time()\n self._startTime = time.time()\n\n def _buildEPS(self,*ops):\n \"\"\"\n Performs the grunt work for build a SLEPC eps object with PETSC matrices as the operators.\n\n This is called by classes inheriting from :py:class:`Eigensolver`. \n\n :params list(PETSc.Mat) ops: set of operator matrices to pass to the eigensolver\n \"\"\"\n eps = SLEPc.EPS().create() #Generate EPS\n st = eps.getST()\n st.setType('sinvert') #shift invert\n\n #Set up the linear solver\n ksp = st.getKSP()\n ksp.setType('preonly')\n pc = ksp.getPC()\n pc.setType('lu')\n pc.setFactorSolverType('mumps')\n\n #Set the operators\n eps.setOperators(*ops)\n\n eps.setStoppingTest(self._eigensolveStop)\n\n self.eps = eps\n\n def _eigensolveStop(self, solver, its, max_it, nconv, nev):\n currTime = time.time()\n solveTime = currTime - self._startTime\n\n if currTime - self._lastLog > self._defaultLogTime:\n self._lastLog = currTime\n\n if nconv >= nev:\n return SLEPc.EPS.ConvergedReason.CONVERGED_TOL\n\n if self._maxSolveTime is not None and solveTime > self._maxSolveTime and its > 8:\n return SLEPc.EPS.ConvergedReason.CONVERGED_USER\n\n if its > max_it:\n return SLEPc.EPS.ConvergedReason.DIVERGED_ITS\n\n return SLEPc.EPS.ConvergedReason.ITERATING\n\n\n @abstractmethod\n def build(self):\n \"\"\"Builds any matrices required and creates the eigensolver.\n\n Must be overloaded by any class inheriting this.\n \"\"\"\n pass\n\n def solve(self,nEigen, maxSolveTime = 240):\n \"\"\"Solves for eigenvalues.\n\n This is performs the grunt work of performing an eigensolve through the SLEPC interface. It uses the :py:attr:`built`\n flag to determing whether or not to call :py:meth:`build` . \n\n :param int nEigen: number of eigenvalues to look for\n :return: number of eigenvalues found\n :rtype: int\n \"\"\"\n #We make sure we have built all the required matrices and solvers\n\n if not self.built:\n self.build()\n \n #TODO: maybe check if the build flag has raised?\n #Set how many eigenvalues to look for\n self.eps.setDimensions(nEigen,SLEPc.DECIDE)\n\n self._resetTimes()\n self._maxSolveTime = maxSolveTime\n\n gc.collect(2) #We should garbage collect before solving #TODO - need to sort out when and how this happens. May do it too oftern\n self.eps.solve()\n\n\n self.validatedEigenpairs = []\n self.storedEigenpairs = []\n\n self.solved = True\n\n return self.eps.getConverged()\n \n def nConverged(self):\n \"\"\"Returns number of eigenvalues converged.\n\n :return: number of eigenvalues converged\n :rtype: int\n \"\"\"\n return self.eps.getConverged()\n\n\n\n @abstractmethod\n def getEigenpair(self,i,absSpectra=True):\n \"\"\"Retrieves eigenpair.\n\n Must be overloaded by any class inheriting this.\n\n :param int i: which eigenpair to return.\n :param bool absSpectra: (optional) for use if a shift is involved. If true then the eigenvalue is the absolute position in the spectra as opposed to the position relative to the shift\n \"\"\"\n pass\n\n\n#COMPLEX EIGENVALUE PROBLEM#\nclass ComplexEigensolver(Eigensolver):\n \"\"\"This is an eigensolver that takes the real representation of a complex eigenvalue and allows it to be solver using\n real PETSc. \n\n .. todo::\n\n With no shift then this struggles validating the eigenvalues, it should always be run with a shift\n\n Because all the matrices are real, it morphs an NxN problem into a 2Nx2N problem. See :ref:`complex-eigensolver-label` for\n details.\n\n :param dolfin.PETScMatrix AReal: The real part of the A operator\n :param dolfin.PETScMatrix AImag: The imaginary part of the A operator\n :param dolfin.PETScMatrix B: (optional) the B operator of a generalised eigenvalue problem\n :param str mode: (optional) whether to use direct mode (right eigenvectors, default) or adjoint mode (left eigenvectors)\n \"\"\"\n def __init__(self, AReal, AImag, B=None, mode = None):\n super().__init__()\n\n #TODO: implement dealing with no B matrix\n if B == None:\n raise EigenError('Not yet implemented ComplexEigensolver without B specified')\n\n self.AReal = AReal\n self.AImag = AImag\n self.B = B \n\n self.shift = 0.\n self.solved = False\n\n self.validatedEigenpairs = []\n self.storedEigenpairs = []\n\n if mode is None:\n self.mode = 'direct'\n else:\n self.mode = mode\n\n\n def build(self):\n \"\"\"Builds the necessary matrices needed for SLEPc eigensolver.\"\"\"\n\n self.solved = False #we make sure we clear the solved flag\n self._validated = False\n self.validatedEigenpairs = []\n self.storedEigenpairs = []\n\n A00 = self.AReal.mat().copy()\n\n if self.AImag != 0:\n A10 = self.AImag.mat().copy()\n\n B00 = self.B.mat().copy()\n \n dimBlock = A00.getSize()\n\n #The case of zero real part of the shift causes problems and a real eigenvalue problem, leads to the case where ghosts can't be differentiated\n if self.shift.imag == 0 and self.AImag == 0:\n #We have a special case where we have a purely real system. The splitting into 2Nx2N makes no sense and so we\n #produce a reduced system\n A00.axpy(-self.shift.real, B00)\n self.AA = A00\n self.BB = B00\n\n\n else:\n #We have to produce a split system\n\n #We check all the matrices we've been given are compatible\n if dimBlock != B00.getSize():\n raise EigenError('Matrices A and B must agree in dimension')\n if self.AImag != 0 and dimBlock != A10.getSize():\n raise EigenError('Real part and complex part of A must agree')\n\n dummy = PETSc.Mat() #dummy matrix for building the block system\n\n comm = A00.getComm() #We use the same mpi communicator that dolfin was using\n \n #We construct the augmented A matrix\n A11 = A00.copy() #get base copy for A11\n A00.axpy(-self.shift.real,B00)\n A11.axpy(-self.shift.real,B00)\n\n if self.AImag == 0:\n A01 = B00.copy()\n A01.scale(self.shift.imag)\n\n A10 = B00.copy()\n A10.scale(-self.shift.imag)\n\n else:\n A01 = B00.copy()\n A01.scale(self.shift.imag)\n A01.axpy(-1., A10)\n\n A10.axpy(-self.shift.imag, B00)\n\n #We construct the augmented B matrix\n BB = PETSc.Mat().createNest([[B00 ,dummy],\n [dummy, B00]] ,comm=comm)\n\n AA = PETSc.Mat().createNest([[A00, A01],\n [A10, A11]],comm=comm)\n\n #We now convert the matrices to SEQ AIJ form\n AA.convert(mat_type=PETSc.Mat.Type.AIJ,out = AA)\n BB.convert(mat_type=PETSc.Mat.Type.AIJ,out = BB)\n\n self.AA = AA\n self.BB = BB\n\n self.indicesReal = PETSc.IS().createBlock(dimBlock[0],0)\n self.indicesImag = PETSc.IS().createBlock(dimBlock[0],1)\n\n #store dimensions\n self.dimBlock = dimBlock\n self.dim = self.AA.getSize()\n\n #We generate the eps obejct\n if self.mode == 'adjoint':\n self.AA.transpose(out=self.AA)\n self.BB.transpose(out=self.BB)\n self._buildEPS(self.AA,self.BB)\n\n self.built=True\n\n def applyShift(self,shift):\n \"\"\"Applies a complex shift.\n\n This clears the built flag and so the matrices will be rebuilt for the next solve.\n\n :param complex shift: complex shift to apply\n \"\"\"\n self.shift = shift\n self.built = False\n\n def _reconstructEigenvector(self,rx,cx):\n \"\"\"Reconstructs the original real and imaginary parts of the eigenvector.\n\n Reconstruction is required because the spltting into 2Nx2N redistributes the eigenvector\n into real and imaginary parts.\n\n :param PETSC.Vec rx: PETSc vector representing the real part of the eigenvector\n :param PETSC.Vec cx: PETSc vector representing the complex part of the eigenvector\n :return: tuple of PETSC.Vec of the reconstructed real and imaginary parts of the eigenvector\n \"\"\"\n #We generate the index sets for the block which represents the real component and the block which represents the complex component\n \n if self.shift.imag != 0:\n\n r0 = PETSc.Vec().createSeq(self.dimBlock[0]); rx.getSubVector(self.indicesReal, subvec=r0)\n r1 = PETSc.Vec().createSeq(self.dimBlock[0]); rx.getSubVector(self.indicesImag, subvec=r1)\n c0 = PETSc.Vec().createSeq(self.dimBlock[0]); cx.getSubVector(self.indicesReal, subvec=c0)\n c1 = PETSc.Vec().createSeq(self.dimBlock[0]); cx.getSubVector(self.indicesImag, subvec=c1)\n\n r0.axpy(-1.,c1)\n r1.axpy( 1.,c0)\n\n return r0, r1\n else:\n return rx,cx\n\n def validateEigenpairs(self, store=False, sTol = 1e-3, rTol = 1e3):\n \"\"\"Validates the converged eigenpairs.\n\n This is done to eliminate the additional 'ghost' solutions that arise from the 2Nx2N real representation of a\n complex matrix. The way this works is that we know the ghost solutions appear as eigenvalues that are exactly mirrored\n about the sinvert point\n\n :param bool store: (optional) whether to store the validated eigenpairs for future use\n :param float sTol: (optional) spectral tolerance for checking mirrored eigenvalues. Default is 1e-3\n :param flaot rTol: (optional) relative tolerance for checking which mode is the ghost and which is the real eigenvector. Default is 1e3. \n\n :return: list of validated eigenpairs\n :rtype: bool\n\n \"\"\"\n if not self.solved:\n raise EigenError('Must call solve() before validating eigenpairs')\n\n #we clear the \n\n\n #We identify the pairs\n evList = []\n procEvs = []\n evGroups = []\n validPairs = []\n\n nEv = self.eps.getConverged()\n\n rx = PETSc.Vec().createSeq(self.dim[0])\n cx = PETSc.Vec().createSeq(self.dim[0])\n\n counter = 0\n\n if self.shift.imag == 0:\n\n self.validatedEigenpairs = [i for i in range(nEv)]\n self.storedEigenpairs = [[self.eps.getEigenvalue(i)] for i in range(nEv)]\n\n if store:\n for i in range(nEv):\n self.eps.getEigenpair(i, rx, cx)\n self.storedEigenpairs[i].extend([rx.copy(), cx.copy()])\n\n else:\n #The imaginary shift means we get possible ghost solutions\n #We get all the eigenvalues\n for i in range(nEv):\n evList.append([self.eps.getEigenvalue(i), i])\n\n #We organise them into potential ghost/no ghost pairs\n for i in range(nEv):\n #We locate groups\n if i in procEvs: continue\n\n evI = evList[i][0]\n\n newGroup = []\n\n newGroup.append(evList[i])\n procEvs.append(i)\n\n for j in range(i+1, nEv):\n #in the relative spectrum frame these ghost pairs should be complex conjugates of each other\n if j in procEvs: continue\n\n evJ = evList[j][0]\n\n if np.abs(evI.real - evJ.real) < sTol and np.abs(evI.imag + evJ.imag) < sTol:\n #this is a candidate for being part of a ghost/no ghost pair\n newGroup.append(evList[j])\n procEvs.append(j)\n\n evGroups.append(newGroup)\n\n\n for evGroup in evGroups:\n #We process the groups looking for which of the pair has the largest norm\n \n\n if len(evGroup) > 2:\n continue\n #raise Exception('Cannot handle ev groups of more than 2 members')\n elif len(evGroup) == 1:\n\n pair = [evGroup[0][0]]\n\n if store:\n\n #self.eps.getEigenpair(evGroup[0][1], rx, cx)\n norm, real, imag = self._eigenpairNorm(evGroup[0][1])\n pair.extend([real, imag])\n\n self.validatedEigenpairs.append(evGroup[0][1])\n self.storedEigenpairs.append(pair)\n\n \n else:\n #We have a two group. We need to check the relative magnitudes\n norm0, rx0, cx0 = self._eigenpairNorm(evGroup[0][1])\n norm1, rx1, cx1 = self._eigenpairNorm(evGroup[1][1])\n\n\n if norm0 > norm1:\n index = evGroup[0][1]\n ev = evGroup[0][0]\n rx = rx0\n cx = cx0\n\n else:\n index = evGroup[1][1]\n ev = evGroup[1][0]\n rx = rx1\n cx = cx1\n\n self.validatedEigenpairs.append(index)\n\n if store:\n self.storedEigenpairs.append([ev, rx, cx])\n else:\n self.storedEigenpairs.append([ev])\n\n def _eigenpairNorm(self,i):\n \"\"\"Reconstructs an eigenpair and checks what the l2 norm is. This is used when testing for ghost solutions.\n\n :param int i: which eigenpair to validate\n :return: the calculated l2 norm\n :rtype: float and the combined test vector\n \"\"\"\n\n \n rx = PETSc.Vec().createSeq(self.dim[0])\n cx = PETSc.Vec().createSeq(self.dim[0])\n\n ev = self.eps.getEigenpair(i,rx,cx)\n\n real,imag = self._reconstructEigenvector(rx,cx)\n\n storeReal = real.copy() #We have to keep a backup - using restoreVector seems to free() the memory pointed to by these vectors\n storeImag = imag.copy()\n\n #We create the vector used to check whether the solution is a ghost or not\n testVec = PETSc.Vec().createSeq(self.dim[0])\n testVec.restoreSubVector(self.indicesReal,real)\n testVec.restoreSubVector(self.indicesImag,imag)\n\n #testVec.setType(PETSc.Vec.Type.SEQ) #change its type back to a normal seq\n resVec = testVec.duplicate() #allocate the emmory for the test vector\n\n self.AA.mult(testVec,resVec)\n\n norm = resVec.norm(PETSc.NormType.N2)\n\n\n return norm, storeReal, storeImag\n\n\n def solve(self,nEigen, store=True, maxSolveTime = 240):\n super().solve(nEigen, maxSolveTime)\n #We validate\n self.validateEigenpairs(store=store)\n\n return len(self.validatedEigenpairs)\n\n\n def getEigenpair(self,i,absSpectra=True):\n \"\"\"Gets the i-th eigenpair.\n\n :param int i: index of the eigenpair to resturn\n :param bool absSpectra: (optional) whether to return the absolute spectra or spectra relative to shift\n \"\"\"\n\n [ev, real, imag] = self.storedEigenpairs[i]\n\n if absSpectra:\n\n if self.mode == 'direct':\n ev += self.shift\n else:\n ev += self.shift.conjugate()\n\n return ev, dolf.PETScVector(real), dolf.PETScVector(imag)\n\nclass RealEigensolver(ComplexEigensolver):\n \"\"\"This is an eigensolver that takes a real eigenvalue problem and enables a complex shift to be applied. This is implemented\n by extending the ComplexEigensolver and setting the imaginary part to zero.\n\n Because all the matrices are real, it morphs an NxN problem into a 2Nx2N problem. See :ref:`real-eigensolver-label` for\n details.\n\n :param dolfin.PETScMatrix A: The A operator\n :param dolfin.PETScMatrix B: (optional) The B operator of a generalised eigenvalue problem.\n :param str mode: (optional) whether to use direct mode (right eigenvectors) or adjoint mode (left eigenvectors)\n \"\"\"\n\n def __init__(self,A,B=None,mode=None):\n super().__init__(AReal = A, AImag = 0, B = B, mode = mode)\n"
] |
[
[
"numpy.abs"
]
] |
ctittel/worldengine
|
[
"a91ae436f6298be6a0bf7b68c43415f10b6e751f"
] |
[
"worldengine/drawing_functions.py"
] |
[
"\"\"\"\nThis file should contain only functions that operates on pixels, not on images,\nso no references to PIL are necessary and the module can be used also through\nJython\n\"\"\"\n\nimport numpy\nimport sys\nimport time\nfrom worldengine.common import get_verbose, count_neighbours\nfrom worldengine.common import anti_alias as anti_alias_channel\nfrom worldengine.biome import BiomeGroup, _un_camelize\n\n\n# -------------------\n# Reusable functions\n# -------------------\n\n\ndef gradient(value, low, high, low_color, high_color):\n lr, lg, lb = low_color\n if high == low:\n return lr, lg, lb, 255\n _range = float(high - low)\n _x = float(value - low) / _range\n _ix = 1.0 - _x\n hr, hg, hb = high_color\n r = int(lr * _ix + hr * _x)\n g = int(lg * _ix + hg * _x)\n b = int(lb * _ix + hb * _x)\n return r, g, b, 255\n\n\ndef rgba_to_rgb(rgba):\n r, g, b, a = rgba\n return r, g, b\n\n\ndef draw_rivers_on_image(world, target, factor=1):\n \"\"\"Draw only the rivers, it expect the background to be in place\n \"\"\"\n\n for y in range(world.height):\n for x in range(world.width):\n if world.is_land((x, y)) and (world.layers['river_map'].data[y, x] > 0.0):\n for dx in range(factor):\n for dy in range(factor):\n target.set_pixel(x * factor + dx, y * factor + dy, (0, 0, 128, 255))\n if world.is_land((x, y)) and (world.layers['lake_map'].data[y, x] != 0):\n for dx in range(factor):\n for dy in range(factor):\n target.set_pixel(x * factor + dx, y * factor + dy, (0, 100, 128, 255))\n\n\n# -------------------\n# Drawing ancient map\n# -------------------\n\ndef _find_mountains_mask(world, factor):\n _mask = numpy.zeros((world.height, world.width), float)\n _mask[world.elevation>world.get_mountain_level()] = 1.0\n\n # disregard elevated oceans\n _mask[world.ocean] = 0.0\n\n # this is fast but not 100% precise\n # subsequent steps are fiendishly sensitive to these precision errors\n # therefore the rounding\n _mask[_mask>0] = numpy.around(count_neighbours(_mask, 3)[_mask>0], 6)\n\n _mask[_mask<32.000000001] = 0.0\n _mask /= 4.0\n _mask = _mask.repeat(factor, 0).repeat(factor, 1)\n\n return _mask\n\n\ndef _build_biome_group_masks(world, factor):\n\n biome_groups = BiomeGroup.__subclasses__()\n\n biome_masks = {}\n\n for group in biome_groups:\n group_mask = numpy.zeros((world.height, world.width), float)\n\n for biome in group.__subclasses__():\n group_mask[world.biome==_un_camelize(biome.__name__)] += 1.0\n \n group_mask[group_mask>0] = count_neighbours(group_mask)[group_mask>0]\n\n group_mask[group_mask<5.000000001] = 0.0\n\n group_mask = group_mask.repeat(factor, 0).repeat(factor, 1)\n\n biome_masks[_un_camelize(group.__name__)] = group_mask\n\n return biome_masks\n\ndef _draw_shaded_pixel(pixels, x, y, r, g, b):\n nb = (x ** int(y / 5) + x * 23 + y * 37 + (x * y) * 13) % 75\n nr = r - nb\n ng = g - nb\n nb = b - nb\n pixels[y, x] = (nr, ng, nb, 255)\n\n\ndef _draw_forest_pattern1(pixels, x, y, c, c2):\n pixels[y - 4, x + 0] = c\n pixels[y - 3, x + 0] = c\n pixels[y - 2, x - 1] = c\n pixels[y - 2, x + 1] = c\n pixels[y - 1, x - 1] = c\n pixels[y - 1, x + 1] = c\n pixels[y + 0, x - 2] = c\n pixels[y + 0, x + 1] = c\n pixels[y + 0, x + 2] = c\n pixels[y + 1, x - 2] = c\n pixels[y + 1, x + 2] = c\n pixels[y + 2, x - 3] = c\n pixels[y + 2, x - 1] = c\n pixels[y + 2, x + 3] = c\n pixels[y + 3, x - 3] = c\n pixels[y + 3, x - 2] = c\n pixels[y + 3, x - 1] = c\n pixels[y + 3, x - 0] = c\n pixels[y + 3, x + 1] = c\n pixels[y + 3, x + 2] = c\n pixels[y + 3, x + 3] = c\n pixels[y + 4, x - 0] = c\n\n pixels[y - 2, x + 0] = c2\n pixels[y - 1, x + 0] = c2\n pixels[y - 0, x - 1] = c2\n pixels[y - 0, x - 0] = c2\n pixels[y + 1, x - 1] = c2\n pixels[y + 1, x - 0] = c2\n pixels[y + 1, x + 1] = c2\n pixels[y + 2, x - 2] = c2\n pixels[y + 2, x - 0] = c2\n pixels[y + 2, x + 1] = c2\n pixels[y + 2, x + 2] = c2\n\n\ndef _draw_forest_pattern2(pixels, x, y, c, c2):\n pixels[y - 4, x - 1] = c\n pixels[y - 4, x - 0] = c\n pixels[y - 4, x + 1] = c\n pixels[y - 3, x - 2] = c\n pixels[y - 3, x - 1] = c\n pixels[y - 3, x + 2] = c\n pixels[y - 2, x - 2] = c\n pixels[y - 2, x + 1] = c\n pixels[y - 2, x + 2] = c\n pixels[y - 1, x - 2] = c\n pixels[y - 1, x + 2] = c\n pixels[y - 0, x - 2] = c\n pixels[y - 0, x - 1] = c\n pixels[y - 0, x + 2] = c\n pixels[y + 1, x - 2] = c\n pixels[y + 1, x + 1] = c\n pixels[y + 1, x + 2] = c\n pixels[y + 2, x - 1] = c\n pixels[y + 2, x - 0] = c\n pixels[y + 2, x + 1] = c\n pixels[y + 3, x - 0] = c\n pixels[y + 4, x - 0] = c\n\n pixels[y - 3, x + 0] = c2\n pixels[y - 3, x + 1] = c2\n pixels[y - 2, x - 1] = c2\n pixels[y - 2, x - 0] = c2\n pixels[y - 1, x - 1] = c2\n pixels[y - 1, x - 0] = c2\n pixels[y - 1, x + 1] = c2\n pixels[y - 0, x - 0] = c2\n pixels[y - 0, x + 1] = c2\n pixels[y + 1, x - 1] = c2\n pixels[y + 1, x - 0] = c2\n\n\ndef _draw_desert_pattern(pixels, x, y, c):\n pixels[y - 2, x - 1] = c\n pixels[y - 2, x - 0] = c\n pixels[y - 2, x + 1] = c\n pixels[y - 2, x + 1] = c\n pixels[y - 2, x + 2] = c\n pixels[y - 1, x - 2] = c\n pixels[y - 1, x - 1] = c\n pixels[y - 1, x - 0] = c\n pixels[y - 1, x + 4] = c\n pixels[y - 0, x - 4] = c\n pixels[y - 0, x - 3] = c\n pixels[y - 0, x - 2] = c\n pixels[y - 0, x - 1] = c\n pixels[y - 0, x + 1] = c\n pixels[y - 0, x + 2] = c\n pixels[y - 0, x + 6] = c\n pixels[y + 1, x - 5] = c\n pixels[y + 1, x - 0] = c\n pixels[y + 1, x + 7] = c\n pixels[y + 1, x + 8] = c\n pixels[y + 2, x - 8] = c\n pixels[y + 2, x - 7] = c\n\n\ndef _draw_glacier(pixels, x, y):\n rg = 255 - (x ** int(y / 5) + x * 23 + y * 37 + (x * y) * 13) % 75\n pixels[y, x] = (rg, rg, 255, 255)\n\n\ndef _draw_cold_parklands(pixels, x, y, w, h):\n b = (x ** int(y / 5) + x * 23 + y * 37 + (x * y) * 13) % 75\n r = 105 - b\n g = 96 - b\n b = 38 - int(b / 2)\n pixels[y, x] = (r, g, b, 255)\n\n\ndef _draw_boreal_forest(pixels, x, y, w, h):\n c = (0, 32, 0, 255)\n c2 = (0, 64, 0, 255)\n _draw_forest_pattern1(pixels, x, y, c, c2)\n\n\ndef _draw_warm_temperate_forest(pixels, x, y, w, h):\n c = (0, 96, 0, 255)\n c2 = (0, 192, 0, 255)\n _draw_forest_pattern2(pixels, x, y, c, c2)\n \n\ndef _draw_temperate_forest1(pixels, x, y, w, h):\n c = (0, 64, 0, 255)\n c2 = (0, 96, 0, 255)\n _draw_forest_pattern1(pixels, x, y, c, c2)\n\n\ndef _draw_temperate_forest2(pixels, x, y, w, h):\n c = (0, 64, 0, 255)\n c2 = (0, 112, 0, 255)\n _draw_forest_pattern2(pixels, x, y, c, c2)\n\n\ndef _draw_tropical_dry_forest(pixels, x, y, w, h):\n c = (51, 36, 3, 255)\n c2 = (139, 204, 58, 255)\n _draw_forest_pattern2(pixels, x, y, c, c2)\n\n\ndef _draw_jungle(pixels, x, y, w, h):\n c = (0, 128, 0, 255)\n c2 = (0, 255, 0, 255)\n _draw_forest_pattern2(pixels, x, y, c, c2)\n\n\ndef _draw_cool_desert(pixels, x, y, w, h):\n c = (72, 72, 53, 255)\n # c2 = (219, 220, 200, 255) # TODO: not used?\n _draw_desert_pattern(pixels, x, y, c)\n \n \ndef _draw_hot_desert(pixels, x, y, w, h):\n c = (72, 72, 53, 255)\n # c2 = (219, 220, 200, 255) # TODO: not used?\n _draw_desert_pattern(pixels, x, y, c) \n\n\ndef _draw_tundra(pixels, x, y, w, h):\n _draw_shaded_pixel(pixels,x, y, 166, 148, 75)\n\n\ndef _draw_steppe(pixels, x, y, w, h):\n _draw_shaded_pixel(pixels, x, y, 96, 192, 96)\n\n\ndef _draw_chaparral(pixels, x, y, w, h):\n _draw_shaded_pixel(pixels, x, y, 180, 171, 113)\n\n\ndef _draw_savanna(pixels, x, y, w, h):\n _draw_shaded_pixel(pixels, x, y, 255, 246, 188)\n\n\n# TODO: complete and enable this one\ndef _dynamic_draw_a_mountain(pixels, rng, x, y, w=3, h=3):\n # mcl = (0, 0, 0, 255) # TODO: No longer used?\n # mcll = (128, 128, 128, 255)\n mcr = (75, 75, 75, 255)\n # left edge\n last_leftborder = None\n for mody in range(-h, h + 1):\n bottomness = (float(mody + h) / 2.0) / w\n\n min_leftborder = int(bottomness * w * 0.66)\n if not last_leftborder == None:\n min_leftborder = max(min_leftborder, last_leftborder - 1)\n max_leftborder = int(bottomness * w * 1.33)\n if not last_leftborder == None:\n max_leftborder = min(max_leftborder, last_leftborder + 1)\n leftborder = int(bottomness * w) + rng.randint(-2, 2)/2\n if leftborder < min_leftborder:\n leftborder = min_leftborder\n if leftborder > max_leftborder:\n leftborder = max_leftborder\n last_leftborder = leftborder\n\n darkarea = int(bottomness * w / 2)\n lightarea = int(bottomness * w / 2)\n for itx in range(darkarea, leftborder + 1):\n pixels[y + mody, x - itx] = gradient(itx, darkarea, leftborder,\n (0, 0, 0), (64, 64, 64))\n for itx in range(-darkarea, lightarea + 1):\n pixels[y + mody, x - itx] = gradient(itx, -darkarea, lightarea,\n (64, 64, 64), (128, 128, 128))\n for itx in range(lightarea, leftborder):\n pixels[y + mody, x - itx] = (181, 166, 127, 255) # land_color\n # right edge\n last_modx = None\n for mody in range(-h, h + 1):\n bottomness = (float(mody + h) / 2.0) / w\n min_modx = int(bottomness * w * 0.66)\n if not last_modx == None:\n min_modx = max(min_modx, last_modx - 1)\n max_modx = int(bottomness * w * 1.33)\n if not last_modx == None:\n max_modx = min(max_modx, last_modx + 1)\n modx = int(bottomness * w) + numpy.random.randint(-2, 2)/2\n if modx < min_modx:\n modx = min_modx\n if modx > max_modx:\n modx = max_modx\n last_modx = modx\n pixels[y + mody, x - itx] = mcr\n\n\ndef _draw_a_mountain(pixels, x, y, w=3, h=3):\n # mcl = (0, 0, 0, 255) # TODO: No longer used?\n # mcll = (128, 128, 128, 255)\n mcr = (75, 75, 75, 255)\n # left edge\n for mody in range(-h, h + 1):\n bottomness = (float(mody + h) / 2.0) / w\n leftborder = int(bottomness * w)\n darkarea = int(bottomness * w / 2)\n lightarea = int(bottomness * w / 2)\n for itx in range(darkarea, leftborder + 1):\n pixels[y + mody, x - itx] = gradient(itx, darkarea, leftborder,\n (0, 0, 0), (64, 64, 64))\n for itx in range(-darkarea, lightarea + 1):\n pixels[y + mody, x + itx] = gradient(itx, -darkarea, lightarea,\n (64, 64, 64), (128, 128, 128))\n for itx in range(lightarea, leftborder):\n pixels[y + mody, x + itx] = (181, 166, 127, 255) # land_color\n # right edge\n for mody in range(-h, h + 1):\n bottomness = (float(mody + h) / 2.0) / w\n modx = int(bottomness * w)\n pixels[y + mody, x + modx] = mcr \n\n\ndef draw_ancientmap(world, target, resize_factor=1,\n sea_color=(212, 198, 169, 255),\n draw_biome = True, draw_rivers = True, draw_mountains = True,\n draw_outer_land_border = False, verbose=get_verbose()):\n rng = numpy.random.RandomState(world.seed) # create our own random generator\n\n if verbose:\n start_time = time.time()\n\n land_color = (\n 181, 166, 127, 255) # TODO: Put this in the argument list too??\n\n scaled_ocean = world.ocean.repeat(resize_factor, 0).repeat(resize_factor, 1)\n \n borders = numpy.zeros((resize_factor * world.height, resize_factor * world.width), bool)\n borders[count_neighbours(scaled_ocean) > 0] = True\n borders[scaled_ocean] = False\n\n # cache neighbours count at different radii\n border_neighbours = {}\n\n border_neighbours[6] = numpy.rint(count_neighbours(borders, 6))\n border_neighbours[9] = numpy.rint(count_neighbours(borders, 9))\n\n if draw_outer_land_border:\n inner_borders = borders\n outer_borders = None\n\n for i in range(2):\n _outer_borders = numpy.zeros((resize_factor * world.height, resize_factor * world.width), bool)\n _outer_borders[count_neighbours(inner_borders) > 0] = True\n _outer_borders[inner_borders] = False\n _outer_borders[numpy.logical_not(scaled_ocean)] = False\n outer_borders = _outer_borders\n inner_borders = outer_borders\n\n if draw_mountains:\n mountains_mask = _find_mountains_mask(world, resize_factor)\n\n if draw_biome:\n biome_masks = _build_biome_group_masks(world, resize_factor)\n\n def _draw_biome(name, _func, w, h, r, _alt_func = None):\n if verbose:\n start_time = time.time()\n\n for y in range(resize_factor * world.height):\n for x in range(resize_factor * world.width):\n if biome_masks[name][y, x] > 0:\n if r == 0 or border_neighbours[r][y,x] <= 2:\n if _alt_func is not None and rng.random_sample() > .5:\n _alt_func(target, x, y, w, h)\n else:\n _func(target, x, y, w, h)\n biome_masks[name][y-r:y+r+1,x-r:x+r+1] = 0.0\n\n if verbose:\n elapsed_time = time.time() - start_time\n print(\n \"...drawing_functions.draw_ancientmap: \" + name +\n \" Elapsed time \" + str(elapsed_time) + \" seconds.\")\n\n if verbose:\n elapsed_time = time.time() - start_time\n print(\n \"...drawing_functions.draw_oldmap_on_pixel: init Elapsed time \" +\n str(elapsed_time) + \" seconds.\")\n sys.stdout.flush()\n\n if verbose:\n start_time = time.time()\n\n border_color = (0, 0, 0, 255)\n outer_border_color = gradient(0.5, 0, 1.0, rgba_to_rgb(border_color), rgba_to_rgb(sea_color))\n\n # start in low resolution\n num_channels = 4\n channels = numpy.zeros((num_channels, world.height, world.width), int)\n\n for c in range(num_channels):\n channels[c] = land_color[c]\n channels[c][world.ocean] = sea_color[c]\n\n # now go full resolution\n channels = channels.repeat(resize_factor, 1).repeat(resize_factor, 2)\n\n if draw_outer_land_border:\n for c in range(num_channels):\n channels[c][outer_borders] = outer_border_color[c]\n\n for c in range(num_channels):\n channels[c][borders] = border_color[c]\n\n if verbose:\n elapsed_time = time.time() - start_time\n print(\n \"...drawing_functions.draw_oldmap_on_pixel: color ocean \" +\n \"Elapsed time \" + str(elapsed_time) + \" seconds.\")\n\n if verbose:\n start_time = time.time()\n\n # don't anti-alias the alpha channel\n for c in range(num_channels-1):\n channels[c] = anti_alias_channel(channels[c], 1)\n\n \n # switch from channel major storage to pixel major storage\n for c in range(num_channels):\n target[:,:,c] = channels[c,:,:]\n\n\n if verbose:\n elapsed_time = time.time() - start_time\n print(\n \"...drawing_functions.draw_oldmap_on_pixel: anti alias \" +\n \"Elapsed time \" + str(elapsed_time) + \" seconds.\")\n\n if draw_biome:\n # Draw glacier\n if verbose:\n start_time = time.time()\n for y in range(resize_factor * world.height):\n for x in range(resize_factor * world.width):\n if not borders[y, x] and world.is_iceland(\n (int(x / resize_factor), int(y / resize_factor))):\n _draw_glacier(target, x, y)\n if verbose:\n elapsed_time = time.time() - start_time\n print(\n \"...drawing_functions.draw_oldmap_on_pixel: draw glacier \" +\n \"Elapsed time \" + str(elapsed_time) + \" seconds.\")\n \n _draw_biome('tundra', _draw_tundra, 0, 0, 0) \n _draw_biome('cold parklands', _draw_cold_parklands, 0, 0, 0) \n _draw_biome('steppe', _draw_steppe, 0, 0, 0) \n _draw_biome('chaparral', _draw_chaparral, 0, 0, 0) \n _draw_biome('savanna', _draw_savanna, 0, 0, 0) \n _draw_biome('cool desert', _draw_cool_desert, 8, 2, 9)\n _draw_biome('hot desert', _draw_hot_desert, 8, 2, 9)\n _draw_biome('boreal forest', _draw_boreal_forest, 4, 5, 6)\n _draw_biome('cool temperate forest', _draw_temperate_forest1, 4, 5, 6,\n _draw_temperate_forest2) \n _draw_biome('warm temperate forest', _draw_warm_temperate_forest, 4, 5, 6) \n _draw_biome('tropical dry forest group', _draw_tropical_dry_forest, 4, 5, 6)\n _draw_biome('jungle', _draw_jungle, 4, 5, 6)\n\n # TODO: there was a stub for a rock desert biome group\n # it should be super easy to introduce that group with the new\n # biome group concept but since it did nothing I removed the stub\n\n if draw_rivers:\n draw_rivers_on_image(world, target, resize_factor)\n\n # Draw mountains\n if draw_mountains:\n if verbose:\n start_time = time.time()\n for y in range(resize_factor * world.height):\n for x in range(resize_factor * world.width):\n if mountains_mask[y, x] > 0:\n w = mountains_mask[y, x]\n h = 3 + int(world.level_of_mountain(\n (int(x / resize_factor), int(y / resize_factor))))\n r = max(int(w / 3 * 2), h)\n\n if r not in border_neighbours:\n border_neighbours[r] = numpy.rint(count_neighbours(borders, r))\n\n if border_neighbours[r][y,x] <= 2:\n _draw_a_mountain(target, x, y, w=w, h=h)\n mountains_mask[y-r:y+r+1,x-r:x+r+1] = 0.0\n if verbose:\n elapsed_time = time.time() - start_time\n print(\n \"...drawing_functions.draw_oldmap_on_pixel: draw mountains \" +\n \"Elapsed time \" + str(elapsed_time) + \" seconds.\")\n"
] |
[
[
"numpy.logical_not",
"numpy.random.RandomState",
"numpy.zeros",
"numpy.random.randint"
]
] |
williamdjones/deep_protein_binding
|
[
"10b00835024702b6d0e73092c777fed267215ca7"
] |
[
"src/model.py"
] |
[
"import time\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.metrics import r2_score, precision_score, recall_score, f1_score, accuracy_score\n\nimport dc_features as dc\nfrom rdkit import Chem\n\n\n# TODO: is it a good idea to have the validation, train, and step methods defined within the class? is this causing problems when using multiprocessing?\n\n\nclass MPNN(nn.Module):\n\n def __init__(self, target, T=3, p=0.5, n_atom_feats=70, n_bond_feats=146, readout_dim=128, name=\"mpnn\",\n output_type=\"regress\",\n output_dim=1):\n super(MPNN, self).__init__()\n self.T = T\n self.name = name\n self.output_type = output_type\n self.output_dim = output_dim\n self.readout_dim = readout_dim\n self.target = target # need to remove this\n self.n_atom_feats = n_atom_feats # make sure this is correct naming\n self.n_bond_feats = n_bond_feats # make sure this is correct naming\n self.R = nn.Linear(140, self.readout_dim)\n self.U = nn.ModuleList([nn.Linear(self.n_bond_feats, self.n_atom_feats)] * self.T)\n self.V = nn.ModuleList([nn.Linear(self.n_atom_feats, self.n_atom_feats)] * self.T)\n self.E = nn.Linear(6, 6)\n self.output_layer = nn.Linear(self.readout_dim, self.output_dim)\n self.dropout = nn.Dropout(p=p) # need to remove this\n\n def get_n_hidden_units(self):\n n_units = 0\n for child in self.children():\n for param in child.named_parameters():\n if 'weight' in param[0]:\n n_units += param[1].data.size()[0]\n # elif 'bias' in param[0]\n return n_units\n\n def readout(self, h, h2):\n hidden_output = self.output(h, h2)\n if self.output_type == \"regress\":\n return self.output_layer(hidden_output)\n elif self.output_type == \"class\":\n return nn.Softmax()(self.output_layer(hidden_output))\n\n def output(self, h, h2):\n catted_reads = map(lambda x: torch.cat([h[x[0]], h2[x[1]]], dim=1), zip(h2.keys(), h.keys()))\n return torch.sum(torch.cat(list(map(lambda x: nn.ReLU()(self.R(x)), catted_reads)), dim=0), dim=0)\n\n def message_pass(self, g, h, k):\n # for each node v in the molecular graph\n for v in g.keys():\n neighbors = g[v]\n # for each neighbor of v\n for neighbor in neighbors:\n e_vw = neighbor[0] # get the edge feature for nodes v & w\n w = neighbor[1] # get the atom index\n\n m_w = self.V[k](h[w]) # get atom w's feature vector, compute the linear transformation\n m_e_vw = self.E(e_vw) # compute the linear transformation of the edge v,w vector\n reshaped = torch.cat((h[v], m_w, m_e_vw),\n 1) # concat v's features with w's message and the edge feature between v and w, then reshape the vector to n by 1\n h[v] = nn.ReLU()(self.U[k](\n reshaped)) # pass the concat vector through a linear transformation, apply the nonlinearity, and get the new hidden state for v\n\n def forward(self, smiles, hidden_pass=False):\n\n mol = self.construct_multigraph(smiles)\n h = mol[\"h\"]\n g = mol[\"g\"]\n h2 = h\n\n for k in range(0, self.T):\n self.message_pass(h=h, g=g, k=k)\n\n if hidden_pass:\n return self.output(h=h, h2=h2)\n else:\n return self.readout(h=h, h2=h2)\n\n def construct_multigraph(self, smiles):\n g = {}\n h = {}\n molecule = Chem.MolFromSmiles(smiles)\n for i in range(0, molecule.GetNumAtoms()):\n atom_i = molecule.GetAtomWithIdx(i)\n\n # store atom i feature vector\n h[i] = Variable(\n torch.from_numpy(dc.atom_features(atom_i, explicit_H=True)).view(1, 70)).float()\n\n for j in range(0, molecule.GetNumAtoms()):\n e_ij = molecule.GetBondBetweenAtoms(i, j)\n if e_ij is not None:\n\n e_ij = map(lambda x: 1 if x == True else 0,\n dc.bond_features(e_ij))\n\n e_ij = Variable(torch.from_numpy(np.fromiter(e_ij, dtype=float))).view(1, 6).float()\n\n if i not in g:\n g[i] = []\n g[i].append((e_ij, j)) # tuple of bond bit vector and atom idx\n\n return {\"g\": g, \"h\": h}\n\n def train_step(self, batch, loss_fn):\n # make sure model is in train mode\n self.train()\n\n batch_dict = self.step(batch=batch, loss_fn=loss_fn)\n\n # update model gradients()\n batch_dict[\"loss\"].backward()\n\n return batch_dict\n\n def test_step(self, batch, loss_fn):\n # make sure model is evaluation mode\n self.eval()\n\n batch_dict = self.step(batch=batch, loss_fn=loss_fn)\n\n # put the model back into training mode\n self.train()\n\n return batch_dict\n\n def step(self, batch, loss_fn):\n\n batch_dict = {}\n\n if self.output_type == \"regress\":\n\n batch_dict = {key: {\"batch_size\": len(batch), \"pred\": [], \"true\": [], \"loss\": [], \"metrics\": {\"r2\": []}} for\n key in\n [self.target]}\n elif self.output_type == \"class\":\n batch_dict = {\n key: {\"batch_size\": len(batch), \"pred\": [], \"true\": [], \"loss\": [], \"metrics\": {\"acc\": [], \"prec\": [],\n \"rec\": [], \"f1\": []}}\n for\n key in [self.target]}\n\n start_clock = time.clock()\n\n for data in batch:\n # Forward pass: compute output of the network by passing x through the model.\n y_pred = self.forward(data[\"smiles\"])\n\n batch_dict[self.target][\"true\"].append(Variable(data[self.target]))\n batch_dict[self.target][\"pred\"].append(y_pred)\n\n if self.output_type == \"class\":\n y_true = Variable(torch.from_numpy(OneHotEncoder(n_values=self.output_dim, sparse=False).fit_transform(\n torch.stack(batch_dict[self.target][\"true\"]).data.numpy())))\n batch_dict[self.target][\"true\"] = y_true\n else:\n y_true = Variable(torch.from_numpy(torch.stack(batch_dict[self.target][\"true\"]).data.numpy()))\n batch_dict[self.target][\"true\"] = y_true\n y_pred = torch.stack(batch_dict[self.target][\"pred\"]).data.numpy()\n if self.output_type == \"regress\":\n batch_dict[self.target][\"metrics\"][\"r2\"] = r2_score(y_true=y_true.data.numpy(),\n y_pred=y_pred)\n elif self.output_type == \"class\":\n batch_dict[self.target][\"metrics\"][\"acc\"] = accuracy_score(y_true=np.argmax(y_true.data.numpy(), axis=1),\n y_pred=np.argmax(y_pred, axis=1))\n batch_dict[self.target][\"metrics\"][\"prec\"] = precision_score(y_true=np.argmax(y_true.data.numpy(), axis=1),\n y_pred=np.argmax(y_pred, axis=1))\n batch_dict[self.target][\"metrics\"][\"rec\"] = recall_score(y_true=np.argmax(y_true.data.numpy(), axis=1),\n y_pred=np.argmax(y_pred, axis=1))\n batch_dict[self.target][\"metrics\"][\"f1\"] = f1_score(y_true=np.argmax(y_true.data.numpy(), axis=1),\n y_pred=np.argmax(y_pred, axis=1))\n\n stop_clock = time.clock()\n\n loss = loss_fn(batch_dict)\n\n # return a dictionary objects containing the metrics\n return {\"loss\": loss, \"batch_dict\": batch_dict, \"time\": (stop_clock - start_clock)}\n"
] |
[
[
"torch.nn.Softmax",
"torch.nn.Dropout",
"numpy.fromiter",
"torch.cat",
"sklearn.preprocessing.OneHotEncoder",
"torch.nn.Linear",
"numpy.argmax",
"torch.stack",
"torch.nn.ReLU",
"torch.autograd.Variable"
]
] |
wegamekinglc/qlib
|
[
"1bab07e419c9a6bc42f4f7bdcf86b6c922a1718b",
"9459fda174079e1fd9cce1cfbfd8c9f215a3a482"
] |
[
"qlib/contrib/model/pytorch_lstm.py",
"qlib/contrib/report/analysis_model/analysis_model_performance.py"
] |
[
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport copy\nfrom sklearn.metrics import roc_auc_score, mean_squared_error\nimport logging\nfrom ...utils import (\n unpack_archive_with_buffer,\n save_multiple_parts_file,\n create_save_path,\n drop_nan_by_y_index,\n)\nfrom ...log import get_module_logger, TimeInspector\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom ...model.base import Model\nfrom ...data.dataset import DatasetH\nfrom ...data.dataset.handler import DataHandlerLP\n\n\nclass LSTM(Model):\n \"\"\"LSTM Model\n\n Parameters\n ----------\n d_feat : int\n input dimension for each time step\n metric: str\n the evaluate metric used in early stop\n optimizer : str\n optimizer name\n GPU : str\n the GPU ID(s) used for training\n \"\"\"\n\n def __init__(\n self,\n d_feat=6,\n hidden_size=64,\n num_layers=2,\n dropout=0.0,\n n_epochs=200,\n lr=0.001,\n metric=\"\",\n batch_size=2000,\n early_stop=20,\n loss=\"mse\",\n optimizer=\"adam\",\n GPU=\"0\",\n seed=None,\n **kwargs\n ):\n # Set logger.\n self.logger = get_module_logger(\"LSTM\")\n self.logger.info(\"LSTM pytorch version...\")\n\n # set hyper-parameters.\n self.d_feat = d_feat\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.dropout = dropout\n self.n_epochs = n_epochs\n self.lr = lr\n self.metric = metric\n self.batch_size = batch_size\n self.early_stop = early_stop\n self.optimizer = optimizer.lower()\n self.loss = loss\n self.device = torch.device(\"cuda:%d\" % (GPU) if torch.cuda.is_available() else \"cpu\")\n self.use_gpu = torch.cuda.is_available()\n self.seed = seed\n\n self.logger.info(\n \"LSTM parameters setting:\"\n \"\\nd_feat : {}\"\n \"\\nhidden_size : {}\"\n \"\\nnum_layers : {}\"\n \"\\ndropout : {}\"\n \"\\nn_epochs : {}\"\n \"\\nlr : {}\"\n \"\\nmetric : {}\"\n \"\\nbatch_size : {}\"\n \"\\nearly_stop : {}\"\n \"\\noptimizer : {}\"\n \"\\nloss_type : {}\"\n \"\\nvisible_GPU : {}\"\n \"\\nuse_GPU : {}\"\n \"\\nseed : {}\".format(\n d_feat,\n hidden_size,\n num_layers,\n dropout,\n n_epochs,\n lr,\n metric,\n batch_size,\n early_stop,\n optimizer.lower(),\n loss,\n GPU,\n self.use_gpu,\n seed,\n )\n )\n\n if self.seed is not None:\n np.random.seed(self.seed)\n torch.manual_seed(self.seed)\n\n self.lstm_model = LSTMModel(\n d_feat=self.d_feat,\n hidden_size=self.hidden_size,\n num_layers=self.num_layers,\n dropout=self.dropout,\n )\n if optimizer.lower() == \"adam\":\n self.train_optimizer = optim.Adam(self.lstm_model.parameters(), lr=self.lr)\n elif optimizer.lower() == \"gd\":\n self.train_optimizer = optim.SGD(self.lstm_model.parameters(), lr=self.lr)\n else:\n raise NotImplementedError(\"optimizer {} is not supported!\".format(optimizer))\n\n self._fitted = False\n self.lstm_model.to(self.device)\n\n def mse(self, pred, label):\n loss = (pred - label) ** 2\n return torch.mean(loss)\n\n def loss_fn(self, pred, label):\n mask = ~torch.isnan(label)\n\n if self.loss == \"mse\":\n return self.mse(pred[mask], label[mask])\n\n raise ValueError(\"unknown loss `%s`\" % self.loss)\n\n def metric_fn(self, pred, label):\n\n mask = torch.isfinite(label)\n\n if self.metric == \"\" or self.metric == \"loss\":\n return -self.loss_fn(pred[mask], label[mask])\n\n raise ValueError(\"unknown metric `%s`\" % self.metric)\n\n def train_epoch(self, x_train, y_train):\n\n x_train_values = x_train.values\n y_train_values = np.squeeze(y_train.values)\n\n self.lstm_model.train()\n\n indices = np.arange(len(x_train_values))\n np.random.shuffle(indices)\n\n for i in range(len(indices))[:: self.batch_size]:\n\n if len(indices) - i < self.batch_size:\n break\n\n feature = torch.from_numpy(x_train_values[indices[i : i + self.batch_size]]).float().to(self.device)\n label = torch.from_numpy(y_train_values[indices[i : i + self.batch_size]]).float().to(self.device)\n\n pred = self.lstm_model(feature)\n loss = self.loss_fn(pred, label)\n\n self.train_optimizer.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_value_(self.lstm_model.parameters(), 3.0)\n self.train_optimizer.step()\n\n def test_epoch(self, data_x, data_y):\n\n # prepare training data\n x_values = data_x.values\n y_values = np.squeeze(data_y.values)\n\n self.lstm_model.eval()\n\n scores = []\n losses = []\n\n indices = np.arange(len(x_values))\n\n for i in range(len(indices))[:: self.batch_size]:\n\n if len(indices) - i < self.batch_size:\n break\n\n feature = torch.from_numpy(x_values[indices[i : i + self.batch_size]]).float().to(self.device)\n label = torch.from_numpy(y_values[indices[i : i + self.batch_size]]).float().to(self.device)\n\n pred = self.lstm_model(feature)\n loss = self.loss_fn(pred, label)\n losses.append(loss.item())\n\n score = self.metric_fn(pred, label)\n scores.append(score.item())\n\n return np.mean(losses), np.mean(scores)\n\n def fit(\n self,\n dataset: DatasetH,\n evals_result=dict(),\n verbose=True,\n save_path=None,\n ):\n\n df_train, df_valid, df_test = dataset.prepare(\n [\"train\", \"valid\", \"test\"],\n col_set=[\"feature\", \"label\"],\n data_key=DataHandlerLP.DK_L,\n )\n\n x_train, y_train = df_train[\"feature\"], df_train[\"label\"]\n x_valid, y_valid = df_valid[\"feature\"], df_valid[\"label\"]\n\n if save_path == None:\n save_path = create_save_path(save_path)\n stop_steps = 0\n train_loss = 0\n best_score = -np.inf\n best_epoch = 0\n evals_result[\"train\"] = []\n evals_result[\"valid\"] = []\n\n # train\n self.logger.info(\"training...\")\n self._fitted = True\n\n for step in range(self.n_epochs):\n self.logger.info(\"Epoch%d:\", step)\n self.logger.info(\"training...\")\n self.train_epoch(x_train, y_train)\n self.logger.info(\"evaluating...\")\n train_loss, train_score = self.test_epoch(x_train, y_train)\n val_loss, val_score = self.test_epoch(x_valid, y_valid)\n self.logger.info(\"train %.6f, valid %.6f\" % (train_score, val_score))\n evals_result[\"train\"].append(train_score)\n evals_result[\"valid\"].append(val_score)\n\n if val_score > best_score:\n best_score = val_score\n stop_steps = 0\n best_epoch = step\n best_param = copy.deepcopy(self.lstm_model.state_dict())\n else:\n stop_steps += 1\n if stop_steps >= self.early_stop:\n self.logger.info(\"early stop\")\n break\n\n self.logger.info(\"best score: %.6lf @ %d\" % (best_score, best_epoch))\n self.lstm_model.load_state_dict(best_param)\n torch.save(best_param, save_path)\n\n if self.use_gpu:\n torch.cuda.empty_cache()\n\n def predict(self, dataset):\n if not self._fitted:\n raise ValueError(\"model is not fitted yet!\")\n\n x_test = dataset.prepare(\"test\", col_set=\"feature\")\n index = x_test.index\n self.lstm_model.eval()\n x_values = x_test.values\n sample_num = x_values.shape[0]\n preds = []\n\n for begin in range(sample_num)[:: self.batch_size]:\n\n if sample_num - begin < self.batch_size:\n end = sample_num\n else:\n end = begin + self.batch_size\n\n x_batch = torch.from_numpy(x_values[begin:end]).float().to(self.device)\n\n with torch.no_grad():\n if self.use_gpu:\n pred = self.lstm_model(x_batch).detach().cpu().numpy()\n else:\n pred = self.lstm_model(x_batch).detach().numpy()\n\n preds.append(pred)\n\n return pd.Series(np.concatenate(preds), index=index)\n\n\nclass LSTMModel(nn.Module):\n def __init__(self, d_feat=6, hidden_size=64, num_layers=2, dropout=0.0):\n super().__init__()\n\n self.rnn = nn.LSTM(\n input_size=d_feat,\n hidden_size=hidden_size,\n num_layers=num_layers,\n batch_first=True,\n dropout=dropout,\n )\n self.fc_out = nn.Linear(hidden_size, 1)\n\n self.d_feat = d_feat\n\n def forward(self, x):\n # x: [N, F*T]\n x = x.reshape(len(x), self.d_feat, -1) # [N, F, T]\n x = x.permute(0, 2, 1) # [N, T, F]\n out, _ = self.rnn(x)\n return self.fc_out(out[:, -1, :]).squeeze()\n",
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport pandas as pd\n\nimport plotly.tools as tls\nimport plotly.graph_objs as go\n\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\n\nfrom scipy import stats\n\nfrom ..graph import ScatterGraph, SubplotsGraph, BarGraph, HeatmapGraph\n\n\ndef _group_return(pred_label: pd.DataFrame = None, reverse: bool = False, N: int = 5, **kwargs) -> tuple:\n \"\"\"\n\n :param pred_label:\n :param reverse:\n :param N:\n :return:\n \"\"\"\n if reverse:\n pred_label[\"score\"] *= -1\n\n pred_label = pred_label.sort_values(\"score\", ascending=False)\n\n # Group1 ~ Group5 only consider the dropna values\n pred_label_drop = pred_label.dropna(subset=[\"score\"])\n\n # Group\n t_df = pd.DataFrame(\n {\n \"Group%d\"\n % (i + 1): pred_label_drop.groupby(level=\"datetime\")[\"label\"].apply(\n lambda x: x[len(x) // N * i : len(x) // N * (i + 1)].mean()\n )\n for i in range(N)\n }\n )\n t_df.index = pd.to_datetime(t_df.index)\n\n # Long-Short\n t_df[\"long-short\"] = t_df[\"Group1\"] - t_df[\"Group%d\" % N]\n\n # Long-Average\n t_df[\"long-average\"] = t_df[\"Group1\"] - pred_label.groupby(level=\"datetime\")[\"label\"].mean()\n\n t_df = t_df.dropna(how=\"all\") # for days which does not contain label\n # FIXME: support HIGH-FREQ\n t_df.index = t_df.index.strftime(\"%Y-%m-%d\")\n # Cumulative Return By Group\n group_scatter_figure = ScatterGraph(\n t_df.cumsum(),\n layout=dict(title=\"Cumulative Return\", xaxis=dict(type=\"category\", tickangle=45)),\n ).figure\n\n t_df = t_df.loc[:, [\"long-short\", \"long-average\"]]\n _bin_size = ((t_df.max() - t_df.min()) / 20).min()\n group_hist_figure = SubplotsGraph(\n t_df,\n kind_map=dict(kind=\"DistplotGraph\", kwargs=dict(bin_size=_bin_size)),\n subplots_kwargs=dict(\n rows=1,\n cols=2,\n print_grid=False,\n subplot_titles=[\"long-short\", \"long-average\"],\n ),\n ).figure\n\n return group_scatter_figure, group_hist_figure\n\n\ndef _plot_qq(data: pd.Series = None, dist=stats.norm) -> go.Figure:\n \"\"\"\n\n :param data:\n :param dist:\n :return:\n \"\"\"\n fig, ax = plt.subplots(figsize=(8, 5))\n _mpl_fig = sm.qqplot(data.dropna(), dist, fit=True, line=\"45\", ax=ax)\n return tls.mpl_to_plotly(_mpl_fig)\n\n\ndef _pred_ic(pred_label: pd.DataFrame = None, rank: bool = False, **kwargs) -> tuple:\n \"\"\"\n\n :param pred_label:\n :param rank:\n :return:\n \"\"\"\n if rank:\n ic = pred_label.groupby(level=\"datetime\").apply(\n lambda x: x[\"label\"].rank(pct=True).corr(x[\"score\"].rank(pct=True))\n )\n else:\n ic = pred_label.groupby(level=\"datetime\").apply(lambda x: x[\"label\"].corr(x[\"score\"]))\n\n _index = ic.index.get_level_values(0).astype(\"str\").str.replace(\"-\", \"\").str.slice(0, 6)\n _monthly_ic = ic.groupby(_index).mean()\n _monthly_ic.index = pd.MultiIndex.from_arrays(\n [_monthly_ic.index.str.slice(0, 4), _monthly_ic.index.str.slice(4, 6)],\n names=[\"year\", \"month\"],\n )\n\n # fill month\n _month_list = pd.date_range(\n start=pd.Timestamp(f\"{_index.min()[:4]}0101\"),\n end=pd.Timestamp(f\"{_index.max()[:4]}1231\"),\n freq=\"1M\",\n )\n _years = []\n _month = []\n for _date in _month_list:\n _date = _date.strftime(\"%Y%m%d\")\n _years.append(_date[:4])\n _month.append(_date[4:6])\n\n fill_index = pd.MultiIndex.from_arrays([_years, _month], names=[\"year\", \"month\"])\n\n _monthly_ic = _monthly_ic.reindex(fill_index)\n\n _ic_df = ic.to_frame(\"ic\")\n ic_bar_figure = ic_figure(_ic_df, kwargs.get(\"show_nature_day\", True))\n\n ic_heatmap_figure = HeatmapGraph(\n _monthly_ic.unstack(),\n layout=dict(title=\"Monthly IC\", yaxis=dict(tickformat=\",d\")),\n graph_kwargs=dict(xtype=\"array\", ytype=\"array\"),\n ).figure\n\n dist = stats.norm\n _qqplot_fig = _plot_qq(ic, dist)\n\n if isinstance(dist, stats.norm.__class__):\n dist_name = \"Normal\"\n else:\n dist_name = \"Unknown\"\n\n _bin_size = ((_ic_df.max() - _ic_df.min()) / 20).min()\n _sub_graph_data = [\n (\n \"ic\",\n dict(\n row=1,\n col=1,\n name=\"\",\n kind=\"DistplotGraph\",\n graph_kwargs=dict(bin_size=_bin_size),\n ),\n ),\n (_qqplot_fig, dict(row=1, col=2)),\n ]\n ic_hist_figure = SubplotsGraph(\n _ic_df.dropna(),\n kind_map=dict(kind=\"HistogramGraph\", kwargs=dict()),\n subplots_kwargs=dict(\n rows=1,\n cols=2,\n print_grid=False,\n subplot_titles=[\"IC\", \"IC %s Dist. Q-Q\" % dist_name],\n ),\n sub_graph_data=_sub_graph_data,\n layout=dict(\n yaxis2=dict(title=\"Observed Quantile\"),\n xaxis2=dict(title=f\"{dist_name} Distribution Quantile\"),\n ),\n ).figure\n\n return ic_bar_figure, ic_heatmap_figure, ic_hist_figure\n\n\ndef _pred_autocorr(pred_label: pd.DataFrame, lag=1, **kwargs) -> tuple:\n pred = pred_label.copy()\n pred[\"score_last\"] = pred.groupby(level=\"instrument\")[\"score\"].shift(lag)\n ac = pred.groupby(level=\"datetime\").apply(lambda x: x[\"score\"].rank(pct=True).corr(x[\"score_last\"].rank(pct=True)))\n # FIXME: support HIGH-FREQ\n _df = ac.to_frame(\"value\")\n _df.index = _df.index.strftime(\"%Y-%m-%d\")\n ac_figure = ScatterGraph(\n _df,\n layout=dict(title=\"Auto Correlation\", xaxis=dict(type=\"category\", tickangle=45)),\n ).figure\n return (ac_figure,)\n\n\ndef _pred_turnover(pred_label: pd.DataFrame, N=5, lag=1, **kwargs) -> tuple:\n pred = pred_label.copy()\n pred[\"score_last\"] = pred.groupby(level=\"instrument\")[\"score\"].shift(lag)\n top = pred.groupby(level=\"datetime\").apply(\n lambda x: 1\n - x.nlargest(len(x) // N, columns=\"score\").index.isin(x.nlargest(len(x) // N, columns=\"score_last\").index).sum()\n / (len(x) // N)\n )\n bottom = pred.groupby(level=\"datetime\").apply(\n lambda x: 1\n - x.nsmallest(len(x) // N, columns=\"score\")\n .index.isin(x.nsmallest(len(x) // N, columns=\"score_last\").index)\n .sum()\n / (len(x) // N)\n )\n r_df = pd.DataFrame(\n {\n \"Top\": top,\n \"Bottom\": bottom,\n }\n )\n # FIXME: support HIGH-FREQ\n r_df.index = r_df.index.strftime(\"%Y-%m-%d\")\n turnover_figure = ScatterGraph(\n r_df,\n layout=dict(title=\"Top-Bottom Turnover\", xaxis=dict(type=\"category\", tickangle=45)),\n ).figure\n return (turnover_figure,)\n\n\ndef ic_figure(ic_df: pd.DataFrame, show_nature_day=True, **kwargs) -> go.Figure:\n \"\"\"IC figure\n\n :param ic_df: ic DataFrame\n :param show_nature_day: whether to display the abscissa of non-trading day\n :return: plotly.graph_objs.Figure\n \"\"\"\n if show_nature_day:\n date_index = pd.date_range(ic_df.index.min(), ic_df.index.max())\n ic_df = ic_df.reindex(date_index)\n # FIXME: support HIGH-FREQ\n ic_df.index = ic_df.index.strftime(\"%Y-%m-%d\")\n ic_bar_figure = BarGraph(\n ic_df,\n layout=dict(\n title=\"Information Coefficient (IC)\",\n xaxis=dict(type=\"category\", tickangle=45),\n ),\n ).figure\n return ic_bar_figure\n\n\ndef model_performance_graph(\n pred_label: pd.DataFrame,\n lag: int = 1,\n N: int = 5,\n reverse=False,\n rank=False,\n graph_names: list = [\"group_return\", \"pred_ic\", \"pred_autocorr\"],\n show_notebook: bool = True,\n show_nature_day=True,\n) -> [list, tuple]:\n \"\"\"Model performance\n\n :param pred_label: index is **pd.MultiIndex**, index name is **[instrument, datetime]**; columns names is **[score,\n label]**. It is usually same as the label of model training(e.g. \"Ref($close, -2)/Ref($close, -1) - 1\").\n\n\n .. code-block:: python\n\n instrument datetime score label\n SH600004 2017-12-11 -0.013502 -0.013502\n 2017-12-12 -0.072367 -0.072367\n 2017-12-13 -0.068605 -0.068605\n 2017-12-14 0.012440 0.012440\n 2017-12-15 -0.102778 -0.102778\n\n\n :param lag: `pred.groupby(level='instrument')['score'].shift(lag)`. It will be only used in the auto-correlation computing.\n :param N: group number, default 5.\n :param reverse: if `True`, `pred['score'] *= -1`.\n :param rank: if **True**, calculate rank ic.\n :param graph_names: graph names; default ['cumulative_return', 'pred_ic', 'pred_autocorr', 'pred_turnover'].\n :param show_notebook: whether to display graphics in notebook, the default is `True`.\n :param show_nature_day: whether to display the abscissa of non-trading day.\n :return: if show_notebook is True, display in notebook; else return `plotly.graph_objs.Figure` list.\n \"\"\"\n figure_list = []\n for graph_name in graph_names:\n fun_res = eval(f\"_{graph_name}\")(\n pred_label=pred_label,\n lag=lag,\n N=N,\n reverse=reverse,\n rank=rank,\n show_nature_day=show_nature_day,\n )\n figure_list += fun_res\n\n if show_notebook:\n BarGraph.show_graph_in_notebook(figure_list)\n else:\n return figure_list\n"
] |
[
[
"torch.mean",
"numpy.random.seed",
"torch.nn.LSTM",
"torch.isnan",
"torch.manual_seed",
"numpy.squeeze",
"torch.cuda.empty_cache",
"numpy.random.shuffle",
"torch.from_numpy",
"numpy.concatenate",
"torch.nn.Linear",
"torch.isfinite",
"numpy.mean",
"torch.no_grad",
"torch.cuda.is_available",
"torch.save"
],
[
"pandas.to_datetime",
"matplotlib.pyplot.subplots",
"pandas.MultiIndex.from_arrays",
"pandas.DataFrame"
]
] |
yuyingyeh/isospectralization-pytorch
|
[
"48317133b8bb57e57a8ecd73b3bc93ba374d0d60"
] |
[
"code_for_3D/plot_eig.py"
] |
[
"\"\"\"Plot the eigenvalue sequences stored in a txt file.\"\"\"\nimport argparse\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Configure Matplotlib\nplt.rc(\"figure\", titleweight=\"bold\", dpi=100)\nplt.rc(\"font\", family=\"serif\")\nplt.rc(\"axes\", labelweight=\"bold\", linewidth=1.5, titleweight=\"bold\")\nplt.rc(\"xtick\", direction=\"in\")\nplt.rc(\"ytick\", direction=\"in\")\n\n\ndef parse_args():\n \"\"\"Return the parsed command line arguments.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"input\", help=\"Input file\")\n parser.add_argument(\"output\", help=\"Output file\")\n parser.add_argument(\"-k\", type=int, default=30, help=\"Number of eigenvalues\")\n parser.add_argument(\"--init\", help=\"Input file for initial sequence\")\n parser.add_argument(\"--target\", help=\"Input file for target sequence\")\n args = parser.parse_args()\n return args.input, args.output, args.k, args.init, args.target\n\ndef main():\n \"\"\"Main function.\"\"\"\n in_file, out_file, k, init_file, target_file = parse_args()\n\n in_eig = np.loadtxt(in_file)[:k]\n if init_file is not None:\n init_eig = np.loadtxt(init_file)[:k]\n if target_file is not None:\n target_eig = np.loadtxt(target_file)[:k]\n\n plt.figure(figsize=(3, 2))\n if init_file is not None:\n plt.plot(np.arange(k), init_eig, color='0.5', linewidth=2, label=\"Initial\")\n plt.plot(np.arange(k), in_eig, color='b', linewidth=4, label=\"Final\")\n if target_file is not None:\n plt.plot(np.arange(k), target_eig, color='r', linewidth=2, label=\"Target\")\n plt.xlim(0, len(in_eig))\n y_max = in_eig.max()\n if init_file is not None and init_eig.max() > y_max:\n y_max = init_eig.max()\n if target_file is not None and target_eig.max() > y_max:\n y_max = target_eig.max()\n plt.ylim(0, y_max)\n plt.xlabel(\"Eigenvalue index\")\n plt.ylabel(\"Eigenvalue\")\n plt.legend(loc=0, prop={\"size\": 8})\n plt.savefig(out_file, bbox_inches=\"tight\")\n plt.close()\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel"
]
] |
x94carbone/hdwell
|
[
"3f3726edd815f82df0a72f7e22cb681032f774d9"
] |
[
"hdwell2/simulator.py"
] |
[
"#!/usr/bin/env python3\n\n__author__ = \"Matthew R. Carbone & Marco Baity-Jesi\"\n__maintainer__ = \"Matthew R. Carbone\"\n__email__ = \"[email protected]\"\n__status__ = \"Prototype\"\n\n\"\"\"Core simulation.\"\"\"\n\nimport numpy as np\nimport sys\nfrom time import time\nfrom collections import Counter\nfrom math import floor\n\nimport hdwell2.auxiliary as aux\n\n\ndef simulate(nMC_lg, N, n_tracer, beta, delta, ptype, protocol,\n save_all_energies=False, n_report=1000, verbose=True,\n lambdaprime=1.0, dw=0.5, n_e_sample=1000, n_mem_sample=50):\n \"\"\"Executes a MC simulation over the unit N-ball. Uses Metropolis selection\n criteria.\n\n Parameters\n ----------\n nMC_lg : int\n Total number of monte carlo timesteps to perform is 10^nMC_lg.\n N : int\n Dimension of the system where the tracers evolve.\n n_tracer : int\n Total number of tracers in the ensemble.\n beta : float\n Inverse temperature 1/T.\n delta : float\n Scale parameter which controls the scaling of the radius during Markov-\n chain MC.\n ptype : str\n Determines the energy of the system (fixes the form of the potential\n energy).\n n_report : int\n Report progress (pipe to output) everytime the simulation reaches this\n many timesteps.\n protocol : int\n Defines the simulation type.\n * 0 => DSMC\n * 1 => MCMC\n save_all_energies : bool\n If true, will save the 10^nMC-dimensional vector containing the average\n energies at every timestep. Mainly used for debugging, since for any\n large number of timesteps this is guaranteed to kill your machine. For\n this reason, defaults to False.\n verbose : bool\n Whether or not to pipe current status at increments to console. Default\n is True.\n lambdaprime : float\n Scale parameter set as lambdaprime = lambda * N. Generally, the\n potential will be defined something like lambda^{-1}*ln r, and this\n lambdaprime is fixed such that the DOS of our system matches that of\n literature precedent. Ultimately, lambdaprime=1 is a good default and\n probably should not be changed. This scaling also guarantees an\n extensive energy with respect to the dimension.\n dw : float\n Traping dynamics parameter (see Cammarota 2018).\n n_e_sample : int\n Number of points where we sample the energy.\n n_mem_sample : int\n Number of points where we sample the memory functions Pi.\n\n Returns\n -------\n tau_sample_grid : list\n List of points where the timestep was sampled (logarithmic)\n eAVG, eSTD, rminAVG, rminSTD: list\n List of points representing the average (and standard deviation) of the\n energy and minimum radius.\n psiB, psiC : collections.Counter\n Counters for the psi basin and config where the key indexes the\n log2(n_points), where n_points is the number of timesteps that the\n tracer remained in some basin/configuration.\n pi_grid_sample_1 : array like\n Numpy array (1d) of the grid points where pi was sampled (tw, not\n tw + tw * dw).\n Pi_basin_final_output, Pi_config_final_output : array like\n Probabilities, properly normalized, corresponding to Pi\n basin/configuration.\n \"\"\"\n\n if protocol == 1 and delta is None:\n raise RuntimeError(\"Need to initialize delta with MCMC simulation.\")\n\n nMC = int(10**nMC_lg) # Define the total number of MC time steps\n\n if verbose:\n print(\"NMC: %i\" % nMC)\n\n # With lambda' = lambda * N, we constrain lambda and choose N such that\n # lambda' is fixed to be the critical beta which further constrains\n # (for log potential) E = ln r / lambda. Usually we choose lambda_prime\n # to be 1.\n lambda_ = lambdaprime / N\n\n if verbose:\n print(\"LAMBDA: %.02f\" % lambda_)\n\n # Used when saving files (determines the number of padding 0's when saving\n # a text file to disk, for example).\n zfill_index = aux.order_of_magnitude(nMC) + 1\n\n # Get the threshold information, which is only a function of the\n # dimensionality, N, and the inverse temperature (as well as the scale\n # factor, lambdaprime, but this is unimportant). Note that lambdaprime\n # is infact equal to the critical inverse temperature the way we chose it.\n [r_th, e_th] = aux.thresholds(N, beta, lambdaprime, ptype=ptype)\n\n if verbose:\n print(\"r/e_th: %.02f/%.02f\" % (r_th, e_th))\n\n # Initialize a uniform distribution on the N-ball\n x0 = aux.sample_nball(N, n_tracer)\n\n # Get the corresponding initial energes\n e0 = aux.energy(x0, lambda_, ptype)\n\n # Wall clock time\n t0 = time()\n\n # Initialize an average energy vector which will keep track of the energy\n # of the tracers, averaged over all tracers, for every MC timestep,\n # henceforth referred to as tau. Also keep track of the standard deviation\n # of the data.\n eAVG = []\n eSTD = []\n\n # The persistence functions (psi) are binned logarithmically; a Counter\n # class is optimal to keep track of these, with the keys of the Counter\n # referencing the number of times that timeframe is observed.\n psiB = Counter({}) # Basin\n psiC = Counter({}) # Config\n\n # It is helpful to keep track of the minimum obtained radius for each\n # tracer,\n min_r_for_tracer = np.ones((n_tracer))\n\n # as well as the average over all tracers as a function of the timestep,\n # sampled at the same intervals as the energy. Similar to the energy, we\n # also want error bars.\n rminAVG = []\n rminSTD = []\n\n # For every tracer, these counters keep track of the amount of time steps\n # that a tracer remains in a single basin or configuration. Each time\n # a tracer leaves the basin or configuration, the counter resets.\n n_tau_in_B = np.zeros((n_tracer))\n n_tau_in_C = np.ones((n_tracer))\n\n # Initialize the timesteps where the energy / min radius (and other\n # quantities) are sampled at.\n tau_sample_grid = []\n\n # The memory functions (Pi) need to be sampled at tau-points tw and\n # tw + tw * dw, where dw is a parameter corresponding to the hwx function\n # in auxiliary.py. We will now define the points at which to determine Pi_C\n # and Pi_B. Starting with some defined dw, and the number of MC\n # points, this defines the maximum point at which we can sample on the\n # first grid such that the second argument in Pi: tw + tw * dw exists in\n # the MC sampling procedure.\n tw_max = nMC // (dw + 1.0)\n\n # Using this value allows us to define the first grid. Note it is not\n # always the case, depending on the amount of points in the grid, that\n # the length of this grid will = n_mem_sample, although it will be close.\n pi_grid_sample_1 = np.unique(np.logspace(0, np.log10(tw_max), n_mem_sample,\n dtype=int, endpoint=True))\n\n # The second grid is related directly to the first via tw -> tw + tw * dw,\n pi_grid_sample_2 = (pi_grid_sample_1 * (dw + 1.0)).astype(int)\n np.testing.assert_equal(True, pi_grid_sample_2[-1] <= nMC)\n N_pi_grid = len(pi_grid_sample_1)\n np.testing.assert_equal(N_pi_grid, len(pi_grid_sample_2))\n\n # Now we need a matrix which saves the full configuration at each recorded\n # point so later they may be compared; one for the configs, one for the\n # basins.\n B_recorder1 = np.zeros((N_pi_grid, n_tracer), dtype=complex)\n B_recorder2 = np.zeros((N_pi_grid, n_tracer), dtype=complex)\n C_recorder1 = np.zeros((N_pi_grid, n_tracer))\n C_recorder2 = np.zeros((N_pi_grid, n_tracer))\n\n # To determine which basin the \"particle\" is in at any given time, we need\n # to keep a counter. It will work as follows: each particle in the ensemble\n # will be assigned a \"basin index.\" The basin index will take on a real\n # value corresponding to the basin number it is in. In other words, in the\n # first basin, this particle will have basin index = 1. Once it exits the\n # first basin, it acquires imaginary component i. In this way, we can keep\n # track of not just whether or not the particle is in a basin, but which\n # basin. Furthermore, once that particle enters the next basin, it looses\n # the imaginary component, and gets +1 to its real component.\n basin_index = np.ones((n_tracer), dtype=complex) * 1j\n\n # Optional: even at the start, particles that are < e_threshold are\n # considered to be in a basin.\n in_basin_to_start = np.where(e0 < e_th)[1]\n basin_index[in_basin_to_start] = 0\n n_tau_in_B[in_basin_to_start] = 1\n\n # It is also critical to have a normalization term for the following\n # reason. A tracer at tw that is not in a basin should not contribute to\n # the overall probability embodied by Pi_B, which states: \"given that a\n # tracer is in a basin, the tracer is still in that basin at tw + tw * dw.\"\n # This normalizer will count the number of tracers which at tw, are in a\n # basin/config.\n B_normalization = np.zeros((N_pi_grid))\n\n # Optional for debugging: save all energies for EVERY tracer, at every\n # timestep:\n if save_all_energies:\n eALL = np.empty((nMC, n_tracer))\n\n # Get the increments where we should sample the energy (this is\n # logarithmic)\n where_sample_e = \\\n np.unique(np.logspace(0, nMC_lg, n_e_sample, dtype=int, endpoint=True))\n\n # And similarly for reporting (this is linear)\n report_increment = nMC // n_report\n\n # Temporarily ignore overflow warnings, since exp(large number) = inf and\n # this is fine for the code.\n np.seterr(over='ignore')\n\n # Initialize some counters\n counter1 = 0\n counter2 = 0\n\n # Begin the sampling.\n for ii in range(nMC + 1):\n\n # Report at designated timesteps so we can keep track of the\n # calculation.\n if ii % report_increment == 0 and verbose:\n ctime = time()\n print(\"%s/%s (%.02f%%) ~ %.02f (eta %.02f) h\"\n % (str(ii).zfill(zfill_index), str(nMC).zfill(zfill_index),\n (ii / nMC * 100.0), ((ctime - t0) / 3600.0),\n ((ctime - t0) / 3600.0 * nMC / (ii + 1))))\n sys.stdout.flush()\n\n if save_all_energies:\n eALL[ii, :] = e0\n\n # Generate a new configuration\n if protocol == 1:\n # --- Old Method ---\n # The random walk first samples a point randomly & uniformally on\n # the surface of the unit n-ball.\n # on_surface = sample_nball(N, nMC=1, n_vec=n_vec, yzero=True)\n\n # Next, a radius is sampled from an exponential distribution and\n # used to scale that ball.\n # exp_rand = np.random.exponential(scale=1.0 / xp_param,\n # size=(1, 1, n_vec))\n\n # The `xf` point is then updated by walking the particle from the\n # old configuration `x0` to the new one.\n\n # --- New Method ---\n # Push the particle by a Gaussian-sampled number\n xf = x0 + np.random.normal(scale=delta, size=(x0.shape))\n elif protocol == 0:\n xf = aux.sample_nball(N, n_tracer)\n else:\n raise RuntimeError(\"Invalid protocol\")\n\n # Get the energy of this new configuration\n ef = aux.energy(xf, lambda_, ptype=ptype)\n\n # Get the difference in energy between the old and new configs\n dE = ef - e0 # Of shape (N, n_tracer)\n\n # Compute the current distance of each particle from the center of the\n # well.\n rf = np.sqrt(np.sum(xf**2, axis=1)).squeeze()\n\n # Tracers which decrease in energy are accepted with p = 1:\n dE_down = np.where(dE < 0.0)[1]\n\n # Boltzmann factor:\n rand_vec = np.random.random(size=(1, n_tracer))\n w_vec = np.exp(-beta * dE)\n\n # Similarly, moves accepted to go up, or move rejected entirely.\n # For instance, a tracer can move up if dE > 0 but only if the\n # Metropolis selection criteria is satisfied.\n dE_up = np.where((dE >= 0.0) & (rand_vec <= w_vec))[1]\n\n # Any move in which dE >= 0 and the Boltzmann critiera is not\n # satisfied, or where the tracer's next move puts it outside the unit\n # ball, is rejected.\n dE_stay = np.where(((dE >= 0.0) & (rand_vec > w_vec)) | (rf > 1))[1]\n\n # Update the xf vector where necessary. All new moves (up or down) are\n # kept while re-initializing the required positions where no move has\n # take place, from the x0 vector.\n xf[:, :, dE_stay] = x0[:, :, dE_stay]\n ef[:, dE_stay] = e0[:, dE_stay]\n\n # Recompute the current radius after moves have been accepted/rejected\n rf = np.sqrt(np.sum(xf**2, axis=1)).squeeze()\n\n # Update the minimum r vector:\n to_update = np.where(rf < min_r_for_tracer)[0]\n min_r_for_tracer[to_update] = rf[to_update]\n\n # Easy to check n_config: only tracers that remained in the same\n # configuration (i.e. dE_stay) contribute:\n n_tau_in_C[dE_stay] += 1\n\n # Get the counters for the particles which exited up until this point:\n configUP = n_tau_in_C[dE_up]\n configDOWN = n_tau_in_C[dE_down]\n\n # And append this to the counter, which will bin logarithmically\n counter_up = Counter(int(floor(np.log2(x__))) for x__ in configUP)\n counter_down = Counter(int(floor(np.log2(x__))) for x__ in configDOWN)\n\n # Further append the frequency of these events to the overall counter\n psiC = psiC + counter_up + counter_down\n\n # Reset the counters\n n_tau_in_C[dE_up] = 1\n n_tau_in_C[dE_down] = 1\n\n # Next there's the basin counter. First, which configs enter a basin:\n entered_basin = np.where((ef < e_th) & (e0 >= e_th))[1]\n\n # And those that were in a basin, and are still in a basin:\n still_in_basin = np.where((ef < e_th) & (e0 < e_th))[1]\n\n # Those two cases acquire an increment to the real part, which indexes\n # the length of time that tracer has been in a basin.\n n_tau_in_B[entered_basin] += 1\n n_tau_in_B[still_in_basin] += 1\n\n # Now we count the tracers that have been in a basin previously, and\n # just exited.\n exited_basin = np.where((e0 < e_th) & (ef >= e_th))[1]\n\n # From there, we query the counter to determine how long that tracer\n # was in that basin, and index its log2 result:\n exited_basin_cc = n_tau_in_B[exited_basin]\n basin_log = \\\n Counter(int(floor(np.log2(x__))) for x__ in exited_basin_cc)\n psiB = psiB + basin_log\n\n # And then reset the counter:\n n_tau_in_B[exited_basin] = 0\n\n # Account for *which* basin the particles are in. Any particle that\n # just entered a basin gets 1-i:\n basin_index[entered_basin] += (1 - 1j)\n\n # Any particle which remains in a basin does not change. However, the\n # basins where a particle just left acquires an imaginary component:\n basin_index[exited_basin] += 1j\n\n # If we hit a point in the Pi grid to record, do so:\n if ii in pi_grid_sample_1:\n\n # Note for C_recorder we simply save the radius, not the exact\n # configuration so that we can save a bit of space. The probability\n # of achieving a different configuraiton xf but the exact same\n # radius is ~0, so this should not be a problem.\n C_recorder1[counter1, :] = rf\n B_recorder1[counter1, :] = basin_index\n\n # Tricky part. We need to compute the normalization here.\n # Basically, if a a tracer is *not* in a basin, it will never\n # contribute to Pi basin calculated downstream, but it should also\n # *NOT* contribute to the normalization (the probability) overall.\n # Thus, here we compute the number of tracers which are actually\n # in a basin and store that value as the normaliztion.\n B_normalization[counter1] = np.sum(np.imag(basin_index) == 0)\n counter1 += 1\n\n if ii in pi_grid_sample_2:\n C_recorder2[counter2, :] = rf\n B_recorder2[counter2, :] = basin_index\n counter2 += 1\n\n # Now the xf's become the x0's for the next iteration.\n x0[:, :, dE_down] = xf[:, :, dE_down]\n x0[:, :, dE_up] = xf[:, :, dE_up]\n e0[:, dE_down] = ef[:, dE_down]\n e0[:, dE_up] = ef[:, dE_up]\n\n # Get the average energy if we're at a sampling timestep\n if ii in where_sample_e:\n\n # Energy\n eAVG.append(np.mean(e0))\n eSTD.append(np.std(e0))\n\n # Minimum radius\n rminAVG.append(np.mean(min_r_for_tracer))\n rminSTD.append(np.std(min_r_for_tracer))\n\n # Log the values of tau where we sampled these quantities\n tau_sample_grid.append(ii)\n\n total_time = ((time() - t0) / 3600.0)\n\n # Reset the overflow warnings\n np.seterr(over='warn')\n\n # Evaluate Pi basin: the first part ensures that the tracer has the same\n # basin index (real part) at both tw and tw + tw * dw. The second part\n # ensures that neither of the tracers happen to be out of a basin at the\n # time of recording. Finally, the third part accounts for the\n # normalization, meaning, any tracer which is not in a basin at tw does not\n # contribute to the overall probability ala Bayes rule.\n part1 = B_recorder1 == B_recorder2\n part2 = np.imag(B_recorder1) == 0\n _condition = (part1 & part2)\n basin_rec_final = np.sum(_condition, axis=1)\n Pi_basin_final_output = basin_rec_final / B_normalization\n\n # Do the same thing, essentially, for the config recorder:\n config_recorder = C_recorder1 == C_recorder2\n Pi_config_final_output = np.sum(config_recorder, axis=1)\n\n print(\"Done. %.05f h\" % total_time)\n\n return [tau_sample_grid, eAVG, eSTD, rminAVG, rminSTD, psiB, psiC,\n pi_grid_sample_1, Pi_basin_final_output, Pi_config_final_output]\n"
] |
[
[
"numpy.testing.assert_equal",
"numpy.imag",
"numpy.random.random",
"numpy.log2",
"numpy.logspace",
"numpy.ones",
"numpy.seterr",
"numpy.random.normal",
"numpy.log10",
"numpy.where",
"numpy.mean",
"numpy.std",
"numpy.exp",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
]
] |
csliuwei/mne-python
|
[
"0e67ce63990117756ff3f63caecb43e4b37c153f"
] |
[
"mne/gui/tests/test_coreg_gui.py"
] |
[
"# Author: Christian Brodbeck <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport os\nimport os.path as op\nimport re\nimport shutil\nimport sys\nfrom unittest import SkipTest\n\nimport numpy as np\nfrom numpy.testing import (assert_allclose, assert_equal,\n assert_array_almost_equal)\nimport pytest\n\nimport mne\nfrom mne.datasets import testing\nfrom mne.io.kit.tests import data_dir as kit_data_dir\nfrom mne.transforms import invert_transform\nfrom mne.utils import _TempDir, run_tests_if_main, requires_mayavi, traits_test\n\n# backend needs to be set early\ntry:\n from traits.etsconfig.api import ETSConfig\nexcept ImportError:\n pass\nelse:\n ETSConfig.toolkit = 'qt4'\n\n\ndata_path = testing.data_path(download=False)\nraw_path = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')\nfname_trans = op.join(data_path, 'MEG', 'sample',\n 'sample_audvis_trunc-trans.fif')\nkit_raw_path = op.join(kit_data_dir, 'test_bin_raw.fif')\nsubjects_dir = op.join(data_path, 'subjects')\n\n\[email protected]_testing_data\n@requires_mayavi\n@traits_test\ndef test_coreg_model_decimation():\n \"\"\"Test CoregModel decimation of high-res to low-res head.\"\"\"\n from mne.gui._coreg_gui import CoregModel\n tempdir = _TempDir()\n subject_dir = op.join(tempdir, 'sample')\n shutil.copytree(op.join(subjects_dir, 'sample'), subject_dir)\n # This makes the test much faster\n shutil.move(op.join(subject_dir, 'bem', 'outer_skin.surf'),\n op.join(subject_dir, 'surf', 'lh.seghead'))\n for fname in ('sample-head.fif', 'sample-head-dense.fif'):\n os.remove(op.join(subject_dir, 'bem', fname))\n\n model = CoregModel(guess_mri_subject=False)\n with pytest.warns(RuntimeWarning, match='No low-resolution'):\n model.mri.subjects_dir = tempdir\n assert model.mri.subject == 'sample' # already set by setting subjects_dir\n assert model.mri.bem_low_res.file == ''\n assert len(model.mri.bem_low_res.surf.rr) == 2562\n assert len(model.mri.bem_high_res.surf.rr) == 2562 # because we moved it\n\n\[email protected]_testing_data\n@requires_mayavi\n@traits_test\ndef test_coreg_model():\n \"\"\"Test CoregModel.\"\"\"\n from mne.gui._coreg_gui import CoregModel\n tempdir = _TempDir()\n trans_dst = op.join(tempdir, 'test-trans.fif')\n\n model = CoregModel()\n pytest.raises(RuntimeError, model.save_trans, 'blah.fif')\n\n model.mri.subjects_dir = subjects_dir\n model.mri.subject = 'sample'\n\n assert not model.mri.fid_ok\n model.mri.lpa = [[-0.06, 0, 0]]\n model.mri.nasion = [[0, 0.05, 0]]\n model.mri.rpa = [[0.08, 0, 0]]\n assert (model.mri.fid_ok)\n\n model.hsp.file = raw_path\n assert_allclose(model.hsp.lpa, [[-7.137e-2, 0, 5.122e-9]], 1e-4)\n assert_allclose(model.hsp.rpa, [[+7.527e-2, 0, 5.588e-9]], 1e-4)\n assert_allclose(model.hsp.nasion, [[+3.725e-9, 1.026e-1, 4.191e-9]], 1e-4)\n assert model.has_lpa_data\n assert model.has_nasion_data\n assert model.has_rpa_data\n assert len(model.hsp.eeg_points) > 1\n\n assert len(model.mri.bem_low_res.surf.rr) == 2562\n assert len(model.mri.bem_high_res.surf.rr) == 267122\n\n lpa_distance = model.lpa_distance\n nasion_distance = model.nasion_distance\n rpa_distance = model.rpa_distance\n avg_point_distance = np.mean(model.point_distance)\n\n model.nasion_weight = 1.\n model.fit_fiducials(0)\n old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2\n new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2 +\n model.nasion_distance ** 2)\n assert new_x < old_x\n\n model.fit_icp(0)\n new_dist = np.mean(model.point_distance)\n assert new_dist < avg_point_distance\n\n model.save_trans(trans_dst)\n trans = mne.read_trans(trans_dst)\n assert_allclose(trans['trans'], model.head_mri_t)\n\n # test restoring trans\n x, y, z = 100, 200, 50\n rot_x, rot_y, rot_z = np.rad2deg([1.5, 0.1, -1.2])\n model.trans_x = x\n model.trans_y = y\n model.trans_z = z\n model.rot_x = rot_x\n model.rot_y = rot_y\n model.rot_z = rot_z\n trans = model.mri_head_t\n model.reset_traits([\"trans_x\", \"trans_y\", \"trans_z\", \"rot_x\", \"rot_y\",\n \"rot_z\"])\n assert_equal(model.trans_x, 0)\n model.set_trans(trans)\n assert_array_almost_equal(model.trans_x, x)\n assert_array_almost_equal(model.trans_y, y)\n assert_array_almost_equal(model.trans_z, z)\n assert_array_almost_equal(model.rot_x, rot_x)\n assert_array_almost_equal(model.rot_y, rot_y)\n assert_array_almost_equal(model.rot_z, rot_z)\n\n # info\n assert (isinstance(model.fid_eval_str, str))\n assert (isinstance(model.points_eval_str, str))\n\n # scaling job\n assert not model.can_prepare_bem_model\n model.n_scale_params = 1\n assert (model.can_prepare_bem_model)\n model.prepare_bem_model = True\n sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \\\n model.get_scaling_job('sample2', False)\n assert_equal(sdir, subjects_dir)\n assert_equal(sfrom, 'sample')\n assert_equal(sto, 'sample2')\n assert_allclose(scale, model.parameters[6:9])\n assert_equal(skip_fiducials, False)\n # find BEM files\n bems = set()\n for fname in os.listdir(op.join(subjects_dir, 'sample', 'bem')):\n match = re.match(r'sample-(.+-bem)\\.fif', fname)\n if match:\n bems.add(match.group(1))\n assert_equal(set(bemsol), bems)\n model.prepare_bem_model = False\n sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \\\n model.get_scaling_job('sample2', True)\n assert_equal(bemsol, [])\n assert (skip_fiducials)\n\n model.load_trans(fname_trans)\n model.save_trans(trans_dst)\n trans = mne.read_trans(trans_dst)\n assert_allclose(trans['trans'], model.head_mri_t)\n assert_allclose(invert_transform(trans)['trans'][:3, 3] * 1000.,\n [model.trans_x, model.trans_y, model.trans_z])\n\n\ndef _check_ci():\n if os.getenv('TRAVIS', 'false').lower() == 'true' and \\\n sys.platform == 'darwin':\n raise SkipTest('Skipping GUI tests on Travis OSX')\n\n\[email protected]_testing_data\n@requires_mayavi\n@traits_test\ndef test_coreg_gui():\n \"\"\"Test CoregFrame.\"\"\"\n _check_ci()\n home_dir = _TempDir()\n os.environ['_MNE_GUI_TESTING_MODE'] = 'true'\n os.environ['_MNE_FAKE_HOME_DIR'] = home_dir\n try:\n pytest.raises(ValueError, mne.gui.coregistration, subject='Elvis',\n subjects_dir=subjects_dir)\n\n from pyface.api import GUI\n from tvtk.api import tvtk\n gui = GUI()\n\n # avoid modal dialog if SUBJECTS_DIR is set to a directory that\n # does not contain valid subjects\n ui, frame = mne.gui.coregistration(subjects_dir='')\n\n frame.model.mri.subjects_dir = subjects_dir\n frame.model.mri.subject = 'sample'\n\n assert not frame.model.mri.fid_ok\n frame.model.mri.lpa = [[-0.06, 0, 0]]\n frame.model.mri.nasion = [[0, 0.05, 0]]\n frame.model.mri.rpa = [[0.08, 0, 0]]\n assert (frame.model.mri.fid_ok)\n frame.data_panel.raw_src.file = raw_path\n assert isinstance(frame.eeg_obj.glyph.glyph.glyph_source.glyph_source,\n tvtk.SphereSource)\n frame.data_panel.view_options_panel.eeg_obj.project_to_surface = True\n assert isinstance(frame.eeg_obj.glyph.glyph.glyph_source.glyph_source,\n tvtk.CylinderSource)\n\n # grow hair (faster for low-res)\n assert frame.data_panel.view_options_panel.head_high_res\n frame.data_panel.view_options_panel.head_high_res = False\n frame.model.grow_hair = 40.\n\n # scale\n frame.coreg_panel.n_scale_params = 3\n frame.coreg_panel.scale_x_inc = True\n assert frame.model.scale_x == 101.\n frame.coreg_panel.scale_y_dec = True\n assert frame.model.scale_y == 99.\n\n # reset parameters\n frame.coreg_panel.reset_params = True\n assert_equal(frame.model.grow_hair, 0)\n assert not frame.data_panel.view_options_panel.head_high_res\n\n # configuration persistence\n assert (frame.model.prepare_bem_model)\n frame.model.prepare_bem_model = False\n frame.save_config(home_dir)\n ui.dispose()\n gui.process_events()\n\n ui, frame = mne.gui.coregistration(subjects_dir=subjects_dir)\n assert not frame.model.prepare_bem_model\n assert not frame.data_panel.view_options_panel.head_high_res\n ui.dispose()\n gui.process_events()\n finally:\n del os.environ['_MNE_GUI_TESTING_MODE']\n del os.environ['_MNE_FAKE_HOME_DIR']\n\n\[email protected]_testing_data\n@requires_mayavi\n@traits_test\ndef test_coreg_model_with_fsaverage():\n \"\"\"Test CoregModel with the fsaverage brain data.\"\"\"\n tempdir = _TempDir()\n from mne.gui._coreg_gui import CoregModel\n\n mne.create_default_subject(subjects_dir=tempdir,\n fs_home=op.join(subjects_dir, '..'))\n\n model = CoregModel()\n model.mri.subjects_dir = tempdir\n model.mri.subject = 'fsaverage'\n assert (model.mri.fid_ok)\n\n model.hsp.file = raw_path\n lpa_distance = model.lpa_distance\n nasion_distance = model.nasion_distance\n rpa_distance = model.rpa_distance\n avg_point_distance = np.mean(model.point_distance)\n\n # test hsp point omission\n model.nasion_weight = 1.\n model.trans_y = -0.008\n model.fit_fiducials(0)\n model.omit_hsp_points(0.02)\n assert model.hsp.n_omitted == 1\n model.omit_hsp_points(np.inf)\n assert model.hsp.n_omitted == 0\n model.omit_hsp_points(0.02)\n assert model.hsp.n_omitted == 1\n model.omit_hsp_points(0.01)\n assert model.hsp.n_omitted == 4\n model.omit_hsp_points(0.005)\n assert model.hsp.n_omitted == 40\n model.omit_hsp_points(0.01)\n assert model.hsp.n_omitted == 4\n model.omit_hsp_points(0.02)\n assert model.hsp.n_omitted == 1\n\n # scale with 1 parameter\n model.n_scale_params = 1\n model.fit_fiducials(1)\n old_x = lpa_distance ** 2 + rpa_distance ** 2 + nasion_distance ** 2\n new_x = (model.lpa_distance ** 2 + model.rpa_distance ** 2 +\n model.nasion_distance ** 2)\n assert (new_x < old_x)\n\n model.fit_icp(1)\n avg_point_distance_1param = np.mean(model.point_distance)\n assert (avg_point_distance_1param < avg_point_distance)\n\n # scaling job\n sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \\\n model.get_scaling_job('scaled', False)\n assert_equal(sdir, tempdir)\n assert_equal(sfrom, 'fsaverage')\n assert_equal(sto, 'scaled')\n assert_allclose(scale, model.parameters[6:9])\n assert_equal(set(bemsol), set(('inner_skull-bem',)))\n model.prepare_bem_model = False\n sdir, sfrom, sto, scale, skip_fiducials, labels, annot, bemsol = \\\n model.get_scaling_job('scaled', False)\n assert_equal(bemsol, [])\n\n # scale with 3 parameters\n model.n_scale_params = 3\n model.fit_icp(3)\n assert (np.mean(model.point_distance) < avg_point_distance_1param)\n\n # test switching raw disables point omission\n assert_equal(model.hsp.n_omitted, 1)\n model.hsp.file = kit_raw_path\n assert_equal(model.hsp.n_omitted, 0)\n\n\nrun_tests_if_main()\n"
] |
[
[
"numpy.testing.assert_equal",
"numpy.rad2deg",
"numpy.mean",
"numpy.testing.assert_allclose",
"numpy.testing.assert_array_almost_equal"
]
] |
djeada/Numerical-Methodes
|
[
"45a5288f4719568a62a82374efbb3fc06d33ec46"
] |
[
"src/systems of linear equations/gaussian_elimination.py"
] |
[
"import numpy as np\n\n\ndef gaussian_elimination(a, b):\n\n n = len(a)\n m = n + 1\n\n for row, element in zip(a, b):\n row.append(element)\n if len(row) != m:\n raise ValueError(\"You have to provide a square matrix\")\n\n for i in range(n):\n if a[i][i] == 0.0:\n raise ZeroDivisionError()\n\n for j in range(i + 1, n):\n ratio = a[j][i] / a[i][i]\n\n for k in range(m):\n a[j][k] -= ratio * a[i][k]\n\n x = np.zeros(n)\n x[-1] = a[n - 1][n] / a[n - 1][n - 1]\n\n for i in range(n - 2, -1, -1):\n x[i] = a[i][n]\n\n for j in range(i + 1, n):\n x[i] -= x[j] * a[i][j]\n\n x[i] /= a[i][i]\n\n return x\n\n\nprint(gaussian_elimination([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]], [8, -11, -3]))\n"
] |
[
[
"numpy.zeros"
]
] |
CulpaBS/wbBach
|
[
"1e2defc8d8ef8612b1f8684af55d433747c22ae6"
] |
[
"rts/python/scalar.py"
] |
[
"# Scalar functions.\n\nimport numpy as np\n\ndef signed(x):\n if type(x) == np.uint8:\n return np.int8(x)\n elif type(x) == np.uint16:\n return np.int16(x)\n elif type(x) == np.uint32:\n return np.int32(x)\n else:\n return np.int64(x)\n\ndef unsigned(x):\n if type(x) == np.int8:\n return np.uint8(x)\n elif type(x) == np.int16:\n return np.uint16(x)\n elif type(x) == np.int32:\n return np.uint32(x)\n else:\n return np.uint64(x)\n\ndef shlN(x,y):\n return x << y\n\ndef ashrN(x,y):\n return x >> y\n\ndef sdivN(x,y):\n return x / y\n\ndef smodN(x,y):\n return x % y\n\ndef udivN(x,y):\n return signed(unsigned(x) / unsigned(y))\n\ndef umodN(x,y):\n return signed(unsigned(x) % unsigned(y))\n\ndef squotN(x,y):\n return np.int32(float(x) / float(y))\n\ndef sremN(x,y):\n return np.fmod(x,y)\n\ndef powN(x,y):\n return x ** y\n\ndef fpowN(x,y):\n return x ** y\n\ndef sleN(x,y):\n return x <= y\n\ndef sltN(x,y):\n return x < y\n\ndef uleN(x,y):\n return unsigned(x) <= unsigned(y)\n\ndef ultN(x,y):\n return unsigned(x) < unsigned(y)\n\ndef lshr8(x,y):\n return np.int8(np.uint8(x) >> np.uint8(y))\n\ndef lshr16(x,y):\n return np.int16(np.uint16(x) >> np.uint16(y))\n\ndef lshr32(x,y):\n return np.int32(np.uint32(x) >> np.uint32(y))\n\ndef lshr64(x,y):\n return np.int64(np.uint64(x) >> np.uint64(y))\n\ndef sext_T_i8(x):\n return np.int8(x)\n\ndef sext_T_i16(x):\n return np.int16(x)\n\ndef sext_T_i32(x):\n return np.int32(x)\n\ndef sext_T_i64(x):\n return np.int32(x)\n\ndef zext_i8_i8(x):\n return np.int8(np.uint8(x))\n\ndef zext_i8_i16(x):\n return np.int16(np.uint8(x))\n\ndef zext_i8_i32(x):\n return np.int32(np.uint8(x))\n\ndef zext_i8_i64(x):\n return np.int64(np.uint8(x))\n\ndef zext_i16_i8(x):\n return np.int8(np.uint16(x))\n\ndef zext_i16_i16(x):\n return np.int16(np.uint16(x))\n\ndef zext_i16_i32(x):\n return np.int32(np.uint16(x))\n\ndef zext_i16_i64(x):\n return np.int64(np.uint16(x))\n\ndef zext_i32_i8(x):\n return np.int8(np.uint32(x))\n\ndef zext_i32_i16(x):\n return np.int16(np.uint32(x))\n\ndef zext_i32_i32(x):\n return np.int32(np.uint32(x))\n\ndef zext_i32_i64(x):\n return np.int64(np.uint32(x))\n\ndef zext_i64_i8(x):\n return np.int8(np.uint64(x))\n\ndef zext_i64_i16(x):\n return np.int16(np.uint64(x))\n\ndef zext_i64_i32(x):\n return np.int32(np.uint64(x))\n\ndef zext_i64_i64(x):\n return np.int64(np.uint64(x))\n\nshl8 = shl16 = shl32 = shl64 = shlN\nashr8 = ashr16 = ashr32 = ashr64 = ashrN\nsdiv8 = sdiv16 = sdiv32 = sdiv64 = sdivN\nsmod8 = smod16 = smod32 = smod64 = smodN\nudiv8 = udiv16 = udiv32 = udiv64 = udivN\numod8 = umod16 = umod32 = umod64 = umodN\nsquot8 = squot16 = squot32 = squot64 = squotN\nsrem8 = srem16 = srem32 = srem64 = sremN\npow8 = pow16 = pow32 = pow64 = powN\nfpow32 = fpow64 = fpowN\nsle8 = sle16 = sle32 = sle64 = sleN\nslt8 = slt16 = slt32 = slt64 = sltN\nule8 = ule16 = ule32 = ule64 = uleN\nult8 = ult16 = ult32 = ult64 = ultN\nsext_i8_i8 = sext_i16_i8 = sext_i32_i8 = sext_i64_i8 = sext_T_i8\nsext_i8_i16 = sext_i16_i16 = sext_i32_i16 = sext_i64_i16 = sext_T_i16\nsext_i8_i32 = sext_i16_i32 = sext_i32_i32 = sext_i64_i32 = sext_T_i32\nsext_i8_i64 = sext_i16_i64 = sext_i32_i64 = sext_i64_i64 = sext_T_i64\n\ndef ssignum(x):\n return np.sign(x)\n\ndef usignum(x):\n if x < 0:\n return ssignum(-x)\n else:\n return ssignum(x)\n\ndef sitofp_T_f32(x):\n return np.float32(x)\nsitofp_i8_f32 = sitofp_i16_f32 = sitofp_i32_f32 = sitofp_i64_f32 = sitofp_T_f32\n\ndef sitofp_T_f64(x):\n return np.float64(x)\nsitofp_i8_f64 = sitofp_i16_f64 = sitofp_i32_f64 = sitofp_i64_f64 = sitofp_T_f64\n\ndef uitofp_T_f32(x):\n return np.float32(unsigned(x))\nuitofp_i8_f32 = uitofp_i16_f32 = uitofp_i32_f32 = uitofp_i64_f32 = uitofp_T_f32\n\ndef uitofp_T_f64(x):\n return np.float64(unsigned(x))\nuitofp_i8_f64 = uitofp_i16_f64 = uitofp_i32_f64 = uitofp_i64_f64 = uitofp_T_f64\n\ndef fptosi_T_i8(x):\n return np.int8(np.trunc(x))\nfptosi_f32_i8 = fptosi_f64_i8 = fptosi_T_i8\n\ndef fptosi_T_i16(x):\n return np.int16(np.trunc(x))\nfptosi_f32_i16 = fptosi_f64_i16 = fptosi_T_i16\n\ndef fptosi_T_i32(x):\n return np.int32(np.trunc(x))\nfptosi_f32_i32 = fptosi_f64_i32 = fptosi_T_i32\n\ndef fptosi_T_i64(x):\n return np.int64(np.trunc(x))\nfptosi_f32_i64 = fptosi_f64_i64 = fptosi_T_i64\n\ndef fptoui_T_i8(x):\n return np.uint8(np.trunc(x))\nfptoui_f32_i8 = fptoui_f64_i8 = fptoui_T_i8\n\ndef fptoui_T_i16(x):\n return np.uint16(np.trunc(x))\nfptoui_f32_i16 = fptoui_f64_i16 = fptoui_T_i16\n\ndef fptoui_T_i32(x):\n return np.uint32(np.trunc(x))\nfptoui_f32_i32 = fptoui_f64_i32 = fptoui_T_i32\n\ndef fptoui_T_i64(x):\n return np.uint64(np.trunc(x))\nfptoui_f32_i64 = fptoui_f64_i64 = fptoui_T_i64\n\ndef fpconv_f32_f64(x):\n return np.float64(x)\n\ndef fpconv_f64_f32(x):\n return np.float32(x)\n\ndef futhark_log64(x):\n return np.float64(np.log(x))\n\ndef futhark_sqrt64(x):\n return np.sqrt(x)\n\ndef futhark_exp64(x):\n return np.exp(x)\n\ndef futhark_cos64(x):\n return np.cos(x)\n\ndef futhark_sin64(x):\n return np.sin(x)\n\ndef futhark_atan2_64(x, y):\n return np.arctan2(x, y)\n\ndef futhark_isnan64(x):\n return np.isnan(x)\n\ndef futhark_isinf64(x):\n return np.isinf(x)\n\ndef futhark_log32(x):\n return np.float32(np.log(x))\n\ndef futhark_sqrt32(x):\n return np.float32(np.sqrt(x))\n\ndef futhark_exp32(x):\n return np.exp(x)\n\ndef futhark_cos32(x):\n return np.cos(x)\n\ndef futhark_sin32(x):\n return np.sin(x)\n\ndef futhark_atan2_32(x, y):\n return np.arctan2(x, y)\n\ndef futhark_isnan32(x):\n return np.isnan(x)\n\ndef futhark_isinf32(x):\n return np.isinf(x)\n"
] |
[
[
"numpy.sqrt",
"numpy.arctan2",
"numpy.exp",
"numpy.fmod",
"numpy.trunc",
"numpy.uint32",
"numpy.uint8",
"numpy.int8",
"numpy.sin",
"numpy.uint16",
"numpy.float32",
"numpy.log",
"numpy.isnan",
"numpy.int64",
"numpy.int32",
"numpy.cos",
"numpy.int16",
"numpy.sign",
"numpy.uint64",
"numpy.float64",
"numpy.isinf"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.