repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
haozhu233/time_series_prediction | [
"9fc40ebd76d44217025aa29b63bd620163773902"
] | [
"src/cnn_hao/dataloader.py"
] | [
"import torch\nfrom torch.utils.data import Dataset, DataLoader\nimport pandas as pd\nimport numpy as np\n\n# Model/dataloader definitions\nclass tsPredDataset(Dataset):\n def __init__(self, x_df, y_df, seq_id, x_cols, y_col, ts_steps=None):\n list_of_x = x_df[[seq_id] + x_cols] \\\n .groupby(seq_id) \\\n .apply(pd.DataFrame.to_numpy)\n if ts_steps is None:\n self.x = np.swapaxes(np.stack(list_of_x)[:, :, 1:], 1, 2).astype('float64')\n else:\n list_of_padded_x = []\n for i in list_of_x.keys():\n padded_x = np.zeros((ts_steps, len(x_cols) + 1))\n padded_x[:list_of_x[i].shape[0], :list_of_x[i].shape[1]] = list_of_x[i]\n list_of_padded_x.append(padded_x)\n self.x = np.swapaxes(np.stack(list_of_padded_x)[:, :, 1:], 1, 2).astype('float64')\n self.y = np.expand_dims(y_df[y_col].to_numpy().astype('float64'), axis = 1)\n \n def __len__(self):\n return self.y.shape[0]\n \n def __getitem__(self, idx):\n return self.x[idx, :, :], self.y[idx, :]\n\ndef load_train_val(x_path, y_path, seq_id, random_seed=None, train_p=0.8):\n x_df = pd.read_csv(x_path)\n y_df = pd.read_csv(y_path)\n all_seq_id = pd.unique(x_df[seq_id])\n if random_seed is not None:\n np.random.seed(random_seed)\n train_msk = np.random.random(all_seq_id.shape)\n train_id = [i for i, msk in zip(all_seq_id, train_msk) if msk <= train_p]\n val_id = [i for i, msk in zip(all_seq_id, train_msk) if msk > train_p]\n \n return (\n x_df[x_df[seq_id].isin(train_id)].reset_index(drop=True), \n y_df[y_df[seq_id].isin(train_id)].reset_index(drop=True),\n x_df[x_df[seq_id].isin(val_id)].reset_index(drop=True),\n y_df[y_df[seq_id].isin(val_id)].reset_index(drop=True)\n )\n\ndef load_test(x_path, y_path):\n x_df = pd.read_csv(x_path)\n y_df = pd.read_csv(y_path) \n return (x_df, y_df)\n\ndef create_datasets(train_x_path, train_y_path, test_x_path, test_y_path,\n seq_id, x_cols, y_col,\n random_seed=None, train_p=0.8, ts_steps=None):\n train_x, train_y, val_x, val_y = load_train_val(\n train_x_path, train_y_path, seq_id, random_seed, train_p\n )\n test_x, test_y = load_test(test_x_path, test_y_path)\n train_ds = tsPredDataset(train_x, train_y, seq_id, x_cols, y_col, ts_steps=ts_steps)\n val_ds = tsPredDataset(val_x, val_y, seq_id, x_cols, y_col, ts_steps=ts_steps)\n test_ds = tsPredDataset(test_x, test_y, seq_id, x_cols, y_col, ts_steps=ts_steps)\n return train_ds, val_ds, test_ds"
] | [
[
"pandas.read_csv",
"numpy.random.random",
"numpy.random.seed",
"numpy.stack",
"pandas.unique"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
maxlz/ML | [
"4929ee496a822e9b2d0981f17bf4b607d42953ad"
] | [
"keras_transfer_catdog.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Flatten, Dense, Dropout\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator,img_to_array,array_to_img,load_img\n\nimport h5py\nimport os\n\nimport tensorflow as tf\ntf.python.control_flow_ops = tf\n\nimport numpy as np\n\n#import cv2, numpy as np\n\n\n#装载对应层的weights\ndef load_weights(weights_path,model): \n assert os.path.exists(weights_path), 'Model weights not found (see \"weights_path\" variable in script).'\n f = h5py.File(weights_path)\n for k in range(f.attrs['nb_layers']):\n if k >= len(model.layers):\n # we don't look at the last (fully-connected) layers in the savefile\n break\n g = f['layer_{}'.format(k)]\n weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]\n model.layers[k].set_weights(weights)\n f.close()\n print('Model loaded.')\n\ndef VGG_16(weights_path=None):\n model = Sequential()\n model.add(ZeroPadding2D((1,1),input_shape=(3,224,224)))\n model.add(Convolution2D(64, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(64, 3, 3, activation='relu'))\n model.add(MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(128, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(128, 3, 3, activation='relu'))\n model.add(MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(256, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(256, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(256, 3, 3, activation='relu'))\n model.add(MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(512, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(512, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(512, 3, 3, activation='relu'))\n model.add(MaxPooling2D((2,2), strides=(2,2)))\n\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(512, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(512, 3, 3, activation='relu'))\n model.add(ZeroPadding2D((1,1)))\n model.add(Convolution2D(512, 3, 3, activation='relu'))\n model.add(MaxPooling2D((2,2), strides=(2,2)))\n \n #不要最后的FC层\n\n\n model.add(Flatten())\n \n if weights_path:\n load_weights(weights_path,model)\n\n return model\n\n\n \nmodel = VGG_16(\"/home/max/下载/vgg16_weights.h5\")\n\n#不用rescale更好!!\n#datagen = ImageDataGenerator(rescale=1./255)\ndatagen = ImageDataGenerator()\n\ntrain_data = datagen.flow_from_directory(\"/home/max/data/train\",target_size=(224,224)\\\n ,shuffle=False,class_mode=None)\n\ntest_data = datagen.flow_from_directory(\"/home/max/data/test\",target_size=(224,224)\\\n ,shuffle=False,class_mode=None)\n\ntrain_out = model.predict_generator(train_data,val_samples=2000)\n\ntest_out = model.predict_generator(test_data,val_samples=800)\n\n\nnp.save(open(\"/home/max/train.out\",'w'),train_out)\nnp.save(open(\"/home/max/test.out\",'w'),test_out)\n\ndef build_top():\n train_feature = np.load(\"/home/max/train.out\")\n test_feature = np.load(\"/home/max/test.out\")\n \n train_label = np.array([0]*1000+[1]*1000)\n test_label = np.array([0]*400+[1]*400)\n \n model = Sequential()\n #model.add(Flatten(input_shape = (1000,)))\n model.add(Dense(256,activation='relu',input_shape=train_out.shape[1:]))\n model.add(Dropout(0.5))\n model.add(Dense(1,activation='sigmoid'))\n \n model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])\n \n model.fit(train_feature,train_label,validation_data=(test_feature,test_label),nb_epoch=50)\n \n\n \n\n"
] | [
[
"numpy.load",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dathudeptrai/rfcx-kaggle | [
"e0d4705cd27c02142f3b2cac42083d6569a90863"
] | [
"backbones/inceptionv3.py"
] | [
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n# pylint: disable=invalid-name\n\"\"\"Inception V3 model for Keras.\nReference:\n - [Rethinking the Inception Architecture for Computer Vision](\n http://arxiv.org/abs/1512.00567) (CVPR 2016)\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras.applications import imagenet_utils\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.layers import VersionAwareLayers\nfrom tensorflow.python.keras.utils import data_utils, layer_utils\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.util.tf_export import keras_export\n\nfrom backbones.mixstyle import MixStyle\n\nWEIGHTS_PATH = (\n \"https://storage.googleapis.com/tensorflow/keras-applications/\"\n \"inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels.h5\"\n)\nWEIGHTS_PATH_NO_TOP = (\n \"https://storage.googleapis.com/tensorflow/keras-applications/\"\n \"inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5\"\n)\n\nlayers = VersionAwareLayers()\n\n\n@keras_export(\n \"keras.applications.inception_v3.InceptionV3\", \"keras.applications.InceptionV3\"\n)\ndef InceptionV3(\n include_top=True,\n weights=\"imagenet\",\n input_tensor=None,\n input_shape=None,\n pooling=None,\n classes=1000,\n classifier_activation=\"softmax\",\n use_mixstyle=False,\n):\n \"\"\"Instantiates the Inception v3 architecture.\n Reference:\n - [Rethinking the Inception Architecture for Computer Vision](\n http://arxiv.org/abs/1512.00567) (CVPR 2016)\n Optionally loads weights pre-trained on ImageNet.\n Note that the data format convention used by the model is\n the one specified in the `tf.keras.backend.image_data_format()`.\n Note: each Keras Application expects a specific kind of input preprocessing.\n For InceptionV3, call `tf.keras.applications.inception_v3.preprocess_input`\n on your inputs before passing them to the model.\n Arguments:\n include_top: Boolean, whether to include the fully-connected\n layer at the top, as the last layer of the network. Default to `True`.\n weights: One of `None` (random initialization),\n `imagenet` (pre-training on ImageNet),\n or the path to the weights file to be loaded. Default to `imagenet`.\n input_tensor: Optional Keras tensor (i.e. output of `layers.Input()`)\n to use as image input for the model. `input_tensor` is useful for sharing\n inputs between multiple different networks. Default to None.\n input_shape: Optional shape tuple, only to be specified\n if `include_top` is False (otherwise the input shape\n has to be `(299, 299, 3)` (with `channels_last` data format)\n or `(3, 299, 299)` (with `channels_first` data format).\n It should have exactly 3 inputs channels,\n and width and height should be no smaller than 75.\n E.g. `(150, 150, 3)` would be one valid value.\n `input_shape` will be ignored if the `input_tensor` is provided.\n pooling: Optional pooling mode for feature extraction\n when `include_top` is `False`.\n - `None` (default) means that the output of the model will be\n the 4D tensor output of the last convolutional block.\n - `avg` means that global average pooling\n will be applied to the output of the\n last convolutional block, and thus\n the output of the model will be a 2D tensor.\n - `max` means that global max pooling will be applied.\n classes: optional number of classes to classify images\n into, only to be specified if `include_top` is True, and\n if no `weights` argument is specified. Default to 1000.\n classifier_activation: A `str` or callable. The activation function to use\n on the \"top\" layer. Ignored unless `include_top=True`. Set\n `classifier_activation=None` to return the logits of the \"top\" layer.\n Returns:\n A `keras.Model` instance.\n Raises:\n ValueError: in case of invalid argument for `weights`,\n or invalid input shape.\n ValueError: if `classifier_activation` is not `softmax` or `None` when\n using a pretrained top layer.\n \"\"\"\n if not (weights in {\"imagenet\", None} or file_io.file_exists_v2(weights)):\n raise ValueError(\n \"The `weights` argument should be either \"\n \"`None` (random initialization), `imagenet` \"\n \"(pre-training on ImageNet), \"\n \"or the path to the weights file to be loaded.\"\n )\n\n if weights == \"imagenet\" and include_top and classes != 1000:\n raise ValueError(\n 'If using `weights` as `\"imagenet\"` with `include_top`'\n \" as true, `classes` should be 1000\"\n )\n\n # Determine proper input shape\n input_shape = imagenet_utils.obtain_input_shape(\n input_shape,\n default_size=299,\n min_size=75,\n data_format=backend.image_data_format(),\n require_flatten=include_top,\n weights=weights,\n )\n\n if input_tensor is None:\n img_input = layers.Input(shape=input_shape)\n else:\n if not backend.is_keras_tensor(input_tensor):\n img_input = layers.Input(tensor=input_tensor, shape=input_shape)\n else:\n img_input = input_tensor\n\n if backend.image_data_format() == \"channels_first\":\n channel_axis = 1\n else:\n channel_axis = 3\n\n x = conv2d_bn(img_input, 32, 3, 3, strides=(2, 2), padding=\"valid\")\n x = conv2d_bn(x, 32, 3, 3, padding=\"valid\")\n x = conv2d_bn(x, 64, 3, 3)\n x = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)\n\n x = conv2d_bn(x, 80, 1, 1, padding=\"valid\")\n x = conv2d_bn(x, 192, 3, 3, padding=\"valid\")\n x = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)\n\n # mixed 0: 35 x 35 x 256\n branch1x1 = conv2d_bn(x, 64, 1, 1)\n\n branch5x5 = conv2d_bn(x, 48, 1, 1)\n branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)\n\n branch3x3dbl = conv2d_bn(x, 64, 1, 1)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)\n\n branch_pool = layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(x)\n branch_pool = conv2d_bn(branch_pool, 32, 1, 1)\n x = layers.concatenate(\n [branch1x1, branch5x5, branch3x3dbl, branch_pool],\n axis=channel_axis,\n name=\"mixed0\",\n )\n\n # mixed 1: 35 x 35 x 288\n branch1x1 = conv2d_bn(x, 64, 1, 1)\n\n branch5x5 = conv2d_bn(x, 48, 1, 1)\n branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)\n\n branch3x3dbl = conv2d_bn(x, 64, 1, 1)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)\n\n branch_pool = layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(x)\n branch_pool = conv2d_bn(branch_pool, 64, 1, 1)\n x = layers.concatenate(\n [branch1x1, branch5x5, branch3x3dbl, branch_pool],\n axis=channel_axis,\n name=\"mixed1\",\n )\n if use_mixstyle:\n x = MixStyle(p=0.5, alpha=0.1, name=\"mixed1_mixstyle\")(x)\n\n # mixed 2: 35 x 35 x 288\n branch1x1 = conv2d_bn(x, 64, 1, 1)\n\n branch5x5 = conv2d_bn(x, 48, 1, 1)\n branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)\n\n branch3x3dbl = conv2d_bn(x, 64, 1, 1)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)\n\n branch_pool = layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(x)\n branch_pool = conv2d_bn(branch_pool, 64, 1, 1)\n x = layers.concatenate(\n [branch1x1, branch5x5, branch3x3dbl, branch_pool],\n axis=channel_axis,\n name=\"mixed2\",\n )\n if use_mixstyle:\n x = MixStyle(p=0.5, alpha=0.1, name=\"mixed2_mixstyle\")(x)\n\n # mixed 3: 17 x 17 x 768\n branch3x3 = conv2d_bn(x, 384, 3, 3, strides=(2, 2), padding=\"valid\")\n\n branch3x3dbl = conv2d_bn(x, 64, 1, 1)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3, strides=(2, 2), padding=\"valid\")\n\n branch_pool = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)\n x = layers.concatenate(\n [branch3x3, branch3x3dbl, branch_pool], axis=channel_axis, name=\"mixed3\"\n )\n if use_mixstyle:\n x = MixStyle(p=0.5, alpha=0.1, name=\"mixed3_mixstyle\")(x)\n\n # mixed 4: 17 x 17 x 768\n branch1x1 = conv2d_bn(x, 192, 1, 1)\n\n branch7x7 = conv2d_bn(x, 128, 1, 1)\n branch7x7 = conv2d_bn(branch7x7, 128, 1, 7)\n branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)\n\n branch7x7dbl = conv2d_bn(x, 128, 1, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 1, 7)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)\n\n branch_pool = layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(x)\n branch_pool = conv2d_bn(branch_pool, 192, 1, 1)\n x = layers.concatenate(\n [branch1x1, branch7x7, branch7x7dbl, branch_pool],\n axis=channel_axis,\n name=\"mixed4\",\n )\n if use_mixstyle:\n x = MixStyle(p=0.5, alpha=0.1, name=\"mixed4_mixstyle\")(x)\n\n # mixed 5, 6: 17 x 17 x 768\n for i in range(2):\n branch1x1 = conv2d_bn(x, 192, 1, 1)\n\n branch7x7 = conv2d_bn(x, 160, 1, 1)\n branch7x7 = conv2d_bn(branch7x7, 160, 1, 7)\n branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)\n\n branch7x7dbl = conv2d_bn(x, 160, 1, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 7, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 1, 7)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 7, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)\n\n branch_pool = layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(x)\n branch_pool = conv2d_bn(branch_pool, 192, 1, 1)\n x = layers.concatenate(\n [branch1x1, branch7x7, branch7x7dbl, branch_pool],\n axis=channel_axis,\n name=\"mixed\" + str(5 + i),\n )\n if use_mixstyle:\n x = MixStyle(p=0.5, alpha=0.1, name=f\"mixed{5 + i}_mixstyle\")(x)\n\n # mixed 7: 17 x 17 x 768\n branch1x1 = conv2d_bn(x, 192, 1, 1)\n\n branch7x7 = conv2d_bn(x, 192, 1, 1)\n branch7x7 = conv2d_bn(branch7x7, 192, 1, 7)\n branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)\n\n branch7x7dbl = conv2d_bn(x, 192, 1, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 7, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 7, 1)\n branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)\n\n branch_pool = layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(x)\n branch_pool = conv2d_bn(branch_pool, 192, 1, 1)\n x = layers.concatenate(\n [branch1x1, branch7x7, branch7x7dbl, branch_pool],\n axis=channel_axis,\n name=\"mixed7\",\n )\n if use_mixstyle:\n x = MixStyle(p=0.5, alpha=0.1, name=\"mixed7_mixstyle\")(x)\n\n # mixed 8: 8 x 8 x 1280\n branch3x3 = conv2d_bn(x, 192, 1, 1)\n branch3x3 = conv2d_bn(branch3x3, 320, 3, 3, strides=(2, 2), padding=\"valid\")\n\n branch7x7x3 = conv2d_bn(x, 192, 1, 1)\n branch7x7x3 = conv2d_bn(branch7x7x3, 192, 1, 7)\n branch7x7x3 = conv2d_bn(branch7x7x3, 192, 7, 1)\n branch7x7x3 = conv2d_bn(branch7x7x3, 192, 3, 3, strides=(2, 2), padding=\"valid\")\n\n branch_pool = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)\n x = layers.concatenate(\n [branch3x3, branch7x7x3, branch_pool], axis=channel_axis, name=\"mixed8\"\n )\n\n # mixed 9: 8 x 8 x 2048\n for i in range(2):\n branch1x1 = conv2d_bn(x, 320, 1, 1)\n\n branch3x3 = conv2d_bn(x, 384, 1, 1)\n branch3x3_1 = conv2d_bn(branch3x3, 384, 1, 3)\n branch3x3_2 = conv2d_bn(branch3x3, 384, 3, 1)\n branch3x3 = layers.concatenate(\n [branch3x3_1, branch3x3_2], axis=channel_axis, name=\"mixed9_\" + str(i)\n )\n\n branch3x3dbl = conv2d_bn(x, 448, 1, 1)\n branch3x3dbl = conv2d_bn(branch3x3dbl, 384, 3, 3)\n branch3x3dbl_1 = conv2d_bn(branch3x3dbl, 384, 1, 3)\n branch3x3dbl_2 = conv2d_bn(branch3x3dbl, 384, 3, 1)\n branch3x3dbl = layers.concatenate(\n [branch3x3dbl_1, branch3x3dbl_2], axis=channel_axis\n )\n\n branch_pool = layers.AveragePooling2D((3, 3), strides=(1, 1), padding=\"same\")(x)\n branch_pool = conv2d_bn(branch_pool, 192, 1, 1)\n x = layers.concatenate(\n [branch1x1, branch3x3, branch3x3dbl, branch_pool],\n axis=channel_axis,\n name=\"mixed\" + str(9 + i),\n )\n if include_top:\n # Classification block\n x = layers.GlobalAveragePooling2D(name=\"avg_pool\")(x)\n imagenet_utils.validate_activation(classifier_activation, weights)\n x = layers.Dense(classes, activation=classifier_activation, name=\"predictions\")(\n x\n )\n else:\n if pooling == \"avg\":\n x = layers.GlobalAveragePooling2D()(x)\n elif pooling == \"max\":\n x = layers.GlobalMaxPooling2D()(x)\n\n # Ensure that the model takes into account\n # any potential predecessors of `input_tensor`.\n if input_tensor is not None:\n inputs = layer_utils.get_source_inputs(input_tensor)\n else:\n inputs = img_input\n # Create model.\n model = training.Model(inputs, x, name=\"inception_v3\")\n\n # Load weights.\n if weights == \"imagenet\":\n if include_top:\n weights_path = data_utils.get_file(\n \"inception_v3_weights_tf_dim_ordering_tf_kernels.h5\",\n WEIGHTS_PATH,\n cache_subdir=\"models\",\n file_hash=\"9a0d58056eeedaa3f26cb7ebd46da564\",\n )\n else:\n weights_path = data_utils.get_file(\n \"inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5\",\n WEIGHTS_PATH_NO_TOP,\n cache_subdir=\"models\",\n file_hash=\"bcbd6486424b2319ff4ef7d526e38f63\",\n )\n model.load_weights(weights_path)\n elif weights is not None:\n model.load_weights(weights)\n\n return model\n\n\ndef conv2d_bn(x, filters, num_row, num_col, padding=\"same\", strides=(1, 1), name=None):\n \"\"\"Utility function to apply conv + BN.\n Arguments:\n x: input tensor.\n filters: filters in `Conv2D`.\n num_row: height of the convolution kernel.\n num_col: width of the convolution kernel.\n padding: padding mode in `Conv2D`.\n strides: strides in `Conv2D`.\n name: name of the ops; will become `name + '_conv'`\n for the convolution and `name + '_bn'` for the\n batch norm layer.\n Returns:\n Output tensor after applying `Conv2D` and `BatchNormalization`.\n \"\"\"\n if name is not None:\n bn_name = name + \"_bn\"\n conv_name = name + \"_conv\"\n else:\n bn_name = None\n conv_name = None\n if backend.image_data_format() == \"channels_first\":\n bn_axis = 1\n else:\n bn_axis = 3\n x = layers.Conv2D(\n filters,\n (num_row, num_col),\n strides=strides,\n padding=padding,\n use_bias=False,\n name=conv_name,\n )(x)\n x = layers.BatchNormalization(axis=bn_axis, scale=False, name=bn_name)(x)\n x = layers.Activation(\"relu\", name=name)(x)\n return x\n\n\n@keras_export(\"keras.applications.inception_v3.preprocess_input\")\ndef preprocess_input(x, data_format=None):\n return imagenet_utils.preprocess_input(x, data_format=data_format, mode=\"tf\")\n\n\n@keras_export(\"keras.applications.inception_v3.decode_predictions\")\ndef decode_predictions(preds, top=5):\n return imagenet_utils.decode_predictions(preds, top=top)\n\n\npreprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format(\n mode=\"\",\n ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_TF,\n error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC,\n)\ndecode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__\n"
] | [
[
"tensorflow.python.keras.applications.imagenet_utils.decode_predictions",
"tensorflow.python.keras.backend.image_data_format",
"tensorflow.python.keras.utils.data_utils.get_file",
"tensorflow.python.keras.layers.VersionAwareLayers",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.utils.layer_utils.get_source_inputs",
"tensorflow.python.keras.backend.is_keras_tensor",
"tensorflow.python.lib.io.file_io.file_exists_v2",
"tensorflow.python.keras.applications.imagenet_utils.PREPROCESS_INPUT_DOC.format",
"tensorflow.python.keras.applications.imagenet_utils.preprocess_input",
"tensorflow.python.keras.applications.imagenet_utils.validate_activation",
"tensorflow.python.keras.engine.training.Model"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
HesNobi/d4rl | [
"5f7834fee82902950cc27be8962bb32f18821f9c"
] | [
"d4rl/__init__.py"
] | [
"import os\nimport sys\nimport collections\nimport numpy as np\n\nimport d4rl.infos\nfrom d4rl.offline_env import set_dataset_path, get_keys\n\nSUPPRESS_MESSAGES = bool(os.environ.get('D4RL_SUPPRESS_IMPORT_ERROR', 0))\n\n_ERROR_MESSAGE = 'Warning: %s failed to import. Set the environment variable D4RL_SUPPRESS_IMPORT_ERROR=1 to suppress this message.'\n\ntry:\n import d4rl.locomotion\n import d4rl.hand_manipulation_suite\n import d4rl.pointmaze\n import d4rl.gym_minigrid\n import d4rl.gym_mujoco\nexcept ImportError as e:\n if not SUPPRESS_MESSAGES:\n print(_ERROR_MESSAGE % 'Mujoco-based envs', file=sys.stderr)\n print(e, file=sys.stderr)\n\ntry:\n import d4rl.flow\nexcept ImportError as e:\n if not SUPPRESS_MESSAGES:\n print(_ERROR_MESSAGE % 'Flow', file=sys.stderr)\n print(e, file=sys.stderr)\n\ntry:\n import d4rl.kitchen\nexcept ImportError as e:\n if not SUPPRESS_MESSAGES:\n print(_ERROR_MESSAGE % 'FrankaKitchen', file=sys.stderr)\n print(e, file=sys.stderr)\n\ntry:\n import d4rl.carla\nexcept ImportError as e:\n if not SUPPRESS_MESSAGES:\n print(_ERROR_MESSAGE % 'CARLA', file=sys.stderr)\n print(e, file=sys.stderr)\n \ntry:\n import d4rl.gym_bullet\n import d4rl.pointmaze_bullet\nexcept ImportError as e:\n if not SUPPRESS_MESSAGES:\n print(_ERROR_MESSAGE % 'GymBullet', file=sys.stderr)\n print(e, file=sys.stderr)\n\ndef reverse_normalized_score(env_name, score):\n ref_min_score = d4rl.infos.REF_MIN_SCORE[env_name]\n ref_max_score = d4rl.infos.REF_MAX_SCORE[env_name]\n return (score * (ref_max_score - ref_min_score)) + ref_min_score\n\ndef get_normalized_score(env_name, score):\n ref_min_score = d4rl.infos.REF_MIN_SCORE[env_name]\n ref_max_score = d4rl.infos.REF_MAX_SCORE[env_name]\n return (score - ref_min_score) / (ref_max_score - ref_min_score)\n\ndef qlearning_dataset(env, dataset=None, terminate_on_end=False, **kwargs):\n \"\"\"\n Returns datasets formatted for use by standard Q-learning algorithms,\n with observations, actions, next_observations, rewards, and a terminal\n flag.\n\n Args:\n env: An OfflineEnv object.\n dataset: An optional dataset to pass in for processing. If None,\n the dataset will default to env.get_dataset()\n terminate_on_end (bool): Set done=True on the last timestep\n in a trajectory. Default is False, and will discard the\n last timestep in each trajectory.\n **kwargs: Arguments to pass to env.get_dataset().\n\n Returns:\n A dictionary containing keys:\n observations: An N x dim_obs array of observations.\n actions: An N x dim_action array of actions.\n next_observations: An N x dim_obs array of next observations.\n rewards: An N-dim float array of rewards.\n terminals: An N-dim boolean array of \"done\" or episode termination flags.\n \"\"\"\n if dataset is None:\n dataset = env.get_dataset(**kwargs)\n\n N = dataset['rewards'].shape[0]\n obs_ = []\n next_obs_ = []\n action_ = []\n reward_ = []\n done_ = []\n\n # The newer version of the dataset adds an explicit\n # timeouts field. Keep old method for backwards compatability.\n use_timeouts = False\n if 'timeouts' in dataset:\n use_timeouts = True\n\n episode_step = 0\n for i in range(N-1):\n obs = dataset['observations'][i].astype(np.float32)\n new_obs = dataset['observations'][i+1].astype(np.float32)\n action = dataset['actions'][i].astype(np.float32)\n reward = dataset['rewards'][i].astype(np.float32)\n done_bool = bool(dataset['terminals'][i])\n\n if use_timeouts:\n final_timestep = dataset['timeouts'][i]\n else:\n final_timestep = (episode_step == env._max_episode_steps - 1)\n if (not terminate_on_end) and final_timestep:\n # Skip this transition and don't apply terminals on the last step of an episode\n episode_step = 0\n continue \n if done_bool or final_timestep:\n episode_step = 0\n\n obs_.append(obs)\n next_obs_.append(new_obs)\n action_.append(action)\n reward_.append(reward)\n done_.append(done_bool)\n episode_step += 1\n\n return {\n 'observations': np.array(obs_),\n 'actions': np.array(action_),\n 'next_observations': np.array(next_obs_),\n 'rewards': np.array(reward_),\n 'terminals': np.array(done_),\n }\n\ndef sequence_dataset(env, dataset=None, max_steps = None, max_episodes=None, **kwargs):\n \"\"\"\n Returns an iterator through trajectories.\n\n Args:\n env: An OfflineEnv object.\n dataset: An optional dataset to pass in for processing. If None,\n the dataset will default to env.get_dataset()\n **kwargs: Arguments to pass to env.get_dataset().\n\n Returns:\n An iterator through dictionaries with keys:\n observations\n actions\n rewards\n terminals\n \"\"\"\n # TODO: Some serious performance issues.\n # TODO: Randomize the episode selection without extracting all of them.\n # TODO: Adding discounted reward returns.\n\n if dataset is None:\n dataset = env.get_dataset(**kwargs)\n\n total_steps = dataset['rewards'].shape[0]\n if max_steps is None:\n max_steps = total_steps\n\n assert max_steps <= dataset['rewards'].shape[0],\\\n \"\\\"max_steps ={} \\\" should be smaller (or equal) than total number of steps = {}.\".format(\n max_steps, total_steps)\n\n data_ = collections.defaultdict(list)\n\n # The newer version of the dataset adds an explicit\n # timeouts field. Keep old method for backwards compatability.\n use_timeouts = False\n if 'timeouts' in dataset:\n use_timeouts = True\n\n key_list = []\n for k_index in dataset:\n if isinstance(dataset[k_index], np.ndarray) \\\n and dataset[k_index].shape[0] == total_steps:\n key_list.append(k_index)\n\n episode_step = 0\n for i in range(max_steps):\n done_bool = bool(dataset['terminals'][i])\n if use_timeouts:\n final_timestep = dataset['timeouts'][i]\n else:\n final_timestep = (episode_step == env._max_episode_steps - 1)\n\n for k in key_list:\n data_[k].append(dataset[k][i])\n\n if done_bool or final_timestep:\n episode_step = 0\n episode_data = {}\n for k in data_:\n episode_data[k] = np.array(data_[k])\n yield episode_data\n data_ = collections.defaultdict(list)\n if max_episodes:\n max_episodes -= 1\n if max_episodes < 1:\n break\n\n episode_step += 1\n\n if max_episodes is not None and max_episodes > 0:\n import warnings\n warnings.warn(\"[WARNING] Not enough steps in the dataset to generate the requested number of episodes\")\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sylviemonet/thewalrus | [
"b39e49573943075d0160baf1cccb3f2ecf653495"
] | [
"thewalrus/_hermite_multidimensional.py"
] | [
"# Copyright 2019 Xanadu Quantum Technologies 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\"\"\"\nHermite Multidimensional Python interface\n\"\"\"\nfrom itertools import product\nfrom typing import Tuple, Generator\nfrom functools import lru_cache\nfrom numba import jit\nfrom numba.cpython.unsafe.tuple import tuple_setitem\nimport numpy as np\n\nfrom .libwalrus import hermite_multidimensional as hm\nfrom .libwalrus import hermite_multidimensional_real as hmr\n\nfrom .libwalrus import renorm_hermite_multidimensional as rhm\nfrom .libwalrus import renorm_hermite_multidimensional_real as rhmr\n\nfrom ._hafnian import input_validation\n\n\n# pylint: disable=too-many-arguments\ndef hermite_multidimensional(\n R, cutoff, y=None, renorm=False, make_tensor=True, modified=False, rtol=1e-05, atol=1e-08\n):\n r\"\"\"Returns the multidimensional Hermite polynomials :math:`H_k^{(R)}(y)`.\n\n Here :math:`R` is an :math:`n \\times n` square matrix, and\n :math:`y` is an :math:`n` dimensional vector. The polynomials are\n parametrized by the multi-index :math:`k=(k_0,k_1,\\ldots,k_{n-1})`,\n and are calculated for all values :math:`0 \\leq k_j < \\text{cutoff}`,\n thus a tensor of dimensions :math:`\\text{cutoff}^n` is returned.\n\n This tensor can either be flattened into a vector or returned as an actual\n tensor with :math:`n` indices.\n\n .. note::\n\n Note that if :math:`R = (1)` then :math:`H_k^{(R)}(y)`\n are precisely the well known **probabilists' Hermite polynomials** :math:`He_k(y)`,\n and if :math:`R = (2)` then :math:`H_k^{(R)}(y)` are precisely the well known\n **physicists' Hermite polynomials** :math:`H_k(y)`.\n\n Args:\n R (array): square matrix parametrizing the Hermite polynomial family\n cutoff (int): maximum size of the subindices in the Hermite polynomial\n y (array): vector argument of the Hermite polynomial\n renorm (bool): If ``True``, normalizes the returned multidimensional Hermite\n polynomials such that :math:`H_k^{(R)}(y)/\\prod_i k_i!`\n make_tensor (bool): If ``False``, returns a flattened one dimensional array\n containing the values of the polynomial\n modified (bool): whether to return the modified multidimensional Hermite polynomials or the standard ones\n rtol (float): the relative tolerance parameter used in ``np.allclose``\n atol (float): the absolute tolerance parameter used in ``np.allclose``\n Returns:\n (array): the multidimensional Hermite polynomials\n \"\"\"\n\n input_validation(R, atol=atol, rtol=rtol)\n n, _ = R.shape\n\n if (modified is False) and (y is not None):\n m = y.shape[0]\n if m == n:\n ym = R @ y\n return hermite_multidimensional(\n R, cutoff, y=ym, renorm=renorm, make_tensor=make_tensor, modified=True\n )\n\n if y is None:\n y = np.zeros([n], dtype=complex)\n\n m = y.shape[0]\n if m != n:\n raise ValueError(\"The matrix R and vector y have incompatible dimensions\")\n\n Rt = np.real_if_close(R)\n yt = np.real_if_close(y)\n\n if Rt.dtype == np.float and yt.dtype == np.float:\n if renorm:\n values = np.array(rhmr(Rt, yt, cutoff))\n else:\n values = np.array(hmr(Rt, yt, cutoff))\n else:\n if renorm:\n values = np.array(rhm(np.complex128(R), np.complex128(y), cutoff))\n else:\n values = np.array(hm(np.complex128(R), np.complex128(y), cutoff))\n\n if make_tensor:\n shape = cutoff * np.ones([n], dtype=int)\n values = np.reshape(values, shape)\n\n return values\n\n\n# pylint: disable=too-many-arguments\ndef hafnian_batched(A, cutoff, mu=None, rtol=1e-05, atol=1e-08, renorm=False, make_tensor=True):\n r\"\"\"Calculates the hafnian of :func:`reduction(A, k) <hafnian.reduction>`\n for all possible values of vector ``k`` below the specified cutoff.\n\n Here,\n\n * :math:`A` is am :math:`n\\times n` square matrix\n * :math:`k` is a vector of (non-negative) integers with the same dimensions as :math:`A`,\n i.e., :math:`k = (k_0,k_1,\\ldots,k_{n-1})`, and where :math:`0 \\leq k_j < \\texttt{cutoff}`.\n\n The function :func:`~.hafnian_repeated` can be used to calculate the reduced hafnian\n for a *specific* value of :math:`k`; see the documentation for more information.\n\n .. note::\n\n If ``mu`` is not ``None``, this function instead returns\n ``hafnian(np.fill_diagonal(reduction(A, k), reduction(mu, k)), loop=True)``.\n This calculation can only be performed if the matrix :math:`A` is invertible.\n\n Args:\n A (array): a square, symmetric :math:`N\\times N` array.\n cutoff (int): maximum size of the subindices in the Hermite polynomial\n mu (array): a vector of length :math:`N` representing the vector of means/displacement\n renorm (bool): If ``True``, the returned hafnians are *normalized*, that is,\n :math:`haf(reduction(A, k))/\\ \\sqrt{prod_i k_i!}`\n (or :math:`lhaf(fill\\_diagonal(reduction(A, k),reduction(mu, k)))` if\n ``mu`` is not None)\n make_tensor: If ``False``, returns a flattened one dimensional array instead\n of a tensor with the values of the hafnians.\n rtol (float): the relative tolerance parameter used in ``np.allclose``.\n atol (float): the absolute tolerance parameter used in ``np.allclose``.\n Returns:\n (array): the values of the hafnians for each value of :math:`k` up to the cutoff\n \"\"\"\n input_validation(A, atol=atol, rtol=rtol)\n n, _ = A.shape\n\n if mu is None:\n mu = np.zeros([n], dtype=complex)\n\n return hermite_multidimensional(\n -A, cutoff, y=mu, renorm=renorm, make_tensor=make_tensor, modified=True\n )\n\n\n# Note the minus signs in the arguments. Those are intentional and are due to the fact that Dodonov et al. in PRA 50, 813 (1994) use (p,q) ordering instead of (q,p) ordering\n@lru_cache()\ndef partition(photons, cutoff):\n r\"\"\"Returns a list of all the ways of putting n photons into modes that have a given cutoff dimension.\n This function is useful to fill the amplitude array by multiplets of constant photon number.\n\n Args:\n photons (int): number of photons in the multiplet\n cutoff (tuple[int]): the cutoff of each mode\n \"\"\"\n return [comb for comb in product(*(range(min(photons, i - 1) + 1) for i in cutoff)) if sum(comb) == photons]\n\n\n@jit(nopython=True)\ndef dec(tup: Tuple[int], i: int) -> Tuple[int, ...]: # pragma: no cover\n r\"\"\"returns a copy of the given tuple of integers where the ith element has been decreased by 1\n\n Args:\n tup (Tuple[int]): the given tuple\n i (int): the position of the element to be decreased\n\n Returns:\n Tuple[int,...]: the new tuple with the decrease on i-th element by 1\n \"\"\"\n copy = tup[:]\n return tuple_setitem(copy, i, tup[i] - 1)\n\n\n@jit(nopython=True)\ndef remove(\n pattern: Tuple[int, ...]\n) -> Generator[Tuple[int, Tuple[int, ...]], None, None]: # pragma: no cover\n r\"\"\"returns a generator for all the possible ways to decrease elements of the given tuple by 1\n\n Args:\n pattern (Tuple[int, ...]): the pattern given to be decreased\n\n Returns:\n Generator[Tuple[int, Tuple[int, ...]], None, None]: the generator\n \"\"\"\n for p, n in enumerate(pattern):\n if n > 0:\n yield p, dec(pattern, p)\n\n\nSQRT = np.sqrt(np.arange(1000)) # saving the time to recompute square roots\n\n\ndef hermite_multidimensional_numba(R, cutoff, y, C=1, dtype=None):\n # pylint: disable=too-many-arguments\n r\"\"\"Returns the renormalized multidimensional Hermite polynomials :math:`C*H_k^{(R)}(y)`.\n\n Here :math:`R` is an :math:`n \\times n` square matrix, and\n :math:`y` is an :math:`n` dimensional vector. The polynomials are\n parametrized by the multi-index :math:`k=(k_0,k_1,\\ldots,k_{n-1})`,\n and are calculated for all values :math:`0 \\leq k_j < \\text{cutoff}`,\n\n Args:\n R (array[complex]): square matrix parametrizing the Hermite polynomial\n cutoff (int or list[int]): maximum sizes of the subindices in the Hermite polynomial\n y (vector[complex]): vector argument of the Hermite polynomial\n C (complex): first value of the Hermite polynomials, the default value is 1\n dtype (data type): Specifies the data type used for the calculation\n\n Returns:\n array[data type]: the multidimensional Hermite polynomials\n \"\"\"\n if dtype is None:\n dtype = np.find_common_type([R.dtype.name, y.dtype.name], [np.array(C).dtype.name])\n n, _ = R.shape\n if y.shape[0] != n:\n raise ValueError(f\"The matrix R and vector y have incompatible dimensions ({R.shape} vs {y.shape})\")\n num_indices = len(y)\n if isinstance(cutoff, int):\n cutoffs = tuple([cutoff] * num_indices)\n else:\n cutoffs = tuple(cutoff)\n array = np.zeros(cutoffs, dtype=dtype)\n array[(0,) * num_indices] = C\n for photons in range(1, sum(cutoffs) - num_indices + 1):\n for idx in partition(photons, cutoffs):\n array = fill_hermite_multidimensional_numba_loop(array, idx, R, y)\n return array\n\n\n@jit(nopython=True)\ndef fill_hermite_multidimensional_numba_loop(array, idx, R, y): # pragma: no cover\n r\"\"\"Calculates the renormalized Hermite multidimensional polynomial for a given index.\n\n Args:\n array (array[data type]): the multidimensional Hermite polynomials\n idx (tuple): index of the gradients to be filled\n R (array[complex]): square matrix parametrizing the Hermite polynomial\n y (vector[complex]): vector argument of the Hermite polynomial\n\n Returns:\n array[data type]: the hermit multidimensional polynomial for a given index\n \"\"\"\n i = 0\n for i, val in enumerate(idx):\n if val > 0:\n break\n ki = dec(idx, i)\n u = y[i] * array[ki]\n for l, kl in remove(ki):\n u -= SQRT[ki[l]] * R[i, l] * array[kl]\n array[idx] = u / SQRT[idx[i]]\n return array\n\n\ndef grad_hermite_multidimensional_numba(array, R, cutoff, y, C=1, dtype=None):\n # pylint: disable=too-many-arguments\n r\"\"\"Calculates the gradients of the renormalized multidimensional Hermite polynomials :math:`C*H_k^{(R)}(y)` with respect to its parameters :math:`C`, :math:`y` and :math:`R`.\n\n Args:\n array (array): the multidimensional Hermite polynomials\n R (array[complex]): square matrix parametrizing the Hermite polynomial\n cutoff (int or list[int]): maximum sizes of the subindices in the Hermite polynomial\n y (vector[complex]): vector argument of the Hermite polynomial\n C (complex): first value of the Hermite polynomials\n dtype (data type): Specifies the data type used for the calculation\n\n Returns:\n array[data type], array[data type], array[data type]: the gradients of the multidimensional Hermite polynomials with respect to C, R and y\n \"\"\"\n if dtype is None:\n dtype = np.find_common_type([array.dtype.name, R.dtype.name, y.dtype.name], [np.array(C).dtype.name])\n n, _ = R.shape\n if y.shape[0] != n:\n raise ValueError(f\"The matrix R and vector y have incompatible dimensions ({R.shape} vs {y.shape})\")\n num_indices = len(y)\n if isinstance(cutoff, int):\n cutoffs = tuple([cutoff] * num_indices)\n else:\n cutoffs = tuple(cutoff)\n dG_dC = np.array(array / C).astype(dtype)\n dG_dR = np.zeros(array.shape + R.shape, dtype=dtype)\n dG_dy = np.zeros(array.shape + y.shape, dtype=dtype)\n for photons in range(1, sum(cutoffs) - num_indices + 1):\n for idx in partition(photons, cutoffs):\n dG_dR, dG_dy = fill_grad_hermite_multidimensional_numba_loop(dG_dR, dG_dy, array, idx, R, y)\n return dG_dC, dG_dR, dG_dy\n\n\n@jit(nopython=True)\ndef fill_grad_hermite_multidimensional_numba_loop(\n dG_dR, dG_dy, array, idx, R, y\n): # pragma: no cover\n # pylint: disable=too-many-arguments\n r\"\"\"Calculates the gradients of the renormalized multidimensional Hermite polynomials for a given index.\n\n Args:\n dG_dR (array[data type]): array representing the gradients with respect to R\n dG_dy (array[data type]): array representing the gradients with respect to y\n array (array[data type]): the multidimensional Hermite polynomials\n idx (tuple): index of the gradients to be filled\n R (array[complex]): square matrix parametrizing the Hermite polynomial\n y (vector[complex]): vector argument of the Hermite polynomial\n\n Returns:\n array[data type], array[data type]: the gradients of the multidimensional Hermite polynomials with respect to R and y for a given index\n \"\"\"\n i = 0\n for i, val in enumerate(idx):\n if val > 0:\n break\n ki = dec(idx, i)\n dy = y[i] * dG_dy[ki]\n dy[i] += array[ki]\n dR = y[i] * dG_dR[ki]\n for l, kl in remove(ki):\n dy -= SQRT[ki[l]] * dG_dy[kl] * R[i, l]\n dR -= SQRT[ki[l]] * R[i, l] * dG_dR[kl]\n dR[i, l] -= SQRT[ki[l]] * array[kl]\n dG_dR[idx] = dR / SQRT[idx[i]]\n dG_dy[idx] = dy / SQRT[idx[i]]\n return dG_dR, dG_dy\n"
] | [
[
"numpy.real_if_close",
"numpy.complex128",
"numpy.reshape",
"numpy.arange",
"numpy.ones",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vishalbelsare/resilience | [
"596a9b8224fc6168bd6ee5718ea6c57425b7f273"
] | [
"resilience/agents/AssetManager.py"
] | [
"import logging\n\nimport numpy as np\n\nfrom ..contracts import Shares\nfrom ..parameters import eps, isequal_float\nfrom .Institution import Institution\nfrom .DefaultException import DefaultException\n\n\nclass AssetManager(Institution):\n def __init__(self, name: str, model):\n super().__init__(name, model)\n self.shares = []\n self.nShares = 0\n self.NAV_lr_previous = 0 # lr stands for loss relative\n self.nShares_extra_previous = 0\n\n def update_valuation_of_all_shares(self) -> None:\n for share in self.shares:\n share.update_valuation()\n\n def issue_shares(self, owner, quantity: int) -> Shares:\n \"\"\"\n This method is used only at balance sheet initialisation step.\n While the initialised quantity is an integer, it will soon change into\n a float.\n \"\"\"\n self.nShares += quantity\n self.update_valuation_of_all_shares()\n return Shares(owner, self, quantity, self.get_net_asset_valuation())\n\n def get_net_asset_valuation(self) -> float:\n # This condition is added to avoid divide-by-zero\n if self.nShares > 0:\n return self.get_equity_valuation() / self.nShares\n return 0\n\n def get_nShares(self):\n return self.nShares\n\n def step(self):\n super().step()\n\n def get_equity_loss(self) -> float:\n return 0.0\n\n def pay_matured_cash_commitments_or_default(self) -> None:\n maturedPullFunding = self.get_matured_obligations()\n if maturedPullFunding > 0:\n logging.debug(\"We have matured payment obligations for a total of %.2f\" % maturedPullFunding)\n if (self.get_ue_cash() >= maturedPullFunding - eps):\n self.fulfil_matured_requests()\n else:\n logging.debug(\"A matured obligation was not fulfilled.\\nDEFAULT DUE TO LACK OF LIQUIDITY\")\n raise DefaultException(self, DefaultException.TypeOfDefault.LIQUIDITY)\n\n def trigger_default(self) -> None:\n super().trigger_default()\n # perform firesale assets\n self.sell_assets_proportionally()\n\n def choose_actions(self) -> None:\n NAV = self.get_net_asset_valuation()\n logging.debug(\"\\nMy NAV is %f\" % NAV)\n if NAV < 0:\n # Equity is negative, probably due to price fell\n raise DefaultException(self, DefaultException.TypeOfDefault.SOLVENCY)\n\n # 1) Redeem shares or default\n # self.pay_matured_cash_commitments_or_default() # not used since AM investor is disabled\n\n assert self.nShares >= self.nShares_extra_previous, (self.nShares, self.nShares_extra_previous) # sanity check so that the AM doesn't over-redeem\n _amount_to_redeem = self.nShares_extra_previous * self.NAV_previous\n if self.get_ue_cash() < _amount_to_redeem:\n raise DefaultException(self, DefaultException.TypeOfDefault.LIQUIDITY)\n share = self.shares[0] # There is only 1 share object\n # NOTE: share.redeem() is called directly here instead of using RedeemSharesOblgn.fulfil()\n # because asset manager investor is currently None instead of an agent\n # TODO ideally this should be within the obligation framework as well\n share.redeem(self.nShares_extra_previous, _amount_to_redeem)\n self.nShares -= self.nShares_extra_previous\n self.update_valuation_of_all_shares()\n\n # 2) Firesell to meet current NAV loss\n assert NAV <= self.NAV_previous + eps, (NAV, self.NAV_previous)\n _mul = 2.5\n if self.NAV_lr_previous > 0 and self.nShares > 0:\n assert isequal_float(self.nShares, (1 - _mul * self.NAV_lr_previous) * self.nShares_initial), (self.nShares, self.NAV_lr_previous, self.nShares_initial)\n # lr stands for loss relative\n NAV_lr = (self.NAV_initial - NAV) / self.NAV_initial\n if NAV_lr > self.NAV_lr_previous:\n # This ensures 0 <= nShares_extra <= self.nShares\n nShares_extra = np.clip(_mul * self.nShares_initial * (NAV_lr - self.NAV_lr_previous), 0, self.nShares)\n\n # Firesale to raise that liquidity\n self.sell_assets_proportionally(nShares_extra * NAV)\n self.nShares_extra_previous = nShares_extra\n\n else:\n self.nShares_extra_previous = 0\n\n # update f^{t-1}, NAV^{t-1}\n self.NAV_lr_previous = NAV_lr\n self.NAV_previous = NAV\n\n # 3) Firesell extra assets to get enough cash if it is too low\n _A = self.get_ledger().get_asset_valuation()\n _C = self.get_cash()\n if _C / _A < 0.9 * self.cash_fraction_initial:\n self.sell_assets_proportionally(_A * self.cash_fraction_initial - _C)\n"
] | [
[
"numpy.clip"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ajmaurais/ms2_annotator | [
"103fa6bef497589005c7fd264a9b68355d4fc056"
] | [
"python/parsers/parse_maxquant.py"
] | [
"\nimport sys\nimport os\nimport re\nimport argparse\nimport pandas as pd\n\nfrom modules.parent_parser import PARENT_PARSER\nfrom modules import tsv_constants\nfrom modules import maxquant_constants\nfrom modules.molecular_formula import MolecularFormula\nfrom modules import atom_table\nfrom modules import utils\n\nMODIFICATION_REGEX = re.compile(r'([A-Z_])\\((.*?)(\\(.*?\\))?\\)')\n\n\ndef get_unique_modifications(modified_sequences):\n '''\n Get a set of unique peptide modifications and the residues they occur on.\n\n Parameters\n ----------\n modified_sequences: Iterable\n Iterable object with all modifications observed in data set.\n\n Returns\n -------\n mods_set: list\n List of tuples (modification, residue)\n '''\n\n ret = set()\n for seq in modified_sequences:\n for match in MODIFICATION_REGEX.findall(seq):\n ret.add((match[1].strip().lower(), ('N-TERM' if match[0] == '_' else match[0])))\n return list(ret)\n\n\ndef extractModifications(modified_sequence, fixed_modifications=None):\n '''\n Convert modified_sequence to list of AminoAcids and formula.\n\n Parameters\n ----------\n modified_sequence: str\n Peptide sequence with modifications.\n fixed_modifications: list\n A list of tuples wher the first elment is the modification the second is the residue.\n \n Returns\n -------\n amino_acids: list\n A list of AminoAcids in the sequence\n formula: MolecularFormula\n Molecular formula for sequence\n '''\n\n seq_no_mod = ''\n matches = list(MODIFICATION_REGEX.finditer(modified_sequence))\n indecies = [True for _ in range(len(modified_sequence))]\n modification_indecies = list()\n for m in matches:\n modification_indecies.append(m.start())\n for i in range(len(indecies)):\n if i in range(m.start() + 1, m.end()):\n indecies[i] = False\n\n new_modification_indecies = list()\n for i, (char, boo) in enumerate(zip(modified_sequence, indecies)):\n if boo:\n if char != '_':\n seq_no_mod += char\n if i in modification_indecies:\n new_modification_indecies.append(len(seq_no_mod))\n\n amino_acids = utils.strToAminoAcids(seq_no_mod)\n formula = MolecularFormula(seq_no_mod)\n\n # add dynamic modifications\n for i, site in enumerate(new_modification_indecies):\n name = matches[i].group(2).lower().strip()\n residue = matches[i].group(1)\n if residue == '_':\n if site == 0:\n residue = 'N-TERM'\n else: # May have to also add c-term at some point but I am too lazy to do it now.\n raise ValueError('Invalid char in sequence: {}'.format(seq_no_mod))\n mod_temp = atom_table.get_mod(name, residue)\n formula.add_mod(name, residue)\n amino_acids[site].mod += atom_table.calc_mass(mod_temp)\n\n # add static modifications\n for mod, residue in fixed_modifications:\n mod_temp = atom_table.get_mod(mod, residue)\n mass_temp = atom_table.calc_mass(mod_temp)\n if residue == 'N_TERM':\n amino_acids[0].mod += mass_temp\n continue\n for i, aa in enumerate(seq_no_mod):\n if aa == residue:\n formula.add_mod(mod, residue)\n amino_acids[i+1].mod += mass_temp\n\n return amino_acids, formula\n\n\ndef extractAllModifications(modified_sequences, fixed_modifications=None):\n '''\n Extract and parse modifications from peptide sequences.\n\n Parameters\n ----------\n modified_sequences: list\n A list of peptide sequences with modification.\n fixed_modifications: list\n A list of tuples wher the first elment is the modification the second is the residue.\n\n Returns\n -------\n amino_acids: list, formulas: list\n A list of lists of AminoAcid(s), and a list of MolecularFormula(s).\n '''\n\n formulas = list()\n amino_acids = list()\n for s in modified_sequences:\n _amino_acids, formula = extractModifications(s, fixed_modifications)\n formulas.append(formula)\n amino_acids.append(_amino_acids)\n\n return amino_acids, formulas\n\n\ndef main():\n parser = argparse.ArgumentParser(prog='parse_maxquant',\n parents=[PARENT_PARSER],\n description='Convert MaxQuant output to proper input for ionFinder tsv input.',\n epilog=\"parse_maxquant was written by Aaron Maurais.\\n\"\n \"Email questions or bugs to [email protected]\")\n\n parser.add_argument('-g', '--groupMethod', choices=[0, 1, 2], default=1, type=int,\n help='How many spectra per peptide? 0: include all scans, '\n '1: Only show the best spectra per sequence, file and charge state, '\n '2: Group by charge; show the best spectra, per sequence, and file. '\n 'Default is 1.')\n\n parser.add_argument('-f', '--fixedMod', default='C:carbamidomethyl',\n help='Specify fixed modification(s) if there are multiple modifications, '\n 'they should be comma separated. Default is \"C:carbamidomethyl\"')\n\n parser.add_argument('input_file', help='Name of file to parse. Should be a MaxQuant msms.txt file.')\n\n args = parser.parse_args()\n\n if args.inplace:\n ofname = args.input_file\n else:\n if args.ofname == '':\n s = os.path.splitext(os.path.basename(args.input_file))\n ofname = '{}_parsed.tsv'.format(s[0])\n else: ofname = args.ofname\n\n # read and format properly\n sys.stdout.write('\\n{}\\n\\nReading {}...'.format(parser.prog, args.input_file))\n dat = pd.read_csv(args.input_file, sep='\\t', low_memory=False)\n dat.columns = [c.lower().replace(' ', '_').replace('/', '') for c in dat.columns]\n dat = dat[dat[maxquant_constants.MSMS_SCAN_NUMBER].isna().apply(lambda x: not x)]\n if maxquant_constants.GENE_NAMES in dat.columns:\n dat = dat[dat[maxquant_constants.GENE_NAMES].isna().apply(lambda x: not x)]\n elif maxquant_constants.LEADING_PROTEINS in dat.columns:\n dat = dat[dat[maxquant_constants.LEADING_PROTEINS].isna().apply(lambda x: not x)]\n else:\n raise RuntimeError('\"{}\" and \"{}\" columns not found.'.format(maxquant_constants.GENE_NAMES,\n maxquant_constants.LEADING_PROTEINS))\n dat = dat.reset_index()\n sys.stdout.write(' Done!\\n')\n\n # parse fixed modifications\n fixed_modifications = list()\n for mod in re.split('\\s?,\\s?', args.fixedMod):\n match = re.search(r'^([A-Z]):(.+)$', mod.strip())\n if match is None:\n raise RuntimeError('Could not parse fixed modification: {}'.format(mod))\n fixed_modifications.append((match.group(2), match.group(1)))\n fixed_modifications = list(set(fixed_modifications))\n\n # Check that modifications are valid\n variable_modifications = get_unique_modifications(dat[dat[maxquant_constants.MODIFICATIONS] !=\n 'Unmodified'][maxquant_constants.MODIFIED_SEQUENCE].to_list())\n sys.stdout.write('Iterating through modifications to make sure their composition is known...')\n fixed_good = utils.check_modifications(fixed_modifications,\n 'fixed', verbose=args.verbose)\n variable_good = utils.check_modifications(variable_modifications,\n 'variable', verbose=args.verbose)\n if not fixed_good and not variable_good:\n return -1\n sys.stdout.write('Success!\\n')\n\n # add columns to ret\n ret = pd.DataFrame()\n ret[tsv_constants.SAMPLE_NAME] = dat[maxquant_constants.EXPERIMENT]\n ret[tsv_constants.PRECURSOR_FILE] = dat[maxquant_constants.RAW_FILE].apply(lambda x: '{}.{}'.format(x, args.fileExt))\n\n # get parent protein data\n # ret[tsv_constants.PARENT_ID] = dat[maxquant_constants.LEADING_PROTEINS].apply(lambda x: [i for i in x.split(';')][0])\n ret[tsv_constants.PARENT_ID] = dat[maxquant_constants.LEADING_PROTEINS]\n if maxquant_constants.GENE_NAMES in dat.columns:\n # ret[tsv_constants.PARENT_PROTEIN] = dat[maxquant_constants.GENE_NAMES].apply(lambda x: [i for i in x.split(';')][0])\n ret[tsv_constants.PARENT_PROTEIN] = dat[maxquant_constants.GENE_NAMES]\n if maxquant_constants.PROTEIN_NAMES in dat.columns:\n # ret[tsv_constants.PARENT_DESCRIPTION] = dat[maxquant_constants.PROTEIN_NAMES].apply(lambda x: [i for i in x.split(';')][0])\n ret[tsv_constants.PARENT_DESCRIPTION] = dat[maxquant_constants.PROTEIN_NAMES]\n\n # parse sequences\n seq_list, formulas = extractAllModifications(dat[maxquant_constants.MODIFIED_SEQUENCE].to_list(), fixed_modifications)\n\n # add formula column\n ret[tsv_constants.FORMULA] = pd.Series([str(x) for x in formulas])\n\n # get seq as string and change R(+0.98) to R*\n seq_str_list = list()\n for seq in seq_list:\n s = str()\n for a in seq:\n s += str(a)\n s = re.sub(r'{}\\([\\-\\+\\d\\.]+\\)'.format(args.mod_residue), '{}*'.format(args.mod_residue), s)\n seq_str_list.append(s)\n\n ret[tsv_constants.SEQUENCE] = pd.Series(seq_str_list)\n ret[tsv_constants.FULL_SEQUENCE] = pd.Series(seq_str_list)\n\n # add other columns\n ret[tsv_constants.SCAN_NUM] = dat[maxquant_constants.MSMS_SCAN_NUMBER].apply(lambda x: int(x))\n ret[tsv_constants.UNIQUE] = dat[maxquant_constants.PROTEINS].apply(lambda x: len(x.split(';')) == 1)\n ret[tsv_constants.PRECURSOR_MZ] = dat[maxquant_constants.MZ]\n ret[tsv_constants.CHARGE] = dat[maxquant_constants.CHARGE]\n ret[tsv_constants.SCORE] = dat[maxquant_constants.SCORE]\n\n # group ret by user specified method\n if args.groupMethod != 0:\n group_cols = [tsv_constants.PRECURSOR_FILE, tsv_constants.SEQUENCE]\n group_method = 'Grouping by {}, {}'.format(tsv_constants.PRECURSOR_FILE, tsv_constants.SEQUENCE)\n if args.groupMethod == 2:\n group_cols.append(tsv_constants.CHARGE)\n group_method += ', and {}'.format(tsv_constants.CHARGE)\n sys.stdout.write('{}.\\n'.format(group_method))\n idx = ret.groupby(group_cols, sort=False)[tsv_constants.SCORE].transform(max) == ret[tsv_constants.SCORE]\n ret = ret[idx]\n ret = ret.drop_duplicates(subset=group_cols, keep='first')\n\n sys.stdout.write('Writing {}...'.format(ofname))\n ret.to_csv(ofname, sep='\\t', index=False)\n sys.stdout.write(' Done!\\n')\n\n\nif __name__ == '__main__':\n main()\n\n\n"
] | [
[
"pandas.read_csv",
"pandas.Series",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
akshat2048/MSOE_ML | [
"78d8d5753d70bb72b36df44926c95a808ad12f53"
] | [
"pytorch/denseNet121Test/DenseNet121.py"
] | [
"import torch\nmodel = torch.hub.load('pytorch/vision:v0.10.0', 'densenet121', pretrained=True)"
] | [
[
"torch.hub.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
has2k1/scikit-misc | [
"21f88c85dc7f4b88b26a85ad228e825dc98018ec"
] | [
"skmisc/loess/tests/test_loess.py"
] | [
"import os\n\nimport pytest\nimport numpy as np\nimport numpy.testing as npt\n\nfrom skmisc.loess import loess, loess_anova\n\ndata_path = os.path.dirname(os.path.abspath(__file__))\n\n\ndef madeup_data():\n dfile = os.path.join(data_path, 'madeup_data')\n rfile = os.path.join(data_path, 'madeup_result')\n\n with open(dfile, 'r') as f:\n f.readline()\n x = np.fromiter(\n (float(v) for v in f.readline().rstrip().split()),\n np.float_).reshape(-1, 2)\n f.readline()\n y = np.fromiter(\n (float(v) for v in f.readline().rstrip().split()),\n np.float_)\n\n results = []\n with open(rfile, 'r') as f:\n for i in range(8):\n f.readline()\n z = np.fromiter(\n (float(v) for v in f.readline().rstrip().split()),\n np.float_)\n results.append(z)\n\n newdata1 = np.array([[-2.5, 0.], [2.5, 0.], [0., 0.]])\n newdata2 = np.array([[-0.5, 0.5], [0., 0.]])\n return (x, y, results, newdata1, newdata2)\n\n\ndef gas_data():\n NOx = np.array([4.818, 2.849, 3.275, 4.691, 4.255, 5.064, 2.118, 4.602,\n 2.286, 0.970, 3.965, 5.344, 3.834, 1.990, 5.199, 5.283,\n 3.752, 0.537, 1.640, 5.055, 4.937, 1.561])\n E = np.array([0.831, 1.045, 1.021, 0.970, 0.825, 0.891, 0.71, 0.801,\n 1.074, 1.148, 1.000, 0.928, 0.767, 0.701, 0.807, 0.902,\n 0.997, 1.224, 1.089, 0.973, 0.980, 0.665])\n gas_fit_E = np.array([0.665, 0.949, 1.224])\n newdata = np.array([0.6650000, 0.7581667, 0.8513333, 0.9445000,\n 1.0376667, 1.1308333, 1.2240000])\n alpha = 0.01\n\n rfile = os.path.join(data_path, 'gas_result')\n results = []\n with open(rfile, 'r') as f:\n for i in range(8):\n f.readline()\n z = np.fromiter(\n (float(v) for v in f.readline().rstrip().split()),\n np.float_)\n results.append(z)\n return (E, NOx, gas_fit_E, newdata, alpha, results)\n\n\nclass TestLoess2d(object):\n \"Test class for lowess.\"\n d = madeup_data()\n\n def test_2dbasic(self):\n \"2D standard\"\n (x, y, results, _, _) = self.d\n madeup = loess(x, y)\n madeup.model.span = 0.5\n madeup.model.normalize = True\n madeup.fit()\n npt.assert_almost_equal(madeup.outputs.fitted_values, results[0], 5)\n npt.assert_almost_equal(madeup.outputs.enp, 14.9, 1)\n npt.assert_almost_equal(madeup.outputs.residual_scale, 0.9693, 4)\n\n def test_2d_modflags(self):\n \"2D - modification of model flags\"\n (x, y, results, _, _) = self.d\n madeup = loess(x, y)\n madeup.model.span = 0.8\n madeup.model.drop_square = [True, False]\n madeup.model.parametric = [True, False]\n npt.assert_equal(madeup.model.parametric[:2], [1, 0])\n madeup.fit()\n npt.assert_almost_equal(madeup.outputs.fitted_values, results[1], 5)\n npt.assert_almost_equal(madeup.outputs.enp, 6.9, 1)\n npt.assert_almost_equal(madeup.outputs.residual_scale, 1.4804, 4)\n\n def test_2d_modfamily(self):\n \"2D - family modification\"\n (x, y, results, _, _) = self.d\n madeup = loess(x, y)\n madeup.model.span = 0.8\n madeup.model.drop_square = [True, False]\n madeup.model.parametric = [True, False]\n madeup.model.family = \"symmetric\"\n madeup.fit()\n npt.assert_almost_equal(madeup.outputs.fitted_values, results[2], 5)\n npt.assert_almost_equal(madeup.outputs.enp, 6.9, 1)\n npt.assert_almost_equal(madeup.outputs.residual_scale, 1.0868, 4)\n\n def test_2d_modnormalize(self):\n \"2D - normalization modification\"\n (x, y, results, _, _) = self.d\n madeup = loess(x, y)\n madeup.model.span = 0.8\n madeup.model.drop_square = [True, False]\n madeup.model.parametric = [True, False]\n madeup.model.family = \"symmetric\"\n madeup.model.normalize = False\n madeup.fit()\n npt.assert_almost_equal(madeup.outputs.fitted_values, results[3], 5)\n npt.assert_almost_equal(madeup.outputs.enp, 6.9, 1)\n npt.assert_almost_equal(madeup.outputs.residual_scale, 1.0868, 4)\n\n def test_2d_pred_nostderr(self):\n \"2D prediction - no stderr\"\n (x, y, results, newdata1, _) = self.d\n madeup = loess(x, y)\n madeup.model.span = 0.5\n madeup.model.normalize = True\n prediction = madeup.predict(newdata1, stderror=False)\n npt.assert_almost_equal(prediction.values, results[4], 5)\n #\n prediction = madeup.predict(newdata1, stderror=False)\n npt.assert_almost_equal(prediction.values, results[4], 5)\n\n def test_2d_pred_nodata(self):\n \"2D prediction - nodata\"\n (x, y, _, _, _) = self.d\n madeup = loess(x, y)\n try:\n madeup.predict(None)\n except ValueError:\n pass\n else:\n raise AssertionError(\"The test should have failed\")\n\n def test_2d_pred_stderr(self):\n \"2D prediction - w/ stderr\"\n (x, y, results, _, newdata2) = self.d\n madeup = loess(x, y)\n madeup.model.span = 0.5\n madeup.model.normalize = True\n prediction = madeup.predict(newdata2, stderror=True)\n npt.assert_almost_equal(prediction.values, results[5], 5)\n npt.assert_almost_equal(prediction.stderr, [0.276746, 0.278009], 5)\n npt.assert_almost_equal(prediction.residual_scale, 0.969302, 6)\n npt.assert_almost_equal(prediction.df, 81.2319, 4)\n\n # Direct access\n prediction = madeup.predict(newdata2, stderror=True)\n npt.assert_almost_equal(prediction.values, results[5], 5)\n npt.assert_almost_equal(prediction.stderr, [0.276746, 0.278009], 5)\n npt.assert_almost_equal(prediction.residual_scale, 0.969302, 6)\n npt.assert_almost_equal(prediction.df, 81.2319, 4)\n\n def test_2d_pred_confinv(self):\n \"2D prediction - confidence\"\n (x, y, results, _, newdata2) = self.d\n madeup = loess(x, y)\n madeup.model.span = 0.5\n madeup.model.normalize = True\n prediction = madeup.predict(newdata2, stderror=True)\n ci = prediction.confidence(alpha=0.01)\n npt.assert_almost_equal(ci.lower, results[6][::3], 5)\n npt.assert_almost_equal(ci.fit, results[6][1::3], 5)\n npt.assert_almost_equal(ci.upper, results[6][2::3], 5)\n\n\nclass TestLoessGas(object):\n \"Test class for lowess.\"\n\n d = gas_data()\n\n def test_1dbasic(self):\n \"Basic test 1d\"\n (E, NOx, _, _, _, results) = self.d\n gas = loess(E, NOx)\n gas.model.span = 2./3.\n gas.fit()\n npt.assert_almost_equal(gas.outputs.fitted_values, results[0], 6)\n npt.assert_almost_equal(gas.outputs.enp, 5.5, 1)\n npt.assert_almost_equal(gas.outputs.residual_scale, 0.3404, 4)\n\n def test_1dbasic_alt(self):\n \"Basic test 1d - part #2\"\n (E, NOx, _, _, _, results) = self.d\n gas_null = loess(E, NOx)\n gas_null.model.span = 1.0\n gas_null.fit()\n npt.assert_almost_equal(gas_null.outputs.fitted_values, results[1], 6)\n npt.assert_almost_equal(gas_null.outputs.enp, 3.5, 1)\n npt.assert_almost_equal(gas_null.outputs.residual_scale, 0.5197, 4)\n\n def test_1dpredict(self):\n \"Basic test 1d - prediction\"\n (E, NOx, gas_fit_E, _, _, results) = self.d\n gas = loess(E, NOx, span=2./3.)\n gas.fit()\n predicted = gas.predict(gas_fit_E, stderror=False).values\n npt.assert_almost_equal(predicted, results[2], 6)\n\n def test_1dpredict_2(self):\n \"Basic test 1d - new predictions\"\n (E, NOx, _, newdata, _, results) = self.d\n # gas = loess(E, NOx, span=2./3.)\n gas = loess(E, NOx)\n gas.model.span = 2./3.\n prediction = gas.predict(newdata, stderror=True)\n ci = prediction.confidence(alpha=0.01)\n npt.assert_almost_equal(ci.lower, results[3][0::3], 6)\n npt.assert_almost_equal(ci.fit, results[3][1::3], 6)\n npt.assert_almost_equal(ci.upper, results[3][2::3], 6)\n\n def test_anova(self):\n \"Tests anova\"\n (E, NOx, _, _, _, results) = self.d\n gas = loess(E, NOx, span=2./3.)\n gas.fit()\n gas_null = loess(E, NOx, span=1.0)\n gas_null.fit()\n gas_anova = loess_anova(gas, gas_null)\n gas_anova_theo = results[4]\n npt.assert_almost_equal(gas_anova.dfn, gas_anova_theo[0], 5)\n npt.assert_almost_equal(gas_anova.dfd, gas_anova_theo[1], 5)\n npt.assert_almost_equal(gas_anova.F_value, gas_anova_theo[2], 5)\n npt.assert_almost_equal(gas_anova.Pr_F, gas_anova_theo[3], 5)\n\n def test_failures(self):\n \"Tests failures\"\n (E, NOx, gas_fit_E, _, _, _) = self.d\n gas = loess(E, NOx, span=2./3.)\n # This one should fail (all parametric)\n gas.model.parametric = True\n with pytest.raises(ValueError):\n gas.fit()\n\n # This one also (all drop_square)\n gas.model.drop_square = True\n with pytest.raises(ValueError):\n gas.fit()\n\n gas.model.degree = 1\n with pytest.raises(ValueError):\n gas.fit()\n\n # This one should not (revert to std)\n gas.model.parametric = False\n gas.model.drop_square = False\n gas.model.degree = 2\n gas.fit()\n\n # Now, for predict .................\n prediction = gas.predict(gas_fit_E, stderror=False)\n # This one should fail (extrapolation & blending)\n with pytest.raises(ValueError):\n gas.predict(prediction.values, stderror=False)\n\n # But this one should not ..........\n gas.predict(gas_fit_E, stderror=False)\n"
] | [
[
"numpy.testing.assert_almost_equal",
"numpy.array",
"numpy.testing.assert_equal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kkirtac/ms-tcn | [
"9905a3342d8f7fe2157b0dd8cda87bf6d2c84d62"
] | [
"dataset.py"
] | [
"import copy\nimport os\nimport pandas as pd\nimport torch\nimport torch.utils.data as data\nfrom tqdm import tqdm\nimport numpy as np\n\n\ndef load_feature_from_index(video_feat_path, frame_index):\n feat_path = os.path.join(video_feat_path, 'image_{:06d}.npy'.format(frame_index))\n\n if os.path.exists(feat_path):\n return np.load(feat_path)\n else:\n return None\n\n\ndef load_features_from_index(video_feat_path, frame_indices):\n \"\"\"\n loads and returns given frame indices as a list of image objects.\n \"\"\"\n video = []\n\n for frame_index in frame_indices:\n video.append(load_feature_from_index(video_feat_path, frame_index))\n\n stack = np.row_stack(video)\n\n return stack\n\n\nclass FeatureDataset(data.Dataset):\n \"\"\"\n Given a video, stack its i3d feature vectors in columns.\n\n Attributes:\n annotation_video_mapping (dict): Dictionary mapping each annotation file path to a video folder path. Both\n paths must be absolute.\n class2idx (dict): mapping from str class names to integer class indices.\n sampling_step (int): Number of steps to sample a frame from given frames.\n num_classes (int): Number of class labels.\n temporal_transform (torchvision.transforms.Compose): Compose object which contains several transforms\n to be applied sequentially. Please check src.transforms.temporal_transforms.py.\n \"\"\"\n\n def __init__(self, annotation_video_mapping, class2idx, sampling_step, num_classes, temporal_transform=None):\n \"\"\"\n The constructor for I3dFeatureDataset class.\n\n :param dict annotation_video_mapping: Dictionary mapping each annotation file path to a video folder path.\n Both paths should be absolute.\n :param dict class2idx: mapping from str class names to integer class indices.\n :param int sampling_step: Number of steps to sample a frame from given frames.\n :param int num_classes: Number of class labels.\n :param torchvision.transforms.Compose temporal_transform: Compose object which contains several transforms\n to be applied sequentially. Please check src.transforms.temporal_transforms.py.\n \"\"\"\n # some consistency checks\n if not isinstance(annotation_video_mapping, dict):\n raise ValueError('annotation_video_mapping {} should be a dict value'.format(annotation_video_mapping))\n\n self.annotation_video_mapping = annotation_video_mapping\n\n if not isinstance(class2idx, dict):\n raise ValueError('class2idx should be a dict of str to int values')\n\n self.class2idx = class2idx\n\n self.sampling_step = sampling_step\n\n self.temporal_transform = temporal_transform\n\n self.num_classes = num_classes\n\n self.data = self._make_dataset()\n\n def gen_data(self):\n\n for annot_filepath, video_dirpath in tqdm(self.annotation_video_mapping.items()):\n\n # read annotation file as a dataframe\n df = pd.read_csv(annot_filepath)\n\n # optionally downsample video along time axis\n if self.sampling_step > 1:\n df = df.iloc[0:-1:self.sampling_step, :]\n\n # filenames are in image_{:06d}.npy format\n # extract existing frame indices from file names\n frame_indices = [int(f.split('_')[1].split('.')[0]) for f in os.listdir(video_dirpath) if\n f.endswith('.npy')]\n\n yield df.loc[df.frame.isin(frame_indices) & df.phase.isin(self.class2idx.keys())], video_dirpath\n\n def _make_dataset(self):\n \"\"\"\n Construct dataset of samples.\n\n The dictionary \"annotation_video_mapping\" maps each full path to an annotation file to its respective\n video directory path. Both paths are supposed to be absolute paths. In each video directory path, we expect\n video frames should have been extracted and present.\n\n Each annotation file is supposed to be in a csv format which contains a frame index denoted by \"Frame\"\n column name and a class label (phase) denoted by \"Phase\" column name at each of its row.\n\n :return: list of samples (dataset)\n \"\"\"\n dataset = []\n\n for df, video_dirpath in self.gen_data():\n sample_init = {\n 'video': video_dirpath\n }\n\n labels = [self.class2idx[label] for label in df.phase]\n\n sample = copy.deepcopy(sample_init)\n\n sample['frame_indices'] = list(df.frame)\n\n sample['label'] = labels\n\n dataset.append(sample)\n\n return dataset\n\n def __getitem__(self, index):\n \"\"\"\n Loads frames using the subclip indices and their respective target, and returns them as a tuple.\n\n :param int index: index of the returned sample\n :return: tuple (sample, target)\n \"\"\"\n video_path = self.data[index]['video']\n\n frame_indices = self.data[index]['frame_indices']\n\n if self.temporal_transform is not None:\n frame_indices = self.temporal_transform(frame_indices)\n\n # feature vectors stacked in rows -> [L, 1024]\n clip = load_features_from_index(video_path, frame_indices)\n\n clip = torch.tensor(clip)\n\n target = self.data[index]['label']\n\n target = torch.LongTensor(target)\n\n return clip, target, self.num_classes\n\n def __len__(self):\n return len(self.data)\n\n\nclass PadSequence:\n def __call__(self, batch):\n # Let's assume that each element in \"batch\" is a tuple (data, label).\n # Sort the batch in the descending order\n sorted_batch = sorted(batch, key=lambda x: x[0].shape[0], reverse=True)\n\n # Get each sequence and pad it\n sequences = [x[0] for x in sorted_batch]\n labels = [x[1] for x in sorted_batch]\n\n sequences_padded = torch.nn.utils.rnn.pad_sequence(sequences, batch_first=True)\n labels_padded = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=-1)\n\n # the third element in the batch tuple is \"num_classes\"\n num_classes = batch[0][2]\n\n # here we define a mask to mark the padded entries as \"zero\"\n mask = torch.zeros(len(batch), 1, labels_padded.shape[1], dtype=torch.float)\n\n mask[:, 0, :] = (labels_padded != -1)\n\n mask = mask.repeat(1, num_classes, 1)\n\n # feature vectors stacked in columns -> [batch_size, n_channels, L]\n sequences_padded = sequences_padded.permute(0, 2, 1)\n\n return sequences_padded, labels_padded, mask\n"
] | [
[
"torch.LongTensor",
"pandas.read_csv",
"torch.nn.utils.rnn.pad_sequence",
"torch.tensor",
"numpy.row_stack",
"numpy.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
kangkang59812/GCNCaption | [
"25314dbf17e67fe0b39acae554f99817e8f02be1"
] | [
"models/gcn/relaAttention.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ScaledDotProductAttention(nn.Module):\n ''' Scaled Dot-Product Attention '''\n\n def __init__(self, temperature, attn_dropout=0.0):\n super().__init__()\n self.temperature = temperature\n self.dropout = nn.Dropout(attn_dropout)\n\n def forward(self, q, k, v, mask=None):\n\n attn = torch.matmul(q / self.temperature, k.transpose(3, 4))\n if mask is not None:\n attn = attn.masked_fill(mask.unsqueeze(1).unsqueeze(\n 1).unsqueeze(1) == 0, -1e9)\n\n attn = self.dropout(F.softmax(attn, dim=-1))\n output = torch.matmul(attn, v)\n\n return output\n\n\nclass RelationMultiHeadAttention(nn.Module):\n ''' Multi-Head Attention module '''\n\n def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):\n super().__init__()\n\n self.n_head = n_head\n self.d_k = d_k\n self.d_v = d_v\n\n self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)\n self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)\n self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)\n # self.fc = nn.Linear(n_head * d_v, 64, bias=False)\n self.rela_p = nn.Linear(n_head * d_v, 1)\n self.attention = ScaledDotProductAttention(temperature=d_k ** 0.5)\n\n # self.dropout = nn.Dropout(dropout)\n\n def forward(self, q, k, v, mask=None):\n\n d_k, d_v, n_head = self.d_k, self.d_v, self.n_head\n sz_b, num_obj, len_q, len_k, len_v = q.size(\n 0), q.size(1), q.size(2), k.size(2), v.size(2)\n\n # Pass through the pre-attention projection: b x lq x (n*dv)\n # Separate different heads: b x lq x n x dv\n q = self.w_qs(q).view(sz_b, num_obj, len_q, n_head, d_k)\n k = self.w_ks(k).view(sz_b, num_obj, len_k, n_head, d_k)\n v = self.w_vs(v).view(sz_b, num_obj, len_v, n_head, d_v)\n\n # Transpose for attention dot product: b x n x lq x dv\n q, k, v = q.transpose(2, 3), k.transpose(2, 3), v.transpose(2, 3)\n\n q = self.attention(q, k, v, mask=mask)\n\n # Transpose to move the head dimension back: b x lq x n x dv\n # Combine the last two dimensions to concatenate all the heads together: b x lq x (n*dv)\n q = q.transpose(2, 3).contiguous().view(sz_b, num_obj, len_q, -1)\n\n p = self.rela_p(q).squeeze(-1)\n\n return q, p\n"
] | [
[
"torch.nn.Linear",
"torch.matmul",
"torch.nn.Dropout",
"torch.nn.functional.softmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
useanalias/logistic | [
"9ac196af82bf2d2dbf4e171c7b340c308ed40ad6"
] | [
"logistic/utils.py"
] | [
"import numpy as np\n\n\ndef gradient_descent(cost_func, grad_func, m, alpha=1e-5, beta=1e-7, epsilon=1e-6):\n theta = 2 * (np.random.rand(m) - 0.5) * beta\n cost = cost_func(theta)\n while True:\n delta = alpha * grad_func(theta)\n print(\"WAT\")\n print(cost)\n theta -= delta\n new_cost = cost_func(theta)\n print(np.abs(new_cost - cost))\n if np.abs(new_cost - cost) < epsilon:\n break\n cost = new_cost\n return theta\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef hypothesis(X, theta):\n X, theta = np.asarray(X), np.asarray(theta)\n if X.size == 0 or theta.size == 0:\n return np.array([]) # np.dot([], []) returns 0\n return sigmoid(np.dot(theta, np.transpose(X)))\n"
] | [
[
"numpy.abs",
"numpy.asarray",
"numpy.random.rand",
"numpy.transpose",
"numpy.exp",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sudo-michael/gail-airl-ppo.pytorch | [
"5864ea9a0d1f4ab533aadc869cbb1ac0fe6ce927"
] | [
"gail_airl_ppo/network/utils.py"
] | [
"import math\nimport torch\nfrom torch import nn\n\n\ndef build_mlp(\n input_dim,\n output_dim,\n hidden_units=[64, 64],\n hidden_activation=nn.Tanh(),\n output_activation=None,\n):\n layers = []\n units = input_dim\n for next_units in hidden_units:\n layers.append(nn.Linear(units, next_units))\n layers.append(hidden_activation)\n units = next_units\n layers.append(nn.Linear(units, output_dim))\n if output_activation is not None:\n layers.append(output_activation)\n return nn.Sequential(*layers)\n\n\ndef calculate_log_pi(log_stds, noises, actions):\n gaussian_log_probs = (-0.5 * noises.pow(2) - log_stds).sum(\n dim=-1, keepdim=True\n ) - 0.5 * math.log(2 * math.pi) * log_stds.size(-1)\n\n return gaussian_log_probs - torch.log(1 - actions.pow(2) + 1e-6).sum(\n dim=-1, keepdim=True\n )\n\n\ndef reparameterize(means, log_stds):\n noises = torch.randn_like(means)\n us = means + noises * log_stds.exp()\n actions = torch.tanh(us)\n return actions, calculate_log_pi(log_stds, noises, actions)\n\n\ndef atanh(x):\n return 0.5 * (torch.log(1 + x + 1e-6) - torch.log(1 - x + 1e-6))\n\n\ndef evaluate_lop_pi(means, log_stds, actions):\n noises = (atanh(actions) - means) / (log_stds.exp() + 1e-8)\n return calculate_log_pi(log_stds, noises, actions)\n"
] | [
[
"torch.randn_like",
"torch.nn.Sequential",
"torch.nn.Tanh",
"torch.tanh",
"torch.nn.Linear",
"torch.log"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Hyunsooooo/silent_speech1 | [
"03f69576f6c6b984340c1ddef2288e3f7d1102ca"
] | [
"pytorch/integration_test.py"
] | [
"# *****************************************************************************\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the NVIDIA CORPORATION nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# *****************************************************************************\n\"\"\"\nTests that the NV-WaveNet class is producing audio\n\"\"\"\nimport torch\nfrom scipy.io.wavfile import write\nimport nv_wavenet\nfrom wavenet import WaveNet\nimport utils\nimport json\n\nif __name__ == '__main__':\n config = json.loads(open('config.json').read())\n wavenet_config = config[\"wavenet_config\"]\n model = WaveNet(**wavenet_config).cuda()\n weights = model.export_weights()\n wavenet = nv_wavenet.NVWaveNet(**weights)\n num_samples = 10*1000\n batch_size = config['train_config']['batch_size']\n cond_input = torch.zeros([2 * wavenet_config['n_residual_channels'], batch_size, wavenet_config['n_layers'], num_samples]).cuda()\n\n samples = wavenet.infer(cond_input, nv_wavenet.Impl.PERSISTENT)[0]\n \n audio = utils.mu_law_decode_numpy(samples.cpu().numpy(), 256)\n audio = utils.MAX_WAV_VALUE * audio\n wavdata = audio.astype('int16')\n write('audio.wav',16000, wavdata)\n"
] | [
[
"scipy.io.wavfile.write",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
daidaiershidi/Paddle | [
"b7bcd0f643b90e87da749251011e364e3681e5d7"
] | [
"python/paddle/fluid/tests/unittests/auto_parallel/test_auto_parallel_while_op.py"
] | [
"# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport paddle\nimport numpy as np\nimport paddle.nn as nn\nimport paddle.utils as utils\nimport paddle.fluid as fluid\nimport paddle.static as static\nimport paddle.nn.functional as F\nimport paddle.distributed.auto_parallel as auto\n\nfrom paddle.distributed import fleet\n\nfrom paddle.distributed.auto_parallel.partitioner import Partitioner\nfrom paddle.distributed.auto_parallel.utils import make_data_unshard\nfrom paddle.distributed.auto_parallel.dist_attribute import OperatorDistributedAttribute, TensorDistributedAttribute\nfrom paddle.distributed.auto_parallel.dist_context import DistributedContext, get_default_distributed_context\nfrom paddle.distributed.auto_parallel.operators import find_best_compatible_distributed_operator_impl\n\npaddle.enable_static()\n\nbatch_size = 4\nepoch_num = 10\nhidden_size = 1024\nsequence_len = 512\n_g_process_mesh = auto.ProcessMesh([0, 1])\n\n\ndef get_random_inputs_and_labels(input_shape, label_shape):\n input = np.random.random(size=input_shape).astype('float32')\n label = np.random.random(size=label_shape).astype('float32')\n return input, label\n\n\ndef batch_generator_creator():\n def __reader__():\n for _ in range(batch_size):\n batch_input, batch_label = get_random_inputs_and_labels(\n [batch_size, sequence_len, hidden_size],\n [batch_size, sequence_len, 1])\n yield batch_input, batch_label\n\n return __reader__\n\n\nclass MLPLayer(nn.Layer):\n def __init__(self,\n hidden_size=1024,\n intermediate_size=4 * 1024,\n dropout_ratio=0.1,\n initializer_range=0.02):\n super(MLPLayer, self).__init__()\n d_model = hidden_size\n dim_feedforward = intermediate_size\n param_initializer = nn.initializer.Normal(\n mean=0.0, std=initializer_range)\n\n self.norm = nn.LayerNorm(d_model, epsilon=1e-5)\n self.linear0 = nn.Linear(\n d_model,\n dim_feedforward,\n weight_attr=paddle.ParamAttr(initializer=param_initializer),\n bias_attr=None)\n self.linear1 = nn.Linear(\n dim_feedforward,\n d_model,\n weight_attr=paddle.ParamAttr(initializer=param_initializer),\n bias_attr=None)\n\n def forward(self, input):\n\n auto.shard_tensor(\n self.norm.weight,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1]})\n auto.shard_tensor(\n self.norm.bias,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1]})\n auto.shard_tensor(\n self.linear0.weight,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, 0]\n })\n auto.shard_tensor(\n self.linear0.bias,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [0]})\n auto.shard_tensor(\n self.linear1.weight,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [0, -1]\n })\n auto.shard_tensor(\n self.linear1.bias,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1]})\n\n out = self.norm(input)\n auto.shard_tensor(\n out,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n out = self.linear0(out)\n auto.shard_tensor(\n out,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, 0]\n })\n out = F.gelu(out, approximate=True)\n auto.shard_tensor(\n out,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, 0]\n })\n out = self.linear1(out)\n auto.shard_tensor(\n out,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n\n return out\n\n\ndef get_program():\n dist_strategy = fleet.DistributedStrategy()\n dist_strategy.semi_auto = True\n # fleet.init(is_collective=True, strategy=dist_strategy)\n\n train_program = static.Program()\n start_program = static.Program()\n with fluid.program_guard(train_program, start_program):\n\n # 循环计数器\n i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)\n auto.shard_tensor(\n i,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1]})\n\n # 循环次数\n loop_len = fluid.layers.fill_constant(\n shape=[1], dtype='int64', value=epoch_num)\n auto.shard_tensor(\n loop_len,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1]})\n\n # input\n input = static.data(\n name=\"input\",\n shape=[batch_size, sequence_len, hidden_size],\n dtype='float32')\n label = static.data(\n name=\"label\", shape=[batch_size, sequence_len, 1], dtype='float32')\n data_holder = [input, label]\n # dataloader\n dataloader = paddle.io.DataLoader.from_generator(\n feed_list=data_holder, capacity=4 * batch_size, iterable=False)\n dataloader.set_batch_generator(\n batch_generator_creator(), places=paddle.static.cuda_places())\n # data dist_attr\n auto.shard_tensor(\n input,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n auto.shard_tensor(\n label,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n\n mlp_start = MLPLayer(\n hidden_size=hidden_size,\n intermediate_size=4 * hidden_size,\n dropout_ratio=0.1,\n initializer_range=0.02)\n pred = mlp_start(input)\n\n input_array = fluid.layers.array_write(pred, i)\n auto.shard_tensor(\n input_array,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n\n cond = fluid.layers.less_than(x=i, y=loop_len)\n auto.shard_tensor(\n cond,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1]})\n\n while_op = fluid.layers.While(cond=cond)\n with while_op.block():\n\n pre_input = fluid.layers.array_read(array=input_array, i=i)\n auto.shard_tensor(\n pre_input,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n\n mlp_while = MLPLayer(\n hidden_size=hidden_size,\n intermediate_size=4 * hidden_size,\n dropout_ratio=0.1,\n initializer_range=0.02)\n cur_pred = mlp_while(pre_input)\n\n # 更新循环条件\n i = fluid.layers.increment(x=i, value=1, in_place=True)\n fluid.layers.array_write(cur_pred, array=input_array, i=i)\n fluid.layers.less_than(x=i, y=loop_len, cond=cond)\n\n end_pred = fluid.layers.array_read(array=input_array, i=i)\n auto.shard_tensor(\n end_pred,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n\n mlp_end = MLPLayer(\n hidden_size=hidden_size,\n intermediate_size=4 * hidden_size,\n dropout_ratio=0.1,\n initializer_range=0.02)\n pred = mlp_end(end_pred)\n\n error_cost = paddle.nn.functional.square_error_cost(pred, label)\n auto.shard_tensor(\n error_cost,\n dist_attr={\n \"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1, -1, -1]\n })\n\n loss = paddle.mean(error_cost)\n auto.shard_tensor(\n loss,\n dist_attr={\"process_mesh\": _g_process_mesh,\n \"dims_mapping\": [-1]})\n\n return train_program, start_program, dataloader, i, loss\n\n\ndef completion(train_program, start_program, dist_context):\n blocks = train_program.blocks\n # completion tensors\n for block in blocks:\n for op in block.ops:\n if op.type == \"layer_norm\":\n for out_name in op.output_arg_names:\n out_var = block.vars[out_name]\n tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n out_var)\n if tensor_dist_attr:\n continue\n tensor_dist_attr = TensorDistributedAttribute()\n tensor_dist_attr.process_mesh = _g_process_mesh\n tensor_dist_attr.dims_mapping = [-1]\n dist_context.set_tensor_dist_attr_for_program(\n out_var, tensor_dist_attr)\n\n elif op.type == \"elementwise_sub\":\n for out_name in op.output_arg_names:\n out_var = block.vars[out_name]\n tensor_dist_attr = TensorDistributedAttribute()\n tensor_dist_attr.process_mesh = _g_process_mesh\n tensor_dist_attr.dims_mapping = [-1, -1, -1]\n dist_context.set_tensor_dist_attr_for_program(\n out_var, tensor_dist_attr)\n\n elif op.type == \"matmul_v2\":\n col = False\n for in_name in op.input_arg_names:\n if \".w_\" not in in_name:\n continue\n if in_name not in block.vars:\n in_var = blocks[0].vars[in_name]\n else:\n in_var = block.vars[in_name]\n tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n in_var)\n assert tensor_dist_attr is not None\n if tensor_dist_attr.dims_mapping == [-1, 0]:\n col = True\n for out_name in op.output_arg_names:\n out_var = block.vars[out_name]\n tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n out_var)\n if tensor_dist_attr:\n continue\n tensor_dist_attr = TensorDistributedAttribute()\n tensor_dist_attr.process_mesh = _g_process_mesh\n if col:\n tensor_dist_attr.dims_mapping = [-1, -1, 0]\n else:\n tensor_dist_attr.dims_mapping = [-1, -1, -1]\n dist_context.set_tensor_dist_attr_for_program(\n out_var, tensor_dist_attr)\n elif op.type == \"while\":\n out_name = op.desc.output(\"StepScopes\")[0]\n out_var = block.vars[out_name]\n tensor_dist_attr = TensorDistributedAttribute()\n tensor_dist_attr.process_mesh = _g_process_mesh\n tensor_dist_attr.dims_mapping = [-1]\n dist_context.set_tensor_dist_attr_for_program(out_var,\n tensor_dist_attr)\n\n # completion ops\n for block in blocks:\n for op in block.ops:\n op_dist_attr = OperatorDistributedAttribute()\n op_dist_attr.process_mesh = _g_process_mesh\n if op.type == \"create_by_read\" or op.type == \"create_double_buffer_reader\":\n for in_name in op.input_arg_names:\n op_dist_attr.set_input_dims_mapping(in_name, [])\n for out_name in op.output_arg_names:\n op_dist_attr.set_output_dims_mapping(out_name, [])\n elif op.type == \"read\":\n for in_name in op.input_arg_names:\n op_dist_attr.set_output_dims_mapping(in_name, [])\n for out_name in op.output_arg_names:\n out_var = block.vars[out_name]\n out_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n out_var)\n op_dist_attr.set_output_dist_attr(out_name, out_dist_attr)\n elif op.type == \"while\":\n for in_name in op.input_arg_names:\n in_var = block.vars[in_name]\n in_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n in_var)\n op_dist_attr.set_input_dist_attr(in_name, in_dist_attr)\n for out_name in op.output_arg_names:\n if out_name == op.desc.output(\"StepScopes\")[0]:\n op_dist_attr.set_output_dims_mapping(out_name, [])\n else:\n out_var = block.vars[out_name]\n out_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n out_var)\n op_dist_attr.set_output_dist_attr(out_name,\n out_dist_attr)\n else:\n for in_name in op.input_arg_names:\n if in_name == \"lod_tensor_blocking_queue_0\":\n continue\n if in_name not in block.vars:\n in_var = blocks[0].vars[in_name]\n else:\n in_var = block.vars[in_name]\n in_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n in_var)\n op_dist_attr.set_input_dist_attr(in_name, in_dist_attr)\n for out_name in op.output_arg_names:\n if out_name not in block.vars:\n out_var = blocks[0].vars[out_name]\n else:\n out_var = block.vars[out_name]\n out_dist_attr = dist_context.get_tensor_dist_attr_for_program(\n out_var)\n op_dist_attr.set_output_dist_attr(out_name, out_dist_attr)\n\n if op.type == \"matmul_v2\":\n op_dist_attr.impl_type = \"matmul_v2\"\n for in_name in op_dist_attr.inputs_dist_attrs.keys():\n in_dist_attr = op_dist_attr.inputs_dist_attrs[in_name]\n if \".w_\" in in_name and in_dist_attr.dims_mapping[-1] == 0:\n op_dist_attr.impl_idx = 0\n else:\n op_dist_attr.impl_idx = 1\n else:\n op_dist_attr.impl_type = \"default\"\n op_dist_attr.impl_idx = 0\n\n dist_context.set_op_dist_attr_for_program(op, op_dist_attr)\n make_data_unshard(train_program, start_program, dist_context)\n\n return train_program, start_program\n\n\ndef partition(train_program, start_program, dist_context):\n\n # optimizer = paddle.optimizer.SGD(learning_rate=0.00001)\n rank = paddle.distributed.get_rank()\n partitioner = Partitioner(dist_context, rank)\n dist_main_prog, dist_startup_prog, _ = partitioner.partition(\n train_program, start_program, [])\n\n return dist_main_prog, dist_startup_prog\n\n\nclass TestMLP(unittest.TestCase):\n def test_partitioner(self):\n\n train_program, start_program, dataloader, i, loss = get_program()\n dist_context = get_default_distributed_context()\n train_program, start_program = completion(train_program, start_program,\n dist_context)\n dist_context.block_state.parse_forward_blocks(train_program)\n\n dist_main_prog, dist_startup_prog = partition(\n train_program, start_program, dist_context)\n global_block_ops = dist_main_prog.blocks[0].ops\n global_block_ops = [op.type for op in global_block_ops]\n sub_block_ops = dist_main_prog.blocks[1].ops\n sub_block_ops = [op.type for op in sub_block_ops]\n\n self.assertTrue(\"c_allreduce_sum\" in global_block_ops)\n self.assertTrue(\"c_allreduce_sum\" in sub_block_ops)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.random.random"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nse1994/l5kit | [
"80530d6920eebd636e41e30793bcef1110a39f7b"
] | [
"l5kit/l5kit/tests/evaluation/compute_mse_loss_test.py"
] | [
"from pathlib import Path\n\nimport numpy as np\nimport pytest\n\nfrom l5kit.data import ChunkedDataset\nfrom l5kit.evaluation import compute_mse_error_csv, export_zarr_to_ground_truth_csv\n\n\ndef test_compute_mse_error(tmp_path: Path, zarr_dataset: ChunkedDataset) -> None:\n future_num_frames = 12 # coords displacements we want to predict\n\n export_zarr_to_ground_truth_csv(zarr_dataset, str(tmp_path / \"gt1.csv\"), future_num_frames, 0.5)\n export_zarr_to_ground_truth_csv(zarr_dataset, str(tmp_path / \"gt2.csv\"), future_num_frames, 0.5)\n err = compute_mse_error_csv(str(tmp_path / \"gt1.csv\"), str(tmp_path / \"gt2.csv\"))\n assert np.all(err == 0.0)\n\n data_fake = ChunkedDataset(str(tmp_path))\n data_fake.scenes = np.asarray(zarr_dataset.scenes).copy()\n data_fake.frames = np.asarray(zarr_dataset.frames).copy()\n data_fake.agents = np.asarray(zarr_dataset.agents).copy()\n data_fake.agents[\"centroid\"] += np.random.rand(*data_fake.agents[\"centroid\"].shape) * 1e-2\n\n export_zarr_to_ground_truth_csv(data_fake, str(tmp_path / \"gt3.csv\"), future_num_frames, 0.5)\n err = compute_mse_error_csv(str(tmp_path / \"gt1.csv\"), str(tmp_path / \"gt3.csv\"))\n assert np.any(err > 0.0)\n\n # test invalid conf by removing lines in gt1\n with open(str(tmp_path / \"gt4.csv\"), \"w\") as fp:\n lines = open(str(tmp_path / \"gt1.csv\")).readlines()\n fp.writelines(lines[:-10])\n\n with pytest.raises(ValueError):\n compute_mse_error_csv(str(tmp_path / \"gt1.csv\"), str(tmp_path / \"gt4.csv\"))\n"
] | [
[
"numpy.all",
"numpy.random.rand",
"numpy.any",
"numpy.asarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jolynch/python_performance_toolkit | [
"c38abd5b75caf2fde9b6f8d4e0fea1af0411de27"
] | [
"notebooks/queueing_theory/src/latency_aware_simulator.py"
] | [
"import random\nfrom collections import namedtuple\n\nimport numpy as np\nimport simpy\n\nLatencyDatum = namedtuple(\n 'LatencyDatum',\n ('t_queued', 't_processing', 't_total')\n)\n\n\nclass LatencyAwareRequestSimulator(object):\n \"\"\" Simulates a M/G/k process common in request processing (computing)\n\n :param worker_desc: A list of ints of capacities to construct workers with\n :param local_balancer: A function which takes the current request number\n the list of workers and the request time and returns the index of the\n worker to send the next request to\n :param latency_fn: A function which takes the curent request number and\n returns the number of milliseconds a request took to process\n :param number_of_requests: The number of requests to run through the\n simulator\n :param request_per_s: The rate of requests per second.\n \"\"\"\n\n def __init__(\n self, worker_desc, load_balancer, latency_fn,\n number_of_requests, request_per_s):\n self.worker_desc = worker_desc\n self.load_balancer = load_balancer\n self.latency_fn = latency_fn\n self.number_of_requests = int(number_of_requests)\n self.request_interval_ms = 1. / (request_per_s / 1000.)\n self.data = []\n self.requests_per_worker = {}\n\n def simulate(self):\n # Setup and start the simulation\n random.seed(1)\n np.random.seed(1)\n\n self.env = simpy.Environment()\n self.workers = []\n idx = 0\n for cap in self.worker_desc:\n self.workers.append(simpy.Resource(self.env, capacity=cap))\n self.requests_per_worker[idx] = 0\n idx += 1\n self.env.process(self.generate_requests())\n self.env.run()\n\n def generate_requests(self):\n for i in range(self.number_of_requests):\n t_processing = self.latency_fn(i)\n idx = self.load_balancer(i, self.workers, t_processing)\n self.requests_per_worker[idx] += 1\n worker = self.workers[idx]\n response = self.process_request(\n i, worker, t_processing\n )\n self.env.process(response)\n # Exponential inter-arrival times == Poisson\n arrival_interval = random.expovariate(\n 1.0 / self.request_interval_ms\n )\n yield self.env.timeout(arrival_interval)\n\n def process_request(self, request_id, worker, duration):\n \"\"\" Request arrives, possibly queues, and then processes\"\"\"\n t_arrive = self.env.now\n\n with worker.request() as req:\n yield req\n t_start = self.env.now\n t_queued = t_start - t_arrive\n\n yield self.env.timeout(duration)\n\n t_done = self.env.now\n t_processing = t_done - t_start\n t_total_response = t_done - t_arrive\n\n datum = LatencyDatum(t_queued, t_processing, t_total_response)\n self.data.append(datum)\n\n\ndef run_simulation(\n worker_desc, load_balancer, num_requests, request_per_s, latency_fn):\n simulator = LatencyAwareRequestSimulator(\n worker_desc, load_balancer, latency_fn,\n num_requests, request_per_s\n )\n simulator.simulate()\n return simulator.data, simulator.requests_per_worker\n"
] | [
[
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
FrazerClews/audacity | [
"b3539ed2b84e2c678f9e645c55150d6fee0c2ea8"
] | [
"lib-src/lv2/lilv/bindings/python/lv2_apply.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport math\nimport lilv\nimport sys\nimport wave\nimport numpy\n\nclass WavFile(object):\n \"\"\"Helper class for accessing wav file data. Should work on the most common\n formats (8 bit unsigned, 16 bit signed, 32 bit signed). Audio data is\n converted to float32.\"\"\"\n\n # (struct format code, is_signedtype) for each sample width:\n WAV_SPECS = {\n 1: (\"B\", False),\n 2: (\"h\", True),\n 4: (\"l\", True),\n }\n\n def __init__(self, wav_in_path):\n self.wav_in = wave.open(wav_in_path, 'r')\n self.framerate = self.wav_in.getframerate()\n self.nframes = self.wav_in.getnframes()\n self.nchannels = self.wav_in.getnchannels()\n self.sampwidth = self.wav_in.getsampwidth()\n wav_spec = self.WAV_SPECS[self.sampwidth]\n self.struct_fmt_code, self.signed = wav_spec\n self.range = 2 ** (8*self.sampwidth)\n\n def read(self):\n \"\"\"Read data from an open wav file. Return a list of channels, where each\n channel is a list of floats.\"\"\"\n raw_bytes = self.wav_in.readframes(self.nframes)\n struct_fmt = \"%u%s\" % (len(raw_bytes) / self.sampwidth, self.struct_fmt_code)\n data = wave.struct.unpack(struct_fmt, raw_bytes)\n if self.signed:\n data = [i / float(self.range/2) for i in data]\n else:\n data = [(i - float(range/2)) / float(range/2) for i in data]\n\n channels = []\n for i in xrange(self.nchannels):\n channels.append([data[j] for j in xrange(0, len(data), self.nchannels) ])\n\n return channels\n\n def close(self):\n self.wav_in.close()\n\ndef main():\n # Read command line arguments\n if len(sys.argv) != 4:\n print('USAGE: lv2_apply.py PLUGIN_URI INPUT_WAV OUTPUT_WAV')\n sys.exit(1)\n\n # Initialise Lilv\n world = lilv.World()\n world.load_all()\n\n plugin_uri = sys.argv[1]\n wav_in_path = sys.argv[2]\n wav_out_path = sys.argv[3]\n\n # Find plugin\n plugin_uri_node = world.new_uri(plugin_uri)\n plugin = world.get_all_plugins().get_by_uri(plugin_uri_node)\n if not plugin:\n print(\"Unknown plugin `%s'\\n\" % plugin_uri)\n sys.exit(1)\n\n lv2_InputPort = world.new_uri(lilv.LILV_URI_INPUT_PORT)\n lv2_OutputPort = world.new_uri(lilv.LILV_URI_OUTPUT_PORT)\n lv2_AudioPort = world.new_uri(lilv.LILV_URI_AUDIO_PORT)\n lv2_ControlPort = world.new_uri(lilv.LILV_URI_CONTROL_PORT)\n lv2_default = world.new_uri(\"http://lv2plug.in/ns/lv2core#default\")\n\n n_audio_in = plugin.get_num_ports_of_class(lv2_InputPort, lv2_AudioPort)\n n_audio_out = plugin.get_num_ports_of_class(lv2_OutputPort, lv2_AudioPort)\n if n_audio_out == 0:\n print(\"Plugin has no audio outputs\\n\")\n sys.exit(1)\n\n # Open input file\n try:\n wav_in = WavFile(wav_in_path)\n except:\n print(\"Failed to open input `%s'\\n\" % wav_in_path)\n sys.exit(1)\n\n if wav_in.nchannels != n_audio_in:\n print(\"Input has %d channels, but plugin has %d audio inputs\\n\" % (\n wav_in.nchannels, n_audio_in))\n sys.exit(1)\n\n # Open output file\n wav_out = wave.open(wav_out_path, 'w')\n if not wav_out:\n print(\"Failed to open output `%s'\\n\" % wav_out_path)\n sys.exit(1)\n\n # Set output file to same format as input (except possibly nchannels)\n wav_out.setparams(wav_in.wav_in.getparams())\n wav_out.setnchannels(n_audio_out)\n\n print('%s => %s => %s @ %d Hz'\n % (wav_in_path, plugin.get_name(), wav_out_path, wav_in.framerate))\n\n instance = lilv.Instance(plugin, wav_in.framerate)\n\n channels = wav_in.read()\n wav_in.close()\n\n # Connect all ports to buffers. NB if we fail to connect any buffer, lilv\n # will segfault.\n audio_input_buffers = []\n audio_output_buffers = []\n control_input_buffers = []\n control_output_buffers = []\n for index in range(plugin.get_num_ports()):\n port = plugin.get_port_by_index(index)\n if port.is_a(lv2_InputPort):\n if port.is_a(lv2_AudioPort):\n audio_input_buffers.append(numpy.array(channels[len(audio_input_buffers)], numpy.float32))\n instance.connect_port(index, audio_input_buffers[-1])\n elif port.is_a(lv2_ControlPort):\n #if port.has_property(lv2_default): # Doesn't seem to work\n default = lilv.lilv_node_as_float(lilv.lilv_nodes_get_first(port.get_value(lv2_default)))\n control_input_buffers.append(numpy.array([default], numpy.float32))\n instance.connect_port(index, control_input_buffers[-1])\n else:\n raise ValueError(\"Unhandled port type\")\n elif port.is_a(lv2_OutputPort):\n if port.is_a(lv2_AudioPort):\n audio_output_buffers.append(numpy.array([0] * wav_in.nframes, numpy.float32))\n instance.connect_port(index, audio_output_buffers[-1])\n elif port.is_a(lv2_ControlPort):\n control_output_buffers.append(numpy.array([0], numpy.float32))\n instance.connect_port(index, control_output_buffers[-1])\n else:\n raise ValueError(\"Unhandled port type\")\n\n # Run the plugin:\n instance.run(wav_in.nframes)\n\n # Interleave output buffers:\n data = numpy.dstack(audio_output_buffers).flatten()\n\n # Return to original int range:\n if wav_in.signed:\n data = data * float(wav_in.range / 2)\n else:\n data = (data + 1) * float(wav_in.range/2)\n\n # Write output file in chunks to stop memory usage getting out of hand:\n CHUNK_SIZE = 8192\n for chunk in numpy.array_split(data, CHUNK_SIZE):\n wav_out.writeframes(wave.struct.pack(\"%u%s\" % (len(chunk), wav_in.struct_fmt_code), *chunk))\n wav_out.close()\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"numpy.array",
"numpy.array_split",
"numpy.dstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NWC-CUAHSI-Summer-Institute/ml_data_processing | [
"ed74a1cdecfb4f3b9015a652c8c807a87ae6c48b"
] | [
"streamflow/reynolds_creek/reynolds_streamflow.py"
] | [
"import numpy as np\nimport pandas as pd\nimport glob\nimport numbers\n\n# Get all the file paths for the data\nreynolds_files = glob.glob('*.dat')\n\n# The hourly data in Martin's paper uses these headers\nhourly_headers = ['date','QObs(mm/h)','QObs count','qualifiers','utcoffset(h)','(iv-camels)/camels','QObs_CAMELS(mm/h)']\n\n# Set a time period to cut down on file size, mostly for the hourly data\nstart_date = pd.to_datetime('1/1/1980')\nend_date = pd.to_datetime('1/1/2019')\n\n# Loop through the data files and save them in the USGS format\nfor q_file in reynolds_files:\n\n print(q_file)\n\n # The 036 gauge has a different format from the rest, so we treat it as a seperate case\n if q_file == \"reynolds-creek-036-hourly-streamflow.dat\":\n\n # Open the file as a pandas dataframe, this will be imortant for getting the daily averages\n with open(q_file, \"r\") as f:\n df = pd.read_csv(f, delim_whitespace=True, index_col=None)\n \n # Remove the index, since the index (days) has duplicates (24, one for each hour in the day)\n df = df.reset_index()\n \n # Remove the first and last value of the dataframe, because there is some funky formatting\n df = df.iloc[1:-1,:]\n \n # Fill in some additional columns. Make sure all the values are numeric.\n df['Hour'] = [int(df.datetime[i].split(':')[0]) for i in df.index.values]\n df['qcms'] = [float(df.loc[i,'qcms']) for i in df.index.values]\n df['Year'] = [int(df.loc[i,'Year']) for i in df.index.values]\n df['datetime'] = pd.to_datetime(df[['Year', 'Month', 'Day', 'Hour']])\n df['date'] = pd.to_datetime(df[['Year', 'Month', 'Day']])\n \n # Now set the index to datetime, so we can get the averages easily\n df = df.set_index('datetime')\n \n # Cut the dataframe to the start and end dates\n df = df.loc[start_date:end_date,:]\n \n #####################################################################\n ############ GET THE MEAN DAILY VALUE #########################\n df_daily = df.resample('D').mean() #########################\n ############ GET THE MEAN DAILY VALUE #########################\n #####################################################################\n \n # The gauge id is part of the file name, so add it to the \"full\" id\n df_daily['basin_id'] = 'RC13172'+q_file.split('-')[2]\n \n # This probably isn't neccessary, but the USGS streamflow values have a quality flag. This is a fake flag.\n df_daily['flag'] = 'si'\n \n # Convert the data from cubic meter per second to cubic feet per second\n df_daily['qcfs'] = df_daily['qcms'] * 35.3147\n \n # Extract just the columns we need, and make sure the dates are integers, just in case.\n df_daily = df_daily[['basin_id', 'Year', 'Month', 'Day', 'qcfs', 'flag']] \n df_daily['Year'] = [int(df_daily.loc[i,'Year']) for i in df_daily.index.values]\n df_daily['Month'] = [int(df_daily.loc[i,'Month']) for i in df_daily.index.values]\n df_daily['Day'] = [int(df_daily.loc[i,'Day']) for i in df_daily.index.values]\n \n #####################################################################\n ############ WRITE THE OUPUT TO CSV FILE ################\n ############ FORMATTED AS THE OTHER STREAMFLOWS ################\n df_daily.to_csv('{}_streamflow_qc.txt'.format(df_daily.basin_id[1]), sep=' ', header=False, index=False)\n\n else:\n\n # Open the file as a pandas dataframe, this will be imortant for getting the daily averages\n with open(q_file, \"r\") as f:\n df = pd.read_csv(f, index_col=None)\n \n # Remove the index, since the index (days) has duplicates (24, one for each hour in the day)\n df = df.reset_index()\n \n # Remove the first and last value of the dataframe, because there is some funky formatting\n df = df.iloc[1:-1,:]\n \n # Fill in some additional columns. Make sure all the values are numeric.\n df['qcms'] = [float(df.loc[i,'qcms']) for i in df.index.values]\n df['Year'] = [pd.to_datetime(df.loc[i,'datetime']).year for i in df.index.values]\n df['Month'] = [pd.to_datetime(df.loc[i,'datetime']).month for i in df.index.values]\n df['Day'] = [pd.to_datetime(df.loc[i,'datetime']).day for i in df.index.values]\n df['Hour'] = [pd.to_datetime(df.loc[i,'datetime']).hour for i in df.index.values]\n df['datetime'] = pd.to_datetime(df[['Year', 'Month', 'Day', 'Hour']])\n df['date'] = pd.to_datetime(df[['Year', 'Month', 'Day']])\n \n # Now set the index to datetime, so we can get the averages easily\n df = df.set_index('datetime')\n \n # Cut the dataframe to the start and end dates\n df = df.loc[start_date:end_date,:]\n \n #####################################################################\n ############ GET THE MEAN DAILY VALUE #########################\n df_daily = df.resample('D').mean() #########################\n ############ GET THE MEAN DAILY VALUE #########################\n #####################################################################\n \n # The gauge id is part of the file name, so add it to the \"full\" id\n df_daily['basin_id'] = 'RC13172'+q_file.split('-')[2]\n \n # This probably isn't neccessary, but the USGS streamflow values have a quality flag. This is a fake flag.\n df_daily['flag'] = 'si'\n \n # Convert the data from cubic meter per second to cubic feet per second\n df_daily['qcfs'] = df_daily['qcms'] * 35.3147\n \n # Fill in some additional columns. Make sure all the values are numeric.\n df_daily = df_daily[['basin_id', 'Year', 'Month', 'Day', 'qcfs', 'flag']] \n df_daily['Year'] = [int(df_daily.loc[i,'Year']) for i in df_daily.index.values]\n df_daily['Month'] = [int(df_daily.loc[i,'Month']) for i in df_daily.index.values]\n df_daily['Day'] = [int(df_daily.loc[i,'Day']) for i in df_daily.index.values]\n \n #####################################################################\n ############ WRITE THE OUPUT TO CSV FILE ################\n ############ FORMATTED AS THE OTHER STREAMFLOWS ################\n df_daily.to_csv('{}_streamflow_qc.txt'.format(df_daily.basin_id[1]), sep=' ', header=False, index=False)\n"
] | [
[
"pandas.to_datetime",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
huminghe/mmdetection | [
"37a3e5d1891a177f9cd16f3ed53195f2d8c2ef70"
] | [
"mmdet/core/visualization/image.py"
] | [
"import matplotlib.pyplot as plt\nimport mmcv\nimport numpy as np\nimport pycocotools.mask as mask_util\nfrom matplotlib.collections import PatchCollection\nfrom matplotlib.patches import Polygon\n\nfrom ..utils import mask2ndarray\n\nEPS = 1e-2\n\n\ndef color_val_matplotlib(color):\n \"\"\"Convert various input in BGR order to normalized RGB matplotlib color\n tuples,\n\n Args:\n color (:obj:`Color`/str/tuple/int/ndarray): Color inputs\n\n Returns:\n tuple[float]: A tuple of 3 normalized floats indicating RGB channels.\n \"\"\"\n color = mmcv.color_val(color)\n color = [color / 255 for color in color[::-1]]\n return tuple(color)\n\n\ndef imshow_det_bboxes(img,\n bboxes,\n labels,\n segms=None,\n class_names=None,\n score_thr=0,\n bbox_color='green',\n text_color='green',\n mask_color=None,\n thickness=2,\n font_size=13,\n win_name='',\n show=True,\n wait_time=0,\n out_file=None,\n visual_label_threshold=-1,\n visual_label_offset=0):\n \"\"\"Draw bboxes and class labels (with scores) on an image.\n\n Args:\n img (str or ndarray): The image to be displayed.\n bboxes (ndarray): Bounding boxes (with scores), shaped (n, 4) or\n (n, 5).\n labels (ndarray): Labels of bboxes.\n segms (ndarray or None): Masks, shaped (n,h,w) or None\n class_names (list[str]): Names of each classes.\n score_thr (float): Minimum score of bboxes to be shown. Default: 0\n bbox_color (str or tuple(int) or :obj:`Color`):Color of bbox lines.\n The tuple of color should be in BGR order. Default: 'green'\n text_color (str or tuple(int) or :obj:`Color`):Color of texts.\n The tuple of color should be in BGR order. Default: 'green'\n mask_color (str or tuple(int) or :obj:`Color`, optional):\n Color of masks. The tuple of color should be in BGR order.\n Default: None\n thickness (int): Thickness of lines. Default: 2\n font_size (int): Font size of texts. Default: 13\n show (bool): Whether to show the image. Default: True\n win_name (str): The window name. Default: ''\n wait_time (float): Value of waitKey param. Default: 0.\n out_file (str, optional): The filename to write the image.\n Default: None\n visual_label_threshold(int, optional): Bbox showed label limit.\n visual_label_offset(int, optional): Bbox showed label offset.\n\n Returns:\n ndarray: The image with bboxes drawn on it.\n \"\"\"\n assert bboxes.ndim == 2, \\\n f' bboxes ndim should be 2, but its ndim is {bboxes.ndim}.'\n assert labels.ndim == 1, \\\n f' labels ndim should be 1, but its ndim is {labels.ndim}.'\n assert bboxes.shape[0] == labels.shape[0], \\\n 'bboxes.shape[0] and labels.shape[0] should have the same length.'\n assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5, \\\n f' bboxes.shape[1] should be 4 or 5, but its {bboxes.shape[1]}.'\n img = mmcv.imread(img).astype(np.uint8)\n\n if score_thr > 0:\n assert bboxes.shape[1] == 5\n scores = bboxes[:, -1]\n inds = scores > score_thr\n bboxes = bboxes[inds, :]\n labels = labels[inds]\n if segms is not None:\n segms = segms[inds, ...]\n\n mask_colors = []\n if labels.shape[0] > 0:\n if mask_color is None:\n # random color\n np.random.seed(42)\n mask_colors = [\n np.random.randint(0, 256, (1, 3), dtype=np.uint8)\n for _ in range(max(labels) + 1)\n ]\n else:\n # specify color\n mask_colors = [\n np.array(mmcv.color_val(mask_color)[::-1], dtype=np.uint8)\n ] * (\n max(labels) + 1)\n\n bbox_color = color_val_matplotlib(bbox_color)\n text_color = color_val_matplotlib(text_color)\n\n img = mmcv.bgr2rgb(img)\n width, height = img.shape[1], img.shape[0]\n img = np.ascontiguousarray(img)\n\n fig = plt.figure(win_name, frameon=False)\n plt.title(win_name)\n canvas = fig.canvas\n dpi = fig.get_dpi()\n # add a small EPS to avoid precision lost due to matplotlib's truncation\n # (https://github.com/matplotlib/matplotlib/issues/15363)\n fig.set_size_inches((width + EPS) / dpi, (height + EPS) / dpi)\n\n # remove white edges by set subplot margin\n plt.subplots_adjust(left=0, right=1, bottom=0, top=1)\n ax = plt.gca()\n ax.axis('off')\n\n polygons = []\n color = []\n for i, (bbox, label) in enumerate(zip(bboxes, labels)):\n if visual_label_threshold < 0 or visual_label_offset <= label <= visual_label_threshold:\n bbox_int = bbox.astype(np.int32)\n poly = [[bbox_int[0], bbox_int[1]], [bbox_int[0], bbox_int[3]],\n [bbox_int[2], bbox_int[3]], [bbox_int[2], bbox_int[1]]]\n np_poly = np.array(poly).reshape((4, 2))\n polygons.append(Polygon(np_poly))\n color.append(bbox_color)\n label_text = class_names[\n label] if class_names is not None else f'class {label}'\n if len(bbox) > 4:\n label_text += f'|{bbox[-1]:.02f}'\n ax.text(\n bbox_int[0],\n bbox_int[1],\n f'{label_text}',\n bbox={\n 'facecolor': 'black',\n 'alpha': 0.8,\n 'pad': 0.7,\n 'edgecolor': 'none'\n },\n color=text_color,\n fontsize=font_size,\n verticalalignment='top',\n horizontalalignment='left')\n if segms is not None:\n color_mask = mask_colors[labels[i]]\n mask = segms[i].astype(bool)\n img[mask] = img[mask] * 0.5 + color_mask * 0.5\n\n plt.imshow(img)\n\n p = PatchCollection(\n polygons, facecolor='none', edgecolors=color, linewidths=thickness)\n ax.add_collection(p)\n\n stream, _ = canvas.print_to_buffer()\n buffer = np.frombuffer(stream, dtype='uint8')\n img_rgba = buffer.reshape(height, width, 4)\n rgb, alpha = np.split(img_rgba, [3], axis=2)\n img = rgb.astype('uint8')\n img = mmcv.rgb2bgr(img)\n\n if show:\n # We do not use cv2 for display because in some cases, opencv will\n # conflict with Qt, it will output a warning: Current thread\n # is not the object's thread. You can refer to\n # https://github.com/opencv/opencv-python/issues/46 for details\n if wait_time == 0:\n plt.show()\n else:\n plt.show(block=False)\n plt.pause(wait_time)\n if out_file is not None:\n mmcv.imwrite(img, out_file)\n\n plt.close()\n\n return img\n\n\ndef imshow_gt_det_bboxes(img,\n annotation,\n result,\n class_names=None,\n score_thr=0,\n gt_bbox_color=(255, 102, 61),\n gt_text_color=(255, 102, 61),\n gt_mask_color=(255, 102, 61),\n det_bbox_color=(72, 101, 241),\n det_text_color=(72, 101, 241),\n det_mask_color=(72, 101, 241),\n thickness=2,\n font_size=13,\n win_name='',\n show=True,\n wait_time=0,\n out_file=None):\n \"\"\"General visualization GT and result function.\n\n Args:\n img (str or ndarray): The image to be displayed.)\n annotation (dict): Ground truth annotations where contain keys of\n 'gt_bboxes' and 'gt_labels' or 'gt_masks'\n result (tuple[list] or list): The detection result, can be either\n (bbox, segm) or just bbox.\n class_names (list[str]): Names of each classes.\n score_thr (float): Minimum score of bboxes to be shown. Default: 0\n gt_bbox_color (str or tuple(int) or :obj:`Color`):Color of bbox lines.\n The tuple of color should be in BGR order. Default: (255, 102, 61)\n gt_text_color (str or tuple(int) or :obj:`Color`):Color of texts.\n The tuple of color should be in BGR order. Default: (255, 102, 61)\n gt_mask_color (str or tuple(int) or :obj:`Color`, optional):\n Color of masks. The tuple of color should be in BGR order.\n Default: (255, 102, 61)\n det_bbox_color (str or tuple(int) or :obj:`Color`):Color of bbox lines.\n The tuple of color should be in BGR order. Default: (72, 101, 241)\n det_text_color (str or tuple(int) or :obj:`Color`):Color of texts.\n The tuple of color should be in BGR order. Default: (72, 101, 241)\n det_mask_color (str or tuple(int) or :obj:`Color`, optional):\n Color of masks. The tuple of color should be in BGR order.\n Default: (72, 101, 241)\n thickness (int): Thickness of lines. Default: 2\n font_size (int): Font size of texts. Default: 13\n win_name (str): The window name. Default: ''\n show (bool): Whether to show the image. Default: True\n wait_time (float): Value of waitKey param. Default: 0.\n out_file (str, optional): The filename to write the image.\n Default: None\n\n Returns:\n ndarray: The image with bboxes or masks drawn on it.\n \"\"\"\n assert 'gt_bboxes' in annotation\n assert 'gt_labels' in annotation\n assert isinstance(\n result,\n (tuple, list)), f'Expected tuple or list, but get {type(result)}'\n\n gt_masks = annotation.get('gt_masks', None)\n if gt_masks is not None:\n gt_masks = mask2ndarray(gt_masks)\n\n img = mmcv.imread(img)\n\n img = imshow_det_bboxes(\n img,\n annotation['gt_bboxes'],\n annotation['gt_labels'],\n gt_masks,\n class_names=class_names,\n bbox_color=gt_bbox_color,\n text_color=gt_text_color,\n mask_color=gt_mask_color,\n thickness=thickness,\n font_size=font_size,\n win_name=win_name,\n show=False)\n\n if isinstance(result, tuple):\n bbox_result, segm_result = result\n if isinstance(segm_result, tuple):\n segm_result = segm_result[0] # ms rcnn\n else:\n bbox_result, segm_result = result, None\n\n bboxes = np.vstack(bbox_result)\n labels = [\n np.full(bbox.shape[0], i, dtype=np.int32)\n for i, bbox in enumerate(bbox_result)\n ]\n labels = np.concatenate(labels)\n\n segms = None\n if segm_result is not None and len(labels) > 0: # non empty\n segms = mmcv.concat_list(segm_result)\n segms = mask_util.decode(segms)\n segms = segms.transpose(2, 0, 1)\n\n img = imshow_det_bboxes(\n img,\n bboxes,\n labels,\n segms=segms,\n class_names=class_names,\n score_thr=score_thr,\n bbox_color=det_bbox_color,\n text_color=det_text_color,\n mask_color=det_mask_color,\n thickness=thickness,\n font_size=font_size,\n win_name=win_name,\n show=show,\n wait_time=wait_time,\n out_file=out_file)\n return img\n"
] | [
[
"matplotlib.pyplot.imshow",
"numpy.split",
"numpy.concatenate",
"matplotlib.patches.Polygon",
"numpy.random.randint",
"matplotlib.pyplot.gca",
"numpy.full",
"numpy.frombuffer",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.ascontiguousarray",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.collections.PatchCollection",
"numpy.random.seed",
"matplotlib.pyplot.pause",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tudo-astroparticlephysics/LST_mono_analysis | [
"0054b0e5c314e493c5e859dd8653c14b2e6de5c8"
] | [
"theta2_wobble.py"
] | [
"import click\nimport operator\n\nimport plotting\nimport calculation\n\nfrom multiprocessing import Pool, cpu_count\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom fact.io import read_h5py\n\nimport astropy.units as u\nfrom astropy import table\nfrom astropy.io import fits\n\nfrom astropy.coordinates import SkyCoord\n\nfrom fact.analysis.statistics import li_ma_significance\n\nfrom pyirf.binning import (\n create_bins_per_decade,\n add_overflow_bins,\n create_histogram_table,\n)\nfrom pyirf.cuts import evaluate_binned_cut\nfrom pyirf.sensitivity import calculate_sensitivity, estimate_background\nfrom pyirf.spectral import CRAB_HEGRA\n\nimport matplotlib\nif matplotlib.get_backend() == 'pgf':\n from matplotlib.backends.backend_pgf import PdfPages\nelse:\n from matplotlib.backends.backend_pdf import PdfPages\n\n\ncolumns = [\n 'obs_id',\n 'event_id',\n 'source_az_prediction',\n 'source_alt_prediction',\n 'source_ra_prediction',\n 'source_dec_prediction',\n 'dragon_time', \n 'gammaness',\n 'alt_tel',\n 'az_tel',\n 'gamma_energy_prediction'\n]\nCOLUMN_MAP = {\n 'obs_id': 'obs_id',\n 'event_id': 'event_id',\n 'gamma_energy_prediction': 'reco_energy',\n 'source_alt_prediction': 'reco_alt',\n 'source_az_prediction': 'reco_az',\n 'alt_tel': 'pointing_alt',\n 'az_tel': 'pointing_az',\n 'gammaness': 'gh_score',\n}\nUNIT_MAP = {\n 'reco_energy': u.TeV,\n 'reco_alt': u.rad,\n 'reco_az': u.rad,\n 'pointing_alt': u.rad,\n 'pointing_az': u.rad\n}\nMAX_BG_RADIUS = 1 * u.deg\n\n\[email protected]()\[email protected]('output', type=click.Path(exists=False, dir_okay=False))\[email protected]('data', nargs=-1, type=click.Path(exists=True, dir_okay=False))\[email protected]('source', type=str)\[email protected]('cuts_file', type=click.Path(exists=True, dir_okay=False))\[email protected]('theta2_cut', type=float)\[email protected]('threshold', type=float)\[email protected](\n '--n_offs', type=int, default=5,\n help='Number of OFF regions (default = 5)'\n)\[email protected](\n '--n_jobs', type=int, default=-1,\n help='Number of processors used (default = -1)'\n)\ndef main(output, data, source, cuts_file, theta2_cut, threshold, n_offs, n_jobs):\n outdir = output.split('/')[0]\n\n src = SkyCoord.from_name(source)\n\n if n_jobs == -1:\n n_jobs = cpu_count()\n\n with Pool(n_jobs) as pool:\n results = np.array(\n pool.starmap(\n calculation.read_run_calculate_thetas, \n [(run, columns, threshold, src, n_offs) for run in data]\n ), dtype=object\n )\n\n df_selected = pd.concat(results[:,0], ignore_index=True)\n ontime = np.sum(results[:,1])\n theta = np.concatenate(results[:,2])\n df_selected5 = pd.concat(results[:,3], ignore_index=True)\n theta_off = np.concatenate(results[:,4])\n\n # use pyirf cuts\n gh_cuts = table.QTable.read(cuts_file, hdu='GH_CUTS')\n theta_cuts_opt = table.QTable.read(cuts_file, hdu='THETA_CUTS_OPT')\n \n with Pool(n_jobs) as pool:\n results = np.array(\n pool.starmap(\n calculation.read_run_calculate_thetas, \n [(run, columns, gh_cuts, src, n_offs) for run in data]\n ), dtype=object\n )\n\n df_pyirf = pd.concat(results[:,0], ignore_index=True)\n theta_pyirf = np.concatenate(results[:,2])\n df_pyirf5 = pd.concat(results[:,3], ignore_index=True)\n theta_off_pyirf = np.concatenate(results[:,4])\n\n n_on = np.count_nonzero(\n evaluate_binned_cut(\n theta_pyirf, df_pyirf.gamma_energy_prediction.to_numpy() * u.TeV, theta_cuts_opt, operator.le\n )\n )\n n_off = np.count_nonzero(\n evaluate_binned_cut(\n theta_off_pyirf, df_pyirf5.gamma_energy_prediction.to_numpy() * u.TeV, theta_cuts_opt, operator.le\n )\n )\n li_ma = li_ma_significance(n_on, n_off, 1/n_offs)\n n_exc_mean = n_on - (1/n_offs) * n_off\n n_exc_std = np.sqrt(n_on + (1/n_offs)**2 * n_off)\n\n\n ##############################################################################################################\n # plots\n ##############################################################################################################\n figures = []\n\n figures.append(plt.figure())\n ax = figures[-1].add_subplot(1, 1, 1)\n plotting.theta2(\n theta.deg**2, \n theta_off.deg**2, \n 1/n_offs, theta2_cut, threshold, \n source, ontime=ontime,\n ax=ax\n )\n ax.set_title('Theta calculated in ICRS using astropy')\n\n figures.append(plt.figure())\n ax = figures[-1].add_subplot(1, 1, 1)\n plotting.theta2(\n theta_pyirf.deg**2, \n theta_off_pyirf.deg**2, \n 1/n_offs, theta2_cut, r'\\mathrm{energy-dependent}', \n source, ontime=ontime,\n ax=ax\n )\n ax.set_title(r'Energy-dependent $t_\\gamma$ optimised using pyirf')\n\n # plot using pyirf theta cuts\n figures.append(plt.figure())\n ax = figures[-1].add_subplot(1, 1, 1)\n\n ax.hist(\n theta_pyirf.deg**2, \n bins=100, range=[0,1], histtype='step', color='r', label='ON'\n )\n ax.hist(\n theta_off_pyirf.deg**2, \n bins=100, range=[0,1], histtype='stepfilled', color='tab:blue', alpha=0.5, label='OFF', \n weights=np.full_like(theta_off_pyirf.deg**2, 1/n_offs)\n )\n\n txt = rf'''Source: {source}, $t_\\mathrm{{obs}} = {ontime.to_value(u.hour):.2f} \\mathrm{{h}}$\n $N_\\mathrm{{on}} = {n_on},\\, N_\\mathrm{{off}} = {n_off},\\, \\alpha = {1/n_offs:.2f}$\n $N_\\mathrm{{exc}} = {n_exc_mean:.0f} \\pm {n_exc_std:.0f},\\, S_\\mathrm{{Li&Ma}} = {li_ma:.2f}$\n '''\n ax.text(0.5, 0.95, txt, transform=ax.transAxes, va='top', ha='center')\n\n ax.set_xlabel(r'$\\theta^2 \\,\\, / \\,\\, \\mathrm{deg}^2$')\n ax.set_xlim(0,1)\n ax.legend()\n ax.set_title(r'Energy-dependent $t_\\gamma$ and $\\theta_\\mathrm{max}^2$ optimised using pyirf')\n\n\n ##############################################################################################################\n # sensitivity\n ##############################################################################################################\n sensitivity_bins = add_overflow_bins(\n create_bins_per_decade(\n 10 ** -1.8 * u.TeV, 10 ** 2.41 * u.TeV, bins_per_decade=5\n )\n )\n # gh_cuts and theta_cuts_opt in line 113f\n\n gammas = plotting.to_astropy_table(\n df_pyirf, # df_pyirf has pyirf gh cuts already applied\n column_map=COLUMN_MAP,\n unit_map=UNIT_MAP,\n theta=theta_pyirf,\n t_obs=ontime\n )\n background = plotting.to_astropy_table(\n df_pyirf5,\n column_map=COLUMN_MAP,\n unit_map=UNIT_MAP,\n theta=theta_off_pyirf,\n t_obs=ontime\n )\n gammas[\"selected_theta\"] = evaluate_binned_cut(\n gammas[\"theta\"], gammas[\"reco_energy\"], theta_cuts_opt, operator.le\n )\n background[\"selected_theta\"] = evaluate_binned_cut(\n background[\"theta\"], background[\"reco_energy\"], theta_cuts_opt, operator.le\n )\n\n # calculate sensitivity\n signal_hist = create_histogram_table(\n gammas[gammas[\"selected_theta\"]], bins=sensitivity_bins\n )\n background_hist = estimate_background(\n background[background[\"selected_theta\"]],\n reco_energy_bins=sensitivity_bins,\n theta_cuts=theta_cuts_opt,\n alpha=1/n_offs,\n background_radius=MAX_BG_RADIUS,\n )\n sensitivity = calculate_sensitivity(\n signal_hist, background_hist, alpha=1/n_offs\n )\n\n # scale relative sensitivity by Crab flux to get the flux sensitivity\n spectrum = CRAB_HEGRA\n sensitivity[\"flux_sensitivity\"] = (\n sensitivity[\"relative_sensitivity\"] * spectrum(sensitivity['reco_energy_center'])\n )\n\n ##############################################################################################################\n # sensitivity using unoptimised cuts\n ##############################################################################################################\n gammas_unop = plotting.to_astropy_table(\n df_selected, # df_selected has gammaness > threshold already applied\n column_map=COLUMN_MAP,\n unit_map=UNIT_MAP,\n theta=theta,\n t_obs=ontime\n )\n background_unop = plotting.to_astropy_table(\n df_selected5,\n column_map=COLUMN_MAP,\n unit_map=UNIT_MAP,\n theta=theta_off,\n t_obs=ontime\n )\n\n gammas_unop[\"selected_theta\"] = gammas_unop[\"theta\"].to_value(u.deg) <= np.sqrt(0.03)\n background_unop[\"selected_theta\"] = background_unop[\"theta\"].to_value(u.deg) <= np.sqrt(0.03)\n\n theta_cut_unop = theta_cuts_opt\n theta_cut_unop['cut'] = np.sqrt(0.03) * u.deg\n\n # calculate sensitivity\n signal_hist_unop = create_histogram_table(\n gammas_unop[gammas_unop[\"selected_theta\"]], bins=sensitivity_bins\n )\n background_hist_unop = estimate_background(\n background_unop[background_unop[\"selected_theta\"]],\n reco_energy_bins=sensitivity_bins,\n theta_cuts=theta_cut_unop,\n alpha=1/n_offs,\n background_radius=MAX_BG_RADIUS,\n )\n sensitivity_unop = calculate_sensitivity(\n signal_hist_unop, background_hist_unop, alpha=1/n_offs\n )\n\n # scale relative sensitivity by Crab flux to get the flux sensitivity\n sensitivity_unop[\"flux_sensitivity\"] = (\n sensitivity_unop[\"relative_sensitivity\"] * spectrum(sensitivity_unop['reco_energy_center'])\n )\n\n # write fits file and create plot\n hdus = [\n fits.PrimaryHDU(),\n fits.BinTableHDU(sensitivity, name=\"SENSITIVITY\"),\n fits.BinTableHDU(sensitivity_unop, name=\"SENSITIVITY_UNOP\")\n ]\n fits.HDUList(hdus).writeto(f'{outdir}/sensitivity_{source}.fits.gz', overwrite=True)\n\n figures.append(plt.figure())\n ax = figures[-1].add_subplot(1, 1, 1)\n for s, label in zip(\n [sensitivity, sensitivity_unop], \n ['pyirf optimised cuts', rf'$\\theta^2 < {theta2_cut}$ and gh_score$> {threshold}$']\n ): plotting.plot_sensitivity(s, label=label, ax=ax)\n\n # plot Magic sensitivity for reference\n magic = table.QTable.read('notebooks/magic_sensitivity_2014.ecsv')\n plotting.plot_sensitivity(magic, label='MAGIC 2014', ax=ax, magic=True)\n\n ax.set_title(f'Minimal Flux Satisfying Requirements for 50 hours \\n(based on {ontime.to_value(u.hour):.2f}h of {source} observations)')\n\n\n # save plots\n with PdfPages(output) as pdf:\n for fig in figures:\n fig.tight_layout()\n pdf.savefig(fig)\n\n\nif __name__ == '__main__':\n main()"
] | [
[
"matplotlib.backends.backend_pdf.PdfPages",
"pandas.concat",
"numpy.sqrt",
"matplotlib.get_backend",
"numpy.concatenate",
"numpy.full_like",
"numpy.sum",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
IshitaTakeshi/SBA | [
"83a9dd14ab6cb33b4da73a15c8b42c783ad36525"
] | [
"sparseba/utils.py"
] | [
"import numpy as np\n\n\ndef all_symmetric(XS):\n # check if top right and bottom left are same\n assert(XS.shape[1:3] == (2, 2))\n return np.allclose(XS[:, 0, 1], XS[:, 1, 0])\n\n\ndef identities2x2(n):\n I = np.zeros((n, 2, 2))\n I[:, [0, 1], [0, 1]] = 1\n return I\n\n\ndef can_run_ba(n_viewpoints, n_points, n_visible,\n n_pose_params, n_point_params):\n n_rows = 2 * n_visible\n n_cols_a = n_pose_params * n_viewpoints\n n_cols_b = n_point_params * n_points\n n_cols = n_cols_a + n_cols_b\n # J' * J cannot be invertible if n_rows(J) < n_cols(J)\n return n_rows >= n_cols\n\n\ndef check_args(indices, x_true, x_pred, A, B, weights, mu):\n n_visible = indices.n_visible\n assert(A.shape[0] == B.shape[0] == n_visible)\n assert(x_true.shape[0] == x_pred.shape[0] == n_visible)\n\n # check the jacobians' shape\n assert(A.shape[1] == B.shape[1] == 2)\n assert(mu >= 0)\n\n if not can_run_ba(indices.n_viewpoints, indices.n_points, n_visible,\n n_pose_params=A.shape[2],\n n_point_params=B.shape[2]):\n raise ValueError(\"n_rows(J) must be greater than n_cols(J)\")\n\n if not all_symmetric(weights):\n raise ValueError(\"All weights must be symmetric\")\n"
] | [
[
"numpy.zeros",
"numpy.allclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZhangJUJU/TransferLearning | [
"1e5ed495595ffa6d727eb182f2349dbf2aac169c"
] | [
"DTN/train.py"
] | [
"import tensorflow as tf\r\nimport numpy as np\r\nfrom sklearn.manifold import TSNE\r\n\r\nfrom load_dataset import *\r\nBATCH_SIZE=4000\r\nlearningrate=0.00001\r\nlamda=10\r\nmiu=10\r\nMAX_STEP=500\r\nY = tf.placeholder('float', shape=[None, 10])\r\nX = tf.placeholder('float', shape=[None, 256])\r\nsource_image,source_label=read_date('usps')#usps\r\ntarget_image_all, target_label_all = read_date('mnist-fake')#mnist-fake\r\ntarget_image = target_image_all[:55000, :]\r\ntarget_label = target_label_all[:55000, :]\r\n\r\ntarget_image_all_real, target_label_all_real = read_date('mnist-real')#mnist-real\r\ntarget_image_test = target_image_all_real[55000:, :]\r\ntarget_label_test = target_label_all_real[55000:, :]\r\ndef createMmetrix():\r\n mat1 = tf.constant(np.float32(1) / (np.square(BATCH_SIZE / 2)), shape=[BATCH_SIZE / 2, BATCH_SIZE / 2],\\\r\n dtype=tf.float32)\r\n mat2=-mat1\r\n mat3=tf.concat([mat1,mat2],1)\r\n mat4=tf.concat([mat2,mat1],1)\r\n mat5=tf.concat([mat3,mat4],0)\r\n return mat5\r\nM=createMmetrix()\r\nsess = tf.Session()\r\nprint(sess.run(M))\r\ndef weight_variable(shape):\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.Variable(initial)\r\ndef bias_variable(shape):\r\n initial = tf.constant(0.1, shape=shape)\r\n return tf.Variable(initial)\r\n# convolution\r\ndef conv2d(x, W):\r\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\r\n# pooling\r\ndef max_pool_2x2(x):\r\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n\r\n\r\n# first convolutinal layer\r\nw_conv1 = weight_variable([3, 3, 1, 32])\r\nb_conv1 = bias_variable([32])\r\nx_image = tf.reshape(X, [-1, 16, 16, 1])\r\nh_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)\r\nh_pool1 = max_pool_2x2(h_conv1)\r\n\r\n# second convolutional layer\r\nw_conv2 = weight_variable([3, 3, 32, 64])\r\nb_conv2 = bias_variable([64])\r\nh_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)\r\nh_pool2 = max_pool_2x2(h_conv2)\r\n\r\n# densely connected layer\r\nw_fc1 = weight_variable([4 * 4 * 64, 256])\r\nb_fc1 = bias_variable([256])\r\nh_pool2_flat = tf.reshape(h_pool2, [-1, 4 * 4 * 64])\r\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)\r\n\r\n# softmax layer\r\nw_fc2 = weight_variable([256, 10])\r\nb_fc2 = bias_variable([10])\r\ny_conv = tf.nn.softmax(tf.matmul(h_fc1, w_fc2) + b_fc2)\r\nlabel = tf.argmax(y_conv, 1)\r\nobj_func = -tf.reduce_sum(Y * tf.log(y_conv)) + tf.constant(lamda, dtype=tf.float32) * tf.trace(\r\n tf.matmul(tf.matmul(h_fc1, M, transpose_a=True), h_fc1)) + tf.constant(miu, dtype=tf.float32) * tf.trace(\r\n tf.matmul(tf.matmul(y_conv, M, transpose_a=True), y_conv))\r\nM_MMD=tf.constant(lamda, dtype=tf.float32) * tf.trace(\r\n tf.matmul(tf.matmul(h_fc1, M, transpose_a=True), h_fc1))\r\nC_MMD=tf.constant(miu, dtype=tf.float32) * tf.trace(\r\n tf.matmul(tf.matmul(y_conv, M, transpose_a=True), y_conv))\r\noptimizer = tf.train.GradientDescentOptimizer(learningrate).minimize(obj_func)\r\nget_feature=h_fc1\r\ncorrect_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(Y, 1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\r\nsess = tf.Session()\r\nsess.run(tf.global_variables_initializer())\r\nfor echo in np.arange(20):\r\n for step in np.arange(MAX_STEP):\r\n source_image_batch, source_label_batch = get_minibatch(source_image, source_label, BATCH_SIZE)\r\n target_image_batch, target_label_batch = get_minibatch(target_image, target_label, BATCH_SIZE)\r\n total_image_batch=np.vstack([source_image_batch,target_image_batch])\r\n total_label_batch=np.vstack([source_label_batch,target_label_batch])\r\n _, train_acc,train_loss,m,c = sess.run([optimizer,accuracy,obj_func,M_MMD,C_MMD],\r\n feed_dict={X: total_image_batch,Y: total_label_batch})\r\n if(step%10 == 0):\r\n print('step=%d,...loss=%f,acc_train=%0.2f%%,MMMD=%f, CMMD=%f'%(step,train_loss,train_acc*100, m,c))\r\n\r\n new_label=sess.run([label],feed_dict={X: target_image_all})\r\n new_label = dense_to_one_hot(np.transpose(np.array(new_label)),10)\r\n target_label=new_label[:55000, :]\r\n target_acc = sess.run([accuracy],feed_dict={X: target_image_test,Y:target_label_test})\r\n print('DA ACC=%',target_acc)\r\n\r\n"
] | [
[
"tensorflow.concat",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.conv2d",
"numpy.square",
"tensorflow.Variable",
"numpy.arange",
"tensorflow.Session",
"numpy.float32",
"tensorflow.argmax",
"tensorflow.matmul",
"tensorflow.truncated_normal",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"numpy.array",
"tensorflow.constant",
"tensorflow.reshape",
"tensorflow.log",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
DenisVVV/test | [
"f56699ebdd6f1d141427ce766498506c923247a2"
] | [
"tests/c_api_test/test.py"
] | [
"import sys\nimport os\nimport ctypes\nimport collections\n\nimport numpy as np\nfrom scipy import sparse\n\ndef LoadDll():\n if os.name == 'nt':\n lib_path = '../../windows/x64/DLL/lib_lightgbm.dll'\n else:\n lib_path = '../../lib_lightgbm.so'\n lib = ctypes.cdll.LoadLibrary(lib_path)\n return lib\n\nLIB = LoadDll()\n\ndtype_float32 = 0\ndtype_float64 = 1\ndtype_int32 = 2\ndtype_int64 = 3\n\n\ndef c_array(ctype, values):\n return (ctype * len(values))(*values)\n\ndef c_str(string):\n return ctypes.c_char_p(string.encode('ascii'))\n\ndef test_load_from_file(filename, reference):\n ref = None\n if reference != None:\n ref = ctypes.byref(reference)\n handle = ctypes.c_void_p()\n LIB.LGBM_CreateDatasetFromFile(c_str(filename), \n c_str('max_bin=15'), \n ref, ctypes.byref(handle) )\n num_data = ctypes.c_long()\n LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data) )\n num_feature = ctypes.c_long()\n LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature) )\n print ('#data:%d #feature:%d' %(num_data.value, num_feature.value) ) \n return handle\n\ndef test_save_to_binary(handle, filename):\n LIB.LGBM_DatasetSaveBinary(handle, c_str(filename))\n\ndef test_load_from_binary(filename):\n handle = ctypes.c_void_p()\n LIB.LGBM_CreateDatasetFromBinaryFile(c_str(filename), ctypes.byref(handle) )\n num_data = ctypes.c_long()\n LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data) )\n num_feature = ctypes.c_long()\n LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature) )\n print ('#data:%d #feature:%d' %(num_data.value, num_feature.value) ) \n return handle\n\ndef test_load_from_csr(filename, reference):\n data = []\n label = []\n inp = open(filename, 'r')\n for line in inp.readlines():\n data.append( [float(x) for x in line.split('\\t')[1:]] )\n label.append( float(line.split('\\t')[0]) )\n inp.close()\n mat = np.array(data)\n label = np.array(label, dtype=np.float32)\n csr = sparse.csr_matrix(mat)\n handle = ctypes.c_void_p()\n ref = None\n if reference != None:\n ref = ctypes.byref(reference)\n\n LIB.LGBM_CreateDatasetFromCSR(c_array(ctypes.c_int, csr.indptr), \n dtype_int32, \n c_array(ctypes.c_int, csr.indices), \n csr.data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)),\n dtype_float64, \n len(csr.indptr), \n len(csr.data),\n csr.shape[1], \n c_str('max_bin=15'), \n ref, \n ctypes.byref(handle) )\n num_data = ctypes.c_long()\n LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data) )\n num_feature = ctypes.c_long()\n LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature) )\n LIB.LGBM_DatasetSetField(handle, c_str('label'), c_array(ctypes.c_float, label), len(label), 0)\n print ('#data:%d #feature:%d' %(num_data.value, num_feature.value) ) \n return handle\n\ndef test_load_from_csc(filename, reference):\n data = []\n label = []\n inp = open(filename, 'r')\n for line in inp.readlines():\n data.append( [float(x) for x in line.split('\\t')[1:]] )\n label.append( float(line.split('\\t')[0]) )\n inp.close()\n mat = np.array(data)\n label = np.array(label, dtype=np.float32)\n csr = sparse.csc_matrix(mat)\n handle = ctypes.c_void_p()\n ref = None\n if reference != None:\n ref = ctypes.byref(reference)\n\n LIB.LGBM_CreateDatasetFromCSC(c_array(ctypes.c_int, csr.indptr), \n dtype_int32, \n c_array(ctypes.c_int, csr.indices), \n csr.data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)),\n dtype_float64, \n len(csr.indptr), \n len(csr.data),\n csr.shape[0], \n c_str('max_bin=15'), \n ref, \n ctypes.byref(handle) )\n num_data = ctypes.c_long()\n LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data) )\n num_feature = ctypes.c_long()\n LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature) )\n LIB.LGBM_DatasetSetField(handle, c_str('label'), c_array(ctypes.c_float, label), len(label), 0)\n print ('#data:%d #feature:%d' %(num_data.value, num_feature.value) ) \n return handle\n\ndef test_load_from_mat(filename, reference):\n data = []\n label = []\n inp = open(filename, 'r')\n for line in inp.readlines():\n data.append( [float(x) for x in line.split('\\t')[1:]] )\n label.append( float(line.split('\\t')[0]) )\n inp.close()\n mat = np.array(data)\n data = np.array(mat.reshape(mat.size), copy=False)\n label = np.array(label, dtype=np.float32)\n handle = ctypes.c_void_p()\n ref = None\n if reference != None:\n ref = ctypes.byref(reference)\n\n LIB.LGBM_CreateDatasetFromMat(data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)), \n dtype_float64,\n mat.shape[0],\n mat.shape[1],\n 1,\n c_str('max_bin=15'), \n ref, \n ctypes.byref(handle) )\n num_data = ctypes.c_long()\n LIB.LGBM_DatasetGetNumData(handle, ctypes.byref(num_data) )\n num_feature = ctypes.c_long()\n LIB.LGBM_DatasetGetNumFeature(handle, ctypes.byref(num_feature) )\n LIB.LGBM_DatasetSetField(handle, c_str('label'), c_array(ctypes.c_float, label), len(label), 0)\n print ('#data:%d #feature:%d' %(num_data.value, num_feature.value) ) \n return handle\ndef test_free_dataset(handle):\n LIB.LGBM_DatasetFree(handle)\n\ndef test_dataset():\n train = test_load_from_file('../../examples/binary_classification/binary.train', None)\n test = test_load_from_mat('../../examples/binary_classification/binary.test', train)\n test_free_dataset(test)\n test = test_load_from_csr('../../examples/binary_classification/binary.test', train)\n test_free_dataset(test)\n test = test_load_from_csc('../../examples/binary_classification/binary.test', train)\n test_free_dataset(test)\n test_save_to_binary(train, 'train.binary.bin')\n test_free_dataset(train)\n train = test_load_from_binary('train.binary.bin')\n test_free_dataset(train)\ndef test_booster():\n train = test_load_from_mat('../../examples/binary_classification/binary.train', None)\n test = [test_load_from_mat('../../examples/binary_classification/binary.test', train)]\n name = [c_str('test')]\n booster = ctypes.c_void_p()\n LIB.LGBM_BoosterCreate(train, c_array(ctypes.c_void_p, test), c_array(ctypes.c_char_p, name), \n len(test), c_str(\"app=binary metric=auc num_leaves=31 verbose=0\"), ctypes.byref(booster))\n is_finished = ctypes.c_int(0)\n for i in range(100):\n LIB.LGBM_BoosterUpdateOneIter(booster,ctypes.byref(is_finished))\n result = np.array([0.0], dtype=np.float32)\n out_len = ctypes.c_ulong(0)\n LIB.LGBM_BoosterEval(booster, 0, ctypes.byref(out_len), result.ctypes.data_as(ctypes.POINTER(ctypes.c_float)))\n print ('%d Iteration test AUC %f' %(i, result[0]))\n LIB.LGBM_BoosterSaveModel(booster, -1, c_str('model.txt'))\n LIB.LGBM_BoosterFree(booster)\n test_free_dataset(train)\n test_free_dataset(test[0])\n booster2 = ctypes.c_void_p()\n LIB.LGBM_BoosterLoadFromModelfile(c_str('model.txt'), ctypes.byref(booster2))\n data = []\n inp = open('../../examples/binary_classification/binary.test', 'r')\n for line in inp.readlines():\n data.append( [float(x) for x in line.split('\\t')[1:]] )\n inp.close()\n mat = np.array(data)\n preb = np.zeros(( mat.shape[0],1 ), dtype=np.float64)\n data = np.array(mat.reshape(mat.size), copy=False)\n LIB.LGBM_BoosterPredictForMat(booster2,\n data.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)), \n dtype_float64,\n mat.shape[0],\n mat.shape[1],\n 1,\n 1,\n 50,\n preb.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))\n LIB.LGBM_BoosterPredictForFile(booster2, 1, 50, 0, c_str('../../examples/binary_classification/binary.test'), c_str('preb.txt'))\n LIB.LGBM_BoosterFree(booster2)\n\ntest_dataset()\ntest_booster()\n\n"
] | [
[
"scipy.sparse.csc_matrix",
"numpy.array",
"numpy.zeros",
"scipy.sparse.csr_matrix"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
dataiku-research/mealy | [
"039978fbb4bbda4e89e55ae05a75bdb3560191e2"
] | [
"mealy/error_analyzer.py"
] | [
"# -*- coding: utf-8 -*-\nimport numpy as np\nimport collections\nfrom sklearn import tree\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.base import is_regressor\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.base import BaseEstimator\nfrom sklearn.metrics import make_scorer\nfrom .error_analysis_utils import check_enough_data, get_epsilon, format_float\nfrom .constants import ErrorAnalyzerConstants\nfrom .metrics import error_decision_tree_report, fidelity_balanced_accuracy_score\nfrom .preprocessing import PipelinePreprocessor, DummyPipelinePreprocessor\nfrom .error_tree import ErrorTree\nfrom sklearn.exceptions import NotFittedError\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO, format='mealy | %(levelname)s - %(message)s')\n\n\nclass ErrorAnalyzer(BaseEstimator):\n \"\"\" ErrorAnalyzer analyzes the errors of a prediction model on a test set.\n\n It uses model predictions and ground truth target to compute the model errors on the test set.\n It then trains a Decision Tree, called a Error Analyzer Tree, on the same test set by using the model error\n as target. The nodes of the decision tree are different segments of errors to be studied individually.\n\n Args:\n primary_model (sklearn.base.BaseEstimator or sklearn.pipeline.Pipeline): a sklearn model to analyze. Either an estimator\n or a Pipeline containing a ColumnTransformer with the preprocessing steps and an estimator as last step.\n feature_names (list of str): list of feature names. Defaults to None.\n param_grid (dict): sklearn.tree.DecisionTree hyper-parameters values for grid search.\n random_state (int): random seed.\n\n Attributes:\n _error_tree (DecisionTreeClassifier): the estimator used to train the Error Analyzer Tree\n \"\"\"\n\n def __init__(self, primary_model,\n feature_names=None,\n param_grid=None,\n probability_threshold=0.5,\n random_state=65537):\n self.param_grid = param_grid\n self.probability_threshold = probability_threshold\n self.random_state = random_state\n\n if isinstance(primary_model, Pipeline):\n if len(primary_model.steps) != 2:\n logger.warning(\"Pipeline should have two steps: the preprocessing of the features, and the primary model to analyze.\")\n estimator = primary_model.steps[-1][1]\n if not isinstance(estimator, BaseEstimator):\n raise TypeError(\"The last step of the pipeline has to be a BaseEstimator.\")\n self._primary_model = estimator\n\n ct_preprocessor = primary_model.steps[0][1]\n if not isinstance(ct_preprocessor, ColumnTransformer):\n raise TypeError(\"The input preprocessor has to be a ColumnTransformer.\")\n self.pipeline_preprocessor = PipelinePreprocessor(ct_preprocessor, feature_names)\n elif isinstance(primary_model, BaseEstimator):\n self._primary_model = primary_model\n self.pipeline_preprocessor = DummyPipelinePreprocessor(feature_names)\n else:\n raise TypeError('ErrorAnalyzer needs as input either a scikit BaseEstimator or a scikit Pipeline.')\n\n if not hasattr(self._primary_model, \"_estimator_type\"):\n raise ValueError(\"The primary model is missing the required parameter '_estimator_type'. It should be 'regressor' or 'classifier'.\")\n if self._primary_model._estimator_type not in {\"regressor\", \"classifier\"}:\n raise ValueError(\"The primary model is neither a classifier nor a regressor.\")\n\n self._error_tree = None\n self._error_train_x = None\n self._error_train_y = None\n self.epsilon = None\n\n @property\n def param_grid(self):\n return self._param_grid\n\n @param_grid.setter\n def param_grid(self, value):\n self._param_grid = value\n\n @property\n def random_state(self):\n return self._random_state\n\n @random_state.setter\n def random_state(self, value):\n self._random_state = value\n\n @property\n def error_tree(self):\n if self._error_tree is None:\n raise NotFittedError(\"The error tree is not fitted yet. Call 'fit' method with appropriate arguments before using this estimator.\")\n return self._error_tree\n\n @error_tree.setter\n def error_tree(self, tree):\n if self.pipeline_preprocessor.get_preprocessed_feature_names() is None:\n self.pipeline_preprocessor.preprocessed_feature_names = [\"feature#%s\" % feature_index\n for feature_index in range(tree.estimator_.n_features_)]\n self._error_tree = tree\n\n @property\n def preprocessed_feature_names(self):\n return self.pipeline_preprocessor.get_preprocessed_feature_names()\n\n def fit(self, X, y):\n \"\"\"\n Fit the Error Analyzer Tree.\n\n Trains the Error Analyzer Tree, a Decision Tree to discriminate between samples that are correctly\n predicted or wrongly predicted (errors) by a primary model.\n\n Args:\n X (numpy.ndarray or pandas.DataFrame): feature data from a test set to evaluate the primary predictor and\n train a Error Analyzer Tree.\n y (numpy.ndarray or pandas.DataFrame): target data from a test set to evaluate the primary predictor and\n train a Error Analyzer Tree.\n \"\"\"\n logger.info(\"Preparing the Error Analyzer Tree...\")\n\n np.random.seed(self._random_state)\n preprocessed_X = self.pipeline_preprocessor.transform(X)\n\n check_enough_data(preprocessed_X, min_len=ErrorAnalyzerConstants.MIN_NUM_ROWS)\n self._error_train_y, error_rate = self._compute_primary_model_error(preprocessed_X, y)\n self._error_train_x = preprocessed_X\n\n logger.info(\"Fitting the Error Analyzer Tree...\")\n # entropy/mutual information is used to split nodes in Microsoft Pandora system\n dt_clf = tree.DecisionTreeClassifier(criterion=ErrorAnalyzerConstants.CRITERION,\n random_state=self._random_state)\n param_grid = self.param_grid\n if param_grid is None:\n min_samples_leaf_max = min(error_rate, ErrorAnalyzerConstants.MIN_SAMPLES_LEAF_LOWEST_UPPER_BOUND)\n param_grid = {\n 'max_depth': ErrorAnalyzerConstants.MAX_DEPTH,\n 'min_samples_leaf': np.linspace(min_samples_leaf_max/5, min_samples_leaf_max, 5)\n }\n\n logger.info('Grid search the Error Tree with the following grid: {}'.format(param_grid))\n gs_clf = GridSearchCV(dt_clf,\n param_grid=param_grid,\n cv=5,\n scoring=make_scorer(fidelity_balanced_accuracy_score))\n\n gs_clf.fit(self._error_train_x, self._error_train_y)\n self.error_tree = ErrorTree(error_decision_tree=gs_clf.best_estimator_)\n logger.info('Chosen parameters: {}'.format(gs_clf.best_params_))\n\n def get_error_leaf_summary(self, leaf_selector=None, add_path_to_leaves=False,\n output_format='dict', rank_by='total_error_fraction'):\n \"\"\" Return summary information regarding leaves.\n\n Args:\n leaf_selector (None, int or array-like): The leaves whose information will be returned\n * int: Only return information of the leaf with the corresponding id\n * array-like: Only return information of the leaves corresponding to these ids\n * None (default): Return information of all the leaves\n add_path_to_leaves (bool): Whether to add information of the path across the tree till the selected node. Defaults to False.\n output_format (string): Return format used for the report. Valid values are 'dict' or 'str'. Defaults to 'dict'.\n rank_by (str): Ranking criterion for the leaves. Valid values are:\n * 'total_error_fraction' (default): rank by the fraction of total error in the node\n * 'purity': rank by the purity (ratio of wrongly predicted samples over the total number of node samples)\n * 'class_difference': rank by the difference of number of wrongly and correctly predicted samples\n in a node.\n\n Return:\n dict or str: list of reports (as dictionary or string) with different information on each selected leaf.\n \"\"\"\n\n leaf_nodes = self._get_ranked_leaf_ids(leaf_selector=leaf_selector, rank_by=rank_by)\n\n leaves_summary = []\n for leaf_id in leaf_nodes:\n n_errors = int(self.error_tree.estimator_.tree_.value[leaf_id, 0, self.error_tree.error_class_idx])\n n_samples = self.error_tree.estimator_.tree_.n_node_samples[leaf_id]\n local_error = n_errors / n_samples\n total_error_fraction = n_errors / self.error_tree.n_total_errors\n n_corrects = n_samples - n_errors\n\n if output_format == 'dict':\n leaf_dict = {\n \"id\": leaf_id,\n \"n_corrects\": n_corrects,\n \"n_errors\": n_errors,\n \"local_error\": local_error,\n \"total_error_fraction\": total_error_fraction\n }\n if add_path_to_leaves:\n leaf_dict[\"path_to_leaf\"] = self._get_path_to_node(leaf_id)\n leaves_summary.append(leaf_dict)\n\n elif output_format == 'str':\n leaf_summary = 'LEAF %d:\\n' % leaf_id\n leaf_summary += ' Correct predictions: %d | Wrong predictions: %d | Local error (purity): %.2f | Fraction of total error: %.2f\\n' % (n_corrects, n_errors, local_error, total_error_fraction)\n\n if add_path_to_leaves:\n leaf_summary += ' Path to leaf:\\n'\n for (step_idx, step) in enumerate(self._get_path_to_node(leaf_id)):\n leaf_summary += ' ' + ' ' * step_idx + step + '\\n'\n\n leaves_summary.append(leaf_summary)\n\n else:\n raise ValueError(\"Output format should either be 'dict' or 'str'\")\n\n return leaves_summary\n\n def evaluate(self, X, y, output_format='str'):\n \"\"\"\n Evaluate performance of ErrorAnalyzer on the given test data and labels.\n Return ErrorAnalyzer summary metrics regarding the Error Tree.\n\n Args:\n X (numpy.ndarray or pandas.DataFrame): feature data from a test set to evaluate the primary predictor\n and train a Error Analyzer Tree.\n y (numpy.ndarray or pandas.DataFrame): target data from a test set to evaluate the primary predictor and\n train a Error Analyzer Tree.\n output_format (string): Return format used for the report. Valid values are 'dict' or 'str'. Defaults to 'str'.\n\n Return:\n dict or str: dictionary or string report storing different metrics regarding the Error Decision Tree.\n \"\"\"\n prep_x, prep_y = self.pipeline_preprocessor.transform(X), np.array(y)\n y_pred = self.error_tree.estimator_.predict(prep_x)\n y_true, _ = self._compute_primary_model_error(prep_x, prep_y)\n return error_decision_tree_report(y_true, y_pred, output_format)\n\n def _compute_primary_model_error(self, X, y):\n \"\"\"\n Computes the errors of the primary model predictions and samples\n\n Args:\n X: array-like of shape (n_samples, n_features)\n Input samples.\n\n y: array-like of shape (n_samples,)\n True target values for `X`.\n\n Returns:\n sampled_X: ndarray\n A sample of `X`.\n\n error_y: array of string of shape (n_sampled_X, )\n Boolean value of whether or not the primary model predicted correctly or incorrectly the samples in sampled_X.\n \"\"\"\n if is_regressor(self._primary_model) or len(np.unique(y)) > 2:\n # regression or multiclass classification models: no proba threshold\n y_pred = self._primary_model.predict(X)\n else: # binary -> need to check the proba threshold\n prediction_index = (self._primary_model.predict_proba(X)[:, 1] > self.probability_threshold).astype(int)\n # map the prediction indexes to the original target values\n y_pred = np.array([self._primary_model.classes_[i] for i in prediction_index])\n\n error_y, error_rate = self._evaluate_primary_model_predictions(y_true=y, y_pred=y_pred)\n return error_y, error_rate\n\n def _evaluate_primary_model_predictions(self, y_true, y_pred):\n \"\"\"\n Compute errors of the primary model on the test set\n\n Args:\n y_true: 1D array\n True target values.\n\n y_pred: 1D array\n Predictions of the primary model.\n\n Return:\n error_y: array of string of len(y_true)\n Boolean value of whether or not the primary model got the prediction right.\n\n error_rate: float\n Accuracy of the primary model\n \"\"\"\n\n error_y = np.full_like(y_true, ErrorAnalyzerConstants.CORRECT_PREDICTION, dtype=\"O\")\n if is_regressor(self._primary_model):\n difference = np.abs(y_true - y_pred)\n if self.epsilon is None:\n # only compute epsilon when fitting the model (not while evaluating)\n self.epsilon = get_epsilon(difference)\n error_mask = difference > self.epsilon\n else:\n error_mask = y_true != y_pred\n\n n_wrong_preds = np.count_nonzero(error_mask)\n error_y[error_mask] = ErrorAnalyzerConstants.WRONG_PREDICTION\n\n if n_wrong_preds == 0 or n_wrong_preds == len(error_y):\n raise RuntimeError('All predictions are {}. To build a proper ErrorAnalyzer decision tree both correct and incorrect predictions are needed'.format(error_y[0]))\n\n error_rate = n_wrong_preds / len(error_y)\n logger.info('The primary model has an error rate of {}'.format(format_float(error_rate, 3)))\n return error_y, error_rate\n\n def _get_ranked_leaf_ids(self, leaf_selector=None, rank_by='total_error_fraction'):\n \"\"\" Select error nodes and rank them by importance.\n\n Args:\n leaf_selector (None, int or array-like): the leaves whose information will be returned\n * int: Only return information of the leaf with the corresponding id\n * array-like: Only return information of the leaves corresponding to these ids\n * None (default): Return information of all the leaves\n rank_by (str): ranking criterion for the leaves. Valid values are:\n * 'total_error_fraction': rank by the fraction of total error in the node\n * 'purity': rank by the purity (ratio of wrongly predicted samples over the total number of node samples)\n * 'class_difference': rank by the difference of number of wrongly and correctly predicted samples\n in a node.\n\n Return:\n list or numpy.ndarray: list of selected leaves indices.\n\n \"\"\"\n apply_leaf_selector = self._get_leaf_selector(self.error_tree.leaf_ids, leaf_selector)\n selected_leaves = apply_leaf_selector(self.error_tree.leaf_ids)\n if selected_leaves.size == 0:\n return selected_leaves\n if rank_by == 'total_error_fraction':\n sorted_ids = np.argsort(-apply_leaf_selector(self.error_tree.total_error_fraction))\n elif rank_by == 'purity':\n sorted_ids = np.lexsort((apply_leaf_selector(self.error_tree.difference), apply_leaf_selector(self.error_tree.quantized_impurity)))\n elif rank_by == 'class_difference':\n sorted_ids = np.lexsort((apply_leaf_selector(self.error_tree.impurity), apply_leaf_selector(self.error_tree.difference)))\n else:\n raise ValueError(\n \"Input argument for rank_by is invalid. Should be 'total_error_fraction', 'purity' or 'class_difference'\")\n return selected_leaves.take(sorted_ids)\n\n @staticmethod\n def _get_leaf_selector(leaf_ids, leaf_selector=None):\n \"\"\"\n Return a function that select rows of provided arrays. Arrays must be of shape (1, number of leaves)\n Args:\n leaf_selector: None, int or array-like\n How to select the rows of the array\n * int: Only keep the row corresponding to this leaf id\n * array-like: Only keep the rows corresponding to these leaf ids\n * None (default): Keep the whole array of leaf ids\n\n Return:\n A function with one argument array as a selector of leaf ids\n Args:\n array: numpy array of shape (1, number of leaves)\n An array of which we only want to keep some rows\n \"\"\"\n if leaf_selector is None:\n return lambda array: array\n\n leaf_selector_as_array = np.array(leaf_selector)\n leaf_selector = np.in1d(leaf_ids, leaf_selector_as_array)\n nr_kept_leaves = np.count_nonzero(leaf_selector)\n if nr_kept_leaves == 0:\n logger.info(\"None of the ids provided correspond to a leaf id.\")\n elif nr_kept_leaves < leaf_selector_as_array.size:\n logger.info(\"Some of the ids provided do not belong to leaves. Only leaf ids are kept.\")\n return lambda array: array[leaf_selector]\n\n def _get_path_to_node(self, node_id):\n \"\"\" Return path to node as a list of split steps from the nodes of the sklearn Tree object \"\"\"\n feature_names = self.pipeline_preprocessor.get_original_feature_names()\n children_left = list(self.error_tree.estimator_.tree_.children_left)\n children_right = list(self.error_tree.estimator_.tree_.children_right)\n threshold = self._inverse_transform_thresholds()\n feature = self._inverse_transform_features()\n\n cur_node_id = node_id\n path_to_node = collections.deque()\n while cur_node_id > 0:\n\n node_is_left_child = cur_node_id in children_left\n if node_is_left_child:\n parent_id = children_left.index(cur_node_id)\n else:\n parent_id = children_right.index(cur_node_id)\n\n feat = feature[parent_id]\n thresh = threshold[parent_id]\n\n is_categorical = self.pipeline_preprocessor.is_categorical(feat)\n thresh = str(thresh) if is_categorical else format_float(thresh, 2)\n\n decision_rule = ''\n if node_is_left_child:\n decision_rule += ' <= ' if not is_categorical else ' is not '\n else:\n decision_rule += \" > \" if not is_categorical else ' is '\n\n decision_rule = str(feature_names[feat]) + decision_rule + thresh\n path_to_node.appendleft(decision_rule)\n cur_node_id = parent_id\n\n return path_to_node\n\n def _inverse_transform_features(self):\n \"\"\" Undo preprocessing of feature values.\n\n If the predictor comes with a Pipeline preprocessor, map the features indices of the Error Analysis\n Tree back to their indices in the original unpreprocessed space of features.\n Otherwise simply return the feature indices of the decision tree. The feature indices of a decision tree\n indicate what features are used to split the training set at each node.\n See https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html.\n\n Return:\n list or numpy.ndarray:\n indices of features of the Error Analyzer Tree, possibly mapped back to the\n original unprocessed feature space.\n \"\"\"\n return [self.pipeline_preprocessor.inverse_transform_feature_id(feat_idx) if feat_idx > 0 else feat_idx\n for feat_idx in self.error_tree.estimator_.tree_.feature]\n\n def _inverse_transform_thresholds(self):\n \"\"\" Undo preprocessing of feature threshold values.\n\n If the predictor comes with a Pipeline preprocessor, undo the preprocessing on the thresholds of the Error Analyzer\n Tree for an easier plot interpretation. Otherwise simply return the thresholds of\n the decision tree. The thresholds of a decision tree are the feature values used to split the training set at\n each node. See https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html.\n\n Return:\n numpy.ndarray:\n thresholds of the Error Tree, possibly with preprocessing undone.\n \"\"\"\n return self.pipeline_preprocessor.inverse_thresholds(self.error_tree.estimator_.tree_)\n"
] | [
[
"numpy.abs",
"numpy.random.seed",
"numpy.linspace",
"numpy.unique",
"numpy.in1d",
"sklearn.exceptions.NotFittedError",
"numpy.full_like",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.metrics.make_scorer",
"numpy.count_nonzero",
"sklearn.base.is_regressor",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ErikHambardzumyan/dowhy | [
"685f64723e2a37334164dbb8da7d55f4e45975de"
] | [
"dowhy/causal_estimators/propensity_score_estimator.py"
] | [
"import numpy as np\r\nimport pandas as pd\r\n\r\nfrom dowhy.causal_estimator import CausalEstimator\r\n\r\nclass PropensityScoreEstimator(CausalEstimator):\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n # We need to initialize the model when we create any propensity score estimator\r\n self._propensity_score_model = None\r\n # Check if the treatment is one-dimensional\r\n if len(self._treatment_name) > 1:\r\n error_msg = str(self.__class__) + \"cannot handle more than one treatment variable\"\r\n raise Exception(error_msg)\r\n # Checking if the treatment is binary\r\n if not pd.api.types.is_bool_dtype(self._data[self._treatment_name[0]]):\r\n error_msg = \"Propensity score methods are applicable only for binary treatments\"\r\n self.logger.error(error_msg)\r\n raise Exception(error_msg)\r\n\r\n self.logger.debug(\"Back-door variables used:\" +\r\n \",\".join(self._target_estimand.backdoor_variables))\r\n \r\n self._observed_common_causes_names = self._target_estimand.backdoor_variables\r\n\r\n if self._observed_common_causes_names:\r\n self._observed_common_causes = self._data[self._observed_common_causes_names]\r\n # Convert the categorical variables into dummy/indicator variables\r\n # Basically, this gives a one hot encoding for each category\r\n # The first category is taken to be the base line.\r\n self._observed_common_causes = pd.get_dummies(self._observed_common_causes, drop_first=True)\r\n else:\r\n self._observed_common_causes = None\r\n error_msg = \"No common causes/confounders present. Propensity score based methods are not applicable\"\r\n self.logger.error(error_msg)\r\n raise Exception(error_msg)\r\n\r\n def construct_symbolic_estimator(self, estimand):\r\n '''\r\n A symbolic string that conveys what each estimator does. \r\n For instance, linear regression is expressed as\r\n y ~ bx + e\r\n '''\r\n raise NotImplementedError\r\n\r\n def _estimate_effect(self, recalculate_propensity_score=False):\r\n '''\r\n A custom estimator based on the way the propensity score estimates are to be used.\r\n \r\n Parameters\r\n -----------\r\n recalculate_propensity_score: bool, default False,\r\n This forces the estimator to recalculate the estimate for the propensity score.\r\n '''\r\n raise NotImplementedError\r\n\r\n"
] | [
[
"pandas.api.types.is_bool_dtype",
"pandas.get_dummies"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
hussainsan/enas | [
"4bcfd73b524627ea96574e5fed33da74bc7855d5"
] | [
"src/ptb/ptb_enas_child.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom src.common_ops import lstm\n\nfrom src.utils import count_model_params\nfrom src.utils import get_train_ops\n\nfrom src.ptb.data_utils import ptb_input_producer\nfrom src.ptb.ptb_ops import batch_norm\nfrom src.ptb.ptb_ops import layer_norm\n\nclass PTBEnasChild(object):\n def __init__(self,\n x_train,\n x_valid,\n x_test,\n num_funcs=4,\n rnn_l2_reg=None,\n rnn_slowness_reg=None,\n rhn_depth=2,\n fixed_arc=None,\n base_number=4,\n batch_size=32,\n bptt_steps=25,\n lstm_num_layers=2,\n lstm_hidden_size=32,\n lstm_e_keep=1.0,\n lstm_x_keep=1.0,\n lstm_h_keep=1.0,\n lstm_o_keep=1.0,\n lstm_l_skip=False,\n vocab_size=10000,\n lr_warmup_val=None,\n lr_warmup_steps=None,\n lr_init=1.0,\n lr_dec_start=4,\n lr_dec_every=1,\n lr_dec_rate=0.5,\n lr_dec_min=None,\n l2_reg=None,\n clip_mode=\"global\",\n grad_bound=5.0,\n optim_algo=None,\n optim_moving_average=None,\n sync_replicas=False,\n num_aggregate=None,\n num_replicas=None,\n temperature=None,\n name=\"ptb_lstm\",\n seed=None,\n *args,\n **kwargs):\n \"\"\"\n Args:\n lr_dec_every: number of epochs to decay\n \"\"\"\n print(\"-\" * 80)\n print(\"Build model {}\".format(name))\n\n self.num_funcs = num_funcs\n self.rnn_l2_reg = rnn_l2_reg\n self.rnn_slowness_reg = rnn_slowness_reg\n self.rhn_depth = rhn_depth\n self.fixed_arc = fixed_arc\n self.base_number = base_number\n self.num_nodes = 2 * self.base_number - 1\n self.batch_size = batch_size\n self.bptt_steps = bptt_steps\n self.lstm_num_layers = lstm_num_layers\n self.lstm_hidden_size = lstm_hidden_size\n self.lstm_e_keep = lstm_e_keep\n self.lstm_x_keep = lstm_x_keep\n self.lstm_h_keep = lstm_h_keep\n self.lstm_o_keep = lstm_o_keep\n self.lstm_l_skip = lstm_l_skip\n self.vocab_size = vocab_size\n self.lr_warmup_val = lr_warmup_val\n self.lr_warmup_steps = lr_warmup_steps\n self.lr_init = lr_init\n self.lr_dec_min = lr_dec_min\n self.l2_reg = l2_reg\n self.clip_mode = clip_mode\n self.grad_bound = grad_bound\n\n self.optim_algo = optim_algo\n self.optim_moving_average = optim_moving_average\n self.sync_replicas = sync_replicas\n self.num_aggregate = num_aggregate\n self.num_replicas = num_replicas\n self.temperature = temperature\n\n self.name = name\n self.seed = seed\n \n self.global_step = None\n self.valid_loss = None\n self.test_loss = None\n\n print(\"Build data ops\")\n # training data\n self.x_train, self.y_train, self.num_train_batches = ptb_input_producer(\n x_train, self.batch_size, self.bptt_steps)\n self.y_train = tf.reshape(self.y_train, [self.batch_size * self.bptt_steps])\n\n self.lr_dec_start = lr_dec_start * self.num_train_batches\n self.lr_dec_every = lr_dec_every * self.num_train_batches\n self.lr_dec_rate = lr_dec_rate\n\n # valid data\n self.x_valid, self.y_valid, self.num_valid_batches = ptb_input_producer(\n np.copy(x_valid), self.batch_size, self.bptt_steps)\n self.y_valid = tf.reshape(self.y_valid, [self.batch_size * self.bptt_steps])\n\n # valid_rl data\n (self.x_valid_rl, self.y_valid_rl,\n self.num_valid_batches) = ptb_input_producer(\n np.copy(x_valid), self.batch_size, self.bptt_steps, randomize=True)\n self.y_valid_rl = tf.reshape(self.y_valid_rl,\n [self.batch_size * self.bptt_steps])\n\n # test data\n self.x_test, self.y_test, self.num_test_batches = ptb_input_producer(\n x_test, 1, 1)\n self.y_test = tf.reshape(self.y_test, [1])\n\n self.x_valid_raw = x_valid\n\n def eval_once(self, sess, eval_set, feed_dict=None, verbose=False):\n \"\"\"Expects self.acc and self.global_step to be defined.\n\n Args:\n sess: tf.Session() or one of its wrap arounds.\n feed_dict: can be used to give more information to sess.run().\n eval_set: \"valid\" or \"test\"\n \"\"\"\n\n assert self.global_step is not None, \"TF op self.global_step not defined.\"\n global_step = sess.run(self.global_step)\n print(\"Eval at {}\".format(global_step))\n \n if eval_set == \"valid\":\n assert self.valid_loss is not None, \"TF op self.valid_loss is not defined.\"\n num_batches = self.num_valid_batches\n loss_op = self.valid_loss\n reset_op = self.valid_reset\n batch_size = self.batch_size\n bptt_steps = self.bptt_steps\n elif eval_set == \"test\":\n assert self.test_loss is not None, \"TF op self.test_loss is not defined.\"\n num_batches = self.num_test_batches\n loss_op = self.test_loss\n reset_op = self.test_reset\n batch_size = 1\n bptt_steps = 1\n else:\n raise ValueError(\"Unknown eval_set '{}'\".format(eval_set))\n\n sess.run(reset_op)\n total_loss = 0\n for batch_id in range(num_batches):\n curr_loss = sess.run(loss_op, feed_dict=feed_dict)\n total_loss += curr_loss # np.minimum(curr_loss, 10.0 * bptt_steps * batch_size)\n ppl_sofar = np.exp(total_loss / (bptt_steps * batch_size * (batch_id + 1)))\n if verbose and (batch_id + 1) % 1000 == 0:\n print(\"{:<5d} {:<6.2f}\".format(batch_id + 1, ppl_sofar))\n if verbose:\n print(\"\")\n log_ppl = total_loss / (num_batches * batch_size * bptt_steps)\n ppl = np.exp(np.minimum(log_ppl, 10.0))\n sess.run(reset_op)\n print(\"{}_total_loss: {:<6.2f}\".format(eval_set, total_loss))\n print(\"{}_log_ppl: {:<6.2f}\".format(eval_set, log_ppl))\n print(\"{}_ppl: {:<6.2f}\".format(eval_set, ppl))\n return ppl\n\n def _build_train(self):\n print(\"Build train graph\")\n all_h, self.train_reset = self._model(self.x_train, True, False)\n log_probs = self._get_log_probs(\n all_h, self.y_train, batch_size=self.batch_size, is_training=True)\n self.loss = tf.reduce_sum(log_probs) / tf.to_float(self.batch_size)\n self.train_ppl = tf.exp(tf.reduce_mean(log_probs))\n\n tf_variables = [\n var for var in tf.trainable_variables() if var.name.startswith(self.name)]\n self.num_vars = count_model_params(tf_variables)\n print(\"-\" * 80)\n print(\"Model has {} parameters\".format(self.num_vars))\n\n loss = self.loss\n if self.rnn_l2_reg is not None:\n loss += (self.rnn_l2_reg * tf.reduce_sum(all_h ** 2) /\n tf.to_float(self.batch_size))\n if self.rnn_slowness_reg is not None:\n loss += (self.rnn_slowness_reg * self.all_h_diff /\n tf.to_float(self.batch_size))\n self.global_step = tf.Variable(\n 0, dtype=tf.int32, trainable=False, name=\"global_step\")\n (self.train_op,\n self.lr,\n self.grad_norm,\n self.optimizer,\n self.grad_norms) = get_train_ops(\n loss,\n tf_variables,\n self.global_step,\n clip_mode=self.clip_mode,\n grad_bound=self.grad_bound,\n l2_reg=self.l2_reg,\n lr_warmup_val=self.lr_warmup_val,\n lr_warmup_steps=self.lr_warmup_steps,\n lr_init=self.lr_init,\n lr_dec_start=self.lr_dec_start,\n lr_dec_every=self.lr_dec_every,\n lr_dec_rate=self.lr_dec_rate,\n lr_dec_min=self.lr_dec_min,\n optim_algo=self.optim_algo,\n moving_average=self.optim_moving_average,\n sync_replicas=self.sync_replicas,\n num_aggregate=self.num_aggregate,\n num_replicas=self.num_replicas,\n get_grad_norms=True,\n )\n\n def _get_log_probs(self, all_h, labels, batch_size=None, is_training=False):\n logits = tf.matmul(all_h, self.w_emb, transpose_b=True)\n log_probs = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits, labels=labels)\n\n return log_probs\n\n def _build_valid(self):\n print(\"-\" * 80)\n print(\"Build valid graph\")\n all_h, self.valid_reset = self._model(self.x_valid, False, False)\n all_h = tf.stop_gradient(all_h)\n log_probs = self._get_log_probs(all_h, self.y_valid)\n self.valid_loss = tf.reduce_sum(log_probs)\n\n def _build_valid_rl(self):\n print(\"-\" * 80)\n print(\"Build valid graph for RL\")\n all_h, self.valid_rl_reset = self._model(\n self.x_valid_rl, False, False, should_carry=False)\n all_h = tf.stop_gradient(all_h)\n log_probs = self._get_log_probs(all_h, self.y_valid_rl)\n self.rl_loss = tf.reduce_mean(log_probs)\n self.rl_loss = tf.stop_gradient(self.rl_loss)\n\n def _build_test(self):\n print(\"-\" * 80)\n print(\"Build test graph\")\n all_h, self.test_reset = self._model(self.x_test, False, True)\n all_h = tf.stop_gradient(all_h)\n log_probs = self._get_log_probs(all_h, self.y_test)\n self.test_loss = tf.reduce_sum(log_probs)\n\n def _rhn_fixed(self, x, prev_s, w_prev, w_skip, is_training,\n x_mask=None, s_mask=None):\n batch_size = prev_s.get_shape()[0].value\n start_idx = self.sample_arc[0] * 2 * self.lstm_hidden_size\n end_idx = start_idx + 2 * self.lstm_hidden_size\n if is_training:\n assert x_mask is not None, \"x_mask is None\"\n assert s_mask is not None, \"s_mask is None\"\n ht = tf.matmul(tf.concat([x * x_mask, prev_s * s_mask], axis=1), w_prev)\n else:\n ht = tf.matmul(tf.concat([x, prev_s], axis=1), w_prev)\n # with tf.variable_scope(\"rhn_layer_0\"):\n # ht = layer_norm(ht, is_training)\n h, t = tf.split(ht, 2, axis=1)\n\n if self.sample_arc[0] == 0:\n h = tf.tanh(h)\n elif self.sample_arc[0] == 1:\n h = tf.nn.relu(h)\n elif self.sample_arc[0] == 2:\n h = tf.identity(h)\n elif self.sample_arc[0] == 3:\n h = tf.sigmoid(h)\n else:\n raise ValueError(\"Unknown func_idx {}\".format(self.sample_arc[0]))\n t = tf.sigmoid(t)\n s = prev_s + t * (h - prev_s)\n layers = [s]\n\n start_idx = 1\n used = np.zeros([self.rhn_depth], dtype=np.int32)\n for rhn_layer_id in range(1, self.rhn_depth):\n with tf.variable_scope(\"rhn_layer_{}\".format(rhn_layer_id)):\n prev_idx = self.sample_arc[start_idx]\n func_idx = self.sample_arc[start_idx + 1]\n used[prev_idx] = 1\n prev_s = layers[prev_idx]\n if is_training:\n ht = tf.matmul(prev_s * s_mask, w_skip[rhn_layer_id])\n else:\n ht = tf.matmul(prev_s, w_skip[rhn_layer_id])\n # ht = layer_norm(ht, is_training)\n h, t = tf.split(ht, 2, axis=1)\n\n if func_idx == 0:\n h = tf.tanh(h)\n elif func_idx == 1:\n h = tf.nn.relu(h)\n elif func_idx == 2:\n h = tf.identity(h)\n elif func_idx == 3:\n h = tf.sigmoid(h)\n else:\n raise ValueError(\"Unknown func_idx {}\".format(func_idx))\n\n t = tf.sigmoid(t)\n s = prev_s + t * (h - prev_s)\n layers.append(s)\n start_idx += 2\n\n layers = [prev_layer for u, prev_layer in zip(used, layers) if u == 0]\n layers = tf.add_n(layers) / np.sum(1.0 - used)\n layers.set_shape([batch_size, self.lstm_hidden_size])\n\n return layers\n\n def _rhn_enas(self, x, prev_s, w_prev, w_skip, is_training,\n x_mask=None, s_mask=None):\n batch_size = prev_s.get_shape()[0].value\n start_idx = self.sample_arc[0] * 2 * self.lstm_hidden_size\n end_idx = start_idx + 2 * self.lstm_hidden_size\n if is_training:\n assert x_mask is not None, \"x_mask is None\"\n assert s_mask is not None, \"s_mask is None\"\n ht = tf.matmul(tf.concat([x * x_mask, prev_s * s_mask], axis=1),\n w_prev[start_idx:end_idx, :])\n else:\n ht = tf.matmul(tf.concat([x, prev_s], axis=1),\n w_prev[start_idx:end_idx, :])\n with tf.variable_scope(\"rhn_layer_0\"):\n ht = batch_norm(ht, is_training)\n h, t = tf.split(ht, 2, axis=1)\n func_idx = self.sample_arc[0]\n h = tf.case(\n {\n tf.equal(func_idx, 0): lambda: tf.tanh(h),\n tf.equal(func_idx, 1): lambda: tf.nn.relu(h),\n tf.equal(func_idx, 2): lambda: tf.identity(h),\n tf.equal(func_idx, 3): lambda: tf.sigmoid(h),\n },\n default=lambda: tf.constant(0.0, dtype=tf.float32), exclusive=True)\n t = tf.sigmoid(t)\n s = prev_s + t * (h - prev_s)\n layers = [s]\n\n start_idx = 1\n used = []\n for rhn_layer_id in range(1, self.rhn_depth):\n with tf.variable_scope(\"rhn_layer_{}\".format(rhn_layer_id)):\n prev_idx = self.sample_arc[start_idx]\n func_idx = self.sample_arc[start_idx + 1]\n curr_used = tf.one_hot(prev_idx, depth=self.rhn_depth, dtype=tf.int32)\n used.append(curr_used)\n w_start = (prev_idx * self.num_funcs + func_idx) * self.lstm_hidden_size\n w_end = w_start + self.lstm_hidden_size\n w = w_skip[rhn_layer_id][w_start:w_end, :]\n prev_s = tf.concat(layers, axis=0)\n prev_s = prev_s[prev_idx*batch_size : (prev_idx+1)*batch_size, :]\n if is_training:\n ht = tf.matmul(prev_s * s_mask, w)\n else:\n ht = tf.matmul(prev_s, w)\n ht = batch_norm(ht, is_training)\n h, t = tf.split(ht, 2, axis=1)\n h = tf.case(\n {\n tf.equal(func_idx, 0): lambda: tf.tanh(h),\n tf.equal(func_idx, 1): lambda: tf.nn.relu(h),\n tf.equal(func_idx, 2): lambda: tf.identity(h),\n tf.equal(func_idx, 3): lambda: tf.sigmoid(h),\n },\n default=lambda: tf.constant(0.0, dtype=tf.float32), exclusive=True)\n t = tf.sigmoid(t)\n s = prev_s + t * (h - prev_s)\n layers.append(s)\n start_idx += 2\n\n used = tf.add_n(used)\n used = tf.equal(used, 0)\n with tf.control_dependencies([tf.Assert(tf.reduce_any(used), [used])]):\n layers = tf.stack(layers)\n layers = tf.boolean_mask(layers, used)\n layers = tf.reduce_mean(layers, axis=0)\n layers.set_shape([batch_size, self.lstm_hidden_size])\n layers = batch_norm(layers, is_training)\n \n return layers\n\n def _model(self, x, is_training, is_test, should_carry=True):\n if is_test:\n start_h = self.test_start_h\n num_steps = 1\n batch_size = 1\n else:\n start_h = self.start_h\n num_steps = self.bptt_steps\n batch_size = self.batch_size\n\n all_h = tf.TensorArray(tf.float32, size=num_steps, infer_shape=True)\n embedding = tf.nn.embedding_lookup(self.w_emb, x)\n\n if is_training:\n def _gen_mask(shape, keep_prob):\n _mask = tf.random_uniform(shape, dtype=tf.float32)\n _mask = tf.floor(_mask + keep_prob) / keep_prob\n return _mask\n\n # variational dropout in the embedding layer\n e_mask = _gen_mask([batch_size, num_steps], self.lstm_e_keep)\n first_e_mask = e_mask\n zeros = tf.zeros_like(e_mask)\n ones = tf.ones_like(e_mask)\n r = [tf.constant([[False]] * batch_size, dtype=tf.bool)] # more zeros to e_mask\n for step in range(1, num_steps):\n should_zero = tf.logical_and(\n tf.equal(x[:, :step], x[:, step:step+1]),\n tf.equal(e_mask[:, :step], 0))\n should_zero = tf.reduce_any(should_zero, axis=1, keep_dims=True)\n r.append(should_zero)\n r = tf.concat(r, axis=1)\n e_mask = tf.where(r, tf.zeros_like(e_mask), e_mask)\n e_mask = tf.reshape(e_mask, [batch_size, num_steps, 1])\n embedding *= e_mask\n\n # variational dropout in the hidden layers\n x_mask, h_mask = [], []\n for layer_id in range(self.lstm_num_layers):\n x_mask.append(_gen_mask([batch_size, self.lstm_hidden_size], self.lstm_x_keep))\n h_mask.append(_gen_mask([batch_size, self.lstm_hidden_size], self.lstm_h_keep))\n h_mask.append(h_mask)\n\n # variational dropout in the output layer\n o_mask = _gen_mask([batch_size, self.lstm_hidden_size], self.lstm_o_keep)\n\n def condition(step, *args):\n return tf.less(step, num_steps)\n\n def body(step, prev_h, all_h):\n with tf.variable_scope(self.name):\n next_h = []\n for layer_id, (p_h, w_prev, w_skip) in enumerate(zip(prev_h, self.w_prev, self.w_skip)):\n with tf.variable_scope(\"layer_{}\".format(layer_id)):\n if layer_id == 0:\n inputs = embedding[:, step, :]\n else:\n inputs = next_h[-1]\n\n if self.fixed_arc is None:\n curr_h = self._rhn_enas(\n inputs, p_h, w_prev, w_skip, is_training,\n x_mask=x_mask[layer_id] if is_training else None,\n s_mask=h_mask[layer_id] if is_training else None)\n else:\n curr_h = self._rhn_fixed(\n inputs, p_h, w_prev, w_skip, is_training,\n x_mask=x_mask[layer_id] if is_training else None,\n s_mask=h_mask[layer_id] if is_training else None)\n\n if self.lstm_l_skip:\n curr_h += inputs\n\n next_h.append(curr_h)\n\n out_h = next_h[-1]\n if is_training:\n out_h *= o_mask\n all_h = all_h.write(step, out_h)\n return step + 1, next_h, all_h\n \n loop_vars = [tf.constant(0, dtype=tf.int32), start_h, all_h]\n loop_outputs = tf.while_loop(condition, body, loop_vars, back_prop=True)\n next_h = loop_outputs[-2]\n all_h = loop_outputs[-1].stack()\n all_h_diff = (all_h[1:, :, :] - all_h[:-1, :, :]) ** 2\n self.all_h_diff = tf.reduce_sum(all_h_diff)\n all_h = tf.transpose(all_h, [1, 0, 2])\n all_h = tf.reshape(all_h, [batch_size * num_steps, self.lstm_hidden_size])\n \n carry_states = []\n reset_states = []\n for layer_id, (s_h, n_h) in enumerate(zip(start_h, next_h)):\n reset_states.append(tf.assign(s_h, tf.zeros_like(s_h), use_locking=True))\n carry_states.append(tf.assign(s_h, tf.stop_gradient(n_h), use_locking=True))\n\n if should_carry:\n with tf.control_dependencies(carry_states):\n all_h = tf.identity(all_h)\n\n return all_h, reset_states\n\n def _build_params(self):\n if self.lstm_hidden_size <= 300:\n init_range = 0.1\n elif self.lstm_hidden_size <= 400:\n init_range = 0.05\n else:\n init_range = 0.04\n initializer = tf.random_uniform_initializer(\n minval=-init_range, maxval=init_range)\n with tf.variable_scope(self.name, initializer=initializer):\n if self.fixed_arc is None:\n with tf.variable_scope(\"rnn\"):\n self.w_prev, self.w_skip = [], []\n for layer_id in range(self.lstm_num_layers):\n with tf.variable_scope(\"layer_{}\".format(layer_id)):\n w_prev = tf.get_variable(\n \"w_prev\",\n [2 * self.num_funcs * self.lstm_hidden_size,\n 2 * self.lstm_hidden_size])\n w_skip = [None]\n for rhn_layer_id in range(1, self.rhn_depth):\n with tf.variable_scope(\"layer_{}\".format(rhn_layer_id)):\n w = tf.get_variable(\n \"w\", [self.num_funcs * rhn_layer_id * self.lstm_hidden_size,\n 2 * self.lstm_hidden_size])\n w_skip.append(w)\n self.w_prev.append(w_prev)\n self.w_skip.append(w_skip)\n else:\n with tf.variable_scope(\"rnn\"):\n self.w_prev, self.w_skip = [], []\n for layer_id in range(self.lstm_num_layers):\n with tf.variable_scope(\"layer_{}\".format(layer_id)):\n w_prev = tf.get_variable(\"w_prev\", [2 * self.lstm_hidden_size,\n 2 * self.lstm_hidden_size])\n w_skip = [None]\n for rhn_layer_id in range(1, self.rhn_depth):\n with tf.variable_scope(\"layer_{}\".format(rhn_layer_id)):\n w = tf.get_variable(\"w\", [self.lstm_hidden_size,\n 2 * self.lstm_hidden_size])\n w_skip.append(w)\n self.w_prev.append(w_prev)\n self.w_skip.append(w_skip)\n\n with tf.variable_scope(\"embedding\"):\n self.w_emb = tf.get_variable(\n \"w\", [self.vocab_size, self.lstm_hidden_size])\n\n with tf.variable_scope(\"starting_states\"):\n zeros = np.zeros(\n [self.batch_size, self.lstm_hidden_size], dtype=np.float32)\n zeros_one_instance = np.zeros(\n [1, self.lstm_hidden_size], dtype=np.float32)\n\n self.start_h, self.test_start_h = [], []\n for _ in range(self.lstm_num_layers):\n self.start_h.append(tf.Variable(zeros, trainable=False))\n self.test_start_h.append(tf.Variable(zeros_one_instance,\n trainable=False))\n\n def connect_controller(self, controller_model):\n if self.fixed_arc is None:\n self.sample_arc = controller_model.sample_arc\n else:\n sample_arc = np.array(\n [x for x in self.fixed_arc.split(\" \") if x], dtype=np.int32)\n self.sample_arc = sample_arc\n\n self._build_params()\n self._build_train()\n self._build_valid()\n self._build_valid_rl()\n self._build_test()\n\n\n"
] | [
[
"tensorflow.get_variable",
"numpy.minimum",
"tensorflow.concat",
"tensorflow.control_dependencies",
"tensorflow.reduce_sum",
"tensorflow.stack",
"tensorflow.equal",
"tensorflow.tanh",
"numpy.exp",
"tensorflow.add_n",
"tensorflow.boolean_mask",
"tensorflow.while_loop",
"tensorflow.Variable",
"tensorflow.random_uniform_initializer",
"tensorflow.floor",
"tensorflow.stop_gradient",
"numpy.copy",
"tensorflow.to_float",
"tensorflow.trainable_variables",
"numpy.zeros",
"tensorflow.matmul",
"tensorflow.less",
"tensorflow.TensorArray",
"tensorflow.reduce_any",
"tensorflow.identity",
"tensorflow.zeros_like",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.one_hot",
"tensorflow.split",
"tensorflow.nn.embedding_lookup",
"numpy.sum",
"tensorflow.nn.relu",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.sigmoid",
"tensorflow.ones_like",
"tensorflow.variable_scope",
"tensorflow.random_uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
wangz49777/Play-Sudoku-automatically | [
"eda522e7ba390a3964874f4e0553048c8acf1fc3"
] | [
"auto_solve_sudoku.py"
] | [
"import cv2\nimport numpy as np\nimport pyautogui\nimport sudoku99\n\nleft = 731\ntop = 120\nwidth = 82\n\n\ndef read_img(image):\n sudoku = np.zeros([9, 9], dtype=np.int)\n img_gray = np.array(image.convert('L'))\n for i in range(1, 10):\n template = cv2.imread('img/{}.png'.format(i), 0)\n h, w = template.shape[:2]\n res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)\n threshold = 0.95\n loc = np.where(res >= threshold)\n out_pts = [(-30, -30)]\n for pt in zip(*loc[::-1]):\n add_flag = True\n for out_pt in out_pts:\n if abs(pt[0] - out_pt[0]) + abs(pt[1] - out_pt[1]) < 30:\n add_flag = False\n break\n if add_flag:\n out_pts.append(pt)\n del out_pts[0]\n for pt in out_pts:\n sudoku[(pt[1] - top) // width][(pt[0] - left) // width] = i\n cv2.rectangle(img_gray, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)\n return sudoku\n\n\ndef complete_sudoku(original_sudoku, sudoku):\n for i in range(9):\n for j in range(9):\n if original_sudoku[i][j] == 0:\n pyautogui.moveTo(left + width * (j + 1), top + width * (i + 1))\n pyautogui.click()\n pyautogui.press(str(sudoku[i][j]))\n\n\nif __name__ == '__main__':\n taskbar = pyautogui.screenshot(region=(0, 1030, 1920, 50))\n taskbar_gray = np.array(taskbar.convert('L'))\n sudoku_ico = cv2.imread('img/sudoku.png', 0)\n loc = cv2.matchTemplate(taskbar_gray, sudoku_ico, cv2.TM_CCOEFF_NORMED)\n pt = np.unravel_index(loc.argmax(), loc.shape)\n pyautogui.moveTo(pt[1] + 25, 1050)\n pyautogui.click()\n pyautogui.sleep(0.5)\n pos = pyautogui.locateCenterOnScreen('img/resume.png', grayscale=False)\n if pos != None:\n pyautogui.moveTo(pos)\n pyautogui.click()\n pyautogui.sleep(0.5)\n screen = pyautogui.screenshot()\n print('开始读取')\n original_sudoku = read_img(screen)\n sum = sum(sum(original_sudoku))\n if sum == 0:\n print(\"读取sudoku失败\")\n exit()\n sudoku = original_sudoku.tolist()\n sudoku = [i for row in sudoku for i in row]\n pointList = sudoku99.initPoint(sudoku)\n sudoku99.showSudoku(sudoku)\n print('开始计算')\n p = pointList.pop()\n sudoku99.tryInsert(p, sudoku, pointList)\n print('计算完毕:')\n sudoku99.showSudoku(sudoku)\n print('自动填充')\n sudoku = np.asarray(sudoku)\n sudoku.resize([9, 9])\n print(original_sudoku)\n print(sudoku)\n complete_sudoku(original_sudoku, sudoku)\n print('自动填充完毕')\n"
] | [
[
"numpy.asarray",
"numpy.zeros",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bhavsarpratik/jina-hub | [
"5d9a804f768e6e8042bbdc0a15fa9d3b8b68ddda"
] | [
"encoders/nlp/FlairTextEncoder/tests/test_flairtextencoder.py"
] | [
"import os\nimport numpy as np\nimport shutil\nimport mock\nimport pytest\n\nfrom .. import FlairTextEncoder\nfrom jina.executors import BaseExecutor\nfrom jina.executors.metas import get_default_metas\n\ntarget_output_dim = 100\n\n\ndef get_metas():\n metas = get_default_metas()\n if 'JINA_TEST_GPU' in os.environ:\n metas['on_gpu'] = True\n return metas\n\n\ndef rm_files(tmp_files):\n for file in tmp_files:\n if file and os.path.exists(file):\n if os.path.isfile(file):\n os.remove(file)\n elif os.path.isdir(file):\n shutil.rmtree(file, ignore_errors=False, onerror=None)\n\n\ntest_data = np.array(['it is a good day!', 'the dog sits on the floor.'])\n\n\nclass MockEmbedding:\n pass\n\n\nclass MockDocumentEmbedding:\n def embed(self, sentences):\n return np.random.random((len(sentences), target_output_dim))\n\n\nclass MockSentence:\n @property\n def embedding(self):\n return np.random.random((1, target_output_dim))\n\n\ndef _test_encoding_results(*args, **kwargs):\n encoder = FlairTextEncoder(embeddings=('word:glove',), pooling_strategy='mean')\n encoded_data = encoder.encode(test_data)\n assert encoded_data.shape == (2, target_output_dim)\n rm_files([encoder.config_abspath, encoder.save_abspath])\n\n\[email protected]('flair.device', return_value='')\[email protected]('flair.embeddings.WordEmbeddings', return_value=MockEmbedding())\[email protected]('flair.embeddings.DocumentPoolEmbeddings', return_value=MockDocumentEmbedding())\[email protected]('flair.data.Sentence', return_value=MockSentence())\ndef test_encoding_results_local(*args, **kwargs):\n _test_encoding_results(*args, **kwargs)\n\n\[email protected]('flair.device', return_value='')\[email protected]('flair.embeddings.WordEmbeddings', return_value=MockEmbedding())\[email protected]('flair.embeddings.DocumentPoolEmbeddings', return_value=MockDocumentEmbedding())\[email protected]('flair.data.Sentence', return_value=MockSentence())\ndef test_save_and_load(*args, **kwargs):\n encoder = FlairTextEncoder(embeddings=('word:glove',), pooling_strategy='mean')\n encoder.touch()\n encoder.save()\n assert os.path.exists(encoder.save_abspath)\n encoder_loaded = BaseExecutor.load(encoder.save_abspath)\n assert encoder_loaded.embeddings == encoder.embeddings\n rm_files([encoder.config_abspath, encoder.save_abspath])\n\n\[email protected]('flair.device', return_value='')\[email protected]('flair.embeddings.WordEmbeddings', return_value=MockEmbedding())\[email protected]('flair.embeddings.FlairEmbeddings', return_value=MockEmbedding())\[email protected]('flair.embeddings.DocumentPoolEmbeddings', return_value=MockDocumentEmbedding())\[email protected]('flair.data.Sentence', return_value=MockSentence())\ndef test_save_and_load_config(*args, **kwargs):\n encoder = FlairTextEncoder(embeddings=('word:glove',), pooling_strategy='mean')\n encoder.save_config()\n assert os.path.exists(encoder.config_abspath)\n encoder_loaded = BaseExecutor.load_config(encoder.config_abspath)\n assert encoder_loaded.max_length == encoder.max_length\n rm_files([encoder.config_abspath, encoder.save_abspath])\n\n\[email protected]('JINA_TEST_PRETRAINED' not in os.environ, reason='skip the pretrained test if not set')\ndef test_encoding_results(*args, **kwargs):\n _test_encoding_results(*args, **kwargs)\n"
] | [
[
"numpy.array",
"numpy.random.random"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ibutsky/cv | [
"4f39bb62871ba9de70284764d38a14b26460335a"
] | [
"get_pubs.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function\n\nimport json\nfrom operator import itemgetter\nimport re\nimport ads\nfrom utf8totex import utf8totex\nfrom titlecase import titlecase\nfrom tqdm import tqdm\nimport numpy as np\nimport time\n\n__all__ = [\"get_papers\"]\n\n\ndef title_callback(word, **kwargs):\n if \"\\\\\" in word:\n return word\n else:\n return None\n\n\ndef format_title(arg):\n \"\"\"\n Customized!\n\n \"\"\"\n\n # Do the conversion\n arg = utf8totex(arg)\n\n # Handle subscripts\n arg = re.sub(\"<SUB>(.*?)</SUB>\", r\"$_\\1$\", arg)\n\n # Fudge O2 paper\n arg = re.sub(\"O2Buildup\", r\"O$_2$ Buildup\", arg)\n\n # Capitalize!\n arg = titlecase(arg, callback=title_callback)\n\n return arg\n\n\ndef format_authors(authors):\n \"\"\"\n Customized!\n\n \"\"\"\n\n # Do the conversion\n authors = list(map(utf8totex, authors))\n\n # Abbreviate names. This drops middle\n # initials -- should eventually fix this.\n for i, author in enumerate(authors):\n match = re.match(\"^(.*?),\\s(.*?)$\", author)\n if match is not None:\n first, last = match.groups()\n authors[i] = \"%s, %s.\" % (first, last[0])\n\n return authors\n\n\ndef manual_exclude(paper):\n \"\"\"Manual exclusions.\"\"\"\n # Remove DDS talks\n if paper.pub == \"LPI Contributions\":\n return True\n\n if paper.pub == \"Bulletin of the American Astronomical Society\":\n return True\n \n # Remove DS Tuc duplicate\n if \"Four Newborn Planets\" in format_title(paper.title[0]) and paper.doi is None:\n return True\n\n return False\n\n\ndef get_papers(author, count_cites=True):\n papers = list(\n ads.SearchQuery(\n author=author,\n fl=[\n \"id\",\n \"title\",\n \"author\",\n \"doi\",\n \"year\",\n \"pubdate\",\n \"pub\",\n \"volume\",\n \"page\",\n \"identifier\",\n \"doctype\",\n \"citation_count\",\n \"bibcode\",\n \"citation\",\n ],\n max_pages=100,\n )\n )\n dicts = []\n\n # Count the citations as a function of time\n citedates = []\n\n # Save bibcodes for later\n bibcodes = []\n\n for paper in papers:\n if not (\n (\"Butsky, Iryna\" in paper.author)\n or (\"Butsky, I.\" in paper.author)\n or (\"Butusky, I\" in paper.author)\n or (\"Butsky, Iryna S.\" in paper.author) \n ):\n print(\"Skipping author: \", paper.author)\n continue\n\n if manual_exclude(paper):\n continue\n\n aid = [\n \":\".join(t.split(\":\")[1:])\n for t in paper.identifier\n if t.startswith(\"arXiv:\")\n ]\n for t in paper.identifier:\n if len(t.split(\".\")) != 2:\n continue\n try:\n list(map(int, t.split(\".\")))\n except ValueError:\n pass\n else:\n aid.append(t)\n try:\n page = int(paper.page[0])\n except ValueError:\n page = None\n if paper.page[0].startswith(\"arXiv:\"):\n aid.append(\":\".join(paper.page[0].split(\":\")[1:]))\n except TypeError:\n page = None\n\n # Get citation dates\n if count_cites and paper.citation is not None:\n for i, bibcode in tqdm(\n enumerate(paper.citation), total=len(paper.citation)\n ):\n try:\n cite = list(ads.SearchQuery(bibcode=bibcode, fl=[\"pubdate\"]))[0]\n date = int(cite.pubdate[:4]) + int(cite.pubdate[5:7]) / 12.0\n citedates.append(date)\n except IndexError:\n pass\n\n # Save bibcode\n bibcodes.append(paper.bibcode)\n\n dicts.append(\n dict(\n doctype=paper.doctype,\n authors=format_authors(paper.author),\n year=paper.year,\n pubdate=paper.pubdate,\n doi=paper.doi[0] if paper.doi is not None else None,\n title=format_title(paper.title[0]),\n pub=paper.pub,\n volume=paper.volume,\n page=page,\n arxiv=aid[0] if len(aid) else None,\n citations=paper.citation_count,\n url=\"http://adsabs.harvard.edu/abs/\" + paper.bibcode,\n )\n )\n\n if count_cites:\n # Sort the cite dates\n citedates = sorted(citedates)\n np.savetxt(\"citedates.txt\", citedates, fmt=\"%.3f\")\n\n # Save bibcodes\n with open(\"bibcodes.txt\", \"w\") as f:\n for bibcode in bibcodes:\n print(bibcode, file=f)\n\n return sorted(dicts, key=itemgetter(\"pubdate\"), reverse=True)\n\n\nif __name__ == \"__main__\":\n papers = get_papers(\"Butsky, I\", count_cites=True)\n with open(\"pubs.json\", \"w\") as f:\n json.dump(papers, f, sort_keys=True, indent=2, separators=(\",\", \": \"))\n"
] | [
[
"numpy.savetxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
andrescevp/pyEX | [
"4c8daa411b01133a292d341a78f6e1b80cc2be99"
] | [
"pyEX/studies/technicals/pattern.py"
] | [
"# -*- coding: utf-8 -*-\nimport talib as t\nimport pandas as pd\n\n\ndef cdl2crows(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of Two crows for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDL2CROWS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdl2crows\": val,\n }\n )\n\n\ndef cdl3blackcrows(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of 3 black crows for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDL3BLACKCROWS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdl3blackcrows\": val,\n }\n )\n\n\ndef cdl3inside(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of 3 inside up/down for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDL3INSIDE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdl3inside\": val,\n }\n )\n\n\ndef cdl3linestrike(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of 3 line strike for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDL3LINESTRIKE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdl3linestrike\": val,\n }\n )\n\n\ndef cdl3outside(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of 3 outside for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDL3OUTSIDE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdl3outside\": val,\n }\n )\n\n\ndef cdl3starsinsouth(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of 3 stars in south for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDL3STARSINSOUTH(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdl3starsinsouth\": val,\n }\n )\n\n\ndef cdl3whitesoldiers(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of 3 white soldiers for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDL3WHITESOLDIERS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdl3whitesoldiers\": val,\n }\n )\n\n\ndef cdlabandonedbaby(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of abandoned baby for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLABANDONEDBABY(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlabandonedbaby\": val,\n }\n )\n\n\ndef cdladvanceblock(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of advance block for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLADVANCEBLOCK(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdladvanceblock\": val,\n }\n )\n\n\ndef cdlbelthold(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of belt hold for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLBELTHOLD(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlbelthold\": val,\n }\n )\n\n\ndef cdlbreakaway(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of breakaway for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLBREAKAWAY(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlbreakaway\": val,\n }\n )\n\n\ndef cdlclosingmarubozu(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of closing maru bozu for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLCLOSINGMARUBOZU(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlclosingmarubozu\": val,\n }\n )\n\n\ndef cdlconcealbabyswallow(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of conceal baby swallow for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLCONCEALBABYSWALL(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlconcealbabyswallow\": val,\n }\n )\n\n\ndef cdlcounterattack(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of counterattack for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLCOUNTERATTACK(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlcounterattack\": val,\n }\n )\n\n\ndef cdldarkcloudcover(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n penetration=0,\n):\n \"\"\"This will return a dataframe of dark cloud cover for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n penetration (int): penetration\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLDARKCLOUDCOVER(\n df[opencol].values,\n df[highcol].values,\n df[lowcol].values,\n df[closecol].values,\n penetration,\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdldarkcloudcover\": val,\n }\n )\n\n\ndef cdldoji(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of doji for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLDOJI(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdldoji\": val,\n }\n )\n\n\ndef cdldojistar(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of doji star for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLDOJISTAR(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdldojistar\": val,\n }\n )\n\n\ndef cdldragonflydoji(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of dragonfly doji for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLDRAGONFLYDOJI(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdldragonflydoji\": val,\n }\n )\n\n\ndef cdlengulfing(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of engulfing for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLENGULFING(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlengulfing\": val,\n }\n )\n\n\ndef cdleveningdojistar(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n penetration=0,\n):\n \"\"\"This will return a dataframe of evening doji star for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n penetration (int): penetration\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLEVENINGDOJISTAR(\n df[opencol].values,\n df[highcol].values,\n df[lowcol].values,\n df[closecol].values,\n penetration,\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdleveningdojistar\": val,\n }\n )\n\n\ndef cdleveningstar(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n penetration=0,\n):\n \"\"\"This will return a dataframe of evening star for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n penetration (int): penetration\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLEVENINGSTAR(\n df[opencol].values,\n df[highcol].values,\n df[lowcol].values,\n df[closecol].values,\n penetration,\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdleveningstar\": val,\n }\n )\n\n\ndef cdlgapsidesidewhite(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of up.down-gap side-by-side white lines for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLGAPSIDESIDEWHITE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlgapsidesidewhite\": val,\n }\n )\n\n\ndef cdlgravestonedoji(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of gravestone doji for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLGRAVESTONEDOJI(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlgravestonedoji\": val,\n }\n )\n\n\ndef cdlhammer(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of hammer for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHAMMER(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlhammer\": val,\n }\n )\n\n\ndef cdlhangingman(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of hanging man for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHANGINGMAN(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlhangingman\": val,\n }\n )\n\n\ndef cdlharami(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of harami for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHARAMI(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlharami\": val,\n }\n )\n\n\ndef cdlharamicross(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of harami cross for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHARAMICROSS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlharamicross\": val,\n }\n )\n\n\ndef cdlhighwave(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of high-wave candle for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHIGHWAVE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlhighwave\": val,\n }\n )\n\n\ndef cdlhikkake(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of hikkake pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHIKKAKE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlhikkake\": val,\n }\n )\n\n\ndef cdlhikkakemod(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of modified hikkake pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHIKKAKEMOD(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlhikkakemod\": val,\n }\n )\n\n\ndef cdlhomingpigeon(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of homing pigeon for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLHOMINGPIGEON(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlhomingpigeon\": val,\n }\n )\n\n\ndef cdlidentical3crows(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of identical three crows for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLIDENTICAL3CROWS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlidentical3crows\": val,\n }\n )\n\n\ndef cdlinneck(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of in-neck pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLINNECK(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlinneck\": val,\n }\n )\n\n\ndef cdlinvertedhammer(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of inverted hammer for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLINVERTEDHAMMER(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlinvertedhammer\": val,\n }\n )\n\n\ndef cdlkicking(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of kicking for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLKICKING(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlkicking\": val,\n }\n )\n\n\ndef cdlkickingbylength(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of kicking bull/bear determing by the longer marubozu for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLKICKINGBYLENGTH(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlkickingbylength\": val,\n }\n )\n\n\ndef cdlladderbottom(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of ladder bottom for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLLADDERBOTTOM(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlladderbottom\": val,\n }\n )\n\n\ndef cdllongleggeddoji(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of long legged doji for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLLONGLEGGEDDOJI(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdllongleggeddoji\": val,\n }\n )\n\n\ndef cdllongline(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of long line candle for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLLONGLINE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdllongline\": val,\n }\n )\n\n\ndef cdlmarubozu(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of marubozu for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLMARUBOZU(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlmarubozu\": val,\n }\n )\n\n\ndef cdlmatchinglow(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of matching low for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLMATCHINGLOW(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlmatchinglow\": val,\n }\n )\n\n\ndef cdlmathold(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n penetration=0,\n):\n \"\"\"This will return a dataframe of mat hold for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n penetration (int): penetration\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLMATHOLD(\n df[opencol].values,\n df[highcol].values,\n df[lowcol].values,\n df[closecol].values,\n penetration,\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlmathold\": val,\n }\n )\n\n\ndef cdlmorningdojistar(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n penetration=0,\n):\n \"\"\"This will return a dataframe of morning doji star for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n penetration (int): penetration\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLMORNINGDOJISTAR(\n df[opencol].values,\n df[highcol].values,\n df[lowcol].values,\n df[closecol].values,\n penetration,\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlmorningdojistar\": val,\n }\n )\n\n\ndef cdlmorningstar(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n penetration=0,\n):\n \"\"\"This will return a dataframe of morning star for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n penetration (int): penetration\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLMORNINGSTAR(\n df[opencol].values,\n df[highcol].values,\n df[lowcol].values,\n df[closecol].values,\n penetration,\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlmorningstar\": val,\n }\n )\n\n\ndef cdlonneck(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of on-neck pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLONNECK(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlonneck\": val,\n }\n )\n\n\ndef cdlpiercing(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of piercing pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLPIERCING(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlpiercing\": val,\n }\n )\n\n\ndef cdlrickshawman(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of rickshaw man for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLRICKSHAWMAN(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlrickshawman\": val,\n }\n )\n\n\ndef cdlrisefall3methods(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of rising/falling three methods for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLRISEFALL3METHODS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlrisefall3methods\": val,\n }\n )\n\n\ndef cdlseparatinglines(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of separating lines for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLSEPARATINGLINES(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlseparatinglines\": val,\n }\n )\n\n\ndef cdlshootingstar(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of shooting star for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLSHOOTINGSTAR(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlshootingstar\": val,\n }\n )\n\n\ndef cdlshortline(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of short line candle for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLSHORTLINE(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlshortline\": val,\n }\n )\n\n\ndef cdlspinningtop(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of spinning top for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLSPINNINGTOP(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlspinningtop\": val,\n }\n )\n\n\ndef cdlstalledpattern(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of stalled pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLSTALLEDPATTERN(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlstalledpattern\": val,\n }\n )\n\n\ndef cdlsticksandwich(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of stick sandwich for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLSTICKSANDWICH(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlsticksandwich\": val,\n }\n )\n\n\ndef cdltakuri(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of takuri dragonfly doji with very long lower shadow for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLTAKURI(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdltakuri\": val,\n }\n )\n\n\ndef cdltasukigap(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of tasuki gap for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLTASUKIGAP(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdltasukigap\": val,\n }\n )\n\n\ndef cdlthrusting(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of thrusting pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLTHRUSTING(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlthrusting\": val,\n }\n )\n\n\ndef cdltristar(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of tristar pattern for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLTRISTAR(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdltristar\": val,\n }\n )\n\n\ndef cdlunique3river(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of unique 3 river for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLUNIQUE3RIVER(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlunique3river\": val,\n }\n )\n\n\ndef cdlupsidegap2crows(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of upside gap two crows for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLUPSIDEGAP2CROWS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlupsidegap2crows\": val,\n }\n )\n\n\ndef cdlxsidegap3methods(\n client,\n symbol,\n timeframe=\"6m\",\n opencol=\"open\",\n highcol=\"high\",\n lowcol=\"low\",\n closecol=\"close\",\n):\n \"\"\"This will return a dataframe of upside/downside gap three methods for the given symbol across\n the given timeframe\n\n Args:\n client (pyEX.Client): Client\n symbol (string): Ticker\n timeframe (string): timeframe to use, for pyEX.chart\n opencol (string): column to use to calculate\n highcol (string): column to use to calculate\n lowcol (string): column to use to calculate\n closecol (string): column to use to calculate\n\n Returns:\n DataFrame: result\n \"\"\"\n df = client.chartDF(symbol, timeframe)\n val = t.CDLXSIDEGAP3METHODS(\n df[opencol].values, df[highcol].values, df[lowcol].values, df[closecol].values\n )\n return pd.DataFrame(\n {\n opencol: df[opencol].values,\n highcol: df[highcol].values,\n lowcol: df[lowcol].values,\n closecol: df[closecol].values,\n \"cdlxsidegap3methods\": val,\n }\n )\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
roysaurabh1308/Cryptographic-Algorithms | [
"a8a92548b8d15fe317e0658f14385b6a4e29c5ce"
] | [
"Playfair_cipher.py"
] | [
"import numpy as np\r\nimport random\r\n#X=np.array([chr(x) for x in range(65,91) and x!=73])\r\nKey=np.array([['L','G','D','B','A'],['Q','M','H','E','C'],['U','R','N','I','F'],['X','V','S','O','K'],['Z','Y','W','T','P']])\r\nmsg=input(\"Enter message: \")\r\nMsg=[x for x in msg]\r\nT=[];i=-1\r\nfor x in range(len(Msg)-1):\r\n if(Msg[x]==Msg[x+1]):\r\n T+=['1'];i+=1\r\n T[i]=x+1\r\nfor j in T:\r\n Msg.insert(j,'X')\r\nif len(Msg)%2!=0:\r\n Msg.append('X')\r\nprint(\"Modified:\",Msg)\r\nprint()\r\nC=\"\"\r\nfor x in range(0,len(Msg)-1,2):\r\n c1=list(zip(*np.where(Key == Msg[x])))\r\n c2=list(zip(*np.where(Key == Msg[x+1])))\r\n if(c1[0][0]==c2[0][0]):\r\n C+=Key[c1[0][0]][(c1[0][1]+1)%5]+Key[c1[0][0]][(c2[0][1]+1)%5]\r\n elif(c1[0][1]==c2[0][1]):\r\n C+=Key[(c1[0][0]+1)%5][c1[0][1]]+Key[(c2[0][0]+1)%5][c1[0][1]]\r\n else:\r\n C+=Key[c1[0][0]][c2[0][1]]+Key[c2[0][0]][c1[0][1]]\r\nprint(\"Cipher text:\",C)\r\nprint(\"Decrypted Text:\",msg)"
] | [
[
"numpy.array",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
anthonyhsyu/tune-sklearn | [
"9216d31c25a09c61b650a85560b9045cbbac94ce"
] | [
"examples/sgd.py"
] | [
"\"\"\"\nAn example training an SGDClassifier, performing grid search\nusing TuneGridSearchCV.\n\nThis example uses early stopping to further improve runtimes\nby eliminating worse hyperparameter choices early based off\nof its average test score from cross validation.\n\"\"\"\n\nfrom tune_sklearn import TuneGridSearchCV\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom ray.tune.schedulers import MedianStoppingRule\nimport numpy as np\n\ndigits = datasets.load_digits()\nx = digits.data\ny = digits.target\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2)\n\nclf = SGDClassifier()\nparameter_grid = {\"alpha\": [1e-4, 1e-1, 1], \"epsilon\": [0.01, 0.1]}\n\nscheduler = MedianStoppingRule(grace_period=10.0)\n\ntune_search = TuneGridSearchCV(\n clf,\n parameter_grid,\n early_stopping=scheduler,\n max_iters=10,\n)\ntune_search.fit(x_train, y_train)\n\npred = tune_search.predict(x_test)\naccuracy = np.count_nonzero(np.array(pred) == np.array(y_test)) / len(pred)\nprint(accuracy)\n"
] | [
[
"numpy.array",
"sklearn.model_selection.train_test_split",
"sklearn.datasets.load_digits",
"sklearn.linear_model.SGDClassifier"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kids-first/kf-lib-data-ingest | [
"92889efef082c64744a00a9c110d778da7383959"
] | [
"kf_lib_data_ingest/validation/reporting/table.py"
] | [
"\"\"\"\nTable based validation report builder. Produces the following tabular files:\n\ntable_reports/\n - validation_results.tsv\n - files_validated.tsv\n - type_counts.tsv\n\nUnpack the validation results JSON into a tabular form where the content is\na little bit less nested and verbose\n\nExtends kf_lib_data_ingest.validation.reporting.base.AbstractReportBuilder\n\"\"\"\nimport os\nfrom collections import defaultdict\n\nimport pandas\nfrom kf_lib_data_ingest.validation.reporting.base import (\n RESULTS_FILENAME,\n AbstractReportBuilder,\n)\n\nTYPE_COUNTS_FILENAME = \"type_counts.tsv\"\nFILES_VALIDATED_FILENAME = \"files_validated.tsv\"\n\n\nclass TableReportBuilder(AbstractReportBuilder):\n def __init__(self, output_dir=None, setup_logger=False):\n \"\"\"\n Constructor - see AbstractReportBuilder.__init__\n \"\"\"\n super().__init__(output_dir=output_dir, setup_logger=setup_logger)\n\n def _build(self, results):\n \"\"\"\n Build a pandas.DataFrame from the list of validation test result dicts\n\n :param results: See AbstractReportBuilder._build\n :param type: See AbstractReportBuilder._build\n :param title: Report title\n :type title: str\n \"\"\"\n dfs = []\n # Validation results table\n row_dicts = [\n rd\n for r in results[\"validation\"]\n for rd in self._result_dict_to_df_row(r)\n ]\n dfs.append(\n (\n pandas.DataFrame(row_dicts)[\n [\n \"type\",\n \"result\",\n \"description\",\n \"errors\",\n \"locations\",\n \"details\",\n ]\n ],\n RESULTS_FILENAME + \".tsv\",\n )\n )\n # Type counts table\n dfs.append(\n (\n pandas.DataFrame(\n [\n {\"Entity\": typ, \"Count\": count}\n for typ, count in results[\"counts\"].items()\n ]\n ),\n TYPE_COUNTS_FILENAME,\n )\n )\n # Files validated\n dfs.append(\n (\n pandas.DataFrame(\n results[\"files_validated\"], columns={\"Files Validated\"}\n ),\n FILES_VALIDATED_FILENAME,\n )\n )\n\n return dfs\n\n def _write_report(self, dfs):\n \"\"\"\n Write tabular validation report files to disk:\n\n table_reports/\n - validation_results.tsv -> Validation test results\n - files_validated.tsv -> List of files validated\n - type_counts.tsv -> Entity counts by type\n\n :param dfs: list of (pandas.DataFrame, filename)\n :type dfs: list of tuples\n \"\"\"\n output_dir = os.path.join(self.output_dir, \"table_reports\")\n os.makedirs(output_dir, exist_ok=True)\n\n for df, fn in dfs:\n df.to_csv(os.path.join(output_dir, fn), sep=\"\\t\", index=False)\n\n return output_dir\n\n def _result_dict_to_df_row(self, result):\n \"\"\"\n Unpack verbose, nested validation result dict into a simpler dict\n suitable for a pandas.DataFrame row\n\n :param result: See sample_validation_results.py\n :type result: dict\n \"\"\"\n row_dicts = []\n # Successful tests or tests that did not run\n if not result[\"errors\"]:\n row_dicts.append({\"errors\": None, \"locations\": None})\n # -- Failed tests --\n elif result[\"type\"] == \"count\":\n row_dicts.append({\"errors\": result[\"errors\"], \"locations\": None})\n elif result[\"type\"] == \"attribute\":\n for filepath, invalid_values in result[\"errors\"].items():\n row_dicts.append(\n {\"errors\": set(invalid_values), \"locations\": filepath}\n )\n elif result[\"type\"] == \"relationship\":\n for error in result[\"errors\"]:\n # Errors\n from_type, from_val = error[\"from\"]\n details = {from_val: from_type}\n to_nodes = []\n for to_node in error[\"to\"]:\n to_type, to_val = to_node\n to_nodes.append(to_val)\n details[to_val] = to_type\n formatted_errors = (from_val, to_nodes)\n\n # Locations\n formatted_locations = defaultdict(set)\n for (typ, val), files in error[\"locations\"].items():\n for f in files:\n formatted_locations[f].add(f\"`{val}`\")\n\n row_dicts.append(\n {\n \"errors\": formatted_errors,\n \"locations\": dict(formatted_locations),\n \"details\": details,\n }\n )\n\n for rd in row_dicts:\n rd.update(\n {\n \"type\": result[\"type\"],\n \"description\": result[\"description\"],\n \"result\": self._result_code(result),\n \"details\": rd.get(\"details\"),\n }\n )\n\n return row_dicts\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
mewim/d3l | [
"ce3874b98965be828059c7d9eee7c1ee810a84b2"
] | [
"d3l/indexing/feature_extraction/values/fasttext_embedding_transformer.py"
] | [
"import os\nimport shutil\nfrom typing import Iterable, Optional, Set\nfrom urllib.request import urlopen\n\nimport numpy as np\nimport gzip\nfrom fasttext import load_model\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom d3l.utils.constants import FASTTEXTURL, STOPWORDS\nfrom d3l.utils.functions import shingles\n\n\nclass FasttextTransformer:\n def __init__(\n self,\n token_pattern: str = r\"(?u)\\b\\w\\w+\\b\",\n max_df: float = 0.5,\n stop_words: Iterable[str] = STOPWORDS,\n embedding_model_lang=\"en\",\n cache_dir: Optional[str] = None,\n ):\n \"\"\"\n Instantiate a new embedding-based transformer\n Parameters\n ----------\n token_pattern : str\n The regex used to identify tokens.\n The default value is scikit-learn's TfidfVectorizer default.\n max_df : float\n Percentage of values the token can appear in before it is ignored.\n stop_words : Iterable[str]\n A collection of stopwords to ignore that defaults to NLTK's English stopwords.\n embedding_model_lang : str\n The embedding model language.\n cache_dir : Optional[str]\n An exising directory path where the model will be stored.\n If not given, the current working directory will be used.\n \"\"\"\n\n self._token_pattern = token_pattern\n self._max_df = max_df\n self._stop_words = stop_words\n self._embedding_model_lang = embedding_model_lang\n self._cache_dir = (\n cache_dir if cache_dir is not None and os.path.isdir(cache_dir) else None\n )\n\n self._embedding_model = self.get_embedding_model(\n overwrite=False,\n )\n\n def __getstate__(self):\n d = self.__dict__\n self_dict = {k: d[k] for k in d if k != \"_embedding_model\"}\n return self_dict\n\n def __setstate__(self, state):\n self.__dict__ = state\n self._embedding_model = self.get_embedding_model(overwrite=False)\n\n @property\n def cache_dir(self) -> Optional[str]:\n return self._cache_dir\n\n def _download_fasttext(self, model_file_name: str, chunk_size: int = 2 ** 13):\n \"\"\"\n Download pre-trained common-crawl vectors from fastText's website\n https://fasttext.cc/docs/en/crawl-vectors.html\n\n Parameters\n ----------\n model_file_name : str\n The model file name to download.\n chunk_size : int\n The Fasttext models are commonly large - several GBs.\n The disk writing will therefore be made in chunks.\n\n Returns\n -------\n\n \"\"\"\n\n url = FASTTEXTURL + model_file_name\n print(\"Downloading %s\" % url)\n response = urlopen(url)\n\n downloaded = 0\n write_file_name = (\n os.path.join(self._cache_dir, model_file_name)\n if self._cache_dir is not None\n else model_file_name\n )\n download_file_name = write_file_name + \".part\"\n with open(download_file_name, \"wb\") as f:\n while True:\n chunk = response.read(chunk_size)\n downloaded += len(chunk)\n if not chunk:\n break\n f.write(chunk)\n # print(\"{} downloaded ...\".format(downloaded))\n\n os.rename(download_file_name, write_file_name)\n\n def _download_model(self, if_exists: str = \"strict\"):\n \"\"\"\n Download the pre-trained model file.\n Parameters\n ----------\n if_exists : str\n Supported values:\n - *ignore*: The model will not be downloaded\n - *strict*: This is the defaul. The model will be downloaded only if it does not exist at the *cache_dir*.\n - *overwrite*: The model will be downloaded even if it already exists at the *cache_dir*.\n\n Returns\n -------\n\n \"\"\"\n\n base_file_name = \"cc.%s.300.bin\" % self._embedding_model_lang\n file_name = (\n os.path.join(self._cache_dir, base_file_name)\n if self._cache_dir is not None\n else base_file_name\n )\n gz_file_name = \"%s.gz\" % base_file_name\n\n if os.path.isfile(file_name):\n if if_exists == \"ignore\":\n return file_name\n elif if_exists == \"strict\":\n print(\"File exists. Use --overwrite to download anyway.\")\n return file_name\n elif if_exists == \"overwrite\":\n pass\n\n absolute_gz_file_name = (\n os.path.join(self._cache_dir, gz_file_name)\n if self._cache_dir is not None\n else gz_file_name\n )\n if not os.path.isfile(absolute_gz_file_name):\n self._download_fasttext(gz_file_name)\n\n with gzip.open(absolute_gz_file_name, \"rb\") as f:\n with open(file_name, \"wb\") as f_out:\n shutil.copyfileobj(f, f_out)\n\n \"\"\"Cleanup\"\"\"\n if os.path.isfile(absolute_gz_file_name):\n os.remove(absolute_gz_file_name)\n\n return file_name\n\n def get_embedding_model(\n self,\n overwrite: bool = False,\n ):\n \"\"\"\n Download, if not exists, and load the pretrained FastText embedding model in the working directory.\n Note that the default gzipped English Common Crawl FastText model has 4.2 GB\n and its unzipped version has 6.7 GB.\n Parameters\n ----------\n overwrite : bool\n If True overwrites the model if exists.\n\n Returns\n -------\n\n \"\"\"\n if_exists = \"strict\" if not overwrite else \"overwrite\"\n\n model_file = self._download_model(if_exists=if_exists)\n embedding_model = load_model(model_file)\n return embedding_model\n\n def get_embedding_dimension(self) -> int:\n \"\"\"\n Retrieve the embedding dimensions of the underlying model.\n Returns\n -------\n int\n The dimensions of each embedding\n \"\"\"\n return self._embedding_model.get_dimension()\n\n def get_vector(self, word: str) -> np.ndarray:\n \"\"\"\n Retrieve the embedding of the given word.\n If the word is out of vocabulary a zero vector is returned.\n Parameters\n ----------\n word : str\n The word to retrieve the vector for.\n\n Returns\n -------\n np.ndarray\n A vector of float numbers.\n \"\"\"\n vector = self._embedding_model.get_word_vector(\n str(word).strip().lower(), np.random.randn(self.get_embedding_dimension())\n )\n return vector\n\n def get_tokens(self, input_values: Iterable[str]) -> Set[str]:\n \"\"\"\n Extract the most representative tokens of each value and return the token set.\n Here, the most representative tokens are the ones with the lowest TF/IDF scores -\n tokens that describe what the values are about.\n Parameters\n ----------\n input_values : Iterable[str]\n The collection of values to extract tokens from.\n\n Returns\n -------\n Set[str]\n A set of representative tokens\n \"\"\"\n\n if len(input_values) < 1:\n return set()\n\n try:\n vectorizer = TfidfVectorizer(\n decode_error=\"ignore\",\n strip_accents=\"unicode\",\n lowercase=True,\n analyzer=\"word\",\n stop_words=self._stop_words,\n token_pattern=self._token_pattern,\n max_df=self._max_df,\n use_idf=True,\n )\n vectorizer.fit_transform(input_values)\n except ValueError:\n return set()\n\n weight_map = dict(zip(vectorizer.get_feature_names(), vectorizer.idf_))\n tokenset = set()\n tokenizer = vectorizer.build_tokenizer()\n for value in input_values:\n value = value.lower().replace(\"\\n\", \" \").strip()\n for shingle in shingles(value):\n tokens = [t for t in tokenizer(shingle)]\n\n if len(tokens) < 1:\n continue\n\n token_weights = [weight_map.get(t, 0.0) for t in tokens]\n min_tok_id = np.argmin(token_weights)\n tokenset.add(tokens[min_tok_id])\n\n return tokenset\n\n def transform(self, input_values: Iterable[str]) -> np.ndarray:\n \"\"\"\n Extract the embeddings of the most representative tokens of each value and return their **mean** embedding.\n Here, the most representative tokens are the ones with the lowest TF/IDF scores -\n tokens that describe what the values are about.\n Given that the underlying embedding model is a n-gram based one,\n the number of out-of-vocabulary tokens should be relatively small or zero.\n Parameters\n ----------\n input_values : Iterable[str]\n The collection of values to extract tokens from.\n\n Returns\n -------\n np.ndarray\n A Numpy vector representing the mean of all token embeddings.\n \"\"\"\n\n embeddings = [self.get_vector(token) for token in self.get_tokens(input_values)]\n if len(embeddings) == 0:\n return np.empty(0)\n return np.mean(np.array(embeddings), axis=0)\n"
] | [
[
"numpy.array",
"numpy.argmin",
"sklearn.feature_extraction.text.TfidfVectorizer",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dankovacek/flood_frequency | [
"3bdbac49f5eb033f891058b17c755c83fade043a"
] | [
"main.py"
] | [
"import os\nimport math\n\nimport numpy as np\nimport pandas as pd\nimport time\n\nimport scipy.special\nimport scipy.stats as st\n\nfrom multiprocessing import Pool\n\nfrom bokeh.layouts import row, column\nfrom bokeh.models import CustomJS, Slider, Band, Spinner\nfrom bokeh.plotting import figure, curdoc, ColumnDataSource\nfrom bokeh.models.widgets import AutocompleteInput, Div\n\nfrom get_station_data import get_daily_UR, get_annual_inst_peaks\n\nfrom stations import IDS_AND_DAS, STATIONS_DF, IDS_TO_NAMES, NAMES_TO_IDS\n\ndef get_stats(data, param):\n mean = data[param].mean()\n var = np.var(data[param])\n stdev = data[param].std()\n skew = st.skew(data[param])\n return mean, var, stdev, skew\n\n\ndef calculate_Tr(data, param, correction_factor=None):\n if correction_factor is None:\n correction_factor = 1\n\n data['rank'] = data[param].rank(ascending=False, method='first')\n data.loc[:, 'logQ'] = list(map(math.log, data[param]))\n\n # mean_Q, var_Q, stdev_Q, skew_Q = get_stats(data, param)\n\n# print('mean: {}, var: {}, stdev: {}, skew: {}'.format(\n# round(mean_Q, 2), round(var_Q, 2), round(stdev_Q, 2), round(skew_Q, 2)))\n data['Tr'] = (len(data) + 1) / \\\n data['rank'].astype(int).round(1)\n\n data.sort_values(by='rank', inplace=True, ascending=False)\n\n return data # , mean_Q, var_Q, stdev_Q, skew_Q\n\n\ndef norm_ppf(x):\n if x == 1.0:\n x += 0.001\n return st.norm.ppf(1-(1/x))\n\n\ndef update_UI_text_output(n_years):\n ffa_info.text = \"\"\"Mean of {} simulations of a sample size {} \\n\n out of a total {} years of record. \\n\n Bands indicate 1 and 2 standard deviations from the mean, respectively.\"\"\".format(\n simulation_number_input.value, sample_size_input.value, n_years)\n\n error_info.text = \"\"\n\n\ndef run_ffa_simulation(data, target_param, n_simulations):\n # reference:\n # https://nbviewer.jupyter.org/github/demotu/BMC/blob/master/notebooks/CurveFitting.ipynb\n\n model = pd.DataFrame()\n model['Tr'] = np.linspace(1.01, 200, 500)\n model.set_index('Tr', inplace=True)\n\n model['z'] = list(map(norm_ppf, model.index.values))\n\n for i in range(n_simulations):\n\n sample_set = data.sample(\n sample_size_input.value, replace=False)\n\n selection = calculate_Tr(sample_set, target_param)\n\n # log-pearson distribution\n log_skew = st.skew(np.log10(selection[target_param]))\n\n lp3 = 2 / log_skew * \\\n (np.power((model['z'] - log_skew / 6) * log_skew / 6 + 1, 3) - 1)\n\n lp3_model = np.power(10, np.mean(\n np.log10(selection[target_param])) + lp3 * np.std(np.log10(selection[target_param])))\n\n model[i] = lp3_model\n return model\n\n\ndef update():\n station_name = station_name_input.value.split(':')[-1].strip()\n df = get_annual_inst_peaks(\n NAMES_TO_IDS[station_name])\n\n # set the target param to PEAK to extract peak annual values \n target_param = 'PEAK'\n\n if len(df) < 2:\n error_info.text = \"Error, insufficient data in record (n = {}). Resetting to default.\".format(\n len(df))\n station_name_input.value = IDS_TO_NAMES['08MH016']\n update()\n\n data = calculate_Tr(df, 'PEAK')\n data.sort_values('Tr', ascending=False, inplace=True)\n\n data['Mean'] = np.mean(data['PEAK'])\n\n n_years = len(data)\n print('number of years of data = {}'.format(n_years))\n print(\"\")\n\n # prevent the sample size from exceeding the\n # length of record\n if n_years < sample_size_input.value:\n sample_size_input.value = n_years - 1\n\n\n # Run the FFA fit simulation on a sample of specified size\n ## number of times to run the simulation\n n_simulations = simulation_number_input.value\n\n time0 = time.time()\n model = run_ffa_simulation(data, target_param, n_simulations)\n time_end = time.time()\n print(\"Time for {:.0f} simulations = {:0.2f} s\".format(\n n_simulations, time_end - time0))\n\n # plot the log-pearson fit to the entire dataset\n log_skew = st.skew(np.log10(data[target_param]))\n z_model = np.array(list(map(norm_ppf, model.index.values)))\n z_empirical = np.array(list(map(norm_ppf, data['Tr'])))\n\n lp3_model = 2 / log_skew * \\\n (np.power((z_model - log_skew / 6) * log_skew / 6 + 1, 3) - 1)\n\n lp3_empirical = 2 / log_skew * \\\n (np.power((z_empirical - log_skew/6)*log_skew/6 + 1, 3)-1)\n\n lp3_quantiles_model = np.power(10, np.mean(\n np.log10(data[target_param])) + lp3_model*np.std(np.log10(data[target_param])))\n\n lp3_quantiles_empirical = np.power(10, np.mean(\n np.log10(data[target_param])) + lp3_empirical*np.std(np.log10(data[target_param])))\n\n data['theoretical'] = lp3_quantiles_empirical\n\n data['empirical_cdf'] = data['rank'] / (len(data) + 1)\n\n # pearson_fit_params = st.pearson3.fit(np.log(data['PEAK']))\n\n # reverse the order for proper plotting on P-P plot\n data['theoretical_cdf'] = st.pearson3.cdf(z_empirical, skew=log_skew)[::-1]\n\n # update the peak flow data source\n peak_source.data = peak_source.from_df(data)\n data_flag_filter = data[~data['SYMBOL'].isin([None, ' '])]\n peak_flagged_source.data = peak_flagged_source.from_df(data_flag_filter)\n\n # plot the simulation error bounds\n mean_models = model.apply(lambda row: row.mean(), axis=1)\n stdev_models = model.apply(lambda row: row.std(), axis=1)\n\n simulation = {'Tr': model.index,\n 'lower_1_sigma': np.subtract(mean_models, stdev_models),\n 'upper_1_sigma': np.add(mean_models, stdev_models),\n 'lower_2_sigma': np.subtract(mean_models, 2*stdev_models),\n 'upper_2_sigma': np.add(mean_models, 2*stdev_models),\n 'mean': mean_models,\n 'lp3_model': lp3_quantiles_model\n } \n\n distribution_source.data = simulation\n \n update_UI_text_output(n_years)\n\n\ndef update_station(attr, old, new):\n update()\n\n\ndef update_n_simulations(attr, old, new):\n if new > 1000:\n simulation_number_input.value = 1000\n error_info.text = \"Max simulation size is 500\"\n update()\n\n\ndef update_simulation_sample_size(attr, old, new):\n update()\n\n\n# configure Bokeh Inputs, data sources, and plots\nautocomplete_station_names = list(STATIONS_DF['Station Name'])\npeak_source = ColumnDataSource(data=dict())\npeak_flagged_source = ColumnDataSource(data=dict())\ndistribution_source = ColumnDataSource(data=dict())\nqq_source = ColumnDataSource(data=dict())\n\n\nstation_name_input = AutocompleteInput(\n completions=autocomplete_station_names, title='Enter Station Name (ALL CAPS)',\n value=IDS_TO_NAMES['08MH016'], min_characters=3)\n\nsimulation_number_input = Spinner(\n high=1000, low=1, step=1, value=50, title=\"Number of Simulations\",\n)\n\nsample_size_input = Spinner(\n high=200, low=2, step=1, value=10, title=\"Sample Size for Simulations\"\n)\n\nffa_info = Div(\n text=\"Mean of {} simulations of a sample size {}.\".format('x', 'y'))\n\nerror_info = Div(text=\"\", style={'color': 'red'})\n\n# callback for updating the plot based on a changes to inputs\nstation_name_input.on_change('value', update_station)\nsimulation_number_input.on_change('value', update_n_simulations)\nsample_size_input.on_change(\n 'value', update_simulation_sample_size)\n\nupdate()\n\n# widgets\nts_plot = figure(title=\"Annual Maximum Flood\",\n # x_range=(0.9, 2E2),\n # x_axis_type='log',\n width=800,\n height=250,\n output_backend=\"webgl\")\n\nts_plot.xaxis.axis_label = \"Year\"\nts_plot.yaxis.axis_label = \"Flow (m³/s)\"\nts_plot.circle('YEAR', 'PEAK', source=peak_source, legend_label=\"Measured Data\")\nts_plot.circle('YEAR', 'PEAK', source=peak_flagged_source, color=\"orange\",\n legend_label=\"Measured Data (QA/QC Flag)\")\n\nts_plot.line('YEAR', 'Mean', source=peak_source, color='red',\n legend_label='Mean Annual Max', line_dash='dashed')\n\nts_plot.legend.location = \"top_left\"\nts_plot.legend.click_policy = 'hide'\n\n# create a plot for the Flood Frequency Values and style its properties\nffa_plot = figure(title=\"Flood Frequency Analysis Explorer\",\n x_range=(0.9, 2E2),\n x_axis_type='log',\n width=800,\n height=500,\n output_backend=\"webgl\")\n\nffa_plot.xaxis.axis_label = \"Return Period (Years)\"\nffa_plot.yaxis.axis_label = \"Flow (m³/s)\"\n\nffa_plot.circle('Tr', 'PEAK', source=peak_source, legend_label=\"Measured Data\")\nffa_plot.circle('Tr', 'PEAK', source=peak_flagged_source, color=\"orange\",\n legend_label=\"Measured Data (QA/QC Flag)\")\nffa_plot.line('Tr', 'lp3_model', color='red',\n source=distribution_source,\n legend_label='Log-Pearson3 (All Data)')\n\nffa_plot.line('Tr', 'mean', color='navy',\n line_dash='dashed',\n source=distribution_source,\n legend_label='Mean Simulation')\n\n\n# plot the error bands as shaded areas\nffa_2_sigma_band = Band(base='Tr', lower='lower_2_sigma', upper='upper_2_sigma', level='underlay',\n fill_alpha=0.25, fill_color='#1c9099',\n source=distribution_source)\nffa_1_sigma_band = Band(base='Tr', lower='lower_1_sigma', upper='upper_1_sigma', level='underlay',\n fill_alpha=0.65, fill_color='#a6bddb', \n source=distribution_source)\n\nffa_plot.add_layout(ffa_2_sigma_band)\nffa_plot.add_layout(ffa_1_sigma_band)\n\nffa_plot.legend.location = \"top_left\"\nffa_plot.legend.click_policy = \"hide\"\n\n# prepare a Q-Q plot\nqq_plot = figure(title=\"Q-Q Plot\",\n width=400,\n height=300,\n output_backend=\"webgl\")\n\nqq_plot.xaxis.axis_label = \"Empirical\"\nqq_plot.yaxis.axis_label = \"Theoretical\"\n\nqq_plot.circle('PEAK', 'theoretical', source=peak_source)\nqq_plot.line('PEAK', 'PEAK', source=peak_source, legend_label='1:1',\n line_dash='dashed', color='green')\n\nqq_plot.legend.location = 'top_left'\n\n# prepare a P-P plot\npp_plot = figure(title=\"P-P Plot\",\n width=400,\n height=300,\n output_backend=\"webgl\")\n\npp_plot.xaxis.axis_label = \"Empirical\"\npp_plot.yaxis.axis_label = \"Theoretical\"\n\npp_plot.circle('empirical_cdf', 'theoretical_cdf', source=peak_source)\npp_plot.line('empirical_cdf', 'empirical_cdf', source=peak_source, legend_label='1:1',\n line_dash='dashed', color='green')\n\npp_plot.legend.location = 'top_left'\n\n# create a page layout\nlayout = column(station_name_input,\n sample_size_input,\n simulation_number_input,\n ffa_info,\n error_info,\n ts_plot,\n ffa_plot,\n row(qq_plot, pp_plot)\n )\n\ncurdoc().add_root(layout)\n"
] | [
[
"scipy.stats.norm.ppf",
"scipy.stats.pearson3.cdf",
"numpy.linspace",
"numpy.power",
"numpy.subtract",
"pandas.DataFrame",
"numpy.log10",
"numpy.mean",
"numpy.var",
"numpy.add",
"scipy.stats.skew"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
zj1008/GALD-DGCNet | [
"be7ebfe2b3d28ea28a2b4714852999d4af2a785e"
] | [
"libs/core/loss.py"
] | [
"# CE-loss\nimport torch.nn as nn\nimport torch\nimport torch.nn.functional as F\n\n\nclass OhemCrossEntropy2dTensor(nn.Module):\n def __init__(self, ignore_label, reduction='elementwise_mean', thresh=0.6, min_kept=256,\n down_ratio=1, use_weight=False):\n super(OhemCrossEntropy2dTensor, self).__init__()\n self.ignore_label = ignore_label\n self.thresh = float(thresh)\n self.min_kept = int(min_kept)\n self.down_ratio = down_ratio\n if use_weight:\n weight = torch.FloatTensor(\n [0.8373, 0.918, 0.866, 1.0345, 1.0166, 0.9969, 0.9754, 1.0489,\n 0.8786, 1.0023, 0.9539, 0.9843, 1.1116, 0.9037, 1.0865, 1.0955,\n 1.0865, 1.1529, 1.0507])\n self.criterion = torch.nn.CrossEntropyLoss(reduction=reduction,\n weight=weight,\n ignore_index=ignore_label)\n else:\n self.criterion = torch.nn.CrossEntropyLoss(reduction=reduction,\n ignore_index=ignore_label)\n\n def forward(self, pred, target):\n b, c, h, w = pred.size()\n target = target.view(-1)\n valid_mask = target.ne(self.ignore_label)\n target = target * valid_mask.long()\n num_valid = valid_mask.sum()\n\n prob = F.softmax(pred, dim=1)\n prob = (prob.transpose(0, 1)).reshape(c, -1)\n\n if self.min_kept > num_valid:\n print('Labels: {}'.format(num_valid))\n elif num_valid > 0:\n prob = prob.masked_fill_(~valid_mask, 1)\n mask_prob = prob[\n target, torch.arange(len(target), dtype=torch.long)]\n threshold = self.thresh\n if self.min_kept > 0:\n _, index = mask_prob.sort()\n threshold_index = index[min(len(index), self.min_kept) - 1]\n if mask_prob[threshold_index] > self.thresh:\n threshold = mask_prob[threshold_index]\n kept_mask = mask_prob.le(threshold)\n target = target * kept_mask.long()\n valid_mask = valid_mask * kept_mask\n\n target = target.masked_fill_(~valid_mask, self.ignore_label)\n target = target.view(b, h, w)\n\n return self.criterion(pred, target)\n\n\nclass CriterionDSN(nn.CrossEntropyLoss):\n def __init__(self, ignore_index=255,reduce=True):\n super(CriterionDSN, self).__init__()\n\n self.ignore_index = ignore_index\n self.reduce = reduce\n def forward(self, preds, target):\n scale_pred = preds[0]\n loss1 = super(CriterionDSN, self).forward(scale_pred, target)\n scale_pred = preds[1]\n loss2 = super(CriterionDSN, self).forward(scale_pred, target)\n\n return loss1 + loss2 * 0.4\n\n\nclass CriterionOhemDSN(nn.Module):\n '''\n DSN : We need to consider two supervision for the models.\n '''\n def __init__(self, ignore_index=255, thresh=0.7, min_kept=100000, reduce=True):\n super(CriterionOhemDSN, self).__init__()\n self.ignore_index = ignore_index\n self.criterion1 = OhemCrossEntropy2dTensor(ignore_index, thresh=thresh, min_kept=min_kept)\n self.criterion2 = torch.nn.CrossEntropyLoss(ignore_index=ignore_index, reduce=reduce)\n if not reduce:\n print(\"disabled the reduce.\")\n\n def forward(self, preds, target):\n h, w = target.size(1), target.size(2)\n\n scale_pred = F.upsample(input=preds[0], size=(h, w), mode='bilinear', align_corners=True)\n loss1 = self.criterion1(scale_pred, target)\n\n scale_pred = F.upsample(input=preds[1], size=(h, w), mode='bilinear', align_corners=True)\n loss2 = self.criterion2(scale_pred, target)\n\n return loss1 + loss2 * 0.4"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.nn.functional.upsample",
"torch.nn.functional.softmax",
"torch.FloatTensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pchtsp/metaheuristics | [
"61f17002265d6fa50e094cc36ef49749538dbe14"
] | [
"notebooks/01-voronoi_mouse.py"
] | [
"# Squelette d'un fichier .py indépendant\n\nimport numpy as np\nfrom vispy import app\n\nfrom stochastic.voronoi import Voronoi\n\nclass Discover(Voronoi):\n\n def __init__(self, nb_points, nb_colors):\n Voronoi.__init__(self, nb_points=nb_points, nb_colors=nb_colors)\n self.current = 0\n\n def on_mouse_move(self, event):\n x, y = event.pos\n x, y = x / float(self.width), 1 - y / float(self.height)\n\n # Ne pas écrire self.points[self.current, :] = ...\n # (sinon le programme quitte proprement!)\n new = np.array(self.points)\n new[self.current, :] = x * self.ps, y * self.ps\n self.points = new\n\n def on_mouse_press(self, event):\n self.current = (self.current + 1) % self.nb_points\n\nc = Discover(10, 30)\napp.run()\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
paskino/ML-exercises | [
"6f6586595583c9d85be72944ce8a1a97fdcd0d91"
] | [
"faces/nn.py"
] | [
"import numpy\nfrom functools import reduce\nimport matplotlib.pyplot as plt\nimport pickle\nimport tensorflow as tf\nimport sys\n\n__version__ = '0.1.0'\n\n# PCA matrix\nu = numpy.load(\"lfwfp1140eigim.npy\")\n\n# coordinates\nv = numpy.load(\"lfwfp1140coord.npy\")\n\n# neig total number of eigenvectors, ni total number of images\nneig, ni = v.shape\n\n\n#nc, ny, nx = u.shape\n\n#index = index_repeat[i]\n#PCA_image = numpy.dot(u.T, v.T[index])\n#PCA_image = numpy.reshape(PCA_image, (ny, nx))\n# plt.figure()\n#plt.title('PCA approximation of the image %d' % i)\n#plt.imshow(PCA_image.T, cmap = 'gray')\n# plt.show()\n\n# The problem of classification of a picture of a face to the name of the person is not\n# trivially treated with a NN. With this dataset the output layer would have more than 5000 output\n# neurons, given 1140 inputs.\n# A different approach would be to create a NN to compare 2 images, or an image and a tag identifying the\n# the person.\n# I'll start out with a NN with 1140 + 1 input, where 1140 are the PCA coordinates, and the +1 is a\n# unique number for each person in the dataset. Output of this NN will be a single neuron giving the possibility that\n# the tag and the coordinates belong to the same person.\n\n# the image set contains 5953 labelled images. The training set will be much bigger as the plan is to\n# input in the NN 1140 coordinates + a tag. This means that out of each coordinate we can create N_unique_people input set.\n# The input set will be then N_unique_people * len(training_set_indices)\n\n\ntraining_set_indices = pickle.load(open(\"training_set_indices.pkl\", \"rb\"))\ncv_set_indices = pickle.load(open(\"cv_set_indices.pkl\", \"rb\"))\n# PCA matrix\nu = numpy.load(\"lfwfp1140eigim.npy\")\n\n# coordinates\nv = numpy.load(\"lfwfp1140coord.npy\")\n\nnc, ny, nx = u.shape\n\nN_unique_people = training_set_indices[-1][2] + 1\n\nselect = 'George_W_Bush'\nselect = 'Serena_Williams'\nselect = 'Laura_Bush'\nindex = 0 \n\nwhile (not select == cv_set_indices[index][0]):\n index += 1\n print (cv_set_indices[index][0])\n \nPCA_image = numpy.dot(u.T, v.T[cv_set_indices[index][1]])\nPCA_image = numpy.reshape(PCA_image, (ny, nx))\nplt.figure()\nplt.title('PCA approximation of the image {}'.format(cv_set_indices[index][0]))\nplt.imshow(PCA_image.T, cmap = 'gray')\nplt.show()\n#sys.exit(0)\n\nclass FaceDataset(object):\n '''Create an iterator class as generator for Tensorflow's DataSet\n\n https://www.tensorflow.org/guide/datasets\n https://www.tensorflow.org/api_docs/python/tf/data/Dataset\n '''\n def __init__(self, indices, eigcoord, batch_size=50):\n self.N_unique = indices[-1][2] + 1\n self.v = eigcoord\n self.indices = indices\n self.index = 0\n self.__length = len(indices) * self.N_unique\n self.dimPic = len(indices)\n self.dimName = self.N_unique\n self.indexPic = 0\n self.indexName = 0\n self.batch_size = batch_size\n\n def __len__(self):\n return self.__length\n\n def __call__(self):\n return self\n\n def __iter__(self):\n return self\n\n def __next__(self):\n\n if self.index == self.__length:\n raise StopIteration\n\n face = self.indices[self.indexPic]\n y = (numpy.hstack((self.v.T[self.indexPic], self.indexName)),\n True if face[2] == self.indexName else False)\n # print(face)\n # print(self.indexName, \"is the same\",\n # 1 if face[2] == self.indexName else 0)\n\n # update the index\n if self.indexName == self.dimName:\n self.indexName = 0\n self.indexPic += 1\n else:\n self.indexName += 1\n\n self.index = self.indexPic * self.dimName + self.indexName\n\n return y\n\n def __getitem__(self):\n\n labels = []\n features = []\n for i in range(self.batch_size):\n el = self.__next__()\n labels.append(el[1])\n features.append(el[0])\n\n labels = numpy.asarray(labels)\n features = numpy.asarray(features)\n return (features, labels)\n\n def on_epoch_end(self):\n self.__init__(self.indices, self.v,\n self.batch_size)\n\n\n\nclass LabelDataset(FaceDataset):\n def __init__(self, indices, eigcoord):\n super(LabelDataset, self).__init__(indices, eigcoord)\n def __next__(self):\n return super(LabelDataset, self).__next__()[1]\n\nclass XDataset(FaceDataset):\n def __init__(self, indices, eigcoord):\n super(XDataset, self).__init__(indices, eigcoord)\n def __next__(self):\n return super(XDataset, self).__next__()[0]\n\n# next(dataset)\ndataset = FaceDataset(training_set_indices , v)\n#print (\"dataset: \" , dataset.__next__())\n\nlabels = []\nfeatures = []\nfor i in dataset:\n labels.append(i[1])\n features.append(i[0])\n\nlabels = numpy.asarray(labels)\nfeatures = numpy.asarray(features)\nsample_weights = numpy.ones(labels.shape)\nmin_label_distribution = 0.5\nsample_weights[labels] = min_label_distribution * \\\n (len(labels) - labels.sum()) / labels.sum()\n\n# cross validation\ncv_set = FaceDataset(cv_set_indices, v)\n\ncv_labels = []\ncv_features = []\nfor i in cv_set:\n cv_labels.append(i[1])\n cv_features.append(i[0])\n\ncv_labels = numpy.asarray(cv_labels)\ncv_features = numpy.asarray(cv_features)\n\n## Model\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Dense(250, \n input_shape=(neig + 1,), activation=tf.nn.sigmoid),\n tf.keras.layers.Dense(20, activation=tf.nn.sigmoid),\n tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)\n])\nmodel.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['binary_accuracy'])\n\n# train\nhistory = model.fit(features, labels, epochs=2, batch_size=350,\n sample_weight = sample_weights ,\n validation_data = (cv_features, cv_labels),\n shuffle = True,\n verbose = 2)\n#model.evaluate(cv_features, cv_labels)\nplt.subplot(1,2,1)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['train', 'test'], loc='upper left')\nplt.subplot(1,2,2)\nplt.plot(history.history['binary_accuracy'])\nplt.plot(history.history['val_binary_accuracy'])\nplt.legend(['train', 'test'], loc='lower right')\nplt.show()\n\n\n\n\n# find best match\nmatch = []\nfor i in range(cv_set_indices[-1][2]):\n x = numpy.hstack((v.T[cv_set_indices[index][1]],i))\n match.append(\n (model.predict(x, batch_size=None, verbose=0),\\\n i,cv_set_indices[index][0])\n )\n \n#PCA_image = numpy.dot(u.T, v.T[cv_set_indices[index][1]])\n#PCA_image = numpy.reshape(PCA_image, (ny, nx))\n#plt.figure()\n#plt.title('PCA approximation of the image {}'.format(cv_set_indices[index][0]))\n#plt.imshow(PCA_image.T, cmap = 'gray')\n#plt.show()\n"
] | [
[
"numpy.dot",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.legend",
"numpy.hstack",
"numpy.reshape",
"numpy.asarray",
"tensorflow.keras.layers.Dense",
"numpy.ones",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"numpy.load",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
opensystra/systra | [
"442a884ba17dc0a04d0421d0072f7239ef28ab0d"
] | [
"syspy/spatial/geometries.py"
] | [
"\"\"\"\nThis module provides tools for geometry processing.\n\"\"\"\n\n__author__ = 'qchasserieau'\n\nfrom tqdm import tqdm\nimport shapely\nimport json\nfrom math import pi\nimport numpy as np\nimport pandas as pd\n\ndef reversed_polyline(polyline):\n coords = list(polyline.coords)\n return shapely.geometry.LineString(reversed(coords))\n\ndef linestring_geometry(row):\n return shapely.geometry.LineString(\n [\n [row['x_origin'], row['y_origin']],\n [row['x_destination'], row['y_destination']]\n ]\n )\n\n\ndef point_geometry(row):\n return shapely.geometry.Point(row['stop_lon'], row['stop_lat'])\n\n\ndef linestring_from_indexed_point_geometries(indexed, points):\n try:\n geometries = indexed.loc[points]\n coordinates = []\n for geometry in list(geometries):\n coordinates += list(geometry.coords)\n return shapely.geometry.linestring.LineString(coordinates)\n except ValueError:\n return None\n\ndef line_list_to_polyline(geometries):\n coord_sequence = []\n last = False\n for geometry in geometries:\n coords = list(geometry.coords)\n coord_sequence += coords[1:] if last == coords[0] else coords\n last = coords[-1]\n try:\n return shapely.geometry.linestring.LineString(coord_sequence)\n except ValueError:\n return None\n\ndef polyline_to_line_list(geometry, tolerance=0):\n sequence = geometry.simplify(tolerance).coords if tolerance else geometry.coords\n couples = [(sequence[i], sequence[i+1]) for i in range(len(sequence) - 1)]\n return [shapely.geometry.linestring.LineString(couple) for couple in couples]\n\n\ndef string_to_geometry(string_series):\n iterator = tqdm(list(string_series), 'string_to_geometry')\n return [shapely.geometry.shape(json.loads(x)) for x in iterator]\n\n\ndef geometry_to_string(geometry_series):\n iterator = tqdm(list(geometry_series), 'geometry_to_string')\n return [json.dumps(shapely.geometry.mapping(x)) for x in iterator]\n\n\ndef coexist(\n line_a,\n line_b,\n rate=0.25,\n buffer=1e-4,\n check_collinearity=True\n):\n buffer_a = line_a.buffer(buffer)\n buffer_b = line_b.buffer(buffer)\n min_area = min(buffer_a.area, buffer_b.area)\n inter = buffer_a.intersection(buffer_b)\n intersect = (inter.area / min_area) > rate\n\n clause = True\n if check_collinearity:\n clause = collinear(line_a, line_b)\n\n return intersect * clause\n\n\ndef angle(geometry):\n xa = geometry.coords[0][0]\n ya = geometry.coords[0][1]\n xb = geometry.coords[-1][0]\n yb = geometry.coords[-1][1]\n\n if xb != xa:\n tan = (yb - ya) / (xb - xa)\n a = np.arctan(tan)\n else:\n a = 0\n return (a + 2*pi) % (2*pi)\n\n\ndef delta_angle(g_a, g_b):\n delta = angle(g_a) - angle(g_b)\n return (delta + 2*pi) % (2*pi)\n\n\ndef collinear(g_a, g_b, tol=pi/4):\n return np.absolute(delta_angle(g_a, g_b) - pi) >= (pi - tol)\n\n\ndef dissociate_collinear_lines(lines, coexist_kwargs={}):\n conflicts = [\n [\n coexist(line_a, line_b, **coexist_kwargs)\n for line_a in lines\n ]\n for line_b in tqdm(lines)\n ]\n\n df = pd.DataFrame(conflicts)\n uniques = {i: None for i in range(len(conflicts))}\n sorted_lines = list(df.sum().sort_values(ascending=True).index)\n possibilities = {i for i in range(len(lines))}\n\n for line in sorted_lines:\n taken = {\n uniques[other_line]\n for other_line in sorted_lines\n if conflicts[line][other_line] and\n other_line != line\n }\n uniques[line] = min(possibilities - taken)\n\n return uniques\n\n\ndef line_rows(row, tolerance):\n \"\"\"\n Splits the geometry of a row and returns the list of chunks as a series\n The initial geometry is a polyline. It is simplified then cut at its checkpoints.\n \"\"\"\n line_list = polyline_to_line_list(row['geometry'], tolerance)\n df = pd.DataFrame([row]*(len(line_list))).reset_index(drop=True)\n df['geometry'] = pd.Series(line_list)\n return df\n\n\ndef simplify(dataframe, tolerance=False):\n \"\"\"\n from a dataframe of polylines,\n returns a longer dataframe of straight lines\n \"\"\"\n to_concat = []\n for name, row in dataframe.iterrows():\n to_concat.append(line_rows(row, tolerance))\n return pd.concat(to_concat)\n\n\ndef cut_ab_at_c(geometry, intersection):\n \"\"\"\n Geometry is a line. intersection is a point.\n returns two lines : origin->intersection and intersection->destination\n\n \"\"\"\n\n coords = list(geometry.coords)\n a = coords[0]\n b = coords[-1]\n c = list(intersection.coords)[0]\n\n if c in {a, b}:\n return [geometry]\n else:\n return shapely.geometry.LineString([a, c]), shapely.geometry.LineString([c, b])\n\n\ndef add_centroid_to_polyline(polyline, polygon):\n \"\"\"\n polyline is actualy two points geometry. Returns a three points geometry\n if the line intersects the polygon. The centroid of the polygon is added \n to the line (in the midle)\n \"\"\"\n lines = polyline_to_line_list(polyline)\n to_concatenate = []\n centroid = polygon.centroid\n for line in lines:\n to_concatenate += cut_ab_at_c(line, centroid) if polygon.intersects(line) else [line]\n\n chained = line_list_to_polyline(to_concatenate)\n\n return chained\n\n\ndef add_centroids_to_polyline(geometry, intersections, buffer=1e-9):\n \"\"\"\n Recursive:\n geometry is a line. Every point in itersections is added to it recursively.\n In the end, a polyline is returned. All the points that were in intersections can \n be found in the coordinates of the polyline.\n \"\"\"\n\n if not len(intersections):\n return [geometry]\n\n coords = list(geometry.coords)\n remaining_intersections = intersections - set(geometry.coords)\n\n coord_intersections = set(intersections).intersection(coords)\n sequence_dict = {coords[i]: i for i in range(len(coords))}\n cuts = sorted([0] + [sequence_dict[coord] for coord in coord_intersections] + [len(coords)-1])\n coord_lists = [coords[cuts[i]: cuts[i+1] + 1] for i in range(len(cuts)-1)]\n polylines = [shapely.geometry.LineString(coord_list) for coord_list in coord_lists if len(coord_list) > 1]\n\n if len(remaining_intersections) == 0:\n return polylines\n\n else:\n polygons = [shapely.geometry.point.Point(i).buffer(buffer) for i in remaining_intersections]\n centroids = [polygon.centroid for polygon in polygons]\n\n centroid_coords = {list(centroid.coords)[0] for centroid in centroids if len(centroid.coords)}\n\n while len(polygons):\n polygon = polygons.pop()\n\n polylines = [add_centroid_to_polyline(polyline, polygon) for polyline in polylines]\n\n # recursive\n return add_centroids_to_polyline(\n line_list_to_polyline(polylines), \n coord_intersections.union(centroid_coords), \n buffer\n )\n\n\ndef intersects_in_between(geometry_a, geometry_b):\n \"\"\"\n Returns True if :\n geometry_a and geometry_b form a T intersection or a cross intersection\n \"\"\"\n\n # they dont even intersect, it is not an intersection\n if not geometry_a.intersects(geometry_b):\n return False\n\n boundaries_a = [list(geometry_a.coords)[0], list(geometry_a.coords)[-1]]\n boundaries_b = [list(geometry_b.coords)[0], list(geometry_b.coords)[-1]]\n\n # the two geometries share an endpoint.\n if set(boundaries_a).intersection(set(boundaries_b)):\n return False\n\n return True"
] | [
[
"pandas.concat",
"numpy.arctan",
"pandas.Series",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
prowe12/game-solver | [
"0c197c077a82c79c97c9cf1ed5bcda0dc38eed61"
] | [
"sudoku/create_image.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 24 09:39:43 2022\n\n@author: prowe\n\"\"\"\n\n\nimport imageio\nimport os\nimport numpy as np\n\nfignames = []\nfnames = os.listdir()\nfor fname in fnames:\n if fname[:3] == 'fig' and fname[-4:] == '.png':\n fignames.append(fname)\nfignames = np.sort(fignames)\n\n\nwith imageio.get_writer('mygif.gif', mode='I') as writer:\n for filename in fignames:\n image = imageio.imread(filename)\n writer.append_data(image)\n"
] | [
[
"numpy.sort"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TooSchoolForCool/CS275-Parkour-Go | [
"a302357c0f2373bb4e03318d4cf37765b77ec8f3"
] | [
"a3c/src/trainer.py"
] | [
"import logging\nimport time\n\nimport gym\nimport torch\nimport numpy as np\nfrom setproctitle import setproctitle as ptitle\nfrom torch.autograd import Variable\n\nimport environment\nfrom utils import setup_logger, ensure_shared_grads\nfrom network import MLP\nfrom agent import Agent\n\nRANDOM_SEED = 1\n\ndef test(args, nn):\n ptitle('Test Agent')\n \n log = {}\n setup_logger('{}_log'.format(args.env),\n r'{0}{1}_log'.format(args.log, args.env))\n log['{}_log'.format(args.env)] = logging.getLogger(\n '{}_log'.format(args.env))\n d_args = vars(args)\n for k in d_args.keys():\n log['{}_log'.format(args.env)].info('{0}: {1}'.format(k, d_args[k]))\n\n env = environment.make(args.env, args)\n\n reward_sum = 0\n start_time = time.time()\n num_tests = 0\n reward_total_sum = 0\n player = Agent(None, env, args, None)\n\n player.model = MLP(player.env.observation_space.shape[0], player.env.action_space, args.n_frames)\n\n player.state = player.env.reset()\n player.state = torch.from_numpy(player.state).float()\n \n player.model.eval()\n max_score = 0\n\n while True:\n if player.done:\n player.model.load_state_dict(nn.state_dict())\n\n player.action_test()\n reward_sum += player.reward\n\n if player.done:\n num_tests += 1\n reward_total_sum += reward_sum\n reward_mean = reward_total_sum / num_tests\n log['{}_log'.format(args.env)].info(\n \"Time {0}, reward {1}, average reward {2:.4f}\".\n format(\n time.strftime(\"%Hh %Mm %Ss\",\n time.gmtime(time.time() - start_time)),\n reward_sum, reward_mean))\n\n if reward_sum >= max_score:\n max_score = reward_sum\n state_to_save = player.model.state_dict()\n torch.save(state_to_save, '{}.dat'.format(args.model_save_dir))\n\n reward_sum = 0\n player.eps_len = 0\n state = player.env.reset()\n time.sleep(60)\n player.state = torch.from_numpy(state).float()\n\n\ndef train(rank, args, nn, optimizer):\n ptitle('Training Agent: {}'.format(rank))\n \n env = environment.make(args.env, args)\n env.seed(RANDOM_SEED + rank)\n\n player = Agent(None, env, args, None)\n player.model = MLP(player.env.observation_space.shape[0], player.env.action_space, args.n_frames)\n\n player.state = player.env.reset()\n player.state = torch.from_numpy(player.state).float()\n player.model.train()\n\n while True:\n player.model.load_state_dict(nn.state_dict())\n if player.done:\n player.cx = Variable(torch.zeros(1, 128))\n player.hx = Variable(torch.zeros(1, 128))\n else:\n player.cx = Variable(player.cx.data)\n player.hx = Variable(player.hx.data)\n \n for step in range(args.n_steps):\n\n player.action_train()\n\n if player.done:\n break\n\n if player.done:\n player.eps_len = 0\n state = player.env.reset()\n player.state = torch.from_numpy(state).float()\n\n R = torch.zeros(1, 1)\n\n if not player.done:\n state = player.state\n value, _, _, _ = player.model(\n (Variable(state), (player.hx, player.cx)))\n R = value.data\n\n player.values.append(Variable(R))\n policy_loss = 0\n value_loss = 0\n R = Variable(R)\n gae = torch.zeros(1, 1)\n for i in reversed(range(len(player.rewards))):\n R = args.gamma * R + player.rewards[i]\n advantage = R - player.values[i]\n value_loss = value_loss + 0.5 * advantage.pow(2)\n\n # Generalized Advantage Estimataion\n # print(player.rewards[i])\n delta_t = player.rewards[i] + args.gamma * \\\n player.values[i + 1].data - player.values[i].data\n\n gae = gae * args.gamma * args.tau + delta_t\n\n policy_loss = policy_loss - \\\n (player.log_probs[i].sum() * Variable(gae)) - \\\n (0.01 * player.entropies[i].sum())\n\n player.model.zero_grad()\n (policy_loss + 0.5 * value_loss).backward()\n ensure_shared_grads(player.model, nn, gpu=False)\n optimizer.step()\n player.clear_actions()"
] | [
[
"torch.autograd.Variable",
"torch.from_numpy",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wzt1001/indoor_space_cnn_classifier | [
"2d0f2bff63a8d20e8e1d5a03ce8b81bcc2b0c13e"
] | [
"scripts/frame_extraction.py"
] | [
"import cv2\r\nimport os\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nfrom sys import stdout\r\nimport psycopg2\r\nimport pickle\r\nimport numpy as np\r\nimport math\r\nfrom PIL import Image\r\nfrom math import floor\r\nimport hashlib\r\nimport random\r\nfrom multiprocessing.dummy import Pool as ThreadPool\r\nfrom sklearn.utils import shuffle\r\n\r\n# generating the accurate geo-coordinates for a specific time poing\r\ndef gen_coord(line, time):\r\n\r\n\tpercentage = None\r\n\tfor idx, timestamp in enumerate(line[\"time\"]):\r\n\t\tif time < timestamp:\r\n\t\t\tindex = idx\r\n\t\t\tpercentage = (time - line[\"time\"][index - 1]) * 1.0 / (timestamp - line[\"time\"][index - 1])\r\n\t\t\tbreak\r\n\tif percentage is None:\r\n\t\treturn None\r\n\telse:\r\n\t\tcoord_x = (line[\"points\"][index][0] - line[\"points\"][index - 1][0]) * percentage + line[\"points\"][index - 1][0]\r\n\t\tcoord_y = (line[\"points\"][index][1] - line[\"points\"][index - 1][1]) * percentage + line[\"points\"][index - 1][1]\r\n\t\treturn (coord_x, coord_y)\r\n\r\n# function to randomly crop images from original in order to perform data augmentation\r\ndef random_crop(image, min_area_per, max_area_per, total_cnt, w_h_ratio_min, w_h_ratio_max):\r\n\r\n\twidth, height, channels = image.shape\r\n\taugmented_images = []\r\n\taugmented_images_infos = []\r\n\r\n\t# for the original image\r\n\tinfos = [True, None, None, None, None]\r\n\taugmented_images.append(image)\r\n\taugmented_images_infos.append(infos)\r\n\r\n\r\n\tfor cnt in range(total_cnt):\r\n\t\tw_h_ratio = random.uniform(w_h_ratio_min, w_h_ratio_max)\r\n\t\tarea = random.uniform(min_area_per, max_area_per)\r\n\r\n\t\tw_new = int(floor(math.sqrt(height * width * area * w_h_ratio)))\r\n\t\th_new = int(floor(w_new / w_h_ratio))\r\n\r\n\t\t# print(width, w_new, height, h_new)\r\n\t\trandom_left_shift = random.randint(0, int((width - w_new))) # Note: randint() is from uniform distribution.\r\n\t\trandom_down_shift = random.randint(0, int((height - h_new)))\r\n\r\n\t\tnew_image = image[random_left_shift : w_new + random_left_shift, random_down_shift: h_new + random_down_shift, :]\r\n\t\t# print(new_image.shape)\r\n\t\tcenterpoint_x = random_left_shift / 2 + w_new\r\n\t\tcenterpoint_y = random_down_shift / 2 + h_new\r\n\t\toriginal = False\r\n\r\n\t\tinfos = [original, w_h_ratio, area, centerpoint_x, centerpoint_y]\r\n\r\n\t\taugmented_images.append(new_image)\r\n\t\taugmented_images_infos.append(infos)\r\n\r\n\treturn {\"augmented_images\": augmented_images, \"augmented_images_infos\": augmented_images_infos}\r\n\r\n\r\n#preset settings\r\nframe_interval = 50\r\naugmentation_split = 8\r\n\r\n# select area for interpolation\r\nconn_string = \"host='localhost' dbname='indoor_position' user='postgres' password='tiancai' port='5432'\"\r\nconn = psycopg2.connect(conn_string)\r\ncur = conn.cursor()\r\n\r\nquery = '''select * from penn_station.areas'''\r\ncur.execute(query)\r\nareas = cur.fetchall()\r\ncur.close()\r\nconn.commit()\r\n\r\n# select route id and its corresponding time list\r\nconn = psycopg2.connect(conn_string)\r\ncur = conn.cursor()\r\nquery = '''select id, field_3 from penn_station.routes'''\r\ncur.execute(query)\r\nresults = cur.fetchall()\r\ncur.close()\r\nconn.commit()\r\nrecords = {}\r\nfor item in results:\r\n\trecords[item[0]] = {}\r\n\trecords[item[0]][\"time\"] = eval(item[1])\r\n\trecords[item[0]][\"points\"] = []\r\n\r\n# select coordinates of these routes\r\nconn = psycopg2.connect(conn_string)\r\ncur = conn.cursor()\r\nquery = '''select id, (ST_DumpPoints(geom)).path, ST_X(((ST_DumpPoints(geom)).geom)), ST_Y(((ST_DumpPoints(geom)).geom)) from penn_station.routes'''\r\ncur.execute(query)\r\nresults = cur.fetchall()\r\ncur.close()\r\nconn.commit()\r\nfor item in results:\r\n\trecords[item[0]][\"points\"].append((item[2], item[3]))\r\n# print(records)\r\nprint(\"--- parameters loaded...\\n--- begin categorizing\")\r\n# for points in results:\r\n\r\nplace_title = \"penn_station\"\r\nroot_dir \t= os.path.join(os.getcwd(), \"..\", \"data\", place_title)\r\n\r\nleft_dir\t= os.path.join(root_dir, \"1\")\r\nforward_dir = os.path.join(root_dir, \"3\")\r\nright_dir = os.path.join(root_dir, \"4\")\r\nback_dir\t= os.path.join(root_dir, \"5\")\r\n\r\noutput_dir \t= os.path.join(root_dir, \"extracted_%sms\" % str(frame_interval))\r\n\r\nleft_files \t\t= [join(left_dir, f) for f in listdir(left_dir) if isfile(join(left_dir, f))]\r\nforward_files \t= [join(forward_dir, f) for f in listdir(forward_dir) if isfile(join(forward_dir, f))]\r\nright_files \t= [join(right_dir, f) for f in listdir(right_dir) if isfile(join(right_dir, f))]\r\nback_files \t\t= [join(back_dir, f) for f in listdir(back_dir) if isfile(join(back_dir, f))]\r\n\r\nif not len(left_files) == len(forward_files) == len(right_files) == len(back_files) == len(top_files):\r\n\tprint(\"!!! file count not consistent\")\r\n# print(left_files, forward_files, right_files, back_files, top_files)\r\nif not os.path.exists(output_dir):\r\n\tos.makedirs(output_dir)\r\n\r\nos.chdir(output_dir)\r\n\r\nall_files = [left_files, forward_files, right_files, back_files]\r\n\r\nglobal total_cnt\r\nglobal fail_cnt\r\nglobal lookup_table\r\n\r\ntotal_cnt = 0\r\nfail_cnt = 0\r\nlookup_table = {\"2-1\": 0, \"2-3\": 1, \"2-4\": 2, \"2-5\": 3, \"2-6\": 4, \"2-8-2\": 5, \"2-9\": 6, \"2-10\": 7}\r\n\r\n# create table to store image infos\r\n# conn = psycopg2.connect(conn_string)\r\n# cur = conn.cursor()\r\n# query = '''\r\n# \tdrop table if exists penn_station.image_lookup_%sms; create table penn_station.image_lookup_%sms\r\n# \t(\r\n# \t image_name text,\r\n# \t id integer,\r\n# \t spec_id text,\r\n# \t path text,\r\n# \t lat double precision,\r\n# \t lon double precision,\r\n# \t original boolean, \r\n# \t w_h_ratio text,\r\n# \t area text, \r\n# \t centerpoint_x text, \r\n# \t centerpoint_y text\r\n# \t);\r\n\r\n# \tdrop table if exists penn_station.missing; create table penn_station.missing\r\n# \t(\r\n# \t lat double precision,\r\n# \t lon double precision\r\n# \t)\r\n\r\n# ''' % (str(frame_interval), str(frame_interval))\r\n# # print(query)\r\n# cur.execute(query)\r\n# cur.close()\r\n# conn.commit()\r\n# print(\"--- table penn_station.image_lookup_%sms created\" % (str(frame_interval)))\r\n\r\n\r\nall_files = [left_files, forward_files, right_files, back_files]\r\n\r\ndef extract(input_direction):\r\n\r\n\tglobal total_cnt\r\n\tglobal fail_cnt\r\n\tglobal lookup_table\r\n\tcam_id = input_direction[0]\r\n\tdirection = input_direction[1]\r\n\t# for cam_id, direction in enumerate(all_files):\r\n\tfor clip_id in range(len(direction)):\r\n\t\tprint(\"------ begin extracting from cam_id: %s, clip_id %s\" % (cam_id, clip_id) )\r\n\t\tvidcap = cv2.VideoCapture(direction[clip_id])\r\n\t\t# success, image = vidcap.read()\r\n\t\tcount = 0\r\n\t\t# if not success:\r\n\t\t# \tprint(\"video reading error for %s\" % direction[clip_id])\r\n\t\t# \tcontinue\r\n\t\twhile True:\r\n\t\t\tcurrent_line = records[lookup_table[os.path.splitext((os.path.basename(direction[clip_id])))[0]]]\r\n\r\n\t\t\t# use this one for opencv 2-- cv2.CAP_PROP_POS_MSEC was removed from opencv 3.0\r\n\t\t\tvidcap.set(cv2.CAP_PROP_POS_MSEC, (count * frame_interval))\r\n\r\n\t\t\t# use this one for opencv 3\r\n\t\t\t# post_frame = cap.get(1)\r\n\r\n\t\t\tcurrent_time = count * 1.0 * frame_interval / 1000\r\n\t\t\tcoord = gen_coord(current_line, current_time)\r\n\t\t\t# print(current_line, count * 1.0 * frame_interval / 1000)\r\n\t\t\tif coord is not None:\r\n\t\t\t\tconn = psycopg2.connect(conn_string)\r\n\t\t\t\tcur = conn.cursor()\r\n\t\t\t\tquery = '''select id from penn_station.areas a where ST_Intersects(ST_PointFromText('POINT(%s %s)', 4326), ST_Transform(a.geom, 4326)) is True''' % (coord[0], coord[1])\r\n\t\t\t\t# print(query)\r\n\r\n\t\t\t\tcur.execute(query)\r\n\r\n\t\t\t\tif not cur.rowcount == 0:\r\n\t\t\t\t\tarea_id = cur.fetchone()[0]\r\n\t\t\t\t\tsuccess, image = vidcap.read()\r\n\t\t\t\t\tcur.close()\r\n\t\t\t\t\tconn.commit()\r\n\r\n\t\t\t\t\tif (image is not None):\r\n\t\t\t\t\t\t#print(count * frame_interval)\r\n\r\n\t\t\t\t\t\tspec_id = str(area_id) + str(cam_id)\r\n\t\t\t\t\t\t# filename = \"%s_%s_%s.png\" % (spec_id, str(cam_id), count)\t\r\n\t\t\t\t\t\tcrop_result = random_crop(image, 0.3, 0.6, augmentation_split, 0.8, 1.2)\r\n\r\n\t\t\t\t\t\tfor crop_item in range(augmentation_split):\r\n\r\n\t\t\t\t\t\t\t# inserting informations below\r\n\t\t\t\t\t\t\toriginal_ins, w_h_ratio_ins, area_ins, centerpoint_x_ins, centerpoint_y_ins = crop_result[\"augmented_images_infos\"][crop_item]\r\n\t\t\t\t\t\t\timage_ins = crop_result[\"augmented_images\"][crop_item]\r\n\r\n\t\t\t\t\t\t\th = hashlib.new('ripemd160')\r\n\t\t\t\t\t\t\th.update(str(image_ins))\r\n\t\t\t\t\t\t\timage_name = h.hexdigest()\r\n\t\t\t\t\t\t\tfilename_level_1 = image_name[:2]\r\n\t\t\t\t\t\t\tfilename_level_2 = image_name[2:4]\r\n\r\n\t\t\t\t\t\t\timage_dir = os.path.join(os.getcwd(), filename_level_1, filename_level_2)\r\n\r\n\t\t\t\t\t\t\tif not os.path.exists(image_dir):\r\n\t\t\t\t\t\t\t\tos.makedirs(image_dir)\r\n\r\n\t\t\t\t\t\t\t# save frame as png file\r\n\t\t\t\t\t\t\timage_ins = cv2.resize(image_ins, dsize=(224, 224), interpolation=cv2.INTER_CUBIC)\r\n\t\t\t\t\t\t\tcv2.imwrite(os.path.join(image_dir, image_name + \".png\"), image_ins)\t \r\n\r\n\t\t\t\t\t\t\t# inserting image infos into database\r\n\t\t\t\t\t\t\tconn = psycopg2.connect(conn_string)\r\n\t\t\t\t\t\t\tcur = conn.cursor()\r\n\t\t\t\t\t\t\tquery = '''insert into penn_station.image_lookup_%sms values('%s', %s, '%s', '%s', %s, %s, %s, '%s', '%s', '%s', '%s')''' % (str(frame_interval), image_name , area_id, spec_id, os.path.join(image_dir, image_name + \".png\"), coord[0], coord[1], original_ins, w_h_ratio_ins, area_ins, centerpoint_x_ins, centerpoint_y_ins)\r\n\t\t\t\t\t\t\t# print(query)\r\n\t\t\t\t\t\t\tcur.execute(query)\r\n\t\t\t\t\t\t\t\r\n\r\n\t\t\t\t\t\tstdout.write(\"\\rcam_id %s, area_id %s, saved cnt %s, not_in_any_area cnt %s, clip_id %s\" % (str(cam_id), area_id, total_cnt - fail_cnt, fail_cnt, clip_id))\r\n\t\t\t\t\t\tstdout.flush()\r\n\t\t\t\t\t\tcur.close()\r\n\t\t\t\t\t\tconn.commit()\r\n\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(\"\\n\" + str(count * frame_interval) + \"disrupted\")\r\n\t\t\t\t\t\tcount += 1\r\n\t\t\t\t\t\t#total_cnt += 1\r\n\t\t\t\t\t\t#fail_cnt += 1\r\n\t\t\t\t\t\t#continue\r\n\t\t\t\t\t\t#print(success, image)\r\n\t\t\t\t\t\t#print(\"\\nend of one video\")\r\n\t\t\t\t\t\tcontinue\r\n\r\n\t\t\t\telse:\r\n\t\t\t\t\tcur.close()\r\n\t\t\t\t\tconn.commit()\r\n\r\n\t\t\t\t\tconn = psycopg2.connect(conn_string)\r\n\t\t\t\t\tcur = conn.cursor()\r\n\t\t\t\t\tquery = '''insert into penn_station.missing values(%s, %s)''' % (coord[0], coord[1])\r\n\t\t\t\t\t# print(query)\r\n\t\t\t\t\tcur.execute(query)\r\n\t\t\t\t\tcur.close()\r\n\t\t\t\t\tconn.commit()\r\n\r\n\t\t\t\t\tstdout.write(\"\\rcam_id %s, saved cnt %s, not_in_any_area cnt %s, clip_id %s\" % (str(cam_id), total_cnt - fail_cnt, fail_cnt, clip_id))\r\n\t\t\t\t\tstdout.flush()\r\n\r\n\t\t\t\t\tfail_cnt += 1\r\n\t\t\t\t\r\n\t\t\telse:\r\n\t\t\t\tprint(\"\\nbreak because coord is None\")\r\n\t\t\t\tbreak\r\n\t\t\tif cv2.waitKey(10) == 27: # exit if Escape is hit\r\n\t\t\t\tbreak\r\n\t\t\tcount += 1\r\n\t\t\ttotal_cnt += 1\r\n\r\n# pool = ThreadPool(processes = 4)\r\n# pool.map(extract, [[cam_id, direction] for cam_id, direction in enumerate(all_files)])\r\n# pool.close()\r\n# pool.join()\r\n\r\n\r\n\r\n\r\n# select specific area name & count from image look up table\r\nconn = psycopg2.connect(conn_string)\r\ncur = conn.cursor()\r\nquery = '''select spec_id, count(spec_id) as cnt1 from penn_station.image_lookup_%sms group by spec_id having count(spec_id) > 100; ''' % str(frame_interval)\r\ncur.execute(query)\r\nresults = cur.fetchall()\r\ncur.close()\r\nconn.commit()\r\nprint(cur.rowcount)\r\nspec_cat = {}\r\n\r\n# for shitty classifer code\r\n# for spec_id in results:\r\n# \tconn = psycopg2.connect(conn_string)\r\n# \tcur = conn.cursor()\r\n# \tquery = '''select * from penn_station.image_lookup_%sms where spec_id = '%s'; ''' % (str(frame_interval), spec_id[0])\r\n# \t# print(query)\r\n# \tcur.execute(query)\r\n# \timages = cur.fetchall()\r\n\t\r\n# \toutput_dir = os.path.join(os.getcwd(), '..', 'categories', spec_id[0])\r\n# \tif not os.path.exists(output_dir):\r\n# \t\tos.makedirs(output_dir)\r\n\r\n# \tspec_cat[spec_id[0]] = []\r\n# \tfor image in images:\r\n# \t\tresized_image = cv2.resize(np.array(Image.open(image[3])), dsize=(200, 200), interpolation=cv2.INTER_CUBIC)\r\n# \t\tcv2.imwrite(os.path.join(output_dir, os.path.basename(image[3])), resized_image)\r\n# \tcur.close()\r\n# \tconn.commit()\r\n\r\n\r\n#\tfor bolei's code\r\nper_train = 0.8\r\nper_val = 0.09\r\nper_test = 0.1\r\n\r\ndata_train = np.array([], dtype=np.uint8).reshape(0, 150528)\r\nlabel_train = np.array([], dtype=np.uint8)\r\n\r\ndata_val = np.array([], dtype=np.uint8).reshape(0, 150528)\r\nlabel_val = np.array([], dtype=np.uint8)\r\n\r\ndata_test = np.array([], dtype=np.uint8).reshape(0, 150528)\r\nlabel_test = np.array([], dtype=np.uint8)\r\n\r\nfor idx, spec_id in enumerate(results):\r\n\tconn = psycopg2.connect(conn_string)\r\n\tcur = conn.cursor()\r\n\tquery = '''select * from penn_station.image_lookup_%sms where spec_id = '%s'; ''' % (str(frame_interval), spec_id[0])\r\n\t# print(query)\r\n\r\n\tcur.execute(query)\r\n\timages = cur.fetchall()\r\n\r\n\tidx = int(idx)\r\n\tcategory = spec_id\r\n\r\n\t# print(images)\r\n\tdata_category = np.array([cv2.resize(np.array(Image.open(fname[3])), dsize=(224, 224), interpolation=cv2.INTER_CUBIC) for fname in images])\t\r\n\r\n\t# data_category = np.load(file_np).astype(np.int8)\r\n\ttotal_cnt = len(data_category)\r\n\tnum_train = int(per_train * total_cnt)\r\n\tnum_val = int(per_val * total_cnt)\r\n\tnum_test = int(per_test * total_cnt)\r\n\tprint (num_train, num_val, num_test)\r\n\t# generate split\r\n\r\n\ttrain_category = data_category[:num_train].reshape(-1, 150528)\r\n\tval_category = data_category[num_train:num_train+num_val].reshape(-1, 150528)\r\n\ttest_category = data_category[num_train+num_val:num_train+num_val+num_test].reshape(-1, 150528)\r\n\r\n\tprint(data_train.shape, train_category.shape)\r\n\r\n\t# concatenate: TODO: change this to pre-assign to speed up\r\n\tdata_train = np.concatenate((data_train, train_category), axis=0)\r\n\tlabel_train = np.concatenate((label_train, np.ones((num_train,), dtype=int) * idx), axis=0)\r\n\r\n\tdata_val = np.concatenate((data_val, val_category), axis=0)\r\n\tlabel_val = np.concatenate((label_val, np.ones((num_val,), dtype=int) * idx), axis=0)\r\n\r\n\tdata_test = np.concatenate((data_test, test_category), axis=0)\r\n\tlabel_test = np.concatenate((label_test, np.ones((num_test,), dtype=int) * idx), axis=0)\r\n\r\n\tprint('num_train=%d num_val=%d num_test=%d' % (data_train.shape[0], data_val.shape[0], data_test.shape[0]))\r\n\r\n# \twith open(os.path.join(os.getcwd(), '..', 'npy', ), 'wb') as f:\r\noutput_dir = os.path.join(os.getcwd(), '..', 'datasplit')\r\nif not os.path.exists(output_dir):\r\n\tos.makedirs(output_dir)\r\n\r\ndata_train, label_train = shuffle(data_train, label_train, random_state=0)\r\n\r\nnp.savez( os.path.join(output_dir, '%s_split_%s_test.npy' % (num_train, \"224\")), data_val=data_val, label_val=label_val, data_test=data_test, label_test=label_test)\r\nnp.savez( os.path.join(output_dir, '%s_split_%s_train0.npy' % (num_train, \"224\")), data_train=data_train[0:29999], label_train=label_train[0:29999])\r\nnp.savez( os.path.join(output_dir, '%s_split_%s_train1.npy' % (num_train, \"224\")), data_train=data_train[30000:59999], label_train=label_train[30000:59999])\r\nnp.savez( os.path.join(output_dir, '%s_split_%s_train2.npy' % (num_train, \"224\")), data_train=data_train[60000:], label_train=label_train[60000:])\r\n# np.savez( os.path.join(output_dir, '%s_split_%s.npy' % (num_train, \"128\")), data_train=data_train, label_train=label_train, data_val=data_val, label_val=label_val, data_test=data_test, label_test=label_test)\r\n\r\n\r\n\r\n"
] | [
[
"numpy.concatenate",
"sklearn.utils.shuffle",
"numpy.array",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PreetamSrikar/brain_dynamics | [
"f3d2133ca382664a8d46f9002e809d6ee9405140"
] | [
"modeling_FC_states.py"
] | [
"\"\"\"\nK-means clustering of the reduced components vectors with silhouette analysis on \nthe best number or clusters.\n\nHidden Markov Model on reduced dim data with log likelihood score to choose the \nbest number of components.\n\nDBSCAN clustering model on reduced dim data.\n\nAutoencoder implemented in Keras for features dimension reduction. If using,\ncheck for different parameters.\n\nGaussian mixture clustering on reduced dim data.\n\nWard hierarchical clustering on reduced dim data.\n\nKaterina Capouskova 2018, [email protected]\n\"\"\"\n\nimport logging\nimport os\n\nimport numpy as np\nfrom hmmlearn import hmm\nfrom keras.layers import Dense\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import Adam\nfrom sklearn import mixture, preprocessing\nfrom sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import silhouette_score, silhouette_samples\nfrom sklearn.neighbors import kneighbors_graph\nfrom tqdm import tqdm\n\nfrom states_features import probability_of_state, mean_lifetime_of_state\nfrom visualizations import plot_silhouette_analysis, plot_autoe_vs_pca\n\n\ndef kmeans_clustering(reduced_components, output_path):\n \"\"\"\n Performs a K-means clustering with silhouette analysis\n\n :param reduced_components: reduced components matrix\n :type reduced_components: np.ndarray\n :param output_path: path to output directory \n :type output_path: str\n :return: clustered array\n :rtype: np.ndarray\n \"\"\"\n logging.basicConfig(filename=os.path.join(output_path,\n 'clustering_FC_states.log'),\n level=logging.INFO)\n samples, timesteps, features = reduced_components.shape\n # new matrix ((time steps x subjects) x number of features(brain areas * n_components))\n reduced_components_2d = np.reshape(reduced_components, (samples * timesteps, features))\n results = []\n n_clusters = []\n for clusters in tqdm(range(2, 3)):\n n_clusters.append(clusters)\n kmeans = KMeans(n_clusters=clusters).fit(reduced_components_2d)\n # perform the silhouette analysis as a metric for the clustering model\n silhouette_avg = silhouette_score(reduced_components_2d, kmeans.labels_,\n sample_size=300)\n logging.info('For n_clusters = {}, the average silhouette score is: {}'\n .format(clusters, silhouette_avg))\n cluster_center, sum_sqr_d = kmeans.cluster_centers_, kmeans.inertia_\n logging.info('For n_clusters = {}, the cluster centers are: {} and the '\n 'sum of squared distances of samples to their closest '\n 'cluster center are: {}'.format(clusters, cluster_center,\n sum_sqr_d))\n results.append(silhouette_avg)\n # select the best performing number of clusters\n index_of_best = results.index(max(results))\n logging.info('The best number of clusters: {}'.format(\n n_clusters[index_of_best]))\n best_clusterer = KMeans(n_clusters=n_clusters[index_of_best])\n clusters_array = best_clusterer.fit_predict(reduced_components_2d)\n np.savez(os.path.join(output_path, 'clustered_matrix'), clusters_array)\n probability_of_state(clusters_array, n_clusters[index_of_best], output_path)\n mean_lifetime_of_state(clusters_array, n_clusters[index_of_best], output_path)\n data_clusters = {'reduced_components': reduced_components_2d, 'clusters': clusters_array}\n return clusters_array\n\n\ndef kmeans_clustering_mean_score(reduced_components, output_path, n_clusters):\n \"\"\"\n Performs a K-means clustering with pre-set number of clusters more times and\n returns the average silhouette score\n\n :param reduced_components: reduced components matrix\n :type reduced_components: np.ndarray\n :param output_path: path to output directory\n :type output_path: str\n :param n_clusters: number of clusters\n :type n_clusters: int\n :return: clustered array, features array with labels\n :rtype: np.ndarray, np.ndarray\n \"\"\"\n logging.basicConfig(filename=os.path.join(output_path,\n 'clustering_FC_states_mean_score.log'),\n level=logging.INFO)\n results = []\n for iter in tqdm(range(1)):\n kmeans = KMeans(n_clusters=n_clusters).fit(reduced_components)\n # perform the silhouette analysis as a metric for the clustering model\n silhouette = silhouette_score(reduced_components, kmeans.labels_,\n sample_size=500)\n logging.info('For iteration = {}, the average silhouette score is: {}'\n .format(iter, silhouette))\n cluster_center, sum_sqr_d = kmeans.cluster_centers_, kmeans.inertia_\n logging.info('For iteration = {}, the cluster centers are: {} and the '\n 'sum of squared distances of samples to their closest '\n 'cluster center are: {}'.format(iter, cluster_center,\n sum_sqr_d))\n results.append(silhouette)\n clusters_array = kmeans.predict(reduced_components)\n sample_silhouette_values = silhouette_samples(reduced_components,\n clusters_array)\n # average silhouette score\n avg_silhouette = sum(results)/float(len(results))\n logging.info('The average silhouette score: {}'.format(avg_silhouette))\n np.savez(os.path.join(output_path, 'clustered_matrix'), clusters_array)\n probability_of_state(clusters_array, n_clusters, output_path)\n mean_lifetime_of_state(clusters_array, n_clusters, output_path)\n plot_silhouette_analysis(reduced_components, output_path, n_clusters, avg_silhouette,\n sample_silhouette_values, clusters_array, cluster_center)\n clusters_array = np.expand_dims(clusters_array, axis=1)\n data_clusters = np.hstack((reduced_components, clusters_array))\n np.savez(os.path.join(output_path, 'concatentated_matrix_clusters'),\n data_clusters)\n return clusters_array, data_clusters\n\n\ndef hidden_markov_model(reduced_components, output_path):\n \"\"\"\n Performs a Hidden Markov Model with log likelihood scoring\n\n :param reduced_components: reduced components matrix\n :type reduced_components: np.ndarray\n :param output_path: path to output directory \n :type output_path: str\n :return: predicted matrix, probabilities matrix, number of components, \n markov array\n :rtype: np.ndarray, np.ndarray, int, np.ndarray\n \"\"\"\n logging.basicConfig(\n filename=os.path.join(output_path, 'hmm_modeling_FC_states.log'),\n level=logging.INFO)\n samples, timesteps, features = reduced_components.shape\n components_swapped = np.swapaxes(reduced_components, 0, 1)\n reduced_components_2d = np.reshape(components_swapped, (timesteps, (samples*features)))\n results = []\n n_components = []\n for component in tqdm(range(100, 300, 4)):\n n_components.append(component)\n model = hmm.GaussianHMM(n_components=component)\n model.fit(reduced_components_2d)\n log_likelihood = model.score(reduced_components_2d)\n logging.info('For number of components: {}, the score is: {}'.format(\n component, log_likelihood))\n results.append(log_likelihood)\n index_of_best = results.index(max(results))\n logging.info('The best number of components: {}'.format(\n n_components[index_of_best]))\n best_hmm = hmm.GaussianHMM(n_components=n_components[index_of_best])\n best_hmm.fit(reduced_components_2d)\n hidden_states = best_hmm.predict(reduced_components_2d)\n np.savez(os.path.join(output_path, 'HMM_state_sequence'), hidden_states)\n predict_proba = best_hmm.predict_proba(reduced_components_2d)\n np.savez(os.path.join(output_path, 'HMM_posteriors'), predict_proba)\n hidden_states_expanded = np.expand_dims(hidden_states, axis=1)\n markov_array = np.append(reduced_components_2d, hidden_states_expanded, axis=1)\n return hidden_states, predict_proba, n_components[index_of_best], \\\n markov_array\n\n\ndef kmeans_clustering_missing(reduced_components, output_path,\n n_clusters=2, max_iter=10):\n \"\"\"\n Performs a K-means clustering with missing data.\n\n :param reduced_components: reduced components matrix\n :type reduced_components: np.ndarray\n :param output_path: path to output directory\n :type output_path: str\n :param n_clusters: number of clusters\n :type n_clusters: int\n :param max_iter: maximum iterations for convergence\n :type max_iter: int\n :return: clustered array, centroids of clusters, filled matrix\n :rtype: np.ndarray, list, np.ndarray\n \"\"\"\n logging.basicConfig(filename=os.path.join(output_path,\n 'clustering_FC_states_missing.log'),\n level=logging.INFO)\n # Initialize missing values to their column means\n missing = ~np.isfinite(reduced_components)\n mu = np.nanmean(reduced_components, axis=0)\n X_filled = np.where(missing, mu, reduced_components)\n\n for i in tqdm(range(max_iter)):\n if i > 0:\n # k means with previous centroids\n cls = KMeans(n_clusters, init=prev_centroids)\n else:\n # do multiple random initializations in parallel\n cls = KMeans(n_clusters, n_jobs=-1)\n # perform clustering on the filled-in data\n labels = cls.fit_predict(X_filled)\n centroids = cls.cluster_centers_\n # fill in the missing values based on their cluster centroids\n X_filled[missing] = centroids[labels][missing]\n # when the labels have stopped changing then we have converged\n if i > 0 and np.all(labels == prev_labels):\n break\n\n prev_labels = labels\n prev_centroids = cls.cluster_centers_\n # perform the silhouette analysis as a metric for the clustering model\n silhouette_avg = silhouette_score(X_filled, cls.labels_,\n sample_size=300)\n logging.info('For n_clusters = {}, the average silhouette score is: {}'\n .format(n_clusters, silhouette_avg))\n logging.info('For n_clusters = {}, the cluster centers are: {} and the '\n 'sum of squared distances of samples to their closest '\n 'cluster center are: {}'.format(n_clusters, centroids,\n cls.inertia_))\n np.savez(os.path.join(output_path, 'clustered_matrix'), labels)\n return labels, centroids, X_filled\n\n\ndef dbscan(reduced_components, output_path):\n \"\"\"\n Performs a DBSCAN clustering.\n\n :param reduced_components: reduced components matrix\n :type reduced_components: np.ndarray\n :param output_path: path to output directory\n :type output_path: str\n :return: clustered array, features array with labels\n :rtype: np.ndarray, np.ndarray\n \"\"\"\n logging.basicConfig(filename=os.path.join(output_path,\n 'clustering_FC_states_mean_score.log'),\n level=logging.INFO)\n\n dbscan = DBSCAN(eps=0.5, min_samples=50)\n labels = dbscan.fit_predict(reduced_components)\n # perform the silhouette analysis as a metric for the clustering model\n silhouette = silhouette_score(reduced_components, labels,\n sample_size=500)\n # Number of clusters in labels, ignoring noise if present.\n n_clusters = len(set(labels)) - (1 if -1 in labels else 0)\n logging.info('For n clusters = {}, the silhouette score is: {}'\n .format(n_clusters, silhouette))\n core_samples = dbscan.core_sample_indices_\n logging.info('Indices of core samples'.format(core_samples))\n sample_silhouette_values = silhouette_samples(reduced_components, labels)\n np.savez(os.path.join(output_path, 'clustered_matrix'), labels)\n probability_of_state(labels, n_clusters, output_path)\n mean_lifetime_of_state(labels, n_clusters, output_path)\n plot_silhouette_analysis(reduced_components, output_path, n_clusters, silhouette,\n sample_silhouette_values, labels, dbscan.components_)\n clusters_array = np.expand_dims(labels, axis=1)\n data_clusters = np.hstack((reduced_components, clusters_array))\n np.savez(os.path.join(output_path, 'concatentated_matrix_clusters'),\n data_clusters)\n return labels, data_clusters\n\n\ndef autoencoder(dfc_all, output_path):\n \"\"\"\n Performs an autoencoder implemented in Keras framework and plots the\n difference with PCA dim reduction.\n\n :param dfc_all: array with all dfc matrices\n :type dfc_all: np.ndarray\n :param output_path: path to output directory\n :type output_path: str\n :return: reduced dim. array\n :rtype: np.ndarray\n \"\"\"\n logging.basicConfig(filename=os.path.join(output_path,\n 'autoencoder.log'),\n level=logging.INFO)\n # reshape input\n all_samples, all_ft_1, all_ft_2 = dfc_all.shape\n dfc_all_2d = dfc_all.reshape(all_samples, (all_ft_1 * all_ft_2))\n\n # normalize\n dfc_all_2d = preprocessing.normalize(dfc_all_2d, norm='l2')\n\n # train and test partition\n x_train, x_test = train_test_split(dfc_all_2d, test_size=0.20)\n\n # PCA\n mu = x_train.mean(axis=0)\n U, s, V = np.linalg.svd(x_train - mu, full_matrices=False)\n Zpca = np.dot(x_train - mu, V.transpose())\n Rpca = np.dot(Zpca[:, :2], V[:2, :]) + mu\n err = np.sum((x_train - Rpca) ** 2) / Rpca.shape[0] / Rpca.shape[1]\n logging.info('PCA reconstruction error with 2 PCs: ' + str(round(err, 3)))\n\n # Autoencoder\n m = Sequential()\n m.add(Dense(2000, activation='relu', input_shape=(4356,)))\n m.add(Dense(500, activation='relu'))\n m.add(Dense(250, activation='relu'))\n m.add(Dense(125, activation='relu'))\n m.add(Dense(66, activation='linear', name=\"bottleneck\"))\n m.add(Dense(125, activation='relu'))\n m.add(Dense(250, activation='relu'))\n m.add(Dense(500, activation='relu'))\n m.add(Dense(2000, activation='relu'))\n m.add(Dense(4356, activation='sigmoid'))\n m.compile(loss='mean_squared_error', optimizer=Adam())\n history = m.fit(x_train, x_train, batch_size=256, epochs=50, verbose=1,\n validation_data=(x_test, x_test))\n\n encoder = Model(m.input, m.get_layer('bottleneck').output)\n Zenc = encoder.predict(dfc_all_2d) # bottleneck representation\n np.savez(os.path.join(output_path, 'encoder_66_features'), Zenc)\n Renc = m.predict(x_train) # reconstruction\n np.savez(os.path.join(output_path, 'autoencoder_reconstruction'), Renc)\n logging.info('MSE:{}, Val loss:{}'.format(history.history['loss'],\n history.history['val_loss']))\n\n plot_autoe_vs_pca(Zpca, Zenc, output_path)\n return Zenc\n\n\ndef gaussian_mixture(reduced_components, output_path, n_clusters):\n \"\"\"\n Performs a Gaussian mixture model clustering.\n\n :param reduced_components: reduced components matrix\n :type reduced_components: np.ndarray\n :param output_path: path to output directory\n :type output_path: str\n :param n_clusters: number of clusters\n :type n_clusters: int\n :return: clustered array, features array with labels\n :rtype: np.ndarray, np.ndarray\n \"\"\"\n logging.basicConfig(filename=os.path.join(output_path,\n 'clustering_GMM.log'),\n level=logging.INFO)\n\n gmm = mixture.GaussianMixture(n_components=n_clusters, covariance_type='full')\n gmm.fit(reduced_components)\n labels = gmm.predict(reduced_components)\n # perform the silhouette analysis as a metric for the clustering model\n silhouette = silhouette_score(reduced_components, labels,\n sample_size=500)\n logging.info('For n clusters = {}, the silhouette score is: {}'\n .format(n_clusters, silhouette))\n sample_silhouette_values = silhouette_samples(reduced_components, labels)\n np.savez(os.path.join(output_path, 'clustered_matrix'), labels)\n probability_of_state(labels, n_clusters, output_path)\n mean_lifetime_of_state(labels, n_clusters, output_path)\n plot_silhouette_analysis(reduced_components, output_path, n_clusters, silhouette,\n sample_silhouette_values, labels, gmm.means_)\n clusters_array = np.expand_dims(labels, axis=1)\n data_clusters = np.hstack((reduced_components, clusters_array))\n np.savez(os.path.join(output_path, 'concatentated_matrix_clusters'),\n data_clusters)\n return labels, data_clusters\n\n\ndef ward_clustering(reduced_components, output_path, n_clusters):\n \"\"\"\n Performs a Ward hierarchical model clustering with structure.\n\n :param reduced_components: reduced components matrix\n :type reduced_components: np.ndarray\n :param output_path: path to output directory\n :type output_path: str\n :param n_clusters: number of clusters\n :type n_clusters: int\n :return: clustered array, features array with labels\n :rtype: np.ndarray, np.ndarray\n \"\"\"\n logging.basicConfig(filename=os.path.join(output_path,\n 'clustering_Ward.log'),\n level=logging.INFO)\n connectivity = kneighbors_graph(reduced_components, 2, mode='connectivity',\n include_self=True)\n ward = AgglomerativeClustering(n_clusters=n_clusters, connectivity=connectivity,\n linkage='ward')\n ward.fit(reduced_components)\n labels = ward.labels_\n # perform the silhouette analysis as a metric for the clustering model\n silhouette = silhouette_score(reduced_components, labels,\n sample_size=500)\n logging.info('For n clusters = {}, the silhouette score is: {}'\n .format(n_clusters, silhouette))\n sample_silhouette_values = silhouette_samples(reduced_components, labels)\n np.savez(os.path.join(output_path, 'clustered_matrix'), labels)\n probability_of_state(labels, n_clusters, output_path)\n mean_lifetime_of_state(labels, n_clusters, output_path)\n plot_silhouette_analysis(reduced_components, output_path, n_clusters, silhouette,\n sample_silhouette_values, labels, ward.children_)\n clusters_array = np.expand_dims(labels, axis=1)\n data_clusters = np.hstack((reduced_components, clusters_array))\n np.savez(os.path.join(output_path, 'concatentated_matrix_clusters'),\n data_clusters)\n return labels, data_clusters\n"
] | [
[
"numpy.dot",
"numpy.expand_dims",
"sklearn.cross_validation.train_test_split",
"sklearn.cluster.KMeans",
"sklearn.metrics.silhouette_score",
"sklearn.metrics.silhouette_samples",
"sklearn.cluster.DBSCAN",
"numpy.all",
"numpy.nanmean",
"sklearn.cluster.AgglomerativeClustering",
"numpy.where",
"numpy.hstack",
"numpy.swapaxes",
"numpy.linalg.svd",
"numpy.reshape",
"sklearn.neighbors.kneighbors_graph",
"numpy.append",
"sklearn.mixture.GaussianMixture",
"numpy.sum",
"numpy.isfinite",
"sklearn.preprocessing.normalize"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LucasYoung/pocketjudge | [
"bf11336160ded127edabcd57cc6f840f006c4722"
] | [
"pjdata.py"
] | [
"import matplotlib.pyplot as plt\nimport numpy as np\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nimport torch\n\nfrom utils import calc_dataset_stats\nimport pjdataset\n\nclass StandardizeSizeTransform():\n def __init__(self):\n pass\n\n def __call__(self, image):\n if image.shape == (3, 640, 640):\n return image\n elif image.shape == (3, 360, 640):\n black = torch.zeros([3, 140, 640], dtype=torch.float)\n image = torch.cat([black, image, black], 1) # pad zeros along H axis\n return image\n else:\n return None\n\n\nclass BenchPressData:\n def __init__(self, args):\n stats_transform = transforms.Compose(\n [transforms.ToTensor(),\n StandardizeSizeTransform()]\n )\n mean, std = calc_dataset_stats(\n pjdataset.BenchPressDataset(im_dir=\"./pj_dataset_train_mini\", transform=stats_transform), \n axis=(0, 1, 2, 3)\n )\n print(mean)\n\n train_transform = transforms.Compose(\n [#transforms.RandomCrop(args.img_height),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(0.3, 0.3, 0.3),\n transforms.ToTensor(),\n StandardizeSizeTransform(),\n transforms.Normalize(mean=mean, std=std)])\n\n test_transform = transforms.Compose(\n [transforms.ToTensor(),\n StandardizeSizeTransform(),\n transforms.Normalize(mean=mean, std=std)])\n\n self.trainloader = DataLoader(pjdataset.BenchPressDataset(im_dir=\"./data/pj_dataset_train\", transform=train_transform),\n batch_size=args.batch_size,\n shuffle=args.shuffle, num_workers=args.dataloader_workers,\n pin_memory=args.pin_memory)\n\n self.testloader = DataLoader(pjdataset.BenchPressDataset(im_dir=\"./data/pj_dataset_test\", transform=test_transform),\n batch_size=args.batch_size,\n shuffle=False, num_workers=args.dataloader_workers,\n pin_memory=args.pin_memory)\n\n\nPJ_LABELS_LIST = [\n 'bad'\n 'good'\n]\n"
] | [
[
"torch.cat",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kampta/PatchGame | [
"12411e3202643217dd47a3590c413e95e960f1fc"
] | [
"eval_patchrank.py"
] | [
"import os\nimport argparse\nimport random\nimport timm\nfrom timm.models.vision_transformer import VisionTransformer\nfrom timm.models.vision_transformer import default_cfgs as timm_vit_cfgs\nimport torch\nfrom torch import nn\nimport torch.backends.cudnn as cudnn\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom patch_game.builder import PatchGame\n\nimport utils\n\n\nclass ReturnIndexDataset(datasets.ImageFolder):\n def __getitem__(self, idx):\n img, lab = super(ReturnIndexDataset, self).__getitem__(idx)\n return img, idx\n\n\n# TODO: Move these 2 functions to a submodule of timm inside our project as this is a very dirty way of overriding\n# class methods\ndef forward_features(self, x, patch_inds=None):\n B = x.shape[0]\n x = self.patch_embed(x)\n cls_token = self.cls_token.expand(x.shape[0], -1, -1) # stole cls_tokens impl from Phil Wang, thanks\n if self.dist_token is None:\n x = torch.cat((cls_token, x), dim=1)\n else:\n x = torch.cat((cls_token, self.dist_token.expand(x.shape[0], -1, -1), x), dim=1)\n x = x + self.pos_embed\n if patch_inds is not None:\n cls_inds = torch.ones(patch_inds.size(0), 1).to(patch_inds.device)\n patch_inds = torch.cat([cls_inds, patch_inds], dim=1)\n patch_inds = patch_inds.bool()\n patch_inds = patch_inds.unsqueeze(-1).expand(-1, -1, self.embed_dim)\n x = x[patch_inds]\n x = x.reshape(B, -1, self.embed_dim)\n x = self.pos_drop(x)\n\n x = self.blocks(x)\n x = self.norm(x)\n if self.dist_token is None:\n return self.pre_logits(x[:, 0])\n else:\n return x[:, 0], x[:, 1]\n\n\ndef forward(self, x, patch_inds=None):\n x = self.forward_features(x, patch_inds)\n if self.head_dist is not None:\n x, x_dist = self.head(x[0]), self.head_dist(x[1]) # x must be a tuple\n if self.training and not torch.jit.is_scripting():\n # during inference, return the average of both classifier predictions\n return x, x_dist\n else:\n return (x + x_dist) / 2\n else:\n x = self.head(x)\n return x\n\n\ndef eval(args):\n # ============ preparing data ... ============\n transform = transforms.Compose([\n transforms.Resize(256, interpolation=3),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n ])\n dataset_train = datasets.ImageFolder(os.path.join(args.data_path, \"train\"), transform=transform)\n dataset_val = datasets.ImageFolder(os.path.join(args.data_path, \"val\"), transform=transform)\n sampler = torch.utils.data.DistributedSampler(dataset_train, shuffle=False)\n data_loader_train = torch.utils.data.DataLoader(\n dataset_train,\n sampler=sampler,\n batch_size=args.batch_size_per_gpu,\n num_workers=args.num_workers,\n pin_memory=True,\n drop_last=False,\n )\n data_loader_val = torch.utils.data.DataLoader(\n dataset_val,\n batch_size=args.batch_size_per_gpu,\n num_workers=args.num_workers,\n pin_memory=True,\n drop_last=False,\n )\n print(f\"Data loaded with {len(dataset_train)} train and {len(dataset_val)} val imgs.\")\n\n # ============ building network ... ============\n vit_model = timm.create_model(args.vit_model, pretrained=True)\n vit_model.forward_features = forward_features.__get__(vit_model, VisionTransformer)\n vit_model.forward = forward.__get__(vit_model, VisionTransformer)\n vit_model.cuda()\n vit_model = nn.SyncBatchNorm.convert_sync_batchnorm(vit_model)\n vit_model = nn.parallel.DistributedDataParallel(vit_model, device_ids=[args.gpu])\n vit_model = vit_model.eval()\n patch_model = PatchGame(patch_size=args.patch_size, sender_arch=args.sender_arch,\n sender_hidden_size=args.patch_hidden_size, sender_dropout=args.sender_dropout,\n use_context=args.use_context, sender_norm=args.sender_norm,\n vocab_size=args.vocab_size, max_len=args.max_len, temperature=args.temperature,\n trainable_temperature=args.trainable_temperature, hard=args.hard,\n receiver_arch=args.receiver_arch, receiver_dim=args.receiver_dim,\n receiver_hidden_size=args.receiver_hidden_size,\n num_heads=args.receiver_num_heads, num_layers=args.receiver_num_layers,\n topk=args.topk\n )\n patch_model = patch_model.cuda()\n patch_model = nn.parallel.DistributedDataParallel(patch_model, device_ids=[args.gpu])\n to_restore = {\"epoch\": 0}\n utils.restart_from_checkpoint(\n args.patch_model,\n run_variables=to_restore,\n model=patch_model,\n )\n patch_model = patch_model.eval()\n\n print('Computing Train Accuracy')\n train_accuracy = eval_patches(data_loader_train, vit_model, patch_model)\n print('Computing Val Accuracy')\n val_accuracy = eval_patches(data_loader_val, vit_model, patch_model, args)\n\n\[email protected]_grad()\ndef eval_patches(loader, vit_model, patch_model, args):\n metric_logger = utils.MetricLogger(delimiter=\" \")\n header = 'Test:'\n\n for inp, target in metric_logger.log_every(loader, 20, header):\n # move to gpu\n inp = nn.functional.interpolate(inp, (args.im_size, args.im_size))\n inp = inp.cuda(non_blocking=True)\n target = target.cuda(non_blocking=True)\n\n with torch.no_grad():\n _, patches = patch_model.module.sender(inp)\n output = vit_model(inp, patches)\n loss = nn.CrossEntropyLoss()(output, target)\n acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))\n batch_size = inp.shape[0]\n metric_logger.update(loss=loss.item())\n metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)\n metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)\n print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}'\n .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss))\n return {k: meter.global_avg for k, meter in metric_logger.meters.items()}\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('Evaluation with pretrained ViT')\n parser.add_argument('--batch_size_per_gpu', default=128, type=int, help='Per-GPU batch-size')\n parser.add_argument('--use_cuda', default=True, type=utils.bool_flag,\n help=\"Should we store the features on GPU? We recommend setting this to False if you encounter OOM\")\n parser.add_argument('--vit_model', default='vit_base_patch32_384', type=str,\n help='Pretrained ViT from timm.')\n parser.add_argument('--speaker_arch', default='resnet', type=str,\n help='Architecture of speaker')\n parser.add_argument('--patch_model', default='', type=str, help=\"Path to pretrained weights for speaker\")\n parser.add_argument('--im_size', default=384, type=int, help='Image size to be used')\n parser.add_argument('--patch_size', default=32, type=int, help='Patch resolution of the model.')\n parser.add_argument('--num_workers', default=4, type=int, help='Number of data loading workers per GPU.')\n parser.add_argument(\"--dist_url\", default=\"env://\", type=str, help=\"\"\"url used to set up\n distributed training; see https://pytorch.org/docs/stable/distributed.html\"\"\")\n parser.add_argument(\"--world_size\", default=1, type=int, help=\"Please ignore and do not set this argument.\")\n parser.add_argument(\"--local_rank\", default=0, type=int, help=\"Please ignore and do not set this argument.\")\n parser.add_argument('--gpu', default=None, type=int,\n help='GPU id to use.')\n\n # Game play\n # Sender\n parser.add_argument('--patch_hidden_size', default=768, type=int)\n parser.add_argument('--sender_arch', default='resnet', choices=['resnet', 'vit_tiny'])\n parser.add_argument('--sender_norm', default='sort')\n parser.add_argument('--use_context', type=utils.bool_flag, default=True)\n parser.add_argument('--sender_dropout', default=0.1, type=float)\n parser.add_argument('--vocab_size', default=128, type=int)\n parser.add_argument('--max_len', default=1, type=int)\n parser.add_argument('--start_temperature', default=5.0, type=float)\n parser.add_argument('--warmup_gumbel_epochs', default=None, type=int)\n parser.add_argument('--temperature', default=1.0, type=float)\n parser.add_argument('--trainable_temperature', type=utils.bool_flag, default=False)\n parser.add_argument('--hard', type=utils.bool_flag, default=True)\n parser.add_argument('--topk', default=None, type=int)\n\n # Receiver\n parser.add_argument('--receiver_arch', default='resnet18')\n parser.add_argument('--receiver_dim', default=65536, type=int)\n parser.add_argument('--receiver_hidden_size', default=192, type=int)\n parser.add_argument('--receiver_num_heads', default=3, type=int)\n parser.add_argument('--receiver_num_layers', default=12, type=int)\n\n parser.add_argument('--data_path', default='/path/to/imagenet/', type=str)\n args = parser.parse_args()\n\n args.dist_url = f'tcp://localhost:{random.randrange(49152, 65535)}'\n utils.init_distributed_mode(args)\n print(\"git:\\n {}\\n\".format(utils.get_sha()))\n print(\"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(args)).items())))\n cudnn.benchmark = True\n\n # Checking if selected pretrained vit is compatible with other options\n assert args.vit_model in timm_vit_cfgs.keys(), f'vit_model:{args.vit_model} is not available in timm'\n vit_cfg = timm_vit_cfgs[args.vit_model]\n assert vit_cfg['input_size'] == (3, args.im_size, args.im_size), f'vit_model:{args.vit_model} has a size that is not supported'\n vit_patch_size = int(args.vit_model.split('_')[-2].replace('patch', ''))\n assert vit_patch_size == args.patch_size, f'vit_model={args.vit_model} has a patch_size={vit_patch_size} but ' \\\n f'given rank model has patch_size={args.patch_size}'\n eval(args)\n\n\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.utils.data.DistributedSampler",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.nn.SyncBatchNorm.convert_sync_batchnorm",
"torch.no_grad",
"torch.jit.is_scripting",
"torch.nn.functional.interpolate",
"torch.nn.parallel.DistributedDataParallel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
iionez/hai-project | [
"db81b3d03acf5cfe9bd5827149158c8a0dd58a9a"
] | [
"notebooks/mlworkflows/plot.py"
] | [
"import altair as alt\nimport pandas as pd\nimport numpy as np\n\n\n\nMAX_POINTS = 2500\n\ndef activate():\n pass\n \ndef plot_points(df, **kwargs):\n activate()\n plot_df = df.sample(min(len(df), MAX_POINTS))\n return alt.Chart(plot_df).encode(**kwargs).mark_point().interactive()\n\n\ndef plot_pca(df, input_column, **kwargs):\n import sklearn.decomposition\n DIMENSIONS = 2\n \n activate()\n samples = MAX_POINTS\n \n if \"func\" in kwargs:\n func = kwargs[\"func\"]\n del kwargs[\"func\"]\n else:\n func = lambda x: x\n \n a = np.array([func(v) for v in df[input_column].values])\n \n pca_a = sklearn.decomposition.PCA(DIMENSIONS).fit_transform(a)\n pca_data = pd.concat([df.reset_index(), pd.DataFrame(pca_a, columns=[\"x\", \"y\"])], axis=1)\n\n return plot_points(pca_data, **kwargs) \n \ndef plot_tsne(df, input_column, **kwargs):\n import sklearn.manifold\n \n activate()\n samples = MAX_POINTS\n \n if \"tsne_sample\" in kwargs:\n samples = kwargs[\"tsne_sample\"]\n del kwargs[\"tsne_sample\"]\n \n sdf = df.sample(samples)\n \n if \"func\" in kwargs:\n func = kwargs[\"func\"]\n del kwargs[\"func\"]\n else:\n func = lambda x: x\n \n a = np.array([func(v) for v in sdf[input_column].values])\n \n tsne = sklearn.manifold.TSNE()\n tsne_a = tsne.fit_transform(a)\n tsne_plot_data = pd.concat([sdf.reset_index(), pd.DataFrame(tsne_a, columns=[\"x\", \"y\"])], axis=1)\n\n return plot_points(tsne_plot_data, **kwargs) \n \ndef binary_confusion_matrix(actuals, predictions, labels = None, width = 215, height = 215):\n activate()\n from sklearn.metrics import confusion_matrix\n \n if labels is None:\n from sklearn.utils.multiclass import unique_labels\n labels = unique_labels(predictions, actuals)\n \n assert(len(labels) == 2)\n \n ccm = confusion_matrix(actuals, predictions, labels=labels)\n ncm = ccm.astype('float') / ccm.sum(axis=1)[:, np.newaxis]\n \n def labelizer(labels):\n def labelize(tup):\n i, v = tup\n return { 'actual': labels[int(i / 2)],'predicted': labels[i & 1], 'raw_count': v[0], 'value': v[1]}\n return labelize\n\n labelize = labelizer(labels)\n \n cmdf = pd.DataFrame([labelize(t) for t in enumerate(zip(ccm.ravel(), ncm.ravel()))])\n c = alt.Chart(cmdf).mark_rect().encode(\n x='predicted:O',\n y='actual:O',\n color='value:Q',\n tooltip=[\"raw_count:Q\"]\n ).properties(width=width, height=height)\n\n return (cmdf, c)\n "
] | [
[
"sklearn.utils.multiclass.unique_labels",
"sklearn.metrics.confusion_matrix",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
mail-ecnu/multiagent-particle-envs | [
"a3ccb43851dc6b04bab5a6e3f7443a35a4dd445f"
] | [
"multiagent/environment.py"
] | [
"import gym\nfrom gym import spaces\nfrom gym.envs.registration import EnvSpec\nimport numpy as np\n\n# environment for all agents in the multiagent world\n# currently code assumes that no agents will be created/destroyed at runtime!\nclass MultiAgentEnv(gym.Env):\n metadata = {\n 'render.modes' : ['human', 'rgb_array']\n }\n\n def __init__(self, world, reset_callback=None, reward_callback=None,\n observation_callback=None, info_callback=None,\n done_callback=None, post_step_callback=None,\n shared_viewer=True, discrete_action=False):\n\n self.world = world\n self.agents = self.world.policy_agents\n # set required vectorized gym env property\n self.n = len(world.policy_agents)\n # scenario callbacks\n self.reset_callback = reset_callback\n self.reward_callback = reward_callback\n self.observation_callback = observation_callback\n self.info_callback = info_callback\n self.done_callback = done_callback\n self.post_step_callback = post_step_callback\n # environment parameters\n self.discrete_action_space = discrete_action\n # if true, action is a number 0...N, otherwise action is a one-hot N-dimensional vector\n self.discrete_action_input = False\n # if true, even the action is continuous, action will be performed discretely\n self.force_discrete_action = world.discrete_action if hasattr(world, 'discrete_action') else False\n # if true, every agent has the same reward\n self.shared_reward = False\n self.time = 0\n\n # configure spaces\n self.action_space = []\n self.observation_space = []\n for agent in self.agents:\n total_action_space = []\n # physical action space\n if self.discrete_action_space:\n u_action_space = spaces.Discrete(world.dim_p * 2 + 1)\n else:\n u_action_space = spaces.Box(low=-agent.u_range, high=+agent.u_range, shape=(world.dim_p,))\n if agent.movable:\n total_action_space.append(u_action_space)\n # communication action space\n c_action_space = spaces.Discrete(world.dim_c)\n if not agent.silent:\n total_action_space.append(c_action_space)\n # total action space\n if len(total_action_space) > 1:\n # all action spaces are discrete, so simplify to MultiDiscrete action space\n if all([isinstance(act_space, spaces.Discrete) for act_space in total_action_space]):\n act_space = spaces.MultiDiscrete([[0,act_space.n-1] for act_space in total_action_space])\n else:\n act_space = spaces.Tuple(total_action_space)\n self.action_space.append(act_space)\n else:\n self.action_space.append(total_action_space[0])\n # observation space\n obs_dim = len(observation_callback(agent, self.world))\n self.observation_space.append(spaces.Box(low=-np.inf, high=+np.inf, shape=(obs_dim,)))\n agent.action.c = np.zeros(self.world.dim_c)\n\n # rendering\n self.shared_viewer = shared_viewer\n if self.shared_viewer:\n self.viewers = [None]\n else:\n self.viewers = [None] * self.n\n self._reset_render()\n\n def _seed(self, seed=None):\n if seed is None:\n np.random.seed(1)\n else:\n np.random.seed(seed)\n\n def _step(self, action_n):\n obs_n = []\n reward_n = []\n done_n = []\n info_n = {'n': []}\n self.agents = self.world.policy_agents\n # set action for each agent\n for i, agent in enumerate(self.agents):\n self._set_action(action_n[i], agent, self.action_space[i])\n # advance world state\n self.world.step()\n # record observation for each agent\n for agent in self.agents:\n obs_n.append(self._get_obs(agent))\n reward_n.append(self._get_reward(agent))\n done_n.append(self._get_done(agent))\n\n info_n['n'].append(self._get_info(agent))\n\n # all agents get total reward in cooperative case\n reward = np.sum(reward_n)\n if self.shared_reward:\n reward_n = [reward] * self.n\n if self.post_step_callback is not None:\n self.post_step_callback(self.world)\n return obs_n, reward_n, done_n, info_n\n\n def _reset(self):\n # reset world\n self.reset_callback(self.world)\n # reset renderer\n self._reset_render()\n # record observations for each agent\n obs_n = []\n self.agents = self.world.policy_agents\n for agent in self.agents:\n obs_n.append(self._get_obs(agent))\n return obs_n\n\n # get info used for benchmarking\n def _get_info(self, agent):\n if self.info_callback is None:\n return {}\n return self.info_callback(agent, self.world)\n\n # get observation for a particular agent\n def _get_obs(self, agent):\n if self.observation_callback is None:\n return np.zeros(0)\n return self.observation_callback(agent, self.world)\n\n # get dones for a particular agent\n # unused right now -- agents are allowed to go beyond the viewing screen\n def _get_done(self, agent):\n if self.done_callback is None:\n return False\n return self.done_callback(agent, self.world)\n\n # get reward for a particular agent\n def _get_reward(self, agent):\n if self.reward_callback is None:\n return 0.0\n return self.reward_callback(agent, self.world)\n\n # set env action for a particular agent\n def _set_action(self, action, agent, action_space, time=None):\n agent.action.u = np.zeros(self.world.dim_p)\n agent.action.c = np.zeros(self.world.dim_c)\n # process action\n if isinstance(action_space, spaces.MultiDiscrete):\n act = []\n size = action_space.high - action_space.low + 1\n index = 0\n for s in size:\n act.append(action[index:(index+s)])\n index += s\n action = act\n else:\n action = [action]\n\n if agent.movable:\n # physical action\n if self.discrete_action_input:\n agent.action.u = np.zeros(self.world.dim_p)\n # process discrete action\n if action[0] == 1: agent.action.u[0] = -1.0\n if action[0] == 2: agent.action.u[0] = +1.0\n if action[0] == 3: agent.action.u[1] = -1.0\n if action[0] == 4: agent.action.u[1] = +1.0\n else:\n if self.force_discrete_action:\n d = np.argmax(action[0])\n action[0][:] = 0.0\n action[0][d] = 1.0\n if self.discrete_action_space:\n agent.action.u[0] += action[0][1] - action[0][2]\n agent.action.u[1] += action[0][3] - action[0][4]\n else:\n agent.action.u = action[0]\n sensitivity = 5.0\n if agent.accel is not None:\n sensitivity = agent.accel\n agent.action.u *= sensitivity\n action = action[1:]\n if not agent.silent:\n # communication action\n if self.discrete_action_input:\n agent.action.c = np.zeros(self.world.dim_c)\n agent.action.c[action[0]] = 1.0\n else:\n agent.action.c = action[0]\n action = action[1:]\n # make sure we used all elements of action\n assert len(action) == 0\n\n # reset rendering assets\n def _reset_render(self):\n self.render_geoms = None\n self.render_geoms_xform = None\n\n # render environment\n def _render(self, mode='human', close=True):\n if close:\n # close any existic renderers\n for i,viewer in enumerate(self.viewers):\n if viewer is not None:\n viewer.close()\n self.viewers[i] = None\n return []\n\n if mode == 'human':\n alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n message = ''\n for agent in self.world.agents:\n comm = []\n for other in self.world.agents:\n if other is agent: continue\n if np.all(other.state.c == 0):\n word = '_'\n else:\n word = alphabet[np.argmax(other.state.c)]\n message += (other.name + ' to ' + agent.name + ': ' + word + ' ')\n # print(message)\n\n for i in range(len(self.viewers)):\n # create viewers (if necessary)\n if self.viewers[i] is None:\n # import rendering only if we need it (and don't import for headless machines)\n #from gym.envs.classic_control import rendering\n from multiagent import rendering\n self.viewers[i] = rendering.Viewer(700,700)\n\n # create rendering geometry\n if self.render_geoms is None:\n # import rendering only if we need it (and don't import for headless machines)\n #from gym.envs.classic_control import rendering\n from multiagent import rendering\n self.render_geoms = []\n self.render_geoms_xform = []\n self.comm_geoms = []\n for entity in self.world.entities:\n geom = rendering.make_circle(entity.size)\n xform = rendering.Transform()\n entity_comm_geoms = []\n if 'agent' in entity.name:\n geom.set_color(*entity.color, alpha=0.5)\n if not entity.silent:\n dim_c = self.world.dim_c\n # make circles to represent communication\n for ci in range(dim_c):\n comm = rendering.make_circle(entity.size / dim_c)\n comm.set_color(1, 1, 1)\n comm.add_attr(xform)\n offset = rendering.Transform()\n comm_size = (entity.size / dim_c)\n offset.set_translation(ci * comm_size * 2 -\n entity.size + comm_size, 0)\n comm.add_attr(offset)\n entity_comm_geoms.append(comm)\n else:\n geom.set_color(*entity.color)\n geom.add_attr(xform)\n self.render_geoms.append(geom)\n self.render_geoms_xform.append(xform)\n self.comm_geoms.append(entity_comm_geoms)\n for wall in self.world.walls:\n corners = ((wall.axis_pos - 0.5 * wall.width, wall.endpoints[0]),\n (wall.axis_pos - 0.5 * wall.width, wall.endpoints[1]),\n (wall.axis_pos + 0.5 * wall.width, wall.endpoints[1]),\n (wall.axis_pos + 0.5 * wall.width, wall.endpoints[0]))\n if wall.orient == 'H':\n corners = tuple(c[::-1] for c in corners)\n geom = rendering.make_polygon(corners)\n if wall.hard:\n geom.set_color(*wall.color)\n else:\n geom.set_color(*wall.color, alpha=0.5)\n self.render_geoms.append(geom)\n\n # add geoms to viewer\n for viewer in self.viewers:\n viewer.geoms = []\n for geom in self.render_geoms:\n viewer.add_geom(geom)\n for entity_comm_geoms in self.comm_geoms:\n for geom in entity_comm_geoms:\n viewer.add_geom(geom)\n\n results = []\n for i in range(len(self.viewers)):\n from multiagent import rendering\n # update bounds to center around agent\n cam_range = 1\n if self.shared_viewer:\n pos = np.zeros(self.world.dim_p)\n else:\n pos = self.agents[i].state.p_pos\n self.viewers[i].set_bounds(pos[0]-cam_range,pos[0]+cam_range,pos[1]-cam_range,pos[1]+cam_range)\n # update geometry positions\n for e, entity in enumerate(self.world.entities):\n self.render_geoms_xform[e].set_translation(*entity.state.p_pos)\n if 'agent' in entity.name:\n self.render_geoms[e].set_color(*entity.color, alpha=0.5)\n if not entity.silent:\n for ci in range(self.world.dim_c):\n color = 1 - entity.state.c[ci]\n self.comm_geoms[e][ci].set_color(color, color, color)\n else:\n self.render_geoms[e].set_color(*entity.color)\n # render to display or array\n results.append(self.viewers[i].render(return_rgb_array = mode=='rgb_array'))\n\n return results\n\n # create receptor field locations in local coordinate frame\n def _make_receptor_locations(self, agent):\n receptor_type = 'polar'\n range_min = 0.05 * 2.0\n range_max = 1.00\n dx = []\n # circular receptive field\n if receptor_type == 'polar':\n for angle in np.linspace(-np.pi, +np.pi, 8, endpoint=False):\n for distance in np.linspace(range_min, range_max, 3):\n dx.append(distance * np.array([np.cos(angle), np.sin(angle)]))\n # add origin\n dx.append(np.array([0.0, 0.0]))\n # grid receptive field\n if receptor_type == 'grid':\n for x in np.linspace(-range_max, +range_max, 5):\n for y in np.linspace(-range_max, +range_max, 5):\n dx.append(np.array([x,y]))\n return dx\n\n\n# vectorized wrapper for a batch of multi-agent environments\n# assumes all environments have the same observation and action space\nclass BatchMultiAgentEnv(gym.Env):\n metadata = {\n 'runtime.vectorized': True,\n 'render.modes' : ['human', 'rgb_array']\n }\n\n def __init__(self, env_batch):\n self.env_batch = env_batch\n\n @property\n def n(self):\n return np.sum([env.n for env in self.env_batch])\n\n @property\n def action_space(self):\n return self.env_batch[0].action_space\n\n @property\n def observation_space(self):\n return self.env_batch[0].observation_space\n\n def _step(self, action_n, time):\n obs_n = []\n reward_n = []\n done_n = []\n info_n = {'n': []}\n i = 0\n for env in self.env_batch:\n obs, reward, done, _ = env.step(action_n[i:(i+env.n)], time)\n i += env.n\n obs_n += obs\n # reward = [r / len(self.env_batch) for r in reward]\n reward_n += reward\n done_n += done\n return obs_n, reward_n, done_n, info_n\n\n def _reset(self):\n obs_n = []\n for env in self.env_batch:\n obs_n += env.reset()\n return obs_n\n\n # render environment\n def _render(self, mode='human', close=True):\n results_n = []\n for env in self.env_batch:\n results_n += env.render(mode, close)\n return results_n\n"
] | [
[
"numpy.random.seed",
"numpy.linspace",
"numpy.cos",
"numpy.sin",
"numpy.all",
"numpy.argmax",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
georgejeno8/modular-layers | [
"6043cca7179955334e638abb6089314affd14efb"
] | [
"mnistalt.py"
] | [
"from __future__ import division, print_function, absolute_import\nimport os\nimport struct\nfrom array import array\nimport numpy as np\n\n\ndef load_mnist(section=\"training\", offset=0, count=None, ret='xy',\n x_dtype=np.float64, y_dtype=np.int64, path=None):\n \"\"\"\n Loads MNIST files into a 3D numpy array.\n\n You have to download the data separately from [MNIST]_. It is recommended\n to set the environment variable ``MNIST_DIR`` to point to the folder where\n you put the data, so that you don't have to select path. On a Linux+bash\n setup, this is done by adding the following to your ``.bashrc``::\n\n export MNIST_DIR=/path/to/mnist\n\n Parameters\n ----------\n section : str\n Either \"training\" or \"testing\", depending on which section you want to\n load.\n offset : int\n Skip this many samples.\n count : int or None\n Try to load this many samples. Default is None, which loads until the\n end.\n ret : str\n What information to return. See return values.\n x_dtype : dtype\n Type of samples. If ``np.uint8``, intensities lie in {0, 1, ..., 255}.\n If a float type, then intensities lie in [0.0, 1.0].\n y_dtype : dtype\n Integer type to store labels.\n path : str\n Path to your MNIST datafiles. The default is ``None``, which will try\n to take the path from your environment variable ``MNIST_DIR``. The data\n can be downloaded from http://yann.lecun.com/exdb/mnist/.\n\n Returns\n -------\n images : ndarray\n Image data of shape ``(N, 28, 28)``, where ``N`` is the number of\n images. Returned if ``ret`` contains ``'x'``.\n labels : ndarray\n Array of size ``N`` describing the labels. Returned if ``ret``\n contains ``'y'``.\n\n Examples\n --------\n Assuming that you have downloaded the MNIST database and set the\n environment variable ``$MNIST_DIR`` point to the folder, this will load all\n images and labels from the training set:\n\n >>> images, labels = ag.io.load_mnist('training') # doctest: +SKIP\n\n Load 100 samples from the testing set:\n\n >>> sevens = ag.io.load_mnist('testing', offset=200, count=100,\n ret='x') # doctest: +SKIP\n\n \"\"\"\n\n # The files are assumed to have these names and should be found in 'path'\n files = {\n 'training': ('train-images-idx3-ubyte',\n 'train-labels-idx1-ubyte',\n 60000),\n 'testing': ('t10k-images-idx3-ubyte',\n 't10k-labels-idx1-ubyte',\n 10000),\n }\n\n if count is None:\n count = files[section][2] - offset\n\n if path is None:\n try:\n path = os.environ['MNIST_DIR']\n except KeyError:\n raise ValueError(\"Unspecified path requires the environment\"\n \"variable $MNIST_DIR to be set\")\n\n try:\n images_fname = os.path.join(path, files[section][0])\n labels_fname = os.path.join(path, files[section][1])\n except KeyError:\n raise ValueError(\"Data set must be 'testing' or 'training'\")\n\n returns = ()\n if 'x' in ret:\n with open(images_fname, 'rb') as fimg:\n magic_nr, size, d0, d1 = struct.unpack(\">IIII\", fimg.read(16))\n fimg.seek(offset * d0 * d1, 1)\n images_raw = array(\"B\", fimg.read(count * d0 * d1))\n\n images = np.asarray(images_raw, dtype=x_dtype).reshape(-1, d0, d1)\n if x_dtype == np.uint8:\n pass # already this type\n elif x_dtype in (np.float16, np.float32, np.float64):\n images /= 255.0\n else:\n raise ValueError(\"Unsupported value for x_dtype\")\n\n returns += (images,)\n\n if 'y' in ret:\n with open(labels_fname, 'rb') as flbl:\n magic_nr, size = struct.unpack(\">II\", flbl.read(8))\n flbl.seek(offset, 1)\n labels_raw = array(\"b\", flbl.read(count))\n\n labels = np.asarray(labels_raw)\n\n returns += (labels,)\n\n if len(returns) == 1:\n return returns[0] # Don't return a tuple of one\n else:\n return returns"
] | [
[
"numpy.asarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ShirleyPmy/lgb_football | [
"305e57d6a865ac5d81d0c8d1b84abdd3052e2de3"
] | [
"code/feature.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 6 14:36:36 2022\n\n@author: pmy\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport time\nimport utils\nimport sys\n\npd.set_option('mode.chained_assignment', None)\n\ndef steps_left_bin(data):\n df_model = data.df_model.copy()\n \n df_model['steps_left_bin'] = np.ceil(df_model['steps_left']/60).astype(int)\n \n data.df_model = df_model\n \ndef ball_position(data):\n df = data.df.copy()\n df_model = data.df_model.copy()\n \n # 小数位数太多容易过拟合\n df_model['ball_position_x'] = data.df['ball'].apply(lambda x:round(x[0],4))\n df_model['ball_position_y'] = data.df['ball'].apply(lambda x:round(x[1],4))\n df_model['ball_position_z'] = data.df['ball'].apply(lambda x:round(x[2],4))\n \n data.df_model = df_model\n\ndef ball_velocity(data):\n df = data.df.copy()\n df_model = data.df_model.copy()\n\n # 小数位数太多容易过拟合\n df_model['ball_velocity_x'] = data.df['ball_direction'].apply(lambda x: round(x[0], 4))\n df_model['ball_velocity_y'] = data.df['ball_direction'].apply(lambda x: round(x[1], 4))\n df_model['ball_velocity_z'] = data.df['ball_direction'].apply(lambda x: round(x[2], 4))\n\n data.df_model = df_model\n\ndef ball_control(data):\n df = data.df.copy()\n df_model = data.df_model.copy()\n\n df_model['ball_control'] = df['ball_owned_team_new']\n data.df_model = df_model\n\ndef owned_player_position(data):\n df = data.df.copy()\n df_model = data.df_model.copy()\n \n # 小数位数太多容易过拟合\n df_model['owned_player_position_x'] = -10\n df_model['owned_player_position_y'] = -10\n \n def from_player_index_get_position(line):\n team = line['ball_owned_team']\n index = line['ball_owned_player']\n if(team==0):\n position = line['left_team']\n elif(team==1):\n position = line['right_team']\n else:\n return np.array([-10,10])\n \n return position[index]\n \n owned_player_position = data.df.apply(from_player_index_get_position,axis=1)\n \n df_model['owned_player_position_x'] = owned_player_position.apply(lambda x:round(x[0],4))\n df_model['owned_player_position_y'] = owned_player_position.apply(lambda x:round(x[1],4))\n \n data.df_model = df_model\n\ndef owned_player_velocity(data):\n df = data.df.copy()\n df_model = data.df_model.copy()\n\n # 小数位数太多容易过拟合\n df_model['owned_player_velocity_x'] = -1\n df_model['owned_player_velocity_y'] = -1\n\n def from_player_index_get_velocity(line):\n team = line['ball_owned_team']\n index = line['ball_owned_player']\n if (team == 0):\n position = line['left_team_direction']\n elif (team == 1):\n position = line['right_team_direction']\n else:\n return np.array([-10, 10])\n\n return position[index]\n\n owned_player_velocity = data.df.apply(from_player_index_get_velocity, axis=1)\n df_model['owned_player_velocity_x'] = owned_player_velocity.apply(lambda x: round(x[0], 4))\n df_model['owned_player_velocity_y'] = owned_player_velocity.apply(lambda x: round(x[1], 4))\n\n data.df_model = df_model\n \ndef owned_ball_distance_horizontal(data):\n df_model = data.df_model.copy()\n \n #这里是偷懒的写法,因为直接使用df_model中的位置计算,而改位置我们只取了4位小数,再计算距离时不够精确\n df_model['owned_ball_distance_horizontal'] = ((df_model['ball_position_x'] - df_model['owned_player_position_x'])**2 +\n (df_model['ball_position_y'] - df_model['owned_player_position_y'])**2)**0.5\n \n data.df_model = df_model\n\ndef dis_owned_left(data):\n df = data.df.copy()\n #temp = df['left_team']\n df_model = data.df_model.copy()\n distance_0 = []\n distance_1 = []\n distance_2 = []\n for i in range(len(df_model['owned_player_position_x'])):\n temp_dis = []\n x = df_model['owned_player_position_x'][i]\n y = df_model['owned_player_position_y'][i]\n temp2 = df['left_team'][i]\n #dis = float('inf')\n for j in range(11):\n temp_dis.append(((x-temp2[j][0])**2+(y-temp2[j][1])**2)**0.5)\n #dis = min(dis, ((x-temp2[j][0])**2+(y-temp2[j][1])**2)**0.5)\n distance_0.append(sorted(temp_dis)[0])\n distance_1.append(sorted(temp_dis)[1])\n distance_2.append(sorted(temp_dis)[2])\n df_model['dis_owned_left_0'] = distance_0\n df_model['dis_owned_left_1'] = distance_1\n df_model['dis_owned_left_2'] = distance_2\n data.df_model = df_model\n\ndef dis_owned_right(data):\n df = data.df.copy()\n #temp = df['left_team']\n df_model = data.df_model.copy()\n distance_0 = []\n distance_1 = []\n distance_2 = []\n for i in range(len(df_model['owned_player_position_x'])):\n temp_dis = []\n x = df_model['owned_player_position_x'][i]\n y = df_model['owned_player_position_y'][i]\n temp2 = df['right_team'][i]\n #dis = float('inf')\n for j in range(11):\n temp_dis.append(((x-temp2[j][0])**2+(y-temp2[j][1])**2)**0.5)\n #dis = min(dis, ((x-temp2[j][0])**2+(y-temp2[j][1])**2)**0.5)\n distance_0.append(sorted(temp_dis)[0])\n distance_1.append(sorted(temp_dis)[1])\n distance_2.append(sorted(temp_dis)[2])\n df_model['dis_owned_right_0'] = distance_0\n df_model['dis_owned_right_1'] = distance_1\n df_model['dis_owned_right_2'] = distance_2\n data.df_model = df_model\n\n\ndef team_tired_factor_mean(data):\n df = data.df.copy()\n df_model = data.df_model.copy()\n \n df_model['left_team_tired_mean'] = df['left_team_tired_factor'].apply(lambda x:np.mean(x))\n df_model['right_team_tired_mean'] = df['right_team_tired_factor'].apply(lambda x:np.mean(x))\n \n data.df_model = df_model\n\n\ndef goal_position_mean(data):\n # 统计特征,统计上一场比赛的平均进球时(label=1),球的平均位置\n df = data.df.copy()\n df_model = data.df_model.copy()\n \n position = df_model.loc[df_model['label']==1,['ball_position_x','ball_position_y','ball_position_z','match_num']]\n position = position.groupby('match_num').mean()\n position.columns = ['last_match_goal_position_mean_x','last_match_goal_position_mean_y','last_match_goal_position_mean_z']\n \n position = position.reset_index()\n position['match_num'] += 1\n \n df_model = df_model.merge(position,how='left',on='match_num')\n \n data.df_model = df_model\n \n #类似的统计特征可以多搞搞,本场比赛的,其他比赛的,就是注意不要leak(标签泄漏)\n\n\n#特征思路:正常指定要计算一些,球,球门,球员的位置信息,距离,速度,前方是不是有队友接应,前方的敌人数量等\n#比较tricky的思路的话,感觉可以把球场建模成一个矩阵,然后上面有球、人的位置,状态等,用比如cnn等方式抽取一些embedding表示,让模型自己学习上述特征\n\n\n\ndef feature_engineering(data):\n # 做特征就写一个函数,然后把函数名字加到这里, 后续做实验发现这个特征没什么用,那就可以在列表中删除它,但是函数还可以留着\n good_funcs = [ball_control, ball_position, ball_velocity, owned_player_position, goal_position_mean,\n owned_player_velocity, dis_owned_left, dis_owned_right]\n \n \n origin_columns = data.df_model.columns\n origin_index = data.df_model.shape[0]\n \n funcs = good_funcs\n \n print('feature_engineering')\n print('running features num: ', len(good_funcs))\n print('data shape: ', data.df_model.shape)\n \n for func in funcs:\n tmp_columns = data.df_model.columns\n t1 = time.time()\n func(data)\n \n #数据条数不能变化\n if(data.df_model.shape[0]!=origin_index):\n print('origin data num: ', origin_index, ', now data num: ', data.df_model.shape[0])\n print('数据错误,样本数变化')\n sys.exit()\n \n add_columns = [i for i in data.df_model.columns if i not in tmp_columns]\n \n # 减内存\n for col in add_columns:\n data.df_model[col] = utils.downcast(data.df_model[col])\n \n t2 = time.time()\n print(f'do feature {func.__name__}, add columns {add_columns}, use time {t2-t1:.4f} s')\n print(data.df_model)\n \n \n"
] | [
[
"numpy.ceil",
"pandas.set_option",
"numpy.array",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
anirudhbhashyam/911-Calls-Seattle-Predictions | [
"8c975ab6c6a85d514ad74388778e1b635ed3e63d"
] | [
"src/train_nn.py"
] | [
"import os\nfrom typing import Union\n\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split, KFold\n\nimport utility as ut\nfrom variables import *\n\n\n# Read the data.\ntrain_data = pd.read_csv(os.path.join(DATA_PATH, \".\".join([DATA_TRAIN, DATA_EXT])), header = 0)\n\n# Get the labels.\nY = train_data.pop(LABEL)\n\nsample_weights = np.ones(Y.shape[0])\nfor i in range(10, 24):\n\tsample_weights[train_data[\"_\".join((\"hour\", str(i)))] == 1] = 1.5\n\n\n# -- For classification -- #\n# CLASSES = np.unique(Y)\n# N_CLASSES = len(CLASSES)\n# Y = Y.replace(dict(zip(CLASSES, range(0, len(CLASSES)))))\n \n\n# Data shape parameters.\nN_FEATURES = train_data.shape[1]\nN_SAMPLES = train_data.shape[0]\n\n# Split the training data.\nX_train, X_val, Y_train, Y_val = train_test_split(train_data, Y, shuffle = True, random_state = 7919)\n\ndef build_and_compile(input_: tuple = (WB_SIZE, N_FEATURES), \n loss_func: str = \"mae\") -> tf.keras.Model:\n\t\"\"\"\n\tBuild and compile a TensorFLow LSTM network.\n\t\n\tParameters\n\t----------\n\tinput_ :\n\t\tShape of the trainining data. Should specify \n\t\t`(batch_size` or `window_size, n_features)`\n\tloss_func :\n\t\tLoss function to use for training.\n \n\tReturns\n\t-------\n\t`tf.keras.Model` :\n\t\tA compiled TensorFlow model.\n\t\"\"\"\n \n\t# Seqential keras model.\n\tmodel = tf.keras.models.Sequential([\n\t\ttf.keras.layers.LSTM(50, input_shape = input_, return_sequences = True),\n\t\ttf.keras.layers.LSTM(50, return_sequences = False),\n\t\ttf.keras.layers.GaussianNoise(1.0),\n\t\ttf.keras.layers.Dense(1024, activation = \"relu\"),\n\t\ttf.keras.layers.Dropout(0.7),\n\t\ttf.keras.layers.Dense(128, activation = \"relu\"),\n\t\ttf.keras.layers.Dropout(0.2),\n\t\ttf.keras.layers.Dense(64, activation = \"relu\"),\n\t\ttf.keras.layers.GaussianNoise(0.2),\n\t\t# tf.keras.layers.Dense(32, activation = \"relu\"),\n\t\t# tf.keras.layers.GaussianNoise(0.7),\n\t\ttf.keras.layers.Dense(1, activation = \"relu\")\n\t])\n \n\t# Compile the model.\n\tmodel.compile(\n\t\tloss = loss_func,\n\t\toptimizer = \"adam\"\n\t)\n \n\treturn model\n\ndef train(model: tf.keras.Model,\n train_data: np.ndarray,\n train_labels: np.ndarray,\n val_data: np.ndarray,\n val_labels: np.ndarray,\n\t\t epochs: int = 200,\n\t\t sample_weights: np.array = None,\n\t\t cross_val = False) -> pd.DataFrame:\n\t\"\"\"\n\tTrains the TensorFlow `model`.\n \n\tParameters\n\t----------\n\tmodel :\n\t\tA TensorFlow compiled model.\n\ttrain_data :\n\t\tThe data to be trained. Shape must be consistent with what is passed during model compilation.\n\ttrain_labels :\n\t\tThe ground truth predictions.\n\tval_data :\n\t\tThe data to be used as validation.\n\tval_labels : \n\t\tThe ground truth validation predictions.\n\tepochs :\n\t\tTotal number of epochs to train.\n\tsample_weights :\n\t\tWeights for `train_data` to use during training.\n \n\tReturns\n\t-------\n\tpd.DataFrame:\n\t\tTraining information.\n\t\"\"\"\n \n\t# Check for overfitting.\n\tearly_stopping = tf.keras.callbacks.EarlyStopping(\n\t\tmonitor = \"val_loss\",\n\t\tmin_delta = 0.001,\n\t\tpatience = 100, \n\t\trestore_best_weights = False)\n \n\thistory = model.fit(\n\t\ttrain_data.reshape(-1, WB_SIZE, N_FEATURES), \n \t\ttrain_labels,\n\t\tsample_weight = sample_weights,\n\t\tvalidation_data = (val_data.reshape(-1, WB_SIZE, N_FEATURES), val_labels),\n\t\tverbose = 1, \n\t\tepochs = epochs,\n\t\tcallbacks = early_stopping)\n \n\treturn pd.DataFrame(history.history)\n\n# def cross_validate(train_data: pd.DataFrame,\n# train_labels: pd.DataFrame,\n# epochs: int = 50,\n# sample_weights: np.array = None,\n# folds: int = 2) -> pd.DataFrame:\n \n# \tsplits = KFold(n_splits = folds, shuffle = True)\n# \tprint(\"Starting cross validation.\")\n# \taccuracy = list()\n# \tval_loss = list()\n# \tmodels = list()\n# \tfor i, (train_index, test_index) in enumerate(splits.split(train_data, train_labels)):\n# \t\tprint(f\"Iteration {i}\\n\")\n# \t\tX_train, X_val, Y_train, Y_val = train_data[train_index], train_data[test_index], train_data[train_index], train_labels[test_index]\n \n# \t\tmodel = build_and_compile((WB_SIZE, N_FEATURES), \"mae\")\n \n# \t\thistory_df = train(model, X_train, Y_train, epochs)\n# \t\t# train_stats(history_df, i)\n\t\t\n# \t\tscores = model.evaluate(X_val.reshape(-1, WB_SIZE, N_FEATURES), Y_val)\n# \t\tprint(f\"Validation loss: {scores}\\n\")\n# #of {scores[0]} {model.metrics_names[1]} of {scores[1] * 100:.2f}%\")\n\n# \t\t# accuracy.append(scores[1] * 100)\n# \t\tval_loss.append(scores)\n# \t\tmodels.append(model)\n \n# \treturn models[np.argmin(val_loss)]\n\t \ndef train_stats(history_df: pd.DataFrame, it: int = None) -> None:\n\t\"\"\"\n\tProduces training statistics once training has run its course.\n\t\n\tParameters\n\t----------\n\thistory_df :\n\t\tThe history as returned by Keras `fit` method.\n\tit :\n\t\tTo be used with cross validation. Specifies the name of the learning curve based on the cross validation itertation `it`. \n \n\tReturns\n\t-------\n\t`None`\n\t\n\t\"\"\"\n\t# Learning curve.\n\tplt.rcParams[\"figure.dpi\"] = 160\n\thistory_df.loc[:, [\"loss\", \"val_loss\"]].plot()\n\tplt.title(\"Model Loss\")\n\tplt.ylabel(\"Loss\")\n\tplt.xlabel(\"Epoch\")\n\tname = TRAIN_FIG_SAVE_NAME\n\tif it is not None:\n\t\tname = \"_\".join([name, str(it)])\n\tplt.savefig(os.path.join(TRAIN_FIG_SAVE_PATH, \".\".join([name, FIG_EXT])))\n \n\t# Stats \n\tprint(f\"Minimum validation loss: {history_df['val_loss'].min()}\")\n\t# plt.plot(f\"Accuracy: {history_df['train_accuracy']}\")\n\t# plt.plot(f\"Validation Accuracy: {history_df['val_accuracy']}\")\n \n\treturn None\n\ndef main():\n\tmodel = build_and_compile((WB_SIZE, N_FEATURES))\n\t# model = cross_validate(np.array(train_data), np.array(Y))\n\thistory_df = train(model, np.array(X_train), np.array(Y_train), np.array(X_val), np.array(Y_val))\n\t\n\t# train_stats(history_df)\n \n\t# Save trained model (better to use checkpoints).\n\tmodel.save(os.path.join(NN_MODEL_SAVE_PATH, NN_MODEL_SAVE_NAME))\n\nif __name__ == \"__main__\":\n\tmain()\n"
] | [
[
"tensorflow.keras.layers.Dropout",
"matplotlib.pyplot.title",
"tensorflow.keras.layers.Dense",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"numpy.ones",
"tensorflow.keras.layers.GaussianNoise",
"tensorflow.keras.layers.LSTM",
"matplotlib.pyplot.xlabel",
"numpy.array",
"tensorflow.keras.callbacks.EarlyStopping",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
kmrozewski-kainos/DeepNeuralNetworkWithNumpy | [
"6394e70bedac5f5e09f33632639ce1d85ba91a32"
] | [
"deep_neural_network/predict.py"
] | [
"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom deep_neural_network.forward_propagation import Forward_Propagation\n\nclass Predict(object):\n\n def __init__(self):\n self.forward_propagation = Forward_Propagation()\n\n def predict(self, X, y, parameters):\n \"\"\"\n This function is used to predict the results of a L-layer neural network.\n\n Arguments:\n X -- data set of examples you would like to label\n parameters -- parameters of the trained model\n\n Returns:\n p -- predictions for the given dataset X\n \"\"\"\n\n m = X.shape[1]\n n = len(parameters) // 2 # number of layers in the neural network\n p = np.zeros((1,m))\n\n # Forward propagation\n probas, caches = forward_propagation.L_model_forward(X, parameters)\n\n\n # convert probas to 0/1 predictions\n for i in range(0, probas.shape[1]):\n if probas[0,i] > 0.5:\n p[0,i] = 1\n else:\n p[0,i] = 0\n\n #print results\n #print (\"predictions: \" + str(p))\n #print (\"true labels: \" + str(y))\n print(\"Accuracy: \" + str(np.sum((p == y)/m)))\n\n return p\n\n def print_mislabeled_images(self, classes, X, y, p):\n \"\"\"\n Plots images where predictions and truth were different.\n X -- dataset\n y -- true labels\n p -- predictions\n \"\"\"\n a = p + y\n mislabeled_indices = np.asarray(np.where(a == 1))\n plt.rcParams['figure.figsize'] = (40.0, 40.0) # set default size of plots\n num_images = len(mislabeled_indices[0])\n for i in range(num_images):\n index = mislabeled_indices[1][i]\n\n plt.subplot(2, num_images, i + 1)\n plt.imshow(X[:,index].reshape(64,64,3), interpolation='nearest')\n plt.axis('off')\n plt.title(\"Prediction: \" + classes[int(p[0,index])].decode(\"utf-8\") + \" \\n Class: \" + classes[y[0,index]].decode(\"utf-8\"))"
] | [
[
"matplotlib.pyplot.subplot",
"numpy.where",
"matplotlib.pyplot.axis",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Bruce198899/YOLOX_Runway | [
"aa3bd25112cfe131556e9e9354288f6b50f3892c"
] | [
"yolox/data/datasets/voc.py"
] | [
"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Code are based on\n# https://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py\n# Copyright (c) Francisco Massa.\n# Copyright (c) Ellis Brown, Max deGroot.\n# Copyright (c) Megvii, Inc. and its affiliates.\n\nimport os\nimport os.path\nimport pickle\nimport xml.etree.ElementTree as ET\nfrom loguru import logger\n\nimport cv2\nimport numpy as np\n\nfrom yolox.evaluators.voc_eval import voc_eval\n\nfrom .datasets_wrapper import Dataset\nfrom .voc_classes import VOC_CLASSES\n\n\nclass AnnotationTransform(object):\n \"\"\"Transforms a VOC annotation into a Tensor of bbox coords and label index\n Initilized with a dictionary lookup of classnames to indexes\n\n Arguments:\n class_to_ind (dict, optional): dictionary lookup of classnames -> indexes\n (default: alphabetic indexing of VOC's 20 classes)\n keep_difficult (bool, optional): keep difficult instances or not\n (default: False)\n height (int): height\n width (int): width\n \"\"\"\n\n def __init__(self, class_to_ind=None, keep_difficult=True):\n self.class_to_ind = class_to_ind or dict(\n zip(VOC_CLASSES, range(len(VOC_CLASSES)))\n )\n self.keep_difficult = keep_difficult\n\n def __call__(self, target):\n \"\"\"\n Arguments:\n target (annotation) : the target annotation to be made usable\n will be an ET.Element\n Returns:\n a list containing lists of bounding boxes [bbox coords, class name]\n \"\"\"\n res = np.empty((0, 5))\n for obj in target.iter(\"object\"):\n difficult = obj.find(\"difficult\")\n if difficult is not None:\n difficult = int(difficult.text) == 1\n else:\n difficult = False\n if not self.keep_difficult and difficult:\n continue\n name = obj.find(\"name\").text.strip()\n bbox = obj.find(\"bndbox\")\n\n pts = [\"xmin\", \"ymin\", \"xmax\", \"ymax\"]\n bndbox = []\n for i, pt in enumerate(pts):\n cur_pt = int(bbox.find(pt).text) - 1\n # scale height or width\n # cur_pt = cur_pt / width if i % 2 == 0 else cur_pt / height\n bndbox.append(cur_pt)\n label_idx = self.class_to_ind[name]\n bndbox.append(label_idx)\n res = np.vstack((res, bndbox)) # [xmin, ymin, xmax, ymax, label_ind]\n # img_id = target.find('filename').text[:-4]\n\n width = int(target.find(\"size\").find(\"width\").text)\n height = int(target.find(\"size\").find(\"height\").text)\n img_info = (height, width)\n\n return res, img_info\n\n\nclass VOCDetection(Dataset):\n \"\"\"\n VOC Detection Dataset Object\n\n input is image, target is annotation\n\n Args:\n root (string): filepath to VOCdevkit folder.\n image_set (string): imageset to use (eg. 'train', 'val', 'test')\n transform (callable, optional): transformation to perform on the\n input image\n target_transform (callable, optional): transformation to perform on the\n target `annotation`\n (eg: take in caption string, return tensor of word indices)\n dataset_name (string, optional): which dataset to load\n (default: 'VOC2007')\n \"\"\"\n\n def __init__(\n self,\n data_dir,\n image_sets=[(\"2007\", \"trainval\"), (\"2012\", \"trainval\")],\n img_size=(416, 416),\n preproc=None,\n target_transform=AnnotationTransform(),\n dataset_name=\"VOC0712\",\n cache=False,\n ):\n super().__init__(img_size)\n self.root = data_dir\n self.image_set = image_sets\n self.img_size = img_size\n self.preproc = preproc\n self.target_transform = target_transform\n self.name = dataset_name\n self._annopath = os.path.join(\"%s\", \"Annotations\", \"%s.xml\")\n self._imgpath = os.path.join(\"%s\", \"JPEGImages\", \"%s.jpg\")\n self._classes = VOC_CLASSES\n self.ids = list()\n for (year, name) in image_sets:\n self._year = year\n rootpath = os.path.join(self.root, \"VOC\" + year)\n for line in open(\n os.path.join(rootpath, \"ImageSets\", \"Main\", name + \".txt\")\n ):\n self.ids.append((rootpath, line.strip()))\n\n self.annotations = self._load_coco_annotations()\n self.imgs = None\n if cache:\n self._cache_images()\n\n def __len__(self):\n return len(self.ids)\n\n def _load_coco_annotations(self):\n return [self.load_anno_from_ids(_ids) for _ids in range(len(self.ids))]\n\n def _cache_images(self):\n logger.warning(\n \"\\n********************************************************************************\\n\"\n \"You are using cached images in RAM to accelerate training.\\n\"\n \"This requires large system RAM.\\n\"\n \"Make sure you have 60G+ RAM and 19G available disk space for training VOC.\\n\"\n \"********************************************************************************\\n\"\n )\n max_h = self.img_size[0]\n max_w = self.img_size[1]\n cache_file = self.root + \"/img_resized_cache_\" + self.name + \".array\"\n if not os.path.exists(cache_file):\n logger.info(\n \"Caching images for the first time. This might take about 3 minutes for VOC\"\n )\n self.imgs = np.memmap(\n cache_file,\n shape=(len(self.ids), max_h, max_w, 3),\n dtype=np.uint8,\n mode=\"w+\",\n )\n from tqdm import tqdm\n from multiprocessing.pool import ThreadPool\n\n NUM_THREADs = min(8, os.cpu_count())\n loaded_images = ThreadPool(NUM_THREADs).imap(\n lambda x: self.load_resized_img(x),\n range(len(self.annotations)),\n )\n pbar = tqdm(enumerate(loaded_images), total=len(self.annotations))\n for k, out in pbar:\n self.imgs[k][: out.shape[0], : out.shape[1], :] = out.copy()\n self.imgs.flush()\n pbar.close()\n else:\n logger.warning(\n \"You are using cached imgs! Make sure your dataset is not changed!!\\n\"\n \"Everytime the self.input_size is changed in your exp file, you need to delete\\n\"\n \"the cached data and re-generate them.\\n\"\n )\n\n logger.info(\"Loading cached imgs...\")\n self.imgs = np.memmap(\n cache_file,\n shape=(len(self.ids), max_h, max_w, 3),\n dtype=np.uint8,\n mode=\"r+\",\n )\n\n def load_anno_from_ids(self, index):\n img_id = self.ids[index]\n target = ET.parse(self._annopath % img_id).getroot()\n\n assert self.target_transform is not None\n res, img_info = self.target_transform(target)\n height, width = img_info\n\n r = min(self.img_size[0] / height, self.img_size[1] / width)\n res[:, :4] *= r\n resized_info = (int(height * r), int(width * r))\n\n return (res, img_info, resized_info)\n\n def load_anno(self, index):\n return self.annotations[index][0]\n\n def load_resized_img(self, index):\n img = self.load_image(index)\n r = min(self.img_size[0] / img.shape[0], self.img_size[1] / img.shape[1])\n resized_img = cv2.resize(\n img,\n (int(img.shape[1] * r), int(img.shape[0] * r)),\n interpolation=cv2.INTER_LINEAR,\n ).astype(np.uint8)\n\n return resized_img\n\n def load_image(self, index):\n img_id = self.ids[index]\n img = cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\n assert img is not None\n\n return img\n\n def pull_item(self, index):\n \"\"\"Returns the original image and target at an index for mixup\n\n Note: not using self.__getitem__(), as any transformations passed in\n could mess up this functionality.\n\n Argument:\n index (int): index of img to show\n Return:\n img, target\n \"\"\"\n if self.imgs is not None:\n target, img_info, resized_info = self.annotations[index]\n pad_img = self.imgs[index]\n img = pad_img[: resized_info[0], : resized_info[1], :].copy()\n else:\n img = self.load_resized_img(index)\n target, img_info, _ = self.annotations[index]\n\n return img, target, img_info, index\n\n @Dataset.mosaic_getitem\n def __getitem__(self, index):\n img, target, img_info, img_id = self.pull_item(index)\n\n if self.preproc is not None:\n img, target = self.preproc(img, target, self.input_dim)\n\n return img, target, img_info, img_id\n\n def evaluate_detections(self, all_boxes, output_dir=None):\n \"\"\"\n all_boxes is a list of length number-of-classes.\n Each list element is a list of length number-of-images.\n Each of those list elements is either an empty list []\n or a numpy array of detection.\n\n all_boxes[class][image] = [] or np.array of shape #dets x 5\n \"\"\"\n self._write_voc_results_file(all_boxes)\n IouTh = np.linspace(\n 0.5, 0.95, int(np.round((0.95 - 0.5) / 0.05)) + 1, endpoint=True\n )\n mAPs = []\n for iou in IouTh:\n mAP = self._do_python_eval(output_dir, iou)\n mAPs.append(mAP)\n\n print(\"--------------------------------------------------------------\")\n print(\"map_5095:\", np.mean(mAPs))\n print(\"map_50:\", mAPs[0])\n print(\"--------------------------------------------------------------\")\n return np.mean(mAPs), mAPs[0]\n\n def _get_voc_results_file_template(self):\n filename = \"comp4_det_test\" + \"_{:s}.txt\"\n filedir = os.path.join(self.root, \"results\", \"VOC\" + self._year, \"Main\")\n if not os.path.exists(filedir):\n os.makedirs(filedir)\n path = os.path.join(filedir, filename)\n return path\n\n def _write_voc_results_file(self, all_boxes):\n for cls_ind, cls in enumerate(VOC_CLASSES):\n cls_ind = cls_ind\n if cls == \"__background__\":\n continue\n print(\"Writing {} VOC results file\".format(cls))\n filename = self._get_voc_results_file_template().format(cls)\n with open(filename, \"wt\") as f:\n for im_ind, index in enumerate(self.ids):\n index = index[1]\n dets = all_boxes[cls_ind][im_ind]\n if dets == []:\n continue\n for k in range(dets.shape[0]):\n f.write(\n \"{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n\".format(\n index,\n dets[k, -1],\n dets[k, 0] + 1,\n dets[k, 1] + 1,\n dets[k, 2] + 1,\n dets[k, 3] + 1,\n )\n )\n\n def _do_python_eval(self, output_dir=\"output\", iou=0.5):\n rootpath = os.path.join(self.root, \"VOC\" + self._year)\n name = self.image_set[0][1]\n # annopath = os.path.join(rootpath, \"Annotations\", \"{:s}.xml\")\n annopath = os.path.join(rootpath, \"Annotations\", \"{}.xml\")\n # 根据 https://blog.csdn.net/weixin_42166222/article/details/119637797 做出修改\n imagesetfile = os.path.join(rootpath, \"ImageSets\", \"Main\", name + \".txt\")\n cachedir = os.path.join(\n self.root, \"annotations_cache\", \"VOC\" + self._year, name\n )\n if not os.path.exists(cachedir):\n os.makedirs(cachedir)\n aps = []\n # The PASCAL VOC metric changed in 2010\n use_07_metric = True if int(self._year) < 2010 else False\n print(\"Eval IoU : {:.2f}\".format(iou))\n if output_dir is not None and not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n for i, cls in enumerate(VOC_CLASSES):\n\n if cls == \"__background__\":\n continue\n\n filename = self._get_voc_results_file_template().format(cls)\n rec, prec, ap = voc_eval(\n filename,\n annopath,\n imagesetfile,\n cls,\n cachedir,\n ovthresh=iou,\n use_07_metric=use_07_metric,\n )\n aps += [ap]\n if iou == 0.5:\n print(\"AP for {} = {:.4f}\".format(cls, ap))\n if output_dir is not None:\n with open(os.path.join(output_dir, cls + \"_pr.pkl\"), \"wb\") as f:\n pickle.dump({\"rec\": rec, \"prec\": prec, \"ap\": ap}, f)\n if iou == 0.5:\n print(\"Mean AP = {:.4f}\".format(np.mean(aps)))\n print(\"~~~~~~~~\")\n print(\"Results:\")\n for ap in aps:\n print(\"{:.3f}\".format(ap))\n print(\"{:.3f}\".format(np.mean(aps)))\n print(\"~~~~~~~~\")\n print(\"\")\n print(\"--------------------------------------------------------------\")\n print(\"Results computed with the **unofficial** Python eval code.\")\n print(\"Results should be very close to the official MATLAB eval code.\")\n print(\"Recompute with `./tools/reval.py --matlab ...` for your paper.\")\n print(\"-- Thanks, The Management\")\n print(\"--------------------------------------------------------------\")\n\n return np.mean(aps)\n"
] | [
[
"numpy.round",
"numpy.vstack",
"numpy.mean",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mysterefrank/covid-test | [
"8651d9515376ca88e25b309c710c256bb22804d9"
] | [
"scripts/score.py"
] | [
"import configs\nimport covid.util as util\nimport covid.states as states\nimport covid.models.SEIRD_variable_detection\nimport covid.jhu as jhu\nimport numpy as np\nimport pandas as pd\nimport argparse\n\nfrom pathlib import Path\n\nroot='results1'\n\nconfig_names=['counties']\nforecast_dates=[\"2020-05-17\", \"2020-05-24\", \"2020-05-31\", \"2020-06-07\", \"2020-06-14\", \"2020-06-21\", \"2020-06-28\", \"2020-07-05\"]\nforecast_dates=[\"2020-06-07\", \"2020-07-05\"]\neval_date = '2020-07-09'\n\nconfig_names=['longer_H', 'resample_80_last_10']\nforecast_dates = ['2020-08-16', '2020-08-23', '2020-08-30', '2020-09-06']\neval_date = '2020-09-12'\n\n\ndef write_summary(summary, filename):\n summary = summary.reset_index(drop=True)\n cols = list(summary.columns)\n special_cols = ['model', 'forecast_date', 'eval_date', 'horizon']\n for c in special_cols:\n cols.remove(c) \n cols = special_cols + cols\n summary.to_csv(filename, float_format=\"%.4f\", columns=cols, index=False)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='Score compartmental models.')\n parser.add_argument('places', help='places to use', nargs='?', choices=['US', 'states', 'counties'], default='states')\n parser.add_argument('-t', '--target', help=\"target to score\", choices=['cases', 'deaths'], default='deaths')\n parser.add_argument('-n', '--num_places', help=\"use this many places only\", type=int, default=None)\n args = parser.parse_args()\n\n data = util.load_data()\n\n # Set places\n if args.places == 'US':\n places = ['US']\n suffix = '-US'\n elif args.places == 'states':\n places = list(jhu.get_state_info().sort_index().index)\n suffix = \"-states\"\n elif args.places == 'counties':\n places = list(jhu.get_county_info().sort_values('Population', ascending=False).index)\n suffix = \"-counties\"\n else:\n raise ValueError('Unrecognized place: ' + args.places)\n\n\n if args.num_places:\n places = places[:args.num_places]\n\n overall_summary = pd.DataFrame()\n\n for config_name in config_names:\n print(f\"****Config {config_name}****\")\n\n config_summary = pd.DataFrame()\n \n for forecast_date in forecast_dates:\n print(f\" **Forecast date {forecast_date}**\")\n\n prefix = f\"{root}/{config_name}/{forecast_date}\"\n\n config = getattr(configs, config_name) \n errs = []\n\n summary, details = util.score_forecast(forecast_date,\n data,\n model_type=config['model'],\n prefix=prefix,\n places=places,\n target=args.target)\n\n summary.insert(0, 'model', config_name)\n details.insert(0, 'model', config_name)\n \n path = Path(prefix) / 'eval'\n path.mkdir(parents=True, exist_ok=True)\n summary.to_csv(path / f'summary{suffix}.csv', float_format=\"%.4f\")\n details.to_csv(path / f'details{suffix}.csv', float_format=\"%.4f\")\n\n\n config_summary = config_summary.append(summary.loc[eval_date])\n \n\n # add eval date and save\n config_summary['eval_date'] = eval_date\n\n print(f\"***Config {config_name} results***\")\n print(config_summary)\n write_summary(config_summary, f\"{root}/{config_name}/summary{suffix}.csv\")\n\n overall_summary = overall_summary.append(config_summary)\n \n\n # write overall summary\n write_summary(overall_summary, Path(root) / f'summary{suffix}.csv')\n print(f\"***Overall results***\")\n print(overall_summary)\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
cxq1/paddle_VinVL | [
"f9136871c43b033cd209ddc7579fa986208e37db"
] | [
"tests/test_box_coder.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport unittest\n\nimport numpy as np\nimport paddle\nfrom maskrcnn_benchmark.modeling.box_coder import BoxCoder\n\n\nclass TestBoxCoder(unittest.TestCase):\n def test_box_decoder(self):\n \"\"\" Match unit test UtilsBoxesTest.TestBboxTransformRandom in\n caffe2/operators/generate_proposals_op_util_boxes_test.cc\n \"\"\"\n box_coder = BoxCoder(weights=(1.0, 1.0, 1.0, 1.0))\n bbox = paddle.to_tensor(\n np.array(\n [\n 175.62031555,\n 20.91103172,\n 253.352005,\n 155.0145874,\n 169.24636841,\n 4.85241556,\n 228.8605957,\n 105.02092743,\n 181.77426147,\n 199.82876587,\n 192.88427734,\n 214.0255127,\n 174.36262512,\n 186.75761414,\n 296.19091797,\n 231.27906799,\n 22.73153877,\n 92.02596283,\n 135.5695343,\n 208.80291748,\n ]\n )\n .astype(np.float32)\n .reshape(-1, 4)\n )\n\n deltas = paddle.to_tensor(\n np.array(\n [\n 0.47861834,\n 0.13992102,\n 0.14961673,\n 0.71495209,\n 0.29915856,\n -0.35664671,\n 0.89018666,\n 0.70815367,\n -0.03852064,\n 0.44466892,\n 0.49492538,\n 0.71409376,\n 0.28052918,\n 0.02184832,\n 0.65289006,\n 1.05060139,\n -0.38172557,\n -0.08533806,\n -0.60335309,\n 0.79052375,\n ]\n )\n .astype(np.float32)\n .reshape(-1, 4)\n )\n\n gt_bbox = (\n np.array(\n [\n 206.949539,\n -30.715202,\n 297.387665,\n 244.448486,\n 143.871216,\n -83.342888,\n 290.502289,\n 121.053398,\n 177.430283,\n 198.666245,\n 196.295273,\n 228.703079,\n 152.251892,\n 145.431564,\n 387.215454,\n 274.594238,\n 5.062420,\n 11.040955,\n 66.328903,\n 269.686218,\n ]\n )\n .astype(np.float32)\n .reshape(-1, 4)\n )\n\n results = box_coder.decode(deltas, bbox)\n\n np.testing.assert_allclose(results.detach().numpy(), gt_bbox, atol=1e-4)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
alempedroso/mxnet-lambda | [
"22a683c63b7d0153cc2249a94d76b3c8969b1972"
] | [
"src/mxnet/ndarray/ndarray.py"
] | [
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# coding: utf-8\n# pylint: disable=too-many-lines, protected-access\n# pylint: disable=import-error, no-name-in-module, undefined-variable\n\"\"\"NDArray API of MXNet.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\n\ntry:\n from __builtin__ import slice as py_slice\nexcept ImportError:\n from builtins import slice as py_slice\n\nimport ctypes\nimport warnings\nimport operator\nfrom functools import reduce # pylint: disable=redefined-builtin\nimport numpy as np\nfrom ..base import _LIB, numeric_types, integer_types\nfrom ..base import c_array, mx_real_t\nfrom ..base import mx_uint, NDArrayHandle, check_call\nfrom ..base import ctypes2buffer\nfrom ..context import Context\nfrom . import _internal\nfrom . import op\nfrom ._internal import NDArrayBase\n\n__all__ = [\"NDArray\", \"concatenate\", \"_DTYPE_NP_TO_MX\", \"_DTYPE_MX_TO_NP\", \"_GRAD_REQ_MAP\",\n \"ones\", \"add\", \"arange\", \"divide\", \"equal\", \"full\", \"greater\", \"greater_equal\",\n \"imdecode\", \"lesser\", \"lesser_equal\", \"maximum\", \"minimum\", \"moveaxis\", \"modulo\",\n \"multiply\", \"not_equal\", \"onehot_encode\", \"power\", \"subtract\", \"true_divide\",\n \"waitall\", \"_new_empty_handle\"]\n\n_STORAGE_TYPE_UNDEFINED = -1\n_STORAGE_TYPE_DEFAULT = 0\n_STORAGE_TYPE_ROW_SPARSE = 1\n_STORAGE_TYPE_CSR = 2\n\n# pylint: disable= no-member\n_DTYPE_NP_TO_MX = {\n None: -1,\n np.float32: 0,\n np.float64: 1,\n np.float16: 2,\n np.uint8: 3,\n np.int32: 4,\n np.int8: 5,\n np.int64: 6,\n}\n\n_DTYPE_MX_TO_NP = {\n -1: None,\n 0: np.float32,\n 1: np.float64,\n 2: np.float16,\n 3: np.uint8,\n 4: np.int32,\n 5: np.int8,\n 6: np.int64,\n}\n\n_STORAGE_TYPE_STR_TO_ID = {\n 'undefined': _STORAGE_TYPE_UNDEFINED,\n 'default': _STORAGE_TYPE_DEFAULT,\n 'row_sparse': _STORAGE_TYPE_ROW_SPARSE,\n 'csr': _STORAGE_TYPE_CSR,\n}\n\n_STORAGE_TYPE_ID_TO_STR = {\n _STORAGE_TYPE_UNDEFINED: 'undefined',\n _STORAGE_TYPE_DEFAULT: 'default',\n _STORAGE_TYPE_ROW_SPARSE: 'row_sparse',\n _STORAGE_TYPE_CSR: 'csr',\n}\n\n_GRAD_REQ_MAP = {\n 'null': 0,\n 'write': 1,\n 'add': 3\n}\n# pylint: enable= no-member\n\n\ndef _new_empty_handle():\n \"\"\"Returns a new empty handle.\n\n Empty handle can be used to hold a result.\n\n Returns\n -------\n handle\n A new empty `NDArray` handle.\n \"\"\"\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl)))\n return hdl\n\n\ndef _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):\n \"\"\"Return a new handle with specified shape and context.\n\n Empty handle is only used to hold results.\n\n Returns\n -------\n handle\n A new empty `NDArray` handle.\n \"\"\"\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayCreateEx(\n c_array(mx_uint, shape),\n mx_uint(len(shape)),\n ctypes.c_int(ctx.device_typeid),\n ctypes.c_int(ctx.device_id),\n ctypes.c_int(int(delay_alloc)),\n ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])),\n ctypes.byref(hdl)))\n return hdl\n\n\ndef waitall():\n \"\"\"Wait for all async operations to finish in MXNet.\n\n This function is used for benchmarking only.\n \"\"\"\n check_call(_LIB.MXNDArrayWaitAll())\n\n\ndef _storage_type(handle):\n storage_type = ctypes.c_int(0)\n check_call(_LIB.MXNDArrayGetStorageType(handle, ctypes.byref(storage_type)))\n return storage_type.value\n\n\nclass NDArray(NDArrayBase):\n \"\"\"An array object representing a multidimensional, homogeneous array of\nfixed-size items.\n\n \"\"\"\n __slots__ = []\n # make numpy functions return NDArray instead of numpy object array\n __array_priority__ = 1000.0\n # pylint: disable= no-member, undefined-variable\n\n def __repr__(self):\n \"\"\"Returns a string representation of the array.\"\"\"\n shape_info = 'x'.join(['%d' % x for x in self.shape])\n return '\\n%s\\n<%s %s @%s>' % (str(self.asnumpy()),\n self.__class__.__name__,\n shape_info, self.context)\n\n def __reduce__(self):\n return NDArray, (None,), self.__getstate__()\n\n def __add__(self, other):\n \"\"\"x.__add__(y) <=> x+y <=> mx.nd.add(x, y) \"\"\"\n return add(self, other)\n\n def __iadd__(self, other):\n \"\"\"x.__iadd__(y) <=> x+=y \"\"\"\n if not self.writable:\n raise ValueError('trying to add to a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_add(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._plus_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __sub__(self, other):\n \"\"\"x.__sub__(y) <=> x-y <=> mx.nd.subtract(x, y) \"\"\"\n return subtract(self, other)\n\n def __isub__(self, other):\n \"\"\"x.__isub__(y) <=> x-=y \"\"\"\n if not self.writable:\n raise ValueError('trying to subtract from a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_sub(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._minus_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __rsub__(self, other):\n \"\"\"x.__rsub__(y) <=> y-x <=> mx.nd.subtract(y, x) \"\"\"\n return subtract(other, self)\n\n def __mul__(self, other):\n \"\"\"x.__mul__(y) <=> x*y <=> mx.nd.multiply(x, y) \"\"\"\n return multiply(self, other)\n\n def __neg__(self):\n \"\"\"x.__neg__(y) <=> -x \"\"\"\n return _internal._mul_scalar(self, -1.0)\n\n def __imul__(self, other):\n \"\"\"x.__imul__(y) <=> x*=y \"\"\"\n if not self.writable:\n raise ValueError('trying to multiply to a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_mul(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._mul_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __div__(self, other):\n \"\"\"x.__div__(y) <=> x/y <=> mx.nd.divide(x, y) \"\"\"\n return divide(self, other)\n\n def __rdiv__(self, other):\n \"\"\"x.__rdiv__(y) <=> y/x <=> mx.nd.divide(y, x) \"\"\"\n return divide(other, self)\n\n def __idiv__(self, other):\n \"\"\"x.__rdiv__(y) <=> x/=y \"\"\"\n if not self.writable:\n raise ValueError('trying to divide from a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_div(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._div_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __truediv__(self, other):\n return divide(self, other)\n\n def __rtruediv__(self, other):\n return divide(other, self)\n\n def __itruediv__(self, other):\n return self.__idiv__(other)\n\n def __mod__(self, other):\n \"\"\"x.__mod__(y) <=> x%y <=> mx.nd.modulo(x, y) \"\"\"\n return modulo(self, other)\n\n def __rmod__(self, other):\n \"\"\"x.__rmod__(y) <=> y%x <=> mx.nd.modulo(y, x) \"\"\"\n return modulo(other, self)\n\n def __imod__(self, other):\n \"\"\"x.__rmod__(y) <=> x%=y \"\"\"\n if not self.writable:\n raise ValueError('trying to take modulo from a readonly NDArray')\n if isinstance(other, NDArray):\n return op.broadcast_mod(self, other, out=self)\n elif isinstance(other, numeric_types):\n return _internal._mod_scalar(self, float(other), out=self)\n else:\n raise TypeError('type %s not supported' % str(type(other)))\n\n def __pow__(self, other):\n \"\"\"x.__pow__(y) <=> x**y <=> mx.nd.power(x,y) \"\"\"\n return power(self, other)\n\n def __rpow__(self, other):\n \"\"\"x.__pow__(y) <=> y**x <=> mx.nd.power(y,x) \"\"\"\n return power(other, self)\n\n def __eq__(self, other):\n \"\"\"x.__eq__(y) <=> x==y <=> mx.nd.equal(x, y) \"\"\"\n return equal(self, other)\n\n def __ne__(self, other):\n \"\"\"x.__ne__(y) <=> x!=y <=> mx.nd.not_equal(x, y) \"\"\"\n return not_equal(self, other)\n\n def __gt__(self, other):\n \"\"\"x.__gt__(y) <=> x>y <=> mx.nd.greater(x, y) \"\"\"\n return greater(self, other)\n\n def __ge__(self, other):\n \"\"\"x.__ge__(y) <=> x>=y <=> mx.nd.greater_equal(x, y) \"\"\"\n return greater_equal(self, other)\n\n def __lt__(self, other):\n \"\"\"x.__lt__(y) <=> x<y <=> mx.nd.lesser(x, y) \"\"\"\n return lesser(self, other)\n\n def __le__(self, other):\n \"\"\"x.__le__(y) <=> x<=y <=> mx.nd.less_equal(x, y) \"\"\"\n return lesser_equal(self, other)\n\n def __bool__(self):\n num_elements = reduce(operator.mul, self.shape, 1)\n if num_elements == 0:\n return False\n elif num_elements == 1:\n return bool(self.asscalar())\n else:\n raise ValueError(\"The truth value of an NDArray with multiple elements \" \\\n \"is ambiguous.\")\n\n __nonzero__ = __bool__\n\n def __len__(self):\n \"\"\"Number of element along the first axis.\"\"\"\n return self.shape[0]\n\n def __getstate__(self):\n handle = self.handle\n this = {'handle' : None}\n if handle is not None:\n length = ctypes.c_size_t()\n cptr = ctypes.POINTER(ctypes.c_char)()\n check_call(_LIB.MXNDArraySaveRawBytes(self.handle,\n ctypes.byref(length),\n ctypes.byref(cptr)))\n this['handle'] = ctypes2buffer(cptr, length.value)\n return this\n\n def __setstate__(self, state):\n # pylint: disable=assigning-non-slot\n handle = state['handle']\n if handle is not None:\n buf = handle\n handle = NDArrayHandle()\n ptr = (ctypes.c_char * len(buf)).from_buffer(buf)\n length = ctypes.c_size_t(len(buf))\n check_call(_LIB.MXNDArrayLoadFromRawBytes(ptr, length, ctypes.byref(handle)))\n self.handle = handle\n else:\n self.handle = None\n\n def __setitem__(self, key, value):\n \"\"\"x.__setitem__(i, y) <=> x[i]=y\n\n Set self[key] to value.\n\n Parameters\n ----------\n key : int, slice or tuple\n The indexing key.\n value : scalar, NDArray or numpy.ndarray\n The value to set.\n\n Examples\n --------\n >>> x = mx.nd.zeros((2,3))\n >>> x[:] = 1\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> x[:,1:2] = 2\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 1., 2., 1.]], dtype=float32)\n >>> x[1:2,1:] = 3\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 1., 3., 3.]], dtype=float32)\n >>> x[1:,0:2] = mx.nd.zeros((1,2))\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 0., 0., 3.]], dtype=float32)\n >>> x[1,2] = 4\n >>> x.asnumpy()\n array([[ 1., 2., 1.],\n [ 0., 0., 4.]], dtype=float32)\n \"\"\"\n # pylint: disable=too-many-branches\n if not self.writable:\n raise ValueError('Cannot assign to readonly NDArray')\n if isinstance(key, integer_types):\n sliced_arr = self._at(key)\n sliced_arr[:] = value\n return\n elif isinstance(key, py_slice):\n if key.step is not None:\n raise ValueError('NDArray only supports slicing with step size 1')\n if key.start is not None or key.stop is not None:\n sliced_arr = self._slice(key.start, key.stop)\n sliced_arr[:] = value\n return\n if isinstance(value, NDArray):\n if value.handle is not self.handle:\n value.copyto(self)\n elif isinstance(value, numeric_types):\n _internal._set_value(float(value), out=self)\n elif isinstance(value, (np.ndarray, np.generic)):\n self._sync_copyfrom(value)\n else:\n raise TypeError(\n 'NDArray does not support assignment with %s of type %s'%(\n str(value), str(type(value))))\n elif isinstance(key, tuple):\n # multi-dimension indexing\n my_shape = self.shape\n assert len(key) <= len(my_shape), \\\n \"Indexing dimensions exceed array dimensions, %d vs %d\"%(\n len(key), len(my_shape))\n begin = [0 for _ in my_shape]\n end = [x for x in my_shape]\n expand = []\n for i, slice_i in enumerate(key):\n if isinstance(slice_i, integer_types):\n assert slice_i < my_shape[i]\n begin[i] = slice_i\n end[i] = slice_i + 1\n expand.append(i)\n elif isinstance(slice_i, py_slice):\n # only support continuous slicing\n assert slice_i.step is None, \\\n \"NDArray only supports slicing with step size 1.\"\n begin[i] = slice_i.start or 0\n end[i] = slice_i.stop or my_shape[i]\n assert begin[i] < end[i]\n assert end[i] <= my_shape[i]\n else:\n raise ValueError(\n \"NDArray does not support slicing with key %s of type %s.\"%(\n str(slice_i), str(type(slice_i))))\n\n if isinstance(value, NDArray):\n value = value.as_in_context(self.context)\n self._slice_assign(value, begin, end, expand)\n elif isinstance(value, numeric_types):\n _internal._crop_assign_scalar(self, out=self,\n begin=begin, end=end,\n scalar=value)\n elif isinstance(value, (np.ndarray, np.generic)):\n value = array(value, ctx=self.context, dtype=self.dtype)\n self._slice_assign(value, begin, end, expand)\n else:\n raise TypeError(\n 'NDArray does not support assignment with %s of type %s'%(\n str(value), str(type(value))))\n else:\n raise ValueError(\n \"NDArray does not support slicing with key %s of type %s.\"%(\n str(key), str(type(key))))\n # pylint: enable=too-many-branches\n\n def _slice_assign(self, value, begin, end, expand):\n vshape = list(value.shape)\n if expand and len(vshape) != len(begin):\n if len(expand) + len(vshape) != len(begin):\n sshape = [e - b for e, b in zip(end, begin)]\n for i in reversed(expand):\n sshape.pop(i)\n raise ValueError(\n \"Cannot assign NDArray with shape %s to NDArray slice with \" \\\n \"shape %s\"%(str(vshape), str(sshape)))\n for i in expand:\n vshape.insert(i, 1)\n value = value.reshape(vshape)\n _internal._crop_assign(self, value, out=self,\n begin=begin, end=end)\n\n def __getitem__(self, key):\n \"\"\"x.__getitem__(i) <=> x[i]\n\n Returns a sliced view of this array.\n\n Parameters\n ----------\n key : int or slice, or array like\n Indexing key.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,6).reshape((2,3))\n >>> x.asnumpy()\n array([[ 0., 1., 2.],\n [ 3., 4., 5.]], dtype=float32)\n >>> x[1].asnumpy()\n array([ 3., 4., 5.], dtype=float32)\n >>> y = x[0:1]\n >>> y[:] = 2\n >>> x.asnumpy()\n array([[ 2., 2., 2.],\n [ 3., 4., 5.]], dtype=float32)\n \"\"\"\n # multi-dimensional slicing is not supported yet\n if isinstance(key, integer_types):\n if key > self.shape[0] - 1:\n raise IndexError(\n 'index {} is out of bounds for axis 0 with size {}'.format(\n key, self.shape[0]))\n return self._at(key)\n elif isinstance(key, py_slice):\n if key.step is not None:\n raise ValueError(\"NDArray only supports slicing with step size 1.\")\n if key.start is not None or key.stop is not None:\n return self._slice(key.start, key.stop)\n return self\n elif isinstance(key, tuple):\n shape = self.shape\n assert len(key) > 0, \"Cannot slice with empty indices\"\n assert len(shape) >= len(key), \\\n \"Slicing dimensions exceeds array dimensions, %d vs %d\"%(\n len(key), len(shape))\n if isinstance(key[0], (NDArray, np.ndarray, list, tuple)):\n indices = []\n dtype = 'int32'\n shape = None\n for idx_i in key:\n if not isinstance(idx_i, NDArray):\n assert isinstance(idx_i, (NDArray, np.ndarray, list, tuple)), \\\n \"Combining basic and advanced indexing is not supported \" \\\n \"yet. Indices must be all NDArray or all slice, not a \" \\\n \"mix of both.\"\n idx_i = array(idx_i, ctx=self.context, dtype=dtype)\n else:\n dtype = idx_i.dtype\n if shape is None:\n shape = idx_i.shape\n else:\n assert shape == idx_i.shape, \\\n \"All index arrays must have the same shape: %s vs %s. \" \\\n \"Broadcasting is not supported yet.\"%(shape, idx_i.shape)\n indices.append(idx_i)\n indices = op.stack(*indices)\n return op.gather_nd(self, indices)\n else:\n oshape = []\n begin = []\n end = []\n i = -1\n for i, slice_i in enumerate(key):\n if isinstance(slice_i, integer_types):\n begin.append(slice_i)\n end.append(slice_i+1)\n elif isinstance(slice_i, py_slice):\n if slice_i.step is not None:\n raise ValueError(\"NDArray only supports slicing with step size 1.\")\n begin.append(0 if slice_i.start is None else slice_i.start)\n end.append(shape[i] if slice_i.stop is None else slice_i.stop)\n oshape.append(end[i] - begin[i])\n elif isinstance(slice_i, (NDArray, np.ndarray, list, tuple)):\n raise ValueError(\n \"Combining basic and advanced indexing is not supported \" \\\n \"yet. Indices must be all NDArray or all slice, not a \" \\\n \"mix of both.\")\n else:\n raise ValueError(\n \"NDArray does not support slicing with key %s of type %s.\"%(\n str(slice_i), str(type(slice_i))))\n oshape.extend(shape[i+1:])\n if len(oshape) == 0:\n oshape.append(1)\n return op.slice(self, begin, end).reshape(oshape)\n else:\n raise ValueError(\n \"NDArray does not support slicing with key %s of type %s.\"%(\n str(key), str(type(key))))\n\n def _sync_copyfrom(self, source_array):\n \"\"\"Performs a synchronized copy from the `source_array` to the current array.\n This is called through ``x[:] = source_array``, where the `source_array`\n is a `numpy.ndarray` or array-like object.\n This function blocks until all the pending read/write operations with respect\n to the current `NDArray` are finished and carry out the copy operation to the\n current NDArray.\n\n Parameters\n ----------\n source_array : array_like\n The data source we would like to copy from.\n\n Example\n -------\n >>> a = mx.nd.array([1, 2])\n >>> a.asnumpy()\n array([ 1., 2.], dtype=float32)\n >>> a[:] = np.array([3, 4])\n >> a.asnumpy()\n array([ 3., 4.], dtype=float32)\n \"\"\"\n if not isinstance(source_array, np.ndarray):\n try:\n source_array = np.array(source_array, dtype=self.dtype)\n except:\n raise TypeError('array must consist of array-like data,' +\n 'type %s is not supported' % str(type(array)))\n source_array = np.ascontiguousarray(source_array, dtype=self.dtype)\n if source_array.shape != self.shape:\n raise ValueError('Shape inconsistent: expected %s vs got %s'%(\n str(self.shape), str(source_array.shape)))\n check_call(_LIB.MXNDArraySyncCopyFromCPU(\n self.handle,\n source_array.ctypes.data_as(ctypes.c_void_p),\n ctypes.c_size_t(source_array.size)))\n\n def _slice(self, start, stop):\n \"\"\"Returns a sliced NDArray that shares memory with the current one.\n This is called through ``x[start:stop]``.\n\n Parameters\n ----------\n start : int\n Starting inclusive index of slice in the first dim.\n stop : int\n Finishing exclusive index of slice in the first dim.\n\n Returns\n -------\n `NDArray` sharing the memory with the current one sliced from\n start to stop in the first dim.\n\n Examples:\n >>> a = mx.nd.array([[1,2], [3, 4], [5, 6], [7, 8]])\n >>> a[1:2].asnumpy()\n array([[ 3., 4.]], dtype=float32)\n >>> a[1:1].asnumpy()\n array([], shape=(0, 2), dtype=float32)\n \"\"\"\n handle = NDArrayHandle()\n if start is None:\n start = mx_uint(0)\n elif start < 0:\n length = self.shape[0]\n start += length\n assert start >= 0, \"Slicing start %d exceeds limit of %d\"%(start-length, length)\n start = mx_uint(start)\n else:\n start = mx_uint(start)\n if stop is None:\n stop = mx_uint(self.shape[0])\n elif stop < 0:\n length = self.shape[0]\n stop += length\n assert stop >= 0, \"Slicing end %d exceeds limit of %d\"%(stop-length, length)\n stop = mx_uint(stop)\n else:\n stop = mx_uint(stop)\n check_call(_LIB.MXNDArraySlice(\n self.handle, start, stop, ctypes.byref(handle)))\n return NDArray(handle=handle, writable=self.writable)\n\n def _at(self, idx):\n \"\"\"Returns a view of the array sliced at `idx` in the first dim.\n This is called through ``x[idx]``.\n\n Parameters\n ----------\n idx : int\n index for slicing the `NDArray` in the first dim.\n\n Returns\n -------\n NDArray\n `NDArray` sharing the memory with the current one sliced at `idx` in the first dim.\n\n Examples\n --------\n >>> a = mx.nd.array([[1,2], [3, 4]])\n >>> a[1].asnumpy()\n array([ 3., 4.], dtype=float32)\n >>> b = mx.nd.array([1, 2, 3, 4])\n >>> b[0].asnumpy()\n array([ 1.], dtype=float32)\n \"\"\"\n handle = NDArrayHandle()\n idx = mx_uint(idx)\n check_call(_LIB.MXNDArrayAt(\n self.handle, idx, ctypes.byref(handle)))\n return NDArray(handle=handle, writable=self.writable)\n\n def reshape(self, shape):\n \"\"\"Returns a **view** of this array with a new shape without altering any data.\n\n Parameters\n ----------\n shape : tuple of int\n The new shape should not change the array size, namely\n ``np.prod(new_shape)`` should be equal to ``np.prod(self.shape)``.\n\n One dimension can be -1. In this case, the value is inferred\n from the length of the array and remaining dimensions.\n\n 0 Dimensions in shape will be copied from original shape, i.e.\n if x.shape == (3, 4, 5), x.reshape((0, 20)).shape will be (3, 20).\n\n\n Returns\n -------\n NDArray\n An array with desired shape that shares data with this array.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,6).reshape((2,3))\n >>> x.asnumpy()\n array([[ 0., 1., 2.],\n [ 3., 4., 5.]], dtype=float32)\n >>> y = x.reshape((3,2))\n >>> y.asnumpy()\n array([[ 0., 1.],\n [ 2., 3.],\n [ 4., 5.]], dtype=float32)\n >>> y = x.reshape((3,-1))\n >>> y.asnumpy()\n array([[ 0., 1.],\n [ 2., 3.],\n [ 4., 5.]], dtype=float32)\n >>> y[:] = -1\n >>> x.asnumpy()\n array([[-1., -1., -1.],\n [-1., -1., -1.]], dtype=float32)\n \"\"\"\n handle = NDArrayHandle()\n\n # Actual reshape\n check_call(_LIB.MXNDArrayReshape(self.handle,\n len(shape),\n c_array(ctypes.c_int, shape),\n ctypes.byref(handle)))\n return NDArray(handle=handle, writable=self.writable)\n\n def reshape_like(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`reshape_like`.\n\n The arguments are the same as for :py:func:`reshape_like`, with\n this array as data.\n \"\"\"\n return op.reshape_like(self, *args, **kwargs)\n\n def zeros_like(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`zeros_like`.\n\n The arguments are the same as for :py:func:`zeros_like`, with\n this array as data.\n \"\"\"\n return op.zeros_like(self, *args, **kwargs)\n\n def ones_like(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`ones_like`.\n\n The arguments are the same as for :py:func:`ones_like`, with\n this array as data.\n \"\"\"\n return op.ones_like(self, *args, **kwargs)\n\n def broadcast_axes(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`broadcast_axes`.\n\n The arguments are the same as for :py:func:`broadcast_axes`, with\n this array as data.\n \"\"\"\n return op.broadcast_axes(self, *args, **kwargs)\n\n def repeat(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`repeat`.\n\n The arguments are the same as for :py:func:`repeat`, with\n this array as data.\n \"\"\"\n return op.repeat(self, *args, **kwargs)\n\n def pad(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`pad`.\n\n The arguments are the same as for :py:func:`pad`, with\n this array as data.\n \"\"\"\n return op.pad(self, *args, **kwargs)\n\n def swapaxes(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`swapaxes`.\n\n The arguments are the same as for :py:func:`swapaxes`, with\n this array as data.\n \"\"\"\n return op.swapaxes(self, *args, **kwargs)\n\n def split(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`split`.\n\n The arguments are the same as for :py:func:`split`, with\n this array as data.\n \"\"\"\n return op.split(self, *args, **kwargs)\n\n def slice(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`slice`.\n\n The arguments are the same as for :py:func:`slice`, with\n this array as data.\n \"\"\"\n return op.slice(self, *args, **kwargs)\n\n def slice_axis(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`slice_axis`.\n\n The arguments are the same as for :py:func:`slice_axis`, with\n this array as data.\n \"\"\"\n return op.slice_axis(self, *args, **kwargs)\n\n def take(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`take`.\n\n The arguments are the same as for :py:func:`take`, with\n this array as data.\n \"\"\"\n return op.take(self, *args, **kwargs)\n\n def one_hot(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`one_hot`.\n\n The arguments are the same as for :py:func:`one_hot`, with\n this array as data.\n \"\"\"\n return op.one_hot(self, *args, **kwargs)\n\n def pick(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`pick`.\n\n The arguments are the same as for :py:func:`pick`, with\n this array as data.\n \"\"\"\n return op.pick(self, *args, **kwargs)\n\n def sort(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sort`.\n\n The arguments are the same as for :py:func:`sort`, with\n this array as data.\n \"\"\"\n return op.sort(self, *args, **kwargs)\n\n def topk(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`topk`.\n\n The arguments are the same as for :py:func:`topk`, with\n this array as data.\n \"\"\"\n return op.topk(self, *args, **kwargs)\n\n def argsort(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argsort`.\n\n The arguments are the same as for :py:func:`argsort`, with\n this array as data.\n \"\"\"\n return op.argsort(self, *args, **kwargs)\n\n def argmax(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argmax`.\n\n The arguments are the same as for :py:func:`argmax`, with\n this array as data.\n \"\"\"\n return op.argmax(self, *args, **kwargs)\n\n def argmax_channel(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argmax_channel`.\n\n The arguments are the same as for :py:func:`argmax_channel`, with\n this array as data.\n \"\"\"\n return op.argmax_channel(self, *args, **kwargs)\n\n def argmin(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`argmin`.\n\n The arguments are the same as for :py:func:`argmin`, with\n this array as data.\n \"\"\"\n return op.argmin(self, *args, **kwargs)\n\n def clip(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`clip`.\n\n The arguments are the same as for :py:func:`clip`, with\n this array as data.\n \"\"\"\n return op.clip(self, *args, **kwargs)\n\n def abs(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`abs`.\n\n The arguments are the same as for :py:func:`abs`, with\n this array as data.\n \"\"\"\n return op.abs(self, *args, **kwargs)\n\n def sign(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sign`.\n\n The arguments are the same as for :py:func:`sign`, with\n this array as data.\n \"\"\"\n return op.sign(self, *args, **kwargs)\n\n def flatten(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`flatten`.\n\n The arguments are the same as for :py:func:`flatten`, with\n this array as data.\n \"\"\"\n return op.flatten(self, *args, **kwargs)\n\n def expand_dims(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`expand_dims`.\n\n The arguments are the same as for :py:func:`expand_dims`, with\n this array as data.\n \"\"\"\n return op.expand_dims(self, *args, **kwargs)\n\n def tile(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`tile`.\n\n The arguments are the same as for :py:func:`tile`, with\n this array as data.\n \"\"\"\n return op.tile(self, *args, **kwargs)\n\n def transpose(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`transpose`.\n\n The arguments are the same as for :py:func:`transpose`, with\n this array as data.\n \"\"\"\n return op.transpose(self, *args, **kwargs)\n\n def flip(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`flip`.\n\n The arguments are the same as for :py:func:`flip`, with\n this array as data.\n \"\"\"\n return op.flip(self, *args, **kwargs)\n\n def sum(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sum`.\n\n The arguments are the same as for :py:func:`sum`, with\n this array as data.\n \"\"\"\n return op.sum(self, *args, **kwargs)\n\n def nansum(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`nansum`.\n\n The arguments are the same as for :py:func:`nansum`, with\n this array as data.\n \"\"\"\n return op.nansum(self, *args, **kwargs)\n\n def prod(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`prod`.\n\n The arguments are the same as for :py:func:`prod`, with\n this array as data.\n \"\"\"\n return op.prod(self, *args, **kwargs)\n\n def nanprod(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`nanprod`.\n\n The arguments are the same as for :py:func:`nanprod`, with\n this array as data.\n \"\"\"\n return op.nanprod(self, *args, **kwargs)\n\n def mean(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`mean`.\n\n The arguments are the same as for :py:func:`mean`, with\n this array as data.\n \"\"\"\n return op.mean(self, *args, **kwargs)\n\n def max(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`max`.\n\n The arguments are the same as for :py:func:`max`, with\n this array as data.\n \"\"\"\n return op.max(self, *args, **kwargs)\n\n def min(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`min`.\n\n The arguments are the same as for :py:func:`min`, with\n this array as data.\n \"\"\"\n return op.min(self, *args, **kwargs)\n\n def norm(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`norm`.\n\n The arguments are the same as for :py:func:`norm`, with\n this array as data.\n \"\"\"\n return op.norm(self, *args, **kwargs)\n\n def round(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`round`.\n\n The arguments are the same as for :py:func:`round`, with\n this array as data.\n \"\"\"\n return op.round(self, *args, **kwargs)\n\n def rint(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`rint`.\n\n The arguments are the same as for :py:func:`rint`, with\n this array as data.\n \"\"\"\n return op.rint(self, *args, **kwargs)\n\n def fix(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`fix`.\n\n The arguments are the same as for :py:func:`fix`, with\n this array as data.\n \"\"\"\n return op.fix(self, *args, **kwargs)\n\n def floor(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`floor`.\n\n The arguments are the same as for :py:func:`floor`, with\n this array as data.\n \"\"\"\n return op.floor(self, *args, **kwargs)\n\n def ceil(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`ceil`.\n\n The arguments are the same as for :py:func:`ceil`, with\n this array as data.\n \"\"\"\n return op.ceil(self, *args, **kwargs)\n\n def trunc(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`trunc`.\n\n The arguments are the same as for :py:func:`trunc`, with\n this array as data.\n \"\"\"\n return op.trunc(self, *args, **kwargs)\n\n def sin(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sin`.\n\n The arguments are the same as for :py:func:`sin`, with\n this array as data.\n \"\"\"\n return op.sin(self, *args, **kwargs)\n\n def cos(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`cos`.\n\n The arguments are the same as for :py:func:`cos`, with\n this array as data.\n \"\"\"\n return op.cos(self, *args, **kwargs)\n\n def tan(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`tan`.\n\n The arguments are the same as for :py:func:`tan`, with\n this array as data.\n \"\"\"\n return op.tan(self, *args, **kwargs)\n\n def arcsin(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arcsin`.\n\n The arguments are the same as for :py:func:`arcsin`, with\n this array as data.\n \"\"\"\n return op.arcsin(self, *args, **kwargs)\n\n def arccos(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arccos`.\n\n The arguments are the same as for :py:func:`arccos`, with\n this array as data.\n \"\"\"\n return op.arccos(self, *args, **kwargs)\n\n def arctan(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arctan`.\n\n The arguments are the same as for :py:func:`arctan`, with\n this array as data.\n \"\"\"\n return op.arctan(self, *args, **kwargs)\n\n def degrees(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`degrees`.\n\n The arguments are the same as for :py:func:`degrees`, with\n this array as data.\n \"\"\"\n return op.degrees(self, *args, **kwargs)\n\n def radians(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`radians`.\n\n The arguments are the same as for :py:func:`radians`, with\n this array as data.\n \"\"\"\n return op.radians(self, *args, **kwargs)\n\n def sinh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sinh`.\n\n The arguments are the same as for :py:func:`sinh`, with\n this array as data.\n \"\"\"\n return op.sinh(self, *args, **kwargs)\n\n def cosh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`cosh`.\n\n The arguments are the same as for :py:func:`cosh`, with\n this array as data.\n \"\"\"\n return op.cosh(self, *args, **kwargs)\n\n def tanh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`tanh`.\n\n The arguments are the same as for :py:func:`tanh`, with\n this array as data.\n \"\"\"\n return op.tanh(self, *args, **kwargs)\n\n def arcsinh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arcsinh`.\n\n The arguments are the same as for :py:func:`arcsinh`, with\n this array as data.\n \"\"\"\n return op.arcsinh(self, *args, **kwargs)\n\n def arccosh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arccosh`.\n\n The arguments are the same as for :py:func:`arccosh`, with\n this array as data.\n \"\"\"\n return op.arccosh(self, *args, **kwargs)\n\n def arctanh(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`arctanh`.\n\n The arguments are the same as for :py:func:`arctanh`, with\n this array as data.\n \"\"\"\n return op.arctanh(self, *args, **kwargs)\n\n def exp(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`exp`.\n\n The arguments are the same as for :py:func:`exp`, with\n this array as data.\n \"\"\"\n return op.exp(self, *args, **kwargs)\n\n def expm1(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`expm1`.\n\n The arguments are the same as for :py:func:`expm1`, with\n this array as data.\n \"\"\"\n return op.expm1(self, *args, **kwargs)\n\n def log(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log`.\n\n The arguments are the same as for :py:func:`log`, with\n this array as data.\n \"\"\"\n return op.log(self, *args, **kwargs)\n\n def log10(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log10`.\n\n The arguments are the same as for :py:func:`log10`, with\n this array as data.\n \"\"\"\n return op.log10(self, *args, **kwargs)\n\n def log2(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log2`.\n\n The arguments are the same as for :py:func:`log2`, with\n this array as data.\n \"\"\"\n return op.log2(self, *args, **kwargs)\n\n def log1p(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log1p`.\n\n The arguments are the same as for :py:func:`log1p`, with\n this array as data.\n \"\"\"\n return op.log1p(self, *args, **kwargs)\n\n def sqrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sqrt`.\n\n The arguments are the same as for :py:func:`sqrt`, with\n this array as data.\n \"\"\"\n return op.sqrt(self, *args, **kwargs)\n\n def rsqrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`rsqrt`.\n\n The arguments are the same as for :py:func:`rsqrt`, with\n this array as data.\n \"\"\"\n return op.rsqrt(self, *args, **kwargs)\n\n def cbrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`cbrt`.\n\n The arguments are the same as for :py:func:`cbrt`, with\n this array as data.\n \"\"\"\n return op.cbrt(self, *args, **kwargs)\n\n def rcbrt(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`rcbrt`.\n\n The arguments are the same as for :py:func:`rcbrt`, with\n this array as data.\n \"\"\"\n return op.rcbrt(self, *args, **kwargs)\n\n def square(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`square`.\n\n The arguments are the same as for :py:func:`square`, with\n this array as data.\n \"\"\"\n return op.square(self, *args, **kwargs)\n\n def reciprocal(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`reciprocal`.\n\n The arguments are the same as for :py:func:`reciprocal`, with\n this array as data.\n \"\"\"\n return op.reciprocal(self, *args, **kwargs)\n\n def relu(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`relu`.\n\n The arguments are the same as for :py:func:`relu`, with\n this array as data.\n \"\"\"\n return op.relu(self, *args, **kwargs)\n\n def sigmoid(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`sigmoid`.\n\n The arguments are the same as for :py:func:`sigmoid`, with\n this array as data.\n \"\"\"\n return op.sigmoid(self, *args, **kwargs)\n\n def softmax(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`softmax`.\n\n The arguments are the same as for :py:func:`softmax`, with\n this array as data.\n \"\"\"\n return op.softmax(self, *args, **kwargs)\n\n def log_softmax(self, *args, **kwargs):\n \"\"\"Convenience fluent method for :py:func:`log_softmax`.\n\n The arguments are the same as for :py:func:`log_softmax`, with\n this array as data.\n \"\"\"\n return op.log_softmax(self, *args, **kwargs)\n\n # pylint: disable= undefined-variable\n def broadcast_to(self, shape):\n \"\"\"Broadcasts the input array to a new shape.\n\n Broadcasting is only allowed on axes with size 1. The new shape cannot change\n the number of dimensions.\n For example, you could broadcast from shape (2, 1) to (2, 3), but not from\n shape (2, 3) to (2, 3, 3).\n\n Parameters\n ----------\n shape : tuple of int\n The shape of the desired array.\n\n Returns\n -------\n NDArray\n A NDArray with the desired shape that is not sharing data with this\n array, even if the new shape is the same as ``self.shape``.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,3).reshape((1,3,1))\n >>> x.asnumpy()\n array([[[ 0.],\n [ 1.],\n [ 2.]]], dtype=float32)\n >>> y = x.broadcast_to((2,3,3))\n >>> y.asnumpy()\n array([[[ 0., 0., 0.],\n [ 1., 1., 1.],\n [ 2., 2., 2.]],\n <BLANKLINE>\n [[ 0., 0., 0.],\n [ 1., 1., 1.],\n [ 2., 2., 2.]]], dtype=float32)\n \"\"\"\n cur_shape = self.shape\n err_str = 'operands could not be broadcast together with remapped shapes' \\\n '[original->remapped]: {} and requested shape {}'.format(cur_shape, shape)\n if len(shape) < len(cur_shape):\n raise ValueError(err_str)\n cur_shape = (1,) * (len(shape) - len(cur_shape)) + cur_shape\n cur_shape_arr = np.array(cur_shape)\n broadcasting_axes = np.nonzero(cur_shape_arr != np.array(shape))\n if (cur_shape_arr[broadcasting_axes] != 1).any():\n raise ValueError(err_str)\n if cur_shape != self.shape:\n return op.broadcast_to(self.reshape(cur_shape), shape=shape)\n else:\n return op.broadcast_to(self, shape=tuple(shape))\n # pylint: enable= undefined-variable\n\n def wait_to_read(self):\n \"\"\"Waits until all previous write operations on the current array are finished.\n\n This method guarantees that all previous write operations that pushed\n into the backend engine for execution are actually finished.\n\n Examples\n --------\n >>> import time\n >>> tic = time.time()\n >>> a = mx.nd.ones((1000,1000))\n >>> b = mx.nd.dot(a, a)\n >>> print(time.time() - tic) # doctest: +SKIP\n 0.003854036331176758\n >>> b.wait_to_read()\n >>> print(time.time() - tic) # doctest: +SKIP\n 0.0893700122833252\n \"\"\"\n check_call(_LIB.MXNDArrayWaitToRead(self.handle))\n\n @property\n def ndim(self):\n \"\"\"Returns the number of dimensions of this array\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.ndim\n 1\n >>> x = mx.nd.array([[1, 2], [3, 4]])\n >>> x.ndim\n 2\n \"\"\"\n return len(self.shape)\n\n @property\n def shape(self):\n \"\"\"Tuple of array dimensions.\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.shape\n (4L,)\n >>> y = mx.nd.zeros((2, 3, 4))\n >>> y.shape\n (2L, 3L, 4L)\n \"\"\"\n ndim = mx_uint()\n pdata = ctypes.POINTER(mx_uint)()\n check_call(_LIB.MXNDArrayGetShape(\n self.handle, ctypes.byref(ndim), ctypes.byref(pdata)))\n return tuple(pdata[:ndim.value])\n\n\n @property\n def size(self):\n \"\"\"Number of elements in the array.\n\n Equivalent to the product of the array's dimensions.\n\n Examples\n --------\n >>> import numpy as np\n >>> x = mx.nd.zeros((3, 5, 2))\n >>> x.size\n 30\n >>> np.prod(x.shape)\n 30\n \"\"\"\n size = 1\n for i in self.shape:\n size *= i\n return size\n\n @property\n def context(self):\n \"\"\"Device context of the array.\n\n Examples\n --------\n >>> x = mx.nd.array([1, 2, 3, 4])\n >>> x.context\n cpu(0)\n >>> type(x.context)\n <class 'mxnet.context.Context'>\n >>> y = mx.nd.zeros((2,3), mx.gpu(0))\n >>> y.context\n gpu(0)\n \"\"\"\n dev_typeid = ctypes.c_int()\n dev_id = ctypes.c_int()\n check_call(_LIB.MXNDArrayGetContext(\n self.handle, ctypes.byref(dev_typeid), ctypes.byref(dev_id)))\n return Context(Context.devtype2str[dev_typeid.value], dev_id.value)\n\n @property\n def dtype(self):\n \"\"\"Data-type of the array's elements.\n\n Returns\n -------\n numpy.dtype\n This NDArray's data type.\n\n Examples\n --------\n >>> x = mx.nd.zeros((2,3))\n >>> x.dtype\n <type 'numpy.float32'>\n >>> y = mx.nd.zeros((2,3), dtype='int32')\n >>> y.dtype\n <type 'numpy.int32'>\n \"\"\"\n mx_dtype = ctypes.c_int()\n check_call(_LIB.MXNDArrayGetDType(\n self.handle, ctypes.byref(mx_dtype)))\n return _DTYPE_MX_TO_NP[mx_dtype.value]\n\n @property\n def stype(self):\n \"\"\"Storage-type of the array.\n \"\"\"\n return _STORAGE_TYPE_ID_TO_STR[_storage_type(self.handle)]\n\n @property\n # pylint: disable= invalid-name, undefined-variable\n def T(self):\n \"\"\"Returns a copy of the array with axes transposed.\n\n Equivalent to ``mx.nd.transpose(self)`` except that\n self is returned if ``self.ndim < 2``.\n\n Unlike ``numpy.ndarray.T``, this function returns a copy\n rather than a view of the array unless ``self.ndim < 2``.\n\n Examples\n --------\n >>> x = mx.nd.arange(0,6).reshape((2,3))\n >>> x.asnumpy()\n array([[ 0., 1., 2.],\n [ 3., 4., 5.]], dtype=float32)\n >>> x.T.asnumpy()\n array([[ 0., 3.],\n [ 1., 4.],\n [ 2., 5.]], dtype=float32)\n\n \"\"\"\n if len(self.shape) < 2:\n return self\n return op.transpose(self)\n # pylint: enable= invalid-name, undefined-variable\n\n @property\n def _fresh_grad(self):\n \"\"\"Whether this array's corresponding gradient array\n (registered via `autograd.mark_variables`) has been\n updated by `autograd.backward` since last reset.\n\n `_fresh_grad` need to be manually set to False\n after consuming gradient (usually after updating this\n array).\n \"\"\"\n out = ctypes.c_int()\n check_call(_LIB.MXNDArrayGetGradState(self.handle, ctypes.byref(out)))\n return out.value\n\n @_fresh_grad.setter\n def _fresh_grad(self, state):\n check_call(_LIB.MXNDArraySetGradState(self.handle, ctypes.c_int(state)))\n\n def asnumpy(self):\n \"\"\"Returns a ``numpy.ndarray`` object with value copied from this array.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = x.asnumpy()\n >>> type(y)\n <type 'numpy.ndarray'>\n >>> y\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> z = mx.nd.ones((2,3), dtype='int32')\n >>> z.asnumpy()\n array([[1, 1, 1],\n [1, 1, 1]], dtype=int32)\n \"\"\"\n data = np.empty(self.shape, dtype=self.dtype)\n check_call(_LIB.MXNDArraySyncCopyToCPU(\n self.handle,\n data.ctypes.data_as(ctypes.c_void_p),\n ctypes.c_size_t(data.size)))\n return data\n\n def asscalar(self):\n \"\"\"Returns a scalar whose value is copied from this array.\n\n This function is equivalent to ``self.asnumpy()[0]``. This NDArray must have shape (1,).\n\n Examples\n --------\n >>> x = mx.nd.ones((1,), dtype='int32')\n >>> x.asscalar()\n 1\n >>> type(x.asscalar())\n <type 'numpy.int32'>\n \"\"\"\n if self.shape != (1,):\n raise ValueError(\"The current array is not a scalar\")\n return self.asnumpy()[0]\n\n def astype(self, dtype):\n \"\"\"Returns a copy of the array after casting to a specified type.\n\n Parameters\n ----------\n dtype : numpy.dtype or str\n The type of the returned array.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The copied array after casting to the specified type.\n\n Examples\n --------\n >>> x = mx.nd.zeros((2,3), dtype='float32')\n >>> y = x.astype('int32')\n >>> y.dtype\n <type 'numpy.int32'>\n \"\"\"\n res = empty(self.shape, ctx=self.context, dtype=dtype)\n self.copyto(res)\n return res\n\n def copyto(self, other):\n \"\"\"Copies the value of this array to another array.\n\n If ``other`` is a ``NDArray`` object, then ``other.shape`` and\n ``self.shape`` should be the same. This function copies the value from\n ``self`` to ``other``.\n\n If ``other`` is a context, a new ``NDArray`` will be first created on\n the target context, and the value of ``self`` is copied.\n\n Parameters\n ----------\n other : NDArray or Context\n The destination array or context.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The copied array. If ``other`` is an ``NDArray``, then the return value\n and ``other`` will point to the same ``NDArray``.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.zeros((2,3), mx.gpu(0))\n >>> z = x.copyto(y)\n >>> z is y\n True\n >>> y.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.copyto(mx.gpu(0))\n <NDArray 2x3 @gpu(0)>\n\n \"\"\"\n if isinstance(other, NDArray):\n if other.handle is self.handle:\n warnings.warn('You are attempting to copy an array to itself', RuntimeWarning)\n return\n return _internal._copyto(self, out=other)\n elif isinstance(other, Context):\n hret = NDArray(_new_alloc_handle(self.shape, other, True, self.dtype))\n return _internal._copyto(self, out=hret)\n else:\n raise TypeError('copyto does not support type ' + str(type(other)))\n\n def copy(self):\n \"\"\"Makes a copy of this ``NDArray``, keeping the same context.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The copied array\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = x.copy()\n >>> y.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n \"\"\"\n return self.copyto(self.context)\n\n def as_in_context(self, context):\n \"\"\"Returns an array on the target device with the same value as this array.\n\n If the target context is the same as ``self.context``, then ``self`` is\n returned. Otherwise, a copy is made.\n\n Parameters\n ----------\n context : Context\n The target context.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n The target array.\n\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = x.as_in_context(mx.cpu())\n >>> y is x\n True\n >>> z = x.as_in_context(mx.gpu(0))\n >>> z is x\n False\n \"\"\"\n if self.context == context:\n return self\n return self.copyto(context)\n\n def attach_grad(self, grad_req='write', stype=None):\n \"\"\"Attach a gradient buffer to this NDArray, so that `backward`\n can compute gradient with respect to it.\n\n Parameters\n ----------\n grad_req : {'write', 'add', 'null'}\n How gradient will be accumulated.\n - 'write': gradient will be overwritten on every backward.\n - 'add': gradient will be added to existing value on every backward.\n - 'null': do not compute gradient for this NDArray.\n stype : str, optional\n The storage type of the gradient array. Defaults to the same stype of this NDArray.\n \"\"\"\n from . import zeros as _zeros\n if stype is not None:\n grad = _zeros(self.shape, stype=stype)\n else:\n grad = op.zeros_like(self) # pylint: disable=undefined-variable\n grad_req = _GRAD_REQ_MAP[grad_req]\n check_call(_LIB.MXAutogradMarkVariables(\n 1, ctypes.pointer(self.handle),\n ctypes.pointer(mx_uint(grad_req)),\n ctypes.pointer(grad.handle)))\n\n @property\n def grad(self):\n \"\"\"Returns gradient buffer attached to this NDArray.\"\"\"\n from . import _ndarray_cls\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayGetGrad(self.handle, ctypes.byref(hdl)))\n if hdl.value is None:\n return None\n return _ndarray_cls(hdl)\n\n def detach(self):\n \"\"\"Returns a new NDArray, detached from the current graph.\"\"\"\n from . import _ndarray_cls\n hdl = NDArrayHandle()\n check_call(_LIB.MXNDArrayDetach(self.handle, ctypes.byref(hdl)))\n return _ndarray_cls(hdl)\n\n def backward(self, out_grad=None, retain_graph=False, train_mode=True):\n \"\"\"Compute the gradients of this NDArray w.r.t variables.\n\n Parameters\n ----------\n out_grad : NDArray, optional\n Gradient with respect to head.\n retain_graph : bool, optional\n Whether to retain the computaion graph for another backward\n pass on the same graph. By default the computaion history\n is cleared.\n train_mode : bool, optional\n Whether to compute gradient for training or inference.\n \"\"\"\n if out_grad is None:\n ograd_handles = [NDArrayHandle(0)]\n else:\n ograd_handles = [out_grad.handle]\n\n check_call(_LIB.MXAutogradBackwardEx(\n 1, c_array(NDArrayHandle, [self.handle]),\n c_array(NDArrayHandle, ograd_handles),\n 0,\n ctypes.c_void_p(0),\n ctypes.c_int(retain_graph),\n ctypes.c_int(0),\n ctypes.c_int(train_mode),\n ctypes.c_void_p(0),\n ctypes.c_void_p(0)))\n\n def tostype(self, stype):\n \"\"\"Return a copy of the array with chosen storage type.\n\n See Also\n ----------\n :meth:`mxnet.ndarray.cast_storage`.\n\n Returns\n -------\n NDArray, CSRNDArray or RowSparseNDArray\n A copy of the array with the chosen storage stype\n \"\"\"\n return op.cast_storage(self, stype=stype)\n\n\ndef onehot_encode(indices, out):\n \"\"\"One-hot encoding indices into matrix out.\n\n .. note:: `onehot_encode` is deprecated. Use `one_hot` instead.\n\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _internal._onehot_encode(indices, out, out=out)\n # pylint: enable= no-member, protected-access\n\n\ndef ones(shape, ctx=None, dtype=None, **kwargs):\n \"\"\"Returns a new array filled with all ones, with the given shape and type.\n\n Parameters\n ----------\n shape : int or tuple of int or list of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context.\n Defaults to the current default context (``mxnet.Context.default_ctx``).\n dtype : str or numpy.dtype, optional\n An optional value type (default is `float32`).\n out : NDArray, optional\n The output NDArray (default is `None`).\n\n Returns\n -------\n NDArray\n A new array of the specified shape filled with all ones.\n\n Examples\n --------\n >>> mx.nd.ones(1).asnumpy()\n array([ 1.], dtype=float32)\n >>> mx.nd.ones((1,2), mx.gpu(0))\n <NDArray 1x2 @gpu(0)>\n >>> mx.nd.ones((1,2), dtype='float16').asnumpy()\n array([[ 1., 1.]], dtype=float16)\n \"\"\"\n # pylint: disable= unused-argument\n if ctx is None:\n ctx = Context.default_ctx\n dtype = mx_real_t if dtype is None else dtype\n # pylint: disable= no-member, protected-access\n return _internal._ones(shape=shape, ctx=ctx, dtype=dtype, **kwargs)\n # pylint: enable= no-member, protected-access\n\n\ndef full(shape, val, ctx=None, dtype=mx_real_t, out=None):\n \"\"\"Returns a new array of given shape and type, filled with the given value `val`.\n\n Parameters\n --------\n shape : int or tuple of int\n The shape of the new array.\n val : scalar\n Fill value.\n ctx : Context, optional\n Device context (default is the current default context).\n dtype : `str` or `numpy.dtype`, optional\n The data type of the returned `NDArray`. The default datatype is `float32`.\n out : NDArray, optional\n The output NDArray (default is `None`).\n\n Returns\n -------\n NDArray\n `NDArray` filled with `val`, with the given shape, ctx, and dtype.\n\n Examples\n --------\n >>> mx.nd.full(1, 2.0).asnumpy()\n array([ 2.], dtype=float32)\n >>> mx.nd.full((1, 2), 2.0, mx.gpu(0))\n <NDArray 1x2 @gpu(0)>\n >>> mx.nd.full((1, 2), 2.0, dtype='float16').asnumpy()\n array([[ 2., 2.]], dtype=float16)\n \"\"\"\n out = empty(shape, ctx, dtype) if out is None else out\n out[:] = val\n return out\n\n\ndef array(source_array, ctx=None, dtype=None):\n \"\"\"Creates an array from any object exposing the array interface.\n\n Parameters\n ----------\n source_array : array_like\n An object exposing the array interface, an object whose `__array__`\n method returns an array, or any (nested) sequence.\n ctx : Context, optional\n Device context (default is the current default context).\n dtype : str or numpy.dtype, optional\n The data type of the output array. The default dtype is ``source_array.dtype``\n if `source_array` is an `NDArray`, `float32` otherwise.\n\n Returns\n -------\n NDArray\n An `NDArray` with the same contents as the `source_array`.\n \"\"\"\n if isinstance(source_array, NDArray):\n dtype = source_array.dtype if dtype is None else dtype\n else:\n dtype = mx_real_t if dtype is None else dtype\n if not isinstance(source_array, np.ndarray):\n try:\n source_array = np.array(source_array, dtype=dtype)\n except:\n raise TypeError('source_array must be array like object')\n arr = empty(source_array.shape, ctx, dtype)\n arr[:] = source_array\n return arr\n\n\ndef moveaxis(tensor, source, destination):\n \"\"\"Moves the `source` axis into the `destination` position\n while leaving the other axes in their original order\n\n Parameters\n ----------\n tensor : mx.nd.array\n The array which axes should be reordered\n source : int\n Original position of the axes to move.\n destination : int\n Destination position for each of the original axes.\n\n Returns\n -------\n result : mx.nd.array\n Array with moved axes.\n\n Examples\n --------\n >>> X = mx.nd.array([[1, 2, 3], [4, 5, 6]])\n >>> mx.nd.moveaxis(X, 0, 1).shape\n (3L, 2L)\n \"\"\"\n axes = list(range(tensor.ndim))\n try:\n axes.pop(source)\n except IndexError:\n raise ValueError('Source should verify 0 <= source < tensor.ndim'\n 'Got %d' % source)\n try:\n axes.insert(destination, source)\n except IndexError:\n raise ValueError('Destination should verify 0 <= destination < tensor.ndim'\n 'Got %d' % destination)\n return op.transpose(tensor, axes)\n\n\n# pylint: disable= no-member, protected-access, too-many-arguments, redefined-outer-name\ndef arange(start, stop=None, step=1.0, repeat=1, ctx=None, dtype=mx_real_t):\n \"\"\"Returns evenly spaced values within a given interval.\n\n Values are generated within the half-open interval [`start`, `stop`). In other\n words, the interval includes `start` but excludes `stop`. The function is\n similar to the built-in Python function `range` and to `numpy.arange`,\n but returns an `NDArray`.\n\n Parameters\n ----------\n start : number, optional\n Start of interval. The default start value is 0.\n stop : number\n End of interval.\n step : number, optional\n Spacing between values. The default step size is 1.\n repeat : int, optional\n Number of times to repeat each element. The default repeat count is 1.\n ctx : Context, optional\n Device context. Default context is the current default context.\n dtype : str or numpy.dtype, optional\n The data type of the `NDArray`. The default datatype is `np.float32`.\n\n Returns\n -------\n NDArray\n `NDArray` of evenly spaced values in the specified range.\n\n Examples\n --------\n >>> mx.nd.arange(3).asnumpy()\n array([ 0., 1., 2.], dtype=float32)\n >>> mx.nd.arange(2, 6).asnumpy()\n array([ 2., 3., 4., 5.], dtype=float32)\n >>> mx.nd.arange(2, 6, step=2).asnumpy()\n array([ 2., 4.], dtype=float32)\n >>> mx.nd.arange(2, 6, step=1.5, repeat=2).asnumpy()\n array([ 2. , 2. , 3.5, 3.5, 5. , 5. ], dtype=float32)\n >>> mx.nd.arange(2, 6, step=2, repeat=3, dtype='int32').asnumpy()\n array([2, 2, 2, 4, 4, 4], dtype=int32)\n \"\"\"\n if ctx is None:\n ctx = Context.default_ctx\n return _internal._arange(start=start, stop=stop, step=step, repeat=repeat,\n dtype=dtype, ctx=str(ctx))\n# pylint: enable= no-member, protected-access, too-many-arguments\n\n\n#pylint: disable= too-many-arguments, no-member, protected-access\ndef _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None):\n \"\"\" Helper function for element-wise operation.\n The function will perform numpy-like broadcasting if needed and call different functions.\n\n Parameters\n --------\n lhs : NDArray or numeric value\n Left-hand side operand.\n\n rhs : NDArray or numeric value\n Right-hand operand,\n\n fn_array : function\n Function to be called if both lhs and rhs are of ``NDArray`` type.\n\n fn_scalar : function\n Function to be called if both lhs and rhs are numeric values.\n\n lfn_scalar : function\n Function to be called if lhs is ``NDArray`` while rhs is numeric value\n\n rfn_scalar : function\n Function to be called if lhs is numeric value while rhs is ``NDArray``;\n if none is provided, then the function is commutative, so rfn_scalar is equal to lfn_scalar\n\n Returns\n --------\n NDArray\n result array\n \"\"\"\n if isinstance(lhs, numeric_types):\n if isinstance(rhs, numeric_types):\n return fn_scalar(lhs, rhs)\n else:\n if rfn_scalar is None:\n # commutative function\n return lfn_scalar(rhs, float(lhs))\n else:\n return rfn_scalar(rhs, float(lhs))\n elif isinstance(rhs, numeric_types):\n return lfn_scalar(lhs, float(rhs))\n elif isinstance(rhs, NDArray):\n return fn_array(lhs, rhs)\n else:\n raise TypeError('type %s not supported' % str(type(rhs)))\n#pylint: enable= too-many-arguments, no-member, protected-access\n\n\ndef add(lhs, rhs):\n \"\"\"Returns element-wise sum of the input arrays with broadcasting.\n\n Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and\n ``mx.nd.broadcast_plus(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be added.\n rhs : scalar or array\n Second array to be added.\n If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise sum of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x+2).asnumpy()\n array([[ 3., 3., 3.],\n [ 3., 3., 3.]], dtype=float32)\n >>> (x+y).asnumpy()\n array([[ 1., 1., 1.],\n [ 2., 2., 2.]], dtype=float32)\n >>> mx.nd.add(x,y).asnumpy()\n array([[ 1., 1., 1.],\n [ 2., 2., 2.]], dtype=float32)\n >>> (z + y).asnumpy()\n array([[ 0., 1.],\n [ 1., 2.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_add,\n operator.add,\n _internal._plus_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef subtract(lhs, rhs):\n \"\"\"Returns element-wise difference of the input arrays with broadcasting.\n\n Equivalent to ``lhs - rhs``, ``mx.nd.broadcast_sub(lhs, rhs)`` and\n ``mx.nd.broadcast_minus(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be subtracted.\n rhs : scalar or array\n Second array to be subtracted.\n If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise difference of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x-2).asnumpy()\n array([[-1., -1., -1.],\n [-1., -1., -1.]], dtype=float32)\n >>> (x-y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.subtract(x,y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z-y).asnumpy()\n array([[ 0., 1.],\n [-1., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_sub,\n operator.sub,\n _internal._minus_scalar,\n _internal._rminus_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef multiply(lhs, rhs):\n \"\"\"Returns element-wise product of the input arrays with broadcasting.\n\n Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be multiplied.\n rhs : scalar or array\n Second array to be multiplied.\n If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise multiplication of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x*2).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> (x*y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.multiply(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z*y).asnumpy()\n array([[ 0., 0.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_mul,\n operator.mul,\n _internal._mul_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef divide(lhs, rhs):\n \"\"\"Returns element-wise division of the input arrays with broadcasting.\n\n Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array in division.\n rhs : scalar or array\n Second array in division.\n The arrays to be divided. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise division of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))*6\n >>> y = mx.nd.ones((2,1))*2\n >>> x.asnumpy()\n array([[ 6., 6., 6.],\n [ 6., 6., 6.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 2.],\n [ 2.]], dtype=float32)\n >>> x/2\n <NDArray 2x3 @cpu(0)>\n >>> (x/3).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> (x/y).asnumpy()\n array([[ 3., 3., 3.],\n [ 3., 3., 3.]], dtype=float32)\n >>> mx.nd.divide(x,y).asnumpy()\n array([[ 3., 3., 3.],\n [ 3., 3., 3.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_div,\n operator.truediv,\n _internal._div_scalar,\n _internal._rdiv_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef modulo(lhs, rhs):\n \"\"\"Returns element-wise modulo of the input arrays with broadcasting.\n\n Equivalent to ``lhs % rhs`` and ``mx.nd.broadcast_mod(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array in modulo.\n rhs : scalar or array\n Second array in modulo.\n The arrays to be taken modulo. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise modulo of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))*6\n >>> y = mx.nd.ones((2,1))*4\n >>> x.asnumpy()\n array([[ 6., 6., 6.],\n [ 6., 6., 6.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 4.],\n [ 4.]], dtype=float32)\n >>> x%5\n <NDArray 2x3 @cpu(0)>\n >>> (x%5).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x%y).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> mx.nd.modulo(x,y).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_mod,\n operator.mod,\n _internal._mod_scalar,\n _internal._rmod_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef power(base, exp):\n \"\"\"Returns result of first array elements raised to powers from second array, element-wise\n with broadcasting.\n\n Equivalent to ``base ** exp`` and ``mx.nd.broadcast_power(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n base : scalar or NDArray\n The base array\n exp : scalar or NDArray\n The exponent array. If ``base.shape != exp.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n --------\n NDArray\n The bases in x raised to the exponents in y.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))*2\n >>> y = mx.nd.arange(1,3).reshape((2,1))\n >>> z = mx.nd.arange(1,3).reshape((2,1))\n >>> x.asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 1.],\n [ 2.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 1.],\n [ 2.]], dtype=float32)\n >>> (x**2).asnumpy()\n array([[ 4., 4., 4.],\n [ 4., 4., 4.]], dtype=float32)\n >>> (x**y).asnumpy()\n array([[ 2., 2., 2.],\n [ 4., 4., 4.]], dtype=float32)\n >>> mx.nd.power(x,y).asnumpy()\n array([[ 2., 2., 2.],\n [ 4., 4., 4.]], dtype=float32)\n >>> (z**y).asnumpy()\n array([[ 1.],\n [ 4.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n base,\n exp,\n op.broadcast_power,\n operator.pow,\n _internal._power_scalar,\n _internal._rpower_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef maximum(lhs, rhs):\n \"\"\"Returns element-wise maximum of the input arrays with broadcasting.\n\n Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise maximum of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> mx.nd.maximum(x, 2).asnumpy()\n array([[ 2., 2., 2.],\n [ 2., 2., 2.]], dtype=float32)\n >>> mx.nd.maximum(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.maximum(y, z).asnumpy()\n array([[ 0., 1.],\n [ 1., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_maximum,\n lambda x, y: x if x > y else y,\n _internal._maximum_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef minimum(lhs, rhs):\n \"\"\"Returns element-wise minimum of the input arrays with broadcasting.\n\n Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n The element-wise minimum of the input arrays.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> mx.nd.minimum(x, 2).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.minimum(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.minimum(z, y).asnumpy()\n array([[ 0., 0.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_minimum,\n lambda x, y: x if x < y else y,\n _internal._minimum_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **equal to** (==) comparison operation with\n broadcasting.\n\n For each element in input arrays, return 1(true) if corresponding elements are same,\n otherwise return 0(false).\n\n Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x == 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x == y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.equal(x,y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z == y).asnumpy()\n array([[ 1., 0.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_equal,\n lambda x, y: 1 if x == y else 0,\n _internal._equal_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef not_equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **not equal to** (!=) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if corresponding elements are different,\n otherwise return 0(false).\n\n Equivalent to ``lhs != rhs`` and ``mx.nd.broadcast_not_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (z == y).asnumpy()\n array([[ 1., 0.],\n [ 0., 1.]], dtype=float32)\n >>> (x != 1).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (x != y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.not_equal(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z != y).asnumpy()\n array([[ 0., 1.],\n [ 1., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_not_equal,\n lambda x, y: 1 if x != y else 0,\n _internal._not_equal_scalar,\n None)\n # pylint: enable= no-member, protected-access\n\n\ndef greater(lhs, rhs):\n \"\"\"Returns the result of element-wise **greater than** (>) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are greater than rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs > rhs`` and ``mx.nd.broadcast_greater(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x > 1).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (x > y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.greater(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z > y).asnumpy()\n array([[ 0., 1.],\n [ 0., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_greater,\n lambda x, y: 1 if x > y else 0,\n _internal._greater_scalar,\n _internal._lesser_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef greater_equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **greater than or equal to** (>=) comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs >= rhs`` and ``mx.nd.broadcast_greater_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x >= 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x >= y).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.greater_equal(x, y).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z >= y).asnumpy()\n array([[ 1., 1.],\n [ 0., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_greater_equal,\n lambda x, y: 1 if x >= y else 0,\n _internal._greater_equal_scalar,\n _internal._lesser_equal_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef lesser(lhs, rhs):\n \"\"\"Returns the result of element-wise **lesser than** (<) comparison operation\n with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are less than rhs,\n otherwise return 0(false).\n\n Equivalent to ``lhs < rhs`` and ``mx.nd.broadcast_lesser(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x < 1).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (x < y).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> mx.nd.lesser(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n >>> (z < y).asnumpy()\n array([[ 0., 0.],\n [ 1., 0.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_lesser,\n lambda x, y: 1 if x < y else 0,\n _internal._lesser_scalar,\n _internal._greater_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef lesser_equal(lhs, rhs):\n \"\"\"Returns the result of element-wise **lesser than or equal to** (<=) comparison\n operation with broadcasting.\n\n For each element in input arrays, return 1(true) if lhs elements are\n lesser than equal to rhs, otherwise return 0(false).\n\n Equivalent to ``lhs <= rhs`` and ``mx.nd.broadcast_lesser_equal(lhs, rhs)``.\n\n .. note::\n\n If the corresponding dimensions of two arrays have the same size or one of them has size 1,\n then the arrays are broadcastable to a common shape.\n\n Parameters\n ----------\n lhs : scalar or array\n First array to be compared.\n rhs : scalar or array\n Second array to be compared. If ``lhs.shape != rhs.shape``, they must be\n broadcastable to a common shape.\n\n Returns\n -------\n NDArray\n Output array of boolean values.\n\n Examples\n --------\n >>> x = mx.nd.ones((2,3))\n >>> y = mx.nd.arange(2).reshape((2,1))\n >>> z = mx.nd.arange(2).reshape((1,2))\n >>> x.asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> y.asnumpy()\n array([[ 0.],\n [ 1.]], dtype=float32)\n >>> z.asnumpy()\n array([[ 0., 1.]], dtype=float32)\n >>> (x <= 1).asnumpy()\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (x <= y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> mx.nd.lesser_equal(x, y).asnumpy()\n array([[ 0., 0., 0.],\n [ 1., 1., 1.]], dtype=float32)\n >>> (z <= y).asnumpy()\n array([[ 1., 0.],\n [ 1., 1.]], dtype=float32)\n \"\"\"\n # pylint: disable= no-member, protected-access\n return _ufunc_helper(\n lhs,\n rhs,\n op.broadcast_lesser_equal,\n lambda x, y: 1 if x <= y else 0,\n _internal._lesser_equal_scalar,\n _internal._greater_equal_scalar)\n # pylint: enable= no-member, protected-access\n\n\ndef true_divide(lhs, rhs):\n\n \"\"\"This function is similar to :meth:`divide`.\n \"\"\"\n return divide(lhs, rhs)\n\n\ndef concatenate(arrays, axis=0, always_copy=True):\n \"\"\"DEPRECATED, use ``concat`` instead\n\n Parameters\n ----------\n arrays : list of `NDArray`\n Arrays to be concatenate. They must have identical shape except\n the first dimension. They also must have the same data type.\n axis : int\n The axis along which to concatenate.\n always_copy : bool\n Default `True`. When not `True`, if the arrays only contain one\n `NDArray`, that element will be returned directly, avoid copying.\n\n Returns\n -------\n NDArray\n An `NDArray` that lives on the same context as `arrays[0].context`.\n \"\"\"\n assert isinstance(arrays, list)\n assert len(arrays) > 0\n assert isinstance(arrays[0], NDArray)\n\n if not always_copy and len(arrays) == 1:\n return arrays[0]\n\n shape_axis = arrays[0].shape[axis]\n shape_rest1 = arrays[0].shape[0:axis]\n shape_rest2 = arrays[0].shape[axis+1:]\n dtype = arrays[0].dtype\n for arr in arrays[1:]:\n shape_axis += arr.shape[axis]\n assert shape_rest1 == arr.shape[0:axis]\n assert shape_rest2 == arr.shape[axis+1:]\n assert dtype == arr.dtype\n ret_shape = shape_rest1 + (shape_axis,) + shape_rest2\n ret = empty(ret_shape, ctx=arrays[0].context, dtype=dtype)\n\n idx = 0\n begin = [0 for _ in ret_shape]\n end = list(ret_shape)\n for arr in arrays:\n if axis == 0:\n ret[idx:idx+arr.shape[0]] = arr\n else:\n begin[axis] = idx\n end[axis] = idx+arr.shape[axis]\n # pylint: disable=no-member,protected-access\n _internal._crop_assign(ret, arr, out=ret,\n begin=tuple(begin),\n end=tuple(end))\n # pylint: enable=no-member,protected-access\n idx += arr.shape[axis]\n\n return ret\n\n\n# pylint: disable=redefined-outer-name\ndef imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None):\n \"\"\"DEPRECATED, use mx.img instead\n\n Parameters\n ----------\n str_img : str\n Binary image data\n clip_rect : iterable of 4 int\n Clip decoded image to rectangle (x0, y0, x1, y1).\n out : NDArray\n Output buffer. Can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w).\n index : int\n Output decoded image to i-th slice of 4 dimensional buffer.\n channels : int\n Number of channels to output. Decode to grey scale when channels = 1.\n mean : NDArray\n Subtract mean from decode image before outputing.\n \"\"\"\n # pylint: disable= no-member, protected-access, too-many-arguments\n if mean is None:\n mean = NDArray(_new_empty_handle())\n if out is None:\n return _internal._imdecode(mean, index,\n clip_rect[0],\n clip_rect[1],\n clip_rect[2],\n clip_rect[3],\n channels,\n len(str_img),\n str_img=str_img)\n else:\n return _internal._imdecode(mean, index,\n clip_rect[0],\n clip_rect[1],\n clip_rect[2],\n clip_rect[3],\n channels,\n len(str_img),\n str_img=str_img,\n out=out)\n\n\ndef zeros(shape, ctx=None, dtype=None, **kwargs):\n \"\"\"Returns a new array filled with all zeros, with the given shape and type.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context (default is the current default context).\n dtype : str or numpy.dtype, optional\n An optional value type (default is `float32`).\n out : NDArray, optional\n The output NDArray (default is `None`).\n\n Returns\n -------\n NDArray\n A created array\n\n Examples\n --------\n >>> mx.nd.zeros(1).asnumpy()\n array([ 0.], dtype=float32)\n >>> mx.nd.zeros((1,2), mx.gpu(0))\n <NDArray 1x2 @gpu(0)>\n >>> mx.nd.zeros((1,2), mx.gpu(0), 'float16').asnumpy()\n array([[ 0., 0.]], dtype=float16)\n \"\"\"\n # pylint: disable= unused-argument\n if ctx is None:\n ctx = Context.default_ctx\n dtype = mx_real_t if dtype is None else dtype\n # pylint: disable= no-member, protected-access\n return _internal._zeros(shape=shape, ctx=ctx, dtype=dtype, **kwargs)\n # pylint: enable= no-member, protected-access\n\n\ndef empty(shape, ctx=None, dtype=None):\n \"\"\"Returns a new array of given shape and type, without initializing entries.\n\n Parameters\n ----------\n shape : int or tuple of int\n The shape of the empty array.\n ctx : Context, optional\n An optional device context (default is the current default context).\n dtype : str or numpy.dtype, optional\n An optional value type (default is `float32`).\n\n Returns\n -------\n NDArray\n A created array.\n\n \"\"\"\n if isinstance(shape, int):\n shape = (shape, )\n if ctx is None:\n ctx = Context.default_ctx\n if dtype is None:\n dtype = mx_real_t\n return NDArray(handle=_new_alloc_handle(shape, ctx, False, dtype))\n"
] | [
[
"numpy.ascontiguousarray",
"numpy.dtype",
"numpy.array",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Gustavo6046/polydung | [
"e8626c67b0f59e00a2400b5a5c644e3f6b925e00"
] | [
"pdserver/objects.py"
] | [
"import base64\nimport random\nimport string\nimport netbyte\nimport numpy as np\n\ntry:\n import simplejson as json\n \nexcept ImportError:\n import json\n \n\nkinds = {}\n\nclass PDObject(object):\n def __init__(self, game, kind, id, pos, properties):\n self.game = game\n self.kind = kind\n self.id = id or ''.join([random.choice(string.ascii_letters + string.digits + \"#$%*\") for _ in range(100)])\n self.pos = np.array(pos)\n self.properties = properties\n \n self.game.handle_object_creation(self)\n \n def __getitem__(self, key): # a shortcut for Netbyte\n return self.properties[key]\n \n def __setitem__(self, key, value): # not only a shortcut for Netbyte\n self.properties[key] = value\n self.game.update_object(self)\n \n def __call__(self, key, **kwargs):\n nbe = netbyte.Netbyte()\n nbe['self'] = self\n nbe['game'] = self.game\n \n for k, v in kwargs.items():\n nbe[k] = v\n \n nbe.execute_instructions(*self.kind.functions[key])\n \n def tick(self, timedelta):\n self('tick', timedelta=timedelta)\n \n def serialize(self):\n return json.dumps({\n \"kind\": self.kind.name,\n 'id': self.id,\n 'pos': self.pos.tolist(),\n \"properties\": self.properties\n })\n\n @classmethod\n def deserialize(cls, game, js):\n data = json.loads(js)\n return cls(game, kinds[data['kind']], data['id'], data['pos'], data['properties'])\n\nclass PDClass(object):\n def __init__(self, game, name, functions=()):\n self.functions = dict(functions)\n self.name = name\n \n kinds[name] = self\n \n nbe = netbyte.Netbyte()\n \n def serializable(self):\n return {\n 'name': self.name,\n 'functions': {k: nbe.dump(v, name=\"{}.{}\".format(self.name, k)) for k, v in self.functions.items()}\n }"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
taesupkim/bmaml | [
"10ef3e5dc288d0d8e18e46bcad99da1e7c114605"
] | [
"utils.py"
] | [
"import os \nimport time \nimport socket\nimport random\nimport tensorflow as tf\n\nfrom tensorflow.contrib.layers.python import layers as tf_layers\nfrom tensorflow.python.platform import flags\n\n# NOTE: this script is based on https://github.com/cbfinn/maml/blob/master/utils.py\n\nFLAGS = flags.FLAGS\n\n## Image helper\ndef get_images(paths, labels, nb_samples=None, shuffle=True):\n if nb_samples is not None:\n sampler = lambda x: random.sample(x, nb_samples)\n else:\n sampler = lambda x: x\n images = [(i, os.path.join(path, image)) \\\n for i, path in zip(labels, paths) \\\n for image in sampler(os.listdir(path))]\n if shuffle:\n random.shuffle(images)\n return images\n\ndef clip_if_not_none(grad, min_value, max_value):\n if grad is None:\n return grad\n return tf.clip_by_value(grad, min_value, max_value)\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\ndef make_logdir(configs, fname_args=[]):\n this_run_str = time.strftime(\"%H%M%S_\") + str(socket.gethostname())\n if is_git_dir():\n this_run_str += '_git' + git_hash_str() # random hash + git hash\n for str_arg in fname_args:\n if str_arg in configs.keys():\n this_run_str += '_' + str_arg.title().replace('_','') + '_' + str(configs[str_arg])\n else:\n raise ValueError('%s in fname_args does not exist in configs' % str_arg)\n this_run_str = this_run_str.replace('/','_')\n #log_dir = os.path.join(configs['log_root_dir'], configs['log_sub_dir'], this_run_str)\n return log_dir\n\ndef experiment_prefix_str(separator=',', hostname=False, git=True):\n this_run_str = time.strftime(\"%y%m%d_%H%M%S\")\n if hostname:\n this_run_str += str(socket.gethostname())\n # NOTE: Unless you can attach your git folder when running borgy, this would fail!\n # Comment out the `is_git_dir` condition and the `str(git_hash_str())` to get this to work\n if git and is_git_dir():\n this_run_str += separator + str(git_hash_str()) # random hash + git hash \n this_run_str = this_run_str.replace('-','')\n return this_run_str\n\ndef experiment_string2(configs, fname_args=[], separator=','):\n this_run_str = ''\n for (org_arg_str, short_arg_str) in fname_args:\n short_arg_str = org_arg_str.title().replace('_','') if short_arg_str is None else short_arg_str\n if org_arg_str in configs.keys():\n this_run_str += separator + short_arg_str + str(configs[org_arg_str]).title().replace('_','')\n else:\n raise ValueError('%s in fname_args doesn not exist in configs' % org_arg_str)\n this_run_str = this_run_str.replace('/', '_')\n return this_run_str\n\ndef experiment_string(configs, fname_args=[], separator=','):\n this_run_str = expr_prefix_str(configs)\n for str_arg in fname_args:\n if str_arg in configs.keys():\n this_run_str += separator + str_arg.title().replace('_','') + '=' + str(configs[str_arg])\n else:\n raise ValueError('%s in fname_args does not exist in configs' % str_arg)\n this_run_str = this_run_str.replace('/','_')\n return this_run_str\n\ndef is_git_dir():\n from subprocess import call, STDOUT\n if call([\"git\", \"branch\"], stderr=STDOUT, stdout=open(os.devnull, 'w')) != 0:\n return False\n else:\n return True\n\ndef git_hash_str(hash_len=7):\n import subprocess\n hash_str = subprocess.check_output(['git','rev-parse','HEAD'])\n return str(hash_str[:hash_len])\n\n"
] | [
[
"tensorflow.clip_by_value"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
ssktotoro/catalyst | [
"2ff687e802250772f8614583af933d6613f87788"
] | [
"catalyst/tests/test_mnist_multioptimizer.py"
] | [
"# flake8: noqa\n\nimport os\nfrom tempfile import TemporaryDirectory\n\nfrom pytest import mark\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader\n\nfrom catalyst import dl, metrics, utils\nfrom catalyst.contrib.datasets import MNIST\nfrom catalyst.data.transforms import ToTensor\nfrom catalyst.settings import IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES, SETTINGS\n\n\nclass CustomRunner(dl.Runner):\n def predict_batch(self, batch):\n # model inference step\n return self.model(batch[0].to(self.device))\n\n def on_loader_start(self, runner):\n super().on_loader_start(runner)\n self.meters = {\n key: metrics.AdditiveValueMetric(compute_on_call=False)\n for key in [\"loss\", \"accuracy01\", \"accuracy03\"]\n }\n\n def handle_batch(self, batch):\n # model train/valid step\n # unpack the batch\n x, y = batch\n # <--- multi-model usage --->\n # run model forward pass\n x_ = self.model[\"encoder\"](x)\n logits = self.model[\"head\"](x_)\n # <--- multi-model usage --->\n # compute the loss\n loss = self.criterion(logits, y)\n # compute other metrics of interest\n accuracy01, accuracy03 = metrics.accuracy(logits, y, topk=(1, 3))\n # log metrics\n self.batch_metrics.update(\n {\"loss\": loss, \"accuracy01\": accuracy01, \"accuracy03\": accuracy03}\n )\n for key in [\"loss\", \"accuracy01\", \"accuracy03\"]:\n self.meters[key].update(self.batch_metrics[key].item(), self.batch_size)\n # run model backward pass\n if self.is_train_loader:\n loss.backward()\n # <--- multi-model/optimizer usage --->\n self.optimizer[\"encoder\"].step()\n self.optimizer[\"head\"].step()\n self.optimizer[\"encoder\"].zero_grad()\n self.optimizer[\"head\"].zero_grad()\n # <--- multi-model/optimizer usage --->\n\n def on_loader_end(self, runner):\n for key in [\"loss\", \"accuracy01\", \"accuracy03\"]:\n self.loader_metrics[key] = self.meters[key].compute()[0]\n super().on_loader_end(runner)\n\n\ndef train_experiment(device, engine=None):\n with TemporaryDirectory() as logdir:\n\n # <--- multi-model/optimizer setup --->\n encoder = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 128))\n head = nn.Linear(128, 10)\n model = {\"encoder\": encoder, \"head\": head}\n optimizer = {\n \"encoder\": optim.Adam(encoder.parameters(), lr=0.02),\n \"head\": optim.Adam(head.parameters(), lr=0.001),\n }\n # <--- multi-model/optimizer setup --->\n criterion = nn.CrossEntropyLoss()\n\n loaders = {\n \"train\": DataLoader(\n MNIST(os.getcwd(), train=True, download=True, transform=ToTensor()), batch_size=32\n ),\n \"valid\": DataLoader(\n MNIST(os.getcwd(), train=False, download=True, transform=ToTensor()), batch_size=32\n ),\n }\n\n runner = CustomRunner()\n # model training\n runner.train(\n engine=engine or dl.DeviceEngine(device),\n model=model,\n criterion=criterion,\n optimizer=optimizer,\n loaders=loaders,\n logdir=logdir,\n num_epochs=1,\n verbose=False,\n valid_loader=\"valid\",\n valid_metric=\"loss\",\n minimize_valid_metric=True,\n )\n\n\n# Torch\ndef test_on_cpu():\n train_experiment(\"cpu\")\n\n\[email protected](not IS_CUDA_AVAILABLE, reason=\"CUDA device is not available\")\ndef test_on_torch_cuda0():\n train_experiment(\"cuda:0\")\n\n\[email protected](\n not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2), reason=\"No CUDA>=2 found\",\n)\ndef test_on_torch_cuda1():\n train_experiment(\"cuda:1\")\n\n\[email protected](\n not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2), reason=\"No CUDA>=2 found\",\n)\ndef test_on_torch_dp():\n train_experiment(None, dl.DataParallelEngine())\n\n\n# @mark.skipif(\n# not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >=2),\n# reason=\"No CUDA>=2 found\",\n# )\n# def test_on_ddp():\n# train_experiment(None, dl.DistributedDataParallelEngine())\n\n# AMP\[email protected](\n not (IS_CUDA_AVAILABLE and SETTINGS.amp_required), reason=\"No CUDA or AMP found\",\n)\ndef test_on_amp():\n train_experiment(None, dl.AMPEngine())\n\n\[email protected](\n not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.amp_required),\n reason=\"No CUDA>=2 or AMP found\",\n)\ndef test_on_amp_dp():\n train_experiment(None, dl.DataParallelAMPEngine())\n\n\n# @mark.skipif(\n# not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.amp_required),\n# reason=\"No CUDA>=2 or AMP found\",\n# )\n# def test_on_amp_ddp():\n# train_experiment(None, dl.DistributedDataParallelAMPEngine())\n\n# APEX\[email protected](\n not (IS_CUDA_AVAILABLE and SETTINGS.apex_required), reason=\"No CUDA or Apex found\",\n)\ndef test_on_apex():\n train_experiment(None, dl.APEXEngine())\n\n\[email protected](\n not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.apex_required),\n reason=\"No CUDA>=2 or Apex found\",\n)\ndef test_on_apex_dp():\n train_experiment(None, dl.DataParallelApexEngine())\n\n\n# @mark.skipif(\n# not (IS_CUDA_AVAILABLE and NUM_CUDA_DEVICES >= 2 and SETTINGS.apex_required),\n# reason=\"No CUDA>=2 or Apex found\",\n# )\n# def test_on_apex_ddp():\n# train_experiment(None, dl.DistributedDataParallelApexEngine())\n"
] | [
[
"torch.nn.Linear",
"torch.nn.CrossEntropyLoss",
"torch.nn.Flatten"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
killdary/genetic_algorithm_route_calculation | [
"f7d9c114d8780bad6124ee61214b7dce0557d312"
] | [
"solution/Make_map.py"
] | [
"from GA_TOPMD import GaTopMd\nfrom PSO_TOP import PSO\nimport gc\nfrom datetime import datetime\nimport os\nimport re\nimport numpy as np\n\npaths = [\n\n 'GATOPMD/mapas/artigo/mapa_4r_40_1d.txt',\n\n]\n\nprizes = [\n 'GATOPMD/mapas/artigo/premio_4r_40_1d.txt',\n]\n\nsize_population = [.1,\n ]\n\ncosts = [\n [20, 23, 25, 30],\n]\n\npoints_init = [\n [0, 0, 0, 0],\n\n]\n\npoints_end = [\n [0, 0, 0, 0],\n]\n\ndeposits = [\n [0, 1, 2, 3, 4],\n]\nnumber_executions = 30\n\nmain_path = './GATOPMD/Result/'\ndata = datetime.now()\nexecucao = str(data.strftime((\"%d-%m-%Y_%H-%M-%S_execucao\")))\n\nresult_folder = main_path + '' + 'grafico'\n\nos.mkdir(result_folder)\n\nprint(os.getcwd())\n\nfor i in range(len(paths)):\n name = 'path_' + str(i + 1)\n path_current = paths[i]\n prize_current = prizes[i]\n\n cost_current = costs[i]\n\n current_init = points_init[i]\n current_end = points_end[i]\n current_deposits = deposits[i]\n population_current = size_population[i]\n\n # ga_execution = GaTopMd(\n # generation=1000,\n # population=100,\n # limit_population=20,\n # crossover_rate= .6,\n # mutation_rate=.8,\n # cost_rate=2,\n # prizes_rate=5,\n # map_points=path_current,\n # prizes=prize_current,\n # max_cost=cost_current,\n # start_point=current_init,\n # end_point=current_end,\n # depositos=current_deposits)\n\n\n folder_cenary = result_folder + '/results_' + re.findall('([\\w]+)\\.', path_current)[0]\n folder_chart = folder_cenary+'/charts'+name\n if not os.path.exists(folder_cenary):\n os.mkdir(folder_cenary)\n\n if not os.path.exists(folder_chart):\n os.mkdir(folder_chart)\n\n with open(folder_cenary + '/Results_Execution.txt', 'a+') as out:\n out.write('Cenario: ' + path_current + '\\n')\n\n print('Cenario: ' + path_current + '\\n')\n\n with open(folder_cenary + '/Results_Execution_melhor_elemento_custo_premio.csv', 'a+') as out:\n out.write(name + '\\n')\n\n for numberExecution in range(number_executions):\n\n pso_execution = PSO(\n iterations=1,\n size_population=1,\n beta=.3,\n alfa=.8,\n cost_rate=2,\n prizes_rate=5,\n map_points=path_current,\n prizes=prize_current,\n max_cost=cost_current,\n start_point=current_init,\n end_point=current_end,\n depositos=current_deposits)\n\n print('####### Inicio Execucao: ' + str(numberExecution))\n\n gbest, primeiro, ultimo = pso_execution.run()\n\n\n\n\n\n\n\n\n\n mapaa = list()\n mapaa.append(np.fromstring('0, 19, 18, 12, 11, 7, 8, 13, 0', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 20, 14, 9, 5, 15, 16, 21, 24, 0', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 28, 29, 27, 34, 33, 37, 41, 38, 0', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 25, 31, 32, 26, 40, 39, 43, 44, 36, 30, 0', dtype=int, sep=','))\n\n pso_execution.plota_rotas_TOP(cidades=pso_execution.map_points, rota=mapaa, file_plot=True,\n name_file_plot=folder_chart + '/Plot_Path_melhor_elemento_' + name + '_execution_' + str(\n 1))\n\n mapaa = list()\n mapaa.append(np.fromstring('0, 35, 38, 41, 37, 34, 27, 29, 28, 0', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 13, 8, 7, 11, 6, 12, 23, 18, 19, 0', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 30, 36, 44, 43, 39, 40, 26, 32, 31, 25, 0', dtype=int, sep=','))\n mapaa.append(np.fromstring('', dtype=int, sep=','))\n\n pso_execution.plota_rotas_TOP(cidades=pso_execution.map_points, rota=mapaa, file_plot=True,\n name_file_plot=folder_chart + '/Plot_Path_melhor_elemento_' + name + '_execution_' + str(\n 2))\n\n mapaa = list()\n mapaa.append(np.fromstring('0, 23, 18, 19, 13, 8, 7, 11, 12, 6, 1', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 20, 14, 9, 5, 15, 16, 21, 17, 10, 2', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 28, 35, 42, 41, 38, 34, 29, 27, 33, 37, 3', dtype=int, sep=','))\n mapaa.append(np.fromstring('0, 25, 24, 26, 32, 31, 30, 36, 44, 43, 39, 40, 4', dtype=int, sep=','))\n\n pso_execution.plota_rotas_TOP(cidades=pso_execution.map_points, rota=mapaa, file_plot=True,\n name_file_plot=folder_chart + '/Plot_Path_melhor_elemento_' + name + '_execution_' + str(\n 3))\n\n\n mapaa = list()\n mapaa.append(np.fromstring('0 14 9 5 15 20 0', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 13 7 11 6 12 18 19 0', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 28 29 34 38 41 37 33 27 0', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 30 31 43 39 40 26 25 24 0', dtype=int, sep=' '))\n\n pso_execution.plota_rotas_TOP(cidades=pso_execution.map_points, rota=mapaa, file_plot=True,\n name_file_plot=folder_chart + '/Plot_Path_melhor_elemento_' + name + '_execution_' + str(\n 4))\n\n\n mapaa = list()\n mapaa.append(np.fromstring('0 13 7 11 6 12 18 19 0', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 28 29 34 38 41 37 33 27 0', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 30 44 43 39 40 26 31 25 0', dtype=int, sep=' '))\n\n pso_execution.plota_rotas_TOP(cidades=pso_execution.map_points, rota=mapaa, file_plot=True,\n name_file_plot=folder_chart + '/Plot_Path_melhor_elemento_' + name + '_execution_' + str(\n 5))\n\n\n\n mapaa = list()\n mapaa.append(np.fromstring('0 23 18 19 13 8 7 11 12 6 1', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 24 20 14 15 9 5 10 2', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 28 29 27 34 38 42 41 37 3', dtype=int, sep=' '))\n mapaa.append(np.fromstring('0 25 26 31 30 36 43 39 40 4', dtype=int, sep=' '))\n\n pso_execution.plota_rotas_TOP(cidades=pso_execution.map_points, rota=mapaa, file_plot=True,\n name_file_plot=folder_chart + '/Plot_Path_melhor_elemento_' + name + '_execution_' + str(\n 6))\n\n print('####### Fim Execucao: ' + str(numberExecution))\n\n del pso_execution\n\n gc.collect()"
] | [
[
"numpy.fromstring"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
colemakdvorak/probability | [
"8164538be2cd1c06b5593b100df1dc605b6d5733"
] | [
"tensorflow_probability/python/distributions/distribution_properties_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\"\"\"Property-based testing for TFP distributions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport contextlib\nimport functools\nimport inspect\nimport re\n\nfrom absl import flags\nfrom absl import logging\nfrom absl.testing import parameterized\nimport hypothesis as hp\nfrom hypothesis import strategies as hps\nimport numpy as np\nimport six\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python import bijectors as tfb\nfrom tensorflow_probability.python import distributions as tfd\nfrom tensorflow_probability.python import util as tfp_util\nfrom tensorflow_probability.python.bijectors import hypothesis_testlib as bijector_hps\nfrom tensorflow_probability.python.internal import hypothesis_testlib as tfp_hps\nfrom tensorflow_probability.python.internal import tensor_util\nfrom tensorflow_probability.python.internal import tensorshape_util\nfrom tensorflow_probability.python.internal import test_case\nfrom tensorflow_probability.python.internal import test_util as tfp_test_util\n\nfrom tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import\n\n\nflags.DEFINE_enum('tf_mode', 'graph', ['eager', 'graph'],\n 'TF execution mode to use')\n\nFLAGS = flags.FLAGS\n\n\nTF2_FRIENDLY_DISTS = (\n 'Bernoulli',\n 'Beta',\n 'Binomial',\n 'Chi',\n 'Chi2',\n 'CholeskyLKJ',\n 'Categorical',\n 'Cauchy',\n 'Deterministic',\n 'Dirichlet',\n 'DirichletMultinomial',\n 'DoublesidedMaxwell',\n 'Empirical',\n 'Exponential',\n 'FiniteDiscrete',\n 'Gamma',\n 'GammaGamma',\n 'GeneralizedPareto',\n 'Geometric',\n 'Gumbel',\n 'HalfCauchy',\n 'HalfNormal',\n 'Horseshoe',\n 'InverseGamma',\n 'InverseGaussian',\n 'Kumaraswamy',\n 'Laplace',\n 'LKJ',\n 'LogNormal',\n 'Logistic',\n 'Normal',\n 'Multinomial',\n 'NegativeBinomial',\n 'OneHotCategorical',\n 'Pareto',\n 'PERT',\n 'PlackettLuce',\n 'Poisson',\n # 'PoissonLogNormalQuadratureCompound' TODO(b/137956955): Add support\n # for hypothesis testing\n 'ProbitBernoulli',\n 'RelaxedBernoulli',\n 'ExpRelaxedOneHotCategorical',\n # 'SinhArcsinh' TODO(b/137956955): Add support for hypothesis testing\n 'StudentT',\n 'Triangular',\n 'Uniform',\n 'VonMises',\n 'VonMisesFisher',\n 'Zipf',\n)\n\nNO_SAMPLE_PARAM_GRADS = {\n 'Deterministic': ('atol', 'rtol'),\n}\nNO_LOG_PROB_PARAM_GRADS = ('Deterministic', 'Empirical')\nNO_KL_PARAM_GRADS = ('Deterministic',)\n\nMUTEX_PARAMS = (\n set(['logits', 'probs']),\n set(['probits', 'probs']),\n set(['rate', 'log_rate']),\n set(['scale', 'scale_tril', 'scale_diag', 'scale_identity_multiplier']),\n)\n\nSPECIAL_DISTS = (\n 'Distribution',\n 'Empirical',\n 'Independent',\n 'MixtureSameFamily',\n 'TransformedDistribution',\n)\n\nEXTRA_TENSOR_CONVERSION_DISTS = (\n 'RelaxedBernoulli',\n)\n\n\nclass DistInfo(collections.namedtuple(\n 'DistInfo', ['cls', 'params_event_ndims'])):\n \"\"\"Sufficient information to instantiate a Distribution.\n\n To wit\n - The Python class `cls` giving the class, and\n - A Python dict `params_event_ndims` giving the event dimensions for the\n parameters (so that parameters can be built with predictable batch shapes).\n\n Specifically, the `params_event_ndims` dict maps string parameter names to\n Python integers. Each integer gives how many (trailing) dimensions of that\n parameter are part of the event.\n \"\"\"\n __slots__ = ()\n\n\ndef instantiable_base_dists():\n \"\"\"Computes the table of mechanically instantiable base Distributions.\n\n A Distribution is mechanically instantiable if\n - The class appears as a symbol binding in `tfp.distributions`;\n - The class defines a `_params_event_ndims` method (necessary\n to generate parameter Tensors with predictable batch shapes); and\n - The name is not blacklisted in `SPECIAL_DISTS`.\n\n Additionally, the Empricial distribution is hardcoded with special\n instantiation rules for each choice of event_ndims among 0, 1, and 2.\n\n Compound distributions like TransformedDistribution have their own\n instantiation rules hard-coded in the `distributions` strategy.\n\n Returns:\n instantiable_base_dists: A Python dict mapping distribution name\n (as a string) to a `DistInfo` carrying the information necessary to\n instantiate it.\n \"\"\"\n result = {}\n for (dist_name, dist_class) in six.iteritems(tfd.__dict__):\n if (not inspect.isclass(dist_class) or\n not issubclass(dist_class, tfd.Distribution) or\n dist_name in SPECIAL_DISTS):\n continue\n try:\n params_event_ndims = dist_class._params_event_ndims()\n except NotImplementedError:\n msg = 'Unable to test tfd.%s: _params_event_ndims not implemented'\n logging.warning(msg, dist_name)\n continue\n result[dist_name] = DistInfo(dist_class, params_event_ndims)\n\n # Empirical._params_event_ndims depends on `self.event_ndims`, so we have to\n # explicitly list these entries.\n result['Empirical|event_ndims=0'] = DistInfo( #\n functools.partial(tfd.Empirical, event_ndims=0), dict(samples=1))\n result['Empirical|event_ndims=1'] = DistInfo( #\n functools.partial(tfd.Empirical, event_ndims=1), dict(samples=2))\n result['Empirical|event_ndims=2'] = DistInfo( #\n functools.partial(tfd.Empirical, event_ndims=2), dict(samples=3))\n\n return result\n\n\n# INSTANTIABLE_BASE_DISTS is a map from str->(DistClass, params_event_ndims)\nINSTANTIABLE_BASE_DISTS = instantiable_base_dists()\ndel instantiable_base_dists\n\nINSTANTIABLE_META_DISTS = (\n 'Independent',\n 'MixtureSameFamily',\n 'TransformedDistribution',\n)\n\n# pylint is unable to handle @hps.composite (e.g. complains \"No value for\n# argument 'batch_shape' in function call\"), so disable this lint for the file.\n\n# pylint: disable=no-value-for-parameter\n\n\[email protected]\ndef valid_slices(draw, batch_shape):\n \"\"\"Samples a legal (possibly empty) slice for shape batch_shape.\"\"\"\n # We build up a list of slices in several stages:\n # 1. Choose 0 to batch_rank slices to come before an Ellipsis (...).\n # 2. Decide whether or not to add an Ellipsis; if using, updating the indexing\n # used (e.g. batch_shape[i]) to identify safe bounds.\n # 3. Choose 0 to [remaining_dims] slices to come last.\n # 4. Decide where to insert between 0 and 3 newaxis slices.\n batch_shape = tf.TensorShape(batch_shape).as_list()\n slices = []\n batch_rank = len(batch_shape)\n arbitrary_slices = hps.tuples(\n hps.one_of(hps.just(None), hps.integers(min_value=-100, max_value=100)),\n hps.one_of(hps.just(None), hps.integers(min_value=-100, max_value=100)),\n hps.one_of(\n hps.just(None),\n hps.integers(min_value=-100, max_value=100).filter(lambda x: x != 0))\n ).map(lambda tup: slice(*tup))\n\n # 1. Choose 0 to batch_rank slices to come before an Ellipsis (...).\n nslc_before_ellipsis = draw(hps.integers(min_value=0, max_value=batch_rank))\n for i in range(nslc_before_ellipsis):\n slc = draw(\n hps.one_of(\n hps.integers(min_value=0, max_value=batch_shape[i] - 1),\n arbitrary_slices))\n slices.append(slc)\n # 2. Decide whether or not to add an Ellipsis; if using, updating the indexing\n # used (e.g. batch_shape[i]) to identify safe bounds.\n has_ellipsis = draw(hps.booleans().map(lambda x: (Ellipsis, x)))[1]\n nslc_after_ellipsis = draw(\n hps.integers(min_value=0, max_value=batch_rank - nslc_before_ellipsis))\n if has_ellipsis:\n slices.append(Ellipsis)\n remain_start, remain_end = (batch_rank - nslc_after_ellipsis, batch_rank)\n else:\n remain_start = nslc_before_ellipsis\n remain_end = nslc_before_ellipsis + nslc_after_ellipsis\n # 3. Choose 0 to [remaining_dims] slices to come last.\n for i in range(remain_start, remain_end):\n slc = draw(\n hps.one_of(\n hps.integers(min_value=0, max_value=batch_shape[i] - 1),\n arbitrary_slices))\n slices.append(slc)\n # 4. Decide where to insert between 0 and 3 newaxis slices.\n newaxis_positions = draw(\n hps.lists(hps.integers(min_value=0, max_value=len(slices)), max_size=3))\n for i in sorted(newaxis_positions, reverse=True):\n slices.insert(i, tf.newaxis)\n slices = tuple(slices)\n # Since `d[0]` ==> `d.__getitem__(0)` instead of `d.__getitem__((0,))`;\n # and similarly `d[:3]` ==> `d.__getitem__(slice(None, 3))` instead of\n # `d.__getitem__((slice(None, 3),))`; it is useful to test such scenarios.\n if len(slices) == 1 and draw(hps.booleans()):\n # Sometimes only a single item non-tuple.\n return slices[0]\n return slices\n\n\ndef stringify_slices(slices):\n \"\"\"Returns a list of strings describing the items in `slices`.\n\n Each returned string (in order) encodes what to do with one dimension of the\n slicee:\n - That number for a single integer slice;\n - 'a:b:c' for a start-stop-step slice, omitting any missing components;\n - 'tf.newaxis' for an axis insertion; or\n - The ellipsis '...' for an arbitrary-rank gap.\n\n Args:\n slices: A single-dimension slice or a Python tuple of single-dimension\n slices.\n\n Returns:\n pretty_slices: A list of Python strings encoding each slice.\n \"\"\"\n pretty_slices = []\n slices = slices if isinstance(slices, tuple) else (slices,)\n for slc in slices:\n if slc == Ellipsis:\n pretty_slices.append('...')\n elif isinstance(slc, slice):\n pretty_slices.append('{}:{}:{}'.format(\n *['' if s is None else s for s in (slc.start, slc.stop, slc.step)]))\n elif isinstance(slc, int) or tf.is_tensor(slc):\n pretty_slices.append(str(slc))\n elif slc is tf.newaxis:\n pretty_slices.append('tf.newaxis')\n else:\n raise ValueError('Unexpected slice type: {}'.format(type(slc)))\n return pretty_slices\n\n\ndef depths():\n return hps.integers(min_value=0, max_value=4)\n\n\[email protected]\ndef broadcasting_params(draw,\n dist_name,\n batch_shape,\n event_dim=None,\n enable_vars=False):\n \"\"\"Strategy for drawing parameters broadcasting to `batch_shape`.\"\"\"\n if dist_name not in INSTANTIABLE_BASE_DISTS:\n raise ValueError('Unknown Distribution name {}'.format(dist_name))\n\n params_event_ndims = INSTANTIABLE_BASE_DISTS[dist_name].params_event_ndims\n\n def _constraint(param):\n return constraint_for(dist_name, param)\n\n return draw(\n tfp_hps.broadcasting_params(\n batch_shape,\n params_event_ndims,\n event_dim=event_dim,\n enable_vars=enable_vars,\n constraint_fn_for=_constraint,\n mutex_params=MUTEX_PARAMS))\n\n\ndef params_used(dist):\n return [k for k, v in six.iteritems(dist.parameters) if v is not None]\n\n\[email protected]\ndef independents(\n draw, batch_shape=None, event_dim=None,\n enable_vars=False, depth=None):\n \"\"\"Strategy for drawing `Independent` distributions.\n\n The underlying distribution is drawn from the `distributions` strategy.\n\n Args:\n draw: Hypothesis strategy sampler supplied by `@hps.composite`.\n batch_shape: An optional `TensorShape`. The batch shape of the resulting\n `Independent` distribution. Note that the underlying distribution will in\n general have a higher-rank batch shape, to make room for reinterpreting\n some of those dimensions as the `Independent`'s event. Hypothesis will\n pick one if omitted.\n event_dim: Optional Python int giving the size of each of the underlying\n distribution's parameters' event dimensions. This is shared across all\n parameters, permitting square event matrices, compatible location and\n scale Tensors, etc. If omitted, Hypothesis will choose one.\n enable_vars: TODO(bjp): Make this `True` all the time and put variable\n initialization in slicing_test. If `False`, the returned parameters are\n all Tensors, never Variables or DeferredTensor.\n depth: Python `int` giving maximum nesting depth of compound Distributions.\n\n Returns:\n dists: A strategy for drawing `Independent` distributions with the specified\n `batch_shape` (or an arbitrary one if omitted).\n \"\"\"\n if depth is None:\n depth = draw(depths())\n\n reinterpreted_batch_ndims = draw(hps.integers(min_value=0, max_value=2))\n\n if batch_shape is None:\n batch_shape = draw(\n tfp_hps.shapes(min_ndims=reinterpreted_batch_ndims))\n else: # This independent adds some batch dims to its underlying distribution.\n batch_shape = tensorshape_util.concatenate(\n batch_shape,\n draw(tfp_hps.shapes(\n min_ndims=reinterpreted_batch_ndims,\n max_ndims=reinterpreted_batch_ndims)))\n\n underlying = draw(\n distributions(\n batch_shape=batch_shape,\n event_dim=event_dim,\n enable_vars=enable_vars,\n depth=depth - 1))\n hp.note('Forming Independent with underlying dist {}; '\n 'parameters {}; reinterpreted_batch_ndims {}'.format(\n underlying, params_used(underlying), reinterpreted_batch_ndims))\n result_dist = tfd.Independent(\n underlying,\n reinterpreted_batch_ndims=reinterpreted_batch_ndims,\n validate_args=True)\n expected_shape = batch_shape[:len(batch_shape) - reinterpreted_batch_ndims]\n if expected_shape != result_dist.batch_shape:\n msg = ('Independent strategy generated a bad batch shape '\n 'for {}, should have been {}.').format(result_dist, expected_shape)\n raise AssertionError(msg)\n return result_dist\n\n\[email protected]\ndef transformed_distributions(draw,\n batch_shape=None,\n event_dim=None,\n enable_vars=False,\n depth=None):\n \"\"\"Strategy for drawing `TransformedDistribution`s.\n\n The transforming bijector is drawn from the\n `bijectors.hypothesis_testlib.unconstrained_bijectors` strategy.\n\n The underlying distribution is drawn from the `distributions` strategy, except\n that it must be compatible with the bijector according to\n `bijectors.hypothesis_testlib.distribution_filter_for` (these generally check\n that vector bijectors are not combined with scalar distributions, etc).\n\n Args:\n draw: Hypothesis strategy sampler supplied by `@hps.composite`.\n batch_shape: An optional `TensorShape`. The batch shape of the resulting\n `TransformedDistribution`. The underlying distribution will sometimes\n have the same `batch_shape`, and sometimes have scalar batch shape.\n Hypothesis will pick a `batch_shape` if omitted.\n event_dim: Optional Python int giving the size of each of the underlying\n distribution's parameters' event dimensions. This is shared across all\n parameters, permitting square event matrices, compatible location and\n scale Tensors, etc. If omitted, Hypothesis will choose one.\n enable_vars: TODO(bjp): Make this `True` all the time and put variable\n initialization in slicing_test. If `False`, the returned parameters are\n all Tensors, never Variables or DeferredTensor.\n depth: Python `int` giving maximum nesting depth of compound Distributions.\n\n Returns:\n dists: A strategy for drawing `TransformedDistribution`s with the specified\n `batch_shape` (or an arbitrary one if omitted).\n \"\"\"\n if depth is None:\n depth = draw(depths())\n\n bijector = draw(bijector_hps.unconstrained_bijectors())\n hp.note('Drawing TransformedDistribution with bijector {}'.format(bijector))\n if batch_shape is None:\n batch_shape = draw(tfp_hps.shapes())\n underlying_batch_shape = batch_shape\n batch_shape_arg = None\n if draw(hps.booleans()):\n # Use batch_shape overrides.\n underlying_batch_shape = tf.TensorShape([]) # scalar underlying batch\n batch_shape_arg = batch_shape\n underlyings = distributions(\n batch_shape=underlying_batch_shape,\n event_dim=event_dim,\n enable_vars=enable_vars,\n depth=depth - 1).filter(\n bijector_hps.distribution_filter_for(bijector))\n to_transform = draw(underlyings)\n hp.note('Forming TransformedDistribution with '\n 'underlying distribution {}; parameters {}'.format(\n to_transform, params_used(to_transform)))\n # TODO(bjp): Add test coverage for `event_shape` argument of\n # `TransformedDistribution`.\n result_dist = tfd.TransformedDistribution(\n bijector=bijector,\n distribution=to_transform,\n batch_shape=batch_shape_arg,\n validate_args=True)\n if batch_shape != result_dist.batch_shape:\n msg = ('TransformedDistribution strategy generated a bad batch shape '\n 'for {}, should have been {}.').format(result_dist, batch_shape)\n raise AssertionError(msg)\n return result_dist\n\n\[email protected]\ndef mixtures_same_family(draw,\n batch_shape=None,\n event_dim=None,\n enable_vars=False,\n depth=None):\n \"\"\"Strategy for drawing `MixtureSameFamily` distributions.\n\n The component distribution is drawn from the `distributions` strategy.\n\n The Categorical mixture distributions are either shared across all batch\n members, or drawn independently for the full batch (as required by\n `MixtureSameFamily`).\n\n Args:\n draw: Hypothesis strategy sampler supplied by `@hps.composite`.\n batch_shape: An optional `TensorShape`. The batch shape of the resulting\n `MixtureSameFamily` distribution. The component distribution will have a\n batch shape of 1 rank higher (for the components being mixed). Hypothesis\n will pick a batch shape if omitted.\n event_dim: Optional Python int giving the size of each of the component\n distribution's parameters' event dimensions. This is shared across all\n parameters, permitting square event matrices, compatible location and\n scale Tensors, etc. If omitted, Hypothesis will choose one.\n enable_vars: TODO(bjp): Make this `True` all the time and put variable\n initialization in slicing_test. If `False`, the returned parameters are\n all Tensors, never Variables or DeferredTensor.\n depth: Python `int` giving maximum nesting depth of compound Distributions.\n\n Returns:\n dists: A strategy for drawing `MixtureSameFamily` distributions with the\n specified `batch_shape` (or an arbitrary one if omitted).\n \"\"\"\n if depth is None:\n depth = draw(depths())\n\n if batch_shape is None:\n # Ensure the components dist has at least one batch dim (a component dim).\n batch_shape = draw(tfp_hps.shapes(min_ndims=1, min_lastdimsize=2))\n else: # This mixture adds a batch dim to its underlying components dist.\n batch_shape = tensorshape_util.concatenate(\n batch_shape,\n draw(tfp_hps.shapes(min_ndims=1, max_ndims=1, min_lastdimsize=2)))\n\n component = draw(\n distributions(\n batch_shape=batch_shape,\n event_dim=event_dim,\n enable_vars=enable_vars,\n depth=depth - 1))\n hp.note('Drawing MixtureSameFamily with component {}; parameters {}'.format(\n component, params_used(component)))\n # scalar or same-shaped categorical?\n mixture_batch_shape = draw(\n hps.one_of(hps.just(batch_shape[:-1]), hps.just(tf.TensorShape([]))))\n mixture_dist = draw(base_distributions(\n dist_name='Categorical',\n batch_shape=mixture_batch_shape,\n event_dim=tensorshape_util.as_list(batch_shape)[-1],\n enable_vars=enable_vars))\n hp.note(('Forming MixtureSameFamily with '\n 'mixture distribution {}; parameters {}').format(\n mixture_dist, params_used(mixture_dist)))\n result_dist = tfd.MixtureSameFamily(\n components_distribution=component,\n mixture_distribution=mixture_dist,\n validate_args=True)\n if batch_shape[:-1] != result_dist.batch_shape:\n msg = ('MixtureSameFamily strategy generated a bad batch shape '\n 'for {}, should have been {}.').format(result_dist, batch_shape[:-1])\n raise AssertionError(msg)\n return result_dist\n\n\ndef assert_shapes_unchanged(target_shaped_dict, possibly_bcast_dict):\n for param, target_param_val in six.iteritems(target_shaped_dict):\n np.testing.assert_array_equal(\n tensorshape_util.as_list(target_param_val.shape),\n tensorshape_util.as_list(possibly_bcast_dict[param].shape))\n\n\[email protected]\ndef base_distributions(draw,\n dist_name=None,\n batch_shape=None,\n event_dim=None,\n enable_vars=False,\n eligibility_filter=lambda name: True):\n \"\"\"Strategy for drawing arbitrary base Distributions.\n\n This does not draw compound distributions like `Independent`,\n `MixtureSameFamily`, or `TransformedDistribution`; only base Distributions\n that do not accept other Distributions as arguments.\n\n Args:\n draw: Hypothesis strategy sampler supplied by `@hps.composite`.\n dist_name: Optional Python `str`. If given, the produced distributions\n will all have this type.\n batch_shape: An optional `TensorShape`. The batch shape of the resulting\n Distribution. Hypothesis will pick a batch shape if omitted.\n event_dim: Optional Python int giving the size of each of the\n distribution's parameters' event dimensions. This is shared across all\n parameters, permitting square event matrices, compatible location and\n scale Tensors, etc. If omitted, Hypothesis will choose one.\n enable_vars: TODO(bjp): Make this `True` all the time and put variable\n initialization in slicing_test. If `False`, the returned parameters are\n all Tensors, never Variables or DeferredTensor.\n eligibility_filter: Optional Python callable. Blacklists some Distribution\n class names so they will not be drawn at the top level.\n\n Returns:\n dists: A strategy for drawing Distributions with the specified `batch_shape`\n (or an arbitrary one if omitted).\n \"\"\"\n if dist_name is None:\n names = [k for k in INSTANTIABLE_BASE_DISTS.keys() if eligibility_filter(k)]\n dist_name = draw(hps.sampled_from(sorted(names)))\n\n if dist_name == 'Empirical':\n variants = [k for k in INSTANTIABLE_BASE_DISTS.keys()\n if eligibility_filter(k) and 'Empirical' in k]\n dist_name = draw(hps.sampled_from(sorted(variants)))\n\n if batch_shape is None:\n batch_shape = draw(tfp_hps.shapes())\n\n params_kwargs = draw(\n broadcasting_params(\n dist_name, batch_shape, event_dim=event_dim, enable_vars=enable_vars))\n params_constrained = constraint_for(dist_name)(params_kwargs)\n\n # Sometimes the \"distribution constraint\" fn may replace c2t-tracking\n # DeferredTensor params with Tensor params (e.g. fix_triangular). In such\n # cases, we preserve the c2t-tracking DeferredTensors by wrapping them but\n # ignoring the value.\n for k in params_constrained:\n if (k in params_kwargs and\n isinstance(params_kwargs[k], tfp_util.DeferredTensor) and\n params_kwargs[k] is not params_constrained[k]):\n\n def constrained_value(v, val=params_constrained[k]):\n # While the gradient to v will be 0, we only care about the c2t counts.\n return v * 0 + val\n\n params_constrained[k] = tfp_util.DeferredTensor(constrained_value,\n params_kwargs[k])\n\n hp.note('Forming dist {} with constrained parameters {}'.format(\n dist_name, params_constrained))\n assert_shapes_unchanged(params_kwargs, params_constrained)\n params_constrained['validate_args'] = True\n dist_cls = INSTANTIABLE_BASE_DISTS[dist_name].cls\n result_dist = dist_cls(**params_constrained)\n if batch_shape != result_dist.batch_shape:\n msg = ('Distributions strategy generated a bad batch shape '\n 'for {}, should have been {}.').format(result_dist, batch_shape)\n raise AssertionError(msg)\n return result_dist\n\n\[email protected]\ndef distributions(draw,\n dist_name=None,\n batch_shape=None,\n event_dim=None,\n enable_vars=False,\n depth=None,\n eligibility_filter=lambda name: True):\n \"\"\"Strategy for drawing arbitrary Distributions.\n\n This may draw compound distributions (i.e., `Independent`,\n `MixtureSameFamily`, and/or `TransformedDistribution`), in which case the\n underlying distributions are drawn recursively from this strategy as well.\n\n Args:\n draw: Hypothesis strategy sampler supplied by `@hps.composite`.\n dist_name: Optional Python `str`. If given, the produced distributions\n will all have this type.\n batch_shape: An optional `TensorShape`. The batch shape of the resulting\n Distribution. Hypothesis will pick a batch shape if omitted.\n event_dim: Optional Python int giving the size of each of the\n distribution's parameters' event dimensions. This is shared across all\n parameters, permitting square event matrices, compatible location and\n scale Tensors, etc. If omitted, Hypothesis will choose one.\n enable_vars: TODO(bjp): Make this `True` all the time and put variable\n initialization in slicing_test. If `False`, the returned parameters are\n all Tensors, never Variables or DeferredTensor.\n depth: Python `int` giving maximum nesting depth of compound Distributions.\n If `None`, Hypothesis will bias choose one, with a bias towards shallow\n nests.\n eligibility_filter: Optional Python callable. Blacklists some Distribution\n class names so they will not be drawn at the top level.\n\n Returns:\n dists: A strategy for drawing Distributions with the specified `batch_shape`\n (or an arbitrary one if omitted).\n\n Raises:\n ValueError: If it doesn't know how to instantiate a Distribution of class\n `dist_name`.\n \"\"\"\n if depth is None:\n depth = draw(depths())\n\n if dist_name is None and depth > 0:\n bases = hps.just(None)\n compounds = hps.one_of(\n map(hps.just, ['Independent', 'MixtureSameFamily',\n 'TransformedDistribution']))\n dist_name = draw(hps.one_of([bases, compounds]))\n\n if (dist_name is None\n or dist_name in INSTANTIABLE_BASE_DISTS\n or dist_name == 'Empirical'):\n return draw(base_distributions(\n dist_name, batch_shape, event_dim, enable_vars, eligibility_filter))\n if dist_name == 'Independent':\n return draw(independents(\n batch_shape, event_dim, enable_vars, depth))\n if dist_name == 'MixtureSameFamily':\n return draw(mixtures_same_family(\n batch_shape, event_dim, enable_vars, depth))\n if dist_name == 'TransformedDistribution':\n return draw(transformed_distributions(\n batch_shape, event_dim, enable_vars, depth))\n raise ValueError('Unknown Distribution name {}'.format(dist_name))\n\n\ndef get_event_dim(dist):\n for param, val in dist.parameters.items():\n if (param in dist._params_event_ndims() and val is not None and\n dist._params_event_ndims()[param]):\n return tf.compat.dimension_value(val.shape[-1])\n\n\ndef extra_tensor_conversion_allowed(dist):\n \"\"\"Returns `True` for dists that are allowed one extra tensor conversion.\"\"\"\n if (isinstance(dist, tfd.TransformedDistribution) or\n (type(dist).__name__ in EXTRA_TENSOR_CONVERSION_DISTS)):\n return True\n return False\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass DistributionParamsAreVarsTest(parameterized.TestCase, test_case.TestCase):\n\n @parameterized.named_parameters(\n {'testcase_name': dname, 'dist_name': dname}\n for dname in TF2_FRIENDLY_DISTS)\n @hp.given(hps.data())\n @tfp_hps.tfp_hp_settings()\n def testDistribution(self, dist_name, data):\n if tf.executing_eagerly() != (FLAGS.tf_mode == 'eager'):\n return\n seed = tfp_test_util.test_seed()\n dist = data.draw(distributions(dist_name=dist_name, enable_vars=True))\n batch_shape = dist.batch_shape\n batch_shape2 = data.draw(tfp_hps.broadcast_compatible_shape(batch_shape))\n dist2 = data.draw(\n distributions(\n dist_name=dist_name,\n batch_shape=batch_shape2,\n event_dim=get_event_dim(dist),\n enable_vars=True))\n self.evaluate([var.initializer for var in dist.variables])\n\n # Check that the distribution passes Variables through to the accessor\n # properties (without converting them to Tensor or anything like that).\n for k, v in six.iteritems(dist.parameters):\n if not tensor_util.is_ref(v):\n continue\n self.assertIs(getattr(dist, k), v)\n\n # Check that standard statistics do not read distribution parameters more\n # than twice (once in the stat itself and up to once in any validation\n # assertions).\n for stat in data.draw(\n hps.sets(\n hps.one_of(\n map(hps.just, [\n 'covariance', 'entropy', 'mean', 'mode', 'stddev',\n 'variance'\n ])),\n min_size=3,\n max_size=3)):\n hp.note('Testing excessive var usage in {}.{}'.format(dist_name, stat))\n try:\n with tfp_hps.assert_no_excessive_var_usage(\n 'statistic `{}` of `{}`'.format(stat, dist)):\n getattr(dist, stat)()\n\n except NotImplementedError:\n pass\n\n # Check that `sample` doesn't read distribution parameters more than twice,\n # and that it produces non-None gradients (if the distribution is fully\n # reparameterized).\n with tf.GradientTape() as tape:\n # TDs do bijector assertions twice (once by distribution.sample, and once\n # by bijector.forward).\n max_permissible = 3 if extra_tensor_conversion_allowed(dist) else 2\n with tfp_hps.assert_no_excessive_var_usage(\n 'method `sample` of `{}`'.format(dist),\n max_permissible=max_permissible):\n sample = dist.sample(seed=seed)\n if dist.reparameterization_type == tfd.FULLY_REPARAMETERIZED:\n grads = tape.gradient(sample, dist.variables)\n for grad, var in zip(grads, dist.variables):\n var_name = var.name.rstrip('_0123456789:')\n if var_name in NO_SAMPLE_PARAM_GRADS.get(dist_name, ()):\n continue\n if grad is None:\n raise AssertionError(\n 'Missing sample -> {} grad for distribution {}'.format(\n var_name, dist_name))\n\n # Turn off validations, since TODO(b/129271256) log_prob can choke on dist's\n # own samples. Also, to relax conversion counts for KL (might do >2 w/\n # validate_args).\n dist = dist.copy(validate_args=False)\n dist2 = dist2.copy(validate_args=False)\n\n # Test that KL divergence reads distribution parameters at most once, and\n # that is produces non-None gradients.\n try:\n for d1, d2 in (dist, dist2), (dist2, dist):\n with tf.GradientTape() as tape:\n with tfp_hps.assert_no_excessive_var_usage(\n '`kl_divergence` of (`{}` (vars {}), `{}` (vars {}))'.format(\n d1, d1.variables, d2, d2.variables),\n max_permissible=1): # No validation => 1 convert per var.\n kl = d1.kl_divergence(d2)\n wrt_vars = list(d1.variables) + list(d2.variables)\n grads = tape.gradient(kl, wrt_vars)\n for grad, var in zip(grads, wrt_vars):\n if grad is None and dist_name not in NO_KL_PARAM_GRADS:\n raise AssertionError('Missing KL({} || {}) -> {} grad:\\n'\n '{} vars: {}\\n{} vars: {}'.format(\n d1, d2, var, d1, d1.variables, d2,\n d2.variables))\n except NotImplementedError:\n pass\n\n # Test that log_prob produces non-None gradients, except for distributions\n # on the NO_LOG_PROB_PARAM_GRADS blacklist.\n if dist_name not in NO_LOG_PROB_PARAM_GRADS:\n with tf.GradientTape() as tape:\n lp = dist.log_prob(tf.stop_gradient(sample))\n grads = tape.gradient(lp, dist.variables)\n for grad, var in zip(grads, dist.variables):\n if grad is None:\n raise AssertionError(\n 'Missing log_prob -> {} grad for distribution {}'.format(\n var, dist_name))\n\n # Test that all forms of probability evaluation avoid reading distribution\n # parameters more than once.\n for evaluative in data.draw(\n hps.sets(\n hps.one_of(\n map(hps.just, [\n 'log_prob', 'prob', 'log_cdf', 'cdf',\n 'log_survival_function', 'survival_function'\n ])),\n min_size=3,\n max_size=3)):\n hp.note('Testing excessive var usage in {}.{}'.format(\n dist_name, evaluative))\n try:\n # No validation => 1 convert. But for TD we allow 2:\n # dist.log_prob(bijector.inverse(samp)) + bijector.ildj(samp)\n max_permissible = 2 if extra_tensor_conversion_allowed(dist) else 1\n with tfp_hps.assert_no_excessive_var_usage(\n 'evaluative `{}` of `{}`'.format(evaluative, dist),\n max_permissible=max_permissible):\n getattr(dist, evaluative)(sample)\n except NotImplementedError:\n pass\n\n\[email protected]\ndef no_tf_rank_errors():\n # TODO(axch): Instead of catching and `assume`ing away rank errors, could try\n # harder to avoid generating them in the first place. For instance, could add\n # a parameter to `valid_slices` that limits how much the rank may increase\n # after the slice. Trouble is, predicting what limits to set is difficult\n # because rank handling is non-uniform, and actually meeting them is also\n # non-trivial because in addition to the batch shape there is the event shape,\n # and at least one more dimention added by `sample`, and the parameters may\n # have larger \"event\" shapes than the distribution itself.\n rank_bcast_pat = (r'Broadcast between \\[([0-9]*,){8,}[0-9]*\\] '\n r'and \\[([0-9]*,){8,}[0-9]*\\] is not supported yet')\n input_dims_pat = r'Unhandled input dimensions (8|9|[1-9][0-9]+)'\n input_rank_pat = r'inputs rank not in \\[0,([6-9]|[1-9][0-9]+)\\]'\n try:\n yield\n except tf.errors.UnimplementedError as e:\n # TODO(b/138385438): This really shouldn't be so complicated.\n msg = str(e)\n if re.search(rank_bcast_pat, msg):\n # We asked some TF op (SelectV2?) to broadcast Tensors of rank >= 9.\n # Let's not.\n hp.assume(False)\n elif re.search(input_dims_pat, msg):\n # We asked some TF op (StridedSlice?) to operate on a Tensor of rank >= 8.\n # Let's not.\n hp.assume(False)\n elif re.search(input_rank_pat, msg):\n # We asked some TF op (PadV2?) to operate on a Tensor of rank >= 7.\n # Let's not.\n hp.assume(False)\n else:\n raise\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass ReproducibilityTest(parameterized.TestCase, test_case.TestCase):\n\n @parameterized.named_parameters(\n {'testcase_name': dname, 'dist_name': dname}\n for dname in sorted(list(INSTANTIABLE_BASE_DISTS.keys()) +\n list(INSTANTIABLE_META_DISTS)))\n @hp.given(hps.data())\n @tfp_hps.tfp_hp_settings()\n def testDistribution(self, dist_name, data):\n if tf.executing_eagerly() != (FLAGS.tf_mode == 'eager'): return\n dist = data.draw(distributions(dist_name=dist_name, enable_vars=False))\n seed = tfp_test_util.test_seed()\n s1 = self.evaluate(dist.sample(50, seed=seed))\n if tf.executing_eagerly():\n tf.random.set_seed(seed)\n s2 = self.evaluate(dist.sample(50, seed=seed))\n self.assertAllEqual(s1, s2)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass DistributionSlicingTest(test_case.TestCase):\n\n def _test_slicing(self, data, dist):\n strm = tfp_test_util.test_seed_stream()\n batch_shape = dist.batch_shape\n slices = data.draw(valid_slices(batch_shape))\n slice_str = 'dist[{}]'.format(', '.join(stringify_slices(slices)))\n # Make sure the slice string appears in Hypothesis' attempted example log\n hp.note('Using slice ' + slice_str)\n if not slices: # Nothing further to check.\n return\n sliced_zeros = np.zeros(batch_shape)[slices]\n sliced_dist = dist[slices]\n\n # Check that slicing modifies batch shape as expected.\n self.assertAllEqual(sliced_zeros.shape, sliced_dist.batch_shape)\n\n if not sliced_zeros.size:\n # TODO(b/128924708): Fix distributions that fail on degenerate empty\n # shapes, e.g. Multinomial, DirichletMultinomial, ...\n return\n\n # Check that sampling of sliced distributions executes.\n with no_tf_rank_errors():\n samples = self.evaluate(dist.sample(seed=strm()))\n sliced_samples = self.evaluate(sliced_dist.sample(seed=strm()))\n\n # Come up with the slices for samples (which must also include event dims).\n sample_slices = (\n tuple(slices) if isinstance(slices, collections.Sequence) else\n (slices,))\n if Ellipsis not in sample_slices:\n sample_slices += (Ellipsis,)\n sample_slices += tuple([slice(None)] *\n tensorshape_util.rank(dist.event_shape))\n\n # Report sub-sliced samples (on which we compare log_prob) to hypothesis.\n hp.note('Sample(s) for testing log_prob ' + str(samples[sample_slices]))\n\n # Check that sampling a sliced distribution produces the same shape as\n # slicing the samples from the original.\n self.assertAllEqual(samples[sample_slices].shape, sliced_samples.shape)\n\n # Check that a sliced distribution can compute the log_prob of its own\n # samples (up to numerical validation errors).\n with no_tf_rank_errors():\n try:\n lp = self.evaluate(dist.log_prob(samples))\n except tf.errors.InvalidArgumentError:\n # TODO(b/129271256): d.log_prob(d.sample()) should not fail\n # validate_args checks.\n # We only tolerate this case for the non-sliced dist.\n return\n sliced_lp = self.evaluate(sliced_dist.log_prob(samples[sample_slices]))\n\n # Check that the sliced dist's log_prob agrees with slicing the original's\n # log_prob.\n # TODO(b/128708201): Better numerics for Geometric/Beta?\n # Eigen can return quite different results for packet vs non-packet ops.\n # To work around this, we use a much larger rtol for the last 3\n # (assuming packet size 4) elements.\n packetized_lp = lp[slices].reshape(-1)[:-3]\n packetized_sliced_lp = sliced_lp.reshape(-1)[:-3]\n rtol = (0.1 if any(\n x in dist.name for x in ('Geometric', 'Beta', 'Dirichlet')) else 0.02)\n self.assertAllClose(packetized_lp, packetized_sliced_lp, rtol=rtol)\n possibly_nonpacket_lp = lp[slices].reshape(-1)[-3:]\n possibly_nonpacket_sliced_lp = sliced_lp.reshape(-1)[-3:]\n\n # TODO(b/140229057): Resolve nan disagreement between eigen vec/scalar paths\n hasnan = (np.isnan(possibly_nonpacket_lp) |\n np.isnan(possibly_nonpacket_sliced_lp))\n possibly_nonpacket_lp = np.where(hasnan, 0, possibly_nonpacket_lp)\n possibly_nonpacket_sliced_lp = np.where(\n hasnan, 0, possibly_nonpacket_sliced_lp)\n self.assertAllClose(\n possibly_nonpacket_lp, possibly_nonpacket_sliced_lp,\n rtol=0.4, atol=1e-4)\n\n def _run_test(self, data):\n dist = data.draw(distributions(enable_vars=False))\n\n # Check that all distributions still register as non-iterable despite\n # defining __getitem__. (Because __getitem__ magically makes an object\n # iterable for some reason.)\n with self.assertRaisesRegexp(TypeError, 'not iterable'):\n iter(dist)\n\n # Test slicing\n self._test_slicing(data, dist)\n\n # TODO(bjp): Enable sampling and log_prob checks. Currently, too many errors\n # from out-of-domain samples.\n # self.evaluate(dist.log_prob(dist.sample()))\n\n @hp.given(hps.data())\n @tfp_hps.tfp_hp_settings()\n def testDistributions(self, data):\n if tf.executing_eagerly() != (FLAGS.tf_mode == 'eager'): return\n self._run_test(data)\n\n def disabled_testFailureCase(self):\n # TODO(b/140229057): This test should pass.\n dist = tfd.Chi(df=np.float32(27.744131))\n dist = tfd.TransformedDistribution(\n bijector=tfb.NormalCDF(), distribution=dist, batch_shape=[4])\n dist = tfb.Expm1()(dist)\n samps = 1.7182817 + tf.zeros_like(dist.sample())\n self.assertAllClose(dist.log_prob(samps)[0], dist[0].log_prob(samps[0]))\n\n\n# Functions used to constrain randomly sampled parameter ndarrays.\n# TODO(b/128518790): Eliminate / minimize the fudge factors in here.\n\n\ndef constrain_between_eps_and_one_minus_eps(eps=1e-6):\n return lambda x: eps + (1 - 2 * eps) * tf.sigmoid(x)\n\n\ndef ensure_high_gt_low(low, high):\n \"\"\"Returns a value with shape matching `high` and gt broadcastable `low`.\"\"\"\n new_high = tf.maximum(low + tf.abs(low) * .1 + .1, high)\n reduce_dims = []\n if (tensorshape_util.rank(new_high.shape) >\n tensorshape_util.rank(high.shape)):\n reduced_leading_axes = tf.range(\n tensorshape_util.rank(new_high.shape) -\n tensorshape_util.rank(high.shape))\n new_high = tf.math.reduce_max(\n input_tensor=new_high, axis=reduced_leading_axes)\n reduce_dims = [\n d for d in range(tensorshape_util.rank(high.shape))\n if high.shape[d] < new_high.shape[d]\n ]\n if reduce_dims:\n new_high = tf.math.reduce_max(\n input_tensor=new_high, axis=reduce_dims, keepdims=True)\n return new_high\n\n\ndef fix_finite_discrete(d):\n size = d.get('probs', d.get('logits', None)).shape[-1]\n return dict(d, outcomes=tf.linspace(-1.0, 1.0, size))\n\n\ndef fix_lkj(d):\n return dict(d, concentration=d['concentration'] + 1, dimension=3)\n\n\ndef fix_pert(d):\n peak = ensure_high_gt_low(d['low'], d['peak'])\n high = ensure_high_gt_low(peak, d['high'])\n temperature = ensure_high_gt_low(\n np.zeros(d['temperature'].shape, dtype=np.float32), d['temperature'])\n return dict(d, peak=peak, high=high, temperature=temperature)\n\n\ndef fix_triangular(d):\n peak = ensure_high_gt_low(d['low'], d['peak'])\n high = ensure_high_gt_low(peak, d['high'])\n return dict(d, peak=peak, high=high)\n\n\ndef fix_wishart(d):\n df = d['df']\n scale = d.get('scale', d.get('scale_tril'))\n return dict(d, df=tf.maximum(df, tf.cast(scale.shape[-1], df.dtype)))\n\n\nCONSTRAINTS = {\n 'atol':\n tf.math.softplus,\n 'rtol':\n tf.math.softplus,\n 'concentration':\n tfp_hps.softplus_plus_eps(),\n 'GeneralizedPareto.concentration': # Permits +ve and -ve concentrations.\n lambda x: tf.math.tanh(x) * 0.24,\n 'concentration0':\n tfp_hps.softplus_plus_eps(),\n 'concentration1':\n tfp_hps.softplus_plus_eps(),\n 'covariance_matrix':\n tfp_hps.positive_definite,\n 'df':\n tfp_hps.softplus_plus_eps(),\n 'InverseGaussian.loc':\n tfp_hps.softplus_plus_eps(),\n 'VonMisesFisher.mean_direction': # max ndims is 3 to avoid instability.\n lambda x: tf.math.l2_normalize(tf.math.sigmoid(x[..., :3]) + 1e-6, -1),\n 'Categorical.probs':\n tf.math.softmax,\n 'ExpRelaxedOneHotCategorical.probs':\n tf.math.softmax,\n 'FiniteDiscrete.probs':\n tf.math.softmax,\n 'Multinomial.probs':\n tf.math.softmax,\n 'OneHotCategorical.probs':\n tf.math.softmax,\n 'RelaxedCategorical.probs':\n tf.math.softmax,\n 'Zipf.power':\n tfp_hps.softplus_plus_eps(1 + 1e-6), # strictly > 1\n 'Geometric.logits': # TODO(b/128410109): re-enable down to -50\n # Capping at 16. so that probability is less than 1, and entropy is\n # defined.\n lambda x: tf.minimum(tf.maximum(x, -16.), 16.), # works around the bug\n 'Geometric.probs':\n constrain_between_eps_and_one_minus_eps(),\n 'Binomial.probs':\n tf.sigmoid,\n 'NegativeBinomial.probs':\n tf.sigmoid,\n 'Bernoulli.probs':\n tf.sigmoid,\n 'PlackettLuce.scores':\n tfp_hps.softplus_plus_eps(),\n 'ProbitBernoulli.probs':\n tf.sigmoid,\n 'RelaxedBernoulli.probs':\n tf.sigmoid,\n 'log_rate':\n lambda x: tf.maximum(x, -16.),\n 'mixing_concentration':\n tfp_hps.softplus_plus_eps(),\n 'mixing_rate':\n tfp_hps.softplus_plus_eps(),\n 'rate':\n tfp_hps.softplus_plus_eps(),\n 'scale':\n tfp_hps.softplus_plus_eps(),\n 'Wishart.scale':\n tfp_hps.positive_definite,\n 'scale_diag':\n tfp_hps.softplus_plus_eps(),\n 'scale_identity_multiplier':\n tfp_hps.softplus_plus_eps(),\n 'scale_tril':\n tfp_hps.lower_tril_positive_definite,\n 'temperature':\n tfp_hps.softplus_plus_eps(),\n 'total_count':\n lambda x: tf.floor(tf.sigmoid(x / 100) * 100) + 1,\n 'Bernoulli':\n lambda d: dict(d, dtype=tf.float32),\n 'CholeskyLKJ':\n fix_lkj,\n 'LKJ':\n fix_lkj,\n 'PERT':\n fix_pert,\n 'Triangular':\n fix_triangular,\n 'TruncatedNormal':\n lambda d: dict(d, high=ensure_high_gt_low(d['low'], d['high'])),\n 'Uniform':\n lambda d: dict(d, high=ensure_high_gt_low(d['low'], d['high'])),\n 'Wishart':\n fix_wishart,\n 'Zipf':\n lambda d: dict(d, dtype=tf.float32),\n 'FiniteDiscrete':\n fix_finite_discrete,\n}\n\n\ndef constraint_for(dist=None, param=None):\n if param is not None:\n return CONSTRAINTS.get('{}.{}'.format(dist, param),\n CONSTRAINTS.get(param, tfp_hps.identity_fn))\n return CONSTRAINTS.get(dist, tfp_hps.identity_fn)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] | [
[
"tensorflow.compat.v2.math.tanh",
"tensorflow.compat.v2.math.reduce_max",
"tensorflow.compat.v2.executing_eagerly",
"tensorflow.compat.v2.TensorShape",
"numpy.where",
"tensorflow.compat.v2.linspace",
"tensorflow.compat.v2.is_tensor",
"numpy.float32",
"tensorflow.compat.v2.abs",
"numpy.zeros",
"tensorflow.compat.v2.math.sigmoid",
"tensorflow.compat.v2.test.main",
"numpy.isnan",
"tensorflow.compat.v2.maximum",
"tensorflow.compat.v2.GradientTape",
"tensorflow.compat.v2.cast",
"tensorflow.compat.v2.random.set_seed",
"tensorflow.compat.v2.stop_gradient",
"tensorflow.compat.v2.compat.dimension_value",
"tensorflow.compat.v2.sigmoid"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jthacker/jtmri | [
"10af3dd932bf73a91e6662eaff8f844fdf07c067"
] | [
"jtmri/learn/features.py"
] | [
"import numpy as np\nimport pylab as pl\nimport itertools\nimport jtmri.utils\n\n\ndef generate_spatial_context_features(n, min_distance=0, max_distance=100, min_region_len=0, max_region_len=100):\n \"\"\"Create n features based on Criminsi2009 long range spatial features\n A feature consists of the mean value of some parameterized portion of the image.\n Features are generated based on uniform interval distributions.\n Features consist of a distance vector and a box size.\n\n Parameters\n ----------\n n : int\n Number of spatial features to create\n min_distance : float (default: 0)\n Minimum distance of a generated feature from the origin\n max_distance : float (default: 100)\n Maximum distance of a generated feature from the origin\n min_region_len : float (default: 0)\n Minimum length of a generated feature side\n max_region_len : float (default: 100)\n Maximum length of a generated feature side\n \n Returns\n -------\n ndarray\n An array of the feature paramters.\n Each set of parameters consists of 4 values: x-distance, y-distance, width, height\n \"\"\"\n radius = min_distance + (max_distance - min_distance) * np.sqrt(np.random.uniform(low=0, high=1, size=n))\n theta = np.random.uniform(low=0, high=2*np.pi, size=n)\n height = np.random.uniform(low=min_region_len, high=max_region_len, size=n)\n width = np.random.uniform(low=min_region_len, high=max_region_len, size=n)\n return np.vstack((radius * np.cos(theta), radius * np.sin(theta), width, height)).T\n\n\ndef plot_spatial_context_features_distributions(features, bins=25):\n params = [\n ('dx',),\n ('dy',),\n ('w',),\n ('h',)\n ]\n _, axs = pl.subplots(ncols=2, nrows=2)\n axs = jtmri.utils.flatten(axs)\n for (name,), ax, data in zip(params, axs, jtmri.np.iter_axes(features, 1)):\n ax.hist(data, bins=bins)\n ax.set_title(name)\n pl.tight_layout()\n\ndef plot_spatial_context_features(origin, features, scale=(1, 1), ax=None, show_arrows=True):\n \"\"\"Given a origin and an array of features, plot them as rectangles and arrows.\"\"\"\n from matplotlib.patches import Rectangle, Arrow\n if ax is None:\n _, ax = pl.subplots()\n ax.set_aspect('equal')\n ox, oy = origin\n sx, sy = scale\n for x, y, w, h in features:\n x /= sx\n y /= sy\n w /= sx\n h /= sy\n ax.add_patch(Rectangle((ox + x - w/2, oy + y - h/2), w, h, facecolor=(1,0,0,0.1)))\n if show_arrows:\n ax.add_patch(Arrow(ox, oy, x, y))\n\n\ndef integral_image(image):\n \"\"\"Create an integral image on the first 2 dimensions from the input.\n Args:\n image -- ndarray with ndim >= 2\n Returns an integral image where every location i,j is the cumulative sum\n of all preceeding pixels.\n \"\"\"\n return image.cumsum(1).cumsum(0)\n\n\ndef integral_image_sum(ii, r0, c0, r1, c1):\n \"\"\"Find the sum of a region using an integral image.\"\"\"\n return ii[r1, c1] + ii[r0, c0] - ii[r0, c1] - ii[r1, c0]\n\n\ndef integral_image_mean(ii, r0, c0, r1, c1):\n \"\"\"Find the mean of a region using an integral image\"\"\"\n N = ((r1 - r0) * (c1 - c0)).astype(float)[:, np.newaxis]\n return integral_image_sum(ii, r0, c0, r1, c1) / N\n \n\ndef spatial_context_features_response(image, feature_params, scale, mask=None):\n \"\"\"Compute the response of each feature for every pixel in the image\n Args:\n image -- ndarray for computing response from.\n if ndim is == 3, then the third dimension is treated as\n extra channels and are aggregated in the response\n feature_params -- ndarray of shape [n_features, 4] (feature units should be in millimeters)\n scale -- a 2-tuple (sx, sy) that gives the scale\n from millimeters to pixels (e.g. 10 mm / pixel)\n mask -- only compute the response for the pixels in this mask\n \n Returns: ndarray of feature responses, shape is [image.size, len(feature_params)]\n \n The response is computed as sum of the mean of each channel in the image.\n \"\"\"\n assert 2 <= image.ndim <= 3\n assert feature_params.ndim == 2\n if image.ndim == 2:\n image = image[:, :, np.newaxis]\n N, M, C = image.shape\n sx, sy = scale\n n_features, _ = feature_params.shape\n\n # Compute the integral image to save on processing time\n ii = integral_image(image)\n \n def cleanse(x, xmax):\n return np.clip(x.ravel(), 0, xmax).astype(int)\n\n rr, cc = np.mgrid[:N, :M]\n if mask is not None:\n rr, cc = rr[mask], cc[mask]\n r, c = [x.ravel()[:,np.newaxis] for x in (rr, cc)]\n dx, dy, w, h = feature_params.T\n R0 = cleanse(r + (dy - h/2.) * sy, N - 1)\n R1 = cleanse(r + (dy + h/2.) * sy, N - 1)\n C0 = cleanse(c + (dx - w/2.) * sx, M - 1)\n C1 = cleanse(c + (dx + w/2.) * sx, M - 1)\n return integral_image_mean(ii, R0, C0, R1, C1).reshape(-1, n_features)\n"
] | [
[
"matplotlib.patches.Arrow",
"matplotlib.patches.Rectangle",
"numpy.cos",
"numpy.sin",
"numpy.random.uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
huster-wgm/mmsegmentation | [
"b46bbfdeed127b1cab325f707c090014f9333c11"
] | [
"tools/onnx2tensorrt.py"
] | [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport argparse\nimport os\nimport os.path as osp\nfrom typing import Iterable, Optional, Union\n\nimport matplotlib.pyplot as plt\nimport mmcv\nimport numpy as np\nimport onnxruntime as ort\nimport torch\nfrom mmcv.ops import get_onnxruntime_op_path\nfrom mmcv.tensorrt import (TRTWraper, is_tensorrt_plugin_loaded, onnx2trt,\n save_trt_engine)\n\nfrom mmseg.apis.inference import LoadImage\nfrom mmseg.datasets import DATASETS\nfrom mmseg.datasets.pipelines import Compose\n\n\ndef get_GiB(x: int):\n \"\"\"return x GiB.\"\"\"\n return x * (1 << 30)\n\n\ndef _prepare_input_img(img_path: str,\n test_pipeline: Iterable[dict],\n shape: Optional[Iterable] = None,\n rescale_shape: Optional[Iterable] = None) -> dict:\n # build the data pipeline\n if shape is not None:\n test_pipeline[1]['img_scale'] = (shape[1], shape[0])\n test_pipeline[1]['transforms'][0]['keep_ratio'] = False\n test_pipeline = [LoadImage()] + test_pipeline[1:]\n test_pipeline = Compose(test_pipeline)\n # prepare data\n data = dict(img=img_path)\n data = test_pipeline(data)\n imgs = data['img']\n img_metas = [i.data for i in data['img_metas']]\n\n if rescale_shape is not None:\n for img_meta in img_metas:\n img_meta['ori_shape'] = tuple(rescale_shape) + (3, )\n\n mm_inputs = {'imgs': imgs, 'img_metas': img_metas}\n\n return mm_inputs\n\n\ndef _update_input_img(img_list: Iterable, img_meta_list: Iterable):\n # update img and its meta list\n N = img_list[0].size(0)\n img_meta = img_meta_list[0][0]\n img_shape = img_meta['img_shape']\n ori_shape = img_meta['ori_shape']\n pad_shape = img_meta['pad_shape']\n new_img_meta_list = [[{\n 'img_shape':\n img_shape,\n 'ori_shape':\n ori_shape,\n 'pad_shape':\n pad_shape,\n 'filename':\n img_meta['filename'],\n 'scale_factor':\n (img_shape[1] / ori_shape[1], img_shape[0] / ori_shape[0]) * 2,\n 'flip':\n False,\n } for _ in range(N)]]\n\n return img_list, new_img_meta_list\n\n\ndef show_result_pyplot(img: Union[str, np.ndarray],\n result: np.ndarray,\n palette: Optional[Iterable] = None,\n fig_size: Iterable[int] = (15, 10),\n opacity: float = 0.5,\n title: str = '',\n block: bool = True):\n img = mmcv.imread(img)\n img = img.copy()\n seg = result[0]\n seg = mmcv.imresize(seg, img.shape[:2][::-1])\n palette = np.array(palette)\n assert palette.shape[1] == 3\n assert len(palette.shape) == 2\n assert 0 < opacity <= 1.0\n color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8)\n for label, color in enumerate(palette):\n color_seg[seg == label, :] = color\n # convert to BGR\n color_seg = color_seg[..., ::-1]\n\n img = img * (1 - opacity) + color_seg * opacity\n img = img.astype(np.uint8)\n\n plt.figure(figsize=fig_size)\n plt.imshow(mmcv.bgr2rgb(img))\n plt.title(title)\n plt.tight_layout()\n plt.show(block=block)\n\n\ndef onnx2tensorrt(onnx_file: str,\n trt_file: str,\n config: dict,\n input_config: dict,\n fp16: bool = False,\n verify: bool = False,\n show: bool = False,\n dataset: str = 'CityscapesDataset',\n workspace_size: int = 1,\n verbose: bool = False):\n import tensorrt as trt\n min_shape = input_config['min_shape']\n max_shape = input_config['max_shape']\n # create trt engine and wraper\n opt_shape_dict = {'input': [min_shape, min_shape, max_shape]}\n max_workspace_size = get_GiB(workspace_size)\n trt_engine = onnx2trt(\n onnx_file,\n opt_shape_dict,\n log_level=trt.Logger.VERBOSE if verbose else trt.Logger.ERROR,\n fp16_mode=fp16,\n max_workspace_size=max_workspace_size)\n save_dir, _ = osp.split(trt_file)\n if save_dir:\n os.makedirs(save_dir, exist_ok=True)\n save_trt_engine(trt_engine, trt_file)\n print(f'Successfully created TensorRT engine: {trt_file}')\n\n if verify:\n inputs = _prepare_input_img(\n input_config['input_path'],\n config.data.test.pipeline,\n shape=min_shape[2:])\n\n imgs = inputs['imgs']\n img_metas = inputs['img_metas']\n img_list = [img[None, :] for img in imgs]\n img_meta_list = [[img_meta] for img_meta in img_metas]\n # update img_meta\n img_list, img_meta_list = _update_input_img(img_list, img_meta_list)\n\n if max_shape[0] > 1:\n # concate flip image for batch test\n flip_img_list = [_.flip(-1) for _ in img_list]\n img_list = [\n torch.cat((ori_img, flip_img), 0)\n for ori_img, flip_img in zip(img_list, flip_img_list)\n ]\n\n # Get results from ONNXRuntime\n ort_custom_op_path = get_onnxruntime_op_path()\n session_options = ort.SessionOptions()\n if osp.exists(ort_custom_op_path):\n session_options.register_custom_ops_library(ort_custom_op_path)\n sess = ort.InferenceSession(onnx_file, session_options)\n sess.set_providers(['CPUExecutionProvider'], [{}]) # use cpu mode\n onnx_output = sess.run(['output'],\n {'input': img_list[0].detach().numpy()})[0][0]\n\n # Get results from TensorRT\n trt_model = TRTWraper(trt_file, ['input'], ['output'])\n with torch.no_grad():\n trt_outputs = trt_model({'input': img_list[0].contiguous().cuda()})\n trt_output = trt_outputs['output'][0].cpu().detach().numpy()\n\n if show:\n dataset = DATASETS.get(dataset)\n assert dataset is not None\n palette = dataset.PALETTE\n\n show_result_pyplot(\n input_config['input_path'],\n (onnx_output[0].astype(np.uint8), ),\n palette=palette,\n title='ONNXRuntime',\n block=False)\n show_result_pyplot(\n input_config['input_path'], (trt_output[0].astype(np.uint8), ),\n palette=palette,\n title='TensorRT')\n\n np.testing.assert_allclose(\n onnx_output, trt_output, rtol=1e-03, atol=1e-05)\n print('TensorRT and ONNXRuntime output all close.')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='Convert MMSegmentation models from ONNX to TensorRT')\n parser.add_argument('config', help='Config file of the model')\n parser.add_argument('model', help='Path to the input ONNX model')\n parser.add_argument(\n '--trt-file', type=str, help='Path to the output TensorRT engine')\n parser.add_argument(\n '--max-shape',\n type=int,\n nargs=4,\n default=[1, 3, 400, 600],\n help='Maximum shape of model input.')\n parser.add_argument(\n '--min-shape',\n type=int,\n nargs=4,\n default=[1, 3, 400, 600],\n help='Minimum shape of model input.')\n parser.add_argument('--fp16', action='store_true', help='Enable fp16 mode')\n parser.add_argument(\n '--workspace-size',\n type=int,\n default=1,\n help='Max workspace size in GiB')\n parser.add_argument(\n '--input-img', type=str, default='', help='Image for test')\n parser.add_argument(\n '--show', action='store_true', help='Whether to show output results')\n parser.add_argument(\n '--dataset',\n type=str,\n default='CityscapesDataset',\n help='Dataset name')\n parser.add_argument(\n '--verify',\n action='store_true',\n help='Verify the outputs of ONNXRuntime and TensorRT')\n parser.add_argument(\n '--verbose',\n action='store_true',\n help='Whether to verbose logging messages while creating \\\n TensorRT engine.')\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n\n assert is_tensorrt_plugin_loaded(), 'TensorRT plugin should be compiled.'\n args = parse_args()\n\n if not args.input_img:\n args.input_img = osp.join(osp.dirname(__file__), '../demo/demo.png')\n\n # check arguments\n assert osp.exists(args.config), 'Config {} not found.'.format(args.config)\n assert osp.exists(args.model), \\\n 'ONNX model {} not found.'.format(args.model)\n assert args.workspace_size >= 0, 'Workspace size less than 0.'\n assert DATASETS.get(args.dataset) is not None, \\\n 'Dataset {} does not found.'.format(args.dataset)\n for max_value, min_value in zip(args.max_shape, args.min_shape):\n assert max_value >= min_value, \\\n 'max_shape sould be larger than min shape'\n\n input_config = {\n 'min_shape': args.min_shape,\n 'max_shape': args.max_shape,\n 'input_path': args.input_img\n }\n\n cfg = mmcv.Config.fromfile(args.config)\n onnx2tensorrt(\n args.model,\n args.trt_file,\n cfg,\n input_config,\n fp16=args.fp16,\n verify=args.verify,\n show=args.show,\n dataset=args.dataset,\n workspace_size=args.workspace_size,\n verbose=args.verbose)\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"torch.cat",
"torch.no_grad",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jens321/allennlp-models | [
"cee3a7507cf8d15cd8520808bd9c6381369e868e"
] | [
"tests/rc/qanet/stacked_self_attention_test.py"
] | [
"import torch\nfrom torch.nn.parallel.data_parallel import DataParallel\n\nimport pytest\n\nfrom allennlp.common.testing import AllenNlpTestCase\n\nfrom allennlp_models.rc.qanet.stacked_self_attention import StackedSelfAttentionEncoder\n\n\nclass TestStackedSelfAttention(AllenNlpTestCase):\n def test_get_dimension_is_correct(self):\n encoder = StackedSelfAttentionEncoder(\n input_dim=9,\n hidden_dim=12,\n projection_dim=6,\n feedforward_hidden_dim=5,\n num_layers=3,\n num_attention_heads=3,\n )\n assert encoder.get_input_dim() == 9\n # hidden_dim + projection_dim\n assert encoder.get_output_dim() == 12\n\n def test_stacked_self_attention_can_run_foward(self):\n # Correctness checks are elsewhere - this is just stacking\n # blocks which are already well tested, so we just check shapes.\n encoder = StackedSelfAttentionEncoder(\n input_dim=9,\n hidden_dim=12,\n projection_dim=9,\n feedforward_hidden_dim=5,\n num_layers=3,\n num_attention_heads=3,\n )\n inputs = torch.randn([3, 5, 9])\n encoder_output = encoder(inputs, None)\n assert list(encoder_output.size()) == [3, 5, 12]\n\n @pytest.mark.skipif(torch.cuda.device_count() < 2, reason=\"Need multiple GPUs.\")\n def test_stacked_self_attention_can_run_foward_on_multiple_gpus(self):\n encoder = StackedSelfAttentionEncoder(\n input_dim=9,\n hidden_dim=12,\n projection_dim=9,\n feedforward_hidden_dim=5,\n num_layers=3,\n num_attention_heads=3,\n ).to(0)\n parallel_encoder = DataParallel(encoder, device_ids=[0, 1])\n inputs = torch.randn([3, 5, 9]).to(0)\n encoder_output = parallel_encoder(inputs, None)\n assert list(encoder_output.size()) == [3, 5, 12]\n"
] | [
[
"torch.randn",
"torch.cuda.device_count",
"torch.nn.parallel.data_parallel.DataParallel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zshyang/FieldConvolution | [
"ca88df568a6f2143dcb85d22c005fce4562a7523"
] | [
"SDFConv/data_code/generate_size_meta.py"
] | [
"import os\nimport shutil\nimport trimesh\nimport json\nimport numpy as np\n\nfrom glob import glob\nfrom tqdm import tqdm\n\n\nleft_mesh_name = \"LHippo_60k.obj\"\nright_mesh_name = \"RHippo_60k.obj\"\n\n\ndef move_meta():\n meta_folder_path = os.path.join(\"..\", \"..\", \"PointNetBaseline\", \"data\", \"meta\")\n meta_folder_path = os.path.abspath(meta_folder_path)\n\n target_folder_path = os.path.join(\"../data/meta\")\n target_folder_path = os.path.abspath(target_folder_path)\n\n shutil.copytree(meta_folder_path, target_folder_path)\n\n\ndef load_merge_left_right_mesh(mesh_root, stage, identity):\n # get the name of the mesh\n left_mesh_name_ = os.path.join(\n mesh_root, stage, identity, left_mesh_name\n )\n right_mesh_name_ = os.path.join(\n mesh_root, stage, identity, right_mesh_name\n )\n\n # load the mesh\n dict_args = {\"process\": False}\n left_mesh = trimesh.load(left_mesh_name_, **dict_args)\n right_mesh = trimesh.load(right_mesh_name_, **dict_args)\n\n # concatenate the vertices\n left_vertices = np.array(left_mesh.vertices, dtype=np.float32)\n right_vertices = np.array(right_mesh.vertices, dtype=np.float32)\n vertices = np.concatenate((left_vertices, right_vertices), axis=0)\n\n # concatenate the faces\n left_faces = np.array(left_mesh.faces, dtype=np.int)\n right_faces = np.array(right_mesh.faces, dtype=np.int)\n faces = np.concatenate([left_faces, right_faces + left_vertices.shape[0]], axis=0)\n\n mesh = trimesh.Trimesh(\n vertices=vertices, faces=faces, process=False\n )\n\n return mesh\n\n\ndef generate_meta_size():\n # get the name to save the size meta\n meta_folder = os.path.join(\"../data/meta\")\n meta_folder = os.path.abspath(meta_folder)\n meta_fn = os.path.join(meta_folder, \"size.json\") # fn is filename.\n\n # gather the list of identity\n stage_identity_list = glob(\"/home/exx/georgey/dataset/hippocampus/obj/*/*\")\n mesh_root = os.path.join(\"/home/exx/georgey/dataset/hippocampus/obj\")\n radius_dict = dict()\n\n # go over the mesh files\n for stage_identity in tqdm(stage_identity_list):\n\n # load and merge the mesh\n stage = stage_identity.split(\"/\")[-2]\n identity = stage_identity.split(\"/\")[-1]\n mesh = load_merge_left_right_mesh(mesh_root, stage, identity)\n\n # compute the bounding box radius\n vertices = np.array(mesh.vertices, dtype=np.float32)\n vertices = vertices - np.expand_dims(np.mean(vertices, axis=0), 0) # center\n dist = np.max(np.sqrt(np.sum(vertices ** 2, axis=1)), 0)\n\n # save the radius, stage, and identity in to dict.\n if stage not in radius_dict:\n radius_dict[stage] = dict()\n if identity not in radius_dict[stage]:\n radius_dict[stage][identity] = str(dist)\n else:\n if identity not in radius_dict[stage]:\n radius_dict[stage][identity] = str(dist)\n\n # save the json.\n with open(meta_fn, \"w\") as file:\n json.dump(radius_dict, file)\n\n\ndef main():\n moved = True\n if not moved:\n move_meta()\n\n # generate the size meta.\n generated = True\n if not generated:\n generate_meta_size()\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.concatenate",
"numpy.array",
"numpy.mean",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
goldentom42/py_ml_utils | [
"95a2788dd78b38d13f2c7c0e311319aac48f028a"
] | [
"py_ml_utils/test/test_featureSelector.py"
] | [
"from unittest import TestCase\nfrom py_ml_utils.feature_transformer import *\nfrom py_ml_utils.feature_selector import *\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import datasets\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import log_loss, accuracy_score\nfrom itertools import combinations\n\n\nclass TestFeatureSelector(TestCase):\n\n def test_feature_selection_with_importances_log_loss(self):\n \"\"\" Test FeatureSelector with the iris dataset and log_loss metric\n This also checks feature importance works \"\"\"\n iris_dataset = datasets.load_iris()\n\n folds = StratifiedKFold(n_splits=2, shuffle=True, random_state=3)\n features = [\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"]\n dataset = pd.DataFrame(iris_dataset.data, columns=features)\n for f1, f2 in combinations(features, 2):\n dataset[f1 + \"_/_\" + f2] = dataset[f1] / dataset[f2]\n\n for f1, f2 in combinations(features, 2):\n dataset[f1 + \"_*_\" + f2] = dataset[f1] * dataset[f2]\n\n tf_pairs = []\n for f_ in dataset.columns:\n tf_pairs.append(\n FeatureTransformationPair(\n transformer=IdentityTransformation(feature_name=f_),\n missing_inferer=None\n )\n )\n tf_pairs.append(\n FeatureTransformationPair(\n transformer=ShadowTransformation(feature_name=f_),\n missing_inferer=None\n )\n )\n\n fs = FeatureSelector(max_features=.5, max_runs=20)\n\n clf = RandomForestClassifier(n_estimators=50,\n max_depth=7,\n max_features=.2,\n criterion=\"entropy\",\n random_state=None,\n n_jobs=-1)\n np.random.seed(10)\n scores = fs.select(dataset=dataset,\n target=pd.Series(iris_dataset.target, name=\"iris_class\"),\n pairs=tf_pairs,\n estimator=clf,\n metric=log_loss,\n probability=True,\n folds=folds,\n maximize=False)\n\n scores.sort_values(by=\"importance_mean\", ascending=False, inplace=True)\n self.assertAlmostEqual(0.1743180, scores.importance_mean.values[0], places=6)\n self.assertEqual(\"petal_length_*_petal_width\", scores.feature.values[0])\n\n def test_feature_selection_without_importances_log_loss(self):\n \"\"\" Test FeatureSelector with the iris dataset and log_loss metric with a classifier that does not\n provide feature_importances \"\"\"\n iris_dataset = datasets.load_iris()\n\n folds = StratifiedKFold(n_splits=2, shuffle=True, random_state=3)\n features = [\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"]\n dataset = pd.DataFrame(iris_dataset.data, columns=features)\n for f1, f2 in combinations(features, 2):\n dataset[f1 + \"_/_\" + f2] = dataset[f1] / dataset[f2]\n\n for f1, f2 in combinations(features, 2):\n dataset[f1 + \"_*_\" + f2] = dataset[f1] * dataset[f2]\n\n tf_pairs = []\n for f_ in dataset.columns:\n tf_pairs.append(\n FeatureTransformationPair(\n transformer=IdentityTransformation(feature_name=f_),\n missing_inferer=None\n )\n )\n tf_pairs.append(\n FeatureTransformationPair(\n transformer=ShadowTransformation(feature_name=f_),\n missing_inferer=None\n )\n )\n\n fs = FeatureSelector(max_features=.5, max_runs=100)\n\n clf = LogisticRegression()\n\n np.random.seed(10)\n scores = fs.select(dataset=dataset,\n target=pd.Series(iris_dataset.target, name=\"iris_class\"),\n pairs=tf_pairs,\n estimator=clf,\n metric=log_loss,\n probability=True,\n folds=folds,\n maximize=False)\n\n # scores.sort_values(by=\"score\", ascending=True, inplace=True)\n self.assertAlmostEqual(0.13078, scores.score.values[0], places=5)\n self.assertEqual(\"petal_length_*_petal_width\", scores.feature.values[0])\n\n def test_feature_selection_without_importances_accuracy(self):\n \"\"\" Test feature selector with iris dataset and accuracy metric\n This also checks maximize and probability arguments \"\"\"\n iris_dataset = datasets.load_iris()\n\n folds = StratifiedKFold(n_splits=2, shuffle=True, random_state=3)\n features = [\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\"]\n dataset = pd.DataFrame(iris_dataset.data, columns=features)\n for f1, f2 in combinations(features, 2):\n dataset[f1 + \"_/_\" + f2] = dataset[f1] / dataset[f2]\n\n for f1, f2 in combinations(features, 2):\n dataset[f1 + \"_*_\" + f2] = dataset[f1] * dataset[f2]\n\n tf_pairs = []\n for f_ in dataset.columns:\n tf_pairs.append(\n FeatureTransformationPair(\n transformer=IdentityTransformation(feature_name=f_),\n missing_inferer=None\n )\n )\n tf_pairs.append(\n FeatureTransformationPair(\n transformer=ShadowTransformation(feature_name=f_),\n missing_inferer=None\n )\n )\n\n fs = FeatureSelector(max_features=.5, max_runs=100)\n\n clf = LogisticRegression()\n\n np.random.seed(10)\n scores = fs.select(dataset=dataset,\n target=pd.Series(iris_dataset.target, name=\"iris_class\"),\n pairs=tf_pairs,\n estimator=clf,\n metric=accuracy_score,\n probability=False,\n folds=folds,\n maximize=True)\n # scores are expected to be sorted in descending order using the score column\n self.assertAlmostEqual(0.951818, scores.score.values[0], places=6)\n self.assertEqual(\"petal_length_*_petal_width\", scores.feature.values[0])\n"
] | [
[
"sklearn.datasets.load_iris",
"sklearn.model_selection.StratifiedKFold",
"sklearn.ensemble.RandomForestClassifier"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nvnovitskiy/python_sstu_course | [
"5de1830eb4430349df8ab1c65a9f16f82a9b91a6"
] | [
"chapter4/task12.py"
] | [
"import numpy as np\n\n\"\"\"\nЗаполнить последовательными натуральными числами прямоугольную матрицу \nиз n строк и m столбцов. Получить и вывести на экран транспонированную \nматрицу. Пример: A = [[1,2,3],[4,5,6]], тогда A^T= [[1, 4], [2, 5], [3, 6]].\n\"\"\"\n\nlines, columns = map(int, input(\"Введите количество строк и столбцов: \").split())\nmatrix = np.random.randint(0, 64, size=(lines, columns))\nprint(f\"Начальная матрица: \\n {matrix}\")\nprint(f\"Транспонированная матрица: \\n {matrix.T}\")\n"
] | [
[
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chenxinfeng4/mmdetection | [
"c72bc707e661d61cf09aca0a53ad21812ef874d0"
] | [
"mmdet/datasets/custom.py"
] | [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport os.path as osp\nimport warnings\nfrom collections import OrderedDict\n\nimport mmcv\nimport numpy as np\nfrom mmcv.utils import print_log\nfrom terminaltables import AsciiTable\nfrom torch.utils.data import Dataset\n\nfrom mmdet.core import eval_map, eval_recalls\nfrom .builder import DATASETS\nfrom .pipelines import Compose\n\n\[email protected]_module()\nclass CustomDataset(Dataset):\n \"\"\"Custom dataset for detection.\n\n The annotation format is shown as follows. The `ann` field is optional for\n testing.\n\n .. code-block:: none\n\n [\n {\n 'filename': 'a.jpg',\n 'width': 1280,\n 'height': 720,\n 'ann': {\n 'bboxes': <np.ndarray> (n, 4) in (x1, y1, x2, y2) order.\n 'labels': <np.ndarray> (n, ),\n 'bboxes_ignore': <np.ndarray> (k, 4), (optional field)\n 'labels_ignore': <np.ndarray> (k, 4) (optional field)\n }\n },\n ...\n ]\n\n Args:\n ann_file (str): Annotation file path.\n pipeline (list[dict]): Processing pipeline.\n classes (str | Sequence[str], optional): Specify classes to load.\n If is None, ``cls.CLASSES`` will be used. Default: None.\n data_root (str, optional): Data root for ``ann_file``,\n ``img_prefix``, ``seg_prefix``, ``proposal_file`` if specified.\n test_mode (bool, optional): If set True, annotation will not be loaded.\n filter_empty_gt (bool, optional): If set true, images without bounding\n boxes of the dataset's classes will be filtered out. This option\n only works when `test_mode=False`, i.e., we never filter images\n during tests.\n \"\"\"\n\n CLASSES = None\n\n PALETTE = None\n\n def __init__(self,\n ann_file,\n pipeline,\n classes=None,\n data_root=None,\n img_prefix='',\n seg_prefix=None,\n proposal_file=None,\n test_mode=False,\n filter_empty_gt=True,\n file_client_args=dict(backend='disk')):\n self.ann_file = ann_file\n self.data_root = data_root\n self.img_prefix = img_prefix\n self.seg_prefix = seg_prefix\n self.proposal_file = proposal_file\n self.test_mode = test_mode\n self.filter_empty_gt = filter_empty_gt\n self.file_client = mmcv.FileClient(**file_client_args)\n self.CLASSES = self.get_classes(classes)\n\n # join paths if data_root is specified\n if self.data_root is not None:\n if not osp.isabs(self.ann_file):\n self.ann_file = osp.join(self.data_root, self.ann_file)\n if not (self.img_prefix is None or osp.isabs(self.img_prefix)):\n self.img_prefix = osp.join(self.data_root, self.img_prefix)\n if not (self.seg_prefix is None or osp.isabs(self.seg_prefix)):\n self.seg_prefix = osp.join(self.data_root, self.seg_prefix)\n if not (self.proposal_file is None\n or osp.isabs(self.proposal_file)):\n self.proposal_file = osp.join(self.data_root,\n self.proposal_file)\n # load annotations (and proposals)\n if hasattr(self.file_client, 'get_local_path'):\n with self.file_client.get_local_path(self.ann_file) as local_path:\n self.data_infos = self.load_annotations(local_path)\n else:\n warnings.warn(\n 'The used MMCV version does not have get_local_path. '\n f'We treat the {self.ann_file} as local paths and it '\n 'might cause errors if the path is not a local path. '\n 'Please use MMCV>= 1.3.16 if you meet errors.')\n self.data_infos = self.load_annotations(self.ann_file)\n\n if self.proposal_file is not None:\n if hasattr(self.file_client, 'get_local_path'):\n with self.file_client.get_local_path(\n self.proposal_file) as local_path:\n self.proposals = self.load_proposals(local_path)\n else:\n warnings.warn(\n 'The used MMCV version does not have get_local_path. '\n f'We treat the {self.ann_file} as local paths and it '\n 'might cause errors if the path is not a local path. '\n 'Please use MMCV>= 1.3.16 if you meet errors.')\n self.proposals = self.load_proposals(self.proposal_file)\n else:\n self.proposals = None\n\n # filter images too small and containing no annotations\n if not test_mode:\n valid_inds = self._filter_imgs()\n self.data_infos = [self.data_infos[i] for i in valid_inds]\n if self.proposals is not None:\n self.proposals = [self.proposals[i] for i in valid_inds]\n # set group flag for the sampler\n self._set_group_flag()\n\n # processing pipeline\n self.pipeline = Compose(pipeline)\n\n def __len__(self):\n \"\"\"Total number of samples of data.\"\"\"\n return len(self.data_infos)\n\n def load_annotations(self, ann_file):\n \"\"\"Load annotation from annotation file.\"\"\"\n return mmcv.load(ann_file)\n\n def load_proposals(self, proposal_file):\n \"\"\"Load proposal from proposal file.\"\"\"\n return mmcv.load(proposal_file)\n\n def get_ann_info(self, idx):\n \"\"\"Get annotation by index.\n\n Args:\n idx (int): Index of data.\n\n Returns:\n dict: Annotation info of specified index.\n \"\"\"\n\n return self.data_infos[idx]['ann']\n\n def get_cat_ids(self, idx):\n \"\"\"Get category ids by index.\n\n Args:\n idx (int): Index of data.\n\n Returns:\n list[int]: All categories in the image of specified index.\n \"\"\"\n\n return self.data_infos[idx]['ann']['labels'].astype(np.int).tolist()\n\n def pre_pipeline(self, results):\n \"\"\"Prepare results dict for pipeline.\"\"\"\n results['img_prefix'] = self.img_prefix\n results['seg_prefix'] = self.seg_prefix\n results['proposal_file'] = self.proposal_file\n results['bbox_fields'] = []\n results['mask_fields'] = []\n results['seg_fields'] = []\n\n def _filter_imgs(self, min_size=32):\n \"\"\"Filter images too small.\"\"\"\n if self.filter_empty_gt:\n warnings.warn(\n 'CustomDataset does not support filtering empty gt images.')\n valid_inds = []\n for i, img_info in enumerate(self.data_infos):\n if min(img_info['width'], img_info['height']) >= min_size:\n valid_inds.append(i)\n return valid_inds\n\n def _set_group_flag(self):\n \"\"\"Set flag according to image aspect ratio.\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0.\n \"\"\"\n self.flag = np.zeros(len(self), dtype=np.uint8)\n for i in range(len(self)):\n img_info = self.data_infos[i]\n if img_info['width'] / img_info['height'] > 1:\n self.flag[i] = 1\n\n def _rand_another(self, idx):\n \"\"\"Get another random index from the same group as the given index.\"\"\"\n pool = np.where(self.flag == self.flag[idx])[0]\n return np.random.choice(pool)\n\n def __getitem__(self, idx):\n \"\"\"Get training/test data after pipeline.\n\n Args:\n idx (int): Index of data.\n\n Returns:\n dict: Training/test data (with annotation if `test_mode` is set \\\n True).\n \"\"\"\n\n if self.test_mode:\n return self.prepare_test_img(idx)\n while True:\n data = self.prepare_train_img(idx)\n if data is None:\n idx = self._rand_another(idx)\n continue\n return data\n\n def prepare_train_img(self, idx):\n \"\"\"Get training data and annotations after pipeline.\n\n Args:\n idx (int): Index of data.\n\n Returns:\n dict: Training data and annotation after pipeline with new keys \\\n introduced by pipeline.\n \"\"\"\n\n img_info = self.data_infos[idx]\n ann_info = self.get_ann_info(idx)\n results = dict(img_info=img_info, ann_info=ann_info)\n if self.proposals is not None:\n results['proposals'] = self.proposals[idx]\n self.pre_pipeline(results)\n return self.pipeline(results)\n\n def prepare_test_img(self, idx):\n \"\"\"Get testing data after pipeline.\n\n Args:\n idx (int): Index of data.\n\n Returns:\n dict: Testing data after pipeline with new keys introduced by \\\n pipeline.\n \"\"\"\n\n img_info = self.data_infos[idx]\n results = dict(img_info=img_info)\n if self.proposals is not None:\n results['proposals'] = self.proposals[idx]\n self.pre_pipeline(results)\n return self.pipeline(results)\n\n @classmethod\n def get_classes(cls, classes=None):\n \"\"\"Get class names of current dataset.\n\n Args:\n classes (Sequence[str] | str | None): If classes is None, use\n default CLASSES defined by builtin dataset. If classes is a\n string, take it as a file name. The file contains the name of\n classes where each line contains one class name. If classes is\n a tuple or list, override the CLASSES defined by the dataset.\n\n Returns:\n tuple[str] or list[str]: Names of categories of the dataset.\n \"\"\"\n if classes is None:\n return cls.CLASSES\n\n if isinstance(classes, str):\n # take it as a file path\n class_names = mmcv.list_from_file(classes)\n elif isinstance(classes, (tuple, list)):\n class_names = classes\n else:\n raise ValueError(f'Unsupported type {type(classes)} of classes.')\n\n return class_names\n\n def format_results(self, results, **kwargs):\n \"\"\"Place holder to format result to dataset specific output.\"\"\"\n\n def evaluate(self,\n results,\n metric='mAP',\n logger=None,\n proposal_nums=(100, 300, 1000),\n iou_thr=0.5,\n scale_ranges=None):\n \"\"\"Evaluate the dataset.\n\n Args:\n results (list): Testing results of the dataset.\n metric (str | list[str]): Metrics to be evaluated.\n logger (logging.Logger | None | str): Logger used for printing\n related information during evaluation. Default: None.\n proposal_nums (Sequence[int]): Proposal number used for evaluating\n recalls, such as recall@100, recall@1000.\n Default: (100, 300, 1000).\n iou_thr (float | list[float]): IoU threshold. Default: 0.5.\n scale_ranges (list[tuple] | None): Scale ranges for evaluating mAP.\n Default: None.\n \"\"\"\n\n if not isinstance(metric, str):\n assert len(metric) == 1\n metric = metric[0]\n allowed_metrics = ['mAP', 'recall']\n if metric not in allowed_metrics:\n raise KeyError(f'metric {metric} is not supported')\n annotations = [self.get_ann_info(i) for i in range(len(self))]\n eval_results = OrderedDict()\n iou_thrs = [iou_thr] if isinstance(iou_thr, float) else iou_thr\n if metric == 'mAP':\n assert isinstance(iou_thrs, list)\n mean_aps = []\n for iou_thr in iou_thrs:\n print_log(f'\\n{\"-\" * 15}iou_thr: {iou_thr}{\"-\" * 15}')\n mean_ap, _ = eval_map(\n results,\n annotations,\n scale_ranges=scale_ranges,\n iou_thr=iou_thr,\n dataset=self.CLASSES,\n logger=logger)\n mean_aps.append(mean_ap)\n eval_results[f'AP{int(iou_thr * 100):02d}'] = round(mean_ap, 3)\n eval_results['mAP'] = sum(mean_aps) / len(mean_aps)\n elif metric == 'recall':\n gt_bboxes = [ann['bboxes'] for ann in annotations]\n recalls = eval_recalls(\n gt_bboxes, results, proposal_nums, iou_thr, logger=logger)\n for i, num in enumerate(proposal_nums):\n for j, iou in enumerate(iou_thrs):\n eval_results[f'recall@{num}@{iou}'] = recalls[i, j]\n if recalls.shape[1] > 1:\n ar = recalls.mean(axis=1)\n for i, num in enumerate(proposal_nums):\n eval_results[f'AR@{num}'] = ar[i]\n return eval_results\n\n def __repr__(self):\n \"\"\"Print the number of instance number.\"\"\"\n dataset_type = 'Test' if self.test_mode else 'Train'\n result = (f'\\n{self.__class__.__name__} {dataset_type} dataset '\n f'with number of images {len(self)}, '\n f'and instance counts: \\n')\n if self.CLASSES is None:\n result += 'Category names are not provided. \\n'\n return result\n instance_count = np.zeros(len(self.CLASSES) + 1).astype(int)\n # count the instance number in each image\n for idx in range(len(self)):\n label = self.get_ann_info(idx)['labels']\n unique, counts = np.unique(label, return_counts=True)\n if len(unique) > 0:\n # add the occurrence number to each class\n instance_count[unique] += counts\n else:\n # background is the last index\n instance_count[-1] += 1\n # create a table with category count\n table_data = [['category', 'count'] * 5]\n row_data = []\n for cls, count in enumerate(instance_count):\n if cls < len(self.CLASSES):\n row_data += [f'{cls} [{self.CLASSES[cls]}]', f'{count}']\n else:\n # add the background number\n row_data += ['-1 background', f'{count}']\n if len(row_data) == 10:\n table_data.append(row_data)\n row_data = []\n if len(row_data) >= 2:\n if row_data[-1] == '0':\n row_data = row_data[:-2]\n if len(row_data) >= 2:\n table_data.append([])\n table_data.append(row_data)\n\n table = AsciiTable(table_data)\n result += table.table\n return result\n"
] | [
[
"numpy.where",
"numpy.unique",
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RamiSketcher/pddm | [
"54ef66e50c2b7ccbefb31c4dfe45c6e94718f71d"
] | [
"pddm/spinup/pddm_envs/mujoco_env.py"
] | [
"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\"\"\"Base environment for MuJoCo-based environments.\"\"\"\n\nimport collections\nimport os\nimport time\nfrom typing import Dict, Optional\n\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport numpy as np\n\nfrom spinup.pddm_envs.simulation.sim_robot import MujocoSimRobot, RenderMode\n\nDEFAULT_RENDER_SIZE = 480\n\nclass MujocoEnv(gym.Env):\n \"\"\"Superclass for all MuJoCo environments.\"\"\"\n\n def __init__(self,\n model_path: str,\n frame_skip: int,\n camera_settings: Optional[Dict] = None,\n ):\n \"\"\"Initializes a new MuJoCo environment.\n\n Args:\n model_path: The path to the MuJoCo XML file.\n frame_skip: The number of simulation steps per environment step. On\n hardware this influences the duration of each environment step.\n camera_settings: Settings to initialize the simulation camera. This\n can contain the keys `distance`, `azimuth`, and `elevation`.\n \"\"\"\n self._seed()\n if not os.path.isfile(model_path):\n raise IOError(\n '[MujocoEnv]: Model path does not exist: {}'.format(model_path))\n self.frame_skip = frame_skip\n\n self.sim_robot = MujocoSimRobot(\n model_path,\n camera_settings=camera_settings)\n self.sim = self.sim_robot.sim\n self.model = self.sim_robot.model\n self.data = self.sim_robot.data\n\n self.metadata = {\n 'render.modes': ['human', 'rgb_array', 'depth_array'],\n 'video.frames_per_second': int(np.round(1.0 / self.dt))\n }\n self.mujoco_render_frames = False\n\n self.init_qpos = self.data.qpos.ravel().copy()\n self.init_qvel = self.data.qvel.ravel().copy()\n observation, _reward, done, _info = self.step(np.zeros(self.model.nu))\n assert not done\n\n bounds = self.model.actuator_ctrlrange.copy()\n act_upper = bounds[:, 1]\n act_lower = bounds[:, 0]\n\n # Define the action and observation spaces.\n # HACK: MJRL is still using gym 0.9.x so we can't provide a dtype.\n try:\n self.action_space = spaces.Box(\n act_lower, act_upper, dtype=np.float32)\n if isinstance(observation, collections.Mapping):\n self.observation_space = spaces.Dict({\n k: spaces.Box(-np.inf, np.inf, shape=v.shape, dtype=np.float32) for k, v in observation.items()})\n else:\n self.obs_dim = np.sum([o.size for o in observation]) if type(observation) is tuple else observation.size\n self.observation_space = spaces.Box(\n -np.inf, np.inf, observation.shape, dtype=np.float32)\n\n except TypeError:\n # Fallback case for gym 0.9.x\n self.action_space = spaces.Box(act_lower, act_upper)\n assert not isinstance(observation, collections.Mapping), 'gym 0.9.x does not support dictionary observation.'\n self.obs_dim = np.sum([o.size for o in observation]) if type(observation) is tuple else observation.size\n self.observation_space = spaces.Box(\n -np.inf, np.inf, observation.shape)\n\n def seed(self, seed=None): # Compatibility with new gym\n return self._seed(seed)\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n # methods to override:\n # ----------------------------\n\n def reset_model(self):\n \"\"\"Reset the robot degrees of freedom (qpos and qvel).\n\n Implement this in each subclass.\n \"\"\"\n raise NotImplementedError\n\n # -----------------------------\n\n def reset(self): # compatibility with new gym\n return self._reset()\n\n def _reset(self):\n self.sim.reset()\n self.sim.forward()\n ob = self.reset_model()\n return ob\n\n def set_state(self, qpos, qvel):\n assert qpos.shape == (self.model.nq,) and qvel.shape == (self.model.nv,)\n state = self.sim.get_state()\n for i in range(self.model.nq):\n state.qpos[i] = qpos[i]\n for i in range(self.model.nv):\n state.qvel[i] = qvel[i]\n self.sim.set_state(state)\n self.sim.forward()\n\n @property\n def dt(self):\n return self.model.opt.timestep * self.frame_skip\n\n def do_simulation(self, ctrl, n_frames):\n for i in range(self.model.nu):\n self.sim.data.ctrl[i] = ctrl[i]\n\n for _ in range(n_frames):\n self.sim.step()\n\n # TODO(michaelahn): Remove this; render should be called separately.\n if self.mujoco_render_frames is True:\n self.mj_render()\n\n def render(self,\n mode='human',\n width=DEFAULT_RENDER_SIZE,\n height=DEFAULT_RENDER_SIZE,\n camera_id=-1):\n \"\"\"Renders the environment.\n\n Args:\n mode: The type of rendering to use.\n - 'human': Renders to a graphical window.\n - 'rgb_array': Returns the RGB image as an np.ndarray.\n - 'depth_array': Returns the depth image as an np.ndarray.\n width: The width of the rendered image. This only affects offscreen\n rendering.\n height: The height of the rendered image. This only affects\n offscreen rendering.\n camera_id: The ID of the camera to use. By default, this is the free\n camera. If specified, only affects offscreen rendering.\n \"\"\"\n if mode == 'human':\n self.sim_robot.renderer.render_to_window()\n elif mode == 'rgb_array':\n assert width and height\n return self.sim_robot.renderer.render_offscreen(\n width, height, mode=RenderMode.RGB, camera_id=camera_id)\n elif mode == 'depth_array':\n assert width and height\n return self.sim_robot.renderer.render_offscreen(\n width, height, mode=RenderMode.DEPTH, camera_id=camera_id)\n elif mode == 'segmentation':\n assert width and height\n return self.sim_robot.renderer.render_offscreen(\n width, height, mode=RenderMode.SEGMENTATION, camera_id=camera_id)\n else:\n raise NotImplementedError(mode)\n\n def close(self):\n self.sim_robot.close()\n\n def mj_render(self):\n \"\"\"Backwards compatibility with MJRL.\"\"\"\n self.render(mode='human')\n\n def state_vector(self):\n state = self.sim.get_state()\n return np.concatenate([state.qpos.flat, state.qvel.flat])\n\n # -----------------------------\n\n def visualize_policy(self,\n policy,\n horizon=1000,\n num_episodes=1,\n mode='exploration',\n env=None,\n render=True):\n if env is None:\n env = self\n self.mujoco_render_frames = render\n\n all_rewards = []\n all_scores_mean = []\n all_scores_last = []\n for ep in range(num_episodes):\n o = env.reset()\n d = False\n t = 0\n rew_for_ep = 0\n scores_for_ep = []\n while t < horizon and d is False:\n a = policy.get_action(\n o)[0] if mode == 'exploration' else policy.get_action(\n o)[1]['evaluation']\n o, r, d, info = env.step(a)\n if type(d)==np.float64:\n d = not(d==0)\n\n t = t + 1\n rew_for_ep += r\n scores_for_ep.append(info['score'])\n\n all_rewards.append(rew_for_ep)\n all_scores_mean.append(np.mean(scores_for_ep))\n all_scores_last.append(np.mean(scores_for_ep[-5:]))\n print(\"rollout rew: \", rew_for_ep)\n\n print(\"\\n\\nREW: \", np.mean(all_rewards), \",\", np.std(all_rewards))\n print(\"SCO mean: \", np.mean(all_scores_mean), \",\", np.std(all_scores_mean),\"\\n\\n\")\n self.mujoco_render_frames = False\n\n def visualize_policy_offscreen(self,\n policy,\n horizon=1000,\n num_episodes=1,\n frame_size=(640, 480),\n mode='exploration',\n save_loc='/tmp/',\n filename='newvid',\n camera_name=None):\n import skvideo.io\n for ep in range(num_episodes):\n print('Episode %d: rendering offline ' % ep, end='', flush=True)\n o = self.reset()\n d = False\n t = 0\n arrs = []\n t0 = time.time()\n while t < horizon and d is False:\n a = policy.get_action(\n o)[0] if mode == 'exploration' else policy.get_action(\n o)[1]['evaluation']\n o, r, d, _ = self.step(a)\n t = t + 1\n curr_frame = self.sim.render(\n width=frame_size[0],\n height=frame_size[1],\n mode='offscreen',\n camera_name=camera_name,\n device_id=0)\n arrs.append(curr_frame[::-1, :, :])\n print(t, end=', ', flush=True)\n file_name = save_loc + filename + str(ep) + '.mp4'\n skvideo.io.vwrite(file_name, np.asarray(arrs))\n print('saved', file_name)\n t1 = time.time()\n print('time taken = %f' % (t1 - t0))\n"
] | [
[
"numpy.asarray",
"numpy.concatenate",
"numpy.round",
"numpy.std",
"numpy.mean",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pauldmccarthy/pandas | [
"b835ca2fc2f772c27c914ae532cd32f8db69724a"
] | [
"pandas/tests/frame/constructors/test_from_records.py"
] | [
"from datetime import datetime\nfrom decimal import Decimal\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas.compat import is_platform_little_endian\n\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n Index,\n Int64Index,\n Interval,\n RangeIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\nclass TestFromRecords:\n def test_from_records_with_datetimes(self):\n\n # this may fail on certain platforms because of a numpy issue\n # related GH#6140\n if not is_platform_little_endian():\n pytest.skip(\"known failure of test on non-little endian\")\n\n # construction with a null in a recarray\n # GH#6140\n expected = DataFrame({\"EXPIRY\": [datetime(2005, 3, 1, 0, 0), None]})\n\n arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])]\n dtypes = [(\"EXPIRY\", \"<M8[ns]\")]\n\n try:\n recarray = np.core.records.fromarrays(arrdata, dtype=dtypes)\n except (ValueError):\n pytest.skip(\"known failure of numpy rec array creation\")\n\n result = DataFrame.from_records(recarray)\n tm.assert_frame_equal(result, expected)\n\n # coercion should work too\n arrdata = [np.array([datetime(2005, 3, 1, 0, 0), None])]\n dtypes = [(\"EXPIRY\", \"<M8[m]\")]\n recarray = np.core.records.fromarrays(arrdata, dtype=dtypes)\n result = DataFrame.from_records(recarray)\n tm.assert_frame_equal(result, expected)\n\n def test_from_records_sequencelike(self):\n df = DataFrame(\n {\n \"A\": np.array(np.random.randn(6), dtype=np.float64),\n \"A1\": np.array(np.random.randn(6), dtype=np.float64),\n \"B\": np.array(np.arange(6), dtype=np.int64),\n \"C\": [\"foo\"] * 6,\n \"D\": np.array([True, False] * 3, dtype=bool),\n \"E\": np.array(np.random.randn(6), dtype=np.float32),\n \"E1\": np.array(np.random.randn(6), dtype=np.float32),\n \"F\": np.array(np.arange(6), dtype=np.int32),\n }\n )\n\n # this is actually tricky to create the recordlike arrays and\n # have the dtypes be intact\n blocks = df._to_dict_of_blocks()\n tuples = []\n columns = []\n dtypes = []\n for dtype, b in blocks.items():\n columns.extend(b.columns)\n dtypes.extend([(c, np.dtype(dtype).descr[0][1]) for c in b.columns])\n for i in range(len(df.index)):\n tup = []\n for _, b in blocks.items():\n tup.extend(b.iloc[i].values)\n tuples.append(tuple(tup))\n\n recarray = np.array(tuples, dtype=dtypes).view(np.recarray)\n recarray2 = df.to_records()\n lists = [list(x) for x in tuples]\n\n # tuples (lose the dtype info)\n result = DataFrame.from_records(tuples, columns=columns).reindex(\n columns=df.columns\n )\n\n # created recarray and with to_records recarray (have dtype info)\n result2 = DataFrame.from_records(recarray, columns=columns).reindex(\n columns=df.columns\n )\n result3 = DataFrame.from_records(recarray2, columns=columns).reindex(\n columns=df.columns\n )\n\n # list of tupels (no dtype info)\n result4 = DataFrame.from_records(lists, columns=columns).reindex(\n columns=df.columns\n )\n\n tm.assert_frame_equal(result, df, check_dtype=False)\n tm.assert_frame_equal(result2, df)\n tm.assert_frame_equal(result3, df)\n tm.assert_frame_equal(result4, df, check_dtype=False)\n\n # tuples is in the order of the columns\n result = DataFrame.from_records(tuples)\n tm.assert_index_equal(result.columns, RangeIndex(8))\n\n # test exclude parameter & we are casting the results here (as we don't\n # have dtype info to recover)\n columns_to_test = [columns.index(\"C\"), columns.index(\"E1\")]\n\n exclude = list(set(range(8)) - set(columns_to_test))\n result = DataFrame.from_records(tuples, exclude=exclude)\n result.columns = [columns[i] for i in sorted(columns_to_test)]\n tm.assert_series_equal(result[\"C\"], df[\"C\"])\n tm.assert_series_equal(result[\"E1\"], df[\"E1\"].astype(\"float64\"))\n\n # empty case\n result = DataFrame.from_records([], columns=[\"foo\", \"bar\", \"baz\"])\n assert len(result) == 0\n tm.assert_index_equal(result.columns, Index([\"foo\", \"bar\", \"baz\"]))\n\n result = DataFrame.from_records([])\n assert len(result) == 0\n assert len(result.columns) == 0\n\n def test_from_records_dictlike(self):\n\n # test the dict methods\n df = DataFrame(\n {\n \"A\": np.array(np.random.randn(6), dtype=np.float64),\n \"A1\": np.array(np.random.randn(6), dtype=np.float64),\n \"B\": np.array(np.arange(6), dtype=np.int64),\n \"C\": [\"foo\"] * 6,\n \"D\": np.array([True, False] * 3, dtype=bool),\n \"E\": np.array(np.random.randn(6), dtype=np.float32),\n \"E1\": np.array(np.random.randn(6), dtype=np.float32),\n \"F\": np.array(np.arange(6), dtype=np.int32),\n }\n )\n\n # columns is in a different order here than the actual items iterated\n # from the dict\n blocks = df._to_dict_of_blocks()\n columns = []\n for dtype, b in blocks.items():\n columns.extend(b.columns)\n\n asdict = {x: y for x, y in df.items()}\n asdict2 = {x: y.values for x, y in df.items()}\n\n # dict of series & dict of ndarrays (have dtype info)\n results = []\n results.append(DataFrame.from_records(asdict).reindex(columns=df.columns))\n results.append(\n DataFrame.from_records(asdict, columns=columns).reindex(columns=df.columns)\n )\n results.append(\n DataFrame.from_records(asdict2, columns=columns).reindex(columns=df.columns)\n )\n\n for r in results:\n tm.assert_frame_equal(r, df)\n\n def test_from_records_with_index_data(self):\n df = DataFrame(np.random.randn(10, 3), columns=[\"A\", \"B\", \"C\"])\n\n data = np.random.randn(10)\n df1 = DataFrame.from_records(df, index=data)\n tm.assert_index_equal(df1.index, Index(data))\n\n def test_from_records_bad_index_column(self):\n df = DataFrame(np.random.randn(10, 3), columns=[\"A\", \"B\", \"C\"])\n\n # should pass\n df1 = DataFrame.from_records(df, index=[\"C\"])\n tm.assert_index_equal(df1.index, Index(df.C))\n\n df1 = DataFrame.from_records(df, index=\"C\")\n tm.assert_index_equal(df1.index, Index(df.C))\n\n # should fail\n msg = r\"Shape of passed values is \\(10, 3\\), indices imply \\(1, 3\\)\"\n with pytest.raises(ValueError, match=msg):\n DataFrame.from_records(df, index=[2])\n with pytest.raises(KeyError, match=r\"^2$\"):\n DataFrame.from_records(df, index=2)\n\n def test_from_records_non_tuple(self):\n class Record:\n def __init__(self, *args):\n self.args = args\n\n def __getitem__(self, i):\n return self.args[i]\n\n def __iter__(self):\n return iter(self.args)\n\n recs = [Record(1, 2, 3), Record(4, 5, 6), Record(7, 8, 9)]\n tups = [tuple(rec) for rec in recs]\n\n result = DataFrame.from_records(recs)\n expected = DataFrame.from_records(tups)\n tm.assert_frame_equal(result, expected)\n\n def test_from_records_len0_with_columns(self):\n # GH#2633\n result = DataFrame.from_records([], index=\"foo\", columns=[\"foo\", \"bar\"])\n expected = Index([\"bar\"])\n\n assert len(result) == 0\n assert result.index.name == \"foo\"\n tm.assert_index_equal(result.columns, expected)\n\n def test_from_records_series_list_dict(self):\n # GH#27358\n expected = DataFrame([[{\"a\": 1, \"b\": 2}, {\"a\": 3, \"b\": 4}]]).T\n data = Series([[{\"a\": 1, \"b\": 2}], [{\"a\": 3, \"b\": 4}]])\n result = DataFrame.from_records(data)\n tm.assert_frame_equal(result, expected)\n\n def test_from_records_series_categorical_index(self):\n # GH#32805\n index = CategoricalIndex(\n [Interval(-20, -10), Interval(-10, 0), Interval(0, 10)]\n )\n series_of_dicts = Series([{\"a\": 1}, {\"a\": 2}, {\"b\": 3}], index=index)\n frame = DataFrame.from_records(series_of_dicts, index=index)\n expected = DataFrame(\n {\"a\": [1, 2, np.NaN], \"b\": [np.NaN, np.NaN, 3]}, index=index\n )\n tm.assert_frame_equal(frame, expected)\n\n def test_frame_from_records_utc(self):\n rec = {\"datum\": 1.5, \"begin_time\": datetime(2006, 4, 27, tzinfo=pytz.utc)}\n\n # it works\n DataFrame.from_records([rec], index=\"begin_time\")\n\n def test_from_records_to_records(self):\n # from numpy documentation\n arr = np.zeros((2,), dtype=(\"i4,f4,a10\"))\n arr[:] = [(1, 2.0, \"Hello\"), (2, 3.0, \"World\")]\n\n # TODO(wesm): unused\n frame = DataFrame.from_records(arr) # noqa\n\n index = Index(np.arange(len(arr))[::-1])\n indexed_frame = DataFrame.from_records(arr, index=index)\n tm.assert_index_equal(indexed_frame.index, index)\n\n # without names, it should go to last ditch\n arr2 = np.zeros((2, 3))\n tm.assert_frame_equal(DataFrame.from_records(arr2), DataFrame(arr2))\n\n # wrong length\n msg = r\"Shape of passed values is \\(2, 3\\), indices imply \\(1, 3\\)\"\n with pytest.raises(ValueError, match=msg):\n DataFrame.from_records(arr, index=index[:-1])\n\n indexed_frame = DataFrame.from_records(arr, index=\"f1\")\n\n # what to do?\n records = indexed_frame.to_records()\n assert len(records.dtype.names) == 3\n\n records = indexed_frame.to_records(index=False)\n assert len(records.dtype.names) == 2\n assert \"index\" not in records.dtype.names\n\n def test_from_records_nones(self):\n tuples = [(1, 2, None, 3), (1, 2, None, 3), (None, 2, 5, 3)]\n\n df = DataFrame.from_records(tuples, columns=[\"a\", \"b\", \"c\", \"d\"])\n assert np.isnan(df[\"c\"][0])\n\n def test_from_records_iterator(self):\n arr = np.array(\n [(1.0, 1.0, 2, 2), (3.0, 3.0, 4, 4), (5.0, 5.0, 6, 6), (7.0, 7.0, 8, 8)],\n dtype=[\n (\"x\", np.float64),\n (\"u\", np.float32),\n (\"y\", np.int64),\n (\"z\", np.int32),\n ],\n )\n df = DataFrame.from_records(iter(arr), nrows=2)\n xp = DataFrame(\n {\n \"x\": np.array([1.0, 3.0], dtype=np.float64),\n \"u\": np.array([1.0, 3.0], dtype=np.float32),\n \"y\": np.array([2, 4], dtype=np.int64),\n \"z\": np.array([2, 4], dtype=np.int32),\n }\n )\n tm.assert_frame_equal(df.reindex_like(xp), xp)\n\n # no dtypes specified here, so just compare with the default\n arr = [(1.0, 2), (3.0, 4), (5.0, 6), (7.0, 8)]\n df = DataFrame.from_records(iter(arr), columns=[\"x\", \"y\"], nrows=2)\n tm.assert_frame_equal(df, xp.reindex(columns=[\"x\", \"y\"]), check_dtype=False)\n\n def test_from_records_tuples_generator(self):\n def tuple_generator(length):\n for i in range(length):\n letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n yield (i, letters[i % len(letters)], i / length)\n\n columns_names = [\"Integer\", \"String\", \"Float\"]\n columns = [\n [i[j] for i in tuple_generator(10)] for j in range(len(columns_names))\n ]\n data = {\"Integer\": columns[0], \"String\": columns[1], \"Float\": columns[2]}\n expected = DataFrame(data, columns=columns_names)\n\n generator = tuple_generator(10)\n result = DataFrame.from_records(generator, columns=columns_names)\n tm.assert_frame_equal(result, expected)\n\n def test_from_records_lists_generator(self):\n def list_generator(length):\n for i in range(length):\n letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n yield [i, letters[i % len(letters)], i / length]\n\n columns_names = [\"Integer\", \"String\", \"Float\"]\n columns = [\n [i[j] for i in list_generator(10)] for j in range(len(columns_names))\n ]\n data = {\"Integer\": columns[0], \"String\": columns[1], \"Float\": columns[2]}\n expected = DataFrame(data, columns=columns_names)\n\n generator = list_generator(10)\n result = DataFrame.from_records(generator, columns=columns_names)\n tm.assert_frame_equal(result, expected)\n\n def test_from_records_columns_not_modified(self):\n tuples = [(1, 2, 3), (1, 2, 3), (2, 5, 3)]\n\n columns = [\"a\", \"b\", \"c\"]\n original_columns = list(columns)\n\n df = DataFrame.from_records(tuples, columns=columns, index=\"a\") # noqa\n\n assert columns == original_columns\n\n def test_from_records_decimal(self):\n\n tuples = [(Decimal(\"1.5\"),), (Decimal(\"2.5\"),), (None,)]\n\n df = DataFrame.from_records(tuples, columns=[\"a\"])\n assert df[\"a\"].dtype == object\n\n df = DataFrame.from_records(tuples, columns=[\"a\"], coerce_float=True)\n assert df[\"a\"].dtype == np.float64\n assert np.isnan(df[\"a\"].values[-1])\n\n def test_from_records_duplicates(self):\n result = DataFrame.from_records([(1, 2, 3), (4, 5, 6)], columns=[\"a\", \"b\", \"a\"])\n\n expected = DataFrame([(1, 2, 3), (4, 5, 6)], columns=[\"a\", \"b\", \"a\"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_from_records_set_index_name(self):\n def create_dict(order_id):\n return {\n \"order_id\": order_id,\n \"quantity\": np.random.randint(1, 10),\n \"price\": np.random.randint(1, 10),\n }\n\n documents = [create_dict(i) for i in range(10)]\n # demo missing data\n documents.append({\"order_id\": 10, \"quantity\": 5})\n\n result = DataFrame.from_records(documents, index=\"order_id\")\n assert result.index.name == \"order_id\"\n\n # MultiIndex\n result = DataFrame.from_records(documents, index=[\"order_id\", \"quantity\"])\n assert result.index.names == (\"order_id\", \"quantity\")\n\n def test_from_records_misc_brokenness(self):\n # GH#2179\n\n data = {1: [\"foo\"], 2: [\"bar\"]}\n\n result = DataFrame.from_records(data, columns=[\"a\", \"b\"])\n exp = DataFrame(data, columns=[\"a\", \"b\"])\n tm.assert_frame_equal(result, exp)\n\n # overlap in index/index_names\n\n data = {\"a\": [1, 2, 3], \"b\": [4, 5, 6]}\n\n result = DataFrame.from_records(data, index=[\"a\", \"b\", \"c\"])\n exp = DataFrame(data, index=[\"a\", \"b\", \"c\"])\n tm.assert_frame_equal(result, exp)\n\n # GH#2623\n rows = []\n rows.append([datetime(2010, 1, 1), 1])\n rows.append([datetime(2010, 1, 2), \"hi\"]) # test col upconverts to obj\n df2_obj = DataFrame.from_records(rows, columns=[\"date\", \"test\"])\n result = df2_obj.dtypes\n expected = Series(\n [np.dtype(\"datetime64[ns]\"), np.dtype(\"object\")], index=[\"date\", \"test\"]\n )\n tm.assert_series_equal(result, expected)\n\n rows = []\n rows.append([datetime(2010, 1, 1), 1])\n rows.append([datetime(2010, 1, 2), 1])\n df2_obj = DataFrame.from_records(rows, columns=[\"date\", \"test\"])\n result = df2_obj.dtypes\n expected = Series(\n [np.dtype(\"datetime64[ns]\"), np.dtype(\"int64\")], index=[\"date\", \"test\"]\n )\n tm.assert_series_equal(result, expected)\n\n def test_from_records_empty(self):\n # GH#3562\n result = DataFrame.from_records([], columns=[\"a\", \"b\", \"c\"])\n expected = DataFrame(columns=[\"a\", \"b\", \"c\"])\n tm.assert_frame_equal(result, expected)\n\n result = DataFrame.from_records([], columns=[\"a\", \"b\", \"b\"])\n expected = DataFrame(columns=[\"a\", \"b\", \"b\"])\n tm.assert_frame_equal(result, expected)\n\n def test_from_records_empty_with_nonempty_fields_gh3682(self):\n a = np.array([(1, 2)], dtype=[(\"id\", np.int64), (\"value\", np.int64)])\n df = DataFrame.from_records(a, index=\"id\")\n\n ex_index = Int64Index([1], name=\"id\")\n expected = DataFrame({\"value\": [2]}, index=ex_index, columns=[\"value\"])\n tm.assert_frame_equal(df, expected)\n\n b = a[:0]\n df2 = DataFrame.from_records(b, index=\"id\")\n tm.assert_frame_equal(df2, df.iloc[:0])\n"
] | [
[
"pandas.Series",
"pandas.RangeIndex",
"pandas.DataFrame",
"numpy.dtype",
"numpy.random.randn",
"numpy.core.records.fromarrays",
"pandas.DataFrame.from_records",
"pandas._testing.assert_frame_equal",
"numpy.random.randint",
"numpy.arange",
"pandas.Index",
"pandas.Int64Index",
"pandas._testing.assert_series_equal",
"numpy.zeros",
"pandas._testing.assert_index_equal",
"numpy.isnan",
"pandas.compat.is_platform_little_endian",
"pandas.Interval",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
thanhkaist/datasets | [
"02da35c558ec8ea704e744a2008c5cecb2e7a0a1"
] | [
"tensorflow_datasets/image/coco.py"
] | [
"# coding=utf-8\n# Copyright 2019 The TensorFlow Datasets 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\"\"\"MS Coco Dataset.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport os\n\nfrom absl import logging\nimport tensorflow as tf\n\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\\\n@article{DBLP:journals/corr/LinMBHPRDZ14,\n author = {Tsung{-}Yi Lin and\n Michael Maire and\n Serge J. Belongie and\n Lubomir D. Bourdev and\n Ross B. Girshick and\n James Hays and\n Pietro Perona and\n Deva Ramanan and\n Piotr Doll{\\'{a}}r and\n C. Lawrence Zitnick},\n title = {Microsoft {COCO:} Common Objects in Context},\n journal = {CoRR},\n volume = {abs/1405.0312},\n year = {2014},\n url = {http://arxiv.org/abs/1405.0312},\n archivePrefix = {arXiv},\n eprint = {1405.0312},\n timestamp = {Mon, 13 Aug 2018 16:48:13 +0200},\n biburl = {https://dblp.org/rec/bib/journals/corr/LinMBHPRDZ14},\n bibsource = {dblp computer science bibliography, https://dblp.org}\n}\n\"\"\"\n\n\nclass Coco2014(tfds.core.GeneratorBasedBuilder):\n \"\"\"MS Coco dataset.\"\"\"\n\n VERSION = tfds.core.Version(\"1.0.0\")\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=(\n \"COCO is a large-scale object detection, segmentation, and \"\n \"captioning dataset. This version contains images, bounding boxes \"\n \"and labels for the 2014 version.\\n\"\n \"Note:\\n\"\n \" * Some images from the train and validation sets don't have \"\n \"annotations.\\n\"\n \" * The test split don't have any annotations (only images).\\n\"\n \" * Coco defines 91 classes but the data only had 80 classes.\\n\"),\n # More info could be added, like the segmentation (as png mask),\n # captions, person key-points. For caption encoding, it would probably\n # be better to have a separate class CocoCaption2014 to avoid poluting\n # the main class with builder config for each encoder.\n features=tfds.features.FeaturesDict({\n # Images can have variable shape\n \"image\": tfds.features.Image(encoding_format=\"jpeg\"),\n \"image/filename\": tfds.features.Text(),\n \"objects\": tfds.features.Sequence({\n \"bbox\": tfds.features.BBoxFeature(),\n # Coco has 91 categories but only 80 are present in the dataset\n \"label\": tfds.features.ClassLabel(num_classes=80),\n \"is_crowd\": tf.bool,\n }),\n }),\n urls=[\"http://cocodataset.org/#home\"],\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n root_url = \"http://images.cocodataset.org/\"\n urls = {\n # Train/validation set\n \"train_images\": \"zips/train2014.zip\",\n \"val_images\": \"zips/val2014.zip\",\n \"trainval_annotations\": \"annotations/annotations_trainval2014.zip\",\n # Testing set (no annotations) (2014)\n \"test_images\": \"zips/test2014.zip\",\n \"test_annotations\": \"annotations/image_info_test2014.zip\",\n # Testing set (no annotations) (2015)\n \"test2015_images\": \"zips/test2015.zip\",\n \"test2015_annotations\": \"annotations/image_info_test2015.zip\",\n }\n extracted_paths = dl_manager.download_and_extract({\n key: root_url + url for key, url in urls.items()\n })\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n num_shards=10,\n gen_kwargs=dict(\n image_dir=extracted_paths[\"train_images\"],\n annotation_dir=extracted_paths[\"trainval_annotations\"],\n split_type=\"train2014\",\n )),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n num_shards=10,\n gen_kwargs=dict(\n image_dir=extracted_paths[\"val_images\"],\n annotation_dir=extracted_paths[\"trainval_annotations\"],\n split_type=\"val2014\",\n )),\n # Warning: Testing split only contains the images without any annotation\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n num_shards=10,\n gen_kwargs=dict(\n image_dir=extracted_paths[\"test_images\"],\n annotation_dir=extracted_paths[\"test_annotations\"],\n split_type=\"test2014\",\n has_annotation=False,\n )),\n tfds.core.SplitGenerator(\n name=\"test2015\",\n num_shards=10,\n gen_kwargs=dict(\n image_dir=extracted_paths[\"test2015_images\"],\n annotation_dir=extracted_paths[\"test2015_annotations\"],\n split_type=\"test2015\",\n has_annotation=False,\n )),\n ]\n\n def _generate_examples(\n self, image_dir, annotation_dir, split_type, has_annotation=True):\n \"\"\"Generate examples as dicts.\n\n Args:\n image_dir: `str`, directory containing the images\n annotation_dir: `str`, directory containing\n split_type: `str`, <split_name><year> (ex: train2014)\n has_annotation: `bool`, when False (for the testing set), the annotations\n are not recorded\n\n Yields:\n Generator yielding the next samples\n \"\"\"\n if has_annotation:\n instance_filename = \"instances_{}.json\"\n else:\n instance_filename = \"image_info_{}.json\"\n\n # Load the label names and images\n instance_path = os.path.join(\n annotation_dir,\n \"annotations\",\n instance_filename.format(split_type),\n )\n coco_annotation = CocoAnnotation(instance_path)\n # Each category is a dict:\n # {\n # 'id': 51, # From 1-91, some entry missing\n # 'name': 'bowl',\n # 'supercategory': 'kitchen',\n # }\n categories = coco_annotation.categories\n # Each image is a dict:\n # {\n # 'id': 262145,\n # 'file_name': 'COCO_train2014_000000262145.jpg'\n # 'flickr_url': 'http://farm8.staticflickr.com/7187/xyz.jpg',\n # 'coco_url': 'http://images.cocodataset.org/train2014/xyz.jpg',\n # 'license': 2,\n # 'date_captured': '2013-11-20 02:07:55',\n # 'height': 427,\n # 'width': 640,\n # }\n images = coco_annotation.images\n\n # TODO(b/121375022): ClassLabel names should also contains 'id' and\n # and 'supercategory' (in addition to 'name')\n # Warning: As Coco only use 80 out of the 91 labels, the c['id'] and\n # dataset names ids won't match.\n self.info.features[\"objects\"][\"label\"].names = [\n c[\"name\"] for c in categories\n ]\n # TODO(b/121375022): Conversion should be done by ClassLabel\n categories_id2name = {c[\"id\"]: c[\"name\"] for c in categories}\n\n # Iterate over all images\n annotation_skipped = 0\n for image_info in sorted(images, key=lambda x: x[\"id\"]):\n if has_annotation:\n # Each instance annotation is a dict:\n # {\n # 'iscrowd': 0,\n # 'bbox': [116.95, 305.86, 285.3, 266.03],\n # 'image_id': 480023,\n # 'segmentation': [[312.29, 562.89, 402.25, ...]],\n # 'category_id': 58,\n # 'area': 54652.9556,\n # 'id': 86,\n # }\n instances = coco_annotation.get_annotations(img_id=image_info[\"id\"])\n else:\n instances = [] # No annotations\n\n if not instances:\n annotation_skipped += 1\n\n def build_bbox(x, y, width, height):\n # pylint: disable=cell-var-from-loop\n # build_bbox is only used within the loop so it is ok to use image_info\n return tfds.features.BBox(\n ymin=y / image_info[\"height\"],\n xmin=x / image_info[\"width\"],\n ymax=(y + height) / image_info[\"height\"],\n xmax=(x + width) / image_info[\"width\"],\n )\n # pylint: enable=cell-var-from-loop\n\n yield {\n \"image\": os.path.join(image_dir, split_type, image_info[\"file_name\"]),\n \"image/filename\": image_info[\"file_name\"],\n \"objects\": [{ # pylint: disable=g-complex-comprehension\n \"bbox\": build_bbox(*instance_info[\"bbox\"]),\n \"label\": categories_id2name[instance_info[\"category_id\"]],\n \"is_crowd\": bool(instance_info[\"iscrowd\"]),\n } for instance_info in instances],\n }\n logging.info(\n \"%d/%d images do not contains any annotations\",\n annotation_skipped,\n len(images),\n )\n\n\nclass CocoAnnotation(object):\n \"\"\"Coco annotation helper class.\"\"\"\n\n def __init__(self, annotation_path):\n\n with tf.io.gfile.GFile(annotation_path) as f:\n data = json.load(f)\n self._data = data\n\n self._img_id2annotations = {}\n\n # Get the annotations associated with an image\n if \"annotations\" in data: # Testing set don't has any annotations\n img_id2annotations = collections.defaultdict(list)\n for a in data[\"annotations\"]:\n img_id2annotations[a[\"image_id\"]].append(a)\n self._img_id2annotations = {\n k: list(sorted(v, key=lambda a: a[\"id\"]))\n for k, v in img_id2annotations.items()\n }\n\n @property\n def categories(self):\n \"\"\"Return the category dicts, as sorted in the file.\"\"\"\n return self._data[\"categories\"]\n\n @property\n def images(self):\n \"\"\"Return the image dicts, as sorted in the file.\"\"\"\n return self._data[\"images\"]\n\n def get_annotations(self, img_id):\n \"\"\"Return all annotations associated with the image id string.\"\"\"\n # Some images don't have any annotations. Return empty list instead.\n return self._img_id2annotations.get(img_id, [])\n"
] | [
[
"tensorflow.io.gfile.GFile"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jamiechang917/eddy | [
"157bd035e6e60b9f642a6afcb463671b0c7ee906"
] | [
"eddy/helper_functions.py"
] | [
"from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# -- MCMC / OPTIMIZATION FUNCTIONS -- #\n\ndef random_p0(p0, scatter, nwalkers):\n \"\"\"Introduce scatter to starting positions.\"\"\"\n p0 = np.atleast_1d(np.squeeze(p0))\n dp0 = np.random.randn(nwalkers * len(p0)).reshape(nwalkers, len(p0))\n dp0 = np.where(p0 == 0.0, 1.0, p0)[None, :] * (1.0 + scatter * dp0)\n return np.where(p0[None, :] == 0.0, dp0 - 1.0, dp0)\n\n\ndef _errors(x, dy, return_uncertainty):\n \"\"\"Parse the inputs related to errors.\"\"\"\n if return_uncertainty is None:\n return_uncertainty = dy is not None\n dy = np.ones(x.size) * (1.0 if dy is None else dy)\n if np.all(np.isnan(dy)):\n dy = np.ones(x.size)\n absolute_sigma = False\n else:\n absolute_sigma = True\n return dy, return_uncertainty, absolute_sigma\n\n\ndef fit_gaussian(x, y, dy=None, return_uncertainty=None):\n \"\"\"Fit a gaussian to (x, y[, dy]).\"\"\"\n dy, return_uncertainty, absolute_sigma = _errors(x, dy, return_uncertainty)\n p0 = get_p0_gaussian(x, y)\n try:\n popt, cvar = curve_fit(gaussian, x, y, sigma=dy, p0=p0,\n absolute_sigma=absolute_sigma,\n maxfev=100000)\n cvar = np.diag(cvar)**0.5\n except Exception:\n popt = [np.nan, np.nan, np.nan]\n cvar = popt.copy()\n return (popt, cvar) if return_uncertainty else popt\n\n\ndef fit_gaussian_thick(x, y, dy=None, return_uncertainty=None):\n \"\"\"Fit an optically thick Gaussian function to (x, y[, dy]).\"\"\"\n dy, return_uncertainty, absolute_sigma = _errors(x, dy, return_uncertainty)\n p0 = fit_gaussian(x=x, y=y, dy=dy,\n return_uncertainty=False)\n p0 = np.append(p0, 0.5)\n try:\n popt, cvar = curve_fit(gaussian_thick, x, y, sigma=dy, p0=p0,\n absolute_sigma=absolute_sigma,\n maxfev=100000)\n cvar = np.diag(cvar)**0.5\n except Exception:\n popt = [np.nan, np.nan, np.nan, np.nan]\n cvar = popt.copy()\n return (popt, cvar) if return_uncertainty else popt\n\n\ndef fit_double_gaussian(x, y, dy=None, return_uncertainty=None):\n \"\"\"\n Fit two Gaussian lines to (x, y[, dy]). This will automatically compare the\n results from a single Gaussian fit using `fit_gaussian`, and return the\n results from the model that yields the minimum BIC.\n \"\"\"\n\n # Defaults.\n\n dy, return_uncertainty, absolute_sigma = _errors(x, dy, return_uncertainty)\n popt = [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]\n cvar = popt.copy()\n\n # Single Gaussian fit.\n\n popt_a, cvar_a = fit_gaussian(x=x, y=y, dy=dy, return_uncertainty=True)\n if not all(np.isfinite(popt_a)):\n return (popt, cvar) if return_uncertainty else popt\n BIC_a = 3.0 * np.log(x.size)\n BIC_a -= np.nansum(((y - gaussian(x, *popt_a)) / dy)**2)\n\n # Double Gaussian fit.\n\n p0 = [popt_a[0] + popt_a[1], popt_a[1], 0.8 * popt_a[2],\n popt_a[0] - popt_a[1], popt_a[1], 0.8 * popt_a[2]]\n try:\n popt_b, cvar_b = curve_fit(double_gaussian, x, y, sigma=dy, p0=p0,\n absolute_sigma=absolute_sigma,\n maxfev=100000)\n cvar_b = np.diag(cvar_b)**0.5\n except Exception:\n return (popt, cvar) if return_uncertainty else popt\n BIC_b = 6.0 * np.log(x.size)\n BIC_b -= np.nansum(((y - double_gaussian(x, *popt_b)) / dy)**2)\n\n return (popt_b, cvar_b) if return_uncertainty else popt_b\n\n # Currently just return the double gaussian fit.\n # How do we distinguish which is the better fit?\n\n if min(popt_b[2], popt_b[5]) / max(popt_b[2], popt_b[5]) < 0.1:\n popt[:3], cvar[:3] = popt_a, cvar_a\n else:\n popt, cvar = popt_b, cvar_b\n return (popt, cvar) if return_uncertainty else popt\n\n\ndef get_gaussian_center(x, y, dy=None, return_uncertainty=None, fill=1e50):\n \"\"\"Return the line center from a Gaussian fit to the spectrum.\"\"\"\n if return_uncertainty is None:\n return_uncertainty = dy is not None\n popt, cvar = fit_gaussian(x, y, dy, return_uncertainty=True)\n if np.isfinite(popt[0]):\n return (popt[0], cvar[0]) if return_uncertainty else popt[0]\n return (fill, fill) if return_uncertainty else fill\n\n\ndef get_gaussthick_center(x, y, dy=None, return_uncertainty=None, fill=1e50):\n \"\"\"Return the line center from a Gaussian fit to the spectrum.\"\"\"\n if return_uncertainty is None:\n return_uncertainty = dy is not None\n popt, cvar = fit_gaussian_thick(x, y, dy, return_uncertainty=True)\n if np.isfinite(popt[0]):\n return (popt[0], cvar[0]) if return_uncertainty else popt[0]\n return (fill, fill) if return_uncertainty else fill\n\n\ndef get_doublegauss_center(x, y, dy=None, return_uncertainty=None, fill=1e50):\n \"\"\"Return the line center from a fit of two Gaussians to the spectrum.\"\"\"\n if return_uncertainty is None:\n return_uncertainty = dy is not None\n popt, cvar = fit_double_gaussian(x, y, dy, return_uncertainty=True)\n if np.isfinite(popt[2]) and np.isfinite(popt[5]):\n if popt[2] > popt[5]:\n return (popt[0], cvar[0]) if return_uncertainty else popt[0]\n else:\n return (popt[3], cvar[3]) if return_uncertainty else popt[3]\n else:\n (fill, fill) if return_uncertainty else fill\n\n\ndef get_gaussian_width(x, y, dy=None, return_uncertainty=None, fill=1e50):\n \"\"\"Return the absolute width of a Gaussian fit to the spectrum.\"\"\"\n if return_uncertainty is None:\n return_uncertainty = dy is not None\n popt, cvar = fit_gaussian(x, y, dy, return_uncertainty=True)\n if np.isfinite(popt[1]):\n return (popt[1], cvar[1]) if return_uncertainty else popt[1]\n return (fill, fill) if return_uncertainty else fill\n\n\ndef get_p0_gaussian(x, y):\n \"\"\"Estimate (x0, dV, Tb) for the spectrum.\"\"\"\n if x.size != y.size:\n raise ValueError(\"Mismatch in array shapes.\")\n Tb = np.max(y)\n x0 = x[y.argmax()]\n dV = np.trapz(y, x) / Tb / np.sqrt(2. * np.pi)\n return x0, dV, Tb\n\n\n# -- MODEL FUNCTIONS --#\n\ndef gaussian(x, x0, dV, Tb):\n \"\"\"Gaussian function.\"\"\"\n return Tb * np.exp(-np.power((x - x0) / dV, 2.0))\n\n\ndef gaussian_thick(x, x0, dV, Tex, tau0):\n \"\"\"Optically thick Gaussian line.\"\"\"\n tau = gaussian(x, x0, dV, tau0)\n return Tex * (1. - np.exp(-tau))\n\n\ndef double_gaussian(x, x0, dV0, Tb0, x1, dV1, Tb1):\n \"\"\"Double Gaussian function.\"\"\"\n return gaussian(x, x0, dV0, Tb0) + gaussian(x, x1, dV1, Tb1)\n\n\ndef SHO(x, A, y0):\n \"\"\"Simple harmonic oscillator.\"\"\"\n return A * np.cos(x) + y0\n\n\ndef SHO_offset(x, A, y0, dx):\n \"\"\"Simple harmonic oscillator with offset.\"\"\"\n return A * np.cos(x + dx) + y0\n\n\ndef SHO_double(x, A, B, y0):\n \"\"\"Two orthogonal simple harmonic oscillators.\"\"\"\n return A * np.cos(x) + B * np.sin(x) + y0\n\n\n# -- PLOTTING FUNCTIONS -- #\n\ndef plot_walkers(samples, nburnin=None, labels=None, histogram=True, return_fig=False):\n \"\"\"\n Plot the walkers to check if they are burning in.\n\n Args:\n samples (ndarray):\n nburnin (Optional[int])\n \"\"\"\n\n # Check the length of the label list.\n\n if labels is not None:\n if samples.shape[0] != len(labels):\n raise ValueError(\"Not correct number of labels.\")\n\n # Cycle through the plots.\n\n for s, sample in enumerate(samples):\n fig, ax = plt.subplots()\n for walker in sample.T:\n ax.plot(walker, alpha=0.1, color='k')\n ax.set_xlabel('Steps')\n if labels is not None:\n ax.set_ylabel(labels[s])\n if nburnin is not None:\n ax.axvline(nburnin, ls=':', color='r')\n\n # Include the histogram.\n\n if histogram:\n fig.set_size_inches(1.37 * fig.get_figwidth(),\n fig.get_figheight(), forward=True)\n ax_divider = make_axes_locatable(ax)\n bins = np.linspace(ax.get_ylim()[0], ax.get_ylim()[1], 50)\n hist, _ = np.histogram(sample[nburnin:].flatten(), bins=bins,\n density=True)\n bins = np.average([bins[1:], bins[:-1]], axis=0)\n ax1 = ax_divider.append_axes(\"right\", size=\"35%\", pad=\"2%\")\n ax1.fill_betweenx(bins, hist, np.zeros(bins.size), step='mid',\n color='darkgray', lw=0.0)\n ax1.set_ylim(ax.get_ylim()[0], ax.get_ylim()[1])\n ax1.set_xlim(0, ax1.get_xlim()[1])\n ax1.set_yticklabels([])\n ax1.set_xticklabels([])\n ax1.tick_params(which='both', left=0, bottom=0, top=0, right=0)\n ax1.spines['right'].set_visible(False)\n ax1.spines['bottom'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n if return_fig == True:\n return fig\n\n\ndef plot_corner(samples, labels=None, quantiles=[0.16, 0.5, 0.84]):\n \"\"\"\n A wrapper for DFM's corner plots.\n\n Args:\n samples (ndarry):\n labels (Optional[list]):\n quantiles (Optional[list]): Quantiles to use for plotting.\n \"\"\"\n import corner\n corner.corner(samples, labels=labels, title_fmt='.4f', bins=30,\n quantiles=quantiles, show_titles=True)\n"
] | [
[
"numpy.diag",
"numpy.sqrt",
"numpy.squeeze",
"numpy.max",
"numpy.exp",
"scipy.optimize.curve_fit",
"numpy.where",
"numpy.trapz",
"numpy.sin",
"numpy.zeros",
"numpy.log",
"numpy.power",
"numpy.isnan",
"numpy.append",
"numpy.isfinite",
"matplotlib.pyplot.subplots",
"numpy.cos",
"numpy.ones",
"numpy.average"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
yanlai00/cog | [
"01dbfcbe336072b6f4cb2b9952606bd45c65af7f"
] | [
"rlkit/torch/networks.py"
] | [
"\"\"\"\nGeneral networks for pytorch.\n\nAlgorithm-specific networks should go else-where.\n\"\"\"\nimport torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom rlkit.policies.base import Policy\nfrom rlkit.torch import pytorch_util as ptu\nfrom rlkit.torch.core import eval_np\nfrom rlkit.torch.data_management.normalizer import TorchFixedNormalizer\nfrom rlkit.torch.modules import LayerNorm\n\n\ndef identity(x):\n return x\n\nclass Mlp(nn.Module):\n def __init__(\n self,\n hidden_sizes,\n output_size,\n input_size,\n init_w=3e-3,\n hidden_activation=F.relu,\n output_activation=identity,\n hidden_init=ptu.fanin_init,\n b_init_value=0.1,\n layer_norm=False,\n layer_norm_kwargs=None,\n spectral_norm=False,\n ):\n super().__init__()\n\n if layer_norm_kwargs is None:\n layer_norm_kwargs = dict()\n\n self.input_size = input_size\n self.output_size = output_size\n self.hidden_activation = hidden_activation\n self.output_activation = output_activation\n self.layer_norm = layer_norm\n self.fcs = []\n self.layer_norms = []\n in_size = input_size\n\n for i, next_size in enumerate(hidden_sizes):\n fc = nn.Linear(in_size, next_size)\n if spectral_norm and 0 < i < len(hidden_sizes)-1:\n fc = nn.utils.spectral_norm(fc)\n in_size = next_size\n hidden_init(fc.weight)\n fc.bias.data.fill_(b_init_value)\n self.__setattr__(\"fc{}\".format(i), fc)\n self.fcs.append(fc)\n\n if self.layer_norm:\n ln = LayerNorm(next_size)\n self.__setattr__(\"layer_norm{}\".format(i), ln)\n self.layer_norms.append(ln)\n\n self.last_fc = nn.Linear(in_size, output_size)\n self.last_fc.weight.data.uniform_(-init_w, init_w)\n self.last_fc.bias.data.uniform_(-init_w, init_w)\n\n def forward(self, input, return_preactivations=False):\n h = input\n for i, fc in enumerate(self.fcs):\n h = fc(h)\n if self.layer_norm and i < len(self.fcs) - 1:\n h = self.layer_norms[i](h)\n h = self.hidden_activation(h)\n preactivation = self.last_fc(h)\n output = self.output_activation(preactivation)\n if return_preactivations:\n return output, preactivation\n else:\n return output\n\n\nclass FlattenMlp(Mlp):\n \"\"\"\n Flatten inputs along dimension 1 and then pass through MLP.\n \"\"\"\n\n def forward(self, *inputs, **kwargs):\n flat_inputs = torch.cat(inputs, dim=1)\n return super().forward(flat_inputs, **kwargs)\n\n\nclass MlpPolicy(Mlp, Policy):\n \"\"\"\n A simpler interface for creating policies.\n \"\"\"\n\n def __init__(\n self,\n *args,\n obs_normalizer: TorchFixedNormalizer = None,\n **kwargs\n ):\n super().__init__(*args, **kwargs)\n self.obs_normalizer = obs_normalizer\n\n def forward(self, obs, **kwargs):\n if self.obs_normalizer:\n obs = self.obs_normalizer.normalize(obs)\n return super().forward(obs, **kwargs)\n\n def get_action(self, obs_np):\n actions = self.get_actions(obs_np[None])\n return actions[0, :], {}\n\n def get_actions(self, obs):\n return eval_np(self, obs)\n\n\nclass TanhMlpPolicy(MlpPolicy):\n \"\"\"\n A helper class since most policies have a tanh output activation.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, output_activation=torch.tanh, **kwargs)\n"
] | [
[
"torch.nn.Linear",
"torch.nn.utils.spectral_norm",
"torch.cat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
IvanProdaiko94/UCU-deep-learning-homework | [
"e2a1ce91653696badebb69f17326c3218227be3c"
] | [
"layers/pooling.py"
] | [
"from __future__ import print_function\nimport torch\nfrom .utilities import im2col\n\n\ndef pool2d_vector(a, device, window_size=2):\n N_batch, C_in, img_size, _ = a.shape\n z_col = im2col(a, window_size, device, stride=2)\n out_size = img_size // window_size\n max_val = z_col.max(dim=0)[0]\n return max_val.view(N_batch, C_in, out_size, out_size)\n\n\ndef pool2d_scalar(a, device, window_size=2):\n N_batch, C_in, img_size, _ = a.shape\n result = torch.empty(N_batch, C_in, img_size // window_size, img_size // window_size)\n\n print(\n \"\\nMax pooling layer:\\n\"\n \"\\tInput: A=[{}x{}x{}x{}]\\n\".format(N_batch, C_in, img_size, img_size),\n \"\\tOutput: Z=[{}x{}x{}x{}]\".format(N_batch, C_in, img_size // window_size, img_size // window_size)\n )\n\n for n in range(N_batch):\n for c_in in range(C_in):\n for i in range(img_size // window_size):\n for j in range(img_size // window_size):\n double_i = window_size*i\n double_j = window_size*j\n result[n, c_in, i, j] = max(\n a[n, c_in, double_i, double_j],\n a[n, c_in, double_i + 1, double_j],\n a[n, c_in, double_i, double_j + 1],\n a[n, c_in, double_i + 1, double_j + 1]\n )\n\n return result.to(device)\n"
] | [
[
"torch.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
leokale/yolo_v1 | [
"ddafb5b06e0dc80b61d9271e4c1d4f48a9f050fc"
] | [
"yolo_data.py"
] | [
"# -*- coding:utf-8 -*-\n__author__ = 'Leo.Z'\n\n'''\nimage_name.jpg x y x2 y2 c x y x2 y2 c xy为左上角坐标,x2y2为右下角坐标\n'''\nimport os\nimport os.path\n\nimport random\nimport numpy as np\n\nimport torch\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\n\nimport cv2\n\n\nclass yoloDataset(data.Dataset):\n # 输入图片大小为448\n image_size = 448\n\n def __init__(self, root, list_file, train, transform):\n print('data init')\n self.root = root\n self.train = train\n self.transform = transform\n self.fnames = []\n self.boxes = []\n self.labels = []\n self.mean = (123, 117, 104) # RGB\n\n # if isinstance(list_file, list):\n # # Cat multiple list files together.\n # # This is especially useful for voc07/voc12 combination.\n # tmp_file = '/tmp/listfile.txt'\n # os.system('cat %s > %s' % (' '.join(list_file), tmp_file))\n # list_file = tmp_file\n\n with open(list_file) as f:\n lines = f.readlines()\n\n for line in lines:\n splited = line.strip().split()\n self.fnames.append(splited[0])\n num_boxes = (len(splited) - 1) // 5\n box = []\n label = []\n for i in range(num_boxes):\n x = float(splited[1 + 5 * i])\n y = float(splited[2 + 5 * i])\n x2 = float(splited[3 + 5 * i])\n y2 = float(splited[4 + 5 * i])\n c = splited[5 + 5 * i]\n box.append([x, y, x2, y2])\n label.append(int(c) + 1)\n self.boxes.append(torch.Tensor(box))\n self.labels.append(torch.LongTensor(label))\n self.num_samples = len(self.boxes)\n\n def __getitem__(self, idx):\n fname = self.fnames[idx]\n img = cv2.imread(os.path.join(self.root + fname))\n boxes = self.boxes[idx].clone()\n labels = self.labels[idx].clone()\n\n if self.train:\n # # img = self.random_bright(img)\n img, boxes = self.random_flip(img, boxes)\n img, boxes = self.randomScale(img, boxes)\n img = self.randomBlur(img)\n img = self.RandomBrightness(img)\n img = self.RandomHue(img)\n img = self.RandomSaturation(img)\n img, boxes, labels = self.randomShift(img, boxes, labels)\n img, boxes, labels = self.randomCrop(img, boxes, labels)\n\n h, w, _ = img.shape\n boxes /= torch.Tensor([w, h, w, h]).expand_as(boxes)\n img = self.BGR2RGB(img) # because pytorch pretrained model use RGB\n img = self.subMean(img, self.mean) # 减去均值\n img = cv2.resize(img, (self.image_size, self.image_size))\n target = self.encoder(boxes, labels) # 14x14x30\n for t in self.transform:\n img = t(img)\n\n return img, target\n\n def __len__(self):\n return self.num_samples\n\n def encoder(self, boxes, labels):\n '''\n boxes (tensor) [[x1,y1,x2,y2],[]] 这里的x1,y1,x2,y2都是坐标相对于图片wh的比例\n labels (tensor) [...]\n return 14x14x30\n '''\n grid_num = 14\n target = torch.zeros((grid_num, grid_num, 30))\n cell_size = 1. / grid_num\n wh = boxes[:, 2:] - boxes[:, :2]\n # print('wh:',wh)\n cxcy = (boxes[:, 2:] + boxes[:, :2]) / 2\n # print('cxcy:', cxcy)\n for i in range(cxcy.size()[0]): # 问题?为什么有一个box处于ij cell,就将4,9都设置为1了。万一一个cell中有两个不同的框呢?\n cxcy_sample = cxcy[i]\n # 这里得到的ij就是[cell_x,cell_y] ij[1]代表垂直第n个cell,ij[0]代表水平第n个cell\n ij = (cxcy_sample / cell_size).ceil() - 1\n # print(ij)\n # target[cell_y,cell_x,4] 表示在14x14的cell中位于[cell_y,cell_x]的cell的第一个box的confidence\n target[int(ij[1]), int(ij[0]), 4] = 1\n # target[cell_y,cell_x,4] 表示在14x14的cell中位于[cell_y,cell_x]的cell的第二个box的confidence\n target[int(ij[1]), int(ij[0]), 9] = 1\n # labels范围在1-20,所以target[cell_y,cell_x,10-29]表示classes分类的onehot编码\n # print('labels[i]:',labels[i])\n target[int(ij[1]), int(ij[0]), int(labels[i]) + 9] = 1\n # 先获取ij网格的左上角坐标\n xy = ij * cell_size # 匹配到的网格的左上角相对坐标(比例)\n # 计相对于cell的中心点坐标比例(相对于cell)和宽高比例(相对于整张图片),这里为什么两个box设置为一样的?是为了方便计算IoU么?\n # 实际上根本不是说一个cell中支持两个不同的box,而是一个cell中只能支持一个box,用两个xywhc,是为了pred多个框,然后选择最大IoU??\n delta_xy = (cxcy_sample - xy) / cell_size\n target[int(ij[1]), int(ij[0]), 2:4] = wh[i]\n target[int(ij[1]), int(ij[0]), :2] = delta_xy\n target[int(ij[1]), int(ij[0]), 7:9] = wh[i]\n target[int(ij[1]), int(ij[0]), 5:7] = delta_xy\n return target\n\n def BGR2RGB(self, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n def BGR2HSV(self, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n def HSV2BGR(self, img):\n return cv2.cvtColor(img, cv2.COLOR_HSV2BGR)\n\n def RandomBrightness(self, bgr):\n if random.random() < 0.5:\n hsv = self.BGR2HSV(bgr)\n h, s, v = cv2.split(hsv)\n adjust = random.choice([0.5, 1.5])\n v = v * adjust\n v = np.clip(v, 0, 255).astype(hsv.dtype)\n hsv = cv2.merge((h, s, v))\n bgr = self.HSV2BGR(hsv)\n return bgr\n\n def RandomSaturation(self, bgr):\n if random.random() < 0.5:\n hsv = self.BGR2HSV(bgr)\n h, s, v = cv2.split(hsv)\n adjust = random.choice([0.5, 1.5])\n s = s * adjust\n s = np.clip(s, 0, 255).astype(hsv.dtype)\n hsv = cv2.merge((h, s, v))\n bgr = self.HSV2BGR(hsv)\n return bgr\n\n def RandomHue(self, bgr):\n if random.random() < 0.5:\n hsv = self.BGR2HSV(bgr)\n h, s, v = cv2.split(hsv)\n adjust = random.choice([0.5, 1.5])\n h = h * adjust\n h = np.clip(h, 0, 255).astype(hsv.dtype)\n hsv = cv2.merge((h, s, v))\n bgr = self.HSV2BGR(hsv)\n return bgr\n\n def randomBlur(self, bgr):\n if random.random() < 0.5:\n bgr = cv2.blur(bgr, (5, 5))\n return bgr\n\n def randomShift(self, bgr, boxes, labels):\n # 平移变换\n center = (boxes[:, 2:] + boxes[:, :2]) / 2\n if random.random() < 0.5:\n height, width, c = bgr.shape\n after_shfit_image = np.zeros((height, width, c), dtype=bgr.dtype)\n after_shfit_image[:, :, :] = (104, 117, 123) # bgr\n shift_x = random.uniform(-width * 0.2, width * 0.2)\n shift_y = random.uniform(-height * 0.2, height * 0.2)\n # print(bgr.shape,shift_x,shift_y)\n # 原图像的平移\n if shift_x >= 0 and shift_y >= 0:\n after_shfit_image[int(shift_y):, int(shift_x):, :] = bgr[:height - int(shift_y), :width - int(shift_x),\n :]\n elif shift_x >= 0 and shift_y < 0:\n after_shfit_image[:height + int(shift_y), int(shift_x):, :] = bgr[-int(shift_y):, :width - int(shift_x),\n :]\n elif shift_x < 0 and shift_y >= 0:\n after_shfit_image[int(shift_y):, :width + int(shift_x), :] = bgr[:height - int(shift_y), -int(shift_x):,\n :]\n elif shift_x < 0 and shift_y < 0:\n after_shfit_image[:height + int(shift_y), :width + int(shift_x), :] = bgr[-int(shift_y):,\n -int(shift_x):, :]\n\n shift_xy = torch.FloatTensor([[int(shift_x), int(shift_y)]]).expand_as(center)\n center = center + shift_xy\n mask1 = (center[:, 0] > 0) & (center[:, 0] < width)\n mask2 = (center[:, 1] > 0) & (center[:, 1] < height)\n mask = (mask1 & mask2).view(-1, 1)\n boxes_in = boxes[mask.expand_as(boxes)].view(-1, 4)\n if len(boxes_in) == 0:\n return bgr, boxes, labels\n box_shift = torch.FloatTensor([[int(shift_x), int(shift_y), int(shift_x), int(shift_y)]]).expand_as(\n boxes_in)\n boxes_in = boxes_in + box_shift\n labels_in = labels[mask.view(-1)]\n return after_shfit_image, boxes_in, labels_in\n return bgr, boxes, labels\n\n def randomScale(self, bgr, boxes):\n # 固定住高度,以0.8-1.2伸缩宽度,做图像形变\n if random.random() < 0.5:\n scale = random.uniform(0.8, 1.2)\n height, width, c = bgr.shape\n bgr = cv2.resize(bgr, (int(width * scale), height))\n scale_tensor = torch.FloatTensor([[scale, 1, scale, 1]]).expand_as(boxes)\n boxes = boxes * scale_tensor\n return bgr, boxes\n return bgr, boxes\n\n def randomCrop(self, bgr, boxes, labels):\n if random.random() < 0.5:\n center = (boxes[:, 2:] + boxes[:, :2]) / 2\n height, width, c = bgr.shape\n h = random.uniform(0.6 * height, height)\n w = random.uniform(0.6 * width, width)\n x = random.uniform(0, width - w)\n y = random.uniform(0, height - h)\n x, y, h, w = int(x), int(y), int(h), int(w)\n\n center = center - torch.FloatTensor([[x, y]]).expand_as(center)\n mask1 = (center[:, 0] > 0) & (center[:, 0] < w)\n mask2 = (center[:, 1] > 0) & (center[:, 1] < h)\n mask = (mask1 & mask2).view(-1, 1)\n\n boxes_in = boxes[mask.expand_as(boxes)].view(-1, 4)\n if (len(boxes_in) == 0):\n return bgr, boxes, labels\n box_shift = torch.FloatTensor([[x, y, x, y]]).expand_as(boxes_in)\n\n boxes_in = boxes_in - box_shift\n boxes_in[:, 0] = boxes_in[:, 0].clamp_(min=0, max=w)\n boxes_in[:, 2] = boxes_in[:, 2].clamp_(min=0, max=w)\n boxes_in[:, 1] = boxes_in[:, 1].clamp_(min=0, max=h)\n boxes_in[:, 3] = boxes_in[:, 3].clamp_(min=0, max=h)\n\n labels_in = labels[mask.view(-1)]\n img_croped = bgr[y:y + h, x:x + w, :]\n return img_croped, boxes_in, labels_in\n return bgr, boxes, labels\n\n def subMean(self, bgr, mean):\n mean = np.array(mean, dtype=np.float32)\n bgr = bgr - mean\n return bgr\n\n def random_flip(self, im, boxes):\n if random.random() < 0.5:\n im_lr = np.fliplr(im).copy()\n h, w, _ = im.shape\n xmin = w - boxes[:, 2]\n xmax = w - boxes[:, 0]\n boxes[:, 0] = xmin\n boxes[:, 2] = xmax\n return im_lr, boxes\n return im, boxes\n\n def random_bright(self, im, delta=16):\n alpha = random.random()\n if alpha > 0.3:\n im = im * alpha + random.randrange(-delta, delta)\n im = im.clip(min=0, max=255).astype(np.uint8)\n return im\n"
] | [
[
"torch.LongTensor",
"torch.Tensor",
"torch.zeros",
"numpy.clip",
"numpy.fliplr",
"torch.FloatTensor",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Armannas/SVDD | [
"66a8d3c753aca0759ee6c9e0434d2f54dbc51333"
] | [
"SVDD.py"
] | [
"\n# Author: Arman Naseri Jahfari ([email protected])\n# Original paper: Tax, D. M. J., & Duin, R. P. W. (2004).\n# # Support Vector Data Description. Machine Learning, 54(1), 45–66. https://doi.org/10.1023/B:MACH.0000008084.60811.49\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nfrom scipy.linalg import cholesky, LinAlgError\nfrom cvxopt import matrix, solvers\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom sklearn.base import BaseEstimator, ClassifierMixin\n\nclass SVDD(BaseEstimator, ClassifierMixin):\n '''Support Vector Data Descriptor.'''\n def __init__(self, kernel_type='rbf', bandwidth=1, order=2, fracrej=np.array([0.1, 1])):\n self.kernel_type = kernel_type\n self.bandwidth = bandwidth\n self.order = order\n self.fracrej = fracrej\n\n def _more_tags(self):\n return {'binary_only': True}\n\n def compute_kernel(self, X, Z):\n \"\"\"\n Compute kernel for given data set.\n Parameters\n ----------\n X : array\n data set (N samples by D features)\n Z : array\n data set (M samples by D features)\n type : str\n type of kernel, options: 'linear', 'polynomial', 'rbf',\n 'sigmoid' (def: 'linear')\n order : float\n degree for the polynomial kernel (def: 2.0)\n bandwidth : float\n kernel bandwidth (def: 1.0)\n Returns\n -------\n array\n kernel matrix (N by M)\n \"\"\"\n\n # Data shapes\n # N, DX = X.shape\n\n # Only RBF kernel is implemented\n if self.kernel_type != 'rbf':\n raise NotImplementedError('Kernel not implemented yet.')\n else:\n # Radial basis function kernel\n return np.exp(-cdist(X, Z, 'sqeuclidean') / (self.bandwidth ** 2))\n\n # These kernels are not implemented yet\n # # Select type of kernel to compute\n # if self.kernel_type == 'linear':\n # # Linear kernel is data outer product\n # return np.dot(X, Z.T)\n # elif self.kernel_type == 'polynomial':\n # # Polynomial kernel is an exponentiated data outer product\n # return (np.dot(X, Z.T) + 1) ** self.order\n # elif self.kernel_type == 'sigmoid':\n # # Sigmoidal kernel\n # return 1. / (1 + np.exp(np.dot(X, Z.T)))\n\n\n def optimize_SVDD(self, X, y, c):\n # Solve (quadratic) SVDD program.\n # Maximize Lagrangian by minimizing negation:\n # a'.T @ K @ a' - diag(K).T @ a' (Eq. 2.28)\n\n # Subject to 0 <= a' <= C (Box constraints, Eq. 2.20)\n # 1.T a' = 1 (Equality constraint, Eq. 2.6 and 2.18)\n\n # where a' = y * a (Eq. 2.22)\n\n # CVXOPT has following format:\n # https://github.com/cvxopt/cvxopt/blob/cc46cbd0cea40cdb8c6e272d3e709c268cd38468/src/python/coneprog.py#L4156\n # Minimize (1/2) x.T P x + q.T x\n #\n # Subject to G x <= h\n # A x = b\n\n # TODO: wait, I am not actually substituting a' in the box constraints\n # TODO: Is this valid!!???\n # Therefore, box constraints are rewritten to:\n # -I a' <= 0\n # I a' <= C\n # Where I is the identity matrix\n\n # CVXOPT does not accept integers\n y = np.double(y)\n\n K = self.compute_kernel(X, X)\n # self.K = K\n N = K.shape[0]\n # Incorporate labels y in kernel matrix to rewrite in standard form (again, Eq. 2.22)\n P = np.outer(y, y) * K\n\n q = matrix(- y * np.diag(P))\n # self.q = q\n # Regularize quadratic part if not positive definite\n i = -30\n posdef_warning = False\n I_matrix = np.eye(N)\n while not self.is_pos_def(P + (10.0 ** i) * I_matrix):\n if not posdef_warning:\n print('Warning: matrix not positive definite. Started regularization')\n posdef_warning = True\n\n i = i + 1\n P = P + (10.0 ** i) * I_matrix\n # self.P = P\n print(\"Finished regularization\")\n P = matrix(2*P)\n\n lb = np.zeros(N)\n\n # Either assign C for every sample\n if len(c) > 2:\n ub = c\n # Or one for the inliers and outliers separately.\n else:\n ub = np.zeros(N)\n ub[y == 1] = c[0]\n ub[y == -1] = c[1]\n\n # Equality constraint\n A = matrix(y, (1, N), 'd')\n b = matrix(1.0)\n\n # Box constraints written as inequality constraints\n # With correct substitution of alpha incorporating labels\n # = matrix(np.vstack([-np.eye(N)*y, np.eye(N)*y]), (2 * N, N))\n\n G = matrix(np.vstack([-np.eye(N), np.eye(N)]), (2 * N, N))\n h = matrix(np.hstack([lb, ub]), (2 * N, 1))\n\n # Find optimal alphas\n solvers.options['show_progress'] = False\n res = solvers.qp(P, q, G, h, A, b)\n\n alfs = np.array(res['x']).ravel()\n\n # TODO: Figure out if the multiplication by one in the paper is valid\n # % Important: change sign for negative examples:\n alfs = y * alfs\n\n # The support vectors:\n SV_inds = np.where(abs(alfs) > 1e-8)[0]\n\n # Eq. 2.12, second term: Distance to center of the sphere (ignoring the offset):\n self.Dx = -2 * np.sum(np.outer(np.ones(N), alfs) * K, axis=1)\n\n # Support vectors where 0 < alpha_i < C_i for every i\n borderx = SV_inds[np.where((alfs[SV_inds] < ub[SV_inds]) & (alfs[SV_inds] > 1e-8))[0]]\n if np.shape(borderx)[0] < 1:\n borderx = SV_inds\n\n # Although all support vectors should give the same results, sometimes\n # they do not.\n self.R2 = np.mean(self.Dx[borderx])\n\n # Set all nonl-support-vector alpha to 0\n alfs[abs(alfs) < 1e-8] = 0.0\n\n return (alfs, self.R2, self.Dx, SV_inds)\n\n def fit(self, X, y):\n # Setup the appropriate C's\n self.C = np.zeros(2)\n nrtar = len(np.where(y == 1)[0])\n nrout = len(np.where(y == -1)[0])\n \n # we could get divide by zero, but that is ok.\n self.C[0] = 1/(nrtar*self.fracrej[0])\n self.C[1] = 1/(nrout*self.fracrej[1])\n\n # Only for comparison test with Matlab version\n # self.C = np.array([1, 1])\n alfs, R2, Dx, SV_inds = self.optimize_SVDD(X, y, self.C)\n\n self.SVx = X[SV_inds, :] # (data corresponding to support vectors)\n self.SV_alfs = alfs[SV_inds] # support vectors\n self.alfs = alfs\n self.SV_inds = SV_inds\n\n # Compute the offset (Eq. 2.12, First and last term):\n # Not essential, but now gives the possibility to\n # interpret the output as the distance to the center of the sphere.\n self.offs = 1 + self.SV_alfs.T @ self.compute_kernel(self.SVx, self.SVx) @ self.SV_alfs\n # Eq. 2.12: Include second term to determine threshold\n self.threshold = self.offs + R2\n\n # Only for comparison test with Matlab version\n # return (alfs, R2, Dx, SV_inds)\n\n # Scikit learn requires to return the classifier instance.\n return self\n\n def predict(self, X):\n # # Number of test samples\n # self.m = np.shape(X)[0]\n #\n # # Eq. 2.11: Distance of test objects to center of sphere\n # K = self.compute_kernel(X, self.SVx)\n # self.out = self.offs - 2 * K @ self.SV_alfs\n self.out = self.decision_function(X)\n\n self.newout = np.vstack([self.out, -1 * np.ones(self.m) * self.threshold])\n\n # Eq. 2.14: Indicator function\n I_out = np.greater_equal(self.newout[0, :], self.newout[1, :]).astype(int)\n\n # Assign predicted labels\n I_out[I_out == 0] = -1\n\n return I_out\n def decision_function(self, X):\n # Number of test samples\n self.m = np.shape(X)[0]\n\n # Eq. 2.11: Distance of test objects to center of sphere\n K = self.compute_kernel(X, self.SVx)\n out = self.offs - 2 * K @ self.SV_alfs\n\n return -1 * out\n\n def is_pos_def(self, X):\n \"\"\"Check for positive definiteness.\"\"\"\n try:\n cholesky(X)\n return True\n except LinAlgError:\n return False\n\n def _plot_contour(self, X, y, lims=None):\n\n fig, ax = plt.subplots()\n ax.scatter(X[y == 1, 0], X[y == 1, 1], c='b', marker='+', zorder=2, label='target')\n ax.scatter(X[y == -1, 0], X[y == -1, 1], facecolors='none', edgecolors='r', zorder=2, label='outlier')\n\n # If train data is included in plot, mark the support vectors\n if self.SVx[0] in X:\n ax.scatter(X[self.SV_inds, 0], X[self.SV_inds, 1], facecolors='none', edgecolors='white', zorder=2, label='support vector')\n\n # Define plot boundaries manually\n if lims:\n ax.set_xlim(lims[0:2])\n ax.set_ylim(lims[2:])\n\n ymin, ymax = ax.get_ylim()\n xmin, xmax = ax.get_xlim()\n delta = 0.025\n # x1 = np.arange(X[:, 0].min(), X[:, 0].max(), delta)\n # x2 = np.arange(X[:, 1].min(), X[:, 1].max(), delta)\n x1 = np.arange(xmin, xmax, delta)\n x2 = np.arange(ymin, ymax, delta)\n\n X1, X2 = np.meshgrid(x1, x2)\n X_grid = np.vstack([X1.ravel(), X2.ravel()]).T\n\n K = self.compute_kernel(X_grid, self.SVx)\n Z = (self.offs - 2 * K @ self.SV_alfs).reshape(np.shape(X1))\n ax.contourf(X1, X2, Z, cmap=cm.gray, levels=50)\n\n # Draw decision line\n ax.contour(X1, X2, Z, levels=(self.threshold,), colors='white', linestyles='dashed', zorder=1)\n plt.legend(facecolor='grey')\n plt.title(\"SVDD contour map\")\n plt.savefig('test.pdf', bbox_inches='tight', pad_inches=0)\n\n return plt\n"
] | [
[
"numpy.diag",
"matplotlib.pyplot.legend",
"numpy.mean",
"numpy.where",
"numpy.double",
"numpy.hstack",
"numpy.arange",
"numpy.eye",
"numpy.greater_equal",
"numpy.outer",
"numpy.zeros",
"matplotlib.pyplot.title",
"scipy.spatial.distance.cdist",
"matplotlib.pyplot.savefig",
"numpy.meshgrid",
"numpy.array",
"matplotlib.pyplot.subplots",
"numpy.ones",
"scipy.linalg.cholesky",
"numpy.shape"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.12",
"0.14",
"0.15"
],
"tensorflow": []
}
] |
Joukahainen/chartpy | [
"410f9e4553cb07be7d11823cad404f10da079ada"
] | [
"chartpy/chart.py"
] | [
"__author__ = 'saeedamen' # Saeed Amen\n\n#\n# Copyright 2016 Cuemacro\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the\n# License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# See the License for the specific language governing permissions and limitations under the License.\n#\n\nfrom chartpy.twitter import Twitter\nfrom chartpy.chartconstants import ChartConstants\nfrom chartpy.style import Style\nfrom chartpy.engine import EngineMatplotlib, EngineBokeh, EngineBqplot, EnginePlotly, EngineVisPy\n\nimport pandas\n\n\nclass Chart(object):\n \"\"\"Creates chart using several underlying plotting libraries (Matplotlib, Plotly and Bokeh) using the same interface\n \"\"\"\n\n def __init__(self, df=None, engine=None, chart_type=None, style=None):\n\n self.df = None\n self.engine = ChartConstants().chartfactory_default_engine\n self.style = Style()\n self.chart_type = 'line' # default chart type is line chart\n self.is_plotted = False\n\n if df is not None: self.df = df\n if engine is not None: self.engine = engine\n if chart_type is not None: self.chart_type = chart_type\n if style is not None: self.style = style\n\n pass\n\n ##### implemented chart types:\n ##### heatmap (Plotly)\n ##### line (Bokeh, Matplotlib, Plotly, vispy)\n ##### bar (Bokeh, Matplotlib, Plotly)\n ##### stacked (Bokeh, Matplotlib, Plotly)\n ##### surface (Plotly)\n def plot(self, df=None, engine=None, chart_type=None, style=None, twitter_msg=None, twitter_on=False):\n\n if style is None: style = self.style\n if df is None: df = self.df\n\n if engine is None:\n try:\n engine = style.engine\n except:\n engine = self.engine\n\n if chart_type is None:\n chart_type = self.chart_type\n\n try:\n if style.chart_type is not None:\n chart_type = style.chart_type\n except:\n pass\n\n if isinstance(df, list):\n for i in range(0, len(df)):\n if isinstance(df[i], pandas.Series):\n df[i] = pandas.DataFrame(df[i])\n else:\n if isinstance(df, pandas.Series):\n df = pandas.DataFrame(df)\n\n if engine is None:\n fig = self.get_engine(engine).plot_chart(df, style, chart_type)\n else:\n if isinstance(engine, str):\n fig = self.get_engine(engine).plot_chart(df, style, chart_type)\n else:\n fig = self.engine.plot_chart(df, style, chart_type)\n\n if twitter_on:\n twitter = Twitter()\n twitter.auto_set_key()\n twitter.update_status(twitter_msg, picture=style.file_output)\n\n self.is_plotted = True\n\n return fig\n\n def get_engine(self, engine):\n\n if engine is None:\n return self.get_engine(self.engine)\n elif engine == 'matplotlib':\n return EngineMatplotlib()\n elif engine == 'bokeh':\n return EngineBokeh()\n elif engine == 'bqplot':\n return EngineBqplot()\n elif engine == 'vispy':\n return EngineVisPy()\n elif engine == 'plotly':\n return EnginePlotly()\n\n return None\n\n # TODO fix this\n def _iplot(self, data_frame, engine=None, chart_type=None, style=None):\n return Chart.get_engine(engine).plot_chart(data_frame, style, chart_type)\n\n#######################################################################################################################\n"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
pmdaly/supereeg | [
"750f55db3cbfc2f3430e879fecc7a1f5407282a6"
] | [
"tests/test_load.py"
] | [
"from builtins import str\nfrom builtins import range\nimport supereeg as se\nimport numpy as np\nimport os\nimport nibabel as nib\nimport pytest\n\nbo = se.load('example_data')\nbo_s = bo.get_slice(sample_inds=[0,1,2])\n\nlocs = np.array([[-61., -77., -3.],\n [-41., -77., -23.],\n [-21., -97., 17.],\n [-21., -37., 77.],\n [-21., 63., -3.],\n [ -1., -37., 37.],\n [ -1., 23., 17.],\n [ 19., -57., -23.],\n [ 19., 23., -3.],\n [ 39., -57., 17.],\n [ 39., 3., 37.],\n [ 59., -17., 17.]])\n\nn_samples = 10\nn_subs = 3\nn_elecs = 10\ndata = [se.simulate_model_bos(n_samples=10, sample_rate=10, locs=locs,\n sample_locs = n_elecs) for x in range(n_subs)]\ntest_bo = data[0]\ntest_model = se.Model(data=data, locs=locs, rbf_width=20)\nbo = se.load('example_data')\n\ndef test_load_example_data():\n bo = se.load('example_data')\n assert isinstance(bo, se.Brain)\n\ndef test_load_example_filter():\n bo = se.load('example_filter')\n assert isinstance(bo, se.Brain)\n\ndef test_load_example_model():\n model = se.load('example_model')\n assert isinstance(model, se.Model)\n\ndef test_load_nifti():\n nii = se.load('example_nifti')\n assert isinstance(nii, nib.nifti1.Nifti1Image)\n\n# def test_load_pyFR_union():\n# data = se.load('pyFR_union')\n# assert isinstance(data, np.ndarray)\n\n# def test_load_pyFR():\n# model = se.load('pyFR')\n# assert isinstance(model, se.Model)\n\ndef test_bo_load(tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"example\")\n test_bo.save(fname=p.strpath)\n bo = se.load(os.path.join(p.strpath + '.bo'))\n assert isinstance(bo, se.Brain)\n\ndef test_mo_load(tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"example\")\n test_model.save(fname=p.strpath)\n bo = se.load(os.path.join(p.strpath + '.mo'))\n assert isinstance(bo, se.Model)\n\ndef test_nii_load(tmpdir):\n p = tmpdir.mkdir(\"sub\").join(\"example\")\n test_bo.to_nii(filepath=p.strpath)\n nii = se.load(os.path.join(p.strpath + '.nii'))\n assert isinstance(nii, nib.nifti1.Nifti1Image)\n\ndef test_return_type_bo_with_bo():\n bo = se.load('example_data', return_type='bo')\n assert isinstance(bo, se.Brain)\n\ndef test_return_type_bo_with_mo():\n bo = se.load('example_model', return_type='bo')\n assert isinstance(bo, se.Brain)\n\ndef test_return_type_bo_with_nii():\n bo = se.load('example_nifti', return_type='bo')\n assert isinstance(bo, se.Brain)\n\ndef test_return_type_mo_with_bo():\n mo = se.load('example_data', return_type='mo')\n assert isinstance(mo, se.Model)\n\n#TODO: COMMENTING OUT UNTIL EXAMPLE_MODEL IS REBUILT WITH NEW REFACTOR\n#def test_return_type_mo_with_mo():\n# mo = se.load('example_model', return_type='mo')\n# assert isinstance(mo, se.Model)\n\n# # passes nbut test takes a lot longer (like 10 seconds)\n# def test_return_type_mo_with_nii():\n# mo = se.load('example_nifti', return_type='mo')\n# assert isinstance(mo, se.Model)\n\n# passes\ndef test_return_type_nii_with_bo():\n nii = se.load('example_data', return_type='nii')\n assert isinstance(nii, se.Nifti)\n\n# passes\n#TODO: COMMENTING OUT UNTIL EXAMPLE_MODEL IS REBUILT WITH NEW REFACTOR\n#def test_return_type_nii_with_mo():\n #nii = se.load('example_model', return_type='nii')\n #assert isinstance(nii, se.Nifti)\n\n# passes\ndef test_return_type_nii_with_nii():\n nii = se.load('example_nifti', return_type='nii')\n assert isinstance(nii, se.Nifti)\n\ndef test_bo_load_slice1():\n bo = se.load('example_data', sample_inds=range(10))\n assert bo.data.shape==(10,64)\n\ndef test_bo_load_slice2():\n bo = se.load('example_data', sample_inds=range(10), loc_inds=0)\n assert bo.data.shape==(10,1)\n\ndef test_bo_load_slice3():\n bo = se.load('example_data', sample_inds=0, loc_inds=range(10))\n assert bo.data.shape==(1,10)\n\ndef test_bo_load_slice4():\n bo = se.load('example_data', sample_inds=0, loc_inds=0)\n assert bo.data.shape==(1,1)\n\ndef test_bo_load_slice_raise_error():\n with pytest.raises(IndexError):\n bo = se.load('example_data', sample_inds=range(10), loc_inds=range(10))\n\ndef test_bo_load_field_raise_error():\n with pytest.raises(ValueError):\n bo = se.load('example_data', field='locs', sample_inds=range(10),\n loc_inds=range(10))\n\ndef test_bo_load_field_locs():\n locs = se.load('example_data', field='locs')\n assert locs.shape[0]==64\n\ndef test_model_load_field_locs():\n locs = se.load('example_model', field='locs')\n assert locs.shape[0]==210\n\ndef test_model_load_field_nii_raise_error():\n with pytest.raises(ValueError):\n bo = se.load('example_nifti', field='locs')\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
granttremblay/SloanSpec | [
"5f8879429f7735cd22c61b1c1930b3d3451a5c09"
] | [
"sloanspec/sloanspec.py"
] | [
"\"\"\"Handle an SDSS Spectrum in an object-oriented manner.\"\"\"\n\nimport os\nfrom astropy.io import fits\n\n\nclass SloanSpec(object):\n \"\"\"\n A single SDSS Spectrum, read from a spec-PLATE-MJD-FIBER.fits file.\n\n See the datamodel for details about the file:\n http://data.sdss3.org/datamodel/files/BOSS_SPECTRO_REDUX/RUN2D/spectra/PLATE4/spec.html\n \"\"\"\n\n def __init__(self,filepath):\n \"\"\"Initialize\"\"\"\n self.filepath = filepath\n self.data = fits.open(filepath)\n self.basename = os.path.splitext(os.path.basename(filepath))[0]\n junk,self.plate,self.mjd,self.fiber = self.basename.split('-')\n\n @property\n def wavelength(self):\n \"\"\"Wavelength binning, linear bins.\"\"\"\n if getattr(self,'_wavelength',None) is None:\n self._wavelength = 10**self.data[1].data['loglam']\n return self._wavelength\n\n @property\n def flux(self):\n if getattr(self,'_flux',None) is None:\n self._flux = self.data[1].data['flux']\n return self._flux\n\n @property\n def error(self):\n if getattr(self,'_error',None) is None:\n self._error = 1/self.data[1].data['ivar']\n return self._error\n\n @property\n def sky(self):\n if getattr(self,'_sky',None) is None:\n self._sky = self.data[1].data['sky']\n return self._sky\n\n @property\n def model(self):\n if getattr(self,'_model',None) is None:\n self._model = self.data[1].data['model']\n return self._model\n\n def plot(self, savedir=None):\n \"\"\"Create a plot using the specified matplotlib pyplot/gridspec instance.\"\"\"\n\n # NOTE: cannot pickle matplotlib.pyplot (necessary for multiprocessing.map)\n # so we have to handle all plotting setup inside here.\n\n from matplotlib import gridspec\n import matplotlib.pyplot as plt\n plt.rcParams.update({'font.size':22,\n 'axes.labelsize': 20,\n 'legend.fontsize': 16,\n 'xtick.labelsize': 18,\n 'ytick.labelsize': 18,\n 'axes.linewidth':2})\n\n fig = plt.figure(figsize=(12,8))\n gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])\n ax0 = plt.subplot(gs[0])\n ax1 = plt.subplot(gs[1],sharex=ax0)\n plt.setp(ax0.get_xticklabels(), visible=False)\n\n ax0.plot(self.wavelength, self.sky, color='lightblue', lw=1, label='sky')\n ax0.plot(self.wavelength, self.flux, color='black', lw=2, label='flux')\n ax0.plot(self.wavelength, self.model, color='green', label='model')\n ax0.plot(self.wavelength, self.error, color='red', label='error')\n ax0.set_ylim(-3, self.flux.max()*1.1)\n ax0.set_xlabel('Wavelength [$\\AA$]')\n ax0.set_ylabel('Flux [$10^{-17} \\mathrm{ergs}\\, \\mathrm{s}^{-1} \\mathrm{cm}^{-2} \\mathrm{\\AA}^{-1}$]')\n\n # put the legend on the right or left, depending on the height of the data.\n if self.flux[:100].mean() > self.flux[-100:].mean():\n ax0.legend(loc='upper right',labelspacing=.2)\n else:\n ax0.legend(loc='upper left',labelspacing=.2)\n\n ax1.axhline(0,color='grey')\n ax1.plot(self.wavelength, self.flux-self.model, color='green', label='SDSS model')\n ax1.set_ylim(-5,5)\n ax1.set_yticks(range(-4,5,2))\n ax1.set_ylabel('flux-model')\n\n fig.subplots_adjust(hspace=0)\n ax0.set_xlim(self.wavelength.min(), self.wavelength.max())\n\n plt.suptitle('plate={} mjd={} fiber={}'.format(self.plate,self.mjd,self.fiber))\n\n if savedir is not None:\n plt.savefig(os.path.join(savedir,self.basename+'.pdf'),bbox_inches='tight')\n"
] | [
[
"matplotlib.pyplot.rcParams.update",
"matplotlib.pyplot.subplot",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tufts-ml/false-alarm-control | [
"e9dd263d7a98dde53b6b43c1b379fe6075a3f857"
] | [
"AdversarialPredictionUtils.py"
] | [
"import sys\nimport os\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader, random_split\n\nfrom sklearn.preprocessing import StandardScaler\n\nfrom ap_perf import PerformanceMetric, MetricLayer\n\nnp.random.seed(0)\n\ndef create_toy_data():\n #create toy data\n # generate 225 positive data points\n n_P = [30, 60, 30]\n # n_P = [60, 120, 60]\n P = 3\n prng = np.random.RandomState(101)\n\n # the first 25 data points come from mean 2-D mvn with mean [1, 2.5] and next 200 come from\n # 2-D mvn with mean [1, 1]\n mu_PD = np.asarray([\n [0.7, 2.5],\n [0.7, 1.0],\n [0.7, 0.0]])\n\n cov_PDD = np.vstack([\n np.diag([0.06, 0.1])[np.newaxis,:],\n np.diag([0.1, 0.1])[np.newaxis,:],\n np.diag([0.06, 0.06])[np.newaxis,:],\n ])\n\n xpos_list = list()\n for p in range(P):\n x_ND = prng.multivariate_normal(mu_PD[p], cov_PDD[p], size=n_P[p])\n xpos_list.append(x_ND)\n x_pos_ND = np.vstack(xpos_list)\n y_pos_N = np.ones(x_pos_ND.shape[0])\n\n # generate 340 negative data points\n n_P = [400, 30, 20]\n # n_P = [800, 60, 40]\n P = 3\n prng = np.random.RandomState(201)\n\n # the first 300 data points come from mean 2-D mvn with mean [2.2, 1.5] and next 20 come from\n # 2-D mvn with mean [0, 3] and next 20 from 2-D mvn with mean [0, 0.5]\n mu_PD = np.asarray([\n [2.25, 1.5],\n [0.0, 3.0],\n [0.0, 0.5],\n ])\n\n cov_PDD = np.vstack([\n np.diag([.1, .2])[np.newaxis,:],\n np.diag([.05, .05])[np.newaxis,:],\n np.diag([.05, .05])[np.newaxis,:],\n ])\n\n xneg_list = list()\n for p in range(P):\n x_ND = prng.multivariate_normal(mu_PD[p], cov_PDD[p], size=n_P[p])\n xneg_list.append(x_ND)\n x_neg_ND = np.vstack(xneg_list)\n y_neg_N = np.zeros(x_neg_ND.shape[0])\n\n x_ND = np.vstack([x_pos_ND, x_neg_ND])\n y_N = np.hstack([y_pos_N, y_neg_N])\n\n x_ND = (x_ND - np.mean(x_ND, axis=0))/np.std(x_ND, axis=0)\n\n x_pos_ND = x_ND[y_N == 1]\n x_neg_ND = x_ND[y_N == 0]\n\n return x_ND, y_N\n\n\nclass TabularDataset(Dataset):\n def __init__(self, X, y):\n self.X = X\n self.y = y\n\n def __len__(self):\n return len(self.y)\n\n def __getitem__(self, idx):\n return [self.X[idx, :], self.y[idx]]\n\n \nclass LinearClassifier(nn.Module):\n def __init__(self, nvar):\n super().__init__()\n self.fc1 = nn.Linear(nvar, 1)\n self.double()\n \n def forward(self, x):\n x = self.fc1(x)\n return x.squeeze()\n\n\n\nclass RecallGvPrecision(PerformanceMetric):\n def __init__(self, th):\n self.th = th\n\n def define(self, C):\n return C.tp / C.ap \n\n def constraint(self, C):\n return C.tp / C.pp >= self.th \n\n \nif __name__=='__main__':\n precision_gv_recall_80 = PrecisionGvRecall(0.8)\n precision_gv_recall_80.initialize()\n precision_gv_recall_80.enforce_special_case_positive()\n precision_gv_recall_80.set_cs_special_case_positive(True)\n\n recall_gv_precision_80 = RecallGvPrecision(0.8)\n recall_gv_precision_80.initialize()\n recall_gv_precision_80.enforce_special_case_positive()\n recall_gv_precision_80.set_cs_special_case_positive(True)\n\n\n # performance metric\n pm = recall_gv_precision_80\n\n\n X_tr, y_tr = create_toy_data()\n\n trainset = TabularDataset(X_tr, y_tr)\n # testset = TabularDataset(X_ts, y_ts)\n\n\n batch_size = len(X_tr) # full batch\n trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)\n\n method = \"ap-perf\" # uncomment if we want to use ap-perf objective \n # method = \"bce-loss\" # uncomment if we want to use bce-loss objective\n\n torch.manual_seed(189)\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n nvar = X_tr.shape[1]\n model = LR(nvar).to(device)\n\n if method == \"ap-perf\":\n criterion = MetricLayer(precision_gv_recall_80).to(device)\n lr = 3e-3\n weight_decay = 0\n else:\n criterion = nn.BCEWithLogitsLoss().to(device)\n lr = 1e-2\n weight_decay = 1e-3\n\n optimizer = optim.SGD(model.parameters(), lr=lr, weight_decay=weight_decay)\n\n for epoch in range(2): # epoch 2 was the best checkpoint after running 50 epochs\n\n for i, (inputs, labels) in enumerate(trainloader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n optimizer.zero_grad()\n output = model(inputs)\n\n loss = criterion(output, labels)\n\n loss.backward()\n optimizer.step()\n\n if epoch>=2:\n optimizer.param_groups[0]['lr'] = 0.1*optimizer.param_groups[0]['lr']\n\n sys.stdout.write(\"\\r#%d | progress : %d%%\" % (epoch, int(100 * (i+1) / len(trainloader))))\n sys.stdout.flush()\n\n print()\n\n # evaluate after each epoch\n model.eval()\n\n # train\n train_data = torch.tensor(X_tr).to(device)\n tr_output = model(train_data)\n tr_pred = (tr_output >= 0.0).float()\n tr_pred_np = tr_pred.cpu().numpy()\n\n train_acc = np.sum(y_tr == tr_pred_np) / len(y_tr)\n train_metric = pm.compute_metric(tr_pred_np, y_tr)\n train_constraint = pm.compute_constraints(tr_pred_np, y_tr)\n\n\n model.train()\n\n print('#{} | Acc tr: {:.5f} | Metric tr: {:.5f} | Constraint tr: {:.5f}'.format(\n epoch, train_acc, train_metric, train_constraint[0]))\n \n"
] | [
[
"numpy.diag",
"numpy.hstack",
"numpy.random.seed",
"numpy.asarray",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"numpy.ones",
"torch.tensor",
"torch.nn.Linear",
"numpy.std",
"torch.nn.BCEWithLogitsLoss",
"numpy.mean",
"torch.cuda.is_available",
"torch.device",
"numpy.random.RandomState",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hwong557/tutorials | [
"5eaaf35080dee4545f4b3c6762d82b5487a34e22"
] | [
"beginner_source/nn_tutorial.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nWhat is `torch.nn` *really*?\n============================\nby Jeremy Howard, `fast.ai <https://www.fast.ai>`_. Thanks to Rachel Thomas and Francisco Ingham.\n\"\"\"\n###############################################################################\n# We recommend running this tutorial as a notebook, not a script. To download the notebook (.ipynb) file,\n# click the link at the top of the page.\n#\n# PyTorch provides the elegantly designed modules and classes `torch.nn <https://pytorch.org/docs/stable/nn.html>`_ ,\n# `torch.optim <https://pytorch.org/docs/stable/optim.html>`_ ,\n# `Dataset <https://pytorch.org/docs/stable/data.html?highlight=dataset#torch.utils.data.Dataset>`_ ,\n# and `DataLoader <https://pytorch.org/docs/stable/data.html?highlight=dataloader#torch.utils.data.DataLoader>`_\n# to help you create and train neural networks.\n# In order to fully utilize their power and customize\n# them for your problem, you need to really understand exactly what they're\n# doing. To develop this understanding, we will first train basic neural net\n# on the MNIST data set without using any features from these models; we will\n# initially only use the most basic PyTorch tensor functionality. Then, we will\n# incrementally add one feature from ``torch.nn``, ``torch.optim``, ``Dataset``, or\n# ``DataLoader`` at a time, showing exactly what each piece does, and how it\n# works to make the code either more concise, or more flexible.\n#\n# **This tutorial assumes you already have PyTorch installed, and are familiar\n# with the basics of tensor operations.** (If you're familiar with Numpy array\n# operations, you'll find the PyTorch tensor operations used here nearly identical).\n#\n# MNIST data setup\n# ----------------\n#\n# We will use the classic `MNIST <http://deeplearning.net/data/mnist/>`_ dataset,\n# which consists of black-and-white images of hand-drawn digits (between 0 and 9).\n#\n# We will use `pathlib <https://docs.python.org/3/library/pathlib.html>`_\n# for dealing with paths (part of the Python 3 standard library), and will\n# download the dataset using\n# `requests <http://docs.python-requests.org/en/master/>`_. We will only\n# import modules when we use them, so you can see exactly what's being\n# used at each point.\n\nfrom pathlib import Path\nimport requests\n\nDATA_PATH = Path(\"data\")\nPATH = DATA_PATH / \"mnist\"\n\nPATH.mkdir(parents=True, exist_ok=True)\n\nURL = \"https://github.com/pytorch/tutorials/raw/master/_static/\"\nFILENAME = \"mnist.pkl.gz\"\n\nif not (PATH / FILENAME).exists():\n content = requests.get(URL + FILENAME).content\n (PATH / FILENAME).open(\"wb\").write(content)\n\n###############################################################################\n# This dataset is in numpy array format, and has been stored using pickle,\n# a python-specific format for serializing data.\n\nimport pickle\nimport gzip\n\nwith gzip.open((PATH / FILENAME).as_posix(), \"rb\") as f:\n ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding=\"latin-1\")\n\n###############################################################################\n# Each image is 28 x 28, and is being stored as a flattened row of length\n# 784 (=28x28). Let's take a look at one; we need to reshape it to 2d\n# first.\n\nfrom matplotlib import pyplot\nimport numpy as np\n\npyplot.imshow(x_train[0].reshape((28, 28)), cmap=\"gray\")\nprint(x_train.shape)\n\n###############################################################################\n# PyTorch uses ``torch.tensor``, rather than numpy arrays, so we need to\n# convert our data.\n\nimport torch\n\nx_train, y_train, x_valid, y_valid = map(\n torch.tensor, (x_train, y_train, x_valid, y_valid)\n)\nn, c = x_train.shape\nx_train, x_train.shape, y_train.min(), y_train.max()\nprint(x_train, y_train)\nprint(x_train.shape)\nprint(y_train.min(), y_train.max())\n\n###############################################################################\n# Neural net from scratch (no torch.nn)\n# ---------------------------------------------\n#\n# Let's first create a model using nothing but PyTorch tensor operations. We're assuming\n# you're already familiar with the basics of neural networks. (If you're not, you can\n# learn them at `course.fast.ai <https://course.fast.ai>`_).\n#\n# PyTorch provides methods to create random or zero-filled tensors, which we will\n# use to create our weights and bias for a simple linear model. These are just regular\n# tensors, with one very special addition: we tell PyTorch that they require a\n# gradient. This causes PyTorch to record all of the operations done on the tensor,\n# so that it can calculate the gradient during back-propagation *automatically*!\n#\n# For the weights, we set ``requires_grad`` **after** the initialization, since we\n# don't want that step included in the gradient. (Note that a trailing ``_`` in\n# PyTorch signifies that the operation is performed in-place.)\n#\n# .. note:: We are initializing the weights here with\n# `Xavier initialisation <http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf>`_\n# (by multiplying with 1/sqrt(n)).\n\nimport math\n\nweights = torch.randn(784, 10) / math.sqrt(784)\nweights.requires_grad_()\nbias = torch.zeros(10, requires_grad=True)\n\n###############################################################################\n# Thanks to PyTorch's ability to calculate gradients automatically, we can\n# use any standard Python function (or callable object) as a model! So\n# let's just write a plain matrix multiplication and broadcasted addition\n# to create a simple linear model. We also need an activation function, so\n# we'll write `log_softmax` and use it. Remember: although PyTorch\n# provides lots of pre-written loss functions, activation functions, and\n# so forth, you can easily write your own using plain python. PyTorch will\n# even create fast GPU or vectorized CPU code for your function\n# automatically.\n\ndef log_softmax(x):\n return x - x.exp().sum(-1).log().unsqueeze(-1)\n\ndef model(xb):\n return log_softmax(xb @ weights + bias)\n\n###############################################################################\n# In the above, the ``@`` stands for the dot product operation. We will call\n# our function on one batch of data (in this case, 64 images). This is\n# one *forward pass*. Note that our predictions won't be any better than\n# random at this stage, since we start with random weights.\n\nbs = 64 # batch size\n\nxb = x_train[0:bs] # a mini-batch from x\npreds = model(xb) # predictions\npreds[0], preds.shape\nprint(preds[0], preds.shape)\n\n###############################################################################\n# As you see, the ``preds`` tensor contains not only the tensor values, but also a\n# gradient function. We'll use this later to do backprop.\n#\n# Let's implement negative log-likelihood to use as the loss function\n# (again, we can just use standard Python):\n\n\ndef nll(input, target):\n return -input[range(target.shape[0]), target].mean()\n\nloss_func = nll\n\n###############################################################################\n# Let's check our loss with our random model, so we can see if we improve\n# after a backprop pass later.\n\nyb = y_train[0:bs]\nprint(loss_func(preds, yb))\n\n\n###############################################################################\n# Let's also implement a function to calculate the accuracy of our model.\n# For each prediction, if the index with the largest value matches the\n# target value, then the prediction was correct.\n\ndef accuracy(out, yb):\n preds = torch.argmax(out, dim=1)\n return (preds == yb).float().mean()\n\n###############################################################################\n# Let's check the accuracy of our random model, so we can see if our\n# accuracy improves as our loss improves.\n\nprint(accuracy(preds, yb))\n\n###############################################################################\n# We can now run a training loop. For each iteration, we will:\n#\n# - select a mini-batch of data (of size ``bs``)\n# - use the model to make predictions\n# - calculate the loss\n# - ``loss.backward()`` updates the gradients of the model, in this case, ``weights``\n# and ``bias``.\n#\n# We now use these gradients to update the weights and bias. We do this\n# within the ``torch.no_grad()`` context manager, because we do not want these\n# actions to be recorded for our next calculation of the gradient. You can read\n# more about how PyTorch's Autograd records operations\n# `here <https://pytorch.org/docs/stable/notes/autograd.html>`_.\n#\n# We then set the\n# gradients to zero, so that we are ready for the next loop.\n# Otherwise, our gradients would record a running tally of all the operations\n# that had happened (i.e. ``loss.backward()`` *adds* the gradients to whatever is\n# already stored, rather than replacing them).\n#\n# .. tip:: You can use the standard python debugger to step through PyTorch\n# code, allowing you to check the various variable values at each step.\n# Uncomment ``set_trace()`` below to try it out.\n#\n\nfrom IPython.core.debugger import set_trace\n\nlr = 0.5 # learning rate\nepochs = 2 # how many epochs to train for\n\nfor epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n # set_trace()\n start_i = i * bs\n end_i = start_i + bs\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n with torch.no_grad():\n weights -= weights.grad * lr\n bias -= bias.grad * lr\n weights.grad.zero_()\n bias.grad.zero_()\n\n###############################################################################\n# That's it: we've created and trained a minimal neural network (in this case, a\n# logistic regression, since we have no hidden layers) entirely from scratch!\n#\n# Let's check the loss and accuracy and compare those to what we got\n# earlier. We expect that the loss will have decreased and accuracy to\n# have increased, and they have.\n\nprint(loss_func(model(xb), yb), accuracy(model(xb), yb))\n\n###############################################################################\n# Using torch.nn.functional\n# ------------------------------\n#\n# We will now refactor our code, so that it does the same thing as before, only\n# we'll start taking advantage of PyTorch's ``nn`` classes to make it more concise\n# and flexible. At each step from here, we should be making our code one or more\n# of: shorter, more understandable, and/or more flexible.\n#\n# The first and easiest step is to make our code shorter by replacing our\n# hand-written activation and loss functions with those from ``torch.nn.functional``\n# (which is generally imported into the namespace ``F`` by convention). This module\n# contains all the functions in the ``torch.nn`` library (whereas other parts of the\n# library contain classes). As well as a wide range of loss and activation\n# functions, you'll also find here some convenient functions for creating neural\n# nets, such as pooling functions. (There are also functions for doing convolutions,\n# linear layers, etc, but as we'll see, these are usually better handled using\n# other parts of the library.)\n#\n# If you're using negative log likelihood loss and log softmax activation,\n# then Pytorch provides a single function ``F.cross_entropy`` that combines\n# the two. So we can even remove the activation function from our model.\n\nimport torch.nn.functional as F\n\nloss_func = F.cross_entropy\n\ndef model(xb):\n return xb @ weights + bias\n\n###############################################################################\n# Note that we no longer call ``log_softmax`` in the ``model`` function. Let's\n# confirm that our loss and accuracy are the same as before:\n\nprint(loss_func(model(xb), yb), accuracy(model(xb), yb))\n\n###############################################################################\n# Refactor using nn.Module\n# -----------------------------\n# Next up, we'll use ``nn.Module`` and ``nn.Parameter``, for a clearer and more\n# concise training loop. We subclass ``nn.Module`` (which itself is a class and\n# able to keep track of state). In this case, we want to create a class that\n# holds our weights, bias, and method for the forward step. ``nn.Module`` has a\n# number of attributes and methods (such as ``.parameters()`` and ``.zero_grad()``)\n# which we will be using.\n#\n# .. note:: ``nn.Module`` (uppercase M) is a PyTorch specific concept, and is a\n# class we'll be using a lot. ``nn.Module`` is not to be confused with the Python\n# concept of a (lowercase ``m``) `module <https://docs.python.org/3/tutorial/modules.html>`_,\n# which is a file of Python code that can be imported.\n\nfrom torch import nn\n\nclass Mnist_Logistic(nn.Module):\n def __init__(self):\n super().__init__()\n self.weights = nn.Parameter(torch.randn(784, 10) / math.sqrt(784))\n self.bias = nn.Parameter(torch.zeros(10))\n\n def forward(self, xb):\n return xb @ self.weights + self.bias\n\n###############################################################################\n# Since we're now using an object instead of just using a function, we\n# first have to instantiate our model:\n\nmodel = Mnist_Logistic()\n\n###############################################################################\n# Now we can calculate the loss in the same way as before. Note that\n# ``nn.Module`` objects are used as if they are functions (i.e they are\n# *callable*), but behind the scenes Pytorch will call our ``forward``\n# method automatically.\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Previously for our training loop we had to update the values for each parameter\n# by name, and manually zero out the grads for each parameter separately, like this:\n# ::\n# with torch.no_grad():\n# weights -= weights.grad * lr\n# bias -= bias.grad * lr\n# weights.grad.zero_()\n# bias.grad.zero_()\n#\n#\n# Now we can take advantage of model.parameters() and model.zero_grad() (which\n# are both defined by PyTorch for ``nn.Module``) to make those steps more concise\n# and less prone to the error of forgetting some of our parameters, particularly\n# if we had a more complicated model:\n# ::\n# with torch.no_grad():\n# for p in model.parameters(): p -= p.grad * lr\n# model.zero_grad()\n#\n#\n# We'll wrap our little training loop in a ``fit`` function so we can run it\n# again later.\n\ndef fit():\n for epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n start_i = i * bs\n end_i = start_i + bs\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n with torch.no_grad():\n for p in model.parameters():\n p -= p.grad * lr\n model.zero_grad()\n\nfit()\n\n###############################################################################\n# Let's double-check that our loss has gone down:\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Refactor using nn.Linear\n# -------------------------\n#\n# We continue to refactor our code. Instead of manually defining and\n# initializing ``self.weights`` and ``self.bias``, and calculating ``xb @\n# self.weights + self.bias``, we will instead use the Pytorch class\n# `nn.Linear <https://pytorch.org/docs/stable/nn.html#linear-layers>`_ for a\n# linear layer, which does all that for us. Pytorch has many types of\n# predefined layers that can greatly simplify our code, and often makes it\n# faster too.\n\nclass Mnist_Logistic(nn.Module):\n def __init__(self):\n super().__init__()\n self.lin = nn.Linear(784, 10)\n\n def forward(self, xb):\n return self.lin(xb)\n\n###############################################################################\n# We instantiate our model and calculate the loss in the same way as before:\n\nmodel = Mnist_Logistic()\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# We are still able to use our same ``fit`` method as before.\n\nfit()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Refactor using optim\n# ------------------------------\n#\n# Pytorch also has a package with various optimization algorithms, ``torch.optim``.\n# We can use the ``step`` method from our optimizer to take a forward step, instead\n# of manually updating each parameter.\n#\n# This will let us replace our previous manually coded optimization step:\n# ::\n# with torch.no_grad():\n# for p in model.parameters(): p -= p.grad * lr\n# model.zero_grad()\n#\n# and instead use just:\n# ::\n# opt.step()\n# opt.zero_grad()\n#\n# (``optim.zero_grad()`` resets the gradient to 0 and we need to call it before\n# computing the gradient for the next minibatch.)\n\nfrom torch import optim\n\n###############################################################################\n# We'll define a little function to create our model and optimizer so we\n# can reuse it in the future.\n\ndef get_model():\n model = Mnist_Logistic()\n return model, optim.SGD(model.parameters(), lr=lr)\n\nmodel, opt = get_model()\nprint(loss_func(model(xb), yb))\n\nfor epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n start_i = i * bs\n end_i = start_i + bs\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Refactor using Dataset\n# ------------------------------\n#\n# PyTorch has an abstract Dataset class. A Dataset can be anything that has\n# a ``__len__`` function (called by Python's standard ``len`` function) and\n# a ``__getitem__`` function as a way of indexing into it.\n# `This tutorial <https://pytorch.org/tutorials/beginner/data_loading_tutorial.html>`_\n# walks through a nice example of creating a custom ``FacialLandmarkDataset`` class\n# as a subclass of ``Dataset``.\n#\n# PyTorch's `TensorDataset <https://pytorch.org/docs/stable/_modules/torch/utils/data/dataset.html#TensorDataset>`_\n# is a Dataset wrapping tensors. By defining a length and way of indexing,\n# this also gives us a way to iterate, index, and slice along the first\n# dimension of a tensor. This will make it easier to access both the\n# independent and dependent variables in the same line as we train.\n\nfrom torch.utils.data import TensorDataset\n\n###############################################################################\n# Both ``x_train`` and ``y_train`` can be combined in a single ``TensorDataset``,\n# which will be easier to iterate over and slice.\n\ntrain_ds = TensorDataset(x_train, y_train)\n\n###############################################################################\n# Previously, we had to iterate through minibatches of x and y values separately:\n# ::\n# xb = x_train[start_i:end_i]\n# yb = y_train[start_i:end_i]\n#\n#\n# Now, we can do these two steps together:\n# ::\n# xb,yb = train_ds[i*bs : i*bs+bs]\n#\n\nmodel, opt = get_model()\n\nfor epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n xb, yb = train_ds[i * bs: i * bs + bs]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Refactor using DataLoader\n# ------------------------------\n#\n# Pytorch's ``DataLoader`` is responsible for managing batches. You can\n# create a ``DataLoader`` from any ``Dataset``. ``DataLoader`` makes it easier\n# to iterate over batches. Rather than having to use ``train_ds[i*bs : i*bs+bs]``,\n# the DataLoader gives us each minibatch automatically.\n\nfrom torch.utils.data import DataLoader\n\ntrain_ds = TensorDataset(x_train, y_train)\ntrain_dl = DataLoader(train_ds, batch_size=bs)\n\n###############################################################################\n# Previously, our loop iterated over batches (xb, yb) like this:\n# ::\n# for i in range((n-1)//bs + 1):\n# xb,yb = train_ds[i*bs : i*bs+bs]\n# pred = model(xb)\n#\n# Now, our loop is much cleaner, as (xb, yb) are loaded automatically from the data loader:\n# ::\n# for xb,yb in train_dl:\n# pred = model(xb)\n\nmodel, opt = get_model()\n\nfor epoch in range(epochs):\n for xb, yb in train_dl:\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\nprint(loss_func(model(xb), yb))\n\n###############################################################################\n# Thanks to Pytorch's ``nn.Module``, ``nn.Parameter``, ``Dataset``, and ``DataLoader``,\n# our training loop is now dramatically smaller and easier to understand. Let's\n# now try to add the basic features necessary to create effective models in practice.\n#\n# Add validation\n# -----------------------\n#\n# In section 1, we were just trying to get a reasonable training loop set up for\n# use on our training data. In reality, you **always** should also have\n# a `validation set <https://www.fast.ai/2017/11/13/validation-sets/>`_, in order\n# to identify if you are overfitting.\n#\n# Shuffling the training data is\n# `important <https://www.quora.com/Does-the-order-of-training-data-matter-when-training-neural-networks>`_\n# to prevent correlation between batches and overfitting. On the other hand, the\n# validation loss will be identical whether we shuffle the validation set or not.\n# Since shuffling takes extra time, it makes no sense to shuffle the validation data.\n#\n# We'll use a batch size for the validation set that is twice as large as\n# that for the training set. This is because the validation set does not\n# need backpropagation and thus takes less memory (it doesn't need to\n# store the gradients). We take advantage of this to use a larger batch\n# size and compute the loss more quickly.\n\ntrain_ds = TensorDataset(x_train, y_train)\ntrain_dl = DataLoader(train_ds, batch_size=bs, shuffle=True)\n\nvalid_ds = TensorDataset(x_valid, y_valid)\nvalid_dl = DataLoader(valid_ds, batch_size=bs * 2)\n\n###############################################################################\n# We will calculate and print the validation loss at the end of each epoch.\n#\n# (Note that we always call ``model.train()`` before training, and ``model.eval()``\n# before inference, because these are used by layers such as ``nn.BatchNorm2d``\n# and ``nn.Dropout`` to ensure appropriate behaviour for these different phases.)\n\nmodel, opt = get_model()\n\nfor epoch in range(epochs):\n model.train()\n for xb, yb in train_dl:\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n model.eval()\n with torch.no_grad():\n valid_loss = sum(loss_func(model(xb), yb) for xb, yb in valid_dl)\n\n print(epoch, valid_loss / len(valid_dl))\n\n###############################################################################\n# Create fit() and get_data()\n# ----------------------------------\n#\n# We'll now do a little refactoring of our own. Since we go through a similar\n# process twice of calculating the loss for both the training set and the\n# validation set, let's make that into its own function, ``loss_batch``, which\n# computes the loss for one batch.\n#\n# We pass an optimizer in for the training set, and use it to perform\n# backprop. For the validation set, we don't pass an optimizer, so the\n# method doesn't perform backprop.\n\n\ndef loss_batch(model, loss_func, xb, yb, opt=None):\n loss = loss_func(model(xb), yb)\n\n if opt is not None:\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n return loss.item(), len(xb)\n\n###############################################################################\n# ``fit`` runs the necessary operations to train our model and compute the\n# training and validation losses for each epoch.\n\nimport numpy as np\n\ndef fit(epochs, model, loss_func, opt, train_dl, valid_dl):\n for epoch in range(epochs):\n model.train()\n for xb, yb in train_dl:\n loss_batch(model, loss_func, xb, yb, opt)\n\n model.eval()\n with torch.no_grad():\n losses, nums = zip(\n *[loss_batch(model, loss_func, xb, yb) for xb, yb in valid_dl]\n )\n val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums)\n\n print(epoch, val_loss)\n\n###############################################################################\n# ``get_data`` returns dataloaders for the training and validation sets.\n\n\ndef get_data(train_ds, valid_ds, bs):\n return (\n DataLoader(train_ds, batch_size=bs, shuffle=True),\n DataLoader(valid_ds, batch_size=bs * 2),\n )\n\n###############################################################################\n# Now, our whole process of obtaining the data loaders and fitting the\n# model can be run in 3 lines of code:\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\nmodel, opt = get_model()\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# You can use these basic 3 lines of code to train a wide variety of models.\n# Let's see if we can use them to train a convolutional neural network (CNN)!\n#\n# Switch to CNN\n# -------------\n#\n# We are now going to build our neural network with three convolutional layers.\n# Because none of the functions in the previous section assume anything about\n# the model form, we'll be able to use them to train a CNN without any modification.\n#\n# We will use Pytorch's predefined\n# `Conv2d <https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d>`_ class\n# as our convolutional layer. We define a CNN with 3 convolutional layers.\n# Each convolution is followed by a ReLU. At the end, we perform an\n# average pooling. (Note that ``view`` is PyTorch's version of numpy's\n# ``reshape``)\n\nclass Mnist_CNN(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1)\n self.conv2 = nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1)\n self.conv3 = nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1)\n\n def forward(self, xb):\n xb = xb.view(-1, 1, 28, 28)\n xb = F.relu(self.conv1(xb))\n xb = F.relu(self.conv2(xb))\n xb = F.relu(self.conv3(xb))\n xb = F.avg_pool2d(xb, 4)\n return xb.view(-1, xb.size(1))\n\nlr = 0.1\n\n###############################################################################\n# `Momentum <https://cs231n.github.io/neural-networks-3/#sgd>`_ is a variation on\n# stochastic gradient descent that takes previous updates into account as well\n# and generally leads to faster training.\n\nmodel = Mnist_CNN()\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# nn.Sequential\n# ------------------------\n#\n# ``torch.nn`` has another handy class we can use to simplify our code:\n# `Sequential <https://pytorch.org/docs/stable/nn.html#torch.nn.Sequential>`_ .\n# A ``Sequential`` object runs each of the modules contained within it, in a\n# sequential manner. This is a simpler way of writing our neural network.\n#\n# To take advantage of this, we need to be able to easily define a\n# **custom layer** from a given function. For instance, PyTorch doesn't\n# have a `view` layer, and we need to create one for our network. ``Lambda``\n# will create a layer that we can then use when defining a network with\n# ``Sequential``.\n\nclass Lambda(nn.Module):\n def __init__(self, func):\n super().__init__()\n self.func = func\n\n def forward(self, x):\n return self.func(x)\n\n\ndef preprocess(x):\n return x.view(-1, 1, 28, 28)\n\n###############################################################################\n# The model created with ``Sequential`` is simply:\n\nmodel = nn.Sequential(\n Lambda(preprocess),\n nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.AvgPool2d(4),\n Lambda(lambda x: x.view(x.size(0), -1)),\n)\n\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# Wrapping DataLoader\n# -----------------------------\n#\n# Our CNN is fairly concise, but it only works with MNIST, because:\n# - It assumes the input is a 28\\*28 long vector\n# - It assumes that the final CNN grid size is 4\\*4 (since that's the average\n# pooling kernel size we used)\n#\n# Let's get rid of these two assumptions, so our model works with any 2d\n# single channel image. First, we can remove the initial Lambda layer by\n# moving the data preprocessing into a generator:\n\ndef preprocess(x, y):\n return x.view(-1, 1, 28, 28), y\n\n\nclass WrappedDataLoader:\n def __init__(self, dl, func):\n self.dl = dl\n self.func = func\n\n def __len__(self):\n return len(self.dl)\n\n def __iter__(self):\n batches = iter(self.dl)\n for b in batches:\n yield (self.func(*b))\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\ntrain_dl = WrappedDataLoader(train_dl, preprocess)\nvalid_dl = WrappedDataLoader(valid_dl, preprocess)\n\n###############################################################################\n# Next, we can replace ``nn.AvgPool2d`` with ``nn.AdaptiveAvgPool2d``, which\n# allows us to define the size of the *output* tensor we want, rather than\n# the *input* tensor we have. As a result, our model will work with any\n# size input.\n\nmodel = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.AdaptiveAvgPool2d(1),\n Lambda(lambda x: x.view(x.size(0), -1)),\n)\n\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\n###############################################################################\n# Let's try it out:\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# Using your GPU\n# ---------------\n#\n# If you're lucky enough to have access to a CUDA-capable GPU (you can\n# rent one for about $0.50/hour from most cloud providers) you can\n# use it to speed up your code. First check that your GPU is working in\n# Pytorch:\n\nprint(torch.cuda.is_available())\n\n###############################################################################\n# And then create a device object for it:\n\ndev = torch.device(\n \"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\n###############################################################################\n# Let's update ``preprocess`` to move batches to the GPU:\n\n\ndef preprocess(x, y):\n return x.view(-1, 1, 28, 28).to(dev), y.to(dev)\n\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\ntrain_dl = WrappedDataLoader(train_dl, preprocess)\nvalid_dl = WrappedDataLoader(valid_dl, preprocess)\n\n###############################################################################\n# Finally, we can move our model to the GPU.\n\nmodel.to(dev)\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\n###############################################################################\n# You should find it runs faster now:\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)\n\n###############################################################################\n# Closing thoughts\n# -----------------\n#\n# We now have a general data pipeline and training loop which you can use for\n# training many types of models using Pytorch. To see how simple training a model\n# can now be, take a look at the `mnist_sample` sample notebook.\n#\n# Of course, there are many things you'll want to add, such as data augmentation,\n# hyperparameter tuning, monitoring training, transfer learning, and so forth.\n# These features are available in the fastai library, which has been developed\n# using the same design approach shown in this tutorial, providing a natural\n# next step for practitioners looking to take their models further.\n#\n# We promised at the start of this tutorial we'd explain through example each of\n# ``torch.nn``, ``torch.optim``, ``Dataset``, and ``DataLoader``. So let's summarize\n# what we've seen:\n#\n# - **torch.nn**\n#\n# + ``Module``: creates a callable which behaves like a function, but can also\n# contain state(such as neural net layer weights). It knows what ``Parameter`` (s) it\n# contains and can zero all their gradients, loop through them for weight updates, etc.\n# + ``Parameter``: a wrapper for a tensor that tells a ``Module`` that it has weights\n# that need updating during backprop. Only tensors with the `requires_grad` attribute set are updated\n# + ``functional``: a module(usually imported into the ``F`` namespace by convention)\n# which contains activation functions, loss functions, etc, as well as non-stateful\n# versions of layers such as convolutional and linear layers.\n# - ``torch.optim``: Contains optimizers such as ``SGD``, which update the weights\n# of ``Parameter`` during the backward step\n# - ``Dataset``: An abstract interface of objects with a ``__len__`` and a ``__getitem__``,\n# including classes provided with Pytorch such as ``TensorDataset``\n# - ``DataLoader``: Takes any ``Dataset`` and creates an iterator which returns batches of data.\n"
] | [
[
"numpy.multiply",
"torch.zeros",
"torch.randn",
"torch.utils.data.TensorDataset",
"torch.nn.Conv2d",
"torch.utils.data.DataLoader",
"torch.nn.functional.avg_pool2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"torch.nn.ReLU",
"numpy.sum",
"torch.argmax"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
alihakimtaskiran/Rainbow-Utils | [
"e97403b203f94e7f507cd2141afcf91bca9b640f"
] | [
"rainbow.py"
] | [
"import numpy as np\n\nclass Ambient(object):\n def __init__(self, e_r=1, mu_r=1, name=''):\n if not isinstance(e_r, (int, float, complex)):\n raise TypeError('e_r(relative permittivity) of the ambient must be a int, flat or complex')\n\n if not isinstance(mu_r, (int, float, complex)):\n raise TypeError('mu_r(relative permeability) of the ambient must be a int, flat or complex')\n\n\n if not isinstance(name, str):\n raise TypeError('name must be a string')\n \n self.__e_r=e_r\n self.__mu_r=mu_r\n self.__name=name\n\n\n @property\n def info(self):\n return self.__e_r, self.__mu_r, self.__name\n\n def __repr__(self):\n return f'Ambient {self.__name} Relative Permittivity:{self.__e_r} Relative Permeability:{self.__mu_r}'\n \nclass Substrate(object):\n def __init__(self, e_r=1, mu_r=1, name=''):\n if not isinstance(e_r, (int, float, complex)):\n raise TypeError('e_r(relative permittivity) of the substrate must be a int, flat or complex')\n\n if not isinstance(mu_r, (int, float, complex)):\n raise TypeError('mu_r(relative permeability) of the substrate must be a int, flat or complex')\n\n\n if not isinstance(name, str):\n raise TypeError('name must be a string')\n \n self.__e_r=e_r\n self.__mu_r=mu_r\n self.__name=name\n\n\n @property\n def info(self):\n return self.__e_r, self.__mu_r, self.__name\n\n def __repr__(self):\n return f'Substrate {self.__name} Relative Permittivity:{self.__e_r} Relative Permeability:{self.__mu_r}'\n\nclass ThinLayer(object):\n def __init__(self, d, e_r=1, mu_r=1, name=''):\n if not isinstance(e_r, (int, float, complex)):\n raise TypeError('e_r(relative permittivity) of the ThinLayer must be a int, flat or complex')\n\n if not isinstance(mu_r, (int, float, complex)):\n raise TypeError('mu_r(relative permeability) of the ThinLayer must be a int, flat or complex')\n\n\n if not isinstance(name, str):\n raise TypeError('name must be a string')\n \n self.__d=d\n self.__e_r=e_r\n self.__mu_r=mu_r\n self.__name=name\n \n\n @property\n def info(self):\n return self.__d, self.__e_r, self.__mu_r, self.__name\n\n def __repr__(self):\n return f'ThinLayer {self.__name} Thickness:{self.__d*1e9} nm Relative Permittivity:{self.__e_r} Relative Permeability:{self.__mu_r}'\n\nclass Stack(object):\n def __init__(self):\n\n self.__layers=[]\n self.__ambient=None\n self.__substrate=None\n self.__eta=[]\n self.__n=[]\n self.__radiation=None\n self.__tm=None\n\n\n @property\n def stack(self):\n return self.__ambient, self.__layers, self.__substrate\n def add(self, arg):\n if isinstance(arg, (list, tuple)):\n for argv in arg:\n self.add(argv)\n elif isinstance(arg, Ambient):\n self.__ambient=arg\n elif isinstance(arg, Substrate):\n self.__substrate=arg\n elif isinstance(arg, ThinLayer):\n self.__layers.append(arg)\n else:\n raise TypeError('Only an Ambient, ThinLayer or Substrate can be added')\n\n def Radiation(self, wavelenght, theta=0, polarisation_mode='TM'):\n if polarisation_mode=='TE':\n pm=0\n elif polarisation_mode=='TM':\n pm=1\n else:\n raise ValueError('Polarization mode must be string of \"TE\" or \"TM\"')\n \n self.__radiation = np.math.pi*2/wavelenght, np.sin(theta), pm #wavenumber, theta, polarisaton_mode\n \n def render(self):\n self.__n_layers=len(self.__layers)\n _= self.__n_layers-1\n self.__eta=[np.sqrt(self.__ambient.info[1]/self.__ambient.info[0])]+[np.sqrt(self.__layers[i].info[2]/self.__layers[i].info[1]) for i in range(self.__n_layers)]+[np.sqrt(self.__substrate.info[1]/self.__substrate.info[0])]\n self.__n=[np.sqrt(self.__ambient.info[0]*self.__ambient.info[1])]+[np.sqrt(self.__layers[i].info[2]*self.__layers[i].info[1]) for i in range(self.__n_layers)]+[np.sqrt(self.__substrate.info[0]*self.__substrate.info[1])]\n for i in range(_,-1,-1):##From Ref[1]\n n_2=self.__n[i+1]\n l=self.__layers[i].info[0]\n r_12=self.__r(i, i+1)\n r_23=self.__r(i+1, i+2)\n\n pa=np.exp(1j*n_2*self.__radiation[0]*l)\n na=np.conj(pa)\n M_i=1/(1-r_23)/(1-r_12)*np.array([[pa+r_12*r_23*na, -r_12*pa-r_23*na], [-r_12*na- r_23*pa , na+r_12*r_23*pa]])\n if i!=_:\n self.__tm=np.dot(self.__tm, M_i)\n else:\n self.__tm=M_i\n\n\n def __r(self, i ,j):##From Ref[2]\n\n if self.__radiation[2]==0:\n return (self.__eta[j]/self.__cos_theta_(j)-self.__eta[i]/self.__cos_theta_(i))/(self.__eta[j]/self.__cos_theta_(j)+self.__eta[i]/self.__cos_theta_(i))\n \n elif self.__radiation[2]==1:\n return (self.__eta[j]*self.__cos_theta_(j)-self.__eta[i]*self.__cos_theta_(i))/(self.__eta[j]*self.__cos_theta_(j)+self.__eta[i]*self.__cos_theta_(i))\n \n\n def __cos_theta_(self, i):\n return np.sqrt(1 - (self.__n[0]/self.__n[i]*self.__radiation[1])**2 )\n\n @property\n def reflectance(self):\n return abs(self.__tm[1,0]/self.__tm[0,0])**2\n \n @property\n def transmittance(self):\n return abs(1/self.__tm[0,0])**2 \n\n @property\n def TransferMatrix(self):\n return self.__tm\n"
] | [
[
"numpy.dot",
"numpy.conj",
"numpy.sqrt",
"numpy.sin",
"numpy.exp",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Jey1394/ARC | [
"877ac3219fe802a7421d3a669c9f6bd077e1dcfa"
] | [
"src/utils/common_utility.py"
] | [
"'''\nCode for common utilies used by all 3 tasks.\n'''\nimport json\nimport matplotlib.pyplot as plt\n\n\ndef json_src_reader(json_file):\n '''\n Function to read and return the json file and split the data into train input, train output, test input, test output. \n \n Parameters: \n -----------\n data = reads the input json file\n \n Returns\n -------\n train_inputs,train_outputs,test_inputs,test_outputs = lists of test and train set.\n ''' \n data = json.load(json_file)\n \n train_inputs = [data['train'][i]['input'] for i in range(len(data['train']))]\n train_outputs = [data['train'][i]['output'] for i in range(len(data['train']))]\n test_inputs = [data['test'][i]['input'] for i in range(len(data['test']))]\n test_outputs = [data['test'][i]['output'] for i in range(len(data['test']))]\n return train_inputs,train_outputs,test_inputs,test_outputs\n\n\ndef visualize(input):\n '''\n Function to plot grids and emulate testing interface.\n \n Parameters: \n -----------\n input = A list of test input and computed output.\n '''\n for i in range(len(input)):\n plt.matshow(input[i])\n plt.show()\n"
] | [
[
"matplotlib.pyplot.matshow",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xinjiyuan97/statisticalMachineLearning | [
"d937c2a62b6f20ec463bc65bb5afa55b821e99ad"
] | [
"kNearestNeighbor(kdTree).py"
] | [
"import numpy as np\n\n\ndef createData():\n x = np.array([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]])\n return x;\n\ndef createTree(dataSet, k, j):\n if len(dataSet) == 0:\n return\n if len(dataSet) == 1:\n print(dataSet[0, :], j)\n return\n #return dataSet[0, :]\n num = dataSet.shape[0]\n rank = np.argsort(dataSet[:, j % k])\n #print(rank)\n mid = int(num / 2);\n #print(mid)\n left = np.array([dataSet[x, :] for x in rank[ : mid]])\n #print(left)\n right = np.array([dataSet[x, :] for x in rank[mid + 1:]])\n #print(right)\n #print(dataSet[mid])\n root = dataSet[rank[mid], :]\n print(root, j)\n #myTree = { root.tostring() : {}}\n #myTree[root.tostring()][0] = createTree(left, k, j + 1)\n #myTree[root.tostring()][1] = createTree(right, k, j + 1)\n createTree(left, k, j + 1)\n createTree(right, k, j + 1)\n return \n #return myTree\n\nif __name__ == \"__main__\":\n X = createData()\n k = X.shape[1]\n #print(X)\n createTree(X, k, 0)\n #print(myTree)\n "
] | [
[
"numpy.argsort",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
haowei01/pytorch | [
"b5e832111e5e4bb3dd66d716d398b81fe70c6af0"
] | [
"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\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)\nfrom .._core import _dispatch_dtypes\nfrom torch.testing._internal.common_device_type import \\\n (skipIf, skipCUDAIfNoMagma, skipCUDAIfNoMagmaAndNoCusolver, skipCUDAIfNoCusolver,\n skipCPUIfNoLapack, skipCPUIfNoMkl, skipCUDAIfRocm, precisionOverride,)\nfrom torch.testing._internal.common_cuda import CUDA11OrLater, SM53OrLater\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,\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, slowTest, TEST_WITH_ASAN,\n GRADCHECK_NONDET_TOL,)\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__(self, cls_name=None, test_name=None, *,\n device_type=None, dtypes=None, active_if=True):\n super().__init__(decorators=skipIf(True, \"Skipped!\"), cls_name=cls_name,\n test_name=test_name, device_type=device_type, dtypes=dtypes,\n active_if=active_if)\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=None, 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\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# 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 op=None, # the function variant of the operation, populated as torch.<name> if None\n dtypes=floating_types(), # dtypes this function is expected to work with\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. Gets intersected\n # with the dtypes support on the tested device\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 supports_out=True, # whether the op supports the out kwarg\n skips=tuple(), # information about which tests to skip\n decorators=None, # decorators to apply to generated tests\n safe_casts_outputs=False, # whether op allows safe casting when writing to out arguments\n sample_inputs_func=None, # function to generate sample inputs\n aten_name=None, # name of the corresponding aten:: operator\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 supports_autograd=True, # support for autograd\n supports_gradgrad=True, # support second order gradients (this value is ignored if supports_autograd=False)\n supports_inplace_autograd=None, # whether the operation supports inplace autograd\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 supports_sparse=False, # whether the op supports sparse inputs\n gradcheck_wrapper=lambda op, *args, **kwargs: op(*args, **kwargs), # wrapper function for gradcheck\n check_batched_grad=True, # check batched grad when doing gradcheck\n check_batched_gradgrad=True, # 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 inplace_variant=_NOTHING, # explicitly pass the inplace variant of the operator if required\n method_variant=_NOTHING, # explicitly pass the method variant of the operator if required\n test_conjugated_samples=True,\n ):\n\n # Validates the dtypes are generated from the dispatch-related functions\n for dtype_list in (dtypes, dtypesIfCPU, dtypesIfCUDA, dtypesIfROCM):\n assert isinstance(dtype_list, (_dispatch_dtypes, type(None)))\n\n self.name = name\n self.aten_name = aten_name if aten_name is not None else name\n self.variant_test_name = variant_test_name\n\n self.dtypes = set(dtypes)\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.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 self.dtypesIfCPU if dtypesIfCPU is not None else self.backward_dtypes)\n self.backward_dtypesIfCUDA = set(backward_dtypesIfCUDA) if backward_dtypesIfCUDA is not None else (\n self.dtypesIfCUDA if dtypesIfCUDA is not None else self.backward_dtypes)\n self.backward_dtypesIfROCM = set(backward_dtypesIfROCM) if backward_dtypesIfROCM is not None else (\n self.dtypesIfROCM if dtypesIfROCM is not None else self.backward_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.skips = skips\n self.decorators = decorators\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.test_conjugated_samples = test_conjugated_samples\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 # Returns True if the test should be skipped and False otherwise\n def should_skip(self, cls_name, test_name, device_type, dtype):\n return any(si.is_active(cls_name, test_name, device_type, dtype)\n for si in self.skips)\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 device_type == 'cpu':\n return self.backward_dtypesIfCPU\n if device_type == 'cuda':\n return self.backward_dtypesIfROCM if TEST_WITH_ROCM else self.backward_dtypesIfCUDA\n else:\n return self.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 # dim2_null, rank1 and rank2 are disabled because of\n # https://github.com/pytorch/pytorch/issues/53364\n # we should re-enable them once the issue is solved\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_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_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 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 sample_inputs = []\n for input_args in cases:\n args = (make_tensor(input_args[0], device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n make_tensor(input_args[1], device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n make_tensor(input_args[2], device, dtype,\n low=None, high=None,\n requires_grad=requires_grad))\n alpha, beta = input_args[3], input_args[4]\n broadcasts_input = input_args[5]\n sample_inputs.append(SampleInput(args[0], args=(args[1], args[2]), kwargs=dict(beta=beta, alpha=alpha),\n broadcasts_input=broadcasts_input))\n return tuple(sample_inputs)\n\ndef sample_inputs_addbmm(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = [((S, M), (S, S, S), (S, S, M), 1, 1),\n ((1,), (S, S, S), (S, S, M), 1, 1),\n ((S, M), (S, S, S), (S, S, M), 0.6, 0.2),\n ((1,), (S, S, S), (S, S, M), 0.6, 0.2),\n ((), (S, S, S), (S, S, M), 1, 1),\n ((), (S, S, S), (S, S, M), 0.6, 0.2),\n ]\n sample_inputs = []\n for input_args in test_cases:\n args = (make_tensor(input_args[0], device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n make_tensor(input_args[1], device, dtype,\n low=None, high=None,\n requires_grad=requires_grad),\n make_tensor(input_args[2], device, dtype,\n low=None, high=None,\n requires_grad=requires_grad))\n alpha, beta = input_args[3], input_args[4]\n sample_inputs.append(SampleInput(args[0], args=(args[1], args[2]), kwargs=dict(beta=beta, alpha=alpha)))\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\n return tuple(sample_inputs)\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\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_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\ndef sample_inputs_amax_amin(op_info, device, dtype, requires_grad, **kwargs):\n test_cases = (\n ((S, S, S), ()),\n ((S, S, S), (1,)),\n ((S, S, S), ((1, 2,),)),\n ((S, S, S), (1, True,)),\n ((), (0,)),\n ((), ()),\n ((), (0, True,)),\n )\n return tuple(SampleInput((make_tensor(size, device, dtype,\n low=None, high=None,\n requires_grad=requires_grad)),\n args=args)\n for size, args in test_cases)\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_gradient(op_info, device, dtype, requires_grad):\n sample_inputs = []\n test_cases_float = (\n ((S,), None, None),\n ((S,), 2., None),\n ((S, S), None, None),\n ((S, S), [2.0, 2.1], None),\n ((S, S), [2.0, 2.1], (0, 1)),\n ((4, 4, 4), [2., 1.], (0, 1)),\n )\n for size, spacing, dim 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)))\n\n test_cases_tensor = (\n ((3, 3, 3), ((1.1, 2.0, 3.5), (4.0, 2, 6.0)), (0, -1)),\n ((3, 3, 3), ((1.0, 3.0, 2.0), (8.0, 6.0, 1.0)), (0, 1)),\n )\n for size, coordinates, dim 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)))\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 # no CUDA support for stable sort yet\n if not device.startswith('cuda'):\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_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_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\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_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 skipCPUIfNoMkl,\n skipCUDAIfRocm,\n # gradgrad is quite slow\n DecorateInfo(slowTest, 'TestGradients', 'test_fn_gradgrad'),\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):\n tensors = [make_tensor((N - i, N - i), device, dtype, noncontiguous=noncontiguous) for i in range(N)]\n return tensors\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 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\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_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 _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 = ( # type: ignore[assignment]\n ((S, S, S), 1.5, False),\n ((), 1.5, False),\n )\n else:\n cases = ( # type: ignore[assignment]\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 = ( # type: ignore[assignment]\n ((), torch.tensor(1, dtype=dtype, device=device, requires_grad=False), False),\n )\n\n # Sample inputs with broadcasting\n cases_with_broadcasting = ( # type: ignore[assignment]\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\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\ndef sample_inputs_log_softmax(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 if with_dtype:\n cases = (((S, S, S), (1, torch.float64)),)\n else:\n cases = (((S, S, S), (1,)),) # type:ignore[assignment]\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_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\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 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 not skip_redundant:\n # Redundant tests\n skips = skips + ( # type: ignore[assignment]\n SkipInfo('TestGradients'),\n SkipInfo('TestOpInfo'),\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 variant_test_name=variant_test_name,\n domain=domain,\n decorators=(precisionOverride({torch.float16: 5e-2}),),\n dtypes=floating_types(),\n dtypesIfCUDA=floating_types_and(torch.half),\n sample_inputs_func=sample_inputs_mvlgamma,\n supports_out=False,\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# 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 = ( # type: ignore[assignment]\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 yield(SampleInput(make_arg(shape), 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 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_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\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\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_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\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 )),\n # NOTE: the derivative for inplace acosh is not implemented\n UnaryUfuncInfo('acosh',\n aliases=('arccosh', ),\n ref=np.arccosh,\n domain=(1, float('inf')),\n dtypes=all_types_and_complex_and(torch.bool),\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 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 aliases=('subtract',),\n dtypes=all_types_and_complex_and(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 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 skips=(\n # issue may fix: https://github.com/pytorch/pytorch/issues/55589\n # AssertionError: UserWarning not triggered : Resized a non-empty tensor but did not warn about it.\n SkipInfo('TestCommon', 'test_out', dtypes=(torch.float32,)),\n # Reference: https://github.com/pytorch/pytorch/issues/55589\n SkipInfo('TestCommon', 'test_variant_consistency_eager'),\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16, torch.complex64, torch.complex128), active_if=TEST_WITH_ROCM),\n ),\n sample_inputs_func=sample_inputs_addmv),\n OpInfo('addbmm',\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 dtypesIfROCM=floating_types_and(torch.half),\n supports_forward_ad=True,\n skips=(\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 SkipInfo('TestOpInfo', 'test_supported_backward', dtypes=(torch.bfloat16, ),\n device_type='cuda', active_if=not SM53OrLater),\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16, torch.complex64, torch.complex128), active_if=TEST_WITH_ROCM),\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 supports_forward_ad=True,\n skips=(\n # baddbmm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n SkipInfo('TestOpInfo', 'test_supported_backward', dtypes=(torch.bfloat16, ),\n device_type='cuda', active_if=not SM53OrLater),\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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 skips=(\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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 skips=(\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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 assert_autodiffed=True,\n supports_forward_ad=True,\n skips=(\n # bmm does not correctly warn when resizing out= inputs\n SkipInfo('TestCommon', 'test_out'),\n SkipInfo('TestOpInfo', 'test_supported_backward', dtypes=(torch.bfloat16, ),\n device_type='cuda', active_if=not SM53OrLater),\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\n ),\n sample_inputs_func=sample_inputs_bmm),\n OpInfo('mv',\n dtypes=all_types_and_complex_and(torch.float16, 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 SkipInfo('TestOpInfo', 'test_supported_backward', dtypes=(torch.float16,)),\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\n # mv calls into addmv which doesn't fully support float16\n # RuntimeError: \"addmv_impl_cpu\" not implemented for 'Half'\n SkipInfo('TestOpInfo', 'test_supported_dtypes', dtypes=(torch.float16,)),),\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 SkipInfo('TestOpInfo', 'test_unsupported_backward',\n device_type='cuda', dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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 dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool),\n sample_inputs_func=sample_inputs_amax_amin,),\n OpInfo('amin',\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 decorators=(precisionOverride({torch.bfloat16: 1e-2}),),\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 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 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 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_extremal',\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],\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 UnaryUfuncInfo('bitwise_not',\n ref=np.bitwise_not,\n dtypes=integral_types_and(torch.bool),\n supports_autograd=False),\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 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 # 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('TestCommon', '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('TestCommon', '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('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 skips=(\n # \"sum_cpu/sum_cuda\" not implemented for 'ComplexHalf'\n SkipInfo('TestOpInfo', 'test_supported_backward', dtypes=(torch.half,)),\n ),\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 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('cross',\n dtypes=all_types_and_complex(),\n dtypesIfCUDA=all_types_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 # CUDA illegal memory access on Windows\n SkipInfo(device_type='cuda', active_if=IS_WINDOWS))),\n OpInfo('cumsum',\n dtypesIfCPU=all_types_and_complex_and(torch.bool),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16),\n supports_forward_ad=True,\n skips=(\n # \"cumsum_out_{cpu,cuda}\" not implemented for 'Bool'\n SkipInfo('TestOpInfo', 'test_supported_dtypes',\n dtypes=(torch.bool,)),\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_and(torch.bool),\n dtypesIfCUDA=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_forward_ad=True,\n skips=(\n # \"cumprod_out_{cpu, cuda}\" not implemented for 'Bool'\n SkipInfo('TestOpInfo', 'test_supported_dtypes',\n dtypes=(torch.bool,)),\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 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('TestCommon', '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('TestCommon', '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 # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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('TestCommon', '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('TestCommon', '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 dtypes=all_types_and(torch.float16),\n sample_inputs_func=sample_inputs_fmod_remainder),\n OpInfo('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 dtypesIfCPU=all_types_and(torch.float16),\n dtypesIfCUDA=all_types_and(torch.float16, torch.bfloat16),\n sample_inputs_func=sample_inputs_fmod_remainder),\n OpInfo('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 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_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_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_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 skips=(\n # `test_duplicate_method_tests` doesn't raise any warning, as it doesn't actually\n # call the operator.\n SkipInfo('TestOpInfo', 'test_duplicate_method_tests'),),\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 # TODO(@anjali411): Test this once neg bit is added.\n test_conjugated_samples=False,\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 skips=(\n # following tests give a runtime error with undefined value tensor\n # see discussion : https://github.com/pytorch/pytorch/issues/56660\n SkipInfo('TestCommon', '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('kthvalue',\n dtypes=all_types(),\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 # det doesn't support complex autograd, https://github.com/pytorch/pytorch/issues/57358\n backward_dtypes=floating_types(),\n aten_name='linalg_det',\n sample_inputs_func=sample_inputs_linalg_det,\n decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],\n supports_inplace_autograd=False,\n skips=(\n # The following tests fail only on ROCm. This is probably\n # related to the fact that the current linalg.det backward is\n # unstable if the matrix has repeated singular values, see\n # https://github.com/pytorch/pytorch/issues/53364\n SkipInfo('TestGradients', 'test_fn_grad', device_type='cuda',\n dtypes=(torch.float64,), active_if=TEST_WITH_ROCM),\n SkipInfo('TestGradients', 'test_fn_gradgrad', device_type='cuda',\n dtypes=(torch.float64,), active_if=TEST_WITH_ROCM),\n SkipInfo('TestCommon', 'test_variant_consistency_jit', device_type='cuda',\n dtypes=(torch.float64, torch.float32), active_if=TEST_WITH_ROCM),\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 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('TestCommon', '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 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 sample_inputs_func=sample_inputs_linalg_multi_dot,\n gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,\n skips=(\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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, float('inf')),\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, float('inf')),\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 domain=(-1, float('inf')),\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, float('inf')),\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('TestCommon', '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_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 skips=(\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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 assert_autodiffed=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 # https://github.com/pytorch/pytorch/issues/55755\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes',\n device_type='cpu', dtypes=(torch.float16,)),\n # Backward for BFloat16 isn't supported because of the error\n # \"RuntimeError: CUDA error: CUBLAS_STATUS_NOT_SUPPORTED when\n # calling cublasGemmStridedBatchedExFix.\"\n SkipInfo('TestOpInfo', 'test_supported_backward',\n device_type='cuda', dtypes=(torch.bfloat16,)),\n SkipInfo('TestCommon', 'test_conj_view', device_type='cpu'),\n # \"addmv_impl_cpu\" not implemented for 'Half'\n SkipInfo('TestOpInfo', 'test_unsupported_backward',\n device_type='cpu', dtypes=(torch.float16,)),\n # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.complex64, torch.complex128), active_if=TEST_WITH_ROCM),\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 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 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 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_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: review with var_mean tests in test_autograd.py\n SkipInfo('TestCommon', '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 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_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: fix along with var_mean autograd tests\n SkipInfo('TestCommon', '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 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 dtypesIfCPU=all_types_and(torch.float16, 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 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.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 autodiff_nonfusible_nodes=[\"aten::leaky_relu\"]),\n OpInfo('topk',\n dtypes=all_types(),\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 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 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 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 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 # some test samples works for ROCM backward but not all\n SkipInfo('TestOpInfo', 'test_unsupported_backward', device_type='cuda',\n dtypes=(torch.bfloat16,), active_if=TEST_WITH_ROCM),\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=(1e-4, float('inf')),\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=(1.1, float('inf')),\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=(2.1, float('inf')),\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 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 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 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 skips=(\n SkipInfo('TestCommon', '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 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 dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half),\n supports_out=False,\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 sample_inputs_func=sample_inputs_rot90),\n UnaryUfuncInfo('round',\n ref=np.round,\n dtypes=floating_types_and(torch.bfloat16),\n dtypesIfCUDA=floating_types_and(torch.half, torch.bfloat16),\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 decorators=(precisionOverride({torch.bfloat16: 1e-2}),)),\n UnaryUfuncInfo('sinc',\n ref=np_sinc_with_fp16_as_fp32,\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 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 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 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 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('TestCommon', '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('TestCommon', 'test_variant_consistency_jit',),),\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('TestCommon', 'test_variant_consistency_jit',),),\n assert_autodiffed=True,\n supports_forward_ad=True,\n autodiff_nonfusible_nodes=['aten::mul'],),\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.complex64, torch.complex128),\n assert_autodiffed=True,\n sample_inputs_func=sample_inputs_matmul,\n supports_out=False,\n skips=(\n SkipInfo('TestCommon', 'test_variant_consistency_jit',),\n # https://github.com/pytorch/pytorch/issues/55755\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes',\n device_type='cpu', dtypes=(torch.float16,)),\n # https://github.com/pytorch/pytorch/pull/57934#issuecomment-840091579\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes',\n device_type='cuda', dtypes=(torch.bfloat16,)),\n # addmv_impl_cpu\" not implemented for 'Half'\n SkipInfo('TestOpInfo', 'test_unsupported_backward',\n dtypes=(torch.float16, torch.bfloat16)),\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('TestCommon', '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 sample_inputs_func=sample_inputs_rbinops,\n supports_out=False,\n skips=(\n # Reference: https://github.com/pytorch/pytorch/issues/54774\n # \"log2\" \"_vml_cpu\" not implemented for Half\n SkipInfo('TestOpInfo', 'test_supported_backward', device_type='cpu',\n dtypes=(torch.float16,)),\n\n SkipInfo('TestCommon', '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('TestCommon', '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('TestCommon', '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('TestCommon', '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 supports_forward_ad=True,\n sample_inputs_func=sample_inputs_select,\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 dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCPU=floating_and_complex_types_and(torch.half),\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 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 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 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 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 # 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 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, float('inf')),\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 handles_complex_extremals=False),\n UnaryUfuncInfo('sqrt',\n ref=np.sqrt,\n supports_sparse=True,\n domain=(0, float('inf')),\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=(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 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 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 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 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),\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('TestCommon', 'test_variant_consistency_jit'),\n # The following dtypes are only supported for some inputs, ideally we should have\n # checked this in the einsum code but to keep BC we'll just skip the tests for now.\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes',\n dtypes=[torch.bool]),\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes',\n device_type='cuda', dtypes=integral_types_and(torch.bfloat16)),\n SkipInfo('TestOpInfo', 'test_unsupported_backward',\n device_type='cuda', dtypes=(torch.bfloat16,)),\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 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('TestCommon', '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 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('TestOpInfo'),\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 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('TestOpInfo'),\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 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('TestOpInfo'),\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 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('TestOpInfo'),\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 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 ),\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 skips=(\n # Because reshape_as does not have a function variant.\n SkipInfo('TestCommon', 'test_variant_consistency_jit'),),\n supports_out=False,\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 skips=(\n # Because view does not have a function variant.\n SkipInfo('TestCommon', '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 skips=(\n # Because view_as does not have a function variant.\n SkipInfo('TestCommon', '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 skips=(SkipInfo('TestOpInfo', 'test_duplicate_method_tests'),),\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('TestCommon', '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 sample_inputs_func=sample_inputs_index_put,\n skips=(\n SkipInfo('TestCommon', '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 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('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('TestCommon', '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 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 check_batched_gradgrad=False,\n skips=(\n # torch.unfold does not exist so we get a RuntimeError.\n SkipInfo('TestCommon', '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.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 # msort does not raise expected Runtime Error.\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes', dtypes=[torch.bool]),\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 sample_inputs_func=sample_movedim_moveaxis,\n skips=(\n # Expected a value of type 'int' for argument 'source'\n # but instead found type 'list'.\n SkipInfo('TestCommon', 'test_jit_alias_remapping'),\n )),\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 skips=(\n # torch.repeat does not exist so we get a RuntimeError.\n SkipInfo('TestCommon', '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 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('TestCommon', '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 skips=(\n # JIT has issue when op is passed as lambda\n SkipInfo('TestCommon', 'test_variant_consistency_jit'),\n ),\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 skips=(\n # JIT has issue when op is passed as lambda\n SkipInfo('TestCommon', 'test_variant_consistency_jit'),\n ),\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 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 sample_inputs_func=sample_repeat_tile),\n OpInfo('unsqueeze',\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n supports_out=False,\n assert_autodiffed=True,\n sample_inputs_func=sample_unsqueeze),\n OpInfo('var',\n dtypes=floating_and_complex_types_and(torch.half),\n dtypesIfCUDA=floating_and_complex_types_and(torch.half, torch.bfloat16),\n backward_dtypesIfCPU=floating_and_complex_types_and(torch.half),\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 dtypes=all_types_and(torch.bool),\n dtypesIfCPU=all_types_and(torch.bool, torch.half, torch.bfloat16),\n dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n supports_inplace_autograd=True,\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 skips=(\n # JIT has issue when op is passed as lambda\n SkipInfo('TestCommon', '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 safe_casts_outputs=True,\n supports_forward_ad=True,\n skips=(\n SkipInfo('TestOpInfo', 'test_supported_backward',\n device_type='cpu', dtypes=[torch.float16]),\n ),\n sample_inputs_func=sample_inputs_xlog1py),\n OpInfo('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 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 sample_inputs_func=sample_inputs_transpose_swapdims),\n OpInfo('tril',\n dtypes=all_types_and_complex_and(torch.bool, torch.half),\n sample_inputs_func=sample_inputs_tril_triu),\n OpInfo('triu',\n dtypes=all_types_and_complex_and(torch.bool, torch.half),\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 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 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 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(\"TestCommon\", \"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 # JIT has issue when op is passed as lambda\n SkipInfo('TestCommon', '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 # 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 # sigmoid doesn't support complex autograd, https://github.com/pytorch/pytorch/issues/48552\n backward_dtypesIfCPU=all_types_and(torch.bool, torch.bfloat16),\n backward_dtypesIfCUDA=all_types_and(torch.bool, torch.half, torch.bfloat16),\n safe_casts_outputs=True,\n assert_autodiffed=True),\n UnaryUfuncInfo('digamma',\n ref=scipy.special.digamma if TEST_SCIPY else _NOTHING,\n decorators=(precisionOverride({torch.float16: 5e-1}),),\n dtypes=all_types_and(torch.bool),\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 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('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 # \"digamma\" not implemented for 'BFloat16'\n backward_dtypesIfCPU=all_types_and(torch.bool),\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 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_log_softmax,\n assert_autodiffed=True),\n OpInfo(\n 'log_softmax',\n variant_test_name='dtype',\n supports_out=False,\n dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n sample_inputs_func=partial(sample_inputs_log_softmax, 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 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('TestCommon', '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('TestCommon', '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('TestCommon', '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('TestCommon', '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('TestCommon', 'test_variant_consistency_jit', dtypes=(torch.float32,)),\n # t = torch.randn((2, 2), dtype=torch.float16)\n # torch.norm(t) # Works\n # torch.norm(t, 'fro', [0, 1]) # Errors\n SkipInfo('TestOpInfo', 'test_unsupported_dtypes'),\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('TestCommon', '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 dtypes=all_types_and_complex_and(torch.bool, torch.float16, torch.bfloat16),\n assert_autodiffed=True,),\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",
"torch.testing._internal.common_utils.random_symmetric_matrix",
"numpy.sqrt",
"torch.zeros",
"torch.randperm",
"torch.testing.all_types_and",
"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",
"torch.no_grad",
"torch.empty_strided",
"torch.testing.floating_types",
"torch.device",
"torch.where",
"torch.testing._internal.common_utils.is_iterable_of_tensors",
"numpy.exp",
"torch.finfo",
"torch.ones",
"numpy.sinc",
"torch.testing._internal.common_device_type.skipIf",
"torch.randn",
"torch.einsum",
"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.get_default_dtype",
"torch.testing.integral_types_and",
"torch.LongTensor",
"torch.linalg.cholesky",
"torch.empty",
"numpy.random.choice",
"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",
"torch.testing.floating_and_complex_types",
"torch.testing.floating_types_and",
"torch.linalg.svd",
"numpy.abs",
"torch.testing._internal.common_utils.random_hermitian_pd_matrix",
"numpy.sign",
"torch.polygamma",
"torch.testing._internal.common_device_type.precisionOverride"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dgketchum/itype | [
"f679d95b489765cb8deadd276872ea3e238bc6ca"
] | [
"predict.py"
] | [
"import os\nimport numpy as np\nfrom argparse import ArgumentParser\nfrom pathlib import Path\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom pytorch_lightning import Trainer\n\nfrom models.unet.unet import UNet\nfrom configure import get_config\n\n\ndef main(params):\n config = get_config(**vars(params))\n\n checkpoint_dir = os.path.join(params.checkpoint, 'checkpoints')\n figures_dir = os.path.join(params.checkpoint, 'figures')\n checkpoint = [os.path.join(checkpoint_dir, x) for x in os.listdir(checkpoint_dir)][0]\n\n model = UNet.load_from_checkpoint(checkpoint_path=checkpoint)\n model.freeze()\n model.hparams.dataset_folder = '/media/nvm/itype_/pth_snt/2019'\n model.hparams.batch_size = 1\n\n if params.metrics:\n trainer = Trainer(\n precision=16,\n gpus=config.device_ct,\n num_nodes=config.node_ct,\n log_every_n_steps=5)\n\n trainer.test(model)\n\n loader = model.val_dataloader()\n for i, (x, y) in enumerate(loader):\n out = model(x)\n pred = out.argmax(1)\n x, y, pred = x.squeeze().numpy(), y.squeeze().numpy(), pred.squeeze().numpy()\n fig = os.path.join(figures_dir, '{}.png'.format(i))\n plot_prediction(x, y, pred, model.mode, out_file=fig)\n\n\ndef plot_prediction(x, label, pred, mode, out_file=None):\n cmap_label = colors.ListedColormap(['white', 'green', 'yellow', 'blue', 'pink', 'grey'])\n bounds_l = [0, 1, 2, 3, 4, 5, 6]\n bound_norm_l = colors.BoundaryNorm(bounds_l, len(bounds_l))\n\n classes = ['flood', 'sprinkler', 'pivot', 'rainfed', 'uncultivated']\n cmap_pred = colors.ListedColormap(['green', 'yellow', 'blue', 'pink', 'grey'])\n bounds_p = [1, 2, 3, 4, 5]\n bound_norm_p = colors.BoundaryNorm(bounds_p, len(bounds_p), extend='max')\n\n fig, ax = plt.subplots(ncols=5, nrows=1, figsize=(20, 10))\n\n r, g, b = x[0, :, :].astype('uint8'), x[1, :, :].astype('uint8'), x[2, :, :].astype('uint8')\n rgb = np.dstack([r, g, b])\n im = ax[0].imshow(rgb)\n ax[0].set(xlabel='image')\n divider = make_axes_locatable(ax[0])\n cax = divider.append_axes('bottom', size='10%', pad=0.6)\n cb = fig.colorbar(im, cax=cax, orientation='horizontal')\n\n mx_ndvi = x[4, :, :] / 1000.\n im = ax[1].imshow(mx_ndvi, cmap='RdYlGn')\n ax[1].set(xlabel='ndvi early')\n divider = make_axes_locatable(ax[1])\n cax = divider.append_axes('bottom', size='10%', pad=0.6)\n cb = fig.colorbar(im, cax=cax, orientation='horizontal')\n\n std_ndvi = x[7, :, :] / 1000.\n im = ax[2].imshow(std_ndvi, cmap='RdYlGn')\n ax[2].set(xlabel='ndvi late')\n divider = make_axes_locatable(ax[2])\n cax = divider.append_axes('bottom', size='10%', pad=0.6)\n cb = fig.colorbar(im, cax=cax, orientation='horizontal')\n\n im = ax[3].imshow(label, cmap=cmap_label, norm=bound_norm_l)\n ax[3].set(xlabel='label {}'.format(np.unique(label)))\n divider = make_axes_locatable(ax[3])\n cax = divider.append_axes('bottom', size='10%', pad=0.6)\n cb = fig.colorbar(im, cax=cax, orientation='horizontal')\n cb.set_ticks([])\n\n im = ax[4].imshow(pred, cmap=cmap_pred, norm=bound_norm_p)\n ax[4].set(xlabel='pred {}'.format(np.unique(pred)))\n divider = make_axes_locatable(ax[4])\n cax = divider.append_axes('bottom', size='10%', pad=0.6)\n cb = fig.colorbar(im, cax=cax, orientation='horizontal')\n cb.ax.set_xticklabels(classes)\n\n plt.tight_layout()\n if out_file:\n plt.savefig(out_file)\n plt.close()\n else:\n plt.show()\n\n\nif __name__ == '__main__':\n project = '/home/dgketchum/PycharmProjects/itype'\n checkpoint_pth = os.path.join(project, 'models/unet/results/aws-2021.04.22.00.39-unet-rgbn_snt')\n parser = ArgumentParser(add_help=False)\n parser.add_argument('--model', default='unet')\n parser.add_argument('--mode', default='rgbn')\n parser.add_argument('--gpu', default='RTX')\n parser.add_argument('--machine', default='pc')\n parser.add_argument('--nodes', default=1, type=int)\n parser.add_argument('--progress', default=0, type=int)\n parser.add_argument('--workers', default=12, type=int)\n parser.add_argument('--checkpoint', default=checkpoint_pth)\n parser.add_argument('--metrics', default=False, type=bool)\n args = parser.parse_args()\n main(args)\n# ========================= EOF ====================================================================\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"numpy.unique",
"matplotlib.pyplot.subplots",
"numpy.dstack",
"matplotlib.pyplot.savefig",
"matplotlib.colors.ListedColormap",
"matplotlib.pyplot.close",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DanyloAntsybor/DAT210x-master | [
"47901140d592352e172f0b22fbf275ebbb640219"
] | [
"Module5/assignment8.py"
] | [
"import pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmatplotlib.style.use('ggplot') # Look Pretty\n\n\ndef drawLine(model, X_test, y_test, title):\n # This convenience method will take care of plotting your\n # test observations, comparing them to the regression line,\n # and displaying the R2 coefficient\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(X_test, y_test, c='g', marker='o')\n ax.plot(X_test, model.predict(X_test), color='orange', linewidth=1, alpha=0.7)\n\n print (\"Est 2014 \" + title + \" Life Expectancy: \", model.predict([[2014]])[0])\n print (\"Est 2030 \" + title + \" Life Expectancy: \", model.predict([[2030]])[0])\n print (\"Est 2045 \" + title + \" Life Expectancy: \", model.predict([[2045]])[0])\n\n score = model.score(X_test, y_test)\n title += \" R2: \" + str(score)\n ax.set_title(title)\n\n\n plt.show()\n\n\n#\n# TODO: Load up the data here into a variable called 'X'.\n# As usual, do a .describe and a print of your dataset and\n# compare it to the dataset loaded in a text file or in a\n# spread sheet application\n#\nfilepath = 'D:\\\\work\\\\Courses\\\\DAT210x-master\\\\Module5\\\\Datasets\\\\life_expectancy.csv'\nX = pd.read_csv(filepath, sep='\\t')\n\n\n#\n# TODO: Create your linear regression model here and store it in a\n# variable called 'model'. Don't actually train or do anything else\n# with it yet:\n#\nfrom sklearn import linear_model\nmodel = linear_model.LinearRegression()\n\n#\n# TODO: Slice out your data manually (e.g. don't use train_test_split,\n# but actually do the Indexing yourself. Set X_train to be year values\n# LESS than 1986, and y_train to be corresponding WhiteMale age values.\n#\n# INFO You might also want to read the note about slicing on the bottom\n# of this document before proceeding.\n#\nX_train = X[X['Year'] < 1986]\ny_train = X_train['WhiteMale']\nX_train = X_train[['Year']]\n\n#\n# TODO: Train your model then pass it into drawLine with your training\n# set and labels. You can title it \"WhiteMale\". drawLine will output\n# to the console a 2014 extrapolation / approximation for what it\n# believes the WhiteMale's life expectancy in the U.S. will be...\n# given the pre-1986 data you trained it with. It'll also produce a\n# 2030 and 2045 extrapolation.\n#\n\nmodel.fit(X_train, y_train)\ntitle = \"WhiteMale\"\ndrawLine(model, X_train, y_train, title)\n\n#\n# TODO: Print the actual 2014 WhiteMale life expectancy from your\n# loaded dataset\n#\nprint(\"Actual 2014 WhiteMale life expectancy:\")\nprint(X.loc[X['Year'] == 2014,'WhiteFemale'].values[0])\n\n\n# \n# TODO: Repeat the process, but instead of for WhiteMale, this time\n# select BlackFemale. Create a slice for BlackFemales, fit your\n# model, and then call drawLine. Lastly, print out the actual 2014\n# BlackFemale life expectancy\n#\nX_train = X[X['Year'] < 1986]\ny_train = X_train['BlackFemale']\nX_train = X_train[['Year']]\nmodel.fit(X_train, y_train)\ntitle = \"BlackFemale\"\ndrawLine(model, X_train, y_train, title)\nprint(\"Actual 2014 BlackFemale life expectancy:\")\nprint(X.loc[X['Year'] == 2014,'BlackFemale'].values[0])\n\n#\n# TODO: Lastly, print out a correlation matrix for your entire\n# dataset, and display a visualization of the correlation\n# matrix, just as we described in the visualization section of\n# the course\n#\nplt.imshow(X.corr(), cmap=plt.cm.Blues, interpolation='nearest')\nplt.colorbar()\ntick_marks = [i for i in range(len(X.columns))]\nplt.xticks(tick_marks, X.columns, rotation='vertical')\nplt.yticks(tick_marks, X.columns)\n\nplt.show()\n\n\n\n\n#\n# INFO + HINT On Fitting, Scoring, and Predicting:\n#\n# Here's a hint to help you complete the assignment without pulling\n# your hair out! When you use .fit(), .score(), and .predict() on\n# your model, SciKit-Learn expects your training data to be in\n# spreadsheet (2D Array-Like) form. This means you can't simply\n# pass in a 1D Array (slice) and get away with it.\n#\n# To properly prep your data, you have to pass in a 2D Numpy Array,\n# or a dataframe. But what happens if you really only want to pass\n# in a single feature?\n#\n# If you slice your dataframe using df[['ColumnName']] syntax, the\n# result that comes back is actually a *dataframe*. Go ahead and do\n# a type() on it to check it out. Since it's already a dataframe,\n# you're good -- no further changes needed.\n#\n# But if you slice your dataframe using the df.ColumnName syntax,\n# OR if you call df['ColumnName'], the result that comes back is\n# actually a series (1D Array)! This will cause SKLearn to bug out.\n# So if you are slicing using either of those two techniques, before\n# sending your training or testing data to .fit / .score, do a\n# my_column = my_column.reshape(-1,1). This will convert your 1D\n# array of [n_samples], to a 2D array shaped like [n_samples, 1].\n# A single feature, with many samples.\n#\n# If you did something like my_column = [my_column], that would produce\n# an array in the shape of [1, n_samples], which is incorrect because\n# SKLearn expects your data to be arranged as [n_samples, n_features].\n# Keep in mind, all of the above only relates to your \"X\" or input\n# data, and does not apply to your \"y\" or labels.\n\n"
] | [
[
"matplotlib.pyplot.yticks",
"pandas.read_csv",
"matplotlib.style.use",
"matplotlib.pyplot.colorbar",
"sklearn.linear_model.LinearRegression",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
jwoehr/pennylane | [
"5de272a1ce6ed39b5c6ee34035f11f8c309266ee"
] | [
"tests/beta/test_vqe.py"
] | [
"# Copyright 2019 Xanadu Quantum Technologies 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\"\"\"\nUnit tests for the :mod:`pennylane.vqe` submodule.\n\"\"\"\nimport pytest\nimport pennylane as qml\nimport numpy as np\nimport pennylane.beta.vqe\n\n\ntry:\n import torch\nexcept ImportError as e:\n pass\n\n\ntry:\n import tensorflow as tf\n\n if tf.__version__[0] == \"1\":\n print(tf.__version__)\n import tensorflow.contrib.eager as tfe\n tf.enable_eager_execution()\n Variable = tfe.Variable\n else:\n from tensorflow import Variable\nexcept ImportError as e:\n pass\n\n\[email protected](scope=\"function\")\ndef seed():\n \"\"\"Resets the random seed with every test\"\"\"\n np.random.seed(0)\n\n\n#####################################################\n# Hamiltonians\n\n\nH_ONE_QUBIT = np.array([[1.0, 0.5j], [-0.5j, 2.5]])\n\nH_TWO_QUBITS = np.array(\n [[0.5, 1.0j, 0.0, -3j], [-1.0j, -1.1, 0.0, -0.1], [0.0, 0.0, -0.9, 12.0], [3j, -0.1, 12.0, 0.0]]\n)\n\nCOEFFS = [(0.5, 1.2, -0.7), (2.2, -0.2, 0.0), (0.33,)]\n\nOBSERVABLES = [\n (qml.PauliZ(0), qml.PauliY(0), qml.PauliZ(1)),\n (qml.PauliX(0) @ qml.PauliZ(1), qml.PauliY(0) @ qml.PauliZ(1), qml.PauliZ(1)),\n (qml.Hermitian(H_TWO_QUBITS, [0, 1]),),\n]\n\nJUNK_INPUTS = [None, [], tuple(), 5.0, {\"junk\": -1}]\n\nvalid_hamiltonians = [\n ((1.0,), (qml.Hermitian(H_TWO_QUBITS, [0, 1]),)),\n ((-0.8,), (qml.PauliZ(0),)),\n ((0.5, -1.6), (qml.PauliX(0), qml.PauliY(1))),\n ((0.5, -1.6), (qml.PauliX(1), qml.PauliY(1))),\n ((1.1, -0.4, 0.333), (qml.PauliX(0), qml.Hermitian(H_ONE_QUBIT, 2), qml.PauliZ(2))),\n ((-0.4, 0.15), (qml.Hermitian(H_TWO_QUBITS, [0, 2]), qml.PauliZ(1))),\n ([1.5, 2.0], [qml.PauliZ(0), qml.PauliY(2)]),\n (np.array([-0.1, 0.5]), [qml.Hermitian(H_TWO_QUBITS, [0, 1]), qml.PauliY(0)]),\n ((0.5, 1.2), (qml.PauliX(0), qml.PauliX(0) @ qml.PauliX(1))),\n]\n\ninvalid_hamiltonians = [\n ((), (qml.PauliZ(0),)),\n ((), (qml.PauliZ(0), qml.PauliY(1))),\n ((3.5,), ()),\n ((1.2, -0.4), ()),\n ((0.5, 1.2), (qml.PauliZ(0),)),\n ((1.0,), (qml.PauliZ(0), qml.PauliY(0))),\n]\n\n\nhamiltonians_with_expvals = [\n ((-0.6,), (qml.PauliZ(0),), [-0.6 * 1.0]),\n ((1.0,), (qml.PauliX(0),), [0.0]),\n ((0.5, 1.2), (qml.PauliZ(0), qml.PauliX(0)), [0.5 * 1.0, 0]),\n ((0.5, 1.2), (qml.PauliZ(0), qml.PauliX(1)), [0.5 * 1.0, 0]),\n ((0.5, 1.2), (qml.PauliZ(0), qml.PauliZ(0)), [0.5 * 1.0, 1.2 * 1.0]),\n ((0.5, 1.2), (qml.PauliZ(0), qml.PauliZ(1)), [0.5 * 1.0, 1.2 * 1.0]),\n]\n\n#####################################################\n# Ansatz\n\ndef custom_fixed_ansatz(*params, wires=None):\n \"\"\"Custom fixed ansatz\"\"\"\n qml.RX(0.5, wires=0)\n qml.RX(-1.2, wires=1)\n qml.Hadamard(wires=0)\n qml.CNOT(wires=[0, 1])\n qml.Hadamard(wires=1)\n qml.CNOT(wires=[0, 1])\n\n\ndef custom_var_ansatz(*params, wires=None):\n \"\"\"Custom parametrized ansatz\"\"\"\n for p in params:\n qml.RX(p, wires=wires[0])\n\n qml.CNOT(wires=[wires[0], wires[1]])\n\n for p in params:\n qml.RX(-p, wires=wires[1])\n\n qml.CNOT(wires=[wires[0], wires[1]])\n\n\ndef amp_embed_and_strong_ent_layer(*params, wires=None):\n \"\"\"Ansatz combining amplitude embedding and\n strongly entangling layers\"\"\"\n qml.templates.embeddings.AmplitudeEmbedding(*params[0], wires=wires)\n qml.templates.layers.StronglyEntanglingLayers(*params[1], wires=wires)\n\n\nANSAETZE = [\n lambda *params, wires=None: None,\n custom_fixed_ansatz,\n custom_var_ansatz,\n qml.templates.embeddings.AmplitudeEmbedding,\n qml.templates.layers.StronglyEntanglingLayers,\n amp_embed_and_strong_ent_layer,\n]\n\n#####################################################\n# Parameters\n\nEMPTY_PARAMS = []\nVAR_PARAMS = [0.5]\nEMBED_PARAMS = [np.array([1 / np.sqrt(2 ** 3)] * 2 ** 3)]\nLAYER_PARAMS = [qml.init.strong_ent_layers_uniform(n_layers=2, n_wires=3)]\n\nCIRCUITS = [\n (lambda *params, wires=None: None, EMPTY_PARAMS),\n (custom_fixed_ansatz, EMPTY_PARAMS),\n (custom_var_ansatz, VAR_PARAMS),\n (qml.templates.layers.StronglyEntanglingLayers, LAYER_PARAMS),\n (qml.templates.embeddings.AmplitudeEmbedding, EMBED_PARAMS),\n (amp_embed_and_strong_ent_layer, (EMBED_PARAMS, LAYER_PARAMS)),\n]\n\n#####################################################\n# Device\n\[email protected](scope=\"function\")\ndef mock_device(monkeypatch):\n with monkeypatch.context() as m:\n m.setattr(qml.Device, \"__abstractmethods__\", frozenset())\n m.setattr(qml.Device, \"_capabilities\", {\"tensor_observables\": True, \"model\": \"qubit\"})\n m.setattr(qml.Device, \"operations\", [\"RX\", \"Rot\", \"CNOT\", \"Hadamard\", \"QubitStateVector\"])\n m.setattr(\n qml.Device, \"observables\", [\"PauliX\", \"PauliY\", \"PauliZ\", \"Hadamard\", \"Hermitian\"]\n )\n m.setattr(qml.Device, \"short_name\", \"MockDevice\")\n m.setattr(qml.Device, \"expval\", lambda self, x, y, z: 1)\n m.setattr(qml.Device, \"var\", lambda self, x, y, z: 2)\n m.setattr(qml.Device, \"sample\", lambda self, x, y, z: 3)\n m.setattr(qml.Device, \"apply\", lambda self, x, y, z: None)\n yield qml.Device()\n\n#####################################################\n# Tests\n\nclass TestHamiltonian:\n \"\"\"Test the Hamiltonian class\"\"\"\n\n @pytest.mark.parametrize(\"coeffs, ops\", valid_hamiltonians)\n def test_hamiltonian_valid_init(self, coeffs, ops):\n \"\"\"Tests that the Hamiltonian object is created with\n the correct attributes\"\"\"\n H = qml.beta.vqe.Hamiltonian(coeffs, ops)\n assert H.terms == (coeffs, ops)\n\n @pytest.mark.parametrize(\"coeffs, ops\", invalid_hamiltonians)\n def test_hamiltonian_invalid_init_exception(self, coeffs, ops):\n \"\"\"Tests that an exception is raised when giving an invalid\n combination of coefficients and ops\"\"\"\n with pytest.raises(ValueError, match=\"number of coefficients and operators does not match\"):\n H = qml.beta.vqe.Hamiltonian(coeffs, ops)\n\n @pytest.mark.parametrize(\"coeffs\", [[0.2, -1j], [0.5j, 2-1j]])\n def test_hamiltonian_complex(self, coeffs):\n \"\"\"Tests that an exception is raised when\n a complex Hamiltonian is given\"\"\"\n obs = [qml.PauliX(0), qml.PauliZ(1)]\n\n with pytest.raises(ValueError, match=\"coefficients are not real-valued\"):\n H = qml.beta.vqe.Hamiltonian(coeffs, obs)\n\n @pytest.mark.parametrize(\"obs\", [[qml.PauliX(0), qml.CNOT(wires=[0, 1])], [qml.PauliZ, qml.PauliZ(0)]])\n def test_hamiltonian_invalid_observables(self, obs):\n \"\"\"Tests that an exception is raised when\n a complex Hamiltonian is given\"\"\"\n coeffs = [0.1, 0.2]\n\n with pytest.raises(ValueError, match=\"observables are not valid\"):\n H = qml.beta.vqe.Hamiltonian(coeffs, obs)\n\n\nclass TestVQE:\n \"\"\"Test the core functionality of the VQE module\"\"\"\n\n @pytest.mark.parametrize(\"ansatz\", ANSAETZE)\n @pytest.mark.parametrize(\"observables\", OBSERVABLES)\n def test_circuits_valid_init(self, ansatz, observables, mock_device):\n \"\"\"Tests that a collection of circuits is properly created by vqe.circuits\"\"\"\n circuits = qml.beta.vqe.circuits(ansatz, observables, device=mock_device)\n\n assert len(circuits) == len(observables)\n assert all(callable(c) for c in circuits)\n assert all(c.device == mock_device for c in circuits)\n assert all(hasattr(c, \"jacobian\") for c in circuits)\n\n @pytest.mark.parametrize(\"ansatz, params\", CIRCUITS)\n @pytest.mark.parametrize(\"observables\", OBSERVABLES)\n def test_circuits_evaluate(self, ansatz, observables, params, mock_device, seed):\n \"\"\"Tests that the circuits returned by ``vqe.circuits`` evaluate properly\"\"\"\n mock_device.num_wires = 3\n circuits = qml.beta.vqe.circuits(ansatz, observables, device=mock_device)\n res = [c(*params) for c in circuits]\n assert all(val == 1.0 for val in res)\n\n @pytest.mark.parametrize(\"coeffs, observables, expected\", hamiltonians_with_expvals)\n def test_circuits_expvals(self, coeffs, observables, expected):\n \"\"\"Tests that the vqe.circuits function returns correct expectation values\"\"\"\n dev = qml.device(\"default.qubit\", wires=2)\n circuits = qml.beta.vqe.circuits(lambda *params, **kwargs: None, observables, dev)\n res = [a * c([]) for a, c in zip(coeffs, circuits)]\n assert np.all(res == expected)\n\n @pytest.mark.parametrize(\"ansatz\", ANSAETZE)\n @pytest.mark.parametrize(\"observables\", JUNK_INPUTS)\n def test_circuits_no_observables(self, ansatz, observables, mock_device):\n \"\"\"Tests that an exception is raised when no observables are supplied to vqe.circuits\"\"\"\n with pytest.raises(ValueError, match=\"observables are not valid\"):\n obs = (observables,)\n circuits = qml.beta.vqe.circuits(ansatz, obs, device=mock_device)\n\n @pytest.mark.parametrize(\"ansatz\", JUNK_INPUTS)\n @pytest.mark.parametrize(\"observables\", OBSERVABLES)\n def test_circuits_no_ansatz(self, ansatz, observables, mock_device):\n \"\"\"Tests that an exception is raised when no valid ansatz is supplied to vqe.circuits\"\"\"\n with pytest.raises(ValueError, match=\"ansatz is not a callable function\"):\n circuits = qml.beta.vqe.circuits(ansatz, observables, device=mock_device)\n\n @pytest.mark.parametrize(\"coeffs, observables, expected\", hamiltonians_with_expvals)\n def test_aggregate_expval(self, coeffs, observables, expected):\n \"\"\"Tests that the aggregate function returns correct expectation values\"\"\"\n dev = qml.device(\"default.qubit\", wires=2)\n qnodes = qml.beta.vqe.circuits(lambda *params, **kwargs: None, observables, dev)\n expval = qml.beta.vqe.aggregate(coeffs, qnodes, [])\n assert expval == sum(expected)\n\n @pytest.mark.parametrize(\"ansatz, params\", CIRCUITS)\n @pytest.mark.parametrize(\"coeffs, observables\", [z for z in zip(COEFFS, OBSERVABLES)])\n def test_cost_evaluate(self, params, ansatz, coeffs, observables):\n \"\"\"Tests that the cost function evaluates properly\"\"\"\n hamiltonian = qml.beta.vqe.Hamiltonian(coeffs, observables)\n dev = qml.device(\"default.qubit\", wires=3)\n expval = qml.beta.vqe.cost(params, ansatz, hamiltonian, dev)\n assert type(expval) == float\n assert np.shape(expval) == () # expval should be scalar\n\n @pytest.mark.parametrize(\"coeffs, observables, expected\", hamiltonians_with_expvals)\n def test_cost_expvals(self, coeffs, observables, expected):\n \"\"\"Tests that the cost function returns correct expectation values\"\"\"\n dev = qml.device(\"default.qubit\", wires=2)\n hamiltonian = qml.beta.vqe.Hamiltonian(coeffs, observables)\n cost = qml.beta.vqe.cost([], lambda *params, **kwargs: None, hamiltonian, dev)\n assert cost == sum(expected)\n\n @pytest.mark.parametrize(\"ansatz\", JUNK_INPUTS)\n def test_cost_invalid_ansatz(self, ansatz, mock_device):\n \"\"\"Tests that the cost function raises an exception if the ansatz is not valid\"\"\"\n hamiltonian = qml.beta.vqe.Hamiltonian((1.0,), [qml.PauliZ(0)])\n with pytest.raises(ValueError, match=\"The ansatz is not a callable function.\"):\n cost = qml.beta.vqe.cost([], 4, hamiltonian, mock_device)\n\n\nclass TestAutogradInterface:\n \"\"\"Tests for the Autograd interface (and the NumPy interface for backward compatibility)\"\"\"\n\n @pytest.mark.parametrize(\"ansatz, params\", CIRCUITS)\n @pytest.mark.parametrize(\"observables\", OBSERVABLES)\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"numpy\"])\n def test_QNodes_have_right_interface(self, ansatz, observables, params, mock_device, interface):\n \"\"\"Test that QNodes have the Autograd interface\"\"\"\n mock_device.num_wires = 3\n circuits = qml.beta.vqe.circuits(ansatz, observables, device=mock_device, interface=interface)\n\n assert all(c.interface == \"autograd\" for c in circuits)\n assert all(c.__class__.__name__ == \"AutogradQNode\" for c in circuits)\n\n res = [c(*params) for c in circuits]\n assert all(isinstance(val, float) for val in res)\n\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"numpy\"])\n def test_gradient(self, tol, interface):\n \"\"\"Test differentiation works\"\"\"\n dev = qml.device(\"default.qubit\", wires=1)\n\n def ansatz(*params, **kwargs):\n qml.RX(params[0], wires=0)\n qml.RY(params[1], wires=0)\n\n coeffs = [0.2, 0.5]\n observables = [qml.PauliX(0), qml.PauliY(0)]\n\n H = qml.beta.vqe.Hamiltonian(coeffs, observables)\n a, b = 0.54, 0.123\n params = np.array([a, b])\n\n cost = qml.beta.vqe.cost(params, ansatz, H, dev, interface=interface)\n\n cost2 = lambda params: qml.beta.vqe.cost(params, ansatz, H, dev, interface=interface)\n dcost = qml.grad(cost2, argnum=[0])\n res = dcost(params)\n\n expected = [\n -coeffs[0]*np.sin(a)*np.sin(b) - coeffs[1]*np.cos(a),\n coeffs[0]*np.cos(a)*np.cos(b)\n ]\n\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n\[email protected](\"skip_if_no_torch_support\")\nclass TestTorchInterface:\n \"\"\"Tests for the PyTorch interface\"\"\"\n\n @pytest.mark.parametrize(\"ansatz, params\", CIRCUITS)\n @pytest.mark.parametrize(\"observables\", OBSERVABLES)\n def test_QNodes_have_right_interface(self, ansatz, observables, params, mock_device):\n \"\"\"Test that QNodes have the torch interface\"\"\"\n mock_device.num_wires = 3\n circuits = qml.beta.vqe.circuits(ansatz, observables, device=mock_device, interface=\"torch\")\n assert all(c.interface == \"torch\" for c in circuits)\n\n res = [c(*params) for c in circuits]\n assert all(isinstance(val, torch.Tensor) for val in res)\n\n def test_gradient(self, tol):\n \"\"\"Test differentiation works\"\"\"\n dev = qml.device(\"default.qubit\", wires=1)\n\n def ansatz(*params, **kwargs):\n qml.RX(params[0], wires=0)\n qml.RY(params[1], wires=0)\n\n coeffs = [0.2, 0.5]\n observables = [qml.PauliX(0), qml.PauliY(0)]\n\n H = qml.beta.vqe.Hamiltonian(coeffs, observables)\n a, b = 0.54, 0.123\n params = torch.autograd.Variable(torch.tensor([a, b]), requires_grad=True)\n\n cost = qml.beta.vqe.cost(params, ansatz, H, dev, interface=\"torch\")\n cost.backward()\n\n res = params.grad.numpy()\n\n expected = [\n -coeffs[0]*np.sin(a)*np.sin(b) - coeffs[1]*np.cos(a),\n coeffs[0]*np.cos(a)*np.cos(b)\n ]\n\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n\n\[email protected](\"skip_if_no_tf_support\")\nclass TestTFInterface:\n \"\"\"Tests for the TF interface\"\"\"\n\n @pytest.mark.parametrize(\"ansatz, params\", CIRCUITS)\n @pytest.mark.parametrize(\"observables\", OBSERVABLES)\n def test_QNodes_have_right_interface(self, ansatz, observables, params, mock_device):\n \"\"\"Test that QNodes have the tf interface\"\"\"\n mock_device.num_wires = 3\n circuits = qml.beta.vqe.circuits(ansatz, observables, device=mock_device, interface=\"tf\")\n assert all(c.interface == \"tf\" for c in circuits)\n\n res = [c(*params) for c in circuits]\n assert all(isinstance(val, (Variable, tf.Tensor)) for val in res)\n\n def test_gradient(self, tol):\n \"\"\"Test differentiation works\"\"\"\n dev = qml.device(\"default.qubit\", wires=1)\n\n def ansatz(*params, **kwargs):\n qml.RX(params[0], wires=0)\n qml.RY(params[1], wires=0)\n\n coeffs = [0.2, 0.5]\n observables = [qml.PauliX(0), qml.PauliY(0)]\n\n H = qml.beta.vqe.Hamiltonian(coeffs, observables)\n a, b = 0.54, 0.123\n params = [Variable(i, dtype=tf.float64) for i in [a, b]]\n\n with tf.GradientTape() as tape:\n cost = qml.beta.vqe.cost(params, ansatz, H, dev, interface=\"tf\")\n res = np.array(tape.gradient(cost, params))\n\n expected = [\n -coeffs[0]*np.sin(a)*np.sin(b) - coeffs[1]*np.cos(a),\n coeffs[0]*np.cos(a)*np.cos(b)\n ]\n\n assert np.allclose(res, expected, atol=tol, rtol=0)\n\n\[email protected](\"skip_if_no_tf_support\")\[email protected](\"skip_if_no_torch_support\")\nclass TestMultipleInterfaceIntegration:\n \"\"\"Tests to ensure that interfaces agree and integrate correctly\"\"\"\n\n def test_all_interfaces_gradient_agree(self, tol):\n \"\"\"Test the gradient agrees across all interfaces\"\"\"\n dev = qml.device(\"default.qubit\", wires=2)\n\n coeffs = [0.2, 0.5]\n observables = [qml.PauliX(0)@qml.PauliZ(1), qml.PauliY(0)]\n\n H = qml.beta.vqe.Hamiltonian(coeffs, observables)\n\n # TensorFlow interface\n params = [Variable(i) for i in [qml.init.strong_ent_layers_normal(n_layers=3, n_wires=2, seed=1)]]\n ansatz = qml.templates.layers.StronglyEntanglingLayers\n\n cost = qml.beta.vqe.cost(params, ansatz, H, dev, interface=\"tf\")\n\n with tf.GradientTape() as tape:\n cost = qml.beta.vqe.cost(params, ansatz, H, dev, interface=\"tf\")\n res_tf = np.array(tape.gradient(cost, params))\n\n # Torch interface\n params = torch.tensor([qml.init.strong_ent_layers_normal(n_layers=3, n_wires=2, seed=1)])\n params = torch.autograd.Variable(params, requires_grad=True)\n ansatz = qml.templates.layers.StronglyEntanglingLayers\n\n cost = qml.beta.vqe.cost(params, ansatz, H, dev, interface=\"torch\")\n cost.backward()\n res_torch = params.grad.numpy()\n\n # NumPy interface\n params = [qml.init.strong_ent_layers_normal(n_layers=3, n_wires=2, seed=1)]\n ansatz = qml.templates.layers.StronglyEntanglingLayers\n cost = qml.beta.vqe.cost(params, ansatz, H, dev, interface=\"numpy\")\n cost2 = lambda params: qml.beta.vqe.cost(params, ansatz, H, dev, interface=\"numpy\")\n dcost = qml.grad(cost2, argnum=[0])\n res = dcost(params)\n\n assert np.allclose(res, res_tf, atol=tol, rtol=0)\n assert np.allclose(res, res_torch, atol=tol, rtol=0)\n\n def test_aggregate_expval_different_interfaces(self):\n \"\"\"Tests that the aggregate function raises an exception if passed\n QNodes with different interfaces\"\"\"\n dev = qml.device(\"default.qubit\", wires=2)\n\n @qml.qnode(dev, interface=\"tf\")\n def circuit1():\n return qml.expval(qml.PauliZ(0))\n\n @qml.qnode(dev)\n def circuit2():\n return qml.expval(qml.PauliZ(0))\n\n with pytest.raises(ValueError, match=\"must all use the same interface\"):\n qml.beta.vqe.aggregate([1, 1], [circuit1, circuit2], [])\n"
] | [
[
"tensorflow.enable_eager_execution",
"numpy.allclose",
"numpy.random.seed",
"tensorflow.Variable",
"numpy.sqrt",
"numpy.cos",
"torch.tensor",
"numpy.all",
"numpy.sin",
"tensorflow.GradientTape",
"numpy.shape",
"numpy.array",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
lockwo/quantum_computation | [
"a377c60e1dcaada466eebfbcb412cd243e54e34c"
] | [
"TFQ/QAE/quantum_autoencoder.py"
] | [
"import tensorflow_quantum as tfq\nimport cirq \nimport sympy\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport random\nfrom itertools import product\n\ndef layer(qs, params):\n circ = cirq.Circuit()\n for i in reversed(range(len(qs)-1)):\n circ += cirq.CNOT(qs[i], qs[i+1])\n for i in range(len(qs)):\n circ += cirq.ry(params[2*i]).on(qs[i])\n circ += cirq.rz(params[2*i + 1]).on(qs[i])\n return circ\n\ndef make_circuit(qs, state, latent, params, depth, swap_qubit, reference_qubits):\n c = cirq.Circuit()\n enc_params = params[:len(params) // 2]\n dec_params = params[len(params) // 2:]\n for i in range(depth):\n c += layer(qs[:state], enc_params[2 * i * state:2 * (i + 1) * state])\n for i in range(depth):\n c += layer(qs[state - latent:], dec_params[2 * i * state:2 * (i + 1) * state])\n # SWAP Test\n c += cirq.H(swap_qubit)\n for i, j in product(range(state), range(state - latent, len(qs))):\n #c += cirq.CSWAP(swap_qubit, reference_qubits[i], qs[j])\n c += cirq.ControlledGate(sub_gate=cirq.SWAP, num_controls=1).on(swap_qubit, reference_qubits[i], qs[j])\n c += cirq.H(swap_qubit)\n return c\n\n\nstate_qubits = 4\nlatent_qubits = 1\ntotal_qubits = state_qubits + (state_qubits - latent_qubits)\n\nqubits = [cirq.GridQubit(0, i) for i in range(total_qubits + 1 + state_qubits)]\nprint(len(qubits))\n#states, _ = tfq.datasets.excited_cluster_states(qubits[:state_qubits])\n#reference_states, _ = tfq.datasets.excited_cluster_states(qubits[total_qubits + 1:])\n#states, _, _, _ = tfq.datasets.xxz_chain(qubits[:state_qubits])\n#reference_states, _, _, _ = tfq.datasets.xxz_chain(qubits[total_qubits + 1:])\nstates, _, _, _ = tfq.datasets.tfi_chain(qubits[:state_qubits])\nreference_states, _, _, _ = tfq.datasets.tfi_chain(qubits[total_qubits + 1:])\nstates = list(states)\nreference_states = list(reference_states)\ntemp = list(zip(states, reference_states))\nrandom.shuffle(temp)\nstates, reference_states = zip(*temp)\n\nlayers = 4\n\nnum_params = 4 * state_qubits * layers\nparameters = sympy.symbols(\"q0:%d\"%num_params)\n\ntrain_size = 9 * len(states) // 10\ntest_size = len(states) - train_size\ntraining_states = states[:train_size]\ntesting_states = states[train_size:]\nreference_states_train = reference_states[:train_size]\nreference_states_test = reference_states[train_size:]\ntrain_circuits = [training_states[i] + reference_states_train[i] for i in range(train_size)]\ntest_circuits = [testing_states[i] + reference_states_test[i] for i in range(test_size)]\n#print(make_circuit(qubits[:total_qubits], state_qubits, latent_qubits, parameters, layers, qubits[total_qubits], qubits[total_qubits + 1:]))\n#print(training_states[0] + reference_states[0] + make_circuit(qubits[:total_qubits], state_qubits, latent_qubits, parameters, layers, qubits[total_qubits], qubits[total_qubits + 1:]))\n#print(train_circuits[0])\n\nc = make_circuit(qubits[:total_qubits], state_qubits, latent_qubits, parameters, layers, qubits[total_qubits], qubits[total_qubits + 1:])\nreadout_operators = [cirq.Z(qubits[total_qubits])]\ninputs = tf.keras.Input(shape=(), dtype=tf.dtypes.string)\nlayer1 = tfq.layers.PQC(c, readout_operators, differentiator=tfq.differentiators.Adjoint())(inputs)\nautoencoder = tf.keras.models.Model(inputs=inputs, outputs=layer1)\nautoencoder.compile(loss='mae', optimizer=tf.keras.optimizers.Adam(lr=0.1))\ncallback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20)\n\nX_train = tfq.convert_to_tensor(train_circuits)\nX_test = tfq.convert_to_tensor(test_circuits)\n\ny_train = np.ones(shape=len(train_circuits))\ny_test = np.ones(shape=len(test_circuits))\n\nhistory = autoencoder.fit(X_train, y_train, epochs=100, batch_size=10, validation_data=(X_test, y_test), callbacks=[callback])\n\nplt.plot(history.history['loss'], label='Train')\nplt.plot(history.history['val_loss'], label='Test')\nplt.legend()\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"1 - Fidelity\")\nplt.show()\nplt.savefig(\"loss_comp\")\n\n\n\n"
] | [
[
"matplotlib.pyplot.legend",
"tensorflow.keras.Input",
"tensorflow.keras.models.Model",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"tensorflow.keras.optimizers.Adam",
"matplotlib.pyplot.xlabel",
"tensorflow.keras.callbacks.EarlyStopping",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
AHGOverbeek/eve-ros2-examples | [
"b61fbdc5dfd2b7895f1e29c493b2126a8e811d51"
] | [
"eve_ros2_examples/task_box.py"
] | [
"#!/usr/bin/env python3\n\n# Copyright 2021 Halodi Robotics\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 uuid\n\nimport numpy as np\nimport rclpy\nimport rclpy.qos\nfrom action_msgs.msg import GoalStatus\nfrom builtin_interfaces.msg import Duration\nfrom halodi_msgs.msg import (\n JointName,\n JointSpaceCommand,\n ReferenceFrameName,\n TaskSpaceCommand,\n TrajectoryInterpolation,\n WholeBodyTrajectory,\n WholeBodyTrajectoryPoint,\n JointNullSpaceConfiguration\n)\nfrom rclpy.node import Node\nfrom scipy.spatial.transform import Rotation\nfrom unique_identifier_msgs.msg import UUID\n\n\ndef generate_uuid_msg():\n \"\"\"Generates a UUID msg based on the current time.\n\n Parameters: None\n\n Returns: UUID msg\n \"\"\"\n return UUID(uuid=np.asarray(list(uuid.uuid1().bytes)).astype(np.uint8))\n\n\ndef generate_task_space_command_msg(\n body_frame_id, expressed_in_frame_id, xyzrpy, z_up=True\n):\n \"\"\"Generates a task space command msg.\n\n Parameters:\n - body_frame_id (enum): body part to be moved, e.g. ReferenceFrameName.PELVIS\n - expressed_in_frame_id (enum): reference frame for body_frame_id, e.g. ReferenceFrameName.BASE\n - xyzrpy (array of 6 floats): desired pose of body_frame_id relative to expressed_in_frame_id\n , as a list/tuple/1D np.array of [ posX, posY, posZ, rotX, rotY, rotZ ]\n - z_up (bool): whether or not xyzrpy follows the Z-up co-ordinate convention. Default: True\n\n Returns: TaskSpaceCommand msg\n \"\"\"\n\n msg_ = TaskSpaceCommand(express_in_z_up=z_up)\n msg_.body_frame.frame_id = body_frame_id\n msg_.expressed_in_frame.frame_id = expressed_in_frame_id\n\n msg_.pose.position.x = xyzrpy[0]\n msg_.pose.position.y = xyzrpy[1]\n msg_.pose.position.z = xyzrpy[2]\n quat_ = Rotation.from_euler(\"xyz\", xyzrpy[3:]).as_quat() # Euler to quaternion\n msg_.pose.orientation.x = quat_[0]\n msg_.pose.orientation.y = quat_[1]\n msg_.pose.orientation.z = quat_[2]\n msg_.pose.orientation.w = quat_[3]\n\n return msg_\n\nclass WholeBodyTrajectoryPublisher(Node):\n\n def __init__(self, periodic_trajectory_msg=None):\n super().__init__(\n \"task_box\"\n ) # initialize the underlying Node with the name whole_body_robot_bringup\n\n # 10 is overloaded for being 10 deep history QoS\n self._publisher = self.create_publisher(\n WholeBodyTrajectory, \"/eve/whole_body_trajectory\", rclpy.qos.qos_profile_action_status_default \n )\n\n self._subscriber = self.create_subscription(\n GoalStatus, \"/eve/whole_body_trajectory_status\", self.goal_status_cb, 10\n ) # create a GoalStatus subscriber with inbound queue size of 10\n\n # Create publisher to the nullspace configurator\n self._publisher_ns = self.create_publisher(\n JointNullSpaceConfiguration, \"/eve/joint_null_space_configuration\", rclpy.qos.qos_profile_action_status_default \n )\n\n ms = JointNullSpaceConfiguration()\n joint = JointName()\n joint.joint_id = JointName.LEFT_SHOULDER_PITCH\n ms.joint = joint\n ms.q_nullspace = -1.5\n self._publisher_ns.publish(ms) \n\n # store periodic_trajectory_msg for re-publishing in goal_status_cb\n self._periodic_trajectory_msg = periodic_trajectory_msg\n\n # Trajectory messages need an uuid, not properly using it here\n self._periodic_trajectory_msg.trajectory_id = generate_uuid_msg() # populate UUID\n self.get_logger().info(\"Publishing first periodic trajectory ...\")\n self._publisher.publish(self._periodic_trajectory_msg) \n\n def goal_status_cb(self, msg):\n\n if msg.status == GoalStatus.STATUS_ACCEPTED:\n self.get_logger().info(\"Goal accepted\")\n elif msg.status == GoalStatus.STATUS_CANCELED:\n self.get_logger().info(\"Goal canceled\")\n elif msg.status == GoalStatus.STATUS_ABORTED:\n self.get_logger().info(\"Goal aborted\")\n elif msg.status == GoalStatus.STATUS_SUCCEEDED:\n self.get_logger().info(\"Goal succeeded!\")\n self.get_logger().info(\"Republishing periodic trajectory ...\")\n self._publisher.publish(self._periodic_trajectory_msg)\n\n\ndef main():\n\n\n x = 0.25\n y1 = 0.3\n y2 = 0.5\n z1 = 0.25\n z2 = 0.0\n dt = 1\n\n cumulative_seconds_from_start_ = 0\n\n cumulative_seconds_from_start_ = cumulative_seconds_from_start_ + dt\n periodic_trajectory_pt_msg_1_ = WholeBodyTrajectoryPoint(\n time_from_start=Duration(sec=cumulative_seconds_from_start_)\n ) # create a trajectory point msg, timestamped for 3 seconds in the future\n periodic_trajectory_pt_msg_1_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.RIGHT_HAND,\n ReferenceFrameName.PELVIS,\n [x, -y1, z1, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n periodic_trajectory_pt_msg_1_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.LEFT_HAND,\n ReferenceFrameName.PELVIS,\n [x, y1, z1, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n\n cumulative_seconds_from_start_ = cumulative_seconds_from_start_ + dt\n periodic_trajectory_pt_msg_2_ = WholeBodyTrajectoryPoint(\n time_from_start=Duration(sec=cumulative_seconds_from_start_)\n ) # create another trajectory point msg, 1 additional second in the future\n periodic_trajectory_pt_msg_2_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.RIGHT_HAND,\n ReferenceFrameName.PELVIS,\n [x, -y1, z2, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n periodic_trajectory_pt_msg_2_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.LEFT_HAND,\n ReferenceFrameName.PELVIS,\n [x, y1, z2, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n\n cumulative_seconds_from_start_ = cumulative_seconds_from_start_ + dt\n periodic_trajectory_pt_msg_3_ = WholeBodyTrajectoryPoint(\n time_from_start=Duration(sec=cumulative_seconds_from_start_)\n ) # create another trajectory point msg, 1 additional second in the future\n periodic_trajectory_pt_msg_3_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.RIGHT_HAND,\n ReferenceFrameName.PELVIS,\n [x, -y2, z2, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n periodic_trajectory_pt_msg_3_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.LEFT_HAND,\n ReferenceFrameName.PELVIS,\n [x, y2, z2, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n\n cumulative_seconds_from_start_ = cumulative_seconds_from_start_ + dt\n periodic_trajectory_pt_msg_4_ = WholeBodyTrajectoryPoint(\n time_from_start=Duration(sec=cumulative_seconds_from_start_)\n ) # create another trajectory point msg, 1 additional second in the future\n periodic_trajectory_pt_msg_4_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.RIGHT_HAND,\n ReferenceFrameName.PELVIS,\n [x, -y2, z1, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n periodic_trajectory_pt_msg_4_.task_space_commands.append(\n generate_task_space_command_msg(\n ReferenceFrameName.LEFT_HAND,\n ReferenceFrameName.PELVIS,\n [x, y2, z1, 0.0, -np.deg2rad(90.0), 0.0],\n )\n ) # append a desired task space pose for the pelvis WRT base\n # [posX, posY, posZ, roll, pitch, yaw]\n\n periodic_trajectory_msg_ = WholeBodyTrajectory(\n append_trajectory=False\n ) # create a whole body trajectory msg that will\n # override any trajectory currently being executed\n periodic_trajectory_msg_.interpolation_mode.value = (\n TrajectoryInterpolation.MINIMUM_JERK_CONSTRAINED\n ) # choose an interpolation mode\n periodic_trajectory_msg_.trajectory_points.append(periodic_trajectory_pt_msg_1_)\n periodic_trajectory_msg_.trajectory_points.append(periodic_trajectory_pt_msg_2_)\n periodic_trajectory_msg_.trajectory_points.append(periodic_trajectory_pt_msg_3_)\n periodic_trajectory_msg_.trajectory_points.append(periodic_trajectory_pt_msg_4_)\n\n rclpy.init() # initialize rclpy\n\n node = WholeBodyTrajectoryPublisher(periodic_trajectory_msg_)\n\n # Spin means wait and listen for what you're subscribed to, otherwise the script would just end\n try:\n rclpy.spin(node)\n except KeyboardInterrupt:\n pass\n\n rclpy.shutdown()\n\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"scipy.spatial.transform.Rotation.from_euler",
"numpy.deg2rad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.5",
"1.2",
"1.3",
"1.4"
],
"tensorflow": []
}
] |
ben-heil/hetio | [
"9a2a218513ff270357775e58360ba950c30197d1"
] | [
"hetio/matrix.py"
] | [
"from collections import OrderedDict\n\nimport logging\nimport numpy\nimport scipy.sparse\n\n\ndef get_nodes(graph, metanode):\n \"\"\"\n Return a list of nodes for a given metanode, in sorted order.\n \"\"\"\n metanode = graph.metagraph.get_metanode(metanode)\n metanode_to_nodes = graph.get_metanode_to_nodes()\n nodes = sorted(metanode_to_nodes[metanode])\n return nodes\n\n\ndef get_node_identifiers(graph, metanode):\n \"\"\"\n Returns a list of identifiers for a given metanode\n \"\"\"\n nodes = get_nodes(graph, metanode)\n return [node.identifier for node in nodes]\n\n\ndef get_node_to_position(graph, metanode):\n \"\"\"\n Given a metanode, return a dictionary of node to position\n \"\"\"\n nodes = get_nodes(graph, metanode)\n node_to_position = OrderedDict((n, i) for i, n in enumerate(nodes))\n return node_to_position\n\n\ndef metaedge_to_adjacency_matrix(\n graph, metaedge, dtype=numpy.bool_, dense_threshold=0):\n \"\"\"\n Returns an adjacency matrix where source nodes are rows and target\n nodes are columns.\n\n Parameters\n ==========\n graph : hetio.hetnet.graph\n metaedge : hetio.hetnet.MetaEdge or an alternative metaedge specification\n dtype : type\n dense_threshold : float (0 ≤ dense_threshold ≤ 1)\n minimum proportion of nonzero values at which to output a dense matrix.\n Default of 0 ensures output is always dense.\n\n Returns\n =======\n row_names : list\n column_names : list\n matrix : numpy.ndarray or scipy.sparse\n \"\"\"\n metaedge = graph.metagraph.get_metaedge(metaedge)\n source_nodes = list(get_node_to_position(graph, metaedge.source))\n target_node_to_position = get_node_to_position(graph, metaedge.target)\n shape = len(source_nodes), len(target_node_to_position)\n row, col, data = [], [], []\n for i, source_node in enumerate(source_nodes):\n for edge in source_node.edges[metaedge]:\n row.append(i)\n col.append(target_node_to_position[edge.target])\n data.append(1)\n adjacency_matrix = scipy.sparse.csc_matrix(\n (data, (row, col)), shape=shape, dtype=dtype)\n adjacency_matrix = sparsify_or_densify(adjacency_matrix, dense_threshold)\n row_names = [node.identifier for node in source_nodes]\n column_names = [node.identifier for node in target_node_to_position]\n return row_names, column_names, adjacency_matrix\n\n\ndef sparsify_or_densify(matrix, dense_threshold=0.3):\n \"\"\"\n Automatically convert a scipy.sparse to a numpy.ndarray if the percent\n nonzero is above a given threshold. Automatically convert a numpy.ndarray\n to scipy.sparse if the percent nonzero is below a given threshold.\n\n Parameters\n ==========\n matrix : numpy.ndarray or scipy.sparse\n dense_threshold : float (0 ≤ dense_threshold ≤ 1)\n minimum proportion of nonzero values at which to output a dense matrix.\n Setting to 0 ensures output is dense. Setting to 1 ensures output is\n sparse, unless matrix has no zero entries (use dense_threshold > 1) to\n guarantee sparse output.\n\n Returns\n =======\n matrix : numpy.ndarray or scipy.sparse\n \"\"\"\n if scipy.sparse.issparse(matrix):\n nnz = matrix.nnz\n else:\n nnz = numpy.count_nonzero(matrix)\n density = nnz / numpy.prod(matrix.shape)\n densify = density >= dense_threshold\n sparse_input = scipy.sparse.issparse(matrix)\n dtype = matrix.dtype\n if sparse_input and densify:\n try:\n return matrix.toarray()\n except ValueError:\n logging.warning(\"scipy.sparse does not support the conversion \"\n \"of numpy.float16 matrices to numpy.arrays. See \"\n \"https://git.io/vpXyy\")\n return matrix.astype(numpy.float32).toarray().astype(dtype)\n if not sparse_input and not densify:\n return scipy.sparse.csc_matrix(matrix, dtype=dtype)\n return matrix\n"
] | [
[
"numpy.prod",
"numpy.count_nonzero"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MeteorKepler/laughing-invention | [
"6f856d7ba27f956d8dceb18fe14ba2575beae6aa"
] | [
"ricga/eval_tools/pycocoevalcap/rouge/rouge.py"
] | [
"#!/usr/bin/env python\n# \n# File Name : rouge.py\n#\n# Description : Computes ROUGE-L metric as described by Lin and Hovey (2004)\n#\n# Creation Date : 2015-01-07 06:03\n# Author : Ramakrishna Vedantam <[email protected]>\n\nimport numpy as np\n\n\ndef my_lcs(string, sub):\n \"\"\"\n Calculates longest common subsequence for a pair of tokenized strings\n :param string : list of str : tokens from a string split using whitespace\n :param sub : list of str : shorter string, also split using whitespace\n :returns: length (list of int): length of the longest common subsequence between the two strings\n\n Note: my_lcs only gives length of the longest common subsequence, not the actual LCS\n \"\"\"\n if (len(string) < len(sub)):\n sub, string = string, sub\n\n lengths = [[0 for i in range(0, len(sub) + 1)] for j in range(0, len(string) + 1)]\n\n for j in range(1, len(sub) + 1):\n for i in range(1, len(string) + 1):\n if (string[i - 1] == sub[j - 1]):\n lengths[i][j] = lengths[i - 1][j - 1] + 1\n else:\n lengths[i][j] = max(lengths[i - 1][j], lengths[i][j - 1])\n\n return lengths[len(string)][len(sub)]\n\n\nclass Rouge():\n '''\n Class for computing ROUGE-L score for a set of candidate sentences for the MS COCO test set\n\n '''\n\n def __init__(self):\n # vrama91: updated the value below based on discussion with Hovey\n self.beta = 1.2\n\n def calc_score(self, candidate, refs):\n \"\"\"\n Compute ROUGE-L score given one candidate and references for an image\n :param candidate: str : candidate sentence to be evaluated\n :param refs: list of str : COCO reference sentences for the particular image to be evaluated\n :returns score: int (ROUGE-L score for the candidate evaluated against references)\n \"\"\"\n assert (len(candidate) == 1)\n assert (len(refs) > 0)\n prec = []\n rec = []\n\n # split into tokens\n token_c = candidate[0].split(\" \")\n\n for reference in refs:\n # split into tokens\n token_r = reference.split(\" \")\n # compute the longest common subsequence\n lcs = my_lcs(token_r, token_c)\n prec.append(lcs / float(len(token_c)))\n rec.append(lcs / float(len(token_r)))\n\n prec_max = max(prec)\n rec_max = max(rec)\n\n if (prec_max != 0 and rec_max != 0):\n score = ((1 + self.beta ** 2) * prec_max * rec_max) / float(rec_max + self.beta ** 2 * prec_max)\n else:\n score = 0.0\n return score\n\n def compute_score(self, gts, res):\n \"\"\"\n Computes Rouge-L score given a set of reference and candidate sentences for the dataset\n Invoked by evaluate_captions.py \n :param hypo_for_image: dict : candidate / test sentences with \"image name\" key and \"tokenized sentences\" as values \n :param ref_for_image: dict : reference MS-COCO sentences with \"image name\" key and \"tokenized sentences\" as values\n :returns: average_score: float (mean ROUGE-L score computed by averaging scores for all the images)\n \"\"\"\n assert (gts.keys() == res.keys())\n imgIds = gts.keys()\n\n score = []\n for id in imgIds:\n hypo = res[id]\n ref = gts[id]\n\n score.append(self.calc_score(hypo, ref))\n\n # Sanity check.\n assert (type(hypo) is list)\n assert (len(hypo) == 1)\n assert (type(ref) is list)\n assert (len(ref) > 0)\n\n average_score = np.mean(np.array(score))\n return average_score, np.array(score)\n\n def method(self):\n return \"Rouge\"\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cyberbaker/CSML | [
"c2adad5e796fa12b5afcfafd5fd1b51f642ce730"
] | [
"ex5/polyFeatures.py"
] | [
"import numpy as np\n\ndef polyFeatures(X, p):\n \"\"\"takes a data matrix X (size m x 1) and\n maps each example into its polynomial features where\n X_poly(i, :) = [X(i) X(i).^2 X(i).^3 ... X(i).^p]\n \"\"\"\n# You need to return the following variables correctly.\n X_poly = np.zeros((X.size, p))\n\n# ====================== YOUR CODE HERE ======================\n# Instructions: Given a vector X, return a matrix X_poly where the p-th \n# column of X contains the values of X to the p-th power.\n#\n# \n\n# =========================================================================\n\n return X_poly\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pombredanne/pandas | [
"aa084162bcaa7ce0efdc044bc8077f6bfca70674"
] | [
"pandas/core/indexes/base.py"
] | [
"from datetime import datetime, timedelta\nimport operator\nfrom textwrap import dedent\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import (\n algos as libalgos, index as libindex, join as libjoin, lib)\nfrom pandas._libs.lib import is_datetime_array\nfrom pandas._libs.tslibs import OutOfBoundsDatetime, Timedelta, Timestamp\nfrom pandas._libs.tslibs.timezones import tz_compare\nimport pandas.compat as compat\nfrom pandas.compat import range, set_function_name, u\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import Appender, Substitution, cache_readonly\n\nfrom pandas.core.dtypes.cast import maybe_cast_to_integer_array\nfrom pandas.core.dtypes.common import (\n ensure_categorical, ensure_int64, ensure_object, ensure_platform_int,\n is_bool, is_bool_dtype, is_categorical, is_categorical_dtype,\n is_datetime64_any_dtype, is_datetime64tz_dtype, is_dtype_equal,\n is_dtype_union_equal, is_extension_array_dtype, is_float, is_float_dtype,\n is_hashable, is_integer, is_integer_dtype, is_interval_dtype, is_iterator,\n is_list_like, is_object_dtype, is_period_dtype, is_scalar,\n is_signed_integer_dtype, is_timedelta64_dtype, is_unsigned_integer_dtype,\n pandas_dtype)\nimport pandas.core.dtypes.concat as _concat\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame, ABCDateOffset, ABCDatetimeArray, ABCIndexClass,\n ABCMultiIndex, ABCPandasArray, ABCPeriodIndex, ABCSeries,\n ABCTimedeltaArray, ABCTimedeltaIndex)\nfrom pandas.core.dtypes.missing import array_equivalent, isna\n\nfrom pandas.core import ops\nfrom pandas.core.accessor import CachedAccessor, DirNamesMixin\nimport pandas.core.algorithms as algos\nfrom pandas.core.arrays import ExtensionArray\nfrom pandas.core.base import IndexOpsMixin, PandasObject\nimport pandas.core.common as com\nfrom pandas.core.indexes.frozen import FrozenList\nimport pandas.core.missing as missing\nfrom pandas.core.ops import get_op_result_name, make_invalid_op\nimport pandas.core.sorting as sorting\nfrom pandas.core.strings import StringMethods\n\nfrom pandas.io.formats.printing import (\n default_pprint, format_object_attrs, format_object_summary, pprint_thing)\n\n__all__ = ['Index']\n\n_unsortable_types = frozenset(('mixed', 'mixed-integer'))\n\n_index_doc_kwargs = dict(klass='Index', inplace='',\n target_klass='Index',\n unique='Index', duplicated='np.ndarray')\n_index_shared_docs = dict()\n\n\ndef _try_get_item(x):\n try:\n return x.item()\n except AttributeError:\n return x\n\n\ndef _make_comparison_op(op, cls):\n def cmp_method(self, other):\n if isinstance(other, (np.ndarray, Index, ABCSeries)):\n if other.ndim > 0 and len(self) != len(other):\n raise ValueError('Lengths must match to compare')\n\n if is_object_dtype(self) and not isinstance(self, ABCMultiIndex):\n # don't pass MultiIndex\n with np.errstate(all='ignore'):\n result = ops._comp_method_OBJECT_ARRAY(op, self.values, other)\n\n else:\n\n # numpy will show a DeprecationWarning on invalid elementwise\n # comparisons, this will raise in the future\n with warnings.catch_warnings(record=True):\n warnings.filterwarnings(\"ignore\", \"elementwise\", FutureWarning)\n with np.errstate(all='ignore'):\n result = op(self.values, np.asarray(other))\n\n # technically we could support bool dtyped Index\n # for now just return the indexing array directly\n if is_bool_dtype(result):\n return result\n try:\n return Index(result)\n except TypeError:\n return result\n\n name = '__{name}__'.format(name=op.__name__)\n # TODO: docstring?\n return set_function_name(cmp_method, name, cls)\n\n\ndef _make_arithmetic_op(op, cls):\n def index_arithmetic_method(self, other):\n if isinstance(other, (ABCSeries, ABCDataFrame)):\n return NotImplemented\n elif isinstance(other, ABCTimedeltaIndex):\n # Defer to subclass implementation\n return NotImplemented\n elif (isinstance(other, (np.ndarray, ABCTimedeltaArray)) and\n is_timedelta64_dtype(other)):\n # GH#22390; wrap in Series for op, this will in turn wrap in\n # TimedeltaIndex, but will correctly raise TypeError instead of\n # NullFrequencyError for add/sub ops\n from pandas import Series\n other = Series(other)\n out = op(self, other)\n return Index(out, name=self.name)\n\n other = self._validate_for_numeric_binop(other, op)\n\n # handle time-based others\n if isinstance(other, (ABCDateOffset, np.timedelta64, timedelta)):\n return self._evaluate_with_timedelta_like(other, op)\n elif isinstance(other, (datetime, np.datetime64)):\n return self._evaluate_with_datetime_like(other, op)\n\n values = self.values\n with np.errstate(all='ignore'):\n result = op(values, other)\n\n result = missing.dispatch_missing(op, values, other, result)\n\n attrs = self._get_attributes_dict()\n attrs = self._maybe_update_attributes(attrs)\n if op is divmod:\n result = (Index(result[0], **attrs), Index(result[1], **attrs))\n else:\n result = Index(result, **attrs)\n return result\n\n name = '__{name}__'.format(name=op.__name__)\n # TODO: docstring?\n return set_function_name(index_arithmetic_method, name, cls)\n\n\nclass InvalidIndexError(Exception):\n pass\n\n\n_o_dtype = np.dtype(object)\n_Identity = object\n\n\ndef _new_Index(cls, d):\n \"\"\"\n This is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__.\n \"\"\"\n # required for backward compat, because PI can't be instantiated with\n # ordinals through __new__ GH #13277\n if issubclass(cls, ABCPeriodIndex):\n from pandas.core.indexes.period import _new_PeriodIndex\n return _new_PeriodIndex(cls, **d)\n return cls.__new__(cls, **d)\n\n\nclass Index(IndexOpsMixin, PandasObject):\n \"\"\"\n Immutable ndarray implementing an ordered, sliceable set. The basic object\n storing axis labels for all pandas objects.\n\n Parameters\n ----------\n data : array-like (1-dimensional)\n dtype : NumPy dtype (default: object)\n If dtype is None, we find the dtype that best fits the data.\n If an actual dtype is provided, we coerce to that dtype if it's safe.\n Otherwise, an error will be raised.\n copy : bool\n Make a copy of input ndarray\n name : object\n Name to be stored in the index\n tupleize_cols : bool (default: True)\n When True, attempt to create a MultiIndex if possible\n\n See Also\n ---------\n RangeIndex : Index implementing a monotonic integer range.\n CategoricalIndex : Index of :class:`Categorical` s.\n MultiIndex : A multi-level, or hierarchical, Index.\n IntervalIndex : An Index of :class:`Interval` s.\n DatetimeIndex, TimedeltaIndex, PeriodIndex\n Int64Index, UInt64Index, Float64Index\n\n Notes\n -----\n An Index instance can **only** contain hashable objects\n\n Examples\n --------\n >>> pd.Index([1, 2, 3])\n Int64Index([1, 2, 3], dtype='int64')\n\n >>> pd.Index(list('abc'))\n Index(['a', 'b', 'c'], dtype='object')\n \"\"\"\n # tolist is not actually deprecated, just suppressed in the __dir__\n _deprecations = DirNamesMixin._deprecations | frozenset(['tolist'])\n\n # To hand over control to subclasses\n _join_precedence = 1\n\n # Cython methods; see github.com/cython/cython/issues/2647\n # for why we need to wrap these instead of making them class attributes\n # Moreover, cython will choose the appropriate-dtyped sub-function\n # given the dtypes of the passed arguments\n def _left_indexer_unique(self, left, right):\n return libjoin.left_join_indexer_unique(left, right)\n\n def _left_indexer(self, left, right):\n return libjoin.left_join_indexer(left, right)\n\n def _inner_indexer(self, left, right):\n return libjoin.inner_join_indexer(left, right)\n\n def _outer_indexer(self, left, right):\n return libjoin.outer_join_indexer(left, right)\n\n _typ = 'index'\n _data = None\n _id = None\n name = None\n asi8 = None\n _comparables = ['name']\n _attributes = ['name']\n _is_numeric_dtype = False\n _can_hold_na = True\n\n # would we like our indexing holder to defer to us\n _defer_to_indexing = False\n\n # prioritize current class for _shallow_copy_with_infer,\n # used to infer integers as datetime-likes\n _infer_as_myclass = False\n\n _engine_type = libindex.ObjectEngine\n\n _accessors = {'str'}\n\n str = CachedAccessor(\"str\", StringMethods)\n\n # --------------------------------------------------------------------\n # Constructors\n\n def __new__(cls, data=None, dtype=None, copy=False, name=None,\n fastpath=None, tupleize_cols=True, **kwargs):\n\n if name is None and hasattr(data, 'name'):\n name = data.name\n\n if fastpath is not None:\n warnings.warn(\"The 'fastpath' keyword is deprecated, and will be \"\n \"removed in a future version.\",\n FutureWarning, stacklevel=2)\n if fastpath:\n return cls._simple_new(data, name)\n\n from .range import RangeIndex\n if isinstance(data, ABCPandasArray):\n # ensure users don't accidentally put a PandasArray in an index.\n data = data.to_numpy()\n\n # range\n if isinstance(data, RangeIndex):\n return RangeIndex(start=data, copy=copy, dtype=dtype, name=name)\n elif isinstance(data, range):\n return RangeIndex.from_range(data, copy=copy, dtype=dtype,\n name=name)\n\n # categorical\n elif is_categorical_dtype(data) or is_categorical_dtype(dtype):\n from .category import CategoricalIndex\n return CategoricalIndex(data, dtype=dtype, copy=copy, name=name,\n **kwargs)\n\n # interval\n elif ((is_interval_dtype(data) or is_interval_dtype(dtype)) and\n not is_object_dtype(dtype)):\n from .interval import IntervalIndex\n closed = kwargs.get('closed', None)\n return IntervalIndex(data, dtype=dtype, name=name, copy=copy,\n closed=closed)\n\n elif (is_datetime64_any_dtype(data) or\n (dtype is not None and is_datetime64_any_dtype(dtype)) or\n 'tz' in kwargs):\n from pandas import DatetimeIndex\n\n if dtype is not None and is_dtype_equal(_o_dtype, dtype):\n # GH#23524 passing `dtype=object` to DatetimeIndex is invalid,\n # will raise in the where `data` is already tz-aware. So\n # we leave it out of this step and cast to object-dtype after\n # the DatetimeIndex construction.\n # Note we can pass copy=False because the .astype below\n # will always make a copy\n result = DatetimeIndex(data, copy=False, name=name, **kwargs)\n return result.astype(object)\n else:\n result = DatetimeIndex(data, copy=copy, name=name,\n dtype=dtype, **kwargs)\n return result\n\n elif (is_timedelta64_dtype(data) or\n (dtype is not None and is_timedelta64_dtype(dtype))):\n from pandas import TimedeltaIndex\n if dtype is not None and is_dtype_equal(_o_dtype, dtype):\n # Note we can pass copy=False because the .astype below\n # will always make a copy\n result = TimedeltaIndex(data, copy=False, name=name, **kwargs)\n return result.astype(object)\n else:\n result = TimedeltaIndex(data, copy=copy, name=name,\n dtype=dtype, **kwargs)\n return result\n\n elif is_period_dtype(data) and not is_object_dtype(dtype):\n from pandas import PeriodIndex\n result = PeriodIndex(data, copy=copy, name=name, **kwargs)\n return result\n\n # extension dtype\n elif is_extension_array_dtype(data) or is_extension_array_dtype(dtype):\n data = np.asarray(data)\n if not (dtype is None or is_object_dtype(dtype)):\n\n # coerce to the provided dtype\n data = dtype.construct_array_type()._from_sequence(\n data, dtype=dtype, copy=False)\n\n # coerce to the object dtype\n data = data.astype(object)\n return Index(data, dtype=object, copy=copy, name=name,\n **kwargs)\n\n # index-like\n elif isinstance(data, (np.ndarray, Index, ABCSeries)):\n if dtype is not None:\n try:\n\n # we need to avoid having numpy coerce\n # things that look like ints/floats to ints unless\n # they are actually ints, e.g. '0' and 0.0\n # should not be coerced\n # GH 11836\n if is_integer_dtype(dtype):\n inferred = lib.infer_dtype(data, skipna=False)\n if inferred == 'integer':\n data = maybe_cast_to_integer_array(data, dtype,\n copy=copy)\n elif inferred in ['floating', 'mixed-integer-float']:\n if isna(data).any():\n raise ValueError('cannot convert float '\n 'NaN to integer')\n\n if inferred == \"mixed-integer-float\":\n data = maybe_cast_to_integer_array(data, dtype)\n\n # If we are actually all equal to integers,\n # then coerce to integer.\n try:\n return cls._try_convert_to_int_index(\n data, copy, name, dtype)\n except ValueError:\n pass\n\n # Return an actual float index.\n from .numeric import Float64Index\n return Float64Index(data, copy=copy, dtype=dtype,\n name=name)\n\n elif inferred == 'string':\n pass\n else:\n data = data.astype(dtype)\n elif is_float_dtype(dtype):\n inferred = lib.infer_dtype(data, skipna=False)\n if inferred == 'string':\n pass\n else:\n data = data.astype(dtype)\n else:\n data = np.array(data, dtype=dtype, copy=copy)\n\n except (TypeError, ValueError) as e:\n msg = str(e)\n if (\"cannot convert float\" in msg or\n \"Trying to coerce float values to integer\" in msg):\n raise\n\n # maybe coerce to a sub-class\n from pandas.core.indexes.period import (\n PeriodIndex, IncompatibleFrequency)\n\n if is_signed_integer_dtype(data.dtype):\n from .numeric import Int64Index\n return Int64Index(data, copy=copy, dtype=dtype, name=name)\n elif is_unsigned_integer_dtype(data.dtype):\n from .numeric import UInt64Index\n return UInt64Index(data, copy=copy, dtype=dtype, name=name)\n elif is_float_dtype(data.dtype):\n from .numeric import Float64Index\n return Float64Index(data, copy=copy, dtype=dtype, name=name)\n elif issubclass(data.dtype.type, np.bool) or is_bool_dtype(data):\n subarr = data.astype('object')\n else:\n subarr = com.asarray_tuplesafe(data, dtype=object)\n\n # asarray_tuplesafe does not always copy underlying data,\n # so need to make sure that this happens\n if copy:\n subarr = subarr.copy()\n\n if dtype is None:\n inferred = lib.infer_dtype(subarr, skipna=False)\n if inferred == 'integer':\n try:\n return cls._try_convert_to_int_index(\n subarr, copy, name, dtype)\n except ValueError:\n pass\n\n return Index(subarr, copy=copy,\n dtype=object, name=name)\n elif inferred in ['floating', 'mixed-integer-float']:\n from .numeric import Float64Index\n return Float64Index(subarr, copy=copy, name=name)\n elif inferred == 'interval':\n from .interval import IntervalIndex\n return IntervalIndex(subarr, name=name, copy=copy)\n elif inferred == 'boolean':\n # don't support boolean explicitly ATM\n pass\n elif inferred != 'string':\n if inferred.startswith('datetime'):\n if (lib.is_datetime_with_singletz_array(subarr) or\n 'tz' in kwargs):\n # only when subarr has the same tz\n from pandas import DatetimeIndex\n try:\n return DatetimeIndex(subarr, copy=copy,\n name=name, **kwargs)\n except OutOfBoundsDatetime:\n pass\n\n elif inferred.startswith('timedelta'):\n from pandas import TimedeltaIndex\n return TimedeltaIndex(subarr, copy=copy, name=name,\n **kwargs)\n elif inferred == 'period':\n try:\n return PeriodIndex(subarr, name=name, **kwargs)\n except IncompatibleFrequency:\n pass\n return cls._simple_new(subarr, name)\n\n elif hasattr(data, '__array__'):\n return Index(np.asarray(data), dtype=dtype, copy=copy, name=name,\n **kwargs)\n elif data is None or is_scalar(data):\n cls._scalar_data_error(data)\n else:\n if tupleize_cols and is_list_like(data):\n # GH21470: convert iterable to list before determining if empty\n if is_iterator(data):\n data = list(data)\n\n if data and all(isinstance(e, tuple) for e in data):\n # we must be all tuples, otherwise don't construct\n # 10697\n from .multi import MultiIndex\n return MultiIndex.from_tuples(\n data, names=name or kwargs.get('names'))\n # other iterable of some kind\n subarr = com.asarray_tuplesafe(data, dtype=object)\n return Index(subarr, dtype=dtype, copy=copy, name=name, **kwargs)\n\n \"\"\"\n NOTE for new Index creation:\n\n - _simple_new: It returns new Index with the same type as the caller.\n All metadata (such as name) must be provided by caller's responsibility.\n Using _shallow_copy is recommended because it fills these metadata\n otherwise specified.\n\n - _shallow_copy: It returns new Index with the same type (using\n _simple_new), but fills caller's metadata otherwise specified. Passed\n kwargs will overwrite corresponding metadata.\n\n - _shallow_copy_with_infer: It returns new Index inferring its type\n from passed values. It fills caller's metadata otherwise specified as the\n same as _shallow_copy.\n\n See each method's docstring.\n \"\"\"\n\n @classmethod\n def _simple_new(cls, values, name=None, dtype=None, **kwargs):\n \"\"\"\n We require that we have a dtype compat for the values. If we are passed\n a non-dtype compat, then coerce using the constructor.\n\n Must be careful not to recurse.\n \"\"\"\n if not hasattr(values, 'dtype'):\n if (values is None or not len(values)) and dtype is not None:\n values = np.empty(0, dtype=dtype)\n else:\n values = np.array(values, copy=False)\n if is_object_dtype(values):\n values = cls(values, name=name, dtype=dtype,\n **kwargs)._ndarray_values\n\n if isinstance(values, (ABCSeries, ABCIndexClass)):\n # Index._data must always be an ndarray.\n # This is no-copy for when _values is an ndarray,\n # which should be always at this point.\n values = np.asarray(values._values)\n\n result = object.__new__(cls)\n result._data = values\n # _index_data is a (temporary?) fix to ensure that the direct data\n # manipulation we do in `_libs/reduction.pyx` continues to work.\n # We need access to the actual ndarray, since we're messing with\n # data buffers and strides. We don't re-use `_ndarray_values`, since\n # we actually set this value too.\n result._index_data = values\n result.name = name\n for k, v in compat.iteritems(kwargs):\n setattr(result, k, v)\n return result._reset_identity()\n\n @cache_readonly\n def _constructor(self):\n return type(self)\n\n # --------------------------------------------------------------------\n # Index Internals Methods\n\n def _get_attributes_dict(self):\n \"\"\"\n Return an attributes dict for my class.\n \"\"\"\n return {k: getattr(self, k, None) for k in self._attributes}\n\n _index_shared_docs['_shallow_copy'] = \"\"\"\n Create a new Index with the same class as the caller, don't copy the\n data, use the same object attributes with passed in attributes taking\n precedence.\n\n *this is an internal non-public method*\n\n Parameters\n ----------\n values : the values to create the new Index, optional\n kwargs : updates the default attributes for this Index\n \"\"\"\n\n @Appender(_index_shared_docs['_shallow_copy'])\n def _shallow_copy(self, values=None, **kwargs):\n if values is None:\n values = self.values\n attributes = self._get_attributes_dict()\n attributes.update(kwargs)\n if not len(values) and 'dtype' not in kwargs:\n attributes['dtype'] = self.dtype\n\n # _simple_new expects an the type of self._data\n values = getattr(values, '_values', values)\n if isinstance(values, ABCDatetimeArray):\n # `self.values` returns `self` for tz-aware, so we need to unwrap\n # more specifically\n values = values.asi8\n\n return self._simple_new(values, **attributes)\n\n def _shallow_copy_with_infer(self, values, **kwargs):\n \"\"\"\n Create a new Index inferring the class with passed value, don't copy\n the data, use the same object attributes with passed in attributes\n taking precedence.\n\n *this is an internal non-public method*\n\n Parameters\n ----------\n values : the values to create the new Index, optional\n kwargs : updates the default attributes for this Index\n \"\"\"\n attributes = self._get_attributes_dict()\n attributes.update(kwargs)\n attributes['copy'] = False\n if not len(values) and 'dtype' not in kwargs:\n attributes['dtype'] = self.dtype\n if self._infer_as_myclass:\n try:\n return self._constructor(values, **attributes)\n except (TypeError, ValueError):\n pass\n return Index(values, **attributes)\n\n def _update_inplace(self, result, **kwargs):\n # guard when called from IndexOpsMixin\n raise TypeError(\"Index can't be updated inplace\")\n\n def is_(self, other):\n \"\"\"\n More flexible, faster check like ``is`` but that works through views.\n\n Note: this is *not* the same as ``Index.identical()``, which checks\n that metadata is also the same.\n\n Parameters\n ----------\n other : object\n other object to compare against.\n\n Returns\n -------\n True if both have same underlying data, False otherwise : bool\n \"\"\"\n # use something other than None to be clearer\n return self._id is getattr(\n other, '_id', Ellipsis) and self._id is not None\n\n def _reset_identity(self):\n \"\"\"\n Initializes or resets ``_id`` attribute with new object.\n \"\"\"\n self._id = _Identity()\n return self\n\n def _cleanup(self):\n self._engine.clear_mapping()\n\n @cache_readonly\n def _engine(self):\n # property, for now, slow to look up\n return self._engine_type(lambda: self._ndarray_values, len(self))\n\n # --------------------------------------------------------------------\n # Array-Like Methods\n\n # ndarray compat\n def __len__(self):\n \"\"\"\n Return the length of the Index.\n \"\"\"\n return len(self._data)\n\n def __array__(self, dtype=None):\n \"\"\"\n The array interface, return my values.\n \"\"\"\n return np.asarray(self._data, dtype=dtype)\n\n def __array_wrap__(self, result, context=None):\n \"\"\"\n Gets called after a ufunc.\n \"\"\"\n result = lib.item_from_zerodim(result)\n if is_bool_dtype(result) or lib.is_scalar(result):\n return result\n\n attrs = self._get_attributes_dict()\n attrs = self._maybe_update_attributes(attrs)\n return Index(result, **attrs)\n\n @cache_readonly\n def dtype(self):\n \"\"\"\n Return the dtype object of the underlying data.\n \"\"\"\n return self._data.dtype\n\n @cache_readonly\n def dtype_str(self):\n \"\"\"\n Return the dtype str of the underlying data.\n \"\"\"\n return str(self.dtype)\n\n def ravel(self, order='C'):\n \"\"\"\n Return an ndarray of the flattened values of the underlying data.\n\n See Also\n --------\n numpy.ndarray.ravel\n \"\"\"\n return self._ndarray_values.ravel(order=order)\n\n def view(self, cls=None):\n\n # we need to see if we are subclassing an\n # index type here\n if cls is not None and not hasattr(cls, '_typ'):\n result = self._data.view(cls)\n else:\n result = self._shallow_copy()\n if isinstance(result, Index):\n result._id = self._id\n return result\n\n _index_shared_docs['astype'] = \"\"\"\n Create an Index with values cast to dtypes. The class of a new Index\n is determined by dtype. When conversion is impossible, a ValueError\n exception is raised.\n\n Parameters\n ----------\n dtype : numpy dtype or pandas type\n Note that any signed integer `dtype` is treated as ``'int64'``,\n and any unsigned integer `dtype` is treated as ``'uint64'``,\n regardless of the size.\n copy : bool, default True\n By default, astype always returns a newly allocated object.\n If copy is set to False and internal requirements on dtype are\n satisfied, the original data is used to create a new Index\n or the original Index is returned.\n\n .. versionadded:: 0.19.0\n \"\"\"\n\n @Appender(_index_shared_docs['astype'])\n def astype(self, dtype, copy=True):\n if is_dtype_equal(self.dtype, dtype):\n return self.copy() if copy else self\n\n elif is_categorical_dtype(dtype):\n from .category import CategoricalIndex\n return CategoricalIndex(self.values, name=self.name, dtype=dtype,\n copy=copy)\n elif is_datetime64tz_dtype(dtype):\n # TODO(GH-24559): Remove this block, use the following elif.\n # avoid FutureWarning from DatetimeIndex constructor.\n from pandas import DatetimeIndex\n tz = pandas_dtype(dtype).tz\n return (DatetimeIndex(np.asarray(self))\n .tz_localize(\"UTC\").tz_convert(tz))\n\n elif is_extension_array_dtype(dtype):\n return Index(np.asarray(self), dtype=dtype, copy=copy)\n\n try:\n if is_datetime64tz_dtype(dtype):\n from pandas import DatetimeIndex\n return DatetimeIndex(self.values, name=self.name, dtype=dtype,\n copy=copy)\n return Index(self.values.astype(dtype, copy=copy), name=self.name,\n dtype=dtype)\n except (TypeError, ValueError):\n msg = 'Cannot cast {name} to dtype {dtype}'\n raise TypeError(msg.format(name=type(self).__name__, dtype=dtype))\n\n _index_shared_docs['take'] = \"\"\"\n Return a new %(klass)s of the values selected by the indices.\n\n For internal compatibility with numpy arrays.\n\n Parameters\n ----------\n indices : list\n Indices to be taken\n axis : int, optional\n The axis over which to select values, always 0.\n allow_fill : bool, default True\n fill_value : bool, default None\n If allow_fill=True and fill_value is not None, indices specified by\n -1 is regarded as NA. If Index doesn't hold NA, raise ValueError\n\n See Also\n --------\n numpy.ndarray.take\n \"\"\"\n\n @Appender(_index_shared_docs['take'] % _index_doc_kwargs)\n def take(self, indices, axis=0, allow_fill=True,\n fill_value=None, **kwargs):\n if kwargs:\n nv.validate_take(tuple(), kwargs)\n indices = ensure_platform_int(indices)\n if self._can_hold_na:\n taken = self._assert_take_fillable(self.values, indices,\n allow_fill=allow_fill,\n fill_value=fill_value,\n na_value=self._na_value)\n else:\n if allow_fill and fill_value is not None:\n msg = 'Unable to fill values because {0} cannot contain NA'\n raise ValueError(msg.format(self.__class__.__name__))\n taken = self.values.take(indices)\n return self._shallow_copy(taken)\n\n def _assert_take_fillable(self, values, indices, allow_fill=True,\n fill_value=None, na_value=np.nan):\n \"\"\"\n Internal method to handle NA filling of take.\n \"\"\"\n indices = ensure_platform_int(indices)\n\n # only fill if we are passing a non-None fill_value\n if allow_fill and fill_value is not None:\n if (indices < -1).any():\n msg = ('When allow_fill=True and fill_value is not None, '\n 'all indices must be >= -1')\n raise ValueError(msg)\n taken = algos.take(values,\n indices,\n allow_fill=allow_fill,\n fill_value=na_value)\n else:\n taken = values.take(indices)\n return taken\n\n _index_shared_docs['repeat'] = \"\"\"\n Repeat elements of a %(klass)s.\n\n Returns a new %(klass)s where each element of the current %(klass)s\n is repeated consecutively a given number of times.\n\n Parameters\n ----------\n repeats : int or array of ints\n The number of repetitions for each element. This should be a\n non-negative integer. Repeating 0 times will return an empty\n %(klass)s.\n axis : None\n Must be ``None``. Has no effect but is accepted for compatibility\n with numpy.\n\n Returns\n -------\n repeated_index : %(klass)s\n Newly created %(klass)s with repeated elements.\n\n See Also\n --------\n Series.repeat : Equivalent function for Series.\n numpy.repeat : Similar method for :class:`numpy.ndarray`.\n\n Examples\n --------\n >>> idx = pd.Index(['a', 'b', 'c'])\n >>> idx\n Index(['a', 'b', 'c'], dtype='object')\n >>> idx.repeat(2)\n Index(['a', 'a', 'b', 'b', 'c', 'c'], dtype='object')\n >>> idx.repeat([1, 2, 3])\n Index(['a', 'b', 'b', 'c', 'c', 'c'], dtype='object')\n \"\"\"\n\n @Appender(_index_shared_docs['repeat'] % _index_doc_kwargs)\n def repeat(self, repeats, axis=None):\n nv.validate_repeat(tuple(), dict(axis=axis))\n return self._shallow_copy(self._values.repeat(repeats))\n\n # --------------------------------------------------------------------\n # Copying Methods\n\n _index_shared_docs['copy'] = \"\"\"\n Make a copy of this object. Name and dtype sets those attributes on\n the new object.\n\n Parameters\n ----------\n name : string, optional\n deep : boolean, default False\n dtype : numpy dtype or pandas type\n\n Returns\n -------\n copy : Index\n\n Notes\n -----\n In most cases, there should be no functional difference from using\n ``deep``, but if ``deep`` is passed it will attempt to deepcopy.\n \"\"\"\n\n @Appender(_index_shared_docs['copy'])\n def copy(self, name=None, deep=False, dtype=None, **kwargs):\n if deep:\n new_index = self._shallow_copy(self._data.copy())\n else:\n new_index = self._shallow_copy()\n\n names = kwargs.get('names')\n names = self._validate_names(name=name, names=names, deep=deep)\n new_index = new_index.set_names(names)\n\n if dtype:\n new_index = new_index.astype(dtype)\n return new_index\n\n def __copy__(self, **kwargs):\n return self.copy(**kwargs)\n\n def __deepcopy__(self, memo=None):\n \"\"\"\n Parameters\n ----------\n memo, default None\n Standard signature. Unused\n \"\"\"\n if memo is None:\n memo = {}\n return self.copy(deep=True)\n\n # --------------------------------------------------------------------\n # Rendering Methods\n\n def __unicode__(self):\n \"\"\"\n Return a string representation for this object.\n\n Invoked by unicode(df) in py2 only. Yields a Unicode String in both\n py2/py3.\n \"\"\"\n klass = self.__class__.__name__\n data = self._format_data()\n attrs = self._format_attrs()\n space = self._format_space()\n\n prepr = (u(\",%s\") %\n space).join(u(\"%s=%s\") % (k, v) for k, v in attrs)\n\n # no data provided, just attributes\n if data is None:\n data = ''\n\n res = u(\"%s(%s%s)\") % (klass, data, prepr)\n\n return res\n\n def _format_space(self):\n\n # using space here controls if the attributes\n # are line separated or not (the default)\n\n # max_seq_items = get_option('display.max_seq_items')\n # if len(self) > max_seq_items:\n # space = \"\\n%s\" % (' ' * (len(klass) + 1))\n return \" \"\n\n @property\n def _formatter_func(self):\n \"\"\"\n Return the formatter function.\n \"\"\"\n return default_pprint\n\n def _format_data(self, name=None):\n \"\"\"\n Return the formatted data as a unicode string.\n \"\"\"\n\n # do we want to justify (only do so for non-objects)\n is_justify = not (self.inferred_type in ('string', 'unicode') or\n (self.inferred_type == 'categorical' and\n is_object_dtype(self.categories)))\n\n return format_object_summary(self, self._formatter_func,\n is_justify=is_justify, name=name)\n\n def _format_attrs(self):\n \"\"\"\n Return a list of tuples of the (attr,formatted_value).\n \"\"\"\n return format_object_attrs(self)\n\n def _mpl_repr(self):\n # how to represent ourselves to matplotlib\n return self.values\n\n def format(self, name=False, formatter=None, **kwargs):\n \"\"\"\n Render a string representation of the Index.\n \"\"\"\n header = []\n if name:\n header.append(pprint_thing(self.name,\n escape_chars=('\\t', '\\r', '\\n')) if\n self.name is not None else '')\n\n if formatter is not None:\n return header + list(self.map(formatter))\n\n return self._format_with_header(header, **kwargs)\n\n def _format_with_header(self, header, na_rep='NaN', **kwargs):\n values = self.values\n\n from pandas.io.formats.format import format_array\n\n if is_categorical_dtype(values.dtype):\n values = np.array(values)\n\n elif is_object_dtype(values.dtype):\n values = lib.maybe_convert_objects(values, safe=1)\n\n if is_object_dtype(values.dtype):\n result = [pprint_thing(x, escape_chars=('\\t', '\\r', '\\n'))\n for x in values]\n\n # could have nans\n mask = isna(values)\n if mask.any():\n result = np.array(result)\n result[mask] = na_rep\n result = result.tolist()\n\n else:\n result = _trim_front(format_array(values, None, justify='left'))\n return header + result\n\n def to_native_types(self, slicer=None, **kwargs):\n \"\"\"\n Format specified values of `self` and return them.\n\n Parameters\n ----------\n slicer : int, array-like\n An indexer into `self` that specifies which values\n are used in the formatting process.\n kwargs : dict\n Options for specifying how the values should be formatted.\n These options include the following:\n\n 1) na_rep : str\n The value that serves as a placeholder for NULL values\n 2) quoting : bool or None\n Whether or not there are quoted values in `self`\n 3) date_format : str\n The format used to represent date-like values\n \"\"\"\n\n values = self\n if slicer is not None:\n values = values[slicer]\n return values._format_native_types(**kwargs)\n\n def _format_native_types(self, na_rep='', quoting=None, **kwargs):\n \"\"\"\n Actually format specific types of the index.\n \"\"\"\n mask = isna(self)\n if not self.is_object() and not quoting:\n values = np.asarray(self).astype(str)\n else:\n values = np.array(self, dtype=object, copy=True)\n\n values[mask] = na_rep\n return values\n\n def _summary(self, name=None):\n \"\"\"\n Return a summarized representation.\n\n Parameters\n ----------\n name : str\n name to use in the summary representation\n\n Returns\n -------\n String with a summarized representation of the index\n \"\"\"\n if len(self) > 0:\n head = self[0]\n if (hasattr(head, 'format') and\n not isinstance(head, compat.string_types)):\n head = head.format()\n tail = self[-1]\n if (hasattr(tail, 'format') and\n not isinstance(tail, compat.string_types)):\n tail = tail.format()\n index_summary = ', %s to %s' % (pprint_thing(head),\n pprint_thing(tail))\n else:\n index_summary = ''\n\n if name is None:\n name = type(self).__name__\n return '%s: %s entries%s' % (name, len(self), index_summary)\n\n def summary(self, name=None):\n \"\"\"\n Return a summarized representation.\n\n .. deprecated:: 0.23.0\n \"\"\"\n warnings.warn(\"'summary' is deprecated and will be removed in a \"\n \"future version.\", FutureWarning, stacklevel=2)\n return self._summary(name)\n\n # --------------------------------------------------------------------\n # Conversion Methods\n\n def to_flat_index(self):\n \"\"\"\n Identity method.\n\n .. versionadded:: 0.24.0\n\n This is implemented for compatability with subclass implementations\n when chaining.\n\n Returns\n -------\n pd.Index\n Caller.\n\n See Also\n --------\n MultiIndex.to_flat_index : Subclass implementation.\n \"\"\"\n return self\n\n def to_series(self, index=None, name=None):\n \"\"\"\n Create a Series with both index and values equal to the index keys\n useful with map for returning an indexer based on an index.\n\n Parameters\n ----------\n index : Index, optional\n index of resulting Series. If None, defaults to original index\n name : string, optional\n name of resulting Series. If None, defaults to name of original\n index\n\n Returns\n -------\n Series : dtype will be based on the type of the Index values.\n \"\"\"\n\n from pandas import Series\n\n if index is None:\n index = self._shallow_copy()\n if name is None:\n name = self.name\n\n return Series(self.values.copy(), index=index, name=name)\n\n def to_frame(self, index=True, name=None):\n \"\"\"\n Create a DataFrame with a column containing the Index.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n index : boolean, default True\n Set the index of the returned DataFrame as the original Index.\n\n name : object, default None\n The passed name should substitute for the index name (if it has\n one).\n\n Returns\n -------\n DataFrame\n DataFrame containing the original Index data.\n\n See Also\n --------\n Index.to_series : Convert an Index to a Series.\n Series.to_frame : Convert Series to DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')\n >>> idx.to_frame()\n animal\n animal\n Ant Ant\n Bear Bear\n Cow Cow\n\n By default, the original Index is reused. To enforce a new Index:\n\n >>> idx.to_frame(index=False)\n animal\n 0 Ant\n 1 Bear\n 2 Cow\n\n To override the name of the resulting column, specify `name`:\n\n >>> idx.to_frame(index=False, name='zoo')\n zoo\n 0 Ant\n 1 Bear\n 2 Cow\n \"\"\"\n\n from pandas import DataFrame\n if name is None:\n name = self.name or 0\n result = DataFrame({name: self.values.copy()})\n\n if index:\n result.index = self\n return result\n\n # --------------------------------------------------------------------\n # Name-Centric Methods\n\n def _validate_names(self, name=None, names=None, deep=False):\n \"\"\"\n Handles the quirks of having a singular 'name' parameter for general\n Index and plural 'names' parameter for MultiIndex.\n \"\"\"\n from copy import deepcopy\n if names is not None and name is not None:\n raise TypeError(\"Can only provide one of `names` and `name`\")\n elif names is None and name is None:\n return deepcopy(self.names) if deep else self.names\n elif names is not None:\n if not is_list_like(names):\n raise TypeError(\"Must pass list-like as `names`.\")\n return names\n else:\n if not is_list_like(name):\n return [name]\n return name\n\n def _get_names(self):\n return FrozenList((self.name, ))\n\n def _set_names(self, values, level=None):\n \"\"\"\n Set new names on index. Each name has to be a hashable type.\n\n Parameters\n ----------\n values : str or sequence\n name(s) to set\n level : int, level name, or sequence of int/level names (default None)\n If the index is a MultiIndex (hierarchical), level(s) to set (None\n for all levels). Otherwise level must be None\n\n Raises\n ------\n TypeError if each name is not hashable.\n \"\"\"\n if not is_list_like(values):\n raise ValueError('Names must be a list-like')\n if len(values) != 1:\n raise ValueError('Length of new names must be 1, got %d' %\n len(values))\n\n # GH 20527\n # All items in 'name' need to be hashable:\n for name in values:\n if not is_hashable(name):\n raise TypeError('{}.name must be a hashable type'\n .format(self.__class__.__name__))\n self.name = values[0]\n\n names = property(fset=_set_names, fget=_get_names)\n\n def set_names(self, names, level=None, inplace=False):\n \"\"\"\n Set Index or MultiIndex name.\n\n Able to set new names partially and by level.\n\n Parameters\n ----------\n names : label or list of label\n Name(s) to set.\n level : int, label or list of int or label, optional\n If the index is a MultiIndex, level(s) to set (None for all\n levels). Otherwise level must be None.\n inplace : bool, default False\n Modifies the object directly, instead of creating a new Index or\n MultiIndex.\n\n Returns\n -------\n Index\n The same type as the caller or None if inplace is True.\n\n See Also\n --------\n Index.rename : Able to set new names without level.\n\n Examples\n --------\n >>> idx = pd.Index([1, 2, 3, 4])\n >>> idx\n Int64Index([1, 2, 3, 4], dtype='int64')\n >>> idx.set_names('quarter')\n Int64Index([1, 2, 3, 4], dtype='int64', name='quarter')\n\n >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],\n ... [2018, 2019]])\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]])\n >>> idx.set_names(['kind', 'year'], inplace=True)\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['kind', 'year'])\n >>> idx.set_names('species', level=0)\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['species', 'year'])\n \"\"\"\n\n if level is not None and not isinstance(self, ABCMultiIndex):\n raise ValueError('Level must be None for non-MultiIndex')\n\n if level is not None and not is_list_like(level) and is_list_like(\n names):\n msg = \"Names must be a string when a single level is provided.\"\n raise TypeError(msg)\n\n if not is_list_like(names) and level is None and self.nlevels > 1:\n raise TypeError(\"Must pass list-like as `names`.\")\n\n if not is_list_like(names):\n names = [names]\n if level is not None and not is_list_like(level):\n level = [level]\n\n if inplace:\n idx = self\n else:\n idx = self._shallow_copy()\n idx._set_names(names, level=level)\n if not inplace:\n return idx\n\n def rename(self, name, inplace=False):\n \"\"\"\n Alter Index or MultiIndex name.\n\n Able to set new names without level. Defaults to returning new index.\n Length of names must match number of levels in MultiIndex.\n\n Parameters\n ----------\n name : label or list of labels\n Name(s) to set.\n inplace : boolean, default False\n Modifies the object directly, instead of creating a new Index or\n MultiIndex.\n\n Returns\n -------\n Index\n The same type as the caller or None if inplace is True.\n\n See Also\n --------\n Index.set_names : Able to set new names partially and by level.\n\n Examples\n --------\n >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score')\n >>> idx.rename('grade')\n Index(['A', 'C', 'A', 'B'], dtype='object', name='grade')\n\n >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],\n ... [2018, 2019]],\n ... names=['kind', 'year'])\n >>> idx\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['kind', 'year'])\n >>> idx.rename(['species', 'year'])\n MultiIndex(levels=[['cobra', 'python'], [2018, 2019]],\n codes=[[1, 1, 0, 0], [0, 1, 0, 1]],\n names=['species', 'year'])\n >>> idx.rename('species')\n Traceback (most recent call last):\n TypeError: Must pass list-like as `names`.\n \"\"\"\n return self.set_names([name], inplace=inplace)\n\n # --------------------------------------------------------------------\n # Level-Centric Methods\n\n @property\n def nlevels(self):\n return 1\n\n def _sort_levels_monotonic(self):\n \"\"\"\n Compat with MultiIndex.\n \"\"\"\n return self\n\n def _validate_index_level(self, level):\n \"\"\"\n Validate index level.\n\n For single-level Index getting level number is a no-op, but some\n verification must be done like in MultiIndex.\n\n \"\"\"\n if isinstance(level, int):\n if level < 0 and level != -1:\n raise IndexError(\"Too many levels: Index has only 1 level,\"\n \" %d is not a valid level number\" % (level, ))\n elif level > 0:\n raise IndexError(\"Too many levels:\"\n \" Index has only 1 level, not %d\" %\n (level + 1))\n elif level != self.name:\n raise KeyError('Level %s must be same as name (%s)' %\n (level, self.name))\n\n def _get_level_number(self, level):\n self._validate_index_level(level)\n return 0\n\n def sortlevel(self, level=None, ascending=True, sort_remaining=None):\n \"\"\"\n For internal compatibility with with the Index API.\n\n Sort the Index. This is for compat with MultiIndex\n\n Parameters\n ----------\n ascending : boolean, default True\n False to sort in descending order\n\n level, sort_remaining are compat parameters\n\n Returns\n -------\n sorted_index : Index\n \"\"\"\n return self.sort_values(return_indexer=True, ascending=ascending)\n\n def _get_level_values(self, level):\n \"\"\"\n Return an Index of values for requested level.\n\n This is primarily useful to get an individual level of values from a\n MultiIndex, but is provided on Index as well for compatability.\n\n Parameters\n ----------\n level : int or str\n It is either the integer position or the name of the level.\n\n Returns\n -------\n values : Index\n Calling object, as there is only one level in the Index.\n\n See Also\n --------\n MultiIndex.get_level_values : Get values for a level of a MultiIndex.\n\n Notes\n -----\n For Index, level should be 0, since there are no multiple levels.\n\n Examples\n --------\n\n >>> idx = pd.Index(list('abc'))\n >>> idx\n Index(['a', 'b', 'c'], dtype='object')\n\n Get level values by supplying `level` as integer:\n\n >>> idx.get_level_values(0)\n Index(['a', 'b', 'c'], dtype='object')\n \"\"\"\n self._validate_index_level(level)\n return self\n\n get_level_values = _get_level_values\n\n def droplevel(self, level=0):\n \"\"\"\n Return index with requested level(s) removed.\n\n If resulting index has only 1 level left, the result will be\n of Index type, not MultiIndex.\n\n .. versionadded:: 0.23.1 (support for non-MultiIndex)\n\n Parameters\n ----------\n level : int, str, or list-like, default 0\n If a string is given, must be the name of a level\n If list-like, elements must be names or indexes of levels.\n\n Returns\n -------\n index : Index or MultiIndex\n \"\"\"\n if not isinstance(level, (tuple, list)):\n level = [level]\n\n levnums = sorted(self._get_level_number(lev) for lev in level)[::-1]\n\n if len(level) == 0:\n return self\n if len(level) >= self.nlevels:\n raise ValueError(\"Cannot remove {} levels from an index with {} \"\n \"levels: at least one level must be \"\n \"left.\".format(len(level), self.nlevels))\n # The two checks above guarantee that here self is a MultiIndex\n\n new_levels = list(self.levels)\n new_codes = list(self.codes)\n new_names = list(self.names)\n\n for i in levnums:\n new_levels.pop(i)\n new_codes.pop(i)\n new_names.pop(i)\n\n if len(new_levels) == 1:\n\n # set nan if needed\n mask = new_codes[0] == -1\n result = new_levels[0].take(new_codes[0])\n if mask.any():\n result = result.putmask(mask, np.nan)\n\n result.name = new_names[0]\n return result\n else:\n from .multi import MultiIndex\n return MultiIndex(levels=new_levels, codes=new_codes,\n names=new_names, verify_integrity=False)\n\n _index_shared_docs['_get_grouper_for_level'] = \"\"\"\n Get index grouper corresponding to an index level\n\n Parameters\n ----------\n mapper: Group mapping function or None\n Function mapping index values to groups\n level : int or None\n Index level\n\n Returns\n -------\n grouper : Index\n Index of values to group on\n labels : ndarray of int or None\n Array of locations in level_index\n uniques : Index or None\n Index of unique values for level\n \"\"\"\n\n @Appender(_index_shared_docs['_get_grouper_for_level'])\n def _get_grouper_for_level(self, mapper, level=None):\n assert level is None or level == 0\n if mapper is None:\n grouper = self\n else:\n grouper = self.map(mapper)\n\n return grouper, None, None\n\n # --------------------------------------------------------------------\n # Introspection Methods\n\n @property\n def is_monotonic(self):\n \"\"\"\n Alias for is_monotonic_increasing.\n \"\"\"\n return self.is_monotonic_increasing\n\n @property\n def is_monotonic_increasing(self):\n \"\"\"\n Return if the index is monotonic increasing (only equal or\n increasing) values.\n\n Examples\n --------\n >>> Index([1, 2, 3]).is_monotonic_increasing\n True\n >>> Index([1, 2, 2]).is_monotonic_increasing\n True\n >>> Index([1, 3, 2]).is_monotonic_increasing\n False\n \"\"\"\n return self._engine.is_monotonic_increasing\n\n @property\n def is_monotonic_decreasing(self):\n \"\"\"\n Return if the index is monotonic decreasing (only equal or\n decreasing) values.\n\n Examples\n --------\n >>> Index([3, 2, 1]).is_monotonic_decreasing\n True\n >>> Index([3, 2, 2]).is_monotonic_decreasing\n True\n >>> Index([3, 1, 2]).is_monotonic_decreasing\n False\n \"\"\"\n return self._engine.is_monotonic_decreasing\n\n @property\n def _is_strictly_monotonic_increasing(self):\n \"\"\"\n Return if the index is strictly monotonic increasing\n (only increasing) values.\n\n Examples\n --------\n >>> Index([1, 2, 3])._is_strictly_monotonic_increasing\n True\n >>> Index([1, 2, 2])._is_strictly_monotonic_increasing\n False\n >>> Index([1, 3, 2])._is_strictly_monotonic_increasing\n False\n \"\"\"\n return self.is_unique and self.is_monotonic_increasing\n\n @property\n def _is_strictly_monotonic_decreasing(self):\n \"\"\"\n Return if the index is strictly monotonic decreasing\n (only decreasing) values.\n\n Examples\n --------\n >>> Index([3, 2, 1])._is_strictly_monotonic_decreasing\n True\n >>> Index([3, 2, 2])._is_strictly_monotonic_decreasing\n False\n >>> Index([3, 1, 2])._is_strictly_monotonic_decreasing\n False\n \"\"\"\n return self.is_unique and self.is_monotonic_decreasing\n\n def is_lexsorted_for_tuple(self, tup):\n return True\n\n @cache_readonly\n def is_unique(self):\n \"\"\"\n Return if the index has unique values.\n \"\"\"\n return self._engine.is_unique\n\n @property\n def has_duplicates(self):\n return not self.is_unique\n\n def is_boolean(self):\n return self.inferred_type in ['boolean']\n\n def is_integer(self):\n return self.inferred_type in ['integer']\n\n def is_floating(self):\n return self.inferred_type in ['floating', 'mixed-integer-float']\n\n def is_numeric(self):\n return self.inferred_type in ['integer', 'floating']\n\n def is_object(self):\n return is_object_dtype(self.dtype)\n\n def is_categorical(self):\n \"\"\"\n Check if the Index holds categorical data.\n\n Returns\n -------\n boolean\n True if the Index is categorical.\n\n See Also\n --------\n CategoricalIndex : Index for categorical data.\n\n Examples\n --------\n >>> idx = pd.Index([\"Watermelon\", \"Orange\", \"Apple\",\n ... \"Watermelon\"]).astype(\"category\")\n >>> idx.is_categorical()\n True\n\n >>> idx = pd.Index([1, 3, 5, 7])\n >>> idx.is_categorical()\n False\n\n >>> s = pd.Series([\"Peter\", \"Victor\", \"Elisabeth\", \"Mar\"])\n >>> s\n 0 Peter\n 1 Victor\n 2 Elisabeth\n 3 Mar\n dtype: object\n >>> s.index.is_categorical()\n False\n \"\"\"\n return self.inferred_type in ['categorical']\n\n def is_interval(self):\n return self.inferred_type in ['interval']\n\n def is_mixed(self):\n return self.inferred_type in ['mixed']\n\n def holds_integer(self):\n return self.inferred_type in ['integer', 'mixed-integer']\n\n @cache_readonly\n def inferred_type(self):\n \"\"\"\n Return a string of the type inferred from the values.\n \"\"\"\n return lib.infer_dtype(self, skipna=False)\n\n @cache_readonly\n def is_all_dates(self):\n if self._data is None:\n return False\n return is_datetime_array(ensure_object(self.values))\n\n # --------------------------------------------------------------------\n # Pickle Methods\n\n def __reduce__(self):\n d = dict(data=self._data)\n d.update(self._get_attributes_dict())\n return _new_Index, (self.__class__, d), None\n\n def __setstate__(self, state):\n \"\"\"\n Necessary for making this object picklable.\n \"\"\"\n\n if isinstance(state, dict):\n self._data = state.pop('data')\n for k, v in compat.iteritems(state):\n setattr(self, k, v)\n\n elif isinstance(state, tuple):\n\n if len(state) == 2:\n nd_state, own_state = state\n data = np.empty(nd_state[1], dtype=nd_state[2])\n np.ndarray.__setstate__(data, nd_state)\n self.name = own_state[0]\n\n else: # pragma: no cover\n data = np.empty(state)\n np.ndarray.__setstate__(data, state)\n\n self._data = data\n self._reset_identity()\n else:\n raise Exception(\"invalid pickle state\")\n\n _unpickle_compat = __setstate__\n\n # --------------------------------------------------------------------\n # Null Handling Methods\n\n _na_value = np.nan\n \"\"\"The expected NA value to use with this index.\"\"\"\n\n @cache_readonly\n def _isnan(self):\n \"\"\"\n Return if each value is NaN.\n \"\"\"\n if self._can_hold_na:\n return isna(self)\n else:\n # shouldn't reach to this condition by checking hasnans beforehand\n values = np.empty(len(self), dtype=np.bool_)\n values.fill(False)\n return values\n\n @cache_readonly\n def _nan_idxs(self):\n if self._can_hold_na:\n w, = self._isnan.nonzero()\n return w\n else:\n return np.array([], dtype=np.int64)\n\n @cache_readonly\n def hasnans(self):\n \"\"\"\n Return if I have any nans; enables various perf speedups.\n \"\"\"\n if self._can_hold_na:\n return bool(self._isnan.any())\n else:\n return False\n\n def isna(self):\n \"\"\"\n Detect missing values.\n\n Return a boolean same-sized object indicating if the values are NA.\n NA values, such as ``None``, :attr:`numpy.NaN` or :attr:`pd.NaT`, get\n mapped to ``True`` values.\n Everything else get mapped to ``False`` values. Characters such as\n empty strings `''` or :attr:`numpy.inf` are not considered NA values\n (unless you set ``pandas.options.mode.use_inf_as_na = True``).\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n numpy.ndarray\n A boolean array of whether my values are NA.\n\n See Also\n --------\n Index.notna : Boolean inverse of isna.\n Index.dropna : Omit entries with missing values.\n isna : Top-level isna.\n Series.isna : Detect missing values in Series object.\n\n Examples\n --------\n Show which entries in a pandas.Index are NA. The result is an\n array.\n\n >>> idx = pd.Index([5.2, 6.0, np.NaN])\n >>> idx\n Float64Index([5.2, 6.0, nan], dtype='float64')\n >>> idx.isna()\n array([False, False, True], dtype=bool)\n\n Empty strings are not considered NA values. None is considered an NA\n value.\n\n >>> idx = pd.Index(['black', '', 'red', None])\n >>> idx\n Index(['black', '', 'red', None], dtype='object')\n >>> idx.isna()\n array([False, False, False, True], dtype=bool)\n\n For datetimes, `NaT` (Not a Time) is considered as an NA value.\n\n >>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'),\n ... pd.Timestamp(''), None, pd.NaT])\n >>> idx\n DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'],\n dtype='datetime64[ns]', freq=None)\n >>> idx.isna()\n array([False, True, True, True], dtype=bool)\n \"\"\"\n return self._isnan\n isnull = isna\n\n def notna(self):\n \"\"\"\n Detect existing (non-missing) values.\n\n Return a boolean same-sized object indicating if the values are not NA.\n Non-missing values get mapped to ``True``. Characters such as empty\n strings ``''`` or :attr:`numpy.inf` are not considered NA values\n (unless you set ``pandas.options.mode.use_inf_as_na = True``).\n NA values, such as None or :attr:`numpy.NaN`, get mapped to ``False``\n values.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n numpy.ndarray\n Boolean array to indicate which entries are not NA.\n\n See Also\n --------\n Index.notnull : Alias of notna.\n Index.isna: Inverse of notna.\n notna : Top-level notna.\n\n Examples\n --------\n Show which entries in an Index are not NA. The result is an\n array.\n\n >>> idx = pd.Index([5.2, 6.0, np.NaN])\n >>> idx\n Float64Index([5.2, 6.0, nan], dtype='float64')\n >>> idx.notna()\n array([ True, True, False])\n\n Empty strings are not considered NA values. None is considered a NA\n value.\n\n >>> idx = pd.Index(['black', '', 'red', None])\n >>> idx\n Index(['black', '', 'red', None], dtype='object')\n >>> idx.notna()\n array([ True, True, True, False])\n \"\"\"\n return ~self.isna()\n notnull = notna\n\n _index_shared_docs['fillna'] = \"\"\"\n Fill NA/NaN values with the specified value\n\n Parameters\n ----------\n value : scalar\n Scalar value to use to fill holes (e.g. 0).\n This value cannot be a list-likes.\n downcast : dict, default is None\n a dict of item->dtype of what to downcast if possible,\n or the string 'infer' which will try to downcast to an appropriate\n equal type (e.g. float64 to int64 if possible)\n\n Returns\n -------\n filled : Index\n \"\"\"\n\n @Appender(_index_shared_docs['fillna'])\n def fillna(self, value=None, downcast=None):\n self._assert_can_do_op(value)\n if self.hasnans:\n result = self.putmask(self._isnan, value)\n if downcast is None:\n # no need to care metadata other than name\n # because it can't have freq if\n return Index(result, name=self.name)\n return self._shallow_copy()\n\n _index_shared_docs['dropna'] = \"\"\"\n Return Index without NA/NaN values\n\n Parameters\n ----------\n how : {'any', 'all'}, default 'any'\n If the Index is a MultiIndex, drop the value when any or all levels\n are NaN.\n\n Returns\n -------\n valid : Index\n \"\"\"\n\n @Appender(_index_shared_docs['dropna'])\n def dropna(self, how='any'):\n if how not in ('any', 'all'):\n raise ValueError(\"invalid how option: {0}\".format(how))\n\n if self.hasnans:\n return self._shallow_copy(self.values[~self._isnan])\n return self._shallow_copy()\n\n # --------------------------------------------------------------------\n # Uniqueness Methods\n\n _index_shared_docs['index_unique'] = (\n \"\"\"\n Return unique values in the index. Uniques are returned in order\n of appearance, this does NOT sort.\n\n Parameters\n ----------\n level : int or str, optional, default None\n Only return values from specified level (for MultiIndex)\n\n .. versionadded:: 0.23.0\n\n Returns\n -------\n Index without duplicates\n\n See Also\n --------\n unique\n Series.unique\n \"\"\")\n\n @Appender(_index_shared_docs['index_unique'] % _index_doc_kwargs)\n def unique(self, level=None):\n if level is not None:\n self._validate_index_level(level)\n result = super(Index, self).unique()\n return self._shallow_copy(result)\n\n def drop_duplicates(self, keep='first'):\n \"\"\"\n Return Index with duplicate values removed.\n\n Parameters\n ----------\n keep : {'first', 'last', ``False``}, default 'first'\n - 'first' : Drop duplicates except for the first occurrence.\n - 'last' : Drop duplicates except for the last occurrence.\n - ``False`` : Drop all duplicates.\n\n Returns\n -------\n deduplicated : Index\n\n See Also\n --------\n Series.drop_duplicates : Equivalent method on Series.\n DataFrame.drop_duplicates : Equivalent method on DataFrame.\n Index.duplicated : Related method on Index, indicating duplicate\n Index values.\n\n Examples\n --------\n Generate an pandas.Index with duplicate values.\n\n >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'])\n\n The `keep` parameter controls which duplicate values are removed.\n The value 'first' keeps the first occurrence for each\n set of duplicated entries. The default value of keep is 'first'.\n\n >>> idx.drop_duplicates(keep='first')\n Index(['lama', 'cow', 'beetle', 'hippo'], dtype='object')\n\n The value 'last' keeps the last occurrence for each set of duplicated\n entries.\n\n >>> idx.drop_duplicates(keep='last')\n Index(['cow', 'beetle', 'lama', 'hippo'], dtype='object')\n\n The value ``False`` discards all sets of duplicated entries.\n\n >>> idx.drop_duplicates(keep=False)\n Index(['cow', 'beetle', 'hippo'], dtype='object')\n \"\"\"\n return super(Index, self).drop_duplicates(keep=keep)\n\n def duplicated(self, keep='first'):\n \"\"\"\n Indicate duplicate index values.\n\n Duplicated values are indicated as ``True`` values in the resulting\n array. Either all duplicates, all except the first, or all except the\n last occurrence of duplicates can be indicated.\n\n Parameters\n ----------\n keep : {'first', 'last', False}, default 'first'\n The value or values in a set of duplicates to mark as missing.\n\n - 'first' : Mark duplicates as ``True`` except for the first\n occurrence.\n - 'last' : Mark duplicates as ``True`` except for the last\n occurrence.\n - ``False`` : Mark all duplicates as ``True``.\n\n Returns\n -------\n numpy.ndarray\n\n See Also\n --------\n Series.duplicated : Equivalent method on pandas.Series.\n DataFrame.duplicated : Equivalent method on pandas.DataFrame.\n Index.drop_duplicates : Remove duplicate values from Index.\n\n Examples\n --------\n By default, for each set of duplicated values, the first occurrence is\n set to False and all others to True:\n\n >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama'])\n >>> idx.duplicated()\n array([False, False, True, False, True])\n\n which is equivalent to\n\n >>> idx.duplicated(keep='first')\n array([False, False, True, False, True])\n\n By using 'last', the last occurrence of each set of duplicated values\n is set on False and all others on True:\n\n >>> idx.duplicated(keep='last')\n array([ True, False, True, False, False])\n\n By setting keep on ``False``, all duplicates are True:\n\n >>> idx.duplicated(keep=False)\n array([ True, False, True, False, True])\n \"\"\"\n return super(Index, self).duplicated(keep=keep)\n\n def get_duplicates(self):\n \"\"\"\n Extract duplicated index elements.\n\n .. deprecated:: 0.23.0\n Use idx[idx.duplicated()].unique() instead\n\n Returns a sorted list of index elements which appear more than once in\n the index.\n\n Returns\n -------\n array-like\n List of duplicated indexes.\n\n See Also\n --------\n Index.duplicated : Return boolean array denoting duplicates.\n Index.drop_duplicates : Return Index with duplicates removed.\n\n Examples\n --------\n\n Works on different Index of types.\n\n >>> pd.Index([1, 2, 2, 3, 3, 3, 4]).get_duplicates() # doctest: +SKIP\n [2, 3]\n\n Note that for a DatetimeIndex, it does not return a list but a new\n DatetimeIndex:\n\n >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03',\n ... '2018-01-03', '2018-01-04', '2018-01-04'],\n ... format='%Y-%m-%d')\n >>> pd.Index(dates).get_duplicates() # doctest: +SKIP\n DatetimeIndex(['2018-01-03', '2018-01-04'],\n dtype='datetime64[ns]', freq=None)\n\n Sorts duplicated elements even when indexes are unordered.\n\n >>> pd.Index([1, 2, 3, 2, 3, 4, 3]).get_duplicates() # doctest: +SKIP\n [2, 3]\n\n Return empty array-like structure when all elements are unique.\n\n >>> pd.Index([1, 2, 3, 4]).get_duplicates() # doctest: +SKIP\n []\n >>> dates = pd.to_datetime(['2018-01-01', '2018-01-02', '2018-01-03'],\n ... format='%Y-%m-%d')\n >>> pd.Index(dates).get_duplicates() # doctest: +SKIP\n DatetimeIndex([], dtype='datetime64[ns]', freq=None)\n \"\"\"\n warnings.warn(\"'get_duplicates' is deprecated and will be removed in \"\n \"a future release. You can use \"\n \"idx[idx.duplicated()].unique() instead\",\n FutureWarning, stacklevel=2)\n\n return self[self.duplicated()].unique()\n\n def _get_unique_index(self, dropna=False):\n \"\"\"\n Returns an index containing unique values.\n\n Parameters\n ----------\n dropna : bool\n If True, NaN values are dropped.\n\n Returns\n -------\n uniques : index\n \"\"\"\n if self.is_unique and not dropna:\n return self\n\n values = self.values\n\n if not self.is_unique:\n values = self.unique()\n\n if dropna:\n try:\n if self.hasnans:\n values = values[~isna(values)]\n except NotImplementedError:\n pass\n\n return self._shallow_copy(values)\n\n # --------------------------------------------------------------------\n # Arithmetic & Logical Methods\n\n def __add__(self, other):\n if isinstance(other, (ABCSeries, ABCDataFrame)):\n return NotImplemented\n return Index(np.array(self) + other)\n\n def __radd__(self, other):\n return Index(other + np.array(self))\n\n def __iadd__(self, other):\n # alias for __add__\n return self + other\n\n def __sub__(self, other):\n return Index(np.array(self) - other)\n\n def __rsub__(self, other):\n return Index(other - np.array(self))\n\n def __and__(self, other):\n return self.intersection(other)\n\n def __or__(self, other):\n return self.union(other)\n\n def __xor__(self, other):\n return self.symmetric_difference(other)\n\n def __nonzero__(self):\n raise ValueError(\"The truth value of a {0} is ambiguous. \"\n \"Use a.empty, a.bool(), a.item(), a.any() or a.all().\"\n .format(self.__class__.__name__))\n\n __bool__ = __nonzero__\n\n # --------------------------------------------------------------------\n # Set Operation Methods\n\n def _get_reconciled_name_object(self, other):\n \"\"\"\n If the result of a set operation will be self,\n return self, unless the name changes, in which\n case make a shallow copy of self.\n \"\"\"\n name = get_op_result_name(self, other)\n if self.name != name:\n return self._shallow_copy(name=name)\n return self\n\n def _validate_sort_keyword(self, sort):\n if sort not in [None, False]:\n raise ValueError(\"The 'sort' keyword only takes the values of \"\n \"None or False; {0} was passed.\".format(sort))\n\n def union(self, other, sort=None):\n \"\"\"\n Form the union of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : bool or None, default None\n Whether to sort the resulting Index.\n\n * None : Sort the result, except when\n\n 1. `self` and `other` are equal.\n 2. `self` or `other` has length 0.\n 3. Some values in `self` or `other` cannot be compared.\n A RuntimeWarning is issued in this case.\n\n * False : do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n union : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.union(idx2)\n Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other = ensure_index(other)\n\n if len(other) == 0 or self.equals(other):\n return self._get_reconciled_name_object(other)\n\n if len(self) == 0:\n return other._get_reconciled_name_object(self)\n\n # TODO: is_dtype_union_equal is a hack around\n # 1. buggy set ops with duplicates (GH #13432)\n # 2. CategoricalIndex lacking setops (GH #10186)\n # Once those are fixed, this workaround can be removed\n if not is_dtype_union_equal(self.dtype, other.dtype):\n this = self.astype('O')\n other = other.astype('O')\n return this.union(other, sort=sort)\n\n # TODO(EA): setops-refactor, clean all this up\n if is_period_dtype(self) or is_datetime64tz_dtype(self):\n lvals = self._ndarray_values\n else:\n lvals = self._values\n if is_period_dtype(other) or is_datetime64tz_dtype(other):\n rvals = other._ndarray_values\n else:\n rvals = other._values\n\n if self.is_monotonic and other.is_monotonic:\n try:\n result = self._outer_indexer(lvals, rvals)[0]\n except TypeError:\n # incomparable objects\n result = list(lvals)\n\n # worth making this faster? a very unusual case\n value_set = set(lvals)\n result.extend([x for x in rvals if x not in value_set])\n else:\n indexer = self.get_indexer(other)\n indexer, = (indexer == -1).nonzero()\n\n if len(indexer) > 0:\n other_diff = algos.take_nd(rvals, indexer,\n allow_fill=False)\n result = _concat._concat_compat((lvals, other_diff))\n\n else:\n result = lvals\n\n if sort is None:\n try:\n result = sorting.safe_sort(result)\n except TypeError as e:\n warnings.warn(\"{}, sort order is undefined for \"\n \"incomparable objects\".format(e),\n RuntimeWarning, stacklevel=3)\n\n # for subclasses\n return self._wrap_setop_result(other, result)\n\n def _wrap_setop_result(self, other, result):\n return self._constructor(result, name=get_op_result_name(self, other))\n\n def intersection(self, other, sort=False):\n \"\"\"\n Form the intersection of two Index objects.\n\n This returns a new Index with elements common to the index and `other`.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default False\n Whether to sort the resulting index.\n\n * False : do not sort the result.\n * None : sort the result, except when `self` and `other` are equal\n or when the values cannot be compared.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default from ``True`` to ``False``, to match\n the behaviour of 0.23.4 and earlier.\n\n Returns\n -------\n intersection : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.intersection(idx2)\n Int64Index([3, 4], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other = ensure_index(other)\n\n if self.equals(other):\n return self._get_reconciled_name_object(other)\n\n if not is_dtype_equal(self.dtype, other.dtype):\n this = self.astype('O')\n other = other.astype('O')\n return this.intersection(other, sort=sort)\n\n # TODO(EA): setops-refactor, clean all this up\n if is_period_dtype(self):\n lvals = self._ndarray_values\n else:\n lvals = self._values\n if is_period_dtype(other):\n rvals = other._ndarray_values\n else:\n rvals = other._values\n\n if self.is_monotonic and other.is_monotonic:\n try:\n result = self._inner_indexer(lvals, rvals)[0]\n return self._wrap_setop_result(other, result)\n except TypeError:\n pass\n\n try:\n indexer = Index(rvals).get_indexer(lvals)\n indexer = indexer.take((indexer != -1).nonzero()[0])\n except Exception:\n # duplicates\n indexer = algos.unique1d(\n Index(rvals).get_indexer_non_unique(lvals)[0])\n indexer = indexer[indexer != -1]\n\n taken = other.take(indexer)\n\n if sort is None:\n taken = sorting.safe_sort(taken.values)\n if self.name != other.name:\n name = None\n else:\n name = self.name\n return self._shallow_copy(taken, name=name)\n\n if self.name != other.name:\n taken.name = None\n\n return taken\n\n def difference(self, other, sort=None):\n \"\"\"\n Return a new Index with elements from the index that are not in\n `other`.\n\n This is the set difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default None\n Whether to sort the resulting index. By default, the\n values are attempted to be sorted, but any TypeError from\n incomparable elements is caught by pandas.\n\n * None : Attempt to sort the result, but catch any TypeErrors\n from comparing incomparable elements.\n * False : Do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n difference : Index\n\n Examples\n --------\n\n >>> idx1 = pd.Index([2, 1, 3, 4])\n >>> idx2 = pd.Index([3, 4, 5, 6])\n >>> idx1.difference(idx2)\n Int64Index([1, 2], dtype='int64')\n >>> idx1.difference(idx2, sort=False)\n Int64Index([2, 1], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n\n if self.equals(other):\n # pass an empty np.ndarray with the appropriate dtype\n return self._shallow_copy(self._data[:0])\n\n other, result_name = self._convert_can_do_setop(other)\n\n this = self._get_unique_index()\n\n indexer = this.get_indexer(other)\n indexer = indexer.take((indexer != -1).nonzero()[0])\n\n label_diff = np.setdiff1d(np.arange(this.size), indexer,\n assume_unique=True)\n the_diff = this.values.take(label_diff)\n if sort is None:\n try:\n the_diff = sorting.safe_sort(the_diff)\n except TypeError:\n pass\n\n return this._shallow_copy(the_diff, name=result_name, freq=None)\n\n def symmetric_difference(self, other, result_name=None, sort=None):\n \"\"\"\n Compute the symmetric difference of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n result_name : str\n sort : False or None, default None\n Whether to sort the resulting index. By default, the\n values are attempted to be sorted, but any TypeError from\n incomparable elements is caught by pandas.\n\n * None : Attempt to sort the result, but catch any TypeErrors\n from comparing incomparable elements.\n * False : Do not sort the result.\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default value from ``True`` to ``None``\n (without change in behaviour).\n\n Returns\n -------\n symmetric_difference : Index\n\n Notes\n -----\n ``symmetric_difference`` contains elements that appear in either\n ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by\n ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates\n dropped.\n\n Examples\n --------\n >>> idx1 = pd.Index([1, 2, 3, 4])\n >>> idx2 = pd.Index([2, 3, 4, 5])\n >>> idx1.symmetric_difference(idx2)\n Int64Index([1, 5], dtype='int64')\n\n You can also use the ``^`` operator:\n\n >>> idx1 ^ idx2\n Int64Index([1, 5], dtype='int64')\n \"\"\"\n self._validate_sort_keyword(sort)\n self._assert_can_do_setop(other)\n other, result_name_update = self._convert_can_do_setop(other)\n if result_name is None:\n result_name = result_name_update\n\n this = self._get_unique_index()\n other = other._get_unique_index()\n indexer = this.get_indexer(other)\n\n # {this} minus {other}\n common_indexer = indexer.take((indexer != -1).nonzero()[0])\n left_indexer = np.setdiff1d(np.arange(this.size), common_indexer,\n assume_unique=True)\n left_diff = this.values.take(left_indexer)\n\n # {other} minus {this}\n right_indexer = (indexer == -1).nonzero()[0]\n right_diff = other.values.take(right_indexer)\n\n the_diff = _concat._concat_compat([left_diff, right_diff])\n if sort is None:\n try:\n the_diff = sorting.safe_sort(the_diff)\n except TypeError:\n pass\n\n attribs = self._get_attributes_dict()\n attribs['name'] = result_name\n if 'freq' in attribs:\n attribs['freq'] = None\n return self._shallow_copy_with_infer(the_diff, **attribs)\n\n def _assert_can_do_setop(self, other):\n if not is_list_like(other):\n raise TypeError('Input must be Index or array-like')\n return True\n\n def _convert_can_do_setop(self, other):\n if not isinstance(other, Index):\n other = Index(other, name=self.name)\n result_name = self.name\n else:\n result_name = get_op_result_name(self, other)\n return other, result_name\n\n # --------------------------------------------------------------------\n # Indexing Methods\n\n _index_shared_docs['get_loc'] = \"\"\"\n Get integer location, slice or boolean mask for requested label.\n\n Parameters\n ----------\n key : label\n method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional\n * default: exact matches only.\n * pad / ffill: find the PREVIOUS index value if no exact match.\n * backfill / bfill: use NEXT index value if no exact match\n * nearest: use the NEAREST index value if no exact match. Tied\n distances are broken by preferring the larger index value.\n tolerance : optional\n Maximum distance from index value for inexact matches. The value of\n the index at the matching location most satisfy the equation\n ``abs(index[loc] - key) <= tolerance``.\n\n Tolerance may be a scalar\n value, which applies the same tolerance to all values, or\n list-like, which applies variable tolerance per element. List-like\n includes list, tuple, array, Series, and must be the same size as\n the index and its dtype must exactly match the index's type.\n\n .. versionadded:: 0.21.0 (list-like tolerance)\n\n Returns\n -------\n loc : int if unique index, slice if monotonic index, else mask\n\n Examples\n ---------\n >>> unique_index = pd.Index(list('abc'))\n >>> unique_index.get_loc('b')\n 1\n\n >>> monotonic_index = pd.Index(list('abbc'))\n >>> monotonic_index.get_loc('b')\n slice(1, 3, None)\n\n >>> non_monotonic_index = pd.Index(list('abcb'))\n >>> non_monotonic_index.get_loc('b')\n array([False, True, False, True], dtype=bool)\n \"\"\"\n\n @Appender(_index_shared_docs['get_loc'])\n def get_loc(self, key, method=None, tolerance=None):\n if method is None:\n if tolerance is not None:\n raise ValueError('tolerance argument only valid if using pad, '\n 'backfill or nearest lookups')\n try:\n return self._engine.get_loc(key)\n except KeyError:\n return self._engine.get_loc(self._maybe_cast_indexer(key))\n indexer = self.get_indexer([key], method=method, tolerance=tolerance)\n if indexer.ndim > 1 or indexer.size > 1:\n raise TypeError('get_loc requires scalar valued input')\n loc = indexer.item()\n if loc == -1:\n raise KeyError(key)\n return loc\n\n _index_shared_docs['get_indexer'] = \"\"\"\n Compute indexer and mask for new index given the current index. The\n indexer should be then used as an input to ndarray.take to align the\n current data to the new index.\n\n Parameters\n ----------\n target : %(target_klass)s\n method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional\n * default: exact matches only.\n * pad / ffill: find the PREVIOUS index value if no exact match.\n * backfill / bfill: use NEXT index value if no exact match\n * nearest: use the NEAREST index value if no exact match. Tied\n distances are broken by preferring the larger index value.\n limit : int, optional\n Maximum number of consecutive labels in ``target`` to match for\n inexact matches.\n tolerance : optional\n Maximum distance between original and new labels for inexact\n matches. The values of the index at the matching locations most\n satisfy the equation ``abs(index[indexer] - target) <= tolerance``.\n\n Tolerance may be a scalar value, which applies the same tolerance\n to all values, or list-like, which applies variable tolerance per\n element. List-like includes list, tuple, array, Series, and must be\n the same size as the index and its dtype must exactly match the\n index's type.\n\n .. versionadded:: 0.21.0 (list-like tolerance)\n\n Returns\n -------\n indexer : ndarray of int\n Integers from 0 to n - 1 indicating that the index at these\n positions matches the corresponding target values. Missing values\n in the target are marked by -1.\n\n Examples\n --------\n >>> index = pd.Index(['c', 'a', 'b'])\n >>> index.get_indexer(['a', 'b', 'x'])\n array([ 1, 2, -1])\n\n Notice that the return value is an array of locations in ``index``\n and ``x`` is marked by -1, as it is not in ``index``.\n \"\"\"\n\n @Appender(_index_shared_docs['get_indexer'] % _index_doc_kwargs)\n def get_indexer(self, target, method=None, limit=None, tolerance=None):\n method = missing.clean_reindex_fill_method(method)\n target = ensure_index(target)\n if tolerance is not None:\n tolerance = self._convert_tolerance(tolerance, target)\n\n # Treat boolean labels passed to a numeric index as not found. Without\n # this fix False and True would be treated as 0 and 1 respectively.\n # (GH #16877)\n if target.is_boolean() and self.is_numeric():\n return ensure_platform_int(np.repeat(-1, target.size))\n\n pself, ptarget = self._maybe_promote(target)\n if pself is not self or ptarget is not target:\n return pself.get_indexer(ptarget, method=method, limit=limit,\n tolerance=tolerance)\n\n if not is_dtype_equal(self.dtype, target.dtype):\n this = self.astype(object)\n target = target.astype(object)\n return this.get_indexer(target, method=method, limit=limit,\n tolerance=tolerance)\n\n if not self.is_unique:\n raise InvalidIndexError('Reindexing only valid with uniquely'\n ' valued Index objects')\n\n if method == 'pad' or method == 'backfill':\n indexer = self._get_fill_indexer(target, method, limit, tolerance)\n elif method == 'nearest':\n indexer = self._get_nearest_indexer(target, limit, tolerance)\n else:\n if tolerance is not None:\n raise ValueError('tolerance argument only valid if doing pad, '\n 'backfill or nearest reindexing')\n if limit is not None:\n raise ValueError('limit argument only valid if doing pad, '\n 'backfill or nearest reindexing')\n\n indexer = self._engine.get_indexer(target._ndarray_values)\n\n return ensure_platform_int(indexer)\n\n def _convert_tolerance(self, tolerance, target):\n # override this method on subclasses\n tolerance = np.asarray(tolerance)\n if target.size != tolerance.size and tolerance.size > 1:\n raise ValueError('list-like tolerance size must match '\n 'target index size')\n return tolerance\n\n def _get_fill_indexer(self, target, method, limit=None, tolerance=None):\n if self.is_monotonic_increasing and target.is_monotonic_increasing:\n method = (self._engine.get_pad_indexer if method == 'pad' else\n self._engine.get_backfill_indexer)\n indexer = method(target._ndarray_values, limit)\n else:\n indexer = self._get_fill_indexer_searchsorted(target, method,\n limit)\n if tolerance is not None:\n indexer = self._filter_indexer_tolerance(target._ndarray_values,\n indexer,\n tolerance)\n return indexer\n\n def _get_fill_indexer_searchsorted(self, target, method, limit=None):\n \"\"\"\n Fallback pad/backfill get_indexer that works for monotonic decreasing\n indexes and non-monotonic targets.\n \"\"\"\n if limit is not None:\n raise ValueError('limit argument for %r method only well-defined '\n 'if index and target are monotonic' % method)\n\n side = 'left' if method == 'pad' else 'right'\n\n # find exact matches first (this simplifies the algorithm)\n indexer = self.get_indexer(target)\n nonexact = (indexer == -1)\n indexer[nonexact] = self._searchsorted_monotonic(target[nonexact],\n side)\n if side == 'left':\n # searchsorted returns \"indices into a sorted array such that,\n # if the corresponding elements in v were inserted before the\n # indices, the order of a would be preserved\".\n # Thus, we need to subtract 1 to find values to the left.\n indexer[nonexact] -= 1\n # This also mapped not found values (values of 0 from\n # np.searchsorted) to -1, which conveniently is also our\n # sentinel for missing values\n else:\n # Mark indices to the right of the largest value as not found\n indexer[indexer == len(self)] = -1\n return indexer\n\n def _get_nearest_indexer(self, target, limit, tolerance):\n \"\"\"\n Get the indexer for the nearest index labels; requires an index with\n values that can be subtracted from each other (e.g., not strings or\n tuples).\n \"\"\"\n left_indexer = self.get_indexer(target, 'pad', limit=limit)\n right_indexer = self.get_indexer(target, 'backfill', limit=limit)\n\n target = np.asarray(target)\n left_distances = abs(self.values[left_indexer] - target)\n right_distances = abs(self.values[right_indexer] - target)\n\n op = operator.lt if self.is_monotonic_increasing else operator.le\n indexer = np.where(op(left_distances, right_distances) |\n (right_indexer == -1), left_indexer, right_indexer)\n if tolerance is not None:\n indexer = self._filter_indexer_tolerance(target, indexer,\n tolerance)\n return indexer\n\n def _filter_indexer_tolerance(self, target, indexer, tolerance):\n distance = abs(self.values[indexer] - target)\n indexer = np.where(distance <= tolerance, indexer, -1)\n return indexer\n\n # --------------------------------------------------------------------\n # Indexer Conversion Methods\n\n _index_shared_docs['_convert_scalar_indexer'] = \"\"\"\n Convert a scalar indexer.\n\n Parameters\n ----------\n key : label of the slice bound\n kind : {'ix', 'loc', 'getitem', 'iloc'} or None\n \"\"\"\n\n @Appender(_index_shared_docs['_convert_scalar_indexer'])\n def _convert_scalar_indexer(self, key, kind=None):\n assert kind in ['ix', 'loc', 'getitem', 'iloc', None]\n\n if kind == 'iloc':\n return self._validate_indexer('positional', key, kind)\n\n if len(self) and not isinstance(self, ABCMultiIndex,):\n\n # we can raise here if we are definitive that this\n # is positional indexing (eg. .ix on with a float)\n # or label indexing if we are using a type able\n # to be represented in the index\n\n if kind in ['getitem', 'ix'] and is_float(key):\n if not self.is_floating():\n return self._invalid_indexer('label', key)\n\n elif kind in ['loc'] and is_float(key):\n\n # we want to raise KeyError on string/mixed here\n # technically we *could* raise a TypeError\n # on anything but mixed though\n if self.inferred_type not in ['floating',\n 'mixed-integer-float',\n 'string',\n 'unicode',\n 'mixed']:\n return self._invalid_indexer('label', key)\n\n elif kind in ['loc'] and is_integer(key):\n if not self.holds_integer():\n return self._invalid_indexer('label', key)\n\n return key\n\n _index_shared_docs['_convert_slice_indexer'] = \"\"\"\n Convert a slice indexer.\n\n By definition, these are labels unless 'iloc' is passed in.\n Floats are not allowed as the start, step, or stop of the slice.\n\n Parameters\n ----------\n key : label of the slice bound\n kind : {'ix', 'loc', 'getitem', 'iloc'} or None\n \"\"\"\n\n @Appender(_index_shared_docs['_convert_slice_indexer'])\n def _convert_slice_indexer(self, key, kind=None):\n assert kind in ['ix', 'loc', 'getitem', 'iloc', None]\n\n # if we are not a slice, then we are done\n if not isinstance(key, slice):\n return key\n\n # validate iloc\n if kind == 'iloc':\n return slice(self._validate_indexer('slice', key.start, kind),\n self._validate_indexer('slice', key.stop, kind),\n self._validate_indexer('slice', key.step, kind))\n\n # potentially cast the bounds to integers\n start, stop, step = key.start, key.stop, key.step\n\n # figure out if this is a positional indexer\n def is_int(v):\n return v is None or is_integer(v)\n\n is_null_slicer = start is None and stop is None\n is_index_slice = is_int(start) and is_int(stop)\n is_positional = is_index_slice and not self.is_integer()\n\n if kind == 'getitem':\n \"\"\"\n called from the getitem slicers, validate that we are in fact\n integers\n \"\"\"\n if self.is_integer() or is_index_slice:\n return slice(self._validate_indexer('slice', key.start, kind),\n self._validate_indexer('slice', key.stop, kind),\n self._validate_indexer('slice', key.step, kind))\n\n # convert the slice to an indexer here\n\n # if we are mixed and have integers\n try:\n if is_positional and self.is_mixed():\n # Validate start & stop\n if start is not None:\n self.get_loc(start)\n if stop is not None:\n self.get_loc(stop)\n is_positional = False\n except KeyError:\n if self.inferred_type == 'mixed-integer-float':\n raise\n\n if is_null_slicer:\n indexer = key\n elif is_positional:\n indexer = key\n else:\n try:\n indexer = self.slice_indexer(start, stop, step, kind=kind)\n except Exception:\n if is_index_slice:\n if self.is_integer():\n raise\n else:\n indexer = key\n else:\n raise\n\n return indexer\n\n def _convert_listlike_indexer(self, keyarr, kind=None):\n \"\"\"\n Parameters\n ----------\n keyarr : list-like\n Indexer to convert.\n\n Returns\n -------\n tuple (indexer, keyarr)\n indexer is an ndarray or None if cannot convert\n keyarr are tuple-safe keys\n \"\"\"\n if isinstance(keyarr, Index):\n keyarr = self._convert_index_indexer(keyarr)\n else:\n keyarr = self._convert_arr_indexer(keyarr)\n\n indexer = self._convert_list_indexer(keyarr, kind=kind)\n return indexer, keyarr\n\n _index_shared_docs['_convert_arr_indexer'] = \"\"\"\n Convert an array-like indexer to the appropriate dtype.\n\n Parameters\n ----------\n keyarr : array-like\n Indexer to convert.\n\n Returns\n -------\n converted_keyarr : array-like\n \"\"\"\n\n @Appender(_index_shared_docs['_convert_arr_indexer'])\n def _convert_arr_indexer(self, keyarr):\n keyarr = com.asarray_tuplesafe(keyarr)\n return keyarr\n\n _index_shared_docs['_convert_index_indexer'] = \"\"\"\n Convert an Index indexer to the appropriate dtype.\n\n Parameters\n ----------\n keyarr : Index (or sub-class)\n Indexer to convert.\n\n Returns\n -------\n converted_keyarr : Index (or sub-class)\n \"\"\"\n\n @Appender(_index_shared_docs['_convert_index_indexer'])\n def _convert_index_indexer(self, keyarr):\n return keyarr\n\n _index_shared_docs['_convert_list_indexer'] = \"\"\"\n Convert a list-like indexer to the appropriate dtype.\n\n Parameters\n ----------\n keyarr : Index (or sub-class)\n Indexer to convert.\n kind : iloc, ix, loc, optional\n\n Returns\n -------\n positional indexer or None\n \"\"\"\n\n @Appender(_index_shared_docs['_convert_list_indexer'])\n def _convert_list_indexer(self, keyarr, kind=None):\n if (kind in [None, 'iloc', 'ix'] and\n is_integer_dtype(keyarr) and not self.is_floating() and\n not isinstance(keyarr, ABCPeriodIndex)):\n\n if self.inferred_type == 'mixed-integer':\n indexer = self.get_indexer(keyarr)\n if (indexer >= 0).all():\n return indexer\n # missing values are flagged as -1 by get_indexer and negative\n # indices are already converted to positive indices in the\n # above if-statement, so the negative flags are changed to\n # values outside the range of indices so as to trigger an\n # IndexError in maybe_convert_indices\n indexer[indexer < 0] = len(self)\n from pandas.core.indexing import maybe_convert_indices\n return maybe_convert_indices(indexer, len(self))\n\n elif not self.inferred_type == 'integer':\n keyarr = np.where(keyarr < 0, len(self) + keyarr, keyarr)\n return keyarr\n\n return None\n\n def _invalid_indexer(self, form, key):\n \"\"\"\n Consistent invalid indexer message.\n \"\"\"\n raise TypeError(\"cannot do {form} indexing on {klass} with these \"\n \"indexers [{key}] of {kind}\".format(\n form=form, klass=type(self), key=key,\n kind=type(key)))\n\n # --------------------------------------------------------------------\n # Reindex Methods\n\n def _can_reindex(self, indexer):\n \"\"\"\n Check if we are allowing reindexing with this particular indexer.\n\n Parameters\n ----------\n indexer : an integer indexer\n\n Raises\n ------\n ValueError if its a duplicate axis\n \"\"\"\n\n # trying to reindex on an axis with duplicates\n if not self.is_unique and len(indexer):\n raise ValueError(\"cannot reindex from a duplicate axis\")\n\n def reindex(self, target, method=None, level=None, limit=None,\n tolerance=None):\n \"\"\"\n Create index with target's values (move/add/delete values\n as necessary).\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulting index.\n indexer : np.ndarray or None\n Indices of output values in original index.\n\n \"\"\"\n # GH6552: preserve names when reindexing to non-named target\n # (i.e. neither Index nor Series).\n preserve_names = not hasattr(target, 'name')\n\n # GH7774: preserve dtype/tz if target is empty and not an Index.\n target = _ensure_has_len(target) # target may be an iterator\n\n if not isinstance(target, Index) and len(target) == 0:\n attrs = self._get_attributes_dict()\n attrs.pop('freq', None) # don't preserve freq\n values = self._data[:0] # appropriately-dtyped empty array\n target = self._simple_new(values, dtype=self.dtype, **attrs)\n else:\n target = ensure_index(target)\n\n if level is not None:\n if method is not None:\n raise TypeError('Fill method not supported if level passed')\n _, indexer, _ = self._join_level(target, level, how='right',\n return_indexers=True)\n else:\n if self.equals(target):\n indexer = None\n else:\n\n if self.is_unique:\n indexer = self.get_indexer(target, method=method,\n limit=limit,\n tolerance=tolerance)\n else:\n if method is not None or limit is not None:\n raise ValueError(\"cannot reindex a non-unique index \"\n \"with a method or limit\")\n indexer, missing = self.get_indexer_non_unique(target)\n\n if preserve_names and target.nlevels == 1 and target.name != self.name:\n target = target.copy()\n target.name = self.name\n\n return target, indexer\n\n def _reindex_non_unique(self, target):\n \"\"\"\n Create a new index with target's values (move/add/delete values as\n necessary) use with non-unique Index and a possibly non-unique target.\n\n Parameters\n ----------\n target : an iterable\n\n Returns\n -------\n new_index : pd.Index\n Resulting index\n indexer : np.ndarray or None\n Indices of output values in original index\n\n \"\"\"\n\n target = ensure_index(target)\n indexer, missing = self.get_indexer_non_unique(target)\n check = indexer != -1\n new_labels = self.take(indexer[check])\n new_indexer = None\n\n if len(missing):\n length = np.arange(len(indexer))\n\n missing = ensure_platform_int(missing)\n missing_labels = target.take(missing)\n missing_indexer = ensure_int64(length[~check])\n cur_labels = self.take(indexer[check]).values\n cur_indexer = ensure_int64(length[check])\n\n new_labels = np.empty(tuple([len(indexer)]), dtype=object)\n new_labels[cur_indexer] = cur_labels\n new_labels[missing_indexer] = missing_labels\n\n # a unique indexer\n if target.is_unique:\n\n # see GH5553, make sure we use the right indexer\n new_indexer = np.arange(len(indexer))\n new_indexer[cur_indexer] = np.arange(len(cur_labels))\n new_indexer[missing_indexer] = -1\n\n # we have a non_unique selector, need to use the original\n # indexer here\n else:\n\n # need to retake to have the same size as the indexer\n indexer[~check] = -1\n\n # reset the new indexer to account for the new size\n new_indexer = np.arange(len(self.take(indexer)))\n new_indexer[~check] = -1\n\n new_index = self._shallow_copy_with_infer(new_labels, freq=None)\n return new_index, indexer, new_indexer\n\n # --------------------------------------------------------------------\n # Join Methods\n\n _index_shared_docs['join'] = \"\"\"\n Compute join_index and indexers to conform data\n structures to the new index.\n\n Parameters\n ----------\n other : Index\n how : {'left', 'right', 'inner', 'outer'}\n level : int or level name, default None\n return_indexers : boolean, default False\n sort : boolean, default False\n Sort the join keys lexicographically in the result Index. If False,\n the order of the join keys depends on the join type (how keyword)\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n join_index, (left_indexer, right_indexer)\n \"\"\"\n\n @Appender(_index_shared_docs['join'])\n def join(self, other, how='left', level=None, return_indexers=False,\n sort=False):\n self_is_mi = isinstance(self, ABCMultiIndex)\n other_is_mi = isinstance(other, ABCMultiIndex)\n\n # try to figure out the join level\n # GH3662\n if level is None and (self_is_mi or other_is_mi):\n\n # have the same levels/names so a simple join\n if self.names == other.names:\n pass\n else:\n return self._join_multi(other, how=how,\n return_indexers=return_indexers)\n\n # join on the level\n if level is not None and (self_is_mi or other_is_mi):\n return self._join_level(other, level, how=how,\n return_indexers=return_indexers)\n\n other = ensure_index(other)\n\n if len(other) == 0 and how in ('left', 'outer'):\n join_index = self._shallow_copy()\n if return_indexers:\n rindexer = np.repeat(-1, len(join_index))\n return join_index, None, rindexer\n else:\n return join_index\n\n if len(self) == 0 and how in ('right', 'outer'):\n join_index = other._shallow_copy()\n if return_indexers:\n lindexer = np.repeat(-1, len(join_index))\n return join_index, lindexer, None\n else:\n return join_index\n\n if self._join_precedence < other._join_precedence:\n how = {'right': 'left', 'left': 'right'}.get(how, how)\n result = other.join(self, how=how, level=level,\n return_indexers=return_indexers)\n if return_indexers:\n x, y, z = result\n result = x, z, y\n return result\n\n if not is_dtype_equal(self.dtype, other.dtype):\n this = self.astype('O')\n other = other.astype('O')\n return this.join(other, how=how, return_indexers=return_indexers)\n\n _validate_join_method(how)\n\n if not self.is_unique and not other.is_unique:\n return self._join_non_unique(other, how=how,\n return_indexers=return_indexers)\n elif not self.is_unique or not other.is_unique:\n if self.is_monotonic and other.is_monotonic:\n return self._join_monotonic(other, how=how,\n return_indexers=return_indexers)\n else:\n return self._join_non_unique(other, how=how,\n return_indexers=return_indexers)\n elif self.is_monotonic and other.is_monotonic:\n try:\n return self._join_monotonic(other, how=how,\n return_indexers=return_indexers)\n except TypeError:\n pass\n\n if how == 'left':\n join_index = self\n elif how == 'right':\n join_index = other\n elif how == 'inner':\n # TODO: sort=False here for backwards compat. It may\n # be better to use the sort parameter passed into join\n join_index = self.intersection(other, sort=False)\n elif how == 'outer':\n # TODO: sort=True here for backwards compat. It may\n # be better to use the sort parameter passed into join\n join_index = self.union(other)\n\n if sort:\n join_index = join_index.sort_values()\n\n if return_indexers:\n if join_index is self:\n lindexer = None\n else:\n lindexer = self.get_indexer(join_index)\n if join_index is other:\n rindexer = None\n else:\n rindexer = other.get_indexer(join_index)\n return join_index, lindexer, rindexer\n else:\n return join_index\n\n def _join_multi(self, other, how, return_indexers=True):\n from .multi import MultiIndex\n from pandas.core.reshape.merge import _restore_dropped_levels_multijoin\n\n # figure out join names\n self_names = set(com._not_none(*self.names))\n other_names = set(com._not_none(*other.names))\n overlap = self_names & other_names\n\n # need at least 1 in common\n if not overlap:\n raise ValueError(\"cannot join with no overlapping index names\")\n\n self_is_mi = isinstance(self, MultiIndex)\n other_is_mi = isinstance(other, MultiIndex)\n\n if self_is_mi and other_is_mi:\n\n # Drop the non-matching levels from left and right respectively\n ldrop_names = list(self_names - overlap)\n rdrop_names = list(other_names - overlap)\n\n self_jnlevels = self.droplevel(ldrop_names)\n other_jnlevels = other.droplevel(rdrop_names)\n\n # Join left and right\n # Join on same leveled multi-index frames is supported\n join_idx, lidx, ridx = self_jnlevels.join(other_jnlevels, how,\n return_indexers=True)\n\n # Restore the dropped levels\n # Returned index level order is\n # common levels, ldrop_names, rdrop_names\n dropped_names = ldrop_names + rdrop_names\n\n levels, codes, names = (\n _restore_dropped_levels_multijoin(self, other,\n dropped_names,\n join_idx,\n lidx, ridx))\n\n # Re-create the multi-index\n multi_join_idx = MultiIndex(levels=levels, codes=codes,\n names=names, verify_integrity=False)\n\n multi_join_idx = multi_join_idx.remove_unused_levels()\n\n return multi_join_idx, lidx, ridx\n\n jl = list(overlap)[0]\n\n # Case where only one index is multi\n # make the indices into mi's that match\n flip_order = False\n if self_is_mi:\n self, other = other, self\n flip_order = True\n # flip if join method is right or left\n how = {'right': 'left', 'left': 'right'}.get(how, how)\n\n level = other.names.index(jl)\n result = self._join_level(other, level, how=how,\n return_indexers=return_indexers)\n\n if flip_order:\n if isinstance(result, tuple):\n return result[0], result[2], result[1]\n return result\n\n def _join_non_unique(self, other, how='left', return_indexers=False):\n from pandas.core.reshape.merge import _get_join_indexers\n\n left_idx, right_idx = _get_join_indexers([self._ndarray_values],\n [other._ndarray_values],\n how=how,\n sort=True)\n\n left_idx = ensure_platform_int(left_idx)\n right_idx = ensure_platform_int(right_idx)\n\n join_index = np.asarray(self._ndarray_values.take(left_idx))\n mask = left_idx == -1\n np.putmask(join_index, mask, other._ndarray_values.take(right_idx))\n\n join_index = self._wrap_joined_index(join_index, other)\n\n if return_indexers:\n return join_index, left_idx, right_idx\n else:\n return join_index\n\n def _join_level(self, other, level, how='left', return_indexers=False,\n keep_order=True):\n \"\"\"\n The join method *only* affects the level of the resulting\n MultiIndex. Otherwise it just exactly aligns the Index data to the\n labels of the level in the MultiIndex.\n\n If ```keep_order == True```, the order of the data indexed by the\n MultiIndex will not be changed; otherwise, it will tie out\n with `other`.\n \"\"\"\n from .multi import MultiIndex\n\n def _get_leaf_sorter(labels):\n \"\"\"\n Returns sorter for the inner most level while preserving the\n order of higher levels.\n \"\"\"\n if labels[0].size == 0:\n return np.empty(0, dtype='int64')\n\n if len(labels) == 1:\n lab = ensure_int64(labels[0])\n sorter, _ = libalgos.groupsort_indexer(lab, 1 + lab.max())\n return sorter\n\n # find indexers of beginning of each set of\n # same-key labels w.r.t all but last level\n tic = labels[0][:-1] != labels[0][1:]\n for lab in labels[1:-1]:\n tic |= lab[:-1] != lab[1:]\n\n starts = np.hstack(([True], tic, [True])).nonzero()[0]\n lab = ensure_int64(labels[-1])\n return lib.get_level_sorter(lab, ensure_int64(starts))\n\n if isinstance(self, MultiIndex) and isinstance(other, MultiIndex):\n raise TypeError('Join on level between two MultiIndex objects '\n 'is ambiguous')\n\n left, right = self, other\n\n flip_order = not isinstance(self, MultiIndex)\n if flip_order:\n left, right = right, left\n how = {'right': 'left', 'left': 'right'}.get(how, how)\n\n level = left._get_level_number(level)\n old_level = left.levels[level]\n\n if not right.is_unique:\n raise NotImplementedError('Index._join_level on non-unique index '\n 'is not implemented')\n\n new_level, left_lev_indexer, right_lev_indexer = \\\n old_level.join(right, how=how, return_indexers=True)\n\n if left_lev_indexer is None:\n if keep_order or len(left) == 0:\n left_indexer = None\n join_index = left\n else: # sort the leaves\n left_indexer = _get_leaf_sorter(left.codes[:level + 1])\n join_index = left[left_indexer]\n\n else:\n left_lev_indexer = ensure_int64(left_lev_indexer)\n rev_indexer = lib.get_reverse_indexer(left_lev_indexer,\n len(old_level))\n\n new_lev_codes = algos.take_nd(rev_indexer, left.codes[level],\n allow_fill=False)\n\n new_codes = list(left.codes)\n new_codes[level] = new_lev_codes\n\n new_levels = list(left.levels)\n new_levels[level] = new_level\n\n if keep_order: # just drop missing values. o.w. keep order\n left_indexer = np.arange(len(left), dtype=np.intp)\n mask = new_lev_codes != -1\n if not mask.all():\n new_codes = [lab[mask] for lab in new_codes]\n left_indexer = left_indexer[mask]\n\n else: # tie out the order with other\n if level == 0: # outer most level, take the fast route\n ngroups = 1 + new_lev_codes.max()\n left_indexer, counts = libalgos.groupsort_indexer(\n new_lev_codes, ngroups)\n\n # missing values are placed first; drop them!\n left_indexer = left_indexer[counts[0]:]\n new_codes = [lab[left_indexer] for lab in new_codes]\n\n else: # sort the leaves\n mask = new_lev_codes != -1\n mask_all = mask.all()\n if not mask_all:\n new_codes = [lab[mask] for lab in new_codes]\n\n left_indexer = _get_leaf_sorter(new_codes[:level + 1])\n new_codes = [lab[left_indexer] for lab in new_codes]\n\n # left_indexers are w.r.t masked frame.\n # reverse to original frame!\n if not mask_all:\n left_indexer = mask.nonzero()[0][left_indexer]\n\n join_index = MultiIndex(levels=new_levels, codes=new_codes,\n names=left.names, verify_integrity=False)\n\n if right_lev_indexer is not None:\n right_indexer = algos.take_nd(right_lev_indexer,\n join_index.codes[level],\n allow_fill=False)\n else:\n right_indexer = join_index.codes[level]\n\n if flip_order:\n left_indexer, right_indexer = right_indexer, left_indexer\n\n if return_indexers:\n left_indexer = (None if left_indexer is None\n else ensure_platform_int(left_indexer))\n right_indexer = (None if right_indexer is None\n else ensure_platform_int(right_indexer))\n return join_index, left_indexer, right_indexer\n else:\n return join_index\n\n def _join_monotonic(self, other, how='left', return_indexers=False):\n if self.equals(other):\n ret_index = other if how == 'right' else self\n if return_indexers:\n return ret_index, None, None\n else:\n return ret_index\n\n sv = self._ndarray_values\n ov = other._ndarray_values\n\n if self.is_unique and other.is_unique:\n # We can perform much better than the general case\n if how == 'left':\n join_index = self\n lidx = None\n ridx = self._left_indexer_unique(sv, ov)\n elif how == 'right':\n join_index = other\n lidx = self._left_indexer_unique(ov, sv)\n ridx = None\n elif how == 'inner':\n join_index, lidx, ridx = self._inner_indexer(sv, ov)\n join_index = self._wrap_joined_index(join_index, other)\n elif how == 'outer':\n join_index, lidx, ridx = self._outer_indexer(sv, ov)\n join_index = self._wrap_joined_index(join_index, other)\n else:\n if how == 'left':\n join_index, lidx, ridx = self._left_indexer(sv, ov)\n elif how == 'right':\n join_index, ridx, lidx = self._left_indexer(ov, sv)\n elif how == 'inner':\n join_index, lidx, ridx = self._inner_indexer(sv, ov)\n elif how == 'outer':\n join_index, lidx, ridx = self._outer_indexer(sv, ov)\n join_index = self._wrap_joined_index(join_index, other)\n\n if return_indexers:\n lidx = None if lidx is None else ensure_platform_int(lidx)\n ridx = None if ridx is None else ensure_platform_int(ridx)\n return join_index, lidx, ridx\n else:\n return join_index\n\n def _wrap_joined_index(self, joined, other):\n name = get_op_result_name(self, other)\n return Index(joined, name=name)\n\n # --------------------------------------------------------------------\n # Uncategorized Methods\n\n @property\n def values(self):\n \"\"\"\n Return an array representing the data in the Index.\n\n .. warning::\n\n We recommend using :attr:`Index.array` or\n :meth:`Index.to_numpy`, depending on whether you need\n a reference to the underlying data or a NumPy array.\n\n Returns\n -------\n array: numpy.ndarray or ExtensionArray\n\n See Also\n --------\n Index.array : Reference to the underlying data.\n Index.to_numpy : A NumPy array representing the underlying data.\n\n Return the underlying data as an ndarray.\n \"\"\"\n return self._data.view(np.ndarray)\n\n @property\n def _values(self):\n # type: () -> Union[ExtensionArray, Index, np.ndarray]\n # TODO(EA): remove index types as they become extension arrays\n \"\"\"\n The best array representation.\n\n This is an ndarray, ExtensionArray, or Index subclass. This differs\n from ``_ndarray_values``, which always returns an ndarray.\n\n Both ``_values`` and ``_ndarray_values`` are consistent between\n ``Series`` and ``Index``.\n\n It may differ from the public '.values' method.\n\n index | values | _values | _ndarray_values |\n ----------------- | --------------- | ------------- | --------------- |\n Index | ndarray | ndarray | ndarray |\n CategoricalIndex | Categorical | Categorical | ndarray[int] |\n DatetimeIndex | ndarray[M8ns] | ndarray[M8ns] | ndarray[M8ns] |\n DatetimeIndex[tz] | ndarray[M8ns] | DTI[tz] | ndarray[M8ns] |\n PeriodIndex | ndarray[object] | PeriodArray | ndarray[int] |\n IntervalIndex | IntervalArray | IntervalArray | ndarray[object] |\n\n See Also\n --------\n values\n _ndarray_values\n \"\"\"\n return self._data\n\n def get_values(self):\n \"\"\"\n Return `Index` data as an `numpy.ndarray`.\n\n Returns\n -------\n numpy.ndarray\n A one-dimensional numpy array of the `Index` values.\n\n See Also\n --------\n Index.values : The attribute that get_values wraps.\n\n Examples\n --------\n Getting the `Index` values of a `DataFrame`:\n\n >>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n ... index=['a', 'b', 'c'], columns=['A', 'B', 'C'])\n >>> df\n A B C\n a 1 2 3\n b 4 5 6\n c 7 8 9\n >>> df.index.get_values()\n array(['a', 'b', 'c'], dtype=object)\n\n Standalone `Index` values:\n\n >>> idx = pd.Index(['1', '2', '3'])\n >>> idx.get_values()\n array(['1', '2', '3'], dtype=object)\n\n `MultiIndex` arrays also have only one dimension:\n\n >>> midx = pd.MultiIndex.from_arrays([[1, 2, 3], ['a', 'b', 'c']],\n ... names=('number', 'letter'))\n >>> midx.get_values()\n array([(1, 'a'), (2, 'b'), (3, 'c')], dtype=object)\n >>> midx.get_values().ndim\n 1\n \"\"\"\n return self.values\n\n @Appender(IndexOpsMixin.memory_usage.__doc__)\n def memory_usage(self, deep=False):\n result = super(Index, self).memory_usage(deep=deep)\n\n # include our engine hashtable\n result += self._engine.sizeof(deep=deep)\n return result\n\n _index_shared_docs['where'] = \"\"\"\n Return an Index of same shape as self and whose corresponding\n entries are from self where cond is True and otherwise are from\n other.\n\n .. versionadded:: 0.19.0\n\n Parameters\n ----------\n cond : boolean array-like with the same length as self\n other : scalar, or array-like\n \"\"\"\n\n @Appender(_index_shared_docs['where'])\n def where(self, cond, other=None):\n if other is None:\n other = self._na_value\n\n dtype = self.dtype\n values = self.values\n\n if is_bool(other) or is_bool_dtype(other):\n\n # bools force casting\n values = values.astype(object)\n dtype = None\n\n values = np.where(cond, values, other)\n\n if self._is_numeric_dtype and np.any(isna(values)):\n # We can't coerce to the numeric dtype of \"self\" (unless\n # it's float) if there are NaN values in our output.\n dtype = None\n\n return self._shallow_copy_with_infer(values, dtype=dtype)\n\n # construction helpers\n @classmethod\n def _try_convert_to_int_index(cls, data, copy, name, dtype):\n \"\"\"\n Attempt to convert an array of data into an integer index.\n\n Parameters\n ----------\n data : The data to convert.\n copy : Whether to copy the data or not.\n name : The name of the index returned.\n\n Returns\n -------\n int_index : data converted to either an Int64Index or a\n UInt64Index\n\n Raises\n ------\n ValueError if the conversion was not successful.\n \"\"\"\n\n from .numeric import Int64Index, UInt64Index\n if not is_unsigned_integer_dtype(dtype):\n # skip int64 conversion attempt if uint-like dtype is passed, as\n # this could return Int64Index when UInt64Index is what's desrired\n try:\n res = data.astype('i8', copy=False)\n if (res == data).all():\n return Int64Index(res, copy=copy, name=name)\n except (OverflowError, TypeError, ValueError):\n pass\n\n # Conversion to int64 failed (possibly due to overflow) or was skipped,\n # so let's try now with uint64.\n try:\n res = data.astype('u8', copy=False)\n if (res == data).all():\n return UInt64Index(res, copy=copy, name=name)\n except (OverflowError, TypeError, ValueError):\n pass\n\n raise ValueError\n\n @classmethod\n def _scalar_data_error(cls, data):\n raise TypeError('{0}(...) must be called with a collection of some '\n 'kind, {1} was passed'.format(cls.__name__,\n repr(data)))\n\n @classmethod\n def _string_data_error(cls, data):\n raise TypeError('String dtype not supported, you may need '\n 'to explicitly cast to a numeric type')\n\n @classmethod\n def _coerce_to_ndarray(cls, data):\n \"\"\"\n Coerces data to ndarray.\n\n Converts other iterables to list first and then to array.\n Does not touch ndarrays.\n\n Raises\n ------\n TypeError\n When the data passed in is a scalar.\n \"\"\"\n\n if not isinstance(data, (np.ndarray, Index)):\n if data is None or is_scalar(data):\n cls._scalar_data_error(data)\n\n # other iterable of some kind\n if not isinstance(data, (ABCSeries, list, tuple)):\n data = list(data)\n data = np.asarray(data)\n return data\n\n def _coerce_scalar_to_index(self, item):\n \"\"\"\n We need to coerce a scalar to a compat for our index type.\n\n Parameters\n ----------\n item : scalar item to coerce\n \"\"\"\n dtype = self.dtype\n\n if self._is_numeric_dtype and isna(item):\n # We can't coerce to the numeric dtype of \"self\" (unless\n # it's float) if there are NaN values in our output.\n dtype = None\n\n return Index([item], dtype=dtype, **self._get_attributes_dict())\n\n def _to_safe_for_reshape(self):\n \"\"\"\n Convert to object if we are a categorical.\n \"\"\"\n return self\n\n def _convert_for_op(self, value):\n \"\"\"\n Convert value to be insertable to ndarray.\n \"\"\"\n return value\n\n def _assert_can_do_op(self, value):\n \"\"\"\n Check value is valid for scalar op.\n \"\"\"\n if not is_scalar(value):\n msg = \"'value' must be a scalar, passed: {0}\"\n raise TypeError(msg.format(type(value).__name__))\n\n @property\n def _has_complex_internals(self):\n # to disable groupby tricks in MultiIndex\n return False\n\n def _is_memory_usage_qualified(self):\n \"\"\"\n Return a boolean if we need a qualified .info display.\n \"\"\"\n return self.is_object()\n\n def is_type_compatible(self, kind):\n return kind == self.inferred_type\n\n _index_shared_docs['contains'] = \"\"\"\n Return a boolean indicating whether the provided key is in the index.\n\n Parameters\n ----------\n key : label\n The key to check if it is present in the index.\n\n Returns\n -------\n bool\n Whether the key search is in the index.\n\n See Also\n --------\n Index.isin : Returns an ndarray of boolean dtype indicating whether the\n list-like key is in the index.\n\n Examples\n --------\n >>> idx = pd.Index([1, 2, 3, 4])\n >>> idx\n Int64Index([1, 2, 3, 4], dtype='int64')\n\n >>> idx.contains(2)\n True\n >>> idx.contains(6)\n False\n\n This is equivalent to:\n\n >>> 2 in idx\n True\n >>> 6 in idx\n False\n \"\"\"\n\n @Appender(_index_shared_docs['contains'] % _index_doc_kwargs)\n def __contains__(self, key):\n hash(key)\n try:\n return key in self._engine\n except (OverflowError, TypeError, ValueError):\n return False\n\n @Appender(_index_shared_docs['contains'] % _index_doc_kwargs)\n def contains(self, key):\n hash(key)\n try:\n return key in self._engine\n except (TypeError, ValueError):\n return False\n\n def __hash__(self):\n raise TypeError(\"unhashable type: %r\" % type(self).__name__)\n\n def __setitem__(self, key, value):\n raise TypeError(\"Index does not support mutable operations\")\n\n def __getitem__(self, key):\n \"\"\"\n Override numpy.ndarray's __getitem__ method to work as desired.\n\n This function adds lists and Series as valid boolean indexers\n (ndarrays only supports ndarray with dtype=bool).\n\n If resulting ndim != 1, plain ndarray is returned instead of\n corresponding `Index` subclass.\n\n \"\"\"\n # There's no custom logic to be implemented in __getslice__, so it's\n # not overloaded intentionally.\n getitem = self._data.__getitem__\n promote = self._shallow_copy\n\n if is_scalar(key):\n key = com.cast_scalar_indexer(key)\n return getitem(key)\n\n if isinstance(key, slice):\n # This case is separated from the conditional above to avoid\n # pessimization of basic indexing.\n return promote(getitem(key))\n\n if com.is_bool_indexer(key):\n key = np.asarray(key, dtype=bool)\n\n key = com.values_from_object(key)\n result = getitem(key)\n if not is_scalar(result):\n return promote(result)\n else:\n return result\n\n def _can_hold_identifiers_and_holds_name(self, name):\n \"\"\"\n Faster check for ``name in self`` when we know `name` is a Python\n identifier (e.g. in NDFrame.__getattr__, which hits this to support\n . key lookup). For indexes that can't hold identifiers (everything\n but object & categorical) we just return False.\n\n https://github.com/pandas-dev/pandas/issues/19764\n \"\"\"\n if self.is_object() or self.is_categorical():\n return name in self\n return False\n\n def append(self, other):\n \"\"\"\n Append a collection of Index options together.\n\n Parameters\n ----------\n other : Index or list/tuple of indices\n\n Returns\n -------\n appended : Index\n \"\"\"\n\n to_concat = [self]\n\n if isinstance(other, (list, tuple)):\n to_concat = to_concat + list(other)\n else:\n to_concat.append(other)\n\n for obj in to_concat:\n if not isinstance(obj, Index):\n raise TypeError('all inputs must be Index')\n\n names = {obj.name for obj in to_concat}\n name = None if len(names) > 1 else self.name\n\n return self._concat(to_concat, name)\n\n def _concat(self, to_concat, name):\n\n typs = _concat.get_dtype_kinds(to_concat)\n\n if len(typs) == 1:\n return self._concat_same_dtype(to_concat, name=name)\n return _concat._concat_index_asobject(to_concat, name=name)\n\n def _concat_same_dtype(self, to_concat, name):\n \"\"\"\n Concatenate to_concat which has the same class.\n \"\"\"\n # must be overridden in specific classes\n return _concat._concat_index_asobject(to_concat, name)\n\n def putmask(self, mask, value):\n \"\"\"\n Return a new Index of the values set with the mask.\n\n See Also\n --------\n numpy.ndarray.putmask\n \"\"\"\n values = self.values.copy()\n try:\n np.putmask(values, mask, self._convert_for_op(value))\n return self._shallow_copy(values)\n except (ValueError, TypeError) as err:\n if is_object_dtype(self):\n raise err\n\n # coerces to object\n return self.astype(object).putmask(mask, value)\n\n def equals(self, other):\n \"\"\"\n Determine if two Index objects contain the same elements.\n \"\"\"\n if self.is_(other):\n return True\n\n if not isinstance(other, Index):\n return False\n\n if is_object_dtype(self) and not is_object_dtype(other):\n # if other is not object, use other's logic for coercion\n return other.equals(self)\n\n try:\n return array_equivalent(com.values_from_object(self),\n com.values_from_object(other))\n except Exception:\n return False\n\n def identical(self, other):\n \"\"\"\n Similar to equals, but check that other comparable attributes are\n also equal.\n \"\"\"\n return (self.equals(other) and\n all((getattr(self, c, None) == getattr(other, c, None)\n for c in self._comparables)) and\n type(self) == type(other))\n\n def asof(self, label):\n \"\"\"\n Return the label from the index, or, if not present, the previous one.\n\n Assuming that the index is sorted, return the passed index label if it\n is in the index, or return the previous index label if the passed one\n is not in the index.\n\n Parameters\n ----------\n label : object\n The label up to which the method returns the latest index label.\n\n Returns\n -------\n object\n The passed label if it is in the index. The previous label if the\n passed label is not in the sorted index or `NaN` if there is no\n such label.\n\n See Also\n --------\n Series.asof : Return the latest value in a Series up to the\n passed index.\n merge_asof : Perform an asof merge (similar to left join but it\n matches on nearest key rather than equal key).\n Index.get_loc : An `asof` is a thin wrapper around `get_loc`\n with method='pad'.\n\n Examples\n --------\n `Index.asof` returns the latest index label up to the passed label.\n\n >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03'])\n >>> idx.asof('2014-01-01')\n '2013-12-31'\n\n If the label is in the index, the method returns the passed label.\n\n >>> idx.asof('2014-01-02')\n '2014-01-02'\n\n If all of the labels in the index are later than the passed label,\n NaN is returned.\n\n >>> idx.asof('1999-01-02')\n nan\n\n If the index is not sorted, an error is raised.\n\n >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02',\n ... '2014-01-03'])\n >>> idx_not_sorted.asof('2013-12-31')\n Traceback (most recent call last):\n ValueError: index must be monotonic increasing or decreasing\n \"\"\"\n try:\n loc = self.get_loc(label, method='pad')\n except KeyError:\n return self._na_value\n else:\n if isinstance(loc, slice):\n loc = loc.indices(len(self))[-1]\n return self[loc]\n\n def asof_locs(self, where, mask):\n \"\"\"\n Find the locations (indices) of the labels from the index for\n every entry in the `where` argument.\n\n As in the `asof` function, if the label (a particular entry in\n `where`) is not in the index, the latest index label upto the\n passed label is chosen and its index returned.\n\n If all of the labels in the index are later than a label in `where`,\n -1 is returned.\n\n `mask` is used to ignore NA values in the index during calculation.\n\n Parameters\n ----------\n where : Index\n An Index consisting of an array of timestamps.\n mask : array-like\n Array of booleans denoting where values in the original\n data are not NA.\n\n Returns\n -------\n numpy.ndarray\n An array of locations (indices) of the labels from the Index\n which correspond to the return values of the `asof` function\n for every element in `where`.\n \"\"\"\n locs = self.values[mask].searchsorted(where.values, side='right')\n locs = np.where(locs > 0, locs - 1, 0)\n\n result = np.arange(len(self))[mask].take(locs)\n\n first = mask.argmax()\n result[(locs == 0) & (where.values < self.values[first])] = -1\n\n return result\n\n def sort_values(self, return_indexer=False, ascending=True):\n \"\"\"\n Return a sorted copy of the index.\n\n Return a sorted copy of the index, and optionally return the indices\n that sorted the index itself.\n\n Parameters\n ----------\n return_indexer : bool, default False\n Should the indices that would sort the index be returned.\n ascending : bool, default True\n Should the index values be sorted in an ascending order.\n\n Returns\n -------\n sorted_index : pandas.Index\n Sorted copy of the index.\n indexer : numpy.ndarray, optional\n The indices that the index itself was sorted by.\n\n See Also\n --------\n Series.sort_values : Sort values of a Series.\n DataFrame.sort_values : Sort values in a DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index([10, 100, 1, 1000])\n >>> idx\n Int64Index([10, 100, 1, 1000], dtype='int64')\n\n Sort values in ascending order (default behavior).\n\n >>> idx.sort_values()\n Int64Index([1, 10, 100, 1000], dtype='int64')\n\n Sort values in descending order, and also get the indices `idx` was\n sorted by.\n\n >>> idx.sort_values(ascending=False, return_indexer=True)\n (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))\n \"\"\"\n _as = self.argsort()\n if not ascending:\n _as = _as[::-1]\n\n sorted_index = self.take(_as)\n\n if return_indexer:\n return sorted_index, _as\n else:\n return sorted_index\n\n def sort(self, *args, **kwargs):\n raise TypeError(\"cannot sort an Index object in-place, use \"\n \"sort_values instead\")\n\n def shift(self, periods=1, freq=None):\n \"\"\"\n Shift index by desired number of time frequency increments.\n\n This method is for shifting the values of datetime-like indexes\n by a specified time increment a given number of times.\n\n Parameters\n ----------\n periods : int, default 1\n Number of periods (or increments) to shift by,\n can be positive or negative.\n freq : pandas.DateOffset, pandas.Timedelta or string, optional\n Frequency increment to shift by.\n If None, the index is shifted by its own `freq` attribute.\n Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc.\n\n Returns\n -------\n pandas.Index\n Shifted index.\n\n See Also\n --------\n Series.shift : Shift values of Series.\n\n Notes\n -----\n This method is only implemented for datetime-like index classes,\n i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex.\n\n Examples\n --------\n Put the first 5 month starts of 2011 into an index.\n\n >>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS')\n >>> month_starts\n DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01',\n '2011-05-01'],\n dtype='datetime64[ns]', freq='MS')\n\n Shift the index by 10 days.\n\n >>> month_starts.shift(10, freq='D')\n DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11',\n '2011-05-11'],\n dtype='datetime64[ns]', freq=None)\n\n The default value of `freq` is the `freq` attribute of the index,\n which is 'MS' (month start) in this example.\n\n >>> month_starts.shift(10)\n DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01',\n '2012-03-01'],\n dtype='datetime64[ns]', freq='MS')\n \"\"\"\n raise NotImplementedError(\"Not supported for type %s\" %\n type(self).__name__)\n\n def argsort(self, *args, **kwargs):\n \"\"\"\n Return the integer indices that would sort the index.\n\n Parameters\n ----------\n *args\n Passed to `numpy.ndarray.argsort`.\n **kwargs\n Passed to `numpy.ndarray.argsort`.\n\n Returns\n -------\n numpy.ndarray\n Integer indices that would sort the index if used as\n an indexer.\n\n See Also\n --------\n numpy.argsort : Similar method for NumPy arrays.\n Index.sort_values : Return sorted copy of Index.\n\n Examples\n --------\n >>> idx = pd.Index(['b', 'a', 'd', 'c'])\n >>> idx\n Index(['b', 'a', 'd', 'c'], dtype='object')\n\n >>> order = idx.argsort()\n >>> order\n array([1, 0, 3, 2])\n\n >>> idx[order]\n Index(['a', 'b', 'c', 'd'], dtype='object')\n \"\"\"\n result = self.asi8\n if result is None:\n result = np.array(self)\n return result.argsort(*args, **kwargs)\n\n def get_value(self, series, key):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing.\n \"\"\"\n\n # if we have something that is Index-like, then\n # use this, e.g. DatetimeIndex\n # Things like `Series._get_value` (via .at) pass the EA directly here.\n s = getattr(series, '_values', series)\n if isinstance(s, (ExtensionArray, Index)) and is_scalar(key):\n # GH 20882, 21257\n # Unify Index and ExtensionArray treatment\n # First try to convert the key to a location\n # If that fails, raise a KeyError if an integer\n # index, otherwise, see if key is an integer, and\n # try that\n try:\n iloc = self.get_loc(key)\n return s[iloc]\n except KeyError:\n if (len(self) > 0 and\n (self.holds_integer() or self.is_boolean())):\n raise\n elif is_integer(key):\n return s[key]\n\n s = com.values_from_object(series)\n k = com.values_from_object(key)\n\n k = self._convert_scalar_indexer(k, kind='getitem')\n try:\n return self._engine.get_value(s, k,\n tz=getattr(series.dtype, 'tz', None))\n except KeyError as e1:\n if len(self) > 0 and (self.holds_integer() or self.is_boolean()):\n raise\n\n try:\n return libindex.get_value_box(s, key)\n except IndexError:\n raise\n except TypeError:\n # generator/iterator-like\n if is_iterator(key):\n raise InvalidIndexError(key)\n else:\n raise e1\n except Exception: # pragma: no cover\n raise e1\n except TypeError:\n # python 3\n if is_scalar(key): # pragma: no cover\n raise IndexError(key)\n raise InvalidIndexError(key)\n\n def set_value(self, arr, key, value):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray.\n\n Notes\n -----\n Only use this if you know what you're doing.\n \"\"\"\n self._engine.set_value(com.values_from_object(arr),\n com.values_from_object(key), value)\n\n _index_shared_docs['get_indexer_non_unique'] = \"\"\"\n Compute indexer and mask for new index given the current index. The\n indexer should be then used as an input to ndarray.take to align the\n current data to the new index.\n\n Parameters\n ----------\n target : %(target_klass)s\n\n Returns\n -------\n indexer : ndarray of int\n Integers from 0 to n - 1 indicating that the index at these\n positions matches the corresponding target values. Missing values\n in the target are marked by -1.\n missing : ndarray of int\n An indexer into the target of the values not found.\n These correspond to the -1 in the indexer array.\n \"\"\"\n\n @Appender(_index_shared_docs['get_indexer_non_unique'] % _index_doc_kwargs)\n def get_indexer_non_unique(self, target):\n target = ensure_index(target)\n if is_categorical(target):\n target = target.astype(target.dtype.categories.dtype)\n pself, ptarget = self._maybe_promote(target)\n if pself is not self or ptarget is not target:\n return pself.get_indexer_non_unique(ptarget)\n\n if self.is_all_dates:\n self = Index(self.asi8)\n tgt_values = target.asi8\n else:\n tgt_values = target._ndarray_values\n\n indexer, missing = self._engine.get_indexer_non_unique(tgt_values)\n return ensure_platform_int(indexer), missing\n\n def get_indexer_for(self, target, **kwargs):\n \"\"\"\n Guaranteed return of an indexer even when non-unique.\n\n This dispatches to get_indexer or get_indexer_nonunique\n as appropriate.\n \"\"\"\n if self.is_unique:\n return self.get_indexer(target, **kwargs)\n indexer, _ = self.get_indexer_non_unique(target, **kwargs)\n return indexer\n\n def _maybe_promote(self, other):\n # A hack, but it works\n from pandas import DatetimeIndex\n if self.inferred_type == 'date' and isinstance(other, DatetimeIndex):\n return DatetimeIndex(self), other\n elif self.inferred_type == 'boolean':\n if not is_object_dtype(self.dtype):\n return self.astype('object'), other.astype('object')\n return self, other\n\n def groupby(self, values):\n \"\"\"\n Group the index labels by a given array of values.\n\n Parameters\n ----------\n values : array\n Values used to determine the groups.\n\n Returns\n -------\n groups : dict\n {group name -> group labels}\n \"\"\"\n\n # TODO: if we are a MultiIndex, we can do better\n # that converting to tuples\n if isinstance(values, ABCMultiIndex):\n values = values.values\n values = ensure_categorical(values)\n result = values._reverse_indexer()\n\n # map to the label\n result = {k: self.take(v) for k, v in compat.iteritems(result)}\n\n return result\n\n def map(self, mapper, na_action=None):\n \"\"\"\n Map values using input correspondence (a dict, Series, or function).\n\n Parameters\n ----------\n mapper : function, dict, or Series\n Mapping correspondence.\n na_action : {None, 'ignore'}\n If 'ignore', propagate NA values, without passing them to the\n mapping correspondence.\n\n Returns\n -------\n applied : Union[Index, MultiIndex], inferred\n The output of the mapping function applied to the index.\n If the function returns a tuple with more than one element\n a MultiIndex will be returned.\n \"\"\"\n\n from .multi import MultiIndex\n new_values = super(Index, self)._map_values(\n mapper, na_action=na_action)\n\n attributes = self._get_attributes_dict()\n\n # we can return a MultiIndex\n if new_values.size and isinstance(new_values[0], tuple):\n if isinstance(self, MultiIndex):\n names = self.names\n elif attributes.get('name'):\n names = [attributes.get('name')] * len(new_values[0])\n else:\n names = None\n return MultiIndex.from_tuples(new_values,\n names=names)\n\n attributes['copy'] = False\n if not new_values.size:\n # empty\n attributes['dtype'] = self.dtype\n\n return Index(new_values, **attributes)\n\n def isin(self, values, level=None):\n \"\"\"\n Return a boolean array where the index values are in `values`.\n\n Compute boolean array of whether each index value is found in the\n passed set of values. The length of the returned boolean array matches\n the length of the index.\n\n Parameters\n ----------\n values : set or list-like\n Sought values.\n\n .. versionadded:: 0.18.1\n\n Support for values as a set.\n\n level : str or int, optional\n Name or position of the index level to use (if the index is a\n `MultiIndex`).\n\n Returns\n -------\n is_contained : ndarray\n NumPy array of boolean values.\n\n See Also\n --------\n Series.isin : Same for Series.\n DataFrame.isin : Same method for DataFrames.\n\n Notes\n -----\n In the case of `MultiIndex` you must either specify `values` as a\n list-like object containing tuples that are the same length as the\n number of levels, or specify `level`. Otherwise it will raise a\n ``ValueError``.\n\n If `level` is specified:\n\n - if it is the name of one *and only one* index level, use that level;\n - otherwise it should be a number indicating level position.\n\n Examples\n --------\n >>> idx = pd.Index([1,2,3])\n >>> idx\n Int64Index([1, 2, 3], dtype='int64')\n\n Check whether each index value in a list of values.\n >>> idx.isin([1, 4])\n array([ True, False, False])\n\n >>> midx = pd.MultiIndex.from_arrays([[1,2,3],\n ... ['red', 'blue', 'green']],\n ... names=('number', 'color'))\n >>> midx\n MultiIndex(levels=[[1, 2, 3], ['blue', 'green', 'red']],\n codes=[[0, 1, 2], [2, 0, 1]],\n names=['number', 'color'])\n\n Check whether the strings in the 'color' level of the MultiIndex\n are in a list of colors.\n\n >>> midx.isin(['red', 'orange', 'yellow'], level='color')\n array([ True, False, False])\n\n To check across the levels of a MultiIndex, pass a list of tuples:\n\n >>> midx.isin([(1, 'red'), (3, 'red')])\n array([ True, False, False])\n\n For a DatetimeIndex, string values in `values` are converted to\n Timestamps.\n\n >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13']\n >>> dti = pd.to_datetime(dates)\n >>> dti\n DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'],\n dtype='datetime64[ns]', freq=None)\n\n >>> dti.isin(['2000-03-11'])\n array([ True, False, False])\n \"\"\"\n if level is not None:\n self._validate_index_level(level)\n return algos.isin(self, values)\n\n def _get_string_slice(self, key, use_lhs=True, use_rhs=True):\n # this is for partial string indexing,\n # overridden in DatetimeIndex, TimedeltaIndex and PeriodIndex\n raise NotImplementedError\n\n def slice_indexer(self, start=None, end=None, step=None, kind=None):\n \"\"\"\n For an ordered or unique index, compute the slice indexer for input\n labels and step.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n step : int, default None\n kind : string, default None\n\n Returns\n -------\n indexer : slice\n\n Raises\n ------\n KeyError : If key does not exist, or key is not unique and index is\n not ordered.\n\n Notes\n -----\n This function assumes that the data is sorted, so use at your own peril\n\n Examples\n ---------\n This is a method on all index types. For example you can do:\n\n >>> idx = pd.Index(list('abcd'))\n >>> idx.slice_indexer(start='b', end='c')\n slice(1, 3)\n\n >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')])\n >>> idx.slice_indexer(start='b', end=('c', 'g'))\n slice(1, 3)\n \"\"\"\n start_slice, end_slice = self.slice_locs(start, end, step=step,\n kind=kind)\n\n # return a slice\n if not is_scalar(start_slice):\n raise AssertionError(\"Start slice bound is non-scalar\")\n if not is_scalar(end_slice):\n raise AssertionError(\"End slice bound is non-scalar\")\n\n return slice(start_slice, end_slice, step)\n\n def _maybe_cast_indexer(self, key):\n \"\"\"\n If we have a float key and are not a floating index, then try to cast\n to an int if equivalent.\n \"\"\"\n\n if is_float(key) and not self.is_floating():\n try:\n ckey = int(key)\n if ckey == key:\n key = ckey\n except (OverflowError, ValueError, TypeError):\n pass\n return key\n\n def _validate_indexer(self, form, key, kind):\n \"\"\"\n If we are positional indexer, validate that we have appropriate\n typed bounds must be an integer.\n \"\"\"\n assert kind in ['ix', 'loc', 'getitem', 'iloc']\n\n if key is None:\n pass\n elif is_integer(key):\n pass\n elif kind in ['iloc', 'getitem']:\n self._invalid_indexer(form, key)\n return key\n\n _index_shared_docs['_maybe_cast_slice_bound'] = \"\"\"\n This function should be overloaded in subclasses that allow non-trivial\n casting on label-slice bounds, e.g. datetime-like indices allowing\n strings containing formatted datetimes.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}\n\n Returns\n -------\n label : object\n\n Notes\n -----\n Value of `side` parameter should be validated in caller.\n\n \"\"\"\n\n @Appender(_index_shared_docs['_maybe_cast_slice_bound'])\n def _maybe_cast_slice_bound(self, label, side, kind):\n assert kind in ['ix', 'loc', 'getitem', None]\n\n # We are a plain index here (sub-class override this method if they\n # wish to have special treatment for floats/ints, e.g. Float64Index and\n # datetimelike Indexes\n # reject them\n if is_float(label):\n if not (kind in ['ix'] and (self.holds_integer() or\n self.is_floating())):\n self._invalid_indexer('slice', label)\n\n # we are trying to find integer bounds on a non-integer based index\n # this is rejected (generally .loc gets you here)\n elif is_integer(label):\n self._invalid_indexer('slice', label)\n\n return label\n\n def _searchsorted_monotonic(self, label, side='left'):\n if self.is_monotonic_increasing:\n return self.searchsorted(label, side=side)\n elif self.is_monotonic_decreasing:\n # np.searchsorted expects ascending sort order, have to reverse\n # everything for it to work (element ordering, search side and\n # resulting value).\n pos = self[::-1].searchsorted(label, side='right' if side == 'left'\n else 'left')\n return len(self) - pos\n\n raise ValueError('index must be monotonic increasing or decreasing')\n\n def _get_loc_only_exact_matches(self, key):\n \"\"\"\n This is overridden on subclasses (namely, IntervalIndex) to control\n get_slice_bound.\n \"\"\"\n return self.get_loc(key)\n\n def get_slice_bound(self, label, side, kind):\n \"\"\"\n Calculate slice bound that corresponds to given label.\n\n Returns leftmost (one-past-the-rightmost if ``side=='right'``) position\n of given label.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'ix', 'loc', 'getitem'}\n \"\"\"\n assert kind in ['ix', 'loc', 'getitem', None]\n\n if side not in ('left', 'right'):\n raise ValueError(\"Invalid value for side kwarg,\"\n \" must be either 'left' or 'right': %s\" %\n (side, ))\n\n original_label = label\n\n # For datetime indices label may be a string that has to be converted\n # to datetime boundary according to its resolution.\n label = self._maybe_cast_slice_bound(label, side, kind)\n\n # we need to look up the label\n try:\n slc = self._get_loc_only_exact_matches(label)\n except KeyError as err:\n try:\n return self._searchsorted_monotonic(label, side)\n except ValueError:\n # raise the original KeyError\n raise err\n\n if isinstance(slc, np.ndarray):\n # get_loc may return a boolean array or an array of indices, which\n # is OK as long as they are representable by a slice.\n if is_bool_dtype(slc):\n slc = lib.maybe_booleans_to_slice(slc.view('u1'))\n else:\n slc = lib.maybe_indices_to_slice(slc.astype('i8'), len(self))\n if isinstance(slc, np.ndarray):\n raise KeyError(\"Cannot get %s slice bound for non-unique \"\n \"label: %r\" % (side, original_label))\n\n if isinstance(slc, slice):\n if side == 'left':\n return slc.start\n else:\n return slc.stop\n else:\n if side == 'right':\n return slc + 1\n else:\n return slc\n\n def slice_locs(self, start=None, end=None, step=None, kind=None):\n \"\"\"\n Compute slice locations for input labels.\n\n Parameters\n ----------\n start : label, default None\n If None, defaults to the beginning\n end : label, default None\n If None, defaults to the end\n step : int, defaults None\n If None, defaults to 1\n kind : {'ix', 'loc', 'getitem'} or None\n\n Returns\n -------\n start, end : int\n\n See Also\n --------\n Index.get_loc : Get location for a single label.\n\n Notes\n -----\n This method only works if the index is monotonic or unique.\n\n Examples\n ---------\n >>> idx = pd.Index(list('abcd'))\n >>> idx.slice_locs(start='b', end='c')\n (1, 3)\n \"\"\"\n inc = (step is None or step >= 0)\n\n if not inc:\n # If it's a reverse slice, temporarily swap bounds.\n start, end = end, start\n\n # GH 16785: If start and end happen to be date strings with UTC offsets\n # attempt to parse and check that the offsets are the same\n if (isinstance(start, (compat.string_types, datetime))\n and isinstance(end, (compat.string_types, datetime))):\n try:\n ts_start = Timestamp(start)\n ts_end = Timestamp(end)\n except (ValueError, TypeError):\n pass\n else:\n if not tz_compare(ts_start.tzinfo, ts_end.tzinfo):\n raise ValueError(\"Both dates must have the \"\n \"same UTC offset\")\n\n start_slice = None\n if start is not None:\n start_slice = self.get_slice_bound(start, 'left', kind)\n if start_slice is None:\n start_slice = 0\n\n end_slice = None\n if end is not None:\n end_slice = self.get_slice_bound(end, 'right', kind)\n if end_slice is None:\n end_slice = len(self)\n\n if not inc:\n # Bounds at this moment are swapped, swap them back and shift by 1.\n #\n # slice_locs('B', 'A', step=-1): s='B', e='A'\n #\n # s='A' e='B'\n # AFTER SWAP: | |\n # v ------------------> V\n # -----------------------------------\n # | | |A|A|A|A| | | | | |B|B| | | | |\n # -----------------------------------\n # ^ <------------------ ^\n # SHOULD BE: | |\n # end=s-1 start=e-1\n #\n end_slice, start_slice = start_slice - 1, end_slice - 1\n\n # i == -1 triggers ``len(self) + i`` selection that points to the\n # last element, not before-the-first one, subtracting len(self)\n # compensates that.\n if end_slice == -1:\n end_slice -= len(self)\n if start_slice == -1:\n start_slice -= len(self)\n\n return start_slice, end_slice\n\n def delete(self, loc):\n \"\"\"\n Make new Index with passed location(-s) deleted.\n\n Returns\n -------\n new_index : Index\n \"\"\"\n return self._shallow_copy(np.delete(self._data, loc))\n\n def insert(self, loc, item):\n \"\"\"\n Make new Index inserting new item at location.\n\n Follows Python list.append semantics for negative values.\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n new_index : Index\n \"\"\"\n _self = np.asarray(self)\n item = self._coerce_scalar_to_index(item)._ndarray_values\n idx = np.concatenate((_self[:loc], item, _self[loc:]))\n return self._shallow_copy_with_infer(idx)\n\n def drop(self, labels, errors='raise'):\n \"\"\"\n Make new Index with passed list of labels deleted.\n\n Parameters\n ----------\n labels : array-like\n errors : {'ignore', 'raise'}, default 'raise'\n If 'ignore', suppress error and existing labels are dropped.\n\n Returns\n -------\n dropped : Index\n\n Raises\n ------\n KeyError\n If not all of the labels are found in the selected axis\n \"\"\"\n arr_dtype = 'object' if self.dtype == 'object' else None\n labels = com.index_labels_to_array(labels, dtype=arr_dtype)\n indexer = self.get_indexer(labels)\n mask = indexer == -1\n if mask.any():\n if errors != 'ignore':\n raise KeyError(\n '{} not found in axis'.format(labels[mask]))\n indexer = indexer[~mask]\n return self.delete(indexer)\n\n # --------------------------------------------------------------------\n # Generated Arithmetic, Comparison, and Unary Methods\n\n def _evaluate_with_timedelta_like(self, other, op):\n # Timedelta knows how to operate with np.array, so dispatch to that\n # operation and then wrap the results\n if self._is_numeric_dtype and op.__name__ in ['add', 'sub',\n 'radd', 'rsub']:\n raise TypeError(\"Operation {opname} between {cls} and {other} \"\n \"is invalid\".format(opname=op.__name__,\n cls=self.dtype,\n other=type(other).__name__))\n\n other = Timedelta(other)\n values = self.values\n\n with np.errstate(all='ignore'):\n result = op(values, other)\n\n attrs = self._get_attributes_dict()\n attrs = self._maybe_update_attributes(attrs)\n if op == divmod:\n return Index(result[0], **attrs), Index(result[1], **attrs)\n return Index(result, **attrs)\n\n def _evaluate_with_datetime_like(self, other, op):\n raise TypeError(\"can only perform ops with datetime like values\")\n\n @classmethod\n def _add_comparison_methods(cls):\n \"\"\"\n Add in comparison methods.\n \"\"\"\n cls.__eq__ = _make_comparison_op(operator.eq, cls)\n cls.__ne__ = _make_comparison_op(operator.ne, cls)\n cls.__lt__ = _make_comparison_op(operator.lt, cls)\n cls.__gt__ = _make_comparison_op(operator.gt, cls)\n cls.__le__ = _make_comparison_op(operator.le, cls)\n cls.__ge__ = _make_comparison_op(operator.ge, cls)\n\n @classmethod\n def _add_numeric_methods_add_sub_disabled(cls):\n \"\"\"\n Add in the numeric add/sub methods to disable.\n \"\"\"\n cls.__add__ = make_invalid_op('__add__')\n cls.__radd__ = make_invalid_op('__radd__')\n cls.__iadd__ = make_invalid_op('__iadd__')\n cls.__sub__ = make_invalid_op('__sub__')\n cls.__rsub__ = make_invalid_op('__rsub__')\n cls.__isub__ = make_invalid_op('__isub__')\n\n @classmethod\n def _add_numeric_methods_disabled(cls):\n \"\"\"\n Add in numeric methods to disable other than add/sub.\n \"\"\"\n cls.__pow__ = make_invalid_op('__pow__')\n cls.__rpow__ = make_invalid_op('__rpow__')\n cls.__mul__ = make_invalid_op('__mul__')\n cls.__rmul__ = make_invalid_op('__rmul__')\n cls.__floordiv__ = make_invalid_op('__floordiv__')\n cls.__rfloordiv__ = make_invalid_op('__rfloordiv__')\n cls.__truediv__ = make_invalid_op('__truediv__')\n cls.__rtruediv__ = make_invalid_op('__rtruediv__')\n if not compat.PY3:\n cls.__div__ = make_invalid_op('__div__')\n cls.__rdiv__ = make_invalid_op('__rdiv__')\n cls.__mod__ = make_invalid_op('__mod__')\n cls.__divmod__ = make_invalid_op('__divmod__')\n cls.__neg__ = make_invalid_op('__neg__')\n cls.__pos__ = make_invalid_op('__pos__')\n cls.__abs__ = make_invalid_op('__abs__')\n cls.__inv__ = make_invalid_op('__inv__')\n\n def _maybe_update_attributes(self, attrs):\n \"\"\"\n Update Index attributes (e.g. freq) depending on op.\n \"\"\"\n return attrs\n\n def _validate_for_numeric_unaryop(self, op, opstr):\n \"\"\"\n Validate if we can perform a numeric unary operation.\n \"\"\"\n if not self._is_numeric_dtype:\n raise TypeError(\"cannot evaluate a numeric op \"\n \"{opstr} for type: {typ}\"\n .format(opstr=opstr, typ=type(self).__name__))\n\n def _validate_for_numeric_binop(self, other, op):\n \"\"\"\n Return valid other; evaluate or raise TypeError if we are not of\n the appropriate type.\n\n Notes\n -----\n This is an internal method called by ops.\n \"\"\"\n opstr = '__{opname}__'.format(opname=op.__name__)\n # if we are an inheritor of numeric,\n # but not actually numeric (e.g. DatetimeIndex/PeriodIndex)\n if not self._is_numeric_dtype:\n raise TypeError(\"cannot evaluate a numeric op {opstr} \"\n \"for type: {typ}\"\n .format(opstr=opstr, typ=type(self).__name__))\n\n if isinstance(other, Index):\n if not other._is_numeric_dtype:\n raise TypeError(\"cannot evaluate a numeric op \"\n \"{opstr} with type: {typ}\"\n .format(opstr=opstr, typ=type(other)))\n elif isinstance(other, np.ndarray) and not other.ndim:\n other = other.item()\n\n if isinstance(other, (Index, ABCSeries, np.ndarray)):\n if len(self) != len(other):\n raise ValueError(\"cannot evaluate a numeric op with \"\n \"unequal lengths\")\n other = com.values_from_object(other)\n if other.dtype.kind not in ['f', 'i', 'u']:\n raise TypeError(\"cannot evaluate a numeric op \"\n \"with a non-numeric dtype\")\n elif isinstance(other, (ABCDateOffset, np.timedelta64, timedelta)):\n # higher up to handle\n pass\n elif isinstance(other, (datetime, np.datetime64)):\n # higher up to handle\n pass\n else:\n if not (is_float(other) or is_integer(other)):\n raise TypeError(\"can only perform ops with scalar values\")\n\n return other\n\n @classmethod\n def _add_numeric_methods_binary(cls):\n \"\"\"\n Add in numeric methods.\n \"\"\"\n cls.__add__ = _make_arithmetic_op(operator.add, cls)\n cls.__radd__ = _make_arithmetic_op(ops.radd, cls)\n cls.__sub__ = _make_arithmetic_op(operator.sub, cls)\n cls.__rsub__ = _make_arithmetic_op(ops.rsub, cls)\n cls.__rpow__ = _make_arithmetic_op(ops.rpow, cls)\n cls.__pow__ = _make_arithmetic_op(operator.pow, cls)\n\n cls.__truediv__ = _make_arithmetic_op(operator.truediv, cls)\n cls.__rtruediv__ = _make_arithmetic_op(ops.rtruediv, cls)\n if not compat.PY3:\n cls.__div__ = _make_arithmetic_op(operator.div, cls)\n cls.__rdiv__ = _make_arithmetic_op(ops.rdiv, cls)\n\n # TODO: rmod? rdivmod?\n cls.__mod__ = _make_arithmetic_op(operator.mod, cls)\n cls.__floordiv__ = _make_arithmetic_op(operator.floordiv, cls)\n cls.__rfloordiv__ = _make_arithmetic_op(ops.rfloordiv, cls)\n cls.__divmod__ = _make_arithmetic_op(divmod, cls)\n cls.__mul__ = _make_arithmetic_op(operator.mul, cls)\n cls.__rmul__ = _make_arithmetic_op(ops.rmul, cls)\n\n @classmethod\n def _add_numeric_methods_unary(cls):\n \"\"\"\n Add in numeric unary methods.\n \"\"\"\n def _make_evaluate_unary(op, opstr):\n\n def _evaluate_numeric_unary(self):\n\n self._validate_for_numeric_unaryop(op, opstr)\n attrs = self._get_attributes_dict()\n attrs = self._maybe_update_attributes(attrs)\n return Index(op(self.values), **attrs)\n\n _evaluate_numeric_unary.__name__ = opstr\n return _evaluate_numeric_unary\n\n cls.__neg__ = _make_evaluate_unary(operator.neg, '__neg__')\n cls.__pos__ = _make_evaluate_unary(operator.pos, '__pos__')\n cls.__abs__ = _make_evaluate_unary(np.abs, '__abs__')\n cls.__inv__ = _make_evaluate_unary(lambda x: -x, '__inv__')\n\n @classmethod\n def _add_numeric_methods(cls):\n cls._add_numeric_methods_unary()\n cls._add_numeric_methods_binary()\n\n @classmethod\n def _add_logical_methods(cls):\n \"\"\"\n Add in logical methods.\n \"\"\"\n _doc = \"\"\"\n %(desc)s\n\n Parameters\n ----------\n *args\n These parameters will be passed to numpy.%(outname)s.\n **kwargs\n These parameters will be passed to numpy.%(outname)s.\n\n Returns\n -------\n %(outname)s : bool or array_like (if axis is specified)\n A single element array_like may be converted to bool.\"\"\"\n\n _index_shared_docs['index_all'] = dedent(\"\"\"\n\n See Also\n --------\n Index.any : Return whether any element in an Index is True.\n Series.any : Return whether any element in a Series is True.\n Series.all : Return whether all elements in a Series are True.\n\n Notes\n -----\n Not a Number (NaN), positive infinity and negative infinity\n evaluate to True because these are not equal to zero.\n\n Examples\n --------\n **all**\n\n True, because nonzero integers are considered True.\n\n >>> pd.Index([1, 2, 3]).all()\n True\n\n False, because ``0`` is considered False.\n\n >>> pd.Index([0, 1, 2]).all()\n False\n\n **any**\n\n True, because ``1`` is considered True.\n\n >>> pd.Index([0, 0, 1]).any()\n True\n\n False, because ``0`` is considered False.\n\n >>> pd.Index([0, 0, 0]).any()\n False\n \"\"\")\n\n _index_shared_docs['index_any'] = dedent(\"\"\"\n\n See Also\n --------\n Index.all : Return whether all elements are True.\n Series.all : Return whether all elements are True.\n\n Notes\n -----\n Not a Number (NaN), positive infinity and negative infinity\n evaluate to True because these are not equal to zero.\n\n Examples\n --------\n >>> index = pd.Index([0, 1, 2])\n >>> index.any()\n True\n\n >>> index = pd.Index([0, 0, 0])\n >>> index.any()\n False\n \"\"\")\n\n def _make_logical_function(name, desc, f):\n @Substitution(outname=name, desc=desc)\n @Appender(_index_shared_docs['index_' + name])\n @Appender(_doc)\n def logical_func(self, *args, **kwargs):\n result = f(self.values)\n if (isinstance(result, (np.ndarray, ABCSeries, Index)) and\n result.ndim == 0):\n # return NumPy type\n return result.dtype.type(result.item())\n else: # pragma: no cover\n return result\n\n logical_func.__name__ = name\n return logical_func\n\n cls.all = _make_logical_function('all', 'Return whether all elements '\n 'are True.',\n np.all)\n cls.any = _make_logical_function('any',\n 'Return whether any element is True.',\n np.any)\n\n @classmethod\n def _add_logical_methods_disabled(cls):\n \"\"\"\n Add in logical methods to disable.\n \"\"\"\n cls.all = make_invalid_op('all')\n cls.any = make_invalid_op('any')\n\n\nIndex._add_numeric_methods_disabled()\nIndex._add_logical_methods()\nIndex._add_comparison_methods()\n\n\ndef ensure_index_from_sequences(sequences, names=None):\n \"\"\"\n Construct an index from sequences of data.\n\n A single sequence returns an Index. Many sequences returns a\n MultiIndex.\n\n Parameters\n ----------\n sequences : sequence of sequences\n names : sequence of str\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n --------\n >>> ensure_index_from_sequences([[1, 2, 3]], names=['name'])\n Int64Index([1, 2, 3], dtype='int64', name='name')\n\n >>> ensure_index_from_sequences([['a', 'a'], ['a', 'b']],\n names=['L1', 'L2'])\n MultiIndex(levels=[['a'], ['a', 'b']],\n codes=[[0, 0], [0, 1]],\n names=['L1', 'L2'])\n\n See Also\n --------\n ensure_index\n \"\"\"\n from .multi import MultiIndex\n\n if len(sequences) == 1:\n if names is not None:\n names = names[0]\n return Index(sequences[0], name=names)\n else:\n return MultiIndex.from_arrays(sequences, names=names)\n\n\ndef ensure_index(index_like, copy=False):\n \"\"\"\n Ensure that we have an index from some index-like object.\n\n Parameters\n ----------\n index : sequence\n An Index or other sequence\n copy : bool\n\n Returns\n -------\n index : Index or MultiIndex\n\n Examples\n --------\n >>> ensure_index(['a', 'b'])\n Index(['a', 'b'], dtype='object')\n\n >>> ensure_index([('a', 'a'), ('b', 'c')])\n Index([('a', 'a'), ('b', 'c')], dtype='object')\n\n >>> ensure_index([['a', 'a'], ['b', 'c']])\n MultiIndex(levels=[['a'], ['b', 'c']],\n codes=[[0, 0], [0, 1]])\n\n See Also\n --------\n ensure_index_from_sequences\n \"\"\"\n if isinstance(index_like, Index):\n if copy:\n index_like = index_like.copy()\n return index_like\n if hasattr(index_like, 'name'):\n return Index(index_like, name=index_like.name, copy=copy)\n\n if is_iterator(index_like):\n index_like = list(index_like)\n\n # must check for exactly list here because of strict type\n # check in clean_index_list\n if isinstance(index_like, list):\n if type(index_like) != list:\n index_like = list(index_like)\n\n converted, all_arrays = lib.clean_index_list(index_like)\n\n if len(converted) > 0 and all_arrays:\n from .multi import MultiIndex\n return MultiIndex.from_arrays(converted)\n else:\n index_like = converted\n else:\n # clean_index_list does the equivalent of copying\n # so only need to do this if not list instance\n if copy:\n from copy import copy\n index_like = copy(index_like)\n\n return Index(index_like)\n\n\ndef _ensure_has_len(seq):\n \"\"\"\n If seq is an iterator, put its values into a list.\n \"\"\"\n try:\n len(seq)\n except TypeError:\n return list(seq)\n else:\n return seq\n\n\ndef _trim_front(strings):\n \"\"\"\n Trims zeros and decimal points.\n \"\"\"\n trimmed = strings\n while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):\n trimmed = [x[1:] for x in trimmed]\n return trimmed\n\n\ndef _validate_join_method(method):\n if method not in ['left', 'right', 'inner', 'outer']:\n raise ValueError('do not recognize join method %s' % method)\n\n\ndef default_index(n):\n from pandas.core.index import RangeIndex\n return RangeIndex(0, n, name=None)\n"
] | [
[
"pandas.core.dtypes.common.ensure_object",
"numpy.where",
"pandas.core.dtypes.common.is_interval_dtype",
"pandas.core.dtypes.concat._concat_index_asobject",
"pandas.core.common.cast_scalar_indexer",
"pandas.core.common._not_none",
"pandas.core.dtypes.common.is_iterator",
"pandas.core.dtypes.common.is_float_dtype",
"pandas.core.dtypes.common.is_categorical_dtype",
"pandas._libs.join.outer_join_indexer",
"pandas.core.dtypes.common.is_list_like",
"numpy.delete",
"numpy.array",
"pandas.core.algorithms.take",
"pandas._libs.lib.is_datetime_with_singletz_array",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas.TimedeltaIndex",
"pandas.core.dtypes.missing.isna",
"pandas.io.formats.printing.pprint_thing",
"pandas._libs.tslibs.Timestamp",
"pandas.Series",
"numpy.asarray",
"pandas._libs.join.inner_join_indexer",
"pandas.core.dtypes.common.is_datetime64tz_dtype",
"numpy.concatenate",
"pandas._libs.lib.clean_index_list",
"pandas.core.dtypes.common.is_unsigned_integer_dtype",
"pandas.core.index.RangeIndex.from_range",
"pandas.core.common.asarray_tuplesafe",
"pandas.io.formats.format.format_array",
"pandas.core.algorithms.take_nd",
"pandas.compat.u",
"numpy.errstate",
"pandas._libs.algos.groupsort_indexer",
"pandas.core.ops._comp_method_OBJECT_ARRAY",
"pandas.core.sorting.safe_sort",
"pandas.core.dtypes.common.is_integer",
"pandas._libs.lib.infer_dtype",
"numpy.ndarray.__setstate__",
"pandas._libs.lib.item_from_zerodim",
"numpy.empty",
"pandas.core.dtypes.cast.maybe_cast_to_integer_array",
"pandas.core.dtypes.common.is_extension_array_dtype",
"pandas.core.dtypes.common.ensure_categorical",
"pandas.core.dtypes.common.is_dtype_equal",
"pandas._libs.lib.is_scalar",
"pandas.core.ops.make_invalid_op",
"pandas.core.indexes.frozen.FrozenList",
"pandas.compat.iteritems",
"pandas.core.reshape.merge._get_join_indexers",
"pandas.core.common.values_from_object",
"numpy.hstack",
"pandas.util._decorators.Substitution",
"pandas.DatetimeIndex",
"pandas.core.dtypes.common.ensure_int64",
"pandas._libs.index.get_value_box",
"numpy.repeat",
"pandas.core.index.RangeIndex",
"pandas._libs.tslibs.timezones.tz_compare",
"pandas.core.dtypes.common.is_dtype_union_equal",
"pandas._libs.join.left_join_indexer_unique",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.util._decorators.Appender",
"pandas.core.dtypes.common.is_categorical",
"pandas.core.dtypes.common.pandas_dtype",
"pandas.core.dtypes.common.is_timedelta64_dtype",
"pandas.core.dtypes.common.is_hashable",
"pandas.core.dtypes.common.is_period_dtype",
"pandas.core.indexes.period._new_PeriodIndex",
"pandas.core.reshape.merge._restore_dropped_levels_multijoin",
"pandas.core.dtypes.common.is_bool",
"pandas._libs.tslibs.Timedelta",
"pandas.core.algorithms.isin",
"pandas.core.common.is_bool_indexer",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.accessor.CachedAccessor",
"pandas.io.formats.printing.format_object_summary",
"numpy.dtype",
"pandas.core.indexes.period.PeriodIndex",
"pandas.core.dtypes.common.is_signed_integer_dtype",
"numpy.arange",
"pandas.core.ops.get_op_result_name",
"pandas.compat.set_function_name",
"pandas.core.dtypes.common.is_float",
"pandas.core.dtypes.common.is_datetime64_any_dtype",
"pandas.core.dtypes.common.ensure_platform_int",
"pandas.io.formats.printing.format_object_attrs",
"pandas.core.dtypes.concat.get_dtype_kinds",
"pandas._libs.join.left_join_indexer",
"pandas.core.dtypes.common.is_object_dtype",
"pandas.core.dtypes.concat._concat_compat",
"pandas._libs.lib.maybe_convert_objects",
"pandas.core.common.index_labels_to_array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"0.24",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
mgkagk01/Coding-Theory | [
"58229b6db4ff42fc529e0ffa6d895e19c1c1c162"
] | [
"LDPC/DecoderExample/LdpcDecoder.py"
] | [
"import numpy as np\r\n\r\nclass Node:\r\n def __init__(self, id, idxStore, idxRead):\r\n self.id = id\r\n self.idxStore = idxStore\r\n self.idxRead = idxRead\r\n self.next = None\r\n\r\n\r\nclass LdpcDecoder():\r\n def __init__(self, fileName, a):\r\n self.a = a\r\n self.weight = (2*a) # for the channel LLR\r\n self.f = open(fileName, \"r\")\r\n temp = self.f.readline().split()\r\n self.V = int(temp[1]) # number of Variable nodes\r\n self.C = int(temp[0]) # number of Check nodes\r\n self.nNodes = self.V + self.C # total number of nodes\r\n self.nNeighbors = np.zeros(self.V + self.C, dtype=int) # number of neighbors\r\n\r\n # --- Count the number of Edges\r\n self.f.readline() # Skip the next line\r\n leftDegress = string2numpy(self.f.readline())\r\n self.E = sum(leftDegress)\r\n\r\n # --- Store the degrees of each node\r\n self.degrees = np.hstack((string2numpy(self.f.readline()),leftDegress))\r\n\r\n # --- Mapping from a node to the starting location at the message array\r\n self.node2msgLoc = self.compNode2msgLoc()\r\n\r\n # --- Array to store the messages\r\n self.messages = np.zeros(2 * self.E)\r\n\r\n # --- Generate Graph\r\n self.adjList = [None] * (self.nNodes)\r\n self.generateGraph()\r\n print()\r\n\r\n # --- Array to store the estimated codeword\r\n self.softCodeword = np.zeros(self.V)\r\n\r\n\r\n# ==================================== Functions for Belief Propagation ==================================== #\r\n def decode(self, y, sigma2, nIter):\r\n\r\n\r\n # === Step 1: Initialize the variable nodes with the channel LLR\r\n self.initVarNodes(y, sigma2)\r\n\r\n for i in range(nIter):\r\n\r\n # === Step 2: Compute the messages from Check nodes to Variable nodes\r\n self.compCheck2Var()\r\n\r\n # === Step 3: Compute the messages from Variable nodes to Check nodes\r\n self.compVar2Check()\r\n\r\n # === Step 4: Check if the values of check node\r\n if self.isCorrect():\r\n return 1, self.softCodeword\r\n\r\n return 0, self.softCodeword\r\n\r\n # ====== Step 1 ====== #\r\n def initVarNodes(self,y, sigma2):\r\n # --- Compute the channel LLR\r\n self.chLLR = self.weight * y / sigma2\r\n for i in range(self.V):\r\n node = self.adjList[i]\r\n for d in range(self.degrees[i]):\r\n\r\n self.messages[self.node2msgLoc[node.id] + node.idxStore] = self.chLLR[i]\r\n node = node.next\r\n\r\n # ====== Step 2 ====== #\r\n def compCheck2Var(self):\r\n for i in range(self.V, self.nNodes, 1):\r\n node = self.adjList[i]\r\n P = np.prod(np.tanh(self.messages[self.node2msgLoc[i]:self.node2msgLoc[i] + self.degrees[i]]/2.0))\r\n for d in range(self.degrees[i]):\r\n\r\n # --- Compute the message\r\n L = self.messages[self.node2msgLoc[i] + node.idxRead]/2.0\r\n msg = 2*np.arctanh(P/np.tanh(L))\r\n\r\n if abs(msg) > 20:\r\n msg = np.sign(msg) * 20\r\n\r\n # --- Store the message\r\n self.messages[self.node2msgLoc[node.id] + node.idxStore] = msg\r\n node = node.next\r\n\r\n\r\n # ====== Step 3 ====== #\r\n def compVar2Check(self):\r\n for i in range(self.V):\r\n node = self.adjList[i]\r\n S = np.sum(self.messages[self.node2msgLoc[i]:self.node2msgLoc[i] + self.degrees[i]])\r\n for d in range(self.degrees[i]):\r\n # --- Compute the message\r\n msg = S - self.messages[self.node2msgLoc[i] + node.idxRead] + self.chLLR[i]\r\n\r\n if abs(msg) > 20:\r\n msg = np.sign(msg) * 20\r\n # --- Store the message\r\n self.messages[self.node2msgLoc[node.id] + node.idxStore] = msg\r\n\r\n node = node.next\r\n if d == 0:\r\n # --- Compute the output LLR\r\n self.softCodeword[i] = S + self.chLLR[i]\r\n\r\n\r\n # ====== Step 4 ====== #\r\n def isCorrect(self):\r\n\r\n # === Step 1: Compute the hard decision\r\n hardCodeword = (self.softCodeword < 0) * 1\r\n\r\n # === Step 2: check the value of the Check node\r\n for i in range(self.V, self.nNodes, 1):\r\n node = self.adjList[i]\r\n sum = 0\r\n for d in range(self.degrees[i]):\r\n sum += hardCodeword[node.id]\r\n node = node.next\r\n\r\n if sum % 2 != 0:\r\n return 0\r\n return 1\r\n\r\n\r\n# ==================================== Functions to Construct the Graph ==================================== #\r\n def generateGraph(self):\r\n\r\n # --- Skip the information for check nodes\r\n for _ in range(self.C):\r\n self.f.readline()\r\n\r\n # --- For all variable nodes\r\n for v in range(self.V):\r\n # --- Find the neighbors of v\r\n neighbors = string2numpy(self.f.readline()) - 1 + self.V\r\n\r\n for c in neighbors:\r\n if c == self.V-1:\r\n break\r\n\r\n # --- Add c node to the neighborhood of v, and\r\n self.addNode(v, c)\r\n\r\n # --- Add this node to the neighborhood of c\r\n self.addNode(c, v)\r\n\r\n self.nNeighbors[v] += 1\r\n self.nNeighbors[c] += 1\r\n\r\n\r\n self.f.close()\r\n\r\n def addNode(self, sourceID, destinationID):\r\n idxRead = self.nNeighbors[sourceID]\r\n idxStore = self.nNeighbors[destinationID]\r\n\r\n # --- Create a new node\r\n newNode = Node(destinationID, idxStore, idxRead)\r\n\r\n # --- Add this neighbor\r\n newNode.next = self.adjList[sourceID]\r\n self.adjList[sourceID] = newNode\r\n\r\n\r\n def compNode2msgLoc(self):\r\n\r\n loc = 0\r\n node2msgLoc = np.zeros(self.nNodes, dtype=int)\r\n for i in range(self.nNodes):\r\n node2msgLoc[i] = loc\r\n loc += self.degrees[i]\r\n return node2msgLoc\r\n\r\n# ==================================== Utility Functions ==================================== #\r\n\r\ndef printGraph(graph, nNodes):\r\n\r\n for i in range(nNodes):\r\n temp = graph[i]\r\n if temp is not None:\r\n print(\"=============================================\")\r\n print('Node: ' + str(i))\r\n print('Neighbors')\r\n print(temp.id)\r\n while temp.next is not None:\r\n temp = temp.next\r\n print(temp.id)\r\n\r\ndef string2numpy(string):\r\n return np.asarray(string.split(), dtype=int)"
] | [
[
"numpy.sign",
"numpy.tanh",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AvocadoTan/cogdl | [
"90e6ea74209fd8a8a310efc4d7e7060bcb313a5e"
] | [
"examples/hyper_search.py"
] | [
"import torch\nimport optuna\n\nfrom cogdl.utils import build_args_from_dict\nfrom cogdl.models import build_model\nfrom cogdl.datasets import build_dataset\nfrom cogdl.tasks import build_task\nfrom cogdl.utils import set_random_seed\n\n\nN_SEED = 5\n\n\nclass HyperSearch(object):\n \"\"\"\n This class does not need to be modified\n Args:\n Hyper-parameter search script\n func_fixed: function to obtain fixed hyper-parameters\n func_search: function to obtain hyper-parameters to search\n \"\"\"\n\n def __init__(self, func_fixed, func_search, n_trials=30):\n self.func_fixed = func_fixed\n self.func_search = func_search\n self.dataset = None\n self.n_trials = n_trials\n\n def build_args(self, params):\n args = build_args_from_dict(params)\n if self.dataset is None:\n self.dataset = build_dataset(args)\n args.num_features = self.dataset.num_features\n args.num_classes = self.dataset.num_classes\n return args\n\n def run_n_seed(self, args):\n result_list = []\n for seed in range(N_SEED):\n set_random_seed(seed)\n\n model = build_model(args)\n task = build_task(args, model=model, dataset=self.dataset)\n\n result = task.train()\n result_list.append(result)\n return result_list\n\n def objective(self, trials):\n fixed_params = self.func_fixed()\n params = self.func_search(trials)\n params.update(fixed_params)\n args = self.build_args(params)\n\n result_list = self.run_n_seed(args)\n\n item = result_list[0]\n key = None\n for _key in item.keys():\n if \"Val\" in _key:\n key = _key\n break\n if not key:\n raise KeyError\n val_meansure = [x[key] for x in result_list]\n mean = sum(val_meansure) / len(val_meansure)\n\n return 1.0 - mean\n\n def final_result(self, best_params):\n params = self.func_fixed()\n params.update(best_params)\n args = self.build_args(params)\n\n result_list = self.run_n_seed(args)\n keys = list(result_list[0].keys())\n result = {}\n for key in keys:\n result[key] = sum(x[key] for x in result_list) / len(result_list)\n\n return result\n\n def run(self):\n study = optuna.create_study()\n study.optimize(self.objective, n_trials=self.n_trials, n_jobs=10)\n best_params = study.best_params\n best_values = 1 - study.best_value\n\n result = self.final_result(best_params)\n return {\"best_params\": best_params, \"best_result_in_search\": best_values, \"result\": result}\n\n\n# To tune the hyper-parameters of a given model.\n# Just fill in the hyper-parameters you want to search in function `hyper_parameters_to_search`\n# and the other necessary fixed hyper-parameters in function `fixed_hyper_parameters`\n# Then run this script.\n\n\ndef hyper_parameters_to_search(trial):\n \"\"\"\n Fill in hyper-parameters to search of your model\n Return hyper-parameters to search\n \"\"\"\n return {\n \"lr\": trial.suggest_categorical(\"lr\", [1e-3, 5e-3, 1e-2]),\n \"hidden_size\": trial.suggest_categorical(\"hidden_size\", [32, 64, 128]),\n \"n_dropout\": trial.suggest_uniform(\"n_dropout\", 0.5, 0.92),\n \"adj_dropout\": trial.suggest_uniform(\"adj_dropout\", 0.0, 0.3),\n \"aug_adj\": trial.suggest_categorical(\"aug_adj\", [True, False]),\n \"improved\": trial.suggest_categorical(\"improved\", [True, False]),\n # \"activation\": trial.suggest_categorical(\"activation\", [\"relu\", \"identity\"]),\n # \"num_layers\": trial.suggest_int(\"num_layers\", 1, 3),\n }\n\n\ndef fixed_hyper_parameters():\n \"\"\"\n Fill in fixed and necessary hyper-parameters of your model\n Return fixed parameters\n \"\"\"\n cpu = not torch.cuda.is_available()\n return {\n \"weight_decay\": 0.001,\n \"max_epoch\": 1000,\n \"patience\": 100,\n \"cpu\": cpu,\n \"device_id\": [0],\n \"seed\": [0, 1, 2],\n \"task\": \"node_classification\",\n \"model\": \"unet\",\n \"dataset\": \"cora\",\n \"n_pool\": 4,\n \"pool_rate\": [0.7, 0.5, 0.5, 0.4],\n \"missing_rate\": -1,\n \"activation\": \"identity\",\n }\n\n\ndef main_hypersearch(n_trials=50):\n cls = HyperSearch(fixed_hyper_parameters, hyper_parameters_to_search, n_trials=n_trials)\n result = cls.run()\n for key, val in result.items():\n print(key, val)\n\n\nif __name__ == \"__main__\":\n main_hypersearch(50)\n"
] | [
[
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gustavovaliati/obj-det-experiments | [
"e81774a18b34c22d971ad15d7ac6eb8663ac6f22"
] | [
"tensorflow/bbox/jrieke-tf-parse/jrieke_tf_dataset.py"
] | [
"'''\nThis code is based on https://github.com/jrieke/shape-detection/\n'''\n\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\nimport tensorflow as tf\nimport datetime\n\nclass JriekeBboxDataset:\n def generate(self):\n # Create images with random rectangles and bounding boxes.\n num_imgs = 50000\n\n self.WIDTH = 8\n self.HEIGHT = 8\n min_object_size = 1\n max_object_size = 4\n num_objects = 1\n\n self.bboxes = np.zeros((num_imgs, num_objects, 4))\n self.imgs = np.zeros((num_imgs, self.WIDTH, self.HEIGHT)) # set background to 0\n\n for i_img in range(num_imgs):\n for i_object in range(num_objects):\n w, h = np.random.randint(min_object_size, max_object_size, size=2)\n x = np.random.randint(0, self.WIDTH - w)\n y = np.random.randint(0, self.HEIGHT - h)\n self.imgs[i_img, x:x+w, y:y+h] = 1. # set rectangle to 1\n self.bboxes[i_img, i_object] = [x, y, w, h]\n\n self.imgs.shape, self.bboxes.shape\n\n # Reshape and normalize the image data to mean 0 and std 1.\n X = (self.imgs.reshape(num_imgs, -1) - np.mean(self.imgs)) / np.std(self.imgs)\n X.shape, np.mean(X), np.std(X)\n\n # Normalize x, y, w, h by self.img_size, so that all values are between 0 and 1.\n # Important: Do not shift to negative values (e.g. by setting to mean 0), because the IOU calculation needs positive w and h.\n y = self.bboxes.reshape(num_imgs, -1) / self.WIDTH\n y.shape, np.mean(y), np.std(y)\n\n # Split training and test.\n i = int(0.8 * num_imgs)\n train_X = X[:i]\n test_X = X[i:]\n train_y = y[:i]\n test_y = y[i:]\n self.test_imgs = self.imgs[i:]\n self.test_bboxes = self.bboxes[i:]\n\n ### check if the generated imgs match to the test_X slice image\n # self.check_dataset_image_compability(test_X[0], self.test_imgs[0])\n\n return train_X, train_y, test_X, test_y\n\n def check_dataset_image_compability(self, test_X_sample, test_imgs_sample):\n fig = plt.figure(figsize=(12, 3))\n fig.suptitle('check if the generated imgs match to the test_X slice image')\n fig.subplots_adjust(top=0.85)\n\n plt.subplot(1, 2, 1)\n plt.gca().set_title('Returned by the dataset class: used for training')\n TMP = test_X_sample.reshape(self.WIDTH, self.HEIGHT)\n plt.imshow(TMP.T, cmap='Greys', interpolation='none', origin='lower', extent=[0, self.WIDTH, 0, self.HEIGHT])\n\n plt.subplot(1, 2, 2)\n plt.gca().set_title('Global image holder: used for plotting.')\n plt.imshow(test_imgs_sample.T, cmap='Greys', interpolation='none', origin='lower', extent=[0, self.WIDTH, 0, self.HEIGHT])\n plt.show()\n print('compare:',TMP,test_imgs_sample)\n\n def IOU(self,bbox1, bbox2):\n '''Calculate overlap between two bounding boxes [x, y, w, h] as the area of intersection over the area of unity'''\n x1, y1, w1, h1 = bbox1[0], bbox1[1], bbox1[2], bbox1[3]\n x2, y2, w2, h2 = bbox2[0], bbox2[1], bbox2[2], bbox2[3]\n\n w_I = min(x1 + w1, x2 + w2) - max(x1, x2)\n h_I = min(y1 + h1, y2 + h2) - max(y1, y2)\n if w_I <= 0 or h_I <= 0: # no overlap\n return 0.\n I = w_I * h_I\n\n U = w1 * h1 + w2 * h2 - I\n\n return I / U\n\n def convertDefaultAnnotToCoord(self, annot):\n '''\n annot -> [x, y, w, h]\n '''\n\n w = annot[2] * self.WIDTH\n h = annot[3] * self.HEIGHT\n\n x = annot[0] * self.HEIGHT\n y = annot[1] * self.HEIGHT\n\n return [x,y,w,h]\n\n def convertYoloAnnotToCoord(self, yolo_annot):\n '''\n yolo_annot -> [x, y, w, h]\n '''\n\n w = yolo_annot[2] * self.WIDTH\n h = yolo_annot[3] * self.HEIGHT\n\n x = (yolo_annot[0] * self.WIDTH) - (w/2)\n y = (yolo_annot[1] * self.HEIGHT) - (h/2)\n\n return [x,y,w,h]\n\n def show_generated(self, i=0):\n fig = plt.figure()\n fig.subplots_adjust(top=0.85)\n fig.suptitle('Generated image sample + GT')\n plt.imshow(self.imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, self.WIDTH, 0, self.HEIGHT])\n for bbox in self.bboxes[i]:\n plt.gca().add_patch(matplotlib.patches.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], ec='r', fc='none'))\n plt.gca().legend(['GT'])\n plt.show()\n\n def plot_rectangle(self, img, bbox):\n\n fig = plt.figure()\n fig.suptitle('Plotting rectangle.')\n fig.subplots_adjust(top=0.85)\n\n plt.subplot(1, 1, 1)\n plt.imshow(img, cmap='Greys', interpolation='none', origin='lower', extent=[0, self.WIDTH, 0, self.HEIGHT])\n plt.gca().add_patch(matplotlib.patches.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], ec='r', fc='none'))\n plt.show()\n\n\n def check_dataset_image_compability(self, test_X_sample, test_imgs_sample):\n fig = plt.figure(figsize=(12, 3))\n fig.suptitle('check if the generated imgs match to the test_X slice image')\n fig.subplots_adjust(top=0.85)\n\n plt.subplot(1, 2, 1)\n plt.gca().set_title('Returned by the dataset class: used for training')\n plt.imshow(TMP.T, cmap='Greys', interpolation='none', origin='lower', extent=[0, self.WIDTH, 0, self.HEIGHT])\n\n plt.subplot(1, 2, 2)\n plt.gca().set_title('Global image holder: used for plotting.')\n plt.imshow(test_imgs_sample.T, cmap='Greys', interpolation='none', origin='lower', extent=[0, self.WIDTH, 0, self.HEIGHT])\n plt.show()\n print('compare:',TMP,test_imgs_sample)\n\n def show_predicted(self, pred_bboxes):\n # Show a few images and predicted bounding boxes from the test dataset.\n\n fig = plt.figure(figsize=(12, 3))\n fig.subplots_adjust(top=0.85)\n fig.suptitle('Prediction demonstration. Random samples.')\n legend_plotted = False\n\n for i_subplot in range(1, 11):\n plt.subplot(1, 10, i_subplot)\n i = np.random.randint(len(pred_bboxes))\n plt.imshow(self.test_imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, self.WIDTH, 0, self.HEIGHT])\n for pred_bbox, exp_bbox in zip(pred_bboxes[i], self.test_bboxes[i]):\n # print('before convertion: pred',pred_bbox, 'gt',exp_bbox)\n pred_bbox = self.convertDefaultAnnotToCoord(pred_bbox)\n # exp_bbox = self.convertDefaultAnnotToCoord(exp_bbox)\n print('after convertion: pred',pred_bbox, 'gt',exp_bbox)\n plt.gca().add_patch(matplotlib.patches.Rectangle((pred_bbox[0], pred_bbox[1]), pred_bbox[2], pred_bbox[3], ec='r', fc='none'))\n #gt\n plt.gca().add_patch(matplotlib.patches.Rectangle((exp_bbox[0], exp_bbox[1]), exp_bbox[2], exp_bbox[3], ec='b', fc='none'))\n plt.annotate('IOU: {:.2f}'.format(self.IOU(pred_bbox, exp_bbox)), (pred_bbox[0], pred_bbox[1]+pred_bbox[3]+0.2), color='r')\n if not legend_plotted:\n legend_plotted = True\n plt.gca().legend(['Pred','GT'],loc='upper center', bbox_to_anchor=(0.5, -0.5), fancybox=True)\n plt.show()\n # plt.savefig('plots/bw-single-rectangle_prediction_{0:%Y-%m-%d%H:%M:%S}.png'.format(datetime.datetime.now()), dpi=300)\n"
] | [
[
"matplotlib.pyplot.gca",
"matplotlib.pyplot.imshow",
"matplotlib.patches.Rectangle",
"numpy.std",
"matplotlib.pyplot.subplot",
"numpy.mean",
"numpy.random.randint",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
romainmartinez/aqua | [
"dd031641a5e1e6f12fa29271d447bea7e49407a0",
"dd031641a5e1e6f12fa29271d447bea7e49407a0"
] | [
"aqua/data.py",
"bayes.py"
] | [
"import pandas as pd\n\n\ndef load_raw_data(data_path: str = \"./data/raw.csv\") -> pd.DataFrame:\n return pd.read_csv(data_path)\n",
"import streamlit as st\n\nfrom aqua import ui, data, processing, ml, plots\n\nui.make_title()\nprocessing_options, modelling_options = ui.make_sidebar()\n\nraw_data = data.load_raw_data().pipe(processing.process_force_data, processing_options)\n\nst.markdown(\"## 1. Data description\")\n\nif st.checkbox(\"Show raw data\", key=\"show-raw\"):\n st.dataframe(raw_data)\n\ntargets, variables = ml.variables_targets_split(raw_data, modelling_options[\"targets\"])\n\nst.markdown(\"### 1.1 Variables\")\nplots.plot_anthropometry(variables)\nplots.plot_forces(variables)\n\nst.markdown(\"### 1.2 Targets\")\nplots.plot_targets(targets)\n\nst.markdown(\"### 1.3 Correlation matrix\")\nplots.plot_correlation_matrix(variables, targets)\n\nst.markdown(\"## 2. Data modelling\")\nX_train, X_test, y_train, y_test = ml.train_test_split(\n variables, targets, modelling_options[\"test_size\"]\n)\n\nst.markdown(\n f\"Train split size: `{X_train.shape[0]}` ({X_train.shape[0] / raw_data.shape[0]:.2f}%)\"\n)\nst.markdown(\n f\"Test split size: `{X_test.shape[0]}` ({X_test.shape[0] / raw_data.shape[0]:.2f}%)\"\n)\n\nst.markdown(\"### 2.1 Test split evaluation\")\n\n# Dirty from here\nimport pymc3 as pm\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport arviz as az\nimport numpy as np\n\nrename_cols = lambda x: x.lower().replace(\" \", \"_\").replace(\"-\", \"_\")\ntrain = pd.concat(\n [(X_train - X_train.mean()) / X_train.std(), y_train], axis=\"columns\"\n).rename(columns=rename_cols)\nvar_cols = X_train.rename(columns=rename_cols).columns\ntarget = 'eb_mean_height'\n\nwith pm.Model() as model:\n pm.GLM.from_formula(f\"{target} ~ {' + '.join(var_cols)}\", train)\n trace = pm.sample(5000)\n\naz.plot_trace(trace)\nplt.show()\n\nfig, ax = plt.subplots(figsize=(8, 8))\nax.axvline(x=0, color=\"black\", linewidth=3)\naz.plot_forest(\n trace,\n kind=\"ridgeplot\",\n combined=True,\n var_names=var_cols,\n colors=\"#800000\",\n ridgeplot_overlap=1.2,\n ridgeplot_alpha=0.6,\n linewidth=0,\n show=False,\n ax=ax,\n)\naz.plot_forest(\n trace,\n kind=\"forestplot\",\n colors=\"black\",\n combined=True,\n var_names=var_cols,\n ridgeplot_overlap=1.2,\n show=False,\n ax=ax,\n linewidth=3,\n credible_interval=0.9,\n)\nax.set_xlim((-1, 1))\nax.set_title(\"\")\nplt.show()\n\nppc = pm.sample_posterior_predictive(trace, samples=10, model=model)\ndata_ppc = az.from_pymc3(trace=trace, posterior_predictive=ppc)\n\naz.plot_ppc(data_ppc, alpha=0.5)\nplt.show()\n\naz.plot_kde(train[target])\naz.plot_kde(ppc['y'])\n\nfor sample in range(ppc['y'].shape[0]):\n y_vals, lower, upper = az._fast_kde(ppc[\"y\"][sample, :])\n x_vals = np.linspace(lower, upper, y_vals.shape[0])\n plt.plot(x_vals, y_vals, color='black')\nplt.show()\n\n"
] | [
[
"pandas.read_csv"
],
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jangarrevoet/pyFAI | [
"0779ac9aa5d72ac582413921989a8375bb7a990a"
] | [
"pyFAI/test/test_openCL.py"
] | [
"#!/usr/bin/env python\n# coding: utf-8\n#\n# Project: Azimuthal integration\n# https://github.com/silx-kit/pyFAI\n#\n# Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France\n#\n# Principal author: Jérôme Kieffer ([email protected])\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"test suite for OpenCL code\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__author__ = \"Jérôme Kieffer\"\n__contact__ = \"[email protected]\"\n__license__ = \"MIT\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"11/01/2019\"\n\n\nimport unittest\nimport os\nimport time\nimport fabio\nimport gc\nimport numpy\nimport logging\nimport shutil\nimport platform\n\nlogger = logging.getLogger(__name__)\ntry:\n import pyopencl\nexcept ImportError as error:\n logger.warning(\"OpenCL module (pyopencl) is not present, skip tests. %s.\", error)\n pyopencl = None\n\nfrom ..opencl import ocl\nif ocl is not None:\n from ..opencl import pyopencl, read_cl_file\n import pyopencl.array\nfrom .. import load\nfrom . import utilstest\nfrom .utilstest import test_options\nfrom ..utils import mathutil\nfrom ..utils.decorators import depreclog\n\n\nclass TestMask(unittest.TestCase):\n\n def setUp(self):\n if not test_options.opencl:\n self.skipTest(\"User request to skip OpenCL tests\")\n if pyopencl is None or ocl is None:\n self.skipTest(\"OpenCL module (pyopencl) is not present or no device available\")\n\n self.tmp_dir = os.path.join(test_options.tempdir, \"opencl\")\n if not os.path.isdir(self.tmp_dir):\n os.makedirs(self.tmp_dir)\n\n self.N = 1000\n self.datasets = [{\"img\": test_options.getimage(\"Pilatus1M.edf\"),\n \"poni\": test_options.getimage(\"Pilatus1M.poni\"),\n \"spline\": None},\n {\"img\": test_options.getimage(\"halfccd.edf\"),\n \"poni\": test_options.getimage(\"halfccd.poni\"),\n \"spline\": test_options.getimage(\"halfccd.spline\")},\n# {\"img\": test_options.getimage(\"Frelon2k.edf\"),\n# \"poni\": test_options.getimage(\"Frelon2k.poni\"),\n# \"spline\": test_options.getimage(\"frelon.spline\")},\n# {\"img\": test_options.getimage(\"Pilatus6M.cbf\"),\n# \"poni\": test_options.getimage(\"Pilatus6M.poni\"),\n# \"spline\": None},\n ]\n for ds in self.datasets:\n if ds[\"spline\"] is not None:\n with open(ds[\"poni\"], \"r\") as ponifile:\n data = ponifile.read()\n # spline = os.path.basename(ds[\"spline\"])\n with open(ds[\"poni\"]) as f:\n data = []\n for line in f:\n if line.startswith(\"SplineFile:\"):\n data.append(\"SplineFile: \" + ds[\"spline\"])\n else:\n data.append(line.strip())\n ds[\"poni\"] = os.path.join(self.tmp_dir, os.path.basename(ds[\"poni\"]))\n with open(ds[\"poni\"], \"w\") as f:\n f.write(os.linesep.join(data))\n\n def tearDown(self):\n shutil.rmtree(self.tmp_dir)\n self.tmp_dir = self.N = self.datasets = None\n\n @unittest.skipIf(test_options.low_mem, \"test using >200M\")\n def test_OpenCL(self):\n logger.info(\"Testing histogram-based algorithm (forward-integration)\")\n for devtype in (\"GPU\", \"CPU\"):\n ids = ocl.select_device(devtype, extensions=[\"cl_khr_int64_base_atomics\"])\n if ids is None:\n logger.error(\"No suitable %s OpenCL device found\", devtype)\n continue\n else:\n logger.info(\"I found a suitable device %s %s: %s %s \", devtype, ids, ocl.platforms[ids[0]], ocl.platforms[ids[0]].devices[ids[1]])\n if ocl.platforms[ids[0]].name == \"Portable Computing Language\":\n logger.warning(\"POCL is known error-prone on this test\")\n continue\n\n for ds in self.datasets:\n ai = load(ds[\"poni\"])\n data = fabio.open(ds[\"img\"]).data\n with utilstest.TestLogging(logger=depreclog, warning=1):\n # Filter deprecated warning\n res = ai.xrpd_OpenCL(data, self.N, devicetype=\"all\", platformid=ids[0], deviceid=ids[1], useFp64=True)\n ref = ai.integrate1d(data, self.N, method=\"splitBBox\", unit=\"2th_deg\")\n r = mathutil.rwp(ref, res)\n logger.info(\"OpenCL histogram vs histogram SplitBBox has R= %.3f for dataset %s\", r, ds)\n self.assertTrue(r < 6, \"Rwp=%.3f for OpenCL histogram processing of %s\" % (r, ds))\n ai.reset()\n del ai, data\n gc.collect()\n\n @unittest.skipIf(test_options.low_mem, \"test using >500M\")\n def test_OpenCL_LUT(self):\n logger.info(\"Testing LUT-based algorithm (backward-integration)\")\n for devtype in (\"GPU\", \"CPU\"):\n ids = ocl.select_device(devtype, best=True)\n if ids is None:\n logger.error(\"No suitable %s OpenCL device found\", devtype)\n continue\n else:\n logger.info(\"I found a suitable device %s %s: %s %s \", devtype, ids, ocl.platforms[ids[0]], ocl.platforms[ids[0]].devices[ids[1]])\n\n for ds in self.datasets:\n ai = load(ds[\"poni\"])\n data = fabio.open(ds[\"img\"]).data\n ref = ai.integrate1d(data, self.N, method=\"splitBBox\", unit=\"2th_deg\")\n try:\n res = ai.integrate1d(data, self.N, method=\"ocl_lut_%i,%i\" % (ids[0], ids[1]), unit=\"2th_deg\")\n except (pyopencl.MemoryError, MemoryError, pyopencl.RuntimeError, RuntimeError) as error:\n logger.warning(\"Memory error on %s dataset %s: %s%s. Converted into warnining: device may not have enough memory.\", devtype, os.path.basename(ds[\"img\"]), os.linesep, error)\n break\n else:\n r = mathutil.rwp(ref, res)\n logger.info(\"OpenCL CSR vs histogram SplitBBox has R= %.3f for dataset %s\", r, ds)\n self.assertTrue(r < 3, \"Rwp=%.3f for OpenCL LUT processing of %s\" % (r, ds))\n ai.reset()\n del ai, data\n gc.collect()\n\n @unittest.skipIf(test_options.low_mem, \"test using >200M\")\n def test_OpenCL_CSR(self):\n logger.info(\"Testing CSR-based algorithm (backward-integration)\")\n for devtype in (\"GPU\", \"CPU\"):\n ids = ocl.select_device(devtype, best=True)\n if ids is None:\n logger.error(\"No suitable %s OpenCL device found\", devtype)\n continue\n else:\n logger.info(\"I found a suitable device %s %s: %s %s\", devtype, ids, ocl.platforms[ids[0]], ocl.platforms[ids[0]].devices[ids[1]])\n\n for ds in self.datasets:\n ai = load(ds[\"poni\"])\n data = fabio.open(ds[\"img\"]).data\n ref = ai.integrate1d(data, self.N, method=\"splitBBox\", unit=\"2th_deg\")\n try:\n res = ai.integrate1d(data, self.N, method=\"ocl_csr_%i,%i\" % (ids[0], ids[1]), unit=\"2th_deg\")\n except (pyopencl.MemoryError, MemoryError, pyopencl.RuntimeError, RuntimeError) as error:\n logger.warning(\"Memory error on %s dataset %s: %s%s. Converted into Warning: device may not have enough memory.\", devtype, os.path.basename(ds[\"img\"]), os.linesep, error)\n break\n else:\n r = mathutil.rwp(ref, res)\n logger.info(\"OpenCL CSR vs histogram SplitBBox has R= %.3f for dataset %s\", r, ds)\n self.assertTrue(r < 3, \"Rwp=%.3f for OpenCL CSR processing of %s\" % (r, ds))\n ai.reset()\n del ai, data\n gc.collect()\n\n\nclass TestSort(unittest.TestCase):\n \"\"\"\n Test the kernels for vector and image sorting\n \"\"\"\n N = 1024\n ws = N // 8\n\n def setUp(self):\n if not test_options.opencl:\n self.skipTest(\"User request to skip OpenCL tests\")\n if pyopencl is None or ocl is None:\n self.skipTest(\"OpenCL module (pyopencl) is not present or no device available\")\n\n self.h_data = numpy.random.random(self.N).astype(\"float32\")\n self.h2_data = numpy.random.random((self.N, self.N)).astype(\"float32\").reshape((self.N, self.N))\n\n self.ctx = ocl.create_context(devicetype=\"GPU\")\n device = self.ctx.devices[0]\n try:\n devtype = pyopencl.device_type.to_string(device.type).upper()\n except ValueError:\n # pocl does not describe itself as a CPU !\n devtype = \"CPU\"\n workgroup = device.max_work_group_size\n if (devtype == \"CPU\") and (device.platform.vendor == \"Apple\"):\n logger.info(\"For Apple's OpenCL on CPU: enforce max_work_goup_size=1\")\n workgroup = 1\n\n self.ws = min(workgroup, self.ws)\n self.queue = pyopencl.CommandQueue(self.ctx, properties=pyopencl.command_queue_properties.PROFILING_ENABLE)\n self.local_mem = pyopencl.LocalMemory(self.ws * 32) # 2float4 = 2*4*4 bytes per workgroup size\n src = read_cl_file(\"pyfai:openCL/bitonic.cl\")\n self.prg = pyopencl.Program(self.ctx, src).build()\n\n def tearDown(self):\n self.h_data = None\n self.queue = None\n self.ctx = None\n self.local_mem = None\n self.h2_data = None\n\n def test_reference_book(self):\n d_data = pyopencl.array.to_device(self.queue, self.h_data)\n t0 = time.time()\n hs_data = numpy.sort(self.h_data)\n t1 = time.time()\n time_sort = 1e3 * (t1 - t0)\n\n evt = self.prg.bsort_book(self.queue, (self.ws,), (self.ws,), d_data.data, self.local_mem)\n evt.wait()\n err = abs(hs_data - d_data.get()).max()\n logger.info(\"test_reference_book\")\n logger.info(\"Numpy sort on %s element took %s ms\", self.N, time_sort)\n logger.info(\"Reference sort time: %s ms, err=%s \", 1e-6 * (evt.profile.end - evt.profile.start), err)\n # this test works under linux:\n if platform.system() == \"Linux\":\n self.assertTrue(err == 0.0)\n else:\n logger.warning(\"Measured error on %s is %s\", platform.system(), err)\n\n def test_reference_file(self):\n d_data = pyopencl.array.to_device(self.queue, self.h_data)\n t0 = time.time()\n hs_data = numpy.sort(self.h_data)\n t1 = time.time()\n time_sort = 1e3 * (t1 - t0)\n\n evt = self.prg.bsort_file(self.queue, (self.ws,), (self.ws,), d_data.data, self.local_mem)\n evt.wait()\n err = abs(hs_data - d_data.get()).max()\n logger.info(\"test_reference_file\")\n logger.info(\"Numpy sort on %s element took %s ms\", self.N, time_sort)\n logger.info(\"Reference sort time: %s ms, err=%s\", 1e-6 * (evt.profile.end - evt.profile.start), err)\n # this test works anywhere !\n self.assertTrue(err == 0.0)\n\n def test_sort_all(self):\n d_data = pyopencl.array.to_device(self.queue, self.h_data)\n t0 = time.time()\n hs_data = numpy.sort(self.h_data)\n t1 = time.time()\n time_sort = 1e3 * (t1 - t0)\n\n evt = self.prg.bsort_all(self.queue, (self.ws,), (self.ws,), d_data.data, self.local_mem)\n evt.wait()\n err = abs(hs_data - d_data.get()).max()\n logger.info(\"test_sort_all\")\n logger.info(\"Numpy sort on %s element took %s ms\", self.N, time_sort)\n logger.info(\"modified function execution time: %s ms, err=%s\", 1e-6 * (evt.profile.end - evt.profile.start), err)\n self.assertTrue(err == 0.0)\n\n def test_sort_horizontal(self):\n d2_data = pyopencl.array.to_device(self.queue, self.h2_data)\n t0 = time.time()\n h2s_data = numpy.sort(self.h2_data, axis=-1)\n t1 = time.time()\n time_sort = 1e3 * (t1 - t0)\n evt = self.prg.bsort_horizontal(self.queue, (self.N, self.ws), (1, self.ws), d2_data.data, self.local_mem)\n evt.wait()\n err = abs(h2s_data - d2_data.get()).max()\n logger.info(\"Numpy horizontal sort on %sx%s elements took %s ms\", self.N, self.N, time_sort)\n logger.info(\"Horizontal execution time: %s ms, err=%s\", 1e-6 * (evt.profile.end - evt.profile.start), err)\n self.assertTrue(err == 0.0)\n\n def test_sort_vertical(self):\n d2_data = pyopencl.array.to_device(self.queue, self.h2_data)\n t0 = time.time()\n h2s_data = numpy.sort(self.h2_data, axis=0)\n t1 = time.time()\n time_sort = 1e3 * (t1 - t0)\n evt = self.prg.bsort_vertical(self.queue, (self.ws, self.N), (self.ws, 1), d2_data.data, self.local_mem)\n evt.wait()\n err = abs(h2s_data - d2_data.get()).max()\n logger.info(\"Numpy vertical sort on %sx%s elements took %s ms\", self.N, self.N, time_sort)\n logger.info(\"Vertical execution time: %s ms, err=%s \", 1e-6 * (evt.profile.end - evt.profile.start), err)\n self.assertTrue(err == 0.0)\n\n\nclass TestKahan(unittest.TestCase):\n \"\"\"\n Test the kernels for compensated math in OpenCL\n \"\"\"\n\n def setUp(self):\n if not test_options.opencl:\n self.skipTest(\"User request to skip OpenCL tests\")\n if pyopencl is None or ocl is None:\n self.skipTest(\"OpenCL module (pyopencl) is not present or no device available\")\n\n self.ctx = ocl.create_context(devicetype=\"GPU\")\n self.queue = pyopencl.CommandQueue(self.ctx, properties=pyopencl.command_queue_properties.PROFILING_ENABLE)\n\n # this is running 32 bits OpenCL with POCL\n if (platform.machine() in (\"i386\", \"i686\", \"x86_64\") and (tuple.__itemsize__ == 4) and\n self.ctx.devices[0].platform.name == 'Portable Computing Language'):\n self.args = \"-DX87_VOLATILE=volatile\"\n else:\n self.args = \"\"\n\n def tearDown(self):\n self.queue = None\n self.ctx = None\n\n @staticmethod\n def dummy_sum(ary, dtype=None):\n \"perform the actual sum in a dummy way \"\n if dtype is None:\n dtype = ary.dtype.type\n sum_ = dtype(0)\n for i in ary:\n sum_ += i\n return sum_\n\n def test_kahan(self):\n # simple test\n N = 26\n data = (1 << (N - 1 - numpy.arange(N))).astype(numpy.float32)\n\n ref64 = numpy.sum(data, dtype=numpy.float64)\n ref32 = self.dummy_sum(data)\n if (ref64 == ref32):\n logger.warning(\"Kahan: invalid tests as float32 provides the same result as float64\")\n # Dummy kernel to evaluate\n src = \"\"\"\n kernel void summation(global float* data,\n int size,\n global float* result)\n {\n float2 acc = (float2)(0.0f, 0.0f);\n for (int i=0; i<size; i++)\n {\n acc = kahan_sum(acc, data[i]);\n }\n result[0] = acc.s0;\n result[1] = acc.s1;\n }\n \"\"\"\n prg = pyopencl.Program(self.ctx, read_cl_file(\"pyfai:openCL/kahan.cl\") + src).build(self.args)\n ones_d = pyopencl.array.to_device(self.queue, data)\n res_d = pyopencl.array.zeros(self.queue, 2, numpy.float32)\n evt = prg.summation(self.queue, (1,), (1,), ones_d.data, numpy.int32(N), res_d.data)\n evt.wait()\n res = res_d.get().sum(dtype=numpy.float64)\n self.assertEqual(ref64, res, \"test_kahan\")\n\n def test_dot16(self):\n # simple test\n N = 16\n data = (1 << (N - 1 - numpy.arange(N))).astype(numpy.float32)\n\n ref64 = numpy.dot(data.astype(numpy.float64), data.astype(numpy.float64))\n ref32 = numpy.dot(data, data)\n if (ref64 == ref32):\n logger.warning(\"dot16: invalid tests as float32 provides the same result as float64\")\n # Dummy kernel to evaluate\n src = \"\"\"\n kernel void test_dot16(global float* data,\n int size,\n global float* result)\n {\n float2 acc = (float2)(0.0f, 0.0f);\n float16 data16 = (float16) (data[0],data[1],data[2],data[3],data[4],\n data[5],data[6],data[7],data[8],data[9],\n data[10],data[11],data[12],data[13],data[14],data[15]);\n acc = comp_dot16(data16, data16);\n result[0] = acc.s0;\n result[1] = acc.s1;\n }\n\n kernel void test_dot8(global float* data,\n int size,\n global float* result)\n {\n float2 acc = (float2)(0.0f, 0.0f);\n float8 data0 = (float8) (data[0],data[2],data[4],data[6],data[8],data[10],data[12],data[14]);\n float8 data1 = (float8) (data[1],data[3],data[5],data[7],data[9],data[11],data[13],data[15]);\n acc = comp_dot8(data0, data1);\n result[0] = acc.s0;\n result[1] = acc.s1;\n }\n\n kernel void test_dot4(global float* data,\n int size,\n global float* result)\n {\n float2 acc = (float2)(0.0f, 0.0f);\n float4 data0 = (float4) (data[0],data[4],data[8],data[12]);\n float4 data1 = (float4) (data[3],data[7],data[11],data[15]);\n acc = comp_dot4(data0, data1);\n result[0] = acc.s0;\n result[1] = acc.s1;\n }\n\n kernel void test_dot3(global float* data,\n int size,\n global float* result)\n {\n float2 acc = (float2)(0.0f, 0.0f);\n float3 data0 = (float3) (data[0],data[4],data[12]);\n float3 data1 = (float3) (data[3],data[11],data[15]);\n acc = comp_dot3(data0, data1);\n result[0] = acc.s0;\n result[1] = acc.s1;\n }\n\n kernel void test_dot2(global float* data,\n int size,\n global float* result)\n {\n float2 acc = (float2)(0.0f, 0.0f);\n float2 data0 = (float2) (data[0],data[14]);\n float2 data1 = (float2) (data[1],data[15]);\n acc = comp_dot2(data0, data1);\n result[0] = acc.s0;\n result[1] = acc.s1;\n }\n\n \"\"\"\n\n prg = pyopencl.Program(self.ctx, read_cl_file(\"pyfai:openCL/kahan.cl\") + src).build(self.args)\n ones_d = pyopencl.array.to_device(self.queue, data)\n res_d = pyopencl.array.zeros(self.queue, 2, numpy.float32)\n evt = prg.test_dot16(self.queue, (1,), (1,), ones_d.data, numpy.int32(N), res_d.data)\n evt.wait()\n res = res_d.get().sum(dtype=\"float64\")\n self.assertEqual(ref64, res, \"test_dot16\")\n\n res_d.fill(0)\n data0 = data[0::2]\n data1 = data[1::2]\n ref64 = numpy.dot(data0.astype(numpy.float64), data1.astype(numpy.float64))\n ref32 = numpy.dot(data0, data1)\n if (ref64 == ref32):\n logger.warning(\"dot8: invalid tests as float32 provides the same result as float64\")\n evt = prg.test_dot8(self.queue, (1,), (1,), ones_d.data, numpy.int32(N), res_d.data)\n evt.wait()\n res = res_d.get().sum(dtype=\"float64\")\n self.assertEqual(ref64, res, \"test_dot8\")\n\n res_d.fill(0)\n data0 = data[0::4]\n data1 = data[3::4]\n ref64 = numpy.dot(data0.astype(numpy.float64), data1.astype(numpy.float64))\n ref32 = numpy.dot(data0, data1)\n if (ref64 == ref32):\n logger.warning(\"dot4: invalid tests as float32 provides the same result as float64\")\n evt = prg.test_dot4(self.queue, (1,), (1,), ones_d.data, numpy.int32(N), res_d.data)\n evt.wait()\n res = res_d.get().sum(dtype=\"float64\")\n self.assertEqual(ref64, res, \"test_dot4\")\n\n res_d.fill(0)\n data0 = numpy.array([data[0], data[4], data[12]])\n data1 = numpy.array([data[3], data[11], data[15]])\n ref64 = numpy.dot(data0.astype(numpy.float64), data1.astype(numpy.float64))\n ref32 = numpy.dot(data0, data1)\n if (ref64 == ref32):\n logger.warning(\"dot3: invalid tests as float32 provides the same result as float64\")\n evt = prg.test_dot3(self.queue, (1,), (1,), ones_d.data, numpy.int32(N), res_d.data)\n evt.wait()\n res = res_d.get().sum(dtype=\"float64\")\n self.assertEqual(ref64, res, \"test_dot3\")\n\n res_d.fill(0)\n data0 = numpy.array([data[0], data[14]])\n data1 = numpy.array([data[1], data[15]])\n ref64 = numpy.dot(data0.astype(numpy.float64), data1.astype(numpy.float64))\n ref32 = numpy.dot(data0, data1)\n if (ref64 == ref32):\n logger.warning(\"dot2: invalid tests as float32 provides the same result as float64\")\n evt = prg.test_dot2(self.queue, (1,), (1,), ones_d.data, numpy.int32(N), res_d.data)\n evt.wait()\n res = res_d.get().sum(dtype=\"float64\")\n self.assertEqual(ref64, res, \"test_dot2\")\n\n\ndef suite():\n testsuite = unittest.TestSuite()\n loader = unittest.defaultTestLoader.loadTestsFromTestCase\n testsuite.addTest(loader(TestMask))\n testsuite.addTest(loader(TestSort))\n testsuite.addTest(loader(TestKahan))\n return testsuite\n\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(suite())\n"
] | [
[
"numpy.dot",
"numpy.random.random",
"numpy.arange",
"numpy.int32",
"numpy.sort",
"numpy.array",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Colossalhavoc/PepeBot | [
"238f246e84696970a93eba508c3b084704b44944"
] | [
"stdplugins/ascii.py"
] | [
"# based on https://gist.github.com/wshanshan/c825efca4501a491447056849dd207d6\n# Ported for ProjectAlf by Alfiananda P.A\n# Kanged from @Nitesh_XD\n\nimport os\nimport random\n\nimport numpy as np\nfrom colour import Color\nfrom hachoir.metadata import extractMetadata\nfrom hachoir.parser import createParser\nfrom PIL import Image, ImageDraw, ImageFont\nfrom telethon.tl.types import DocumentAttributeFilename\n\nfrom uniborg import MODULE, SYNTAX\nfrom uniborg.util import admin_cmd, edit_or_reply\n\nMODULE.append(\"ascii\")\n\nbground = \"black\"\n\n\[email protected](admin_cmd(pattern=r\"(ascii|asciis)$\", outgoing=True, allow_sudo=True))\nasync def ascii(event):\n if not event.reply_to_msg_id:\n await edit_or_reply(event, \"`Reply to Any media..`\")\n return\n reply_message = await event.get_reply_message()\n if not reply_message.media:\n await edit_or_reply(event, \"`Reply to a image/sticker/video`\")\n return\n a = await edit_or_reply(event, \"`Downloading Media..`\")\n if reply_message.photo:\n IMG = await bot.download_media(\n reply_message,\n \"ascii.png\",\n )\n elif (\n DocumentAttributeFilename(file_name=\"AnimatedSticker.tgs\")\n in reply_message.media.document.attributes\n ):\n await bot.download_media(\n reply_message,\n \"ASCII.tgs\",\n )\n os.system(\"lottie_convert.py ASCII.tgs ascii.png\")\n IMG = \"ascii.png\"\n elif reply_message.video:\n video = await bot.download_media(\n reply_message,\n \"ascii.mp4\",\n )\n extractMetadata(createParser(video))\n os.system(\"ffmpeg -i ascii.mp4 -vframes 1 -an -s 480x360 -ss 1 ascii.png\")\n IMG = \"ascii.png\"\n else:\n IMG = await bot.download_media(\n reply_message,\n \"ascii.png\",\n )\n try:\n await a.edit(\"`Processing..`\")\n list = await random_color()\n color1 = list[0]\n color2 = list[1]\n bgcolor = bground\n await asciiart(IMG, color1, color2, bgcolor)\n cmd = event.pattern_match.group(1)\n if cmd == \"asciis\":\n os.system(\"cp ascii.png ascii.webp\")\n ascii_file = \"ascii.webp\"\n else:\n ascii_file = \"ascii.png\"\n await event.client.send_file(\n event.chat_id,\n ascii_file,\n force_document=False,\n reply_to=event.reply_to_msg_id,\n )\n await a.delete()\n os.system(\"rm *.png *.webp *.mp4 *.tgs\")\n except BaseException as e:\n os.system(\"rm *.png *.webp *.mp4 *.tgs\")\n return await edit_or_reply(event, str(e))\n\n\nasync def asciiart(IMG, color1, color2, bgcolor):\n chars = np.asarray(list(\" .,:irs?@9B&#\"))\n font = ImageFont.load_default()\n letter_width = font.getsize(\"x\")[0]\n letter_height = font.getsize(\"x\")[1]\n WCF = letter_height / letter_width\n img = Image.open(IMG)\n widthByLetter = round(img.size[0] * 0.15 * WCF)\n heightByLetter = round(img.size[1] * 0.15)\n S = (widthByLetter, heightByLetter)\n img = img.resize(S)\n img = np.sum(np.asarray(img), axis=2)\n img -= img.min()\n img = (1.0 - img / img.max()) ** 2.2 * (chars.size - 1)\n lines = (\"\\n\".join((\"\".join(r) for r in chars[img.astype(int)]))).split(\"\\n\")\n nbins = len(lines)\n colorRange = list(Color(color1).range_to(Color(color2), nbins))\n newImg_width = letter_width * widthByLetter\n newImg_height = letter_height * heightByLetter\n newImg = Image.new(\"RGBA\", (newImg_width, newImg_height), bgcolor)\n draw = ImageDraw.Draw(newImg)\n leftpadding = 0\n y = 0\n lineIdx = 0\n for line in lines:\n color = colorRange[lineIdx]\n lineIdx += 1\n draw.text((leftpadding, y), line, color.hex, font=font)\n y += letter_height\n IMG = newImg.save(\"ascii.png\")\n return IMG\n\n\n# this is from userge\nasync def random_color():\n color = [\n \"#\" + \"\".join([random.choice(\"0123456789ABCDEF\") for k in range(6)])\n for i in range(2)\n ]\n return color\n\n\[email protected](admin_cmd(pattern=r\"asciibg(?: |$)(.*)\", outgoing=True, allow_sudo=True))\nasync def _(event):\n BG = event.pattern_match.group(1)\n if BG.isnumeric():\n return await event.edit(\"`Please Input a color not a number!`\")\n elif BG:\n global bground\n bground = BG\n else:\n return await event.edit(\"`Please insert bg of ascii`\")\n await event.edit(f\"`Successfully set bg of ascii to` **{BG}**\")\n\n\nSYNTAX.update(\n {\n \"ascii\": \">`.ascii`\\n\"\n \"Usage: create ascii art from media\\n\\n\"\n \">`.asciis`\\n\"\n \"Usage: same but upload the result as sticker\\n\\n\"\n \">`.asciibg <color>`\\n\"\n \"Usage: to change background color of this ascii module\"\n }\n)\n"
] | [
[
"numpy.asarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.