repo_name
stringlengths
8
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
andreeaiana/geneg_benchmarking
[ "0b53989c79b8e3771c144c0332fd36587dfe0f4d" ]
[ "src/ripplenet_data_loader.py" ]
[ "# -*- coding: utf-8 -*-\n\n# DISCLAIMER\n# This code file is forked and adapted from https://github.com/tezignlab/RippleNet-TF2/blob/master/tools/load_data.py, which is under an MIT license.\n\n\"\"\" Utilities for data loading for RippleNet. \"\"\"\n\n# import libraries\nimport os\nimport numpy as np\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, List, Tuple\n\n# import custom code\nfrom src.util.logger import setup_logging\nfrom src.util.caching import create_cache, load_cache\nfrom src.config import FILENAME_RATINGS_FINAL_TXT, FILENAME_RATINGS_FINAL_NPY, FILENAME_KG_FINAL_TXT, FILENAME_KG_FINAL_NPY, FILENAME_TRAIN_RATINGS, FILENAME_USER_HISTORY_DICT\nfrom src.config import FILENAME_TEST_RATINGS, FILENAME_TEST_RATINGS_RANDOM, FILENAME_TEST_RATINGS_NO_TFIDF, FILENAME_TEST_RATINGS_NO_WORD2VEC, FILENAME_TEST_RATINGS_NO_TRANSFORMER\n\n\nclass LoadData:\n def __init__(self, args):\n self.args = args\n self.logger = setup_logging(name=__file__, log_level='info')\n\n def load_data(self) -> Tuple[np.ndarray, np.ndarray, int, int, Dict[int, List[Tuple[int, int, int]]]]:\n \"\"\" \n Loads and returns the data needed in RippleNet.\n\n Returns:\n - :obj:`np.ndarray`: \n Training set of ratings.\n - :obj:`np.ndarray`:\n Test set of ratings.\n - :obj:`int`:\n Number of entities.\n - :obj:`int`:\n Number of relations.\n - :obj:`Dict[int, List[Tuple[int, int, int]]]`:\n Ripple sets of each user.\n \"\"\"\n\n train_data, test_data, user_history_dict = self.load_rating()\n n_entity, n_relation, kg = self.load_kg()\n ripple_set = self.get_ripple_set(kg, user_history_dict)\n return train_data, test_data, n_entity, n_relation, ripple_set\n\n def get_test_file(self, test_set_type: str) -> Path:\n \"\"\" \n Retrieves the filepath of a test set given its type.\n\n Args:\n test_set_type (:obj:`str`):\n The type of test set.\n\n Returns:\n :obj:`Path`:\n The filepath of the test set.\n \"\"\"\n test_set_type2file = {\n 'complete': FILENAME_TEST_RATINGS,\n 'random': FILENAME_TEST_RATINGS_RANDOM,\n 'no_tfidf_ratings': FILENAME_TEST_RATINGS_NO_TFIDF,\n 'no_word2vec_ratings': FILENAME_TEST_RATINGS_NO_WORD2VEC,\n 'no_transformer_ratings': FILENAME_TEST_RATINGS_NO_TRANSFORMER\n }\n return test_set_type2file[test_set_type]\n\n def load_rating(self) -> Tuple[np.ndarray, np.ndarray, Dict[int, List[int]]]:\n \"\"\"\n It loads the training and test data, and the user history, if they exist.\n Otherwise, it loads the user ratings, processes them to construct the training and test sets, and user history, and caches them to disk.\n\n Returns:\n - :obj:`np.ndarray`: \n Training set of ratings.\n - :obj:`np.ndarray`: \n Test set of ratings.\n - :obj:`Dict[int, List[int]]`: \n User history dictionary.\n \"\"\"\n self.logger.info('Reading rating file.')\n\n test_file = self.get_test_file(self.args.test_set) \n\n if os.path.exists(FILENAME_TRAIN_RATINGS) and os.path.exists(test_file) and os.path.exists(FILENAME_USER_HISTORY_DICT):\n self.logger.info('Loading training and test data.')\n train_data = np.load(FILENAME_TRAIN_RATINGS)\n test_data = np.load(test_file)\n user_history_dict = load_cache(FILENAME_USER_HISTORY_DICT)\n\n self.logger.info(f'Size training data: {train_data.shape}.')\n self.logger.info(f'Size test data: {test_data.shape}.')\n else:\n # Read rating file\n if os.path.exists(FILENAME_RATINGS_FINAL_NPY):\n rating_np = np.load(FILENAME_RATINGS_FINAL_NPY)\n else:\n rating_np = np.loadtxt(FILENAME_RATINGS_FINAL_TXT, dtype=np.int32)\n np.save(FILENAME_RATINGS_FINAL_NPY, rating_np)\n\n # Split dataset\n self.logger.info('Splitting dataset.')\n test_ratio = 0.2\n n_ratings = rating_np.shape[0]\n\n test_indices = np.random.choice(n_ratings, size=int(n_ratings * test_ratio), replace=False)\n train_indices = set(range(n_ratings)) - set(test_indices)\n\n # Traverse training data, only keeping the users with positive ratings\n user_history_dict = dict()\n for i in train_indices:\n user = rating_np[i][0]\n item = rating_np[i][1]\n rating = rating_np[i][2]\n if rating == 1:\n if user not in user_history_dict:\n user_history_dict[user] = []\n user_history_dict[user].append(item)\n\n train_indices = [i for i in train_indices if rating_np[i][0] in user_history_dict]\n test_indices = [i for i in test_indices if rating_np[i][0] in user_history_dict]\n\n train_data = rating_np[train_indices]\n test_data = rating_np[test_indices]\n self.logger.info(f'Size training data: {train_data.shape}.')\n self.logger.info(f'Size test data: {test_data.shape}.')\n\n # Cache test and train data\n np.save(FILENAME_TRAIN_RATINGS, train_data)\n np.save(FILENAME_TEST_RATINGS, test_data)\n create_cache(user_history_dict, FILENAME_USER_HISTORY_DICT)\n\n self.logger.info('Finished.\\n')\n\n return train_data, test_data, user_history_dict\n\n def load_kg(self) -> Tuple[int, int, Dict[int, List[Tuple[int, int]]]]:\n \"\"\" \n Loads the knowledge graph if already cached as :obj:`np.ndarray`, otherwise it constructs it from the text file. \n \n Returns:\n - :obj:`int`: \n Number of entities.\n - :obj:`int`:\n Number of relations.\n - :obj:`Dict[int, List[Tuple[int, int]]]`:\n The knowledge graph as a dictionary which maps each head entity to a tuple of the form (tail, relation).\n \"\"\"\n self.logger.info('Reading KG file.')\n\n # Reading KG file\n if os.path.exists(FILENAME_KG_FINAL_NPY):\n kg_np = np.load(FILENAME_KG_FINAL_NPY)\n else:\n kg_np = np.loadtxt(FILENAME_KG_FINAL_TXT, dtype=np.int32)\n np.save(FILENAME_KG_FINAL_NPY, kg_np)\n\n n_entity = len(set(kg_np[:, 0]) | set(kg_np[:, 2]))\n n_relation = len(set(kg_np[:, 1]))\n\n self.logger.info('Constructing knowledge graph.')\n kg = defaultdict(list)\n for head, relation, tail in kg_np:\n kg[head].append((tail, relation))\n\n self.logger.info('Finished.\\n')\n\n return n_entity, n_relation, kg\n\n def get_ripple_set(self, kg: Dict[int, List[Tuple[int, int]]], user_history_dict: Dict[int, List[int]]) -> Dict[int, List[Tuple[int, int, int]]]:\n \"\"\" \n Creates the ripple set for each user. \n\n Args:\n kg (:obj:`Dict[int, List[Tuple[int, int]]]`):\n The knowledge graph as a dictionary which maps each head entity to a tuple of the form (tail, relation).\n user_history_dict (:obj:`Dict[int, List[int]]`):\n User history dictionary.\n\n Returns:\n :obj:`Dict[int, List[Tuple[int, int, int]]]`:\n Ripple sets of each user.\n \"\"\"\n self.logger.info('Constructing ripple set.')\n\n # user -> [(hop_0_heads, hop_0_relations, hop_0_tails), (hop_1_heads, hop_1_relations, hop_1_tails), ...]\n ripple_set = defaultdict(list)\n\n for user in user_history_dict:\n for h in range(self.args.n_hop):\n memories_h = []\n memories_r = []\n memories_t = []\n\n if h == 0:\n tails_of_last_hop = user_history_dict[user]\n else:\n tails_of_last_hop = ripple_set[user][-1][2]\n\n for entity in tails_of_last_hop:\n for tail_and_relation in kg[entity]:\n memories_h.append(entity)\n memories_r.append(tail_and_relation[1])\n memories_t.append(tail_and_relation[0])\n\n \"\"\"\n If the current ripple set of the given user is empty, we simply copy the ripple set of the last hop here\n This won't happen for h = 0, because only the items that appear in the KG have been selected.\n \"\"\"\n if len(memories_h) == 0:\n ripple_set[user].append(ripple_set[user][-1])\n else:\n # Sample a fixed-size 1-hop memory for each user\n replace = len(memories_h) < self.args.n_memory\n indices = np.random.choice(len(memories_h), size=self.args.n_memory, replace=replace)\n memories_h = [memories_h[i] for i in indices]\n memories_r = [memories_r[i] for i in indices]\n memories_t = [memories_t[i] for i in indices]\n ripple_set[user].append((memories_h, memories_r, memories_t))\n \n self.logger.info('Finished.\\n')\n return ripple_set\n" ]
[ [ "numpy.load", "numpy.save", "numpy.loadtxt" ] ]
ankitbhatia/word-mastermind
[ "51529b04e6e1bb150c867e0f6e44f36131c33189" ]
[ "scripts/name_creator.py" ]
[ "import csv\nimport glob\nimport pandas as pd\n\nfiles = glob.glob(\"data/*.txt\")\n\nnames = {}\n\nfor file in files:\n with open(file) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n name = row[0]\n sex = row[1]\n number = row[2]\n if name not in names.keys():\n names[name] = {}\n names[name]['freq'] = number\n names[name]['sex'] = sex\n names[name]['count'] = len(name)\n else:\n names[name]['freq'] += number\n\n\ndf = pd.DataFrame.from_dict(names, orient='index')\n\nwith open(\"dict/names\",'w') as f:\n for v in df[df['count']==5].index.values:\n f.write(v + '\\n')\n \n\n\n\n\n \n\n" ]
[ [ "pandas.DataFrame.from_dict" ] ]
ChambinLee/Pointnet_Pointnet2_pytorch
[ "c5612493ce3bbdbb18a65eefc0dc8d90e09da74d" ]
[ "data_utils/ModelNetDataLoader.py" ]
[ "'''\n@author: Xu Yan\n@file: ModelNet.py\n@time: 2021/3/19 15:51\n'''\nimport os\nimport numpy as np\nimport warnings\nimport pickle\n\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset\n\nwarnings.filterwarnings('ignore')\n\n\ndef pc_normalize(pc):\n centroid = np.mean(pc, axis=0)\n pc = pc - centroid\n m = np.max(np.sqrt(np.sum(pc**2, axis=1)))\n pc = pc / m\n return pc\n\n\ndef farthest_point_sample(point, npoint):\n \"\"\"\n Input:\n xyz: pointcloud data, [N, D]\n npoint: number of samples\n Return:\n centroids: sampled pointcloud index, [npoint, D]\n \"\"\"\n N, D = point.shape\n xyz = point[:,:3]\n centroids = np.zeros((npoint,))\n distance = np.ones((N,)) * 1e10\n farthest = np.random.randint(0, N)\n for i in range(npoint):\n centroids[i] = farthest\n centroid = xyz[farthest, :]\n dist = np.sum((xyz - centroid) ** 2, -1)\n mask = dist < distance\n distance[mask] = dist[mask]\n farthest = np.argmax(distance, -1)\n point = point[centroids.astype(np.int32)]\n return point\n\n\nclass ModelNetDataLoader(Dataset):\n def __init__(self, root, args, split='train', process_data=False):\n self.root = root\n self.npoints = args.num_point\n self.process_data = process_data\n self.uniform = args.use_uniform_sample\n self.use_normals = args.use_normals\n self.num_category = args.num_category\n\n if self.num_category == 10:\n self.catfile = os.path.join(self.root, 'modelnet10_shape_names.txt')\n else:\n self.catfile = os.path.join(self.root, 'modelnet40_shape_names.txt')\n\n self.cat = [line.rstrip() for line in open(self.catfile)]\n self.classes = dict(zip(self.cat, range(len(self.cat))))\n\n shape_ids = {}\n if self.num_category == 10:\n shape_ids['train'] = [line.rstrip() for line in open(os.path.join(self.root, 'modelnet10_train.txt'))]\n shape_ids['test'] = [line.rstrip() for line in open(os.path.join(self.root, 'modelnet10_test.txt'))]\n else:\n shape_ids['train'] = [line.rstrip() for line in open(os.path.join(self.root, 'modelnet40_train.txt'))]\n shape_ids['test'] = [line.rstrip() for line in open(os.path.join(self.root, 'modelnet40_test.txt'))]\n\n assert (split == 'train' or split == 'test')\n shape_names = ['_'.join(x.split('_')[0:-1]) for x in shape_ids[split]]\n self.datapath = [(shape_names[i], os.path.join(self.root, shape_names[i], shape_ids[split][i]) + '.txt') for i\n in range(len(shape_ids[split]))]\n print('The size of %s data is %d' % (split, len(self.datapath)))\n\n if self.uniform:\n self.save_path = os.path.join(root, 'modelnet%d_%s_%dpts_fps.dat' % (self.num_category, split, self.npoints))\n else:\n self.save_path = os.path.join(root, 'modelnet%d_%s_%dpts.dat' % (self.num_category, split, self.npoints))\n\n if self.process_data:\n if not os.path.exists(self.save_path):\n print('Processing data %s (only running in the first time)...' % self.save_path)\n self.list_of_points = [None] * len(self.datapath)\n self.list_of_labels = [None] * len(self.datapath)\n\n for index in tqdm(range(len(self.datapath)), total=len(self.datapath)):\n fn = self.datapath[index]\n cls = self.classes[self.datapath[index][0]]\n cls = np.array([cls]).astype(np.int32)\n point_set = np.genfromtxt(fn[1], delimiter=',').astype(np.float32)\n\n if self.uniform:\n point_set = farthest_point_sample(point_set, self.npoints)\n else:\n point_set = point_set[0:self.npoints, :]\n\n self.list_of_points[index] = point_set\n self.list_of_labels[index] = cls\n\n with open(self.save_path, 'wb') as f:\n pickle.dump([self.list_of_points, self.list_of_labels], f)\n else:\n print('Load processed data from %s...' % self.save_path)\n with open(self.save_path, 'rb') as f:\n self.list_of_points, self.list_of_labels = pickle.load(f)\n\n def __len__(self):\n return len(self.datapath)\n\n def _get_item(self, index):\n if self.process_data:\n point_set, label = self.list_of_points[index], self.list_of_labels[index]\n else:\n fn = self.datapath[index]\n cls = self.classes[self.datapath[index][0]]\n label = np.array([cls]).astype(np.int32)\n point_set = np.loadtxt(fn[1], delimiter=',').astype(np.float32)\n\n if self.uniform:\n point_set = farthest_point_sample(point_set, self.npoints)\n else:\n point_set = point_set[0:self.npoints, :]\n \n point_set[:, 0:3] = pc_normalize(point_set[:, 0:3])\n if not self.use_normals:\n point_set = point_set[:, 0:3]\n\n return point_set, label[0]\n\n def __getitem__(self, index):\n return self._get_item(index)\n\n\nif __name__ == '__main__':\n import torch\n\n data = ModelNetDataLoader('/data/modelnet40_normal_resampled/', split='train')\n DataLoader = torch.utils.data.DataLoader(data, batch_size=12, shuffle=True)\n for point, label in DataLoader:\n print(point.shape)\n print(label.shape)\n" ]
[ [ "torch.utils.data.DataLoader", "numpy.ones", "numpy.sum", "numpy.zeros", "numpy.argmax", "numpy.loadtxt", "numpy.array", "numpy.genfromtxt", "numpy.random.randint", "numpy.mean" ] ]
txya900619/Intern-Training
[ "76cac20ac988609f313765ebeb72d20da9dcc05e" ]
[ "eunice012716/Week2/ch4/4.3/exercise2.py" ]
[ "import torch\nfrom torch import nn\nfrom d2l import torch as d2l\n\nBATCH_SIZE, LR, NUM_EPOCHS = 256, 0.1, 10\nACTIVATE_FUNCS = [nn.ReLU(), nn.Sigmoid(), nn.Tanh()]\n\n\ndef init_weights(m):\n if type(m) == nn.Linear:\n nn.init.normal_(m.weight, std=0.01)\n\n\nif __name__ == \"__main__\":\n for i in range(0, 3):\n net = nn.Sequential(\n nn.Flatten(),\n nn.Linear(784, 256),\n ACTIVATE_FUNCS[i],\n nn.Linear(256, 10),\n )\n net.apply(init_weights)\n\n loss = nn.CrossEntropyLoss()\n trainer = torch.optim.SGD(net.parameters(), lr=LR)\n\n train_iter, test_iter = d2l.load_data_fashion_mnist(BATCH_SIZE)\n d2l.train_ch3(net, train_iter, test_iter, loss, NUM_EPOCHS, trainer)\n\n print(\"Train Accuracy\", d2l.evaluate_accuracy(net, train_iter))\n print(\"Test Accuracy\", d2l.evaluate_accuracy(net, test_iter))\n" ]
[ [ "torch.nn.Linear", "torch.nn.Flatten", "torch.nn.init.normal_", "torch.nn.CrossEntropyLoss", "torch.nn.Tanh", "torch.nn.Sigmoid", "torch.nn.ReLU" ] ]
niqbal996/paz
[ "9fbd50b993f37e1e807297a29c6044c09967c9cc" ]
[ "tests/paz/backend/processor.py" ]
[ "from paz.core import Processor\nfrom paz.core import SequentialProcessor\nimport numpy as np\n\n\nclass ProcessorA(Processor):\n def __init__(self):\n super(ProcessorA, self).__init__()\n\n def call(self, image, boxes):\n boxes = boxes - 1.0\n return image, boxes\n\n\nclass ProcessorB(Processor):\n def __init__(self):\n super(ProcessorB, self).__init__()\n\n def call(self, image, boxes):\n boxes = boxes - 2.0\n return image, boxes\n\n\nclass ProcessorC(Processor):\n def __init__(self, probability=0.5):\n super(ProcessorC, self).__init__()\n\n def call(self, image):\n return image / 255.0\n\n\nclass TransformA(SequentialProcessor):\n def __init__(self):\n super(TransformA, self).__init__()\n self.add(ProcessorC())\n\n\nclass TransformB(SequentialProcessor):\n def __init__(self):\n super(TransformB, self).__init__()\n self.add(ProcessorA())\n self.add(ProcessorB())\n self.add(ProcessorB())\n\n\nclass TransformC(SequentialProcessor):\n def __init__(self):\n super(TransformB, self).__init__()\n self.add(ProcessorA())\n\n\ndef test_arg_in_sequential_processor_input():\n transformA = TransformA()\n values = transformA(255.0)\n assert np.isclose(values == 1.0)\n\n\ndef test_kwargs_in_sequential_processor_input():\n transformB = TransformB()\n values = transformB(image=1.0, boxes=2.0)\n assert np.allclose([1.0, -3.0], values)\n\n\ndef test_kwargs_invariance_in_sequential_processor_input():\n transformB = TransformB()\n values = transformB(boxes=2.0, image=1.0)\n assert np.allclose([1.0, -3.0], values)\n\n\ndef test_flipped_kwargs_in_sequential_processor_input():\n transformB = TransformB()\n values = transformB(boxes=1.0, image=2.0)\n assert np.allclose([2.0, -4.0], values)\n" ]
[ [ "numpy.allclose", "numpy.isclose" ] ]
pedroMoya/M5_kaggle_uncertainty_share
[ "f1dea9af9ec2e29e9bccb21d9b6e3627dff14c6e" ]
[ "5.2_CUSTOM_LIBRARY/model_analyzer.py" ]
[ "# Model architecture analyzer\nimport os\nimport logging\nimport logging.handlers as handlers\nimport json\nimport numpy as np\nimport tensorflow as tf\nphysical_devices = tf.config.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], enable=True)\ntf.keras.backend.set_floatx('float32')\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.experimental import PeepholeLSTMCell\nfrom tensorflow.keras.layers import TimeDistributed\nfrom tensorflow.keras.layers import RepeatVector\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import losses, models\nfrom tensorflow.keras import metrics\nfrom tensorflow.keras import callbacks as cb\nfrom tensorflow.keras import backend as kb\nfrom sklearn.metrics import mean_squared_error\nfrom tensorflow.keras.utils import plot_model, model_to_dot\n\n# open local settings\nwith open('./settings.json') as local_json_file:\n local_submodule_settings = json.loads(local_json_file.read())\n local_json_file.close()\n\n# log setup\ncurrent_script_name = os.path.basename(__file__).split('.')[0]\nlog_path_filename = ''.join([local_submodule_settings['log_path'], current_script_name, '.log'])\nlogging.basicConfig(filename=log_path_filename, level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(name)s %(message)s')\nlogger = logging.getLogger(__name__)\nlogHandler = handlers.RotatingFileHandler(log_path_filename, maxBytes=10485760, backupCount=5)\nlogger.addHandler(logHandler)\n\n\nclass model_structure:\n\n def analize(self, local_model_name, local_settings):\n try:\n # loading model (h5 format)\n print('trying to open model file (assuming h5 format)')\n local_model = models.load_model(''.join([local_settings['models_path'], local_model_name]))\n # saving architecture in JSON format\n local_model_json = local_model.to_json()\n with open(''.join([local_settings['models_path'], local_model_name,\n '_analyzed_.json']), 'w') as json_file:\n json_file.write(local_model_json)\n json_file.close()\n # changing for subclassing to functional model\n local_model_json = json.loads(local_model_json)\n print(type(local_model_json))\n local_batch_size = None\n local_time_step_days = local_model_json['config']['build_input_shape'][1]\n local_features = local_model_json['config']['build_input_shape'][2]\n input_layer = layers.Input(batch_shape=(local_batch_size, local_time_step_days, local_features))\n prev_layer = input_layer\n for layer in local_model.layers:\n prev_layer = layer(prev_layer)\n functional_model = models.Model([input_layer], [prev_layer])\n # plotting (exporting to png) the model\n plot_path = ''.join([local_settings['models_path'], local_model_name, '_model.png'])\n # model_to_dot(functional_model, show_shapes=True, show_layer_names=True, rankdir='TB',\n # expand_nested=True, dpi=96, subgraph=True)\n plot_model(functional_model, to_file=plot_path, show_shapes=True, show_layer_names=True,\n rankdir='TB', expand_nested=True, dpi=216)\n plot_model(functional_model, to_file=''.join([plot_path, '.pdf']), show_shapes=True, show_layer_names=True,\n rankdir='TB', expand_nested=True)\n except Exception as e1:\n print('Error reading or saving model')\n print(e1)\n return False\n return True\n" ]
[ [ "tensorflow.config.experimental.set_memory_growth", "tensorflow.keras.utils.plot_model", "tensorflow.keras.models.Model", "tensorflow.keras.backend.set_floatx", "tensorflow.config.list_physical_devices", "tensorflow.keras.layers.Input" ] ]
luiscarlosgph/easyipc
[ "befe03bd2d1bf9f8378bcdf391dbeac8576bd723" ]
[ "tests/test_easyipc.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @brief This module has unit tests for the classes of EasyIPC.\n# @author Luis C. Garcia-Peraza Herrera ([email protected]).\n# @date 25 June 2020.\n\nimport unittest\nimport os\nimport sys\nimport numpy as np\n\n# My imports\nimport easyipc\n\nclass TestEasyIPC(unittest.TestCase):\n \n def test_pipe(self):\n data = [np.random.rand(1000, 1000) for i in range(100)]\n newpid = os.fork()\n if newpid == 0:\n client = easyipc.Pipe('hoho')\n client.connect()\n client.send_whatever({'Hello': 'from the client'})\n for i in range(len(data)):\n client.send_array(data[i])\n else:\n server = easyipc.Pipe('hoho')\n server.listen()\n \n whatever = None\n while whatever is None:\n whatever = server.recv_whatever(blocking=False)\n self.assertTrue(whatever['Hello'] == 'from the client')\n \n for i in range(len(data)):\n data_back = server.recv_array()\n self.assertTrue(np.sum(data[i] - data_back) == 0)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.sum", "numpy.random.rand" ] ]
juangamella/icp
[ "80548610a13b6b76515f46f56e0f7f486cf9c1c7" ]
[ "causalicp/test/tests_icp.py" ]
[ "# Copyright 2021 Juan L. Gamella\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n\n# 2. 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\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n# ---------------------------------------------------------------------\n# Unit tests\n\nimport unittest\nimport numpy as np\nimport copy\n\n# Tested functions\nfrom causalicp.data import _Data\n\n\nclass DataTests(unittest.TestCase):\n\n def setUp(self):\n self.p = 20\n self.n_obs = [2, 3, 4]\n self.N = np.sum(self.n_obs)\n self.e = len(self.n_obs)\n self.target = 3\n XX = []\n for i, ne in enumerate(self.n_obs):\n X = np.tile(np.ones(self.p), (ne, 1))\n X *= (i + 1)\n X[:, self.target] *= -1\n XX.append(X)\n self.XX = XX\n\n def test_basic(self):\n data = _Data(self.XX)\n self.assertEqual(data.N, self.N)\n self.assertTrue((data.n_obs == self.n_obs).all())\n self.assertEqual(data.p, self.p)\n self.assertEqual(data.e, self.e)\n self.assertEqual(data.e, len(self.XX))\n\n def test_memory(self):\n # Test that the data is copied into the class\n XX = copy.deepcopy(self.XX)\n data = _Data(XX)\n XX[0][0, 0] = -100\n data_pooled = data._pooled_data\n self.assertFalse(data_pooled[0, 0] == XX[0][0, 0])\n" ]
[ [ "numpy.sum", "numpy.ones" ] ]
yqzhangthu/tatk
[ "fafabc45d02ad889f59354acac4e3b1367e7d4bf" ]
[ "tatk/policy/mdrg/multiwoz/model.py" ]
[ "import json\nimport math\nimport operator\nimport os\nimport random\nfrom io import open\nfrom queue import PriorityQueue\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\n\nimport functools\n\nimport tatk.policy.mdrg.multiwoz.default_policy as policy\n\nSOS_token = 0\nEOS_token = 1\nUNK_token = 2\nPAD_token = 3\n\n\n# Shawn beam search decoding\nclass BeamSearchNode(object):\n def __init__(self, h, prevNode, wordid, logp, leng):\n self.h = h\n self.prevNode = prevNode\n self.wordid = wordid\n self.logp = logp\n self.leng = leng\n\n def eval(self, repeatPenalty, tokenReward, scoreTable, alpha=1.0):\n reward = 0\n alpha = 1.0\n\n return self.logp / float(self.leng - 1 + 1e-6) + alpha * reward\n\n\ndef init_lstm(cell, gain=1):\n init_gru(cell, gain)\n\n # positive forget gate bias (Jozefowicz et al., 2015)\n for _, _, ih_b, hh_b in cell.all_weights:\n l = len(ih_b)\n ih_b[l // 4:l // 2].data.fill_(1.0)\n hh_b[l // 4:l // 2].data.fill_(1.0)\n\n\ndef init_gru(gru, gain=1):\n gru.reset_parameters()\n for _, hh, _, _ in gru.all_weights:\n for i in range(0, hh.size(0), gru.hidden_size):\n torch.nn.init.orthogonal_(hh[i:i+gru.hidden_size],gain=gain)\n\n\ndef whatCellType(input_size, hidden_size, cell_type, dropout_rate):\n if cell_type == 'rnn':\n cell = nn.RNN(input_size, hidden_size, dropout=dropout_rate, batch_first=False)\n init_gru(cell)\n return cell\n elif cell_type == 'gru':\n cell = nn.GRU(input_size, hidden_size, dropout=dropout_rate, batch_first=False)\n init_gru(cell)\n return cell\n elif cell_type == 'lstm':\n cell = nn.LSTM(input_size, hidden_size, dropout=dropout_rate, batch_first=False)\n init_lstm(cell)\n return cell\n elif cell_type == 'bigru':\n cell = nn.GRU(input_size, hidden_size, bidirectional=True, dropout=dropout_rate, batch_first=False)\n init_gru(cell)\n return cell\n elif cell_type == 'bilstm':\n cell = nn.LSTM(input_size, hidden_size, bidirectional=True, dropout=dropout_rate, batch_first=False)\n init_lstm(cell)\n return cell\n\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, embedding_size, hidden_size, cell_type, depth, dropout):\n super(EncoderRNN, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.embed_size = embedding_size\n self.n_layers = depth\n self.dropout = dropout\n self.bidirectional = False\n if 'bi' in cell_type:\n self.bidirectional = True\n padding_idx = 3\n self.embedding = nn.Embedding(input_size, embedding_size, padding_idx=padding_idx)\n self.rnn = whatCellType(embedding_size, hidden_size,\n cell_type, dropout_rate=self.dropout)\n\n def forward(self, input_seqs, input_lens, hidden=None):\n \"\"\"\n forward procedure. **No need for inputs to be sorted**\n :param input_seqs: Variable of [T,B]\n :param hidden:\n :param input_lens: *numpy array* of len for each input sequence\n :return:\n \"\"\"\n input_lens = np.asarray(input_lens)\n input_seqs = input_seqs.transpose(0,1)\n #batch_size = input_seqs.size(1)\n embedded = self.embedding(input_seqs)\n embedded = embedded.transpose(0, 1) # [B,T,E]\n sort_idx = np.argsort(-input_lens)\n unsort_idx = torch.LongTensor(np.argsort(sort_idx))\n input_lens = input_lens[sort_idx]\n sort_idx = torch.LongTensor(sort_idx)\n embedded = embedded[sort_idx].transpose(0, 1) # [T,B,E]\n packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lens)\n outputs, hidden = self.rnn(packed, hidden)\n outputs, _ = torch.nn.utils.rnn.pad_packed_sequence(outputs)\n if self.bidirectional:\n outputs = outputs[:, :, :self.hidden_size] + outputs[:, :, self.hidden_size:]\n\n outputs = outputs.transpose(0, 1)[unsort_idx].transpose(0, 1).contiguous()\n\n if isinstance(hidden, tuple):\n hidden = list(hidden)\n hidden[0] = hidden[0].transpose(0, 1)[unsort_idx].transpose(0, 1).contiguous()\n hidden[1] = hidden[1].transpose(0, 1)[unsort_idx].transpose(0, 1).contiguous()\n hidden = tuple(hidden)\n else:\n hidden = hidden.transpose(0, 1)[unsort_idx].transpose(0, 1).contiguous()\n\n return outputs, hidden\n\n\nclass Attn(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n self.method = method\n self.hidden_size = hidden_size\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.rand(hidden_size))\n stdv = 1. / math.sqrt(self.v.size(0))\n self.v.data.normal_(mean=0, std=stdv)\n\n def forward(self, hidden, encoder_outputs):\n '''\n :param hidden:\n previous hidden state of the decoder, in shape (layers*directions,B,H)\n :param encoder_outputs:\n encoder outputs from Encoder, in shape (T,B,H)\n :return\n attention energies in shape (B,T)\n '''\n max_len = encoder_outputs.size(0)\n\n H = hidden.repeat(max_len,1,1).transpose(0,1)\n encoder_outputs = encoder_outputs.transpose(0,1) # [T,B,H] -> [B,T,H]\n attn_energies = self.score(H,encoder_outputs) # compute attention score\n return F.softmax(attn_energies, dim=1).unsqueeze(1) # normalize with softmax\n\n def score(self, hidden, encoder_outputs):\n cat = torch.cat([hidden, encoder_outputs], 2)\n energy = torch.tanh(self.attn(cat)) # [B*T*2H]->[B*T*H]\n energy = energy.transpose(2,1) # [B*H*T]\n v = self.v.repeat(encoder_outputs.data.shape[0],1).unsqueeze(1) #[B*1*H]\n energy = torch.bmm(v,energy) # [B*1*T]\n return energy.squeeze(1) # [B*T]\n\n\nclass SeqAttnDecoderRNN(nn.Module):\n def __init__(self, embedding_size, hidden_size, output_size, cell_type, dropout_p=0.1, max_length=30):\n super(SeqAttnDecoderRNN, self).__init__()\n # Define parameters\n self.hidden_size = hidden_size\n self.embed_size = embedding_size\n self.output_size = output_size\n self.n_layers = 1\n self.dropout_p = dropout_p\n\n # Define layers\n self.embedding = nn.Embedding(output_size, embedding_size)\n self.dropout = nn.Dropout(dropout_p)\n\n if 'bi' in cell_type: # we dont need bidirectionality in decoding\n cell_type = cell_type.strip('bi')\n self.rnn = whatCellType(embedding_size + hidden_size, hidden_size, cell_type, dropout_rate=self.dropout_p)\n self.out = nn.Linear(hidden_size, output_size)\n\n self.score = nn.Linear(self.hidden_size + self.hidden_size, self.hidden_size)\n self.attn_combine = nn.Linear(embedding_size + hidden_size, embedding_size)\n\n # attention\n self.method = 'concat'\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.rand(hidden_size))\n stdv = 1. / math.sqrt(self.v.size(0))\n self.v.data.normal_(mean=0, std=stdv)\n\n def forward(self, input, hidden, encoder_outputs):\n if isinstance(hidden, tuple):\n h_t = hidden[0]\n else:\n h_t = hidden\n encoder_outputs = encoder_outputs.transpose(0, 1)\n embedded = self.embedding(input) # .view(1, 1, -1)\n # embedded = F.dropout(embedded, self.dropout_p)\n\n # SCORE 3\n max_len = encoder_outputs.size(1)\n h_t = h_t.transpose(0, 1) # [1,B,D] -> [B,1,D]\n h_t = h_t.repeat(1, max_len, 1) # [B,1,D] -> [B,T,D]\n energy = self.attn(torch.cat((h_t, encoder_outputs), 2)) # [B,T,2D] -> [B,T,D]\n energy = torch.tanh(energy)\n energy = energy.transpose(2, 1) # [B,H,T]\n v = self.v.repeat(encoder_outputs.size(0), 1).unsqueeze(1) # [B,1,H]\n energy = torch.bmm(v, energy) # [B,1,T]\n attn_weights = F.softmax(energy, dim=2) # [B,1,T]\n\n # getting context\n context = torch.bmm(attn_weights, encoder_outputs) # [B,1,H]\n\n # context = torch.bmm(attn_weights.unsqueeze(0), encoder_outputs.unsqueeze(0)) #[B,1,H]\n # Combine embedded input word and attended context, run through RNN\n rnn_input = torch.cat((embedded, context), 2)\n rnn_input = rnn_input.transpose(0, 1)\n output, hidden = self.rnn(rnn_input, hidden)\n output = output.squeeze(0) # (1,B,V)->(B,V)\n\n output = F.log_softmax(self.out(output), dim=1)\n return output, hidden # , attn_weights\n\n\nclass DecoderRNN(nn.Module):\n def __init__(self, embedding_size, hidden_size, output_size, cell_type, dropout=0.1):\n super(DecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.cell_type = cell_type\n padding_idx = 3\n self.embedding = nn.Embedding(num_embeddings=output_size,\n embedding_dim=embedding_size,\n padding_idx=padding_idx\n )\n if 'bi' in cell_type: # we dont need bidirectionality in decoding\n cell_type = cell_type.strip('bi')\n self.rnn = whatCellType(embedding_size, hidden_size, cell_type, dropout_rate=dropout)\n self.dropout_rate = dropout\n self.out = nn.Linear(hidden_size, output_size)\n\n def forward(self, input, hidden, not_used):\n embedded = self.embedding(input).transpose(0, 1) # [B,1] -> [ 1,B, D]\n embedded = F.dropout(embedded, self.dropout_rate)\n\n output = embedded\n #output = F.relu(embedded)\n\n output, hidden = self.rnn(output, hidden)\n\n out = self.out(output.squeeze(0))\n output = F.log_softmax(out, dim=1)\n\n return output, hidden\n\n\nclass Model(nn.Module):\n def __init__(self, args, input_lang_index2word, output_lang_index2word, input_lang_word2index, output_lang_word2index):\n super(Model, self).__init__()\n self.args = args\n self.max_len = args.max_len\n\n self.output_lang_index2word = output_lang_index2word\n self.input_lang_index2word = input_lang_index2word\n\n self.output_lang_word2index = output_lang_word2index\n self.input_lang_word2index = input_lang_word2index\n\n self.hid_size_enc = args.hid_size_enc\n self.hid_size_dec = args.hid_size_dec\n self.hid_size_pol = args.hid_size_pol\n\n self.emb_size = args.emb_size\n self.db_size = args.db_size\n self.bs_size = args.bs_size\n self.cell_type = args.cell_type\n if 'bi' in self.cell_type:\n self.num_directions = 2\n else:\n self.num_directions = 1\n self.depth = args.depth\n self.use_attn = args.use_attn\n self.attn_type = args.attention_type\n\n self.dropout = args.dropout\n self.device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\n self.model_dir = args.model_dir\n self.model_name = args.model_name\n self.teacher_forcing_ratio = args.teacher_ratio\n self.vocab_size = args.vocab_size\n self.epsln = 10E-5\n\n\n torch.manual_seed(args.seed)\n self.build_model()\n self.getCount()\n try:\n assert self.args.beam_width > 0\n self.beam_search = True\n except:\n self.beam_search = False\n\n self.global_step = 0\n\n def cuda_(self, var):\n return var.cuda() if self.args.cuda else var\n\n def build_model(self):\n self.encoder = EncoderRNN(len(self.input_lang_index2word), self.emb_size, self.hid_size_enc,\n self.cell_type, self.depth, self.dropout).to(self.device)\n\n self.policy = policy.DefaultPolicy(self.hid_size_pol, self.hid_size_enc, self.db_size, self.bs_size).to(self.device)\n\n if self.use_attn:\n if self.attn_type == 'bahdanau':\n self.decoder = SeqAttnDecoderRNN(self.emb_size, self.hid_size_dec, len(self.output_lang_index2word), self.cell_type, self.dropout, self.max_len).to(self.device)\n else:\n self.decoder = DecoderRNN(self.emb_size, self.hid_size_dec, len(self.output_lang_index2word), self.cell_type, self.dropout).to(self.device)\n\n if self.args.mode == 'train':\n self.gen_criterion = nn.NLLLoss(ignore_index=3, size_average=True) # logsoftmax is done in decoder part\n self.setOptimizers()\n\n def train(self, input_tensor, input_lengths, target_tensor, target_lengths, db_tensor, bs_tensor, dial_name=None):\n proba, _, decoded_sent = self.forward(input_tensor, input_lengths, target_tensor, target_lengths, db_tensor, bs_tensor)\n\n proba = proba.view(-1, self.vocab_size)\n self.gen_loss = self.gen_criterion(proba, target_tensor.view(-1))\n\n self.loss = self.gen_loss\n self.loss.backward()\n grad = self.clipGradients()\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n #self.printGrad()\n return self.loss.item(), 0, grad\n\n def setOptimizers(self):\n self.optimizer_policy = None\n if self.args.optim == 'sgd':\n self.optimizer = optim.SGD(lr=self.args.lr_rate, params=filter(lambda x: x.requires_grad, self.parameters()), weight_decay=self.args.l2_norm)\n elif self.args.optim == 'adadelta':\n self.optimizer = optim.Adadelta(lr=self.args.lr_rate, params=filter(lambda x: x.requires_grad, self.parameters()), weight_decay=self.args.l2_norm)\n elif self.args.optim == 'adam':\n self.optimizer = optim.Adam(lr=self.args.lr_rate, params=filter(lambda x: x.requires_grad, self.parameters()), weight_decay=self.args.l2_norm)\n\n def forward(self, input_tensor, input_lengths, target_tensor, target_lengths, db_tensor, bs_tensor):\n \"\"\"Given the user sentence, user belief state and database pointer,\n encode the sentence, decide what policy vector construct and\n feed it as the first hiddent state to the decoder.\"\"\"\n target_length = target_tensor.size(1)\n\n # for fixed encoding this is zero so it does not contribute\n batch_size, seq_len = input_tensor.size()\n\n # ENCODER\n encoder_outputs, encoder_hidden = self.encoder(input_tensor, input_lengths)\n\n # POLICY\n decoder_hidden = self.policy(encoder_hidden, db_tensor, bs_tensor)\n\n # GENERATOR\n # Teacher forcing: Feed the target as the next input\n _, target_len = target_tensor.size()\n decoder_input = torch.LongTensor([[SOS_token] for _ in range(batch_size)], device=self.device)\n\n proba = torch.zeros(batch_size, target_length, self.vocab_size) # [B,T,V]\n\n for t in range(target_len):\n decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden, encoder_outputs)\n\n use_teacher_forcing = True if random.random() < self.args.teacher_ratio else False\n if use_teacher_forcing:\n decoder_input = target_tensor[:, t].view(-1, 1) # [B,1] Teacher forcing\n else:\n # Without teacher forcing: use its own predictions as the next input\n topv, topi = decoder_output.topk(1)\n decoder_input = topi.squeeze().detach() # detach from history as input\n\n proba[:, t, :] = decoder_output\n\n decoded_sent = None\n\n return proba, None, decoded_sent\n\n def predict(self, input_tensor, input_lengths, target_tensor, target_lengths, db_tensor, bs_tensor):\n with torch.no_grad():\n # ENCODER\n encoder_outputs, encoder_hidden = self.encoder(input_tensor, input_lengths)\n\n # POLICY\n decoder_hidden = self.policy(encoder_hidden, db_tensor, bs_tensor)\n\n # GENERATION\n decoded_words = self.decode(target_tensor, decoder_hidden, encoder_outputs)\n\n return decoded_words, 0\n\n def decode(self, target_tensor, decoder_hidden, encoder_outputs):\n decoder_hiddens = decoder_hidden\n\n if self.beam_search: # wenqiang style - sequicity\n decoded_sentences = []\n for idx in range(target_tensor.size(0)):\n if isinstance(decoder_hiddens, tuple): # LSTM case\n decoder_hidden = (decoder_hiddens[0][:,idx, :].unsqueeze(0),decoder_hiddens[1][:,idx, :].unsqueeze(0))\n else:\n decoder_hidden = decoder_hiddens[:, idx, :].unsqueeze(0)\n encoder_output = encoder_outputs[:,idx, :].unsqueeze(1)\n\n # Beam start\n self.topk = 1\n endnodes = [] # stored end nodes\n number_required = min((self.topk + 1), self.topk - len(endnodes))\n decoder_input = torch.LongTensor([[SOS_token]], device=self.device)\n\n # starting node hidden vector, prevNode, wordid, logp, leng,\n node = BeamSearchNode(decoder_hidden, None, decoder_input, 0, 1)\n nodes = PriorityQueue() # start the queue\n nodes.put((-node.eval(None, None, None, None),\n node))\n\n # start beam search\n qsize = 1\n while True:\n # give up when decoding takes too long\n if qsize > 2000: break\n\n # fetch the best node\n score, n = nodes.get()\n decoder_input = n.wordid\n decoder_hidden = n.h\n\n if n.wordid.item() == EOS_token and n.prevNode != None: # its not empty\n endnodes.append((score, n))\n # if reach maximum # of sentences required\n if len(endnodes) >= number_required:\n break\n else:\n continue\n\n # decode for one step using decoder\n decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden, encoder_output)\n\n log_prob, indexes = torch.topk(decoder_output, self.args.beam_width)\n nextnodes = []\n\n for new_k in range(self.args.beam_width):\n decoded_t = indexes[0][new_k].view(1, -1)\n log_p = log_prob[0][new_k].item()\n\n node = BeamSearchNode(decoder_hidden, n, decoded_t, n.logp + log_p, n.leng + 1)\n score = -node.eval(None, None, None, None)\n nextnodes.append((score, node))\n\n # put them into queue\n for i in range(len(nextnodes)):\n score, nn = nextnodes[i]\n nodes.put((score, nn))\n\n # increase qsize\n qsize += len(nextnodes)\n\n # choose nbest paths, back trace them\n if len(endnodes) == 0:\n endnodes = [nodes.get() for n in range(self.topk)]\n\n utterances = []\n for score, n in sorted(endnodes, key=operator.itemgetter(0)):\n utterance = []\n utterance.append(n.wordid)\n # back trace\n while n.prevNode != None:\n n = n.prevNode\n utterance.append(n.wordid)\n\n utterance = utterance[::-1]\n utterances.append(utterance)\n\n decoded_words = utterances[0]\n decoded_sentence = [self.output_index2word(str(ind.item())) for ind in decoded_words]\n #print(decoded_sentence)\n decoded_sentences.append(' '.join(decoded_sentence[1:-1]))\n\n return decoded_sentences\n\n else: # GREEDY DECODING\n decoded_sentences = self.greedy_decode(decoder_hidden, encoder_outputs, target_tensor)\n return decoded_sentences\n\n def greedy_decode(self, decoder_hidden, encoder_outputs, target_tensor):\n decoded_sentences = []\n batch_size, seq_len = target_tensor.size()\n decoder_input = torch.LongTensor([[SOS_token] for _ in range(batch_size)], device=self.device)\n\n decoded_words = torch.zeros((batch_size, self.max_len))\n for t in range(self.max_len):\n decoder_output, decoder_hidden = self.decoder(decoder_input, decoder_hidden, encoder_outputs)\n\n topv, topi = decoder_output.data.topk(1) # get candidates\n topi = topi.view(-1)\n\n decoded_words[:, t] = topi\n decoder_input = topi.detach().view(-1, 1)\n\n for sentence in decoded_words:\n sent = []\n for ind in sentence:\n if self.output_index2word(str(int(ind.item()))) == self.output_index2word(str(EOS_token)):\n break\n sent.append(self.output_index2word(str(int(ind.item()))))\n decoded_sentences.append(' '.join(sent))\n\n return decoded_sentences\n\n def clipGradients(self):\n grad = torch.nn.utils.clip_grad_norm_(self.parameters(), self.args.clip)\n return grad\n\n def saveModel(self, iter):\n print('Saving parameters..')\n if not os.path.exists(os.path.join(os.path.dirname(__file__), self.model_dir)):\n os.makedirs(os.path.join(os.path.dirname(__file__), self.model_dir))\n # print(self.model_dir)\n\n torch.save(self.encoder.state_dict(), os.path.join(os.path.dirname(__file__), self.model_dir + self.model_name + '-' + str(iter) + '.enc'))\n torch.save(self.policy.state_dict(), os.path.join(os.path.dirname(__file__), self.model_dir + self.model_name + '-' + str(iter) + '.pol'))\n torch.save(self.decoder.state_dict(), os.path.join(os.path.dirname(__file__), self.model_dir + self.model_name + '-' + str(iter) + '.dec'))\n\n with open(os.path.join(os.path.dirname(__file__), self.model_dir + self.model_name + '.config'), 'w') as f:\n f.write(json.dumps(vars(self.args), ensure_ascii=False, indent=4))\n\n def loadModel(self, iter=0):\n print('Loading parameters of iter %s ' % iter)\n self.encoder.load_state_dict(torch.load(os.path.join(os.path.dirname(__file__), self.model_dir + self.model_name + '-' + str(iter) + '.enc')))\n self.policy.load_state_dict(torch.load(os.path.join(os.path.dirname(__file__), self.model_dir + self.model_name + '-' + str(iter) + '.pol')))\n self.decoder.load_state_dict(torch.load(os.path.join(os.path.dirname(__file__), self.model_dir + self.model_name + '-' + str(iter) + '.dec')))\n\n def input_index2word(self, index):\n if index in self.input_lang_index2word.has_key:\n return self.input_lang_index2word[index]\n else:\n raise UserWarning('We are using UNK')\n\n def output_index2word(self, index):\n if index in self.output_lang_index2word:\n return self.output_lang_index2word[index]\n else:\n raise UserWarning('We are using UNK')\n\n def input_word2index(self, index):\n if index in self.input_lang_word2index:\n return self.input_lang_word2index[index]\n else:\n return 2\n\n def output_word2index(self, index):\n if index in self.output_lang_word2index:\n return self.output_lang_word2index[index]\n else:\n return 2\n\n def getCount(self):\n learnable_parameters = filter(lambda p: p.requires_grad, self.parameters())\n param_cnt = sum([functools.reduce((lambda x, y: x * y), param.shape) for param in learnable_parameters])\n print('Model has', param_cnt, ' parameters.')\n\n def printGrad(self):\n learnable_parameters = filter(lambda p: p.requires_grad, self.parameters())\n for idx, param in enumerate(learnable_parameters):\n print(param.grad, param.shape)\n" ]
[ [ "torch.nn.functional.softmax", "torch.rand", "torch.no_grad", "numpy.argsort", "numpy.asarray", "torch.nn.GRU", "torch.bmm", "torch.nn.Dropout", "torch.cat", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.functional.dropout", "torch.tanh", "torch.device", "torch.nn.LSTM", "torch.manual_seed", "torch.nn.NLLLoss", "torch.nn.functional.log_softmax", "torch.nn.Linear", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Embedding", "torch.topk", "torch.nn.RNN", "torch.zeros", "torch.LongTensor", "torch.nn.init.orthogonal_" ] ]
zhangxu999/magenta
[ "60b85828cc69cff855fabce78b51ddaddc873a5d" ]
[ "magenta/models/arbitrary_image_stylization/arbitrary_image_stylization_distill_mobilenet.py" ]
[ "# Copyright 2020 The Magenta 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\"\"\"Distills a trained style prediction network using a MobileNetV2.\n\"\"\"\nimport ast\nimport os\n\nfrom magenta.models.arbitrary_image_stylization import arbitrary_image_stylization_build_mobilenet_model as build_mobilenet_model\nfrom magenta.models.arbitrary_image_stylization import arbitrary_image_stylization_build_model as build_model\nfrom magenta.models.image_stylization import image_utils\nimport tensorflow.compat.v1 as tf\nimport tf_slim as slim\n\nDEFAULT_CONTENT_WEIGHTS = '{\"vgg_16/conv3\": 1}'\nDEFAULT_STYLE_WEIGHTS = ('{\"vgg_16/conv1\": 0.5e-3, \"vgg_16/conv2\": 0.5e-3,'\n ' \"vgg_16/conv3\": 0.5e-3, \"vgg_16/conv4\": 0.5e-3}')\n\nflags = tf.app.flags\nflags.DEFINE_float('clip_gradient_norm', 0, 'Clip gradients to this norm')\nflags.DEFINE_float('learning_rate', 1e-5, 'Learning rate')\nflags.DEFINE_float('total_variation_weight', 1e4, 'Total variation weight')\nflags.DEFINE_string('content_weights', DEFAULT_CONTENT_WEIGHTS,\n 'Content weights')\nflags.DEFINE_string('style_weights', DEFAULT_STYLE_WEIGHTS, 'Style weights')\nflags.DEFINE_integer('batch_size', 8, 'Batch size.')\nflags.DEFINE_integer('image_size', 256, 'Image size.')\nflags.DEFINE_boolean('random_style_image_size', True,\n 'Whether to resize the style images '\n 'to a random size or not.')\nflags.DEFINE_boolean(\n 'augment_style_images', True,\n 'Whether to augment style images or not.')\nflags.DEFINE_boolean('center_crop', False,\n 'Whether to center crop the style images.')\nflags.DEFINE_integer('ps_tasks', 0,\n 'Number of parameter servers. If 0, parameters '\n 'are handled locally by the worker.')\nflags.DEFINE_integer('save_summaries_secs', 15,\n 'Frequency at which summaries are saved, in seconds.')\nflags.DEFINE_integer('save_interval_secs', 15,\n 'Frequency at which the model is saved, in seconds.')\nflags.DEFINE_integer('task', 0, 'Task ID. Used when training with multiple '\n 'workers to identify each worker.')\nflags.DEFINE_integer('train_steps', 8000000, 'Number of training steps.')\nflags.DEFINE_string('master', '', 'BNS name of the TensorFlow master to use.')\nflags.DEFINE_string('style_dataset_file', None, 'Style dataset file.')\nflags.DEFINE_string('train_dir', None,\n 'Directory for checkpoints and summaries.')\nflags.DEFINE_string('initial_checkpoint', None,\n 'Path to the pre-trained arbitrary_image_stylization '\n 'checkpoint')\nflags.DEFINE_string('mobilenet_checkpoint', 'mobilenet_v2_1.0_224.ckpt',\n 'Path to the pre-trained mobilenet checkpoint')\nflags.DEFINE_boolean('use_true_loss', False,\n 'Add true style loss term based on VGG.')\nflags.DEFINE_float('true_loss_weight', 1e-9,\n 'Scale factor for real loss')\n\nFLAGS = flags.FLAGS\n\n\ndef main(unused_argv=None):\n tf.logging.set_verbosity(tf.logging.INFO)\n with tf.Graph().as_default():\n # Forces all input processing onto CPU in order to reserve the GPU for the\n # forward inference and back-propagation.\n device = '/cpu:0' if not FLAGS.ps_tasks else '/job:worker/cpu:0'\n with tf.device(\n tf.train.replica_device_setter(FLAGS.ps_tasks, worker_device=device)):\n # Load content images\n content_inputs_, _ = image_utils.imagenet_inputs(FLAGS.batch_size,\n FLAGS.image_size)\n\n # Loads style images.\n [style_inputs_, _,\n style_inputs_orig_] = image_utils.arbitrary_style_image_inputs(\n FLAGS.style_dataset_file,\n batch_size=FLAGS.batch_size,\n image_size=FLAGS.image_size,\n shuffle=True,\n center_crop=FLAGS.center_crop,\n augment_style_images=FLAGS.augment_style_images,\n random_style_image_size=FLAGS.random_style_image_size)\n\n with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks)):\n # Process style and content weight flags.\n content_weights = ast.literal_eval(FLAGS.content_weights)\n style_weights = ast.literal_eval(FLAGS.style_weights)\n\n # Define the model\n stylized_images, \\\n true_loss, \\\n _, \\\n bottleneck_feat = build_mobilenet_model.build_mobilenet_model(\n content_inputs_,\n style_inputs_,\n mobilenet_trainable=True,\n style_params_trainable=False,\n style_prediction_bottleneck=100,\n adds_losses=True,\n content_weights=content_weights,\n style_weights=style_weights,\n total_variation_weight=FLAGS.total_variation_weight,\n )\n\n _, inception_bottleneck_feat = build_model.style_prediction(\n style_inputs_,\n [],\n [],\n is_training=False,\n trainable=False,\n inception_end_point='Mixed_6e',\n style_prediction_bottleneck=100,\n reuse=None,\n )\n\n print('PRINTING TRAINABLE VARIABLES')\n for x in tf.trainable_variables():\n print(x)\n\n mse_loss = tf.losses.mean_squared_error(\n inception_bottleneck_feat, bottleneck_feat)\n total_loss = mse_loss\n if FLAGS.use_true_loss:\n true_loss = FLAGS.true_loss_weight*true_loss\n total_loss += true_loss\n\n if FLAGS.use_true_loss:\n tf.summary.scalar('mse', mse_loss)\n tf.summary.scalar('true_loss', true_loss)\n tf.summary.scalar('total_loss', total_loss)\n tf.summary.image('image/0_content_inputs', content_inputs_, 3)\n tf.summary.image('image/1_style_inputs_orig', style_inputs_orig_, 3)\n tf.summary.image('image/2_style_inputs_aug', style_inputs_, 3)\n tf.summary.image('image/3_stylized_images', stylized_images, 3)\n\n mobilenet_variables_to_restore = slim.get_variables_to_restore(\n include=['MobilenetV2'],\n exclude=['global_step'])\n\n optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)\n train_op = slim.learning.create_train_op(\n total_loss,\n optimizer,\n clip_gradient_norm=FLAGS.clip_gradient_norm,\n summarize_gradients=False\n )\n\n init_fn = slim.assign_from_checkpoint_fn(\n FLAGS.initial_checkpoint,\n slim.get_variables_to_restore(\n exclude=['MobilenetV2', 'mobilenet_conv', 'global_step']))\n init_pretrained_mobilenet = slim.assign_from_checkpoint_fn(\n FLAGS.mobilenet_checkpoint, mobilenet_variables_to_restore)\n\n def init_sub_networks(session):\n init_fn(session)\n init_pretrained_mobilenet(session)\n\n slim.learning.train(\n train_op=train_op,\n logdir=os.path.expanduser(FLAGS.train_dir),\n master=FLAGS.master,\n is_chief=FLAGS.task == 0,\n number_of_steps=FLAGS.train_steps,\n init_fn=init_sub_networks,\n save_summaries_secs=FLAGS.save_summaries_secs,\n save_interval_secs=FLAGS.save_interval_secs)\n\n\ndef console_entry_point():\n tf.disable_v2_behavior()\n tf.app.run(main)\n\n\nif __name__ == '__main__':\n console_entry_point()\n" ]
[ [ "tensorflow.compat.v1.summary.scalar", "tensorflow.compat.v1.Graph", "tensorflow.compat.v1.train.AdamOptimizer", "tensorflow.compat.v1.losses.mean_squared_error", "tensorflow.compat.v1.summary.image", "tensorflow.compat.v1.train.replica_device_setter", "tensorflow.compat.v1.disable_v2_behavior", "tensorflow.compat.v1.app.run", "tensorflow.compat.v1.trainable_variables", "tensorflow.compat.v1.logging.set_verbosity" ] ]
UKPLab/curriculum-annotation
[ "1d6ca490ea180019bb09d1d3818874f4321d4d0f" ]
[ "experiments/ca/ext.py" ]
[ "from typing import List, Tuple\n\nimport pandas as pd\n\n\[email protected]_dataframe_accessor(\"tag\")\nclass CaTaggingAccessor:\n def __init__(self, df: pd.DataFrame):\n self._df = df\n\n def group_by_sentences(self):\n yield from (x[1] for x in self._df.groupby(\"sentence_id\"))\n\n def group_by_documents(self):\n yield from (x[1] for x in self._df.groupby(\"document_id\"))\n\n def number_of_sentences(self):\n return len(self._df.groupby(\"sentence_id\"))\n\n def number_of_documents(self):\n return len(self._df.groupby(\"document_id\"))\n\n def split_x_y_sentencewise(self) -> Tuple[List[List[str]], List[List[str]]]:\n X = []\n y = []\n\n for sent in self._df.tag.group_by_sentences():\n words = list(sent[\"word\"])\n labels = list(sent[\"label\"])\n\n X.append(words)\n y.append(labels)\n\n return X, y\n\n def get_times_per_document(self) -> List[int]:\n t = []\n\n # Right now, we assume that the time per token is the same\n # for a sentence. This might be an invalid assumption\n for df in self._df.tag.group_by_sentences():\n t.append(df[\"t\"].values[0])\n\n return t\n\n def group_by_documents_x_y(self) -> Tuple[List[List[List[str]]], List[List[List[str]]]]:\n \"\"\"Returns a list of documents that each contain a list of sentences and\n their respective labels grouped the same way.\n \"\"\"\n X = []\n y = []\n\n for doc in self._df.tag.group_by_documents():\n X_doc = []\n y_doc = []\n for sent in doc.tag.group_by_sentences():\n words = list(sent[\"word\"])\n labels = list(sent[\"label\"])\n\n X_doc.append(words)\n y_doc.append(labels)\n\n X.append(X_doc)\n y.append(y_doc)\n\n return X, y\n\n def group_by_sentences_x_y(self) -> Tuple[List[List[str]], List[List[str]]]:\n \"\"\"Returns a list of sentences and their respective labels grouped the same way.\"\"\"\n X = []\n y = []\n\n for sent in self._df.tag.group_by_sentences():\n words = list(sent[\"word\"])\n labels = list(sent[\"label\"])\n\n assert len(words) == len(labels)\n\n X.append(words)\n y.append(labels)\n\n return X, y\n\n\[email protected]_dataframe_accessor(\"dclass\")\nclass CaDocumentClassificationAccessor:\n def __init__(self, df: pd.DataFrame):\n self._df = df\n\n def split_x_y(self) -> Tuple[List[str], List[str]]:\n X = self._df[\"sentence\"]\n y = self._df[\"label\"]\n return X.values.tolist(), y.values.tolist()\n\n def get_time_per_sentence(self) -> List[int]:\n return self._df[\"t\"].values.tolist()\n\n\[email protected]_dataframe_accessor(\"pair\")\nclass CaPairAccessor:\n def __init__(self, df: pd.DataFrame):\n self._df = df\n\n def split_args_y(self) -> Tuple[List[str], List[str], List[str]]:\n args1 = self._df[\"arg1\"].values.tolist()\n args2 = self._df[\"arg2\"].values.tolist()\n label = self._df[\"label\"].values.tolist()\n return args1, args2, label\n\n def get_time_per_sentence(self) -> List[int]:\n return self._df[\"t\"].values.tolist()\n" ]
[ [ "pandas.api.extensions.register_dataframe_accessor" ] ]
gmittal/jax
[ "281816221dea03c64f6d8b61253397c719c55feb" ]
[ "jax/_src/lax/lax.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Pytype is too slow to check this file.\n# pytype: skip-file\n\nimport builtins\nimport functools\nimport itertools\nimport operator\nfrom typing import (Any, Callable, List, NamedTuple, Optional, Sequence, Union, Tuple)\nimport warnings\n\nimport numpy as np\n\nimport jax\nfrom jax import core\nfrom jax import ad_util\nfrom jax import api\nfrom jax import api_util\nfrom jax import linear_util as lu\nfrom jax import dtypes\nfrom jax import lazy\nfrom jax import tree_util\nfrom jax.config import flags, config\nfrom jax.core import (Primitive, _canonicalize_dimension, UnshapedArray,\n ShapedArray, ConcreteArray, raise_to_shaped,\n abstract_token, canonicalize_shape)\nfrom jax.abstract_arrays import array_types\nfrom jax.interpreters import partial_eval as pe\nfrom jax.interpreters import xla\nfrom jax.interpreters import pxla\nfrom jax.interpreters import ad\nfrom jax.interpreters import invertible_ad as iad\nfrom jax.interpreters import batching\nfrom jax.interpreters import masking\nfrom jax.util import (cache, safe_zip, partial, prod, safe_map, canonicalize_axis,\n split_list)\nfrom jax.tree_util import tree_map\nfrom jax.lib import pytree\nfrom jax.lib import xla_bridge\nfrom jax.lib import xla_client\n\nxb = xla_bridge\nxc = xla_client\nxops = xla_client.ops\n\nFLAGS = flags.FLAGS\n\n_max = builtins.max\n_min = builtins.min\n_reduce = functools.reduce\n\nArray = Any\nDType = Any\nShape = Sequence[int]\n\ndef _try_broadcast_shapes(shapes):\n assert shapes\n if len(shapes) == 1: return shapes[0]\n rank, *others = {len(shape) for shape in shapes}\n if others: return None # must have consistent rank\n if not rank: return () # scalar case\n result_shape = [None] * rank\n for i, sizes in enumerate(zip(*shapes)):\n if sizes[:-1] == sizes[1:]:\n result_shape[i] = sizes[0] # all equal sizes for this dimension\n else:\n sizes = [d for d in sizes if d != 1]\n if sizes[:-1] != sizes[1:]:\n return None # must have equal sizes other than 1-sized axes\n result_shape[i] = sizes[0] if sizes else 1\n return tuple(result_shape)\n\n@cache()\ndef broadcast_shapes(*shapes):\n \"\"\"Returns the shape that results from NumPy broadcasting of `shapes`.\"\"\"\n if len(shapes) == 1:\n return shapes[0]\n ndim = _max(len(shape) for shape in shapes)\n shapes = [(1,) * (ndim - len(shape)) + shape for shape in shapes]\n result_shape = _try_broadcast_shapes(shapes)\n if result_shape is None:\n raise ValueError(\"Incompatible shapes for broadcasting: {}\"\n .format(tuple(map(tuple, shapes))))\n return result_shape\n\ndef _identity(x): return x\n\n### traceables\n\ndef neg(x: Array) -> Array:\n r\"\"\"Elementwise negation: :math:`-x`.\"\"\"\n return neg_p.bind(x)\n\ndef sign(x: Array) -> Array:\n r\"\"\"Elementwise sign.\n\n For floating-point inputs, returns\n :math:`\\mathrm{sign}(x) = \\begin{cases}\n -1 & x < 0\\\\\n -0 & x = -0\\\\\n \\mathit{NaN} & x = \\mathit{NaN}\\\\\n +0 & x = +0\\\\\n 1 & x > 0\n \\end{cases}`\n\n For signed integer inputs, returns\n :math:`\\mathrm{sign}(x) = \\begin{cases}\n -1 & x < 0\\\\\n 0 & x = 0\\\\\n 1 & x > 0\n \\end{cases}`\n\n For complex inputs, returns the complex phase, i.e.\n :math:`\\mathrm{sign}(x) = \\frac{x}{|x|}`.\n \"\"\"\n return sign_p.bind(x)\n\ndef nextafter(x1: Array, x2: Array) -> Array:\n r\"\"\"Returns the next representable value after `x1` in the direction of `x2`.\n\n Note that in some environments flush-denormal-to-zero semantics is used.\n This means that, around zero, this function returns strictly non-zero\n values which appear as zero in any operations. Consider this example::\n >>> jnp.nextafter(0, 1) # denormal numbers are representable\n DeviceArray(1.e-45, dtype=float32)\n >>> jnp.nextafter(0, 1) * 1 # but are flushed to zero\n DeviceArray(0., dtype=float32)\n\n For the smallest usable (i.e. normal) float, use ``tiny`` of ``jnp.finfo``.\n \"\"\"\n return nextafter_p.bind(_brcast(x1, x2), _brcast(x2, x1))\n\ndef floor(x: Array) -> Array:\n r\"\"\"Elementwise floor: :math:`\\left\\lfloor x \\right\\rfloor`.\"\"\"\n return floor_p.bind(x)\n\ndef ceil(x: Array) -> Array:\n r\"\"\"Elementwise ceiling: :math:`\\left\\lceil x \\right\\rceil`.\"\"\"\n return ceil_p.bind(x)\n\ndef round(x: Array) -> Array:\n r\"\"\"Elementwise round.\n\n Rounds values to the nearest integer. Halfway values (e.g., `0.5`) are rounded\n away from zero.\"\"\"\n return round_p.bind(x)\n\ndef is_finite(x: Array) -> Array:\n r\"\"\"Elementwise :math:`\\mathrm{isfinite}`.\n\n For each element x returns `True` if and only if x is not :math:`\\pm\\infty` or\n :math:`\\mathit{NaN}`.\n \"\"\"\n return is_finite_p.bind(x)\n\ndef exp(x: Array) -> Array:\n r\"\"\"Elementwise exponential: :math:`e^x`.\"\"\"\n return exp_p.bind(x)\n\ndef expm1(x: Array) -> Array:\n r\"\"\"Elementwise :math:`e^{x} - 1`.\"\"\"\n return expm1_p.bind(x)\n\ndef log(x: Array) -> Array:\n r\"\"\"Elementwise natural logarithm: :math:`\\mathrm{log}(x)`.\"\"\"\n return log_p.bind(x)\n\ndef log1p(x: Array) -> Array:\n r\"\"\"Elementwise :math:`\\mathrm{log}(1 + x)`.\"\"\"\n return log1p_p.bind(x)\n\ndef tanh(x: Array) -> Array:\n r\"\"\"Elementwise hyperbolic tangent: :math:`\\mathrm{tanh}(x)`.\"\"\"\n return tanh_p.bind(x)\n\ndef sin(x: Array) -> Array:\n r\"\"\"Elementwise sine: :math:`\\mathrm{sin}(x)`.\"\"\"\n return sin_p.bind(x)\n\ndef cos(x: Array) -> Array:\n r\"\"\"Elementwise cosine: :math:`\\mathrm{cos}(x)`.\"\"\"\n return cos_p.bind(x)\n\ndef atan2(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise arc tangent of two variables:\n :math:`\\mathrm{atan}({x \\over y})`.\"\"\"\n return atan2_p.bind(x, y)\n\ndef betainc(a: Array, b: Array, x: Array) -> Array:\n r\"\"\"Elementwise regularized incomplete beta integral.\"\"\"\n return regularized_incomplete_beta_p.bind(a, b, x)\n\ndef lgamma(x: Array) -> Array:\n r\"\"\"Elementwise log gamma: :math:`\\mathrm{log}(\\Gamma(x))`.\"\"\"\n return lgamma_p.bind(x)\n\ndef digamma(x: Array) -> Array:\n r\"\"\"Elementwise digamma: :math:`\\psi(x)`.\"\"\"\n return digamma_p.bind(x)\n\ndef igamma(a: Array, x: Array) -> Array:\n r\"\"\"Elementwise regularized incomplete gamma function.\"\"\"\n return igamma_p.bind(a, x)\n\ndef igammac(a: Array, x: Array) -> Array:\n r\"\"\"Elementwise complementary regularized incomplete gamma function.\"\"\"\n return igammac_p.bind(a, x)\n\ndef igamma_grad_a(a: Array, x: Array) -> Array:\n r\"\"\"Elementwise derivative of the regularized incomplete gamma function.\"\"\"\n return igamma_grad_a_p.bind(a, x)\n\ndef random_gamma_grad(a: Array, x: Array) -> Array:\n r\"\"\"Elementwise derivative of samples from `Gamma(a, 1)`.\"\"\"\n return random_gamma_grad_p.bind(a, x)\n\ndef bessel_i0e(x: Array) -> Array:\n r\"\"\"Exponentially scaled modified Bessel function of order 0:\n :math:`\\mathrm{i0e}(x) = e^{-|x|} \\mathrm{i0}(x)`\n \"\"\"\n return bessel_i0e_p.bind(x)\n\ndef bessel_i1e(x: Array) -> Array:\n r\"\"\"Exponentially scaled modified Bessel function of order 1:\n :math:`\\mathrm{i1e}(x) = e^{-|x|} \\mathrm{i1}(x)`\n \"\"\"\n return bessel_i1e_p.bind(x)\n\ndef erf(x: Array) -> Array:\n r\"\"\"Elementwise error function: :math:`\\mathrm{erf}(x)`.\"\"\"\n return erf_p.bind(x)\n\ndef erfc(x: Array) -> Array:\n r\"\"\"Elementwise complementary error function:\n :math:`\\mathrm{erfc}(x) = 1 - \\mathrm{erf}(x)`.\"\"\"\n return erfc_p.bind(x)\n\ndef erf_inv(x: Array) -> Array:\n r\"\"\"Elementwise inverse error function: :math:`\\mathrm{erf}^{-1}(x)`.\"\"\"\n return erf_inv_p.bind(x)\n\ndef real(x: Array) -> Array:\n r\"\"\"Elementwise extract real part: :math:`\\mathrm{Re}(x)`.\n\n Returns the real part of a complex number.\n \"\"\"\n return real_p.bind(x)\n\ndef imag(x: Array) -> Array:\n r\"\"\"Elementwise extract imaginary part: :math:`\\mathrm{Im}(x)`.\n\n Returns the imaginary part of a complex number.\n \"\"\"\n return imag_p.bind(x)\n\ndef complex(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise make complex number: :math:`x + jy`.\n\n Builds a complex number from real and imaginary parts.\n \"\"\"\n return complex_p.bind(_brcast(x, y), _brcast(y, x))\n\ndef conj(x: Array) -> Array:\n r\"\"\"Elementwise complex conjugate function: :math:`\\overline{x}`.\"\"\"\n return conj_p.bind(x, input_dtype=_dtype(x))\n\ndef abs(x: Array) -> Array:\n r\"\"\"Elementwise absolute value: :math:`|x|`.\"\"\"\n return abs_p.bind(x)\n\ndef pow(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise power: :math:`x^y`.\"\"\"\n return pow_p.bind(x, y)\n\ndef integer_pow(x: Array, y: int) -> Array:\n r\"\"\"Elementwise power: :math:`x^y`, where :math:`y` is a fixed integer.\"\"\"\n if y == 0:\n return _ones(x)\n elif y == 1:\n return x\n else:\n return integer_pow_p.bind(x, y=y)\n\ndef sqrt(x: Array) -> Array:\n r\"\"\"Elementwise square root: :math:`\\sqrt{x}`.\"\"\"\n return sqrt_p.bind(x)\n\ndef rsqrt(x: Array) -> Array:\n r\"\"\"Elementwise reciprocal square root: :math:`1 \\over \\sqrt{x}.\"\"\"\n return rsqrt_p.bind(x)\n\ndef bitwise_not(x: Array) -> Array:\n r\"\"\"Elementwise NOT: :math:`\\neg x`.\"\"\"\n return not_p.bind(x)\n\ndef bitwise_and(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise AND: :math:`x \\wedge y`.\"\"\"\n return and_p.bind(x, y)\n\ndef bitwise_or(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise OR: :math:`x \\vee y`.\"\"\"\n return or_p.bind(x, y)\n\ndef bitwise_xor(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise exclusive OR: :math:`x \\oplus y`.\"\"\"\n return xor_p.bind(x, y)\n\ndef population_count(x: Array) -> Array:\n r\"\"\"Elementwise popcount, count the number of set bits in each element.\"\"\"\n return population_count_p.bind(x)\n\ndef add(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise addition: :math:`x + y`.\"\"\"\n return add_p.bind(x, y)\n\ndef sub(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise subtraction: :math:`x - y`.\"\"\"\n return sub_p.bind(x, y)\n\ndef mul(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise multiplication: :math:`x \\times y`.\"\"\"\n return mul_p.bind(x, y)\n\ndef div(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise division: :math:`x \\over y`.\"\"\"\n return div_p.bind(x, y)\n\ndef rem(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise remainder: :math:`x \\bmod y`.\"\"\"\n return rem_p.bind(x, y)\n\ndef max(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise maximum: :math:`\\mathrm{max}(x, y)`\n\n For complex numbers, uses a lexicographic comparison on the\n `(real, imaginary)` pairs.\"\"\"\n return max_p.bind(x, y)\n\ndef min(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise minimum: :math:`\\mathrm{min}(x, y)`\n\n For complex numbers, uses a lexicographic comparison on the\n `(real, imaginary)` pairs.\"\"\"\n return min_p.bind(x, y)\n\ndef shift_left(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise left shift: :math:`x \\ll y`.\"\"\"\n return shift_left_p.bind(x, y)\n\ndef shift_right_arithmetic(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise arithmetic right shift: :math:`x \\gg y`.\"\"\"\n return shift_right_arithmetic_p.bind(x, y)\n\ndef shift_right_logical(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise logical right shift: :math:`x \\gg y`.\"\"\"\n return shift_right_logical_p.bind(x, y)\n\ndef eq(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise equals: :math:`x = y`.\"\"\"\n return eq_p.bind(x, y)\n\ndef ne(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise not-equals: :math:`x \\neq y`.\"\"\"\n return ne_p.bind(x, y)\n\ndef ge(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise greater-than-or-equals: :math:`x \\geq y`.\"\"\"\n return ge_p.bind(x, y)\n\ndef gt(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise greater-than: :math:`x > y`.\"\"\"\n return gt_p.bind(x, y)\n\ndef le(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise less-than-or-equals: :math:`x \\leq y`.\"\"\"\n return le_p.bind(x, y)\n\ndef lt(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise less-than: :math:`x < y`.\"\"\"\n return lt_p.bind(x, y)\n\ndef convert_element_type(operand: Array, new_dtype: DType) -> Array:\n \"\"\"Elementwise cast.\n\n Wraps XLA's `ConvertElementType\n <https://www.tensorflow.org/xla/operation_semantics#convertelementtype>`_\n operator, which performs an elementwise conversion from one type to another.\n Similar to a C++ `static_cast`.\n\n Args:\n operand: an array or scalar value to be cast\n new_dtype: the new type. Should be a NumPy type.\n\n Returns:\n An array with the same shape as `operand`, cast elementwise to `new_dtype`.\n \"\"\"\n new_dtype = dtypes.canonicalize_dtype(new_dtype)\n # Avoids dropping precision by casting Python scalars to the default Jax\n # type. If we passed a Python scalar directly to the bind call below, it is\n # cast to the default type as part of the calling convention.\n if type(operand) in dtypes.python_scalar_dtypes:\n operand = np.asarray(operand, new_dtype)\n old_dtype = dtypes.canonicalize_dtype(_dtype(operand))\n if old_dtype == new_dtype:\n return operand\n if (dtypes.issubdtype(old_dtype, np.complexfloating) and\n not dtypes.issubdtype(new_dtype, np.complexfloating)):\n msg = \"Casting complex values to real discards the imaginary part\"\n warnings.warn(msg, np.ComplexWarning, stacklevel=2)\n return convert_element_type_p.bind(\n operand, new_dtype=new_dtype, old_dtype=old_dtype)\n\ndef bitcast_convert_type(operand: Array, new_dtype: DType) -> Array:\n \"\"\"Elementwise bitcast.\n\n Wraps XLA's `BitcastConvertType\n <https://www.tensorflow.org/xla/operation_semantics#bitcastconverttype>`_\n operator, which performs a bit cast from one type to another. The bitwidth\n of the source and destination types must match.\n\n Args:\n operand: an array or scalar value to be cast\n new_dtype: the new type. Should be a NumPy type.\n\n Returns:\n An array with the same shape as `operand`, bitcast elementwise to\n `new_dtype`.\n \"\"\"\n new_dtype = dtypes.canonicalize_dtype(new_dtype)\n old_dtype = _dtype(operand)\n if old_dtype != new_dtype:\n return bitcast_convert_type_p.bind(operand, new_dtype=new_dtype)\n else:\n return operand\n\ndef clamp(min: Array, x: Array, max: Array) -> Array:\n r\"\"\"Elementwise clamp.\n\n Returns :math:`\\mathrm{clamp}(x) = \\begin{cases}\n \\mathit{min} & \\text{if } x < \\mathit{min},\\\\\n \\mathit{max} & \\text{if } x > \\mathit{max},\\\\\n x & \\text{otherwise}\n \\end{cases}`.\n \"\"\"\n return clamp_p.bind(min, x, max)\n\ndef concatenate(operands: Sequence[Array], dimension: int) -> Array:\n \"\"\"Concatenates a sequence of arrays along `dimension`.\n\n Wraps XLA's `Concatenate\n <https://www.tensorflow.org/xla/operation_semantics#concatenate>`_\n operator.\n\n Args:\n operands: a sequence of arrays to concatenate. The arrays must have equal\n shapes, except in the `dimension` axis.\n dimension: the dimension along which to concatenate the arrays.\n\n Returns:\n An array containing the concatenation.\n \"\"\"\n return concatenate_p.bind(*operands, dimension=dimension)\n\nPrecision = xla_client.PrecisionConfig.Precision\nPrecision.__str__ = lambda precision: precision.name\nPrecisionType = Any\nPrecisionLike = Union[None, PrecisionType, Tuple[PrecisionType, PrecisionType]]\n\n\nclass ConvDimensionNumbers(NamedTuple):\n \"\"\"Describes batch, spatial, and feature dimensions of a convolution.\n\n Args:\n lhs_spec: a tuple of nonnegative integer dimension numbers containing\n `(batch dimension, feature dimension, spatial dimensions...)`.\n rhs_spec: a tuple of nonnegative integer dimension numbers containing\n `(out feature dimension, in feature dimension, spatial dimensions...)`.\n out_spec: a tuple of nonnegative integer dimension numbers containing\n `(batch dimension, feature dimension, spatial dimensions...)`.\n \"\"\"\n lhs_spec: Sequence[int]\n rhs_spec: Sequence[int]\n out_spec: Sequence[int]\n\nConvGeneralDilatedDimensionNumbers = Union[\n None, ConvDimensionNumbers, Tuple[str, str, str]]\n\ndef conv_general_dilated(\n lhs: Array, rhs: Array, window_strides: Sequence[int],\n padding: Union[str, Sequence[Tuple[int, int]]],\n lhs_dilation: Optional[Sequence[int]] = None,\n rhs_dilation: Optional[Sequence[int]] = None,\n dimension_numbers: ConvGeneralDilatedDimensionNumbers = None,\n feature_group_count: int = 1, batch_group_count: int = 1,\n precision: PrecisionLike = None) -> Array:\n \"\"\"General n-dimensional convolution operator, with optional dilation.\n\n Wraps XLA's `Conv\n <https://www.tensorflow.org/xla/operation_semantics#conv_convolution>`_\n operator.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n window_strides: a sequence of `n` integers, representing the inter-window\n strides.\n padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of\n `n` `(low, high)` integer pairs that give the padding to apply before and\n after each spatial dimension.\n lhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `lhs`. LHS dilation\n is also known as transposed convolution.\n rhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `rhs`. RHS dilation\n is also known as atrous convolution.\n dimension_numbers: either `None`, a `ConvDimensionNumbers` object, or\n a 3-tuple `(lhs_spec, rhs_spec, out_spec)`, where each element is a string\n of length `n+2`.\n feature_group_count: integer, default 1. See XLA HLO docs.\n batch_group_count: integer, default 1. See XLA HLO docs.\n precision: Optional. Either ``None``, which means the default precision for\n the backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.\n\n Returns:\n An array containing the convolution result.\n\n In the string case of `dimension_numbers`, each character identifies by\n position:\n\n - the batch dimensions in `lhs`, `rhs`, and the output with the character\n 'N',\n - the feature dimensions in `lhs` and the output with the character 'C',\n - the input and output feature dimensions in rhs with the characters 'I'\n and 'O' respectively, and\n - spatial dimension correspondences between lhs, rhs, and the output using\n any distinct characters.\n\n For example, to indicate dimension numbers consistent with the `conv` function\n with two spatial dimensions, one could use `('NCHW', 'OIHW', 'NCHW')`. As\n another example, to indicate dimension numbers consistent with the TensorFlow\n Conv2D operation, one could use `('NHWC', 'HWIO', 'NHWC')`. When using the\n latter form of convolution dimension specification, window strides are\n associated with spatial dimension character labels according to the order in\n which the labels appear in the `rhs_spec` string, so that `window_strides[0]`\n is matched with the dimension corresponding to the first character\n appearing in rhs_spec that is not `'I'` or `'O'`.\n\n If `dimension_numbers` is `None`, the default is `('NCHW', 'OIHW', 'NCHW')`\n (for a 2D convolution).\n \"\"\"\n dnums = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)\n if lhs_dilation is None:\n lhs_dilation = (1,) * (lhs.ndim - 2)\n elif isinstance(padding, str) and not len(lhs_dilation) == lhs_dilation.count(1):\n raise ValueError(\n \"String padding is not implemented for transposed convolution \"\n \"using this op. Please either exactly specify the required padding or \"\n \"use conv_transpose.\")\n if rhs_dilation is None:\n rhs_dilation = (1,) * (rhs.ndim - 2)\n if isinstance(padding, str):\n lhs_perm, rhs_perm, _ = dnums\n rhs_shape = np.take(rhs.shape, rhs_perm)[2:]\n effective_rhs_shape = [(k-1) * r + 1 for k, r in zip(rhs_shape, rhs_dilation)]\n padding = padtype_to_pads(\n np.take(lhs.shape, lhs_perm)[2:], effective_rhs_shape,\n window_strides, padding)\n return conv_general_dilated_p.bind(\n lhs, rhs, window_strides=tuple(window_strides), padding=tuple(padding),\n lhs_dilation=tuple(lhs_dilation), rhs_dilation=tuple(rhs_dilation),\n dimension_numbers=dnums,\n feature_group_count=feature_group_count,\n batch_group_count=batch_group_count,\n lhs_shape=lhs.shape, rhs_shape=rhs.shape,\n precision=_canonicalize_precision(precision))\n\ndef dot(lhs: Array, rhs: Array, precision: PrecisionLike = None) -> Array:\n \"\"\"Vector/vector, matrix/vector, and matrix/matrix multiplication.\n\n Wraps XLA's `Dot\n <https://www.tensorflow.org/xla/operation_semantics#dot>`_\n operator.\n\n For more general contraction, see the `dot_general` operator.\n\n Args:\n lhs: an array of rank 1 or 2.\n rhs: an array of rank 1 or 2.\n precision: Optional. Either ``None``, which means the default precision for\n the backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.\n\n Returns:\n An array containing the product.\n \"\"\"\n if 1 <= lhs.ndim <= 2 and 1 <= rhs.ndim <= 2 and lhs.shape[-1] == rhs.shape[0]:\n return dot_general(lhs, rhs, (((lhs.ndim - 1,), (0,)), ((), ())),\n precision=precision)\n else:\n raise TypeError(\"Incompatible shapes for dot: got {} and {}.\".format(\n lhs.shape, rhs.shape))\n\n\nDotDimensionNumbers = Tuple[Tuple[Sequence[int], Sequence[int]],\n Tuple[Sequence[int], Sequence[int]]]\n\ndef dot_general(lhs: Array, rhs: Array, dimension_numbers: DotDimensionNumbers,\n precision: PrecisionLike = None) -> Array:\n \"\"\"More general contraction operator.\n\n Wraps XLA's `DotGeneral\n <https://www.tensorflow.org/xla/operation_semantics#dotgeneral>`_\n operator.\n\n Args:\n lhs: an array\n rhs: an array\n dimension_numbers: a tuple of tuples of the form\n `((lhs_contracting_dims, rhs_contracting_dims),\n (lhs_batch_dims, rhs_batch_dims))`\n precision: Optional. Either ``None``, which means the default precision for\n the backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.\n\n Returns:\n An array containing the result.\n \"\"\"\n contract_dims_seq, batch_dims_seq = dimension_numbers\n contract_dims = tuple(map(lambda x: tuple(x), contract_dims_seq))\n batch_dims = tuple(map(lambda x: tuple(x), batch_dims_seq))\n return dot_general_p.bind(lhs, rhs,\n dimension_numbers=(contract_dims, batch_dims),\n precision=_canonicalize_precision(precision))\n\ndef broadcast(operand: Array, sizes: Sequence[int]) -> Array:\n \"\"\"Broadcasts an array, adding new major dimensions.\n\n Wraps XLA's `Broadcast\n <https://www.tensorflow.org/xla/operation_semantics#broadcast>`_\n operator.\n\n Args:\n operand: an array\n sizes: a sequence of integers, giving the sizes of new major dimensions\n to add.\n\n Returns:\n An array containing the result.\n \"\"\"\n dims = tuple(range(len(sizes), len(sizes) + np.ndim(operand)))\n return broadcast_in_dim(operand, tuple(sizes) + np.shape(operand), dims)\n\ndef broadcast_in_dim(operand: Array, shape: Shape,\n broadcast_dimensions: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `BroadcastInDim\n <https://www.tensorflow.org/xla/operation_semantics#broadcastindim>`_\n operator.\n \"\"\"\n shape = _broadcast_in_dim_shape_rule(\n operand, shape=shape, broadcast_dimensions=broadcast_dimensions)\n if (np.ndim(operand) == len(shape) and not len(broadcast_dimensions)\n and isinstance(operand, (xla.DeviceArray, core.Tracer))):\n return operand\n return broadcast_in_dim_p.bind(\n operand, shape=tuple(shape),\n broadcast_dimensions=tuple(broadcast_dimensions))\n\ndef broadcast_to_rank(x: Array, rank: int) -> Array:\n \"\"\"Adds leading dimensions of ``1`` to give ``x`` rank ``rank``.\"\"\"\n return broadcast(x, (1,) * (rank - x.ndim))\n\ndef reshape(operand: Array, new_sizes: Shape,\n dimensions: Optional[Sequence[int]] = None) -> Array:\n \"\"\"Wraps XLA's `Reshape\n <https://www.tensorflow.org/xla/operation_semantics#reshape>`_\n operator.\n\n For inserting/removing dimensions of size 1, prefer using ``lax.squeeze`` /\n ``lax.expand_dims``. These preserve information about axis identity that may\n be useful for advanced transformation rules.\n \"\"\"\n new_sizes = canonicalize_shape(new_sizes) # TODO\n new_sizes = tuple(new_sizes)\n same_shape = np.shape(operand) == new_sizes\n same_dims = dimensions is None or tuple(dimensions) == tuple(range(np.ndim(operand)))\n if np.shape(operand) and same_shape and same_dims:\n return operand\n else:\n return reshape_p.bind(\n operand, new_sizes=new_sizes,\n dimensions=None if dimensions is None or same_dims else tuple(dimensions))\n\ndef pad(operand: Array, padding_value: Array,\n padding_config: Sequence[Tuple[int, int, int]]) -> Array:\n \"\"\"Applies low, high, and/or interior padding to an array.\n\n Wraps XLA's `Pad\n <https://www.tensorflow.org/xla/operation_semantics#pad>`_\n operator.\n\n Args:\n operand: an array to be padded.\n padding_value: the value to be inserted as padding. Must have the same dtype\n as ``operand``.\n padding_config: a sequence of ``(low, high, interior)`` tuples of integers,\n giving the amount of low, high, and interior (dilation) padding to insert\n in each dimension.\n\n Returns:\n The ``operand`` array with padding value ``padding_value`` inserted in each\n dimension according to the ``padding_config``.\n \"\"\"\n return pad_p.bind(operand, padding_value, padding_config=tuple(padding_config))\n\ndef rev(operand: Array, dimensions: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `Rev\n <https://www.tensorflow.org/xla/operation_semantics#rev_reverse>`_\n operator.\n \"\"\"\n return rev_p.bind(operand, dimensions=tuple(dimensions))\n\ndef select(pred: Array, on_true: Array, on_false: Array) -> Array:\n \"\"\"Wraps XLA's `Select\n <https://www.tensorflow.org/xla/operation_semantics#select>`_\n operator.\n \"\"\"\n return select_p.bind(pred, on_true, on_false)\n\ndef slice(operand: Array, start_indices: Sequence[int],\n limit_indices: Sequence[int],\n strides: Optional[Sequence[int]] = None) -> Array:\n \"\"\"Wraps XLA's `Slice\n <https://www.tensorflow.org/xla/operation_semantics#slice>`_\n operator.\n \"\"\"\n return slice_p.bind(operand, start_indices=tuple(start_indices),\n limit_indices=tuple(limit_indices),\n strides=None if strides is None else tuple(strides))\n\ndef dynamic_slice(operand: Array, start_indices: Sequence[Array],\n slice_sizes: Shape) -> Array:\n \"\"\"Wraps XLA's `DynamicSlice\n <https://www.tensorflow.org/xla/operation_semantics#dynamicslice>`_\n operator.\n\n Args:\n operand: an array to slice.\n start_indices: a list of scalar indices, one per dimension. These values\n may be dynamic.\n slice_sizes: the size of the slice. Must be a sequence of non-negative\n integers with length equal to `ndim(operand)`. Inside a JIT compiled\n function, only static values are supported (all JAX arrays inside JIT\n must have statically known size).\n\n Returns:\n An array containing the slice.\n \"\"\"\n start_indices = _dynamic_slice_indices(operand, start_indices)\n return dynamic_slice_p.bind(operand, *start_indices,\n slice_sizes=tuple(slice_sizes))\n\ndef dynamic_update_slice(operand: Array, update: Array,\n start_indices: Array) -> Array:\n \"\"\"Wraps XLA's `DynamicUpdateSlice\n <https://www.tensorflow.org/xla/operation_semantics#dynamicupdateslice>`_\n operator.\n\n Args:\n operand: an array to slice.\n update: an array containing the new values to write onto `operand`.\n start_indices: a list of scalar indices, one per dimension.\n\n Returns:\n An array containing the slice.\n \"\"\"\n start_indices = _dynamic_slice_indices(operand, start_indices)\n return dynamic_update_slice_p.bind(operand, update, *start_indices)\n\n\nclass GatherDimensionNumbers(NamedTuple):\n \"\"\"\n Describes the dimension number arguments to an `XLA's Gather operator\n <https://www.tensorflow.org/xla/operation_semantics#gather>`_. See the XLA\n documentation for more details of what the dimension numbers mean.\n\n Args:\n offset_dims: the set of dimensions in the `gather` output that offset into\n an array sliced from `operand`. Must be a tuple of integers in ascending\n order, each representing a dimension number of the output.\n collapsed_slice_dims: the set of dimensions `i` in `operand` that have\n `slice_sizes[i] == 1` and that should not have a corresponding dimension\n in the output of the gather. Must be a tuple of integers in ascending\n order.\n start_index_map: for each dimension in `start_indices`, gives the\n corresponding dimension in `operand` that is to be sliced. Must be a\n tuple of integers with size equal to `start_indices.shape[-1]`.\n\n Unlike XLA's `GatherDimensionNumbers` structure, `index_vector_dim` is\n implicit; there is always an index vector dimension and it must always be the\n last dimension. To gather scalar indices, add a trailing dimension of size 1.\n \"\"\"\n offset_dims: Sequence[int]\n collapsed_slice_dims: Sequence[int]\n start_index_map: Sequence[int]\n\n\ndef gather(operand: Array, start_indices: Array,\n dimension_numbers: GatherDimensionNumbers,\n slice_sizes: Shape) -> Array:\n \"\"\"Gather operator.\n\n Wraps `XLA's Gather operator\n <https://www.tensorflow.org/xla/operation_semantics#gather>`_.\n\n The semantics of gather are complicated, and its API might change in the\n future. For most use cases, you should prefer `Numpy-style indexing\n <https://docs.scipy.org/doc/numpy-1.16.0/reference/arrays.indexing.html>`_\n (e.g., `x[:, (1,4,7), ...]`), rather than using `gather` directly.\n\n Args:\n operand: an array from which slices should be taken\n start_indices: the indices at which slices should be taken\n dimension_numbers: a `lax.GatherDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices` and the output relate.\n slice_sizes: the size of each slice. Must be a sequence of non-negative\n integers with length equal to `ndim(operand)`.\n\n Returns:\n An array containing the gather output.\n \"\"\"\n return gather_p.bind(\n operand, start_indices, dimension_numbers=dimension_numbers,\n slice_sizes=canonicalize_shape(slice_sizes))\n\n\nclass ScatterDimensionNumbers(NamedTuple):\n \"\"\"\n Describes the dimension number arguments to an `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_. See the XLA\n documentation for more details of what the dimension numbers mean.\n\n Args:\n update_window_dims: the set of dimensions in the `updates` that are window\n dimensions. Must be a tuple of integers in ascending\n order, each representing a dimension number.\n inserted_window_dims: the set of size 1 window dimensions that must be inserted\n into the shape of `updates`. Must be a tuple of integers in ascending\n order, each representing a dimension number of the output. These are the\n mirror image of `collapsed_slice_dims` in the case of `gather`.\n scatter_dims_to_operand_dims: for each dimension in `scatter_indices`, gives\n the corresponding dimension in `operand`. Must be a sequence of integers\n with size equal to indices.shape[-1].\n\n Unlike XLA's `ScatterDimensionNumbers` structure, `index_vector_dim` is\n implicit; there is always an index vector dimension and it must always be the\n last dimension. To scatter scalar indices, add a trailing dimension of size 1.\n \"\"\"\n update_window_dims: Sequence[int]\n inserted_window_dims: Sequence[int]\n scatter_dims_to_operand_dims: Sequence[int]\n\ndef scatter_add(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers, *,\n indices_are_sorted: bool = False,\n unique_indices: bool = False) -> Array:\n \"\"\"Scatter-add operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n addition is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n indices_are_sorted: whether `scatter_indices` is known to be sorted. If\n true, may improve performance on some backends.\n unique_indices: whether the indices to be updated in ``operand`` are\n guaranteed to not overlap with each other. If true, may improve performance on\n some backends.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(add, _abstractify(_const(operand, 0)))\n return scatter_add_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n\ndef scatter_mul(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers, *,\n indices_are_sorted: bool = False,\n unique_indices: bool = False) -> Array:\n \"\"\"Scatter-multiply operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n multiplication is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n indices_are_sorted: whether `scatter_indices` is known to be sorted. If\n true, may improve performance on some backends.\n unique_indices: whether the indices to be updated in ``operand`` are\n guaranteed to not overlap with each other. If true, may improve performance on\n some backends.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(mul, _abstractify(_const(operand, 1)))\n return scatter_mul_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n\ndef scatter_min(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers, *,\n indices_are_sorted: bool = False,\n unique_indices: bool = False) -> Array:\n \"\"\"Scatter-min operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n the `min` function is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n indices_are_sorted: whether `scatter_indices` is known to be sorted. If\n true, may improve performance on some backends.\n unique_indices: whether the indices to be updated in ``operand`` are\n guaranteed to not overlap with each other. If true, may improve performance on\n some backends.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(min, _abstractify(_const(operand, 0)))\n return scatter_min_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n\ndef scatter_max(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers, *,\n indices_are_sorted: bool = False,\n unique_indices: bool = False) -> Array:\n \"\"\"Scatter-max operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n the `max` function is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n indices_are_sorted: whether `scatter_indices` is known to be sorted. If\n true, may improve performance on some backends.\n unique_indices: whether the indices to be updated in ``operand`` are\n guaranteed to not overlap with each other. If true, may improve performance on\n some backends.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(max, _abstractify(_const(operand, 0)))\n return scatter_max_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n\n# Define this outside of scatter to ensure cache hits.\n_scatter_reduction_computation = lambda x, y: y\n\ndef scatter(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers, *,\n indices_are_sorted: bool = False,\n unique_indices: bool = False) -> Array:\n \"\"\"Scatter-update operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where updates\n replace values from `operand`.\n\n If multiple updates are performed to the same index of operand, they may be\n applied in any order.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n indices_are_sorted: whether `scatter_indices` is known to be sorted. If\n true, may improve performance on some backends.\n unique_indices: whether the indices to be updated in ``operand`` are\n guaranteed to not overlap with each other. If true, may improve performance on\n some backends.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(_scatter_reduction_computation,\n _abstractify(_const(operand, 0)))\n return scatter_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n\ndef index_take(src: Array, idxs: Array, axes: Sequence[int]) -> Array:\n indices = concatenate([expand_dims(i, (1,)) for i in idxs], 1)\n indices = indices % np.array([src.shape[ax] for ax in axes])\n slice_sizes = list(src.shape)\n for ax in axes:\n slice_sizes[ax] = 1\n offset_dims = tuple(range(1, src.ndim - indices.shape[1] + 1))\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=axes,\n start_index_map=axes)\n return gather(src, indices, dimension_numbers=dnums,\n slice_sizes=tuple(slice_sizes))\n\ndef transpose(operand: Array, permutation: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `Transpose\n <https://www.tensorflow.org/xla/operation_semantics#transpose>`_\n operator.\n \"\"\"\n permutation = tuple(permutation)\n if permutation == tuple(range(len(permutation))):\n return operand\n else:\n return transpose_p.bind(operand, permutation=permutation)\n\ndef argmin(operand: Array, axis: int,\n index_dtype: DType) -> Tuple[Array, Array]:\n \"\"\"Computes the index of the minimum element along ``axis``.\"\"\"\n return argmin_p.bind(operand, axes=(axis,),\n index_dtype=dtypes.canonicalize_dtype(index_dtype))\n\ndef argmax(operand: Array, axis: int,\n index_dtype: DType) -> Tuple[Array, Array]:\n \"\"\"Computes the index of the maximum element along ``axis``.\"\"\"\n return argmax_p.bind(operand, axes=(axis,),\n index_dtype=dtypes.canonicalize_dtype(index_dtype))\n\ndef reduce(operands: Array, init_values: Array, computation: Callable,\n dimensions: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `Reduce\n <https://www.tensorflow.org/xla/operation_semantics#reduce>`_\n operator.\n \"\"\"\n flat_operands, operand_tree = tree_util.tree_flatten(operands)\n flat_init_values, init_value_tree = tree_util.tree_flatten(init_values)\n if operand_tree != init_value_tree:\n raise ValueError('Operands must have the same tree structure as init_values:'\n f' {operand_tree} vs. {init_value_tree}')\n if len(flat_operands) != len(flat_init_values):\n raise ValueError('Must have same total number of operands as init_values: '\n f' {len(flat_operands)} vs. {len(flat_init_values)}')\n monoid_reducer = _get_monoid_reducer(computation, flat_init_values)\n if monoid_reducer:\n return monoid_reducer(*flat_operands, dimensions)\n else:\n flat_init_avals = safe_map(_abstractify, flat_init_values)\n jaxpr, consts, out_tree = _variadic_reduction_jaxpr(\n computation, tuple(flat_init_avals), init_value_tree)\n out = reduce_p.bind(*(flat_operands + flat_init_values), computation=computation,\n jaxpr=jaxpr, consts=consts, dimensions=tuple(dimensions))\n return tree_util.tree_unflatten(out_tree, out)\n\n@cache()\ndef _reduction_jaxpr(computation, aval):\n pval = pe.PartialVal.unknown(aval)\n comp = lu.wrap_init(lambda x, y: (computation(x, y),))\n jaxpr, _, consts = pe.trace_to_jaxpr(comp, (pval, pval), instantiate=False)\n return jaxpr, consts\n\n@cache()\ndef _variadic_reduction_jaxpr(computation, flat_avals, aval_tree):\n avals = tree_util.tree_unflatten(aval_tree, flat_avals)\n flat_in_avals, in_tree = tree_util.tree_flatten((avals, avals))\n pvals = safe_map(pe.PartialVal.unknown, flat_in_avals)\n comp = lu.wrap_init(computation)\n flat_comp, out_tree = api_util.flatten_fun_nokwargs(comp, in_tree)\n jaxpr, _, consts = pe.trace_to_jaxpr(flat_comp, tuple(pvals),\n instantiate=False)\n return jaxpr, consts, out_tree()\n\ndef _get_monoid_reducer(monoid_op: Callable, xs: Array) -> Optional[Callable]:\n if len(xs) != 1:\n return None\n x, = xs\n aval = core.get_aval(x)\n dtype = _dtype(x)\n if (type(aval) is ConcreteArray) and aval.shape == ():\n if monoid_op is add:\n return np.equal(aval.val, 0) and partial(\n _reduce_sum)\n if monoid_op is mul:\n return np.equal(aval.val, 1) and _reduce_prod\n elif monoid_op is bitwise_or and dtype == np.bool_:\n return np.equal(aval.val, _get_max_identity(dtype)) and _reduce_or\n elif monoid_op is bitwise_and and dtype == np.bool_:\n return np.equal(aval.val, _get_min_identity(dtype)) and _reduce_and\n elif monoid_op is max:\n return np.equal(aval.val, _get_max_identity(dtype)) and _reduce_max\n elif monoid_op is min:\n return np.equal(aval.val, _get_min_identity(dtype)) and _reduce_min\n return None\n\ndef _get_max_identity(dtype: DType) -> Array:\n if dtypes.issubdtype(dtype, np.inexact):\n return np.array(-np.inf, dtype)\n elif dtypes.issubdtype(dtype, np.integer):\n return np.array(dtypes.iinfo(dtype).min, dtype)\n elif dtypes.issubdtype(dtype, np.bool_):\n return np.array(False, np.bool_)\n\ndef _get_min_identity(dtype: DType) -> Array:\n if dtypes.issubdtype(dtype, np.inexact):\n return np.array(np.inf, dtype)\n elif dtypes.issubdtype(dtype, np.integer):\n return np.array(dtypes.iinfo(dtype).max, dtype)\n elif dtypes.issubdtype(dtype, np.bool_):\n return np.array(True, np.bool_)\n\ndef _reduce_sum(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_sum_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_prod(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_prod_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_max(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_max_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_min(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_min_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_or(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_or_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_and(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_and_p.bind(operand, axes=tuple(axes))\n\ndef reduce_window(operand: Array, init_value: Array, computation: Callable,\n window_dimensions: Shape, window_strides: Sequence[int],\n padding: Union[str, Sequence[Tuple[int, int]]],\n base_dilation: Optional[Sequence[int]] = None,\n window_dilation: Optional[Sequence[int]] = None) -> Array:\n \"\"\"Wraps XLA's `ReduceWindowWithGeneralPadding\n <https://www.tensorflow.org/xla/operation_semantics#reducewindow>`_\n operator.\n \"\"\"\n if isinstance(padding, str):\n dilated_window_dims = (window_dimensions if window_dilation is None else\n _dilate_shape(window_dimensions, window_dilation))\n padding = tuple(padtype_to_pads(operand.shape, dilated_window_dims,\n window_strides, padding))\n else:\n padding = tuple(padding)\n if base_dilation is None:\n base_dilation = (1,) * len(window_dimensions)\n if window_dilation is None:\n window_dilation = (1,) * len(window_dimensions)\n monoid_reducer = _get_monoid_window_reducer(computation, init_value)\n if monoid_reducer:\n return monoid_reducer(operand, window_dimensions, window_strides, padding,\n base_dilation, window_dilation)\n else:\n jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))\n return reduce_window_p.bind(\n operand, init_value, jaxpr=jaxpr, consts=consts,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding,\n base_dilation=tuple(base_dilation),\n window_dilation=tuple(window_dilation))\n\ndef _get_monoid_window_reducer(monoid_op: Callable, x: Array) -> Optional[Callable]:\n aval = core.get_aval(x)\n if (type(aval) is ConcreteArray) and aval.shape == ():\n if monoid_op is add:\n return aval.val == 0 and _reduce_window_sum\n elif monoid_op is max:\n return aval.val == _get_max_identity(aval.dtype) and _reduce_window_max\n elif monoid_op is min:\n return aval.val == _get_min_identity(aval.dtype) and _reduce_window_min\n return None\n\ndef _reduce_window_sum(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: Sequence[Tuple[int, int]],\n base_dilation: Optional[Sequence[int]] = None,\n window_dilation: Optional[Sequence[int]] = None) -> Array:\n if base_dilation is None:\n base_dilation = (1,) * len(window_dimensions)\n if window_dilation is None:\n window_dilation = (1,) * len(window_dimensions)\n return reduce_window_sum_p.bind(\n operand, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=tuple(padding),\n base_dilation=tuple(base_dilation),\n window_dilation=tuple(window_dilation))\n\ndef _reduce_window_prod(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: Sequence[Tuple[int, int]],\n base_dilation: Optional[Sequence[int]] = None,\n window_dilation: Optional[Sequence[int]] = None) -> Array:\n init_value = _const(operand, 1)\n jaxpr, consts = _reduction_jaxpr(mul, _abstractify(init_value))\n if base_dilation is None:\n base_dilation = (1,) * len(window_dimensions)\n if window_dilation is None:\n window_dilation = (1,) * len(window_dimensions)\n return reduce_window_p.bind(\n operand, init_value, jaxpr=jaxpr, consts=consts,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=tuple(padding),\n base_dilation=tuple(base_dilation),\n window_dilation=tuple(window_dilation))\n\ndef _reduce_window_max(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: Sequence[Tuple[int, int]],\n base_dilation: Optional[Sequence[int]] = None,\n window_dilation: Optional[Sequence[int]] = None) -> Array:\n if base_dilation is None:\n base_dilation = (1,) * len(window_dimensions)\n if window_dilation is None:\n window_dilation = (1,) * len(window_dimensions)\n return reduce_window_max_p.bind(\n operand, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=tuple(padding),\n base_dilation=tuple(base_dilation),\n window_dilation=tuple(window_dilation))\n\ndef _reduce_window_min(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: Sequence[Tuple[int, int]],\n base_dilation: Optional[Sequence[int]] = None,\n window_dilation: Optional[Sequence[int]] = None) -> Array:\n if base_dilation is None:\n base_dilation = (1,) * len(window_dimensions)\n if window_dilation is None:\n window_dilation = (1,) * len(window_dimensions)\n return reduce_window_min_p.bind(\n operand, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=tuple(padding),\n base_dilation=tuple(base_dilation),\n window_dilation=tuple(window_dilation))\n\ndef _select_and_scatter(operand: Array, select: Callable,\n window_dimensions: Shape, window_strides: Sequence[int],\n padding: Sequence[Tuple[int, int]], source: Array,\n init_value: Array, scatter: Callable,\n base_dilation: Sequence[int],\n window_dilation: Sequence[int]) -> Array:\n select_jaxpr, select_consts = _reduction_jaxpr(select, _abstractify(init_value))\n scatter_jaxpr, scatter_consts = _reduction_jaxpr(scatter, _abstractify(init_value))\n return select_and_scatter_p.bind(\n operand, source, init_value, select_jaxpr=select_jaxpr,\n select_consts=select_consts, scatter_jaxpr=scatter_jaxpr,\n scatter_consts=scatter_consts, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=tuple(padding),\n base_dilation=tuple(base_dilation),\n window_dilation=tuple(window_dilation))\n\ndef _select_and_scatter_add(source: Array, operand: Array,\n select_prim: core.Primitive,\n window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: Sequence[Tuple[int, int]]) -> Array:\n return select_and_scatter_add_p.bind(\n source, operand, select_prim=select_prim,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=tuple(padding))\n\ndef _select_and_gather_add(tangents: Array, operand: Array,\n select_prim: core.Primitive,\n window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: Sequence[Tuple[int, int]],\n base_dilation: Sequence[int],\n window_dilation: Sequence[int]) -> Array:\n \"\"\"Extracts the tangent corresponding to the minimum or maximum element in each\n window of the `operand` array.\n\n Wraps XLA's `ReduceWindow\n <https://www.tensorflow.org/xla/operation_semantics#reducewindow>`_\n operator, which applies a reduction function to all elements in each window of the\n input multi-dimensional array. In this case, the input multi-dimensional array is\n built by packing each element in the `operand` array with its corresponding\n element in the `tangents` array.\n\n Args:\n tangents: an array\n operand: an array with the same shape as `tangents`\n select_prim: a reduction function (restricted to `ge_p` and `le_p`)\n window_dimensions: an array of integers for window dimension values\n window_strides: an array of integers for window stride values\n base_dilation: an array of integers for base dilation values\n window_dilation: an array of integers for window dilation values\n\n Returns:\n An array containing the elements in `tangents` corresponding to the output of the\n reduction of `operand` fin each window.\n \"\"\"\n return select_and_gather_add_p.bind(\n tangents, operand, select_prim=select_prim,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=tuple(padding),\n base_dilation=tuple(base_dilation),\n window_dilation=tuple(window_dilation))\n\ndef sort(operand: Union[Array, Sequence[Array]], dimension: int = -1,\n is_stable: bool = True, num_keys: int = 1) -> Union[Array, Tuple[Array, ...]]:\n \"\"\"Wraps XLA's `Sort\n <https://www.tensorflow.org/xla/operation_semantics#sort>`_\n operator.\n\n Args:\n operand : Array or sequence of arrays\n dimension : integer dimension along which to sort. Default: -1.\n is_stable : boolean specifying whether to use a stable sort. Default: True.\n num_keys : number of operands to treat as sort keys. Default: 1.\n For num_keys > 1, the sort order will be determined lexicographically using\n the first `num_keys` arrays, with the first key being primary.\n The remaining operands will be returned with the same permutation.\n\n Returns:\n operand : sorted version of the input or inputs.\n \"\"\"\n if isinstance(operand, Sequence):\n if len(operand) == 0:\n raise TypeError(\"Sort requires at least one operand\")\n if not (1 <= num_keys <= len(operand)):\n raise ValueError(f\"num_keys={num_keys} must be between 1 and len(operand)={len(operand)}\")\n dimension = canonicalize_axis(dimension, len(operand[0].shape))\n return tuple(sort_p.bind(*operand, dimension=dimension,\n is_stable=is_stable,\n num_keys=num_keys))\n else:\n if num_keys != 1:\n raise ValueError(f\"num_keys={num_keys} must equal 1 for a single operand.\")\n dimension = canonicalize_axis(dimension, len(operand.shape))\n return sort_p.bind(operand, dimension=dimension, is_stable=is_stable, num_keys=1)[0]\n\ndef sort_key_val(keys: Array, values: Array, dimension: int = -1,\n is_stable: bool = True) -> Tuple[Array, Array]:\n \"\"\"Sorts ``keys`` along ``dimension`` and applies same permutation to ``values``.\"\"\"\n dimension = canonicalize_axis(dimension, len(keys.shape))\n k, v = sort_p.bind(keys, values, dimension=dimension, is_stable=is_stable, num_keys=1)\n return k, v\n\ndef top_k(operand: Array, k: int) -> Tuple[Array, Array]:\n \"\"\"Returns top ``k`` values and their indices along the last axis of ``operand``.\"\"\"\n k = int(k)\n if k < 0:\n raise ValueError(\"k argument to top_k must be nonnegative, got {}\".format(k))\n return top_k_p.bind(operand, k=k)\n\ndef tie_in(x: Array, y: Array) -> Array:\n \"\"\"Deprecated. Ignores ``x`` and returns ``y``.\"\"\"\n return y\n\ndef full(shape: Shape, fill_value: Array, dtype: Optional[DType] = None) -> Array:\n \"\"\"Returns an array of `shape` filled with `fill_value`.\n\n Arguments:\n shape: sequence of integers, describing the shape of the output array.\n fill_value: the value to fill the new array with.\n dtype: the type of the output array, or `None`. If not `None`, `fill_value`\n will be cast to `dtype`.\n \"\"\"\n shape = canonicalize_shape(shape)\n if np.shape(fill_value):\n msg = \"full must be called with scalar fill_value, got fill_value.shape {}.\"\n raise TypeError(msg.format(np.shape(fill_value)))\n dtype = dtypes.canonicalize_dtype(dtype or _dtype(fill_value))\n fill_value = convert_element_type(fill_value, dtype)\n return broadcast(fill_value, shape)\n\ndef _device_put_raw(x):\n if isinstance(x, xla.DeviceArray):\n return x\n else:\n aval = raise_to_shaped(core.get_aval(x))\n return xla.array_result_handler(None, aval)(*xla.device_put(x))\n\ndef iota(dtype: DType, size: int) -> Array:\n \"\"\"Wraps XLA's `Iota\n <https://www.tensorflow.org/xla/operation_semantics#iota>`_\n operator.\n \"\"\"\n if config.omnistaging_enabled:\n dtype = dtypes.canonicalize_dtype(dtype)\n size = core.concrete_or_error(int, size, \"size argument of lax.iota\")\n return iota_p.bind(dtype=dtype, shape=(size,), dimension=0)\n else:\n size = size if type(size) is masking.Poly else int(size)\n shape = canonicalize_shape((size,))\n dtype = dtypes.canonicalize_dtype(dtype)\n lazy_expr = lazy.iota(dtype, shape[0])\n aval = ShapedArray(shape, dtype)\n return xla.make_device_array(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\n \"\"\"Convenience wrapper around ``iota``.\"\"\"\n dtype = dtypes.canonicalize_dtype(dtype)\n shape = canonicalize_shape(shape)\n dimension = core.concrete_or_error(\n int, dimension, \"dimension argument of lax.broadcasted_iota\")\n return iota_p.bind(dtype=dtype, shape=shape, dimension=dimension)\n\ndef _eye(dtype: DType, shape: Shape, offset: int) -> Array:\n \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\"\"\"\n N, M = tuple(map(int, shape))\n offset = int(offset)\n dtype = dtypes.canonicalize_dtype(dtype)\n if config.omnistaging_enabled:\n bool_eye = eq(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n broadcasted_iota(np.int32, (N, M), 1))\n return convert_element_type_p.bind(bool_eye, new_dtype=dtype,\n old_dtype=np.bool_)\n else:\n lazy_expr = lazy.eye(dtype, (N, M), offset)\n aval = ShapedArray((N, M), dtype)\n return xla.make_device_array(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\n \"\"\"This utility function exists for creating Kronecker delta arrays.\"\"\"\n shape = tuple(map(int, shape))\n axes = tuple(map(int, axes))\n dtype = dtypes.canonicalize_dtype(dtype)\n base_shape = tuple(np.take(shape, axes))\n if config.omnistaging_enabled:\n iotas = [broadcasted_iota(np.uint32, base_shape, i)\n for i in range(len(base_shape))]\n eyes = [eq(i1, i2) for i1, i2 in zip(iotas[:-1], iotas[1:])]\n result = convert_element_type_p.bind(_reduce(operator.and_, eyes),\n new_dtype=dtype, old_dtype=np.bool_)\n return broadcast_in_dim(result, shape, axes)\n else:\n lazy_expr = lazy.broadcast(lazy.delta(dtype, base_shape), shape, axes)\n aval = ShapedArray(shape, dtype)\n return xla.make_device_array(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef _tri(dtype: DType, shape: Shape, offset: int) -> Array:\n \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\"\"\"\n N, M = tuple(map(int, shape))\n offset = int(offset)\n dtype = dtypes.canonicalize_dtype(dtype)\n if config.omnistaging_enabled:\n bool_tri = ge(add(broadcasted_iota(np.int32, (N, M), 0), np.int32(offset)),\n broadcasted_iota(np.int32, (N, M), 1))\n return convert_element_type_p.bind(bool_tri, old_dtype=np.int32,\n new_dtype=dtype)\n else:\n lazy_expr = lazy.tri(dtype, (N, M), offset)\n aval = ShapedArray((N, M), dtype)\n return xla.make_device_array(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef stop_gradient(x):\n \"\"\"Stops gradient computation.\n\n Operationally ``stop_gradient`` is the identity function, that is, it returns\n argument `x` unchanged. However, ``stop_gradient`` prevents the flow of\n gradients during forward or reverse-mode automatic differentiation. If there\n are multiple nested gradient computations, ``stop_gradient`` stops gradients\n for all of them.\n\n For example:\n\n >>> jax.grad(lambda x: x**2)(3.)\n array(6., dtype=float32)\n >>> jax.grad(lambda x: jax.lax.stop_gradient(x)**2)(3.)\n array(0., dtype=float32)\n >>> jax.grad(jax.grad(lambda x: x**2))(3.)\n array(2., dtype=float32)\n >>> jax.grad(jax.grad(lambda x: jax.lax.stop_gradient(x)**2))(3.)\n array(0., dtype=float32)\n \"\"\"\n def stop(x):\n if (dtypes.issubdtype(_dtype(x), np.floating) or\n dtypes.issubdtype(_dtype(x), np.complexfloating)):\n return ad_util.stop_gradient_p.bind(x)\n else:\n return x # only bind primitive on inexact dtypes, to avoid some staging\n return tree_map(stop, x)\n\n\n### convenience wrappers around traceables\n\n\ndef conv(lhs: Array, rhs: Array, window_strides: Sequence[int],\n padding: str, precision: PrecisionLike = None) -> Array:\n \"\"\"Convenience wrapper around `conv_general_dilated`.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n window_strides: a sequence of `n` integers, representing the inter-window\n strides.\n padding: either the string `'SAME'`, the string `'VALID'`.\n precision: Optional. Either ``None``, which means the default precision for\n the backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.\n\n Returns:\n An array containing the convolution result.\n \"\"\"\n return conv_general_dilated(lhs, rhs, window_strides, padding,\n precision=precision)\n\ndef conv_with_general_padding(lhs: Array, rhs: Array,\n window_strides: Sequence[int],\n padding: Union[str, Sequence[Tuple[int, int]]],\n lhs_dilation: Optional[Sequence[int]],\n rhs_dilation: Optional[Sequence[int]],\n precision: PrecisionLike = None) -> Array:\n \"\"\"Convenience wrapper around `conv_general_dilated`.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n window_strides: a sequence of `n` integers, representing the inter-window\n strides.\n padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of\n `n` `(low, high)` integer pairs that give the padding to apply before and\n after each spatial dimension.\n lhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `lhs`. LHS dilation\n is also known as transposed convolution.\n rhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `rhs`. RHS dilation\n is also known as atrous convolution.\n precision: Optional. Either ``None``, which means the default precision for\n the backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.\n\n Returns:\n An array containing the convolution result.\n \"\"\"\n return conv_general_dilated(\n lhs, rhs, window_strides, padding, lhs_dilation=lhs_dilation,\n rhs_dilation=rhs_dilation, precision=precision)\n\n\ndef _conv_transpose_padding(k, s, padding):\n \"\"\"Calculate before and after padding for a dim of transposed convolution.\n\n Args:\n k: int: kernel dimension.\n s: int: dimension stride value.\n padding: 'same' or 'valid' padding mode for original forward conv.\n\n Returns:\n 2-tuple: ints: before and after padding for transposed convolution.\n \"\"\"\n if padding == 'SAME':\n pad_len = k + s - 2\n if s > k - 1:\n pad_a = k - 1\n else:\n pad_a = int(np.ceil(pad_len / 2))\n elif padding == 'VALID':\n pad_len = k + s - 2 + _max(k - s, 0)\n pad_a = k - 1\n else:\n raise ValueError('Padding mode must be `SAME` or `VALID`.')\n pad_b = pad_len - pad_a\n return pad_a, pad_b\n\n\ndef _flip_axes(x, axes):\n \"\"\"Flip ndarray 'x' along each axis specified in axes tuple.\"\"\"\n for axis in axes:\n x = np.flip(x, axis)\n return x\n\n\ndef conv_transpose(lhs: Array, rhs: Array, strides: Sequence[int],\n padding: Union[str, Sequence[Tuple[int, int]]],\n rhs_dilation: Optional[Sequence[int]] = None,\n dimension_numbers: ConvGeneralDilatedDimensionNumbers = None,\n transpose_kernel: bool = False,\n precision: PrecisionLike = None) -> Array:\n \"\"\"Convenience wrapper for calculating the N-d convolution \"transpose\".\n\n This function directly calculates a fractionally strided conv rather than\n indirectly calculating the gradient (transpose) of a forward convolution.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n strides: sequence of `n` integers, sets fractional stride.\n padding: 'SAME', 'VALID' will set as transpose of corresponding forward\n conv, or a sequence of `n` integer 2-tuples describing before-and-after\n padding for each `n` spatial dimension.\n rhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `rhs`. RHS dilation\n is also known as atrous convolution.\n dimension_numbers: tuple of dimension descriptors as in\n lax.conv_general_dilated. Defaults to tensorflow convention.\n transpose_kernel: if True flips spatial axes and swaps the input/output\n channel axes of the kernel. This makes the output of this function identical\n to the gradient-derived functions like keras.layers.Conv2DTranspose\n applied to the same kernel. For typical use in neural nets this is completely\n pointless and just makes input/output channel specification confusing.\n precision: Optional. Either ``None``, which means the default precision for\n the backend, a ``lax.Precision`` enum value (``Precision.DEFAULT``,\n ``Precision.HIGH`` or ``Precision.HIGHEST``) or a tuple of two\n ``lax.Precision`` enums indicating precision of ``lhs``` and ``rhs``.\n\n Returns:\n Transposed N-d convolution, with output padding following the conventions of\n keras.layers.Conv2DTranspose.\n \"\"\"\n assert len(lhs.shape) == len(rhs.shape) and len(lhs.shape) >= 2\n ndims = len(lhs.shape)\n one = (1,) * (ndims - 2)\n # Set dimensional layout defaults if not specified.\n if dimension_numbers is None:\n if ndims == 2:\n dimension_numbers = ('NC', 'IO', 'NC')\n elif ndims == 3:\n dimension_numbers = ('NHC', 'HIO', 'NHC')\n elif ndims == 4:\n dimension_numbers = ('NHWC', 'HWIO', 'NHWC')\n elif ndims == 5:\n dimension_numbers = ('NHWDC', 'HWDIO', 'NHWDC')\n else:\n raise ValueError('No 4+ dimensional dimension_number defaults.')\n dn = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)\n k_shape = np.take(rhs.shape, dn.rhs_spec)\n k_sdims = k_shape[2:]\n # Calculate correct output shape given padding and strides.\n pads: Union[str, Sequence[Tuple[int, int]]]\n if padding in {'SAME', 'VALID'}:\n if rhs_dilation is None:\n rhs_dilation = (1,) * (rhs.ndim - 2)\n effective_k_size = map(lambda k, r: (k-1) * r + 1, k_sdims, rhs_dilation)\n pads = [_conv_transpose_padding(k, s, padding)\n for k,s in zip(effective_k_size, strides)]\n else:\n pads = padding\n if transpose_kernel:\n # flip spatial dims and swap input / output channel axes\n rhs = _flip_axes(rhs, np.array(dn.rhs_spec)[2:])\n rhs = np.swapaxes(rhs, dn.rhs_spec[0], dn.rhs_spec[1])\n return conv_general_dilated(lhs, rhs, one, pads, strides, rhs_dilation, dn,\n precision=precision)\n\n\ndef full_like(x: Array, fill_value: Array, dtype: Optional[DType] = None,\n shape: Optional[Shape] = None) -> Array:\n \"\"\"Create a full array like np.full based on the example array `x`.\n\n Args:\n x: example array-like, used for shape and dtype information.\n fill_value: a scalar value to fill the entries of the output array.\n dtype: optional, a dtype parameter for the output ndarray.\n shape: optional, a shape parameter for the output ndarray.\n\n Returns:\n An ndarray with the same shape as `x` with its entries set equal to\n `fill_value`, similar to the output of np.full.\n \"\"\"\n fill_shape = np.shape(x) if shape is None else canonicalize_shape(shape)\n if not config.omnistaging_enabled:\n fill_value = tie_in(x, fill_value)\n return full(fill_shape, fill_value, dtype or _dtype(x))\n\n\ndef collapse(operand: Array, start_dimension: int,\n stop_dimension: int) -> Array:\n \"\"\"Collapses dimensions of an array into a single dimension.\n\n For example, if ``operand`` is an array with shape ``[2, 3, 4]``,\n ``collapse(operand, 0, 2).shape == [6, 4]``. The elements of the collapsed\n dimension are laid out major-to-minor, i.e., with the lowest-numbered\n dimension as the slowest varying dimension.\n\n Args:\n operand: an input array.\n start_dimension: the start of the dimensions to collapse (inclusive).\n stop_dimension: the end of the dimensions to collapse (exclusive).\n\n Returns:\n An array where dimensions ``[start_dimension, stop_dimension)`` have been\n collapsed (raveled) into a single dimension.\n \"\"\"\n lo, hi = start_dimension, stop_dimension\n size = prod(operand.shape[lo:hi])\n new_shape = operand.shape[:lo] + (size,) + operand.shape[hi:]\n return reshape(operand, new_shape)\n\n\ndef slice_in_dim(operand: Array, start_index: Optional[int],\n limit_index: Optional[int],\n stride: int = 1, axis: int = 0)-> Array:\n \"\"\"Convenience wrapper around slice applying to only one dimension.\"\"\"\n start_indices = [0] * operand.ndim\n limit_indices = list(operand.shape)\n strides = [1] * operand.ndim\n\n # translate `None`\n len_axis = operand.shape[axis]\n start_index_int = _canonicalize_dimension(start_index) if start_index is not None else 0\n limit_index_int = _canonicalize_dimension(limit_index) if limit_index is not None else len_axis\n\n # translate negative indices\n if start_index_int < 0:\n start_index_int = start_index_int + len_axis\n if limit_index_int < 0:\n limit_index_int = limit_index_int + len_axis\n\n axis = int(axis)\n start_indices[axis] = start_index_int\n limit_indices[axis] = limit_index_int\n strides[axis] = int(stride)\n\n return slice(operand, start_indices, limit_indices, strides)\n\n\ndef index_in_dim(operand: Array, index: int, axis: int = 0,\n keepdims: bool = True) -> Array:\n \"\"\"Convenience wrapper around slice to perform int indexing.\"\"\"\n index, axis = int(index), int(axis)\n axis_size = operand.shape[axis]\n wrapped_index = index + axis_size if index < 0 else index\n if not 0 <= wrapped_index < axis_size:\n msg = 'index {} is out of bounds for axis {} with size {}'\n raise IndexError(msg.format(index, axis, axis_size))\n result = slice_in_dim(operand, wrapped_index, wrapped_index + 1, 1, axis)\n if keepdims:\n return result\n else:\n return squeeze(result, (axis,))\n\n\ndef dynamic_slice_in_dim(operand: Array, start_index: Array,\n slice_size: int, axis: int = 0) -> Array:\n \"\"\"Convenience wrapper around dynamic_slice applying to one dimension.\"\"\"\n start_indices = [_zero(start_index)] * operand.ndim\n slice_sizes = list(operand.shape)\n\n axis = int(axis)\n start_indices[axis] = start_index\n slice_sizes[axis] = int(slice_size)\n return dynamic_slice(operand, start_indices, slice_sizes)\n\n\ndef dynamic_index_in_dim(operand: Array, index: Array, axis: int = 0,\n keepdims: bool = True) -> Array:\n \"\"\"Convenience wrapper around dynamic_slice to perform int indexing.\"\"\"\n result = dynamic_slice_in_dim(operand, index, 1, axis)\n if keepdims:\n return result\n else:\n return squeeze(result, (axis,))\n\n\ndef dynamic_update_slice_in_dim(operand: Array, update: Array,\n start_index: Array, axis: int) -> Array:\n \"\"\"Convenience wrapper around :func:`dynamic_update_slice` to update a slice\n in a single ``axis``.\n \"\"\"\n axis = int(axis)\n start_indices = [_zero(start_index)] * _ndim(operand)\n start_indices[axis] = start_index\n return dynamic_update_slice(operand, update, start_indices)\n\n\ndef dynamic_update_index_in_dim(operand: Array, update: Array, index: Array,\n axis: int) -> Array:\n \"\"\"Convenience wrapper around :func:`dynamic_update_slice` to update a slice\n of size 1 in a single ``axis``.\n \"\"\"\n axis = int(axis)\n if _ndim(update) != _ndim(operand):\n assert _ndim(update) + 1 == _ndim(operand)\n update = expand_dims(update, (axis,))\n return dynamic_update_slice_in_dim(operand, update, index, axis)\n\n\ndef batch_matmul(lhs: Array, rhs: Array,\n precision: PrecisionLike = None) -> Array:\n \"\"\"Batch matrix multiplication.\"\"\"\n if _min(lhs.ndim, rhs.ndim) < 2:\n raise ValueError('Arguments to batch_matmul must be at least 2D, got {}, {}'\n .format(lhs.ndim, rhs.ndim))\n if lhs.ndim != rhs.ndim:\n raise ValueError('Arguments to batch_matmul must have same ndim, got {}, {}'\n .format(lhs.ndim, rhs.ndim))\n lhs_contract = (lhs.ndim - 1,)\n rhs_contract = (rhs.ndim - 2,)\n batch = tuple(range(lhs.ndim - 2))\n return dot_general(lhs, rhs, ((lhs_contract, rhs_contract), (batch, batch)),\n precision=precision)\n\n\n# These functions also exist in the XLA client library, but we treat them\n# as non-primitive to maintain a smaller set of autodiff primitives.\n\ndef square(x: Array) -> Array:\n r\"\"\"Elementwise square: :math:`x^2`.\"\"\"\n return integer_pow(x, 2)\n\ndef reciprocal(x: Array) -> Array:\n r\"\"\"Elementwise reciprocal: :math:`1 \\over x`.\"\"\"\n return integer_pow(x, -1)\n\ndef _upcast_fp16_for_computation(f):\n @functools.wraps(f)\n def f_wrapped(x):\n dtype = _dtype(x)\n if dtype == np.float16 or dtype == dtypes.bfloat16:\n return convert_element_type(\n f(convert_element_type(x, np.float32)), dtype)\n return f(x)\n\n return f_wrapped\n\[email protected]\n@_upcast_fp16_for_computation\ndef tan(x: Array) -> Array:\n r\"\"\"Elementwise tangent: :math:`\\mathrm{tan}(x)`.\"\"\"\n return div(sin(x), cos(x))\n\[email protected]\ndef asin(x: Array) -> Array:\n r\"\"\"Elementwise arc sine: :math:`\\mathrm{asin}(x)`.\"\"\"\n if dtypes.issubdtype(_dtype(x), np.complexfloating):\n return mul(_const(x, -1j), asinh(mul(_const(x, 1j), x)))\n else:\n return mul(_const(x, 2),\n atan2(x, add(_const(x, 1), sqrt(sub(_const(x, 1), square(x))))))\n\[email protected]\ndef acos(x: Array) -> Array:\n r\"\"\"Elementwise arc cosine: :math:`\\mathrm{acos}(x)`.\"\"\"\n if dtypes.issubdtype(_dtype(x), np.complexfloating):\n result = mul(_const(x, 1j), acosh(x))\n # By convention, numpy chooses the branch with positive real part.\n rpart = real(result)\n return select(\n gt(rpart, _const(rpart, 0)),\n result,\n neg(result)\n )\n else:\n return select(\n ne(x, _const(x, -1.0)),\n mul(_const(x, 2),\n atan2(sqrt(sub(_const(x, 1), square(x))), add(_const(x, 1), x))),\n full_like(x, np.pi))\n\ndef atan(x: Array) -> Array:\n r\"\"\"Elementwise arc tangent: :math:`\\mathrm{atan}(x)`.\"\"\"\n if dtypes.issubdtype(_dtype(x), np.complexfloating):\n return mul(_const(x, -1j), atanh(mul(_const(x, 1j), x)))\n else:\n return atan2(x, _const(x, 1))\n\ndef sinh(x: Array) -> Array:\n r\"\"\"Elementwise hyperbolic sine: :math:`\\mathrm{sinh}(x)`.\"\"\"\n return sinh_p.bind(x)\n\ndef cosh(x: Array) -> Array:\n r\"\"\"Elementwise hyperbolic cosine: :math:`\\mathrm{cosh}(x)`.\"\"\"\n return cosh_p.bind(x)\n\ndef asinh(x: Array) -> Array:\n r\"\"\"Elementwise inverse hyperbolic sine: :math:`\\mathrm{asinh}(x)`.\"\"\"\n return asinh_p.bind(x)\n\ndef acosh(x: Array) -> Array:\n r\"\"\"Elementwise inverse hyperbolic cosine: :math:`\\mathrm{acosh}(x)`.\"\"\"\n return acosh_p.bind(x)\n\ndef atanh(x: Array) -> Array:\n r\"\"\"Elementwise inverse hyperbolic tangent: :math:`\\mathrm{atanh}(x)`.\"\"\"\n return atanh_p.bind(x)\n\n\n# Add some methods to ShapedArray that rely on lax primitives\n\nShapedArray.broadcast = core.aval_method(broadcast)\nShapedArray.transpose = core.aval_method(transpose) # clobbered by lax_numpy\nShapedArray.reshape = core.aval_method(reshape) # clobbered by lax_numpy\n\ndef _iter(tracer):\n if tracer.ndim == 0:\n raise TypeError(\"iteration over a 0-d array\") # same as numpy error\n else:\n n = int(tracer.shape[0])\n # return (index_in_dim(tracer, i, keepdims=False) for i in range(n))\n return iter([index_in_dim(tracer, i, keepdims=False) for i in range(n)])\nShapedArray._iter = staticmethod(_iter)\n\n# Add some ad handlers that use (or could use) lax primitives\n\ndef zeros_like_array(x):\n return full_like(x, 0)\n\nfor t in itertools.chain(dtypes.python_scalar_dtypes.keys(), array_types,\n [xla.DeviceArray, pxla.ShardedDeviceArray]):\n ad_util.jaxval_adders[t] = add\nad_util.jaxval_zeros_likers[xla.DeviceArray] = zeros_like_array\nad_util.jaxval_zeros_likers[pxla.ShardedDeviceArray] = zeros_like_array\n\n\n### primitives\n\n\n_input_dtype = lambda *args, **_: dtypes.canonicalize_dtype(args[0].dtype)\n_fixed_dtype = lambda dtype: lambda *args, **kwargs: dtypes.canonicalize_dtype(dtype)\n_complex_basetype = lambda dtype: np.abs(np.zeros((), dtype)).dtype\n\ndef standard_primitive(shape_rule, dtype_rule, name, translation_rule=None,\n multiple_results=False):\n prim = Primitive(name)\n prim.multiple_results = multiple_results\n prim.def_impl(partial(xla.apply_primitive, prim))\n prim.def_abstract_eval(partial(standard_abstract_eval, prim, shape_rule, dtype_rule))\n xla.translations[prim] = translation_rule or partial(standard_translate, name)\n return prim\n\n\ndef standard_abstract_eval(prim, shape_rule, dtype_rule, *args, **kwargs):\n assert all(isinstance(arg, UnshapedArray) for arg in args), args\n least_specialized = _max(\n map(type, args), key=operator.attrgetter('array_abstraction_level'))\n if least_specialized is ConcreteArray:\n out_vals = prim.impl(*[x.val for x in args], **kwargs)\n if not prim.multiple_results:\n out_vals = [out_vals]\n out_avals = safe_map(ConcreteArray, out_vals)\n elif least_specialized is ShapedArray:\n shapes, dtypes = shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs)\n if not prim.multiple_results:\n shapes, dtypes = [shapes], [dtypes]\n out_avals = safe_map(ShapedArray, shapes, dtypes)\n elif least_specialized is UnshapedArray:\n dtypes = dtype_rule(*args, **kwargs)\n if not prim.multiple_results:\n dtypes = [dtypes]\n out_avals = safe_map(UnshapedArray, dtypes)\n else:\n raise TypeError(args, least_specialized)\n if not prim.multiple_results:\n return out_avals[0]\n return out_avals\n\n\ndef standard_translate(name, c, *args, **kwargs):\n xla_opname = ''.join(term.capitalize() for term in name.split('_'))\n return getattr(xops, xla_opname)(*args, **kwargs)\n\n\ndef unop_dtype_rule(result_dtype, accepted_dtypes, name, aval, **kwargs):\n if not any(dtypes.issubdtype(aval.dtype, t) for t in accepted_dtypes):\n msg = '{} does not accept dtype {}. Accepted dtypes are subtypes of {}.'\n typename = str(np.dtype(aval.dtype).name)\n accepted_typenames = (t.__name__ for t in accepted_dtypes)\n raise TypeError(msg.format(name, typename, ', '.join(accepted_typenames)))\n return result_dtype(aval.dtype)\n\n\ndef unop(result_dtype, accepted_dtypes, name, translation_rule=None):\n dtype_rule = partial(unop_dtype_rule, result_dtype, accepted_dtypes, name)\n prim = standard_primitive(_attrgetter('shape'), dtype_rule, name,\n translation_rule=translation_rule)\n batching.defvectorized(prim)\n masking.defvectorized(prim)\n return prim\nstandard_unop = partial(unop, _identity)\n_attrgetter = lambda name: lambda x, **kwargs: getattr(x, name)\n\n\ndef naryop_dtype_rule(result_dtype, accepted_dtypes, name, *avals, **kwargs):\n aval_dtypes = [aval.dtype for aval in avals]\n for i, (aval_dtype, types) in enumerate(zip(aval_dtypes, accepted_dtypes)):\n if not any(dtypes.issubdtype(aval_dtype, t) for t in types):\n if aval_dtype is dtypes.float0:\n raise TypeError(\n f\"Called {name} with a float0 at position {i}. \"\n \"float0s do not support any operations by design, because they \"\n \"are not compatible with non-trivial vector spaces. No implicit dtype \"\n \"conversion is done. You can use np.zeros_like(arr, dtype=np.float) \"\n \"to cast a float0 array to a regular zeros array. \\n\"\n \"If you didn't expect to get a float0 you might have accidentally \"\n \"taken a gradient with respect to an integer argument.\")\n else:\n msg = ('{} does not accept dtype {} at position {}. '\n 'Accepted dtypes at position {} are subtypes of {}.')\n typename = str(np.dtype(aval_dtype).name)\n typenames = ', '.join(t.__name__ for t in types)\n raise TypeError(msg.format(name, typename, i, i, typenames))\n _check_same_dtypes(name, False, *aval_dtypes)\n return result_dtype(*avals)\n\n\ndef _broadcasting_shape_rule(name, *avals):\n shapes = [aval.shape for aval in avals if aval.shape]\n if not shapes:\n return ()\n if len({len(shape) for shape in shapes}) != 1:\n msg = '{} got arrays of different rank: {}.'\n raise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\n result_shape = _try_broadcast_shapes(shapes)\n if result_shape is None:\n msg = '{} got incompatible shapes for broadcasting: {}.'\n raise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\n return result_shape\n\n\ndef naryop(result_dtype, accepted_dtypes, name, translation_rule=None):\n dtype_rule = partial(naryop_dtype_rule, result_dtype, accepted_dtypes, name)\n shape_rule = partial(_broadcasting_shape_rule, name)\n prim = standard_primitive(shape_rule, dtype_rule, name,\n translation_rule=translation_rule)\n batching.defbroadcasting(prim)\n masking.defnaryop(prim)\n return prim\nstandard_naryop = partial(naryop, _input_dtype)\n\n\ndef _broadcast_translate(translate: Callable):\n # Decorator for translation rules which adds explicit broadcasting of\n # positional arguments. This is necessary only for a handful of primitives\n # whose XLA implementations do not support broadcasting.\n def _broadcast_array(array, array_shape, result_shape):\n if array_shape == result_shape:\n return array\n bcast_dims = tuple(range(len(result_shape) - len(array_shape),\n len(result_shape)))\n result = xops.BroadcastInDim(array, result_shape, bcast_dims)\n return result\n\n def _broadcasted_translation_rule(c, *args, **kwargs):\n shapes = [c.get_shape(arg).dimensions() for arg in args]\n result_shape = broadcast_shapes(*shapes)\n args = [_broadcast_array(arg, arg_shape, result_shape)\n for arg, arg_shape in zip(args, shapes)]\n return translate(c, *args, **kwargs)\n return _broadcasted_translation_rule\n\n# NOTE(mattjj): this isn't great for orchestrate fwd mode because it means JVPs\n# get two extra ops in them: a reshape and a broadcast_in_dim (or sometimes just\n# a broadcast). but saving the shape info with the primitives isn't great either\n# because then we can't trace these ops without shape data.\ndef _brcast(x, *others):\n # Used in jvprules to make naryop broadcasting explicit for transposability.\n # Requires shape info during jvp tracing, which isn't strictly necessary.\n # We don't need full numpy broadcasting, but otherwise the logic is the same\n # so we reuse the broadcast_shapes function after filtering out scalars.\n shapes = tuple(filter(None, map(np.shape, (x,) + others)))\n shape = shapes and broadcast_shapes(*shapes)\n if np.shape(x) != shape:\n return _brcast_to(x, shape)\n else:\n return x\n\n\ndef _brcast_to(x, shape):\n x_shape = np.shape(x)\n assert x_shape != shape\n if x_shape:\n assert len(x_shape) == len(shape)\n broadcast_dimensions, = np.where(np.equal(x_shape, shape))\n squeezed_dimensions, = np.where(np.not_equal(x_shape, shape))\n squeezed = squeeze(x, squeezed_dimensions)\n return broadcast_in_dim(squeezed, shape, broadcast_dimensions)\n else:\n return broadcast(x, shape)\n\n\n_float = {np.floating}\n_complex = {np.complexfloating}\n_complex_elem_types = {np.float32, np.float64}\n_int = {np.integer}\n_bool = {np.bool_}\n\n_num = _int | _float | _complex\n_any = _int | _float | _complex | _bool\n_bool_or_int = _int | _bool\n\nneg_p = standard_unop(_num, 'neg')\nad.deflinear(neg_p, lambda t: [neg(t)])\n\ndef _sign_translation_rule(c, x):\n shape = c.get_shape(x)\n dtype = shape.numpy_dtype()\n if dtypes.issubdtype(dtype, np.unsignedinteger):\n zero = xb.constant(c, np.array(0, dtype=dtype))\n dims = c.get_shape(x).dimensions()\n return xops.Select(xops.Eq(x, zero), xops.Broadcast(zero, dims),\n xops.Broadcast(xb.constant(c, np.array(1, dtype=dtype)),\n dims))\n return xops.Sign(x)\n\nsign_p = standard_unop(_num, 'sign', translation_rule=_sign_translation_rule)\nad.defjvp_zero(sign_p)\n\nnextafter_p = standard_naryop(\n [_float, _float], 'nextafter',\n translation_rule=lambda c, x1, x2: xops.NextAfter(x1, x2))\n\nfloor_p = standard_unop(_float, 'floor')\nad.defjvp_zero(floor_p)\n\nceil_p = standard_unop(_float, 'ceil')\nad.defjvp_zero(ceil_p)\n\nround_p = standard_unop(_float, 'round')\nad.defjvp_zero(round_p)\n\nis_finite_p = unop(_fixed_dtype(np.bool_), _float, 'is_finite')\nad.defjvp_zero(is_finite_p)\n\nexp_p = standard_unop(_float | _complex, 'exp')\nad.defjvp2(exp_p, lambda g, ans, x: mul(g, ans))\niad.definverse(exp_p, lambda r, x: log(r))\n# For exp_p it is more efficient to use the reconstructed output for the vjp\n# rule instead of computing it again from the input.\niad.primitive_ivjps[exp_p] = lambda x, y, ct: [[log(y[0])], [ct[0] * y[0]]]\n\nlog_p = standard_unop(_float | _complex, 'log')\nad.defjvp(log_p, lambda g, x: div(g, x))\niad.definverse(log_p, lambda r, x: exp(r))\n\nexpm1_p = standard_unop(_float | _complex, 'expm1')\nad.defjvp2(expm1_p, lambda g, ans, x: mul(g, add(ans, _one(ans))))\n\nlog1p_p = standard_unop(_float | _complex, 'log1p')\nad.defjvp(log1p_p, lambda g, x: div(g, add(x, _one(x))))\n\ntanh_p = standard_unop(_float | _complex, 'tanh')\nad.defjvp2(tanh_p, lambda g, ans, x: mul(g, sub(_one(x), mul(ans, ans))))\n\nsin_p = standard_unop(_float | _complex, 'sin')\nad.defjvp(sin_p, lambda g, x: mul(g, cos(x)))\n\ncos_p = standard_unop(_float | _complex, 'cos')\nad.defjvp(cos_p, lambda g, x: neg(mul(g, sin(x))))\n\natan2_p = standard_naryop([_float, _float], 'atan2')\nad.defjvp(atan2_p,\n lambda g, x, y: _brcast(g, y) * (y / (square(x) + square(y))),\n lambda g, x, y: _brcast(g, x) * -x / (square(x) + square(y)))\n\nsinh_p = standard_unop(_float | _complex, 'sinh')\nad.defjvp(sinh_p, lambda g, x: mul(g, cosh(x)))\n\ncosh_p = standard_unop(_float | _complex, 'cosh')\nad.defjvp(cosh_p, lambda g, x: mul(g, sinh(x)))\n\nasinh_p = standard_unop(_float | _complex, 'asinh')\nad.defjvp(asinh_p, lambda g, x: mul(g, rsqrt(square(x) + _one(x))))\n\nacosh_p = standard_unop(_float | _complex, 'acosh')\nad.defjvp(acosh_p,\n lambda g, x: mul(g, rsqrt((x - _one(x)) * (x + _one(x)))))\n\natanh_p = standard_unop(_float | _complex, 'atanh')\nad.defjvp(atanh_p,\n lambda g, x: mul(g, reciprocal((_one(x) - x) * (_one(x) + x))))\n\nregularized_incomplete_beta_p = standard_naryop(\n [_float, _float, _float], 'regularized_incomplete_beta',\n translation_rule=_broadcast_translate(\n partial(standard_translate, 'regularized_incomplete_beta')))\n\ndef betainc_gradx(g, a, b, x):\n lbeta = lgamma(a) + lgamma(b) - lgamma(a + b)\n partial_x = exp((b - 1) * log1p(-x) +\n (a - 1) * log(x) - lbeta)\n return partial_x * g\n\ndef betainc_grad_not_implemented(g, a, b, x):\n raise ValueError(\"Betainc gradient with respect to a and b not supported.\")\n\nad.defjvp(regularized_incomplete_beta_p,\n betainc_grad_not_implemented,\n betainc_grad_not_implemented,\n betainc_gradx)\n\nlgamma_p = standard_unop(_float, 'lgamma')\nad.defjvp(lgamma_p, lambda g, x: mul(g, digamma(x)))\n\ndigamma_p = standard_unop(_float, 'digamma')\n\nigamma_p = standard_naryop(\n [_float, _float], 'igamma',\n translation_rule=_broadcast_translate(partial(standard_translate, 'igamma')))\nigamma_grad_a_p = standard_naryop([_float, _float], 'igamma_grad_a',\n translation_rule=_broadcast_translate(partial(standard_translate,\n 'igamma_grad_a')))\n\ndef igamma_gradx(g, a, x):\n return _brcast(g, a, x) * exp(-x + (a - _ones(a)) * log(x) - lgamma(a))\n\ndef igamma_grada(g, a, x):\n return _brcast(g, a, x) * igamma_grad_a(a, x)\n\nad.defjvp(igamma_p, igamma_grada, igamma_gradx)\n\nigammac_p = standard_naryop(\n [_float, _float], 'igammac',\n translation_rule=_broadcast_translate(partial(standard_translate, 'igammac')))\n\ndef igammac_gradx(g, a, x):\n return -igamma_gradx(g, a, x)\n\ndef igammac_grada(g, a, x):\n return -igamma_grada(g, a, x)\n\nad.defjvp(igammac_p, igammac_grada, igammac_gradx)\n\nrandom_gamma_grad_p = standard_naryop([_float, _float], 'random_gamma_grad',\n translation_rule=_broadcast_translate(partial(standard_translate,\n 'random_gamma_grad')))\n\nbessel_i0e_p = standard_unop(_float, 'bessel_i0e')\nad.defjvp2(bessel_i0e_p, lambda g, y, x: g * (bessel_i1e(x) - sign(x) * y))\n\nbessel_i1e_p = standard_unop(_float, 'bessel_i1e')\ndef _bessel_i1e_jvp(g, y, x):\n eps = dtypes.finfo(_dtype(x)).eps\n x_is_not_tiny = abs(x) > eps\n safe_x = select(x_is_not_tiny, x, full_like(x, eps))\n dy_dx = bessel_i0e(safe_x) - y * (sign(safe_x) + reciprocal(safe_x))\n dy_dx = select(x_is_not_tiny, dy_dx, full_like(x, 0.5))\n return g * dy_dx\nad.defjvp2(bessel_i1e_p, _bessel_i1e_jvp)\n\nerf_p = standard_unop(_float, 'erf')\nad.defjvp(erf_p, lambda g, x: mul(_const(x, 2. / np.sqrt(np.pi)),\n mul(g, exp(neg(square(x))))))\n\nerfc_p = standard_unop(_float, 'erfc')\nad.defjvp(erfc_p, lambda g, x: mul(_const(x, 2. / np.sqrt(np.pi)),\n mul(neg(g), exp(neg(square(x))))))\n\nerf_inv_p = standard_unop(_float, 'erf_inv')\nad.defjvp2(erf_inv_p, lambda g, ans, x: mul(_const(x, np.sqrt(np.pi) / 2.),\n mul(g, exp(square(ans)))))\n\nreal_p = unop(_complex_basetype, _complex, 'real')\nad.deflinear(real_p, lambda t: [complex(t, np.zeros((), _dtype(t)))])\n\nimag_p = unop(_complex_basetype, _complex, 'imag')\nad.defjvp(imag_p, lambda g, _: real(mul(_const(g, -1j), g)))\n\n_complex_dtype = lambda dtype, *args: (np.zeros((), dtype) + np.zeros((), np.complex64)).dtype\ncomplex_p = naryop(_complex_dtype, [_complex_elem_types, _complex_elem_types],\n 'complex')\nad.deflinear(complex_p, lambda t: [real(t), imag(neg(t))])\n\nconj_p = unop(_complex_dtype, _complex_elem_types | _complex, 'conj')\n\ndef _conj_transpose_rule(t, x, *, input_dtype):\n assert ad.is_undefined_primal(x)\n if dtypes.issubdtype(input_dtype, np.complexfloating):\n return [conj(t)]\n else:\n return [real(t)]\n\nxla.translations[conj_p] = lambda c, x, **kwargs: xops.Conj(x)\nad.primitive_jvps[conj_p] = partial(ad.linear_jvp, conj_p)\nad.primitive_transposes[conj_p] = _conj_transpose_rule\n\nabs_p = unop(_complex_basetype, _num, 'abs')\n\ndef _abs_jvp_rule(g, ans, x):\n if _iscomplex(x):\n return _maybe_real(mul(g, div(_maybe_conj(x),\n _replace_zero(convert_element_type(ans, _dtype(x))))))\n else:\n return select(ge(x, _zero(x)), g, neg(g))\nad.defjvp2(abs_p, _abs_jvp_rule)\n_maybe_conj = lambda x: conj(x) if _iscomplex(x) else x\n_maybe_real = lambda x: real(x) if _iscomplex(x) else x\n\nsqrt_p = standard_unop(_float | _complex, 'sqrt')\nad.defjvp2(sqrt_p, lambda g, ans, x: mul(g, div(_const(x, 0.5), ans)))\n\nrsqrt_p = standard_unop(_float | _complex, 'rsqrt')\nad.defjvp2(rsqrt_p,\n lambda g, ans, x:\n mul(g, mul(_const(x, -0.5), pow(x, _const(x, -1.5)))))\n\npow_p = standard_naryop([_float | _complex, _float | _complex], 'pow')\n\ndef _pow_jvp_lhs(g, ans, x, y):\n jac = mul(y, pow(x, select(eq(y, _zeros(y)), _ones(y), sub(y, _ones(y)))))\n return mul(_brcast(g, y), jac)\n\ndef _pow_jvp_rhs(g, ans, x, y):\n return mul(_brcast(g, x), mul(log(_replace_zero(x)), ans))\n\nad.defjvp2(pow_p, _pow_jvp_lhs, _pow_jvp_rhs)\n\n\ndef _integer_pow_dtype_rule(x, *, y):\n dtype = unop_dtype_rule(_identity, _int | _float | _complex, 'integer_pow', x)\n if y < 0 and dtypes.issubdtype(dtype, np.integer):\n raise TypeError(\"Integers cannot be raised to negative powers, got \"\n f\"integer_pow({x}, {y})\")\n return dtype\n\ndef _integer_pow_translation_rule(c, x, *, y):\n if y == 0:\n shape = c.get_shape(x)\n return xb.constant(c, np.array(1, dtype=shape.numpy_dtype()))\n is_reciprocal = y < 0\n if is_reciprocal:\n y = -y\n acc = None\n while y > 0:\n if y & 1:\n acc = x if acc is None else xops.Mul(acc, x)\n y >>= 1\n if y > 0:\n x = xops.Mul(x, x)\n return xops.Reciprocal(acc) if is_reciprocal else acc\n\ndef _integer_pow_jvp(g, x, *, y):\n return g if y == 0 else mul(g, mul(_const(x, y), integer_pow(x, y - 1)))\n\ninteger_pow_p = standard_primitive(\n _attrgetter('shape'), _integer_pow_dtype_rule, 'integer_pow',\n translation_rule=_integer_pow_translation_rule)\nbatching.defvectorized(integer_pow_p)\nmasking.defvectorized(integer_pow_p)\nad.defjvp(integer_pow_p, _integer_pow_jvp)\n\n_replace_zero = lambda x: select(eq(x, _const(x, 0)), _ones(x), x)\n\nnot_p = standard_unop(_bool_or_int, 'not')\nad.defjvp_zero(not_p)\n\nand_p = standard_naryop([_bool_or_int, _bool_or_int], 'and')\nad.defjvp_zero(and_p)\n\nor_p = standard_naryop([_bool_or_int, _bool_or_int], 'or')\nad.defjvp_zero(or_p)\n\nxor_p = standard_naryop([_bool_or_int, _bool_or_int], 'xor')\nad.defjvp_zero(xor_p)\n\npopulation_count_p = standard_unop(_int, 'population_count')\n\ndef _add_transpose(t, x, y):\n # The following linearity assertion is morally true, but because in some cases we\n # instantiate zeros for convenience, it doesn't always hold.\n # assert ad.is_undefined_primal(x) and ad.is_undefined_primal(y)\n return [t, t]\n\nadd_p = standard_naryop([_num, _num], 'add')\nad.defjvp(add_p, lambda g, x, y: _brcast(g, y), lambda g, x, y: _brcast(g, x))\nad.primitive_transposes[add_p] = _add_transpose\ndef _add_inverse(r, x, y):\n xr = r - y\n yr = r - x\n return xr, yr\niad.definverse(add_p, _add_inverse)\n\ndef _sub_transpose(t, x, y):\n # The following linearity assertion is morally true, but because in some cases\n # we instantiate zeros for convenience, it doesn't always hold.\n # assert ad.is_undefined_primal(x) and ad.is_undefined_primal(y)\n return [t, neg(t) if type(t) is not ad_util.Zero else ad_util.Zero]\n\nsub_p = standard_naryop([_num, _num], 'sub')\nad.defjvp(sub_p,\n lambda g, x, y: _brcast(g, y),\n lambda g, x, y: _brcast(neg(g), x))\nad.primitive_transposes[sub_p] = _sub_transpose\n\nmul_p = standard_naryop([_num, _num], 'mul')\nad.defbilinear_broadcasting(_brcast, mul_p, mul, mul)\ndef _mul_inverse(r, x, y):\n xr = r / y\n yr = r / x\n return xr, yr\niad.definverse(mul_p, _mul_inverse)\n\ndef _div_transpose_rule(cotangent, x, y):\n assert ad.is_undefined_primal(x) and not ad.is_undefined_primal(y)\n res = ad_util.Zero if type(cotangent) is ad_util.Zero else div(cotangent, y)\n return res, None\ndiv_p = standard_naryop([_num, _num], 'div')\nad.defjvp(div_p,\n lambda g, x, y: div(_brcast(g, y), y),\n lambda g, x, y: mul(mul(neg(_brcast(g, x)), x), integer_pow(y, -2)))\nad.primitive_transposes[div_p] = _div_transpose_rule\n\nrem_p = standard_naryop([_num, _num], 'rem')\nad.defjvp(rem_p,\n lambda g, x, y: _brcast(g, y),\n lambda g, x, y: mul(_brcast(neg(g), x), floor(div(x, y))))\n\n\ndef _broadcasting_select(c, which, x, y):\n \"\"\"Wrapper around XLA `Select` that broadcasts its arguments.\"\"\"\n which_shape, x_shape, y_shape = (\n c.get_shape(t).dimensions() for t in (which, x, y))\n out_shape = broadcast_shapes(which_shape, x_shape, y_shape)\n bcast_dims = lambda shape: tuple(range(len(out_shape) - len(shape),\n len(out_shape)))\n which = xops.BroadcastInDim(which, out_shape, bcast_dims(which_shape))\n x = xops.BroadcastInDim(x, out_shape, bcast_dims(x_shape))\n y = xops.BroadcastInDim(y, out_shape, bcast_dims(y_shape))\n return xops.Select(which, x, y)\n\n\ndef _minmax_translation_rule(c, x, y, *, minmax=None, cmp=None):\n dtype = c.get_shape(x).numpy_dtype()\n if dtypes.issubdtype(dtype, np.complexfloating):\n rx = xops.Real(x)\n ry = xops.Real(y)\n return _broadcasting_select(\n c, xops.Select(xops.Eq(rx, ry), cmp(xops.Imag(x), xops.Imag(y)),\n cmp(rx, ry)),\n x, y)\n return minmax(x, y)\n\nmax_p: core.Primitive = standard_naryop(\n [_any, _any], 'max', translation_rule=partial(\n _minmax_translation_rule, minmax=xops.Max, cmp=xops.Gt))\nad.defjvp2(max_p,\n lambda g, ans, x, y: mul(_brcast(g, y), _balanced_eq(x, ans, y)),\n lambda g, ans, x, y: mul(_brcast(g, x), _balanced_eq(y, ans, x)))\n\nmin_p: core.Primitive = standard_naryop(\n [_any, _any], 'min', translation_rule=partial(\n _minmax_translation_rule, minmax=xops.Min, cmp=xops.Lt))\nad.defjvp2(min_p,\n lambda g, ans, x, y: mul(_brcast(g, y), _balanced_eq(x, ans, y)),\n lambda g, ans, x, y: mul(_brcast(g, x), _balanced_eq(y, ans, x)))\n\nshift_left_p = standard_naryop([_int, _int], 'shift_left')\nad.defjvp_zero(shift_left_p)\n\nshift_right_arithmetic_p = standard_naryop([_int, _int], 'shift_right_arithmetic')\nad.defjvp_zero(shift_right_arithmetic_p)\n\nshift_right_logical_p = standard_naryop([_int, _int], 'shift_right_logical')\nad.defjvp_zero(shift_right_logical_p)\n\neq_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'eq')\nad.defjvp_zero(eq_p)\n\nne_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'ne')\nad.defjvp_zero(ne_p)\n\nge_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'ge')\nad.defjvp_zero(ge_p)\n\ngt_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'gt')\nad.defjvp_zero(gt_p)\n\nle_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'le')\nad.defjvp_zero(le_p)\n\nlt_p = naryop(_fixed_dtype(np.bool_), [_any, _any], 'lt')\nad.defjvp_zero(lt_p)\n\n\ndef _convert_element_type_shape_rule(operand, *, new_dtype, old_dtype):\n return operand.shape\n\ndef _convert_element_type_dtype_rule(operand, *, new_dtype, old_dtype):\n return new_dtype\n\ndef _convert_element_type_translation_rule(c, operand, *, new_dtype, old_dtype):\n if (dtypes.issubdtype(old_dtype, np.complexfloating) and\n not dtypes.issubdtype(new_dtype, np.complexfloating)):\n operand = xops.Real(operand)\n new_etype = xla_client.dtype_to_etype(new_dtype)\n return xops.ConvertElementType(operand, new_element_type=new_etype)\n\ndef _convert_element_type_transpose_rule(ct, operand, *, new_dtype, old_dtype):\n if type(ct) is ad_util.Zero:\n return [ad_util.Zero(operand.aval)]\n elif core.primal_dtype_to_tangent_dtype(old_dtype) is dtypes.float0:\n return [ad_util.Zero(ShapedArray(operand.aval.shape, dtype=dtypes.float0))]\n else:\n return [convert_element_type_p.bind(ct, new_dtype=old_dtype,\n old_dtype=new_dtype)]\n\ndef _convert_element_type_jvp_rule(tangent, operand , *, new_dtype, old_dtype):\n if core.primal_dtype_to_tangent_dtype(new_dtype) is dtypes.float0:\n return ad_util.Zero(ShapedArray(tangent.shape, dtype=dtypes.float0))\n else:\n return convert_element_type_p.bind(tangent, new_dtype=new_dtype,\n old_dtype=old_dtype)\n\nconvert_element_type_p = standard_primitive(\n _convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n 'convert_element_type', _convert_element_type_translation_rule)\nad.defjvp(convert_element_type_p, _convert_element_type_jvp_rule)\nad.primitive_transposes[convert_element_type_p] = _convert_element_type_transpose_rule\nbatching.defvectorized(convert_element_type_p)\nmasking.defvectorized(convert_element_type_p)\n\n\ndef _bitcast_convert_type_shape_rule(operand, *, new_dtype):\n return operand.shape\n\ndef _bitcast_convert_type_dtype_rule(operand, *, new_dtype):\n return new_dtype\n\ndef _bitcast_convert_type_translation_rule(c, operand, *, new_dtype):\n new_etype = xla_bridge.dtype_to_etype(new_dtype)\n return xops.BitcastConvertType(operand, new_element_type=new_etype)\n\nbitcast_convert_type_p = standard_primitive(\n _bitcast_convert_type_shape_rule, _bitcast_convert_type_dtype_rule,\n 'bitcast_convert_type', _bitcast_convert_type_translation_rule)\nad.defjvp_zero(bitcast_convert_type_p)\nbatching.defvectorized(bitcast_convert_type_p)\nmasking.defvectorized(bitcast_convert_type_p)\n\n\ndef _conv_general_dilated_shape_rule(\n lhs: ShapedArray, rhs: ShapedArray, *, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers, feature_group_count,\n batch_group_count, **unused_kwargs) -> Tuple[int, ...]:\n assert type(dimension_numbers) is ConvDimensionNumbers\n if len(lhs.shape) != len(rhs.shape):\n msg = (\"conv_general_dilated lhs and rhs must have the same number of \"\n \"dimensions, but got {} and {}.\")\n raise ValueError(msg.format(lhs.shape, rhs.shape))\n if not feature_group_count > 0:\n msg = (\"conv_general_dilated feature_group_count \"\n \"must be a positive integer, got {}.\")\n raise ValueError(msg.format(feature_group_count))\n lhs_feature_count = lhs.shape[dimension_numbers.lhs_spec[1]]\n quot, rem = divmod(lhs_feature_count, feature_group_count)\n if rem:\n msg = (\"conv_general_dilated feature_group_count must divide lhs feature \"\n \"dimension size, but {} does not divide {}.\")\n raise ValueError(msg.format(feature_group_count, lhs_feature_count))\n if quot != rhs.shape[dimension_numbers.rhs_spec[1]]:\n msg = (\"conv_general_dilated lhs feature dimension size divided by \"\n \"feature_group_count must equal the rhs input feature dimension \"\n \"size, but {} // {} != {}.\")\n raise ValueError(msg.format(lhs_feature_count, feature_group_count,\n rhs.shape[dimension_numbers.rhs_spec[1]]))\n if rhs.shape[dimension_numbers.rhs_spec[0]] % feature_group_count:\n msg = (\"conv_general_dilated rhs output feature dimension size must be a \"\n \"multiple of feature_group_count, but {} is not a multiple of {}.\")\n raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\n feature_group_count))\n\n if not batch_group_count > 0:\n msg = (\"conv_general_dilated batch_group_count \"\n \"must be a positive integer, got {}.\")\n raise ValueError(msg.format(batch_group_count))\n lhs_batch_count = lhs.shape[dimension_numbers.lhs_spec[0]]\n if lhs_batch_count % batch_group_count != 0:\n msg = (\"conv_general_dilated batch_group_count must divide lhs batch \"\n \"dimension size, but {} does not divide {}.\")\n raise ValueError(msg.format(batch_group_count, lhs_batch_count))\n\n if rhs.shape[dimension_numbers.rhs_spec[0]] % batch_group_count:\n msg = (\"conv_general_dilated rhs output feature dimension size must be a \"\n \"multiple of batch_group_count, but {} is not a multiple of {}.\")\n raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\n batch_group_count))\n\n if batch_group_count > 1 and feature_group_count > 1:\n msg = (\"At most one of batch_group_count and feature_group_count may be > \"\n \"1, got batch_group_count={} and feature_group_count={}\")\n raise ValueError(msg.format(batch_group_count, feature_group_count))\n\n lhs_perm, rhs_perm, out_perm = dimension_numbers\n lhs_trans = _dilate_shape(np.take(lhs.shape, lhs_perm), lhs_dilation)\n rhs_trans = _dilate_shape(np.take(rhs.shape, rhs_perm), rhs_dilation)\n out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding,\n batch_group_count)\n return tuple(np.take(out_trans, np.argsort(out_perm)))\n\ndef _conv_general_dilated_dtype_rule(\n lhs, rhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, **unused_kwargs):\n return naryop_dtype_rule(_input_dtype, [_float | _complex, _float | _complex],\n 'conv_general_dilated', lhs, rhs)\n\n_conv_spec_transpose = lambda spec: (spec[1], spec[0]) + spec[2:]\n_conv_sdims = lambda spec: spec[2:]\n\n# Understanding the convolution transpose rules:\n# Ignoring the spatial dimensions, let m = batch, j = input feature,\n# k = output feature.\n#\n# Convolution computes the following contraction:\n# Forward: [m, j] [j, k] -> [m, k]\n#\n# The transposes are similar to the rules for transposing a matmul:\n# LHS transpose: [m, k] [k, j] -> [m, j]\n# RHS transpose: [j, m] [m, k] -> [j, k]\n#\n# With feature grouping, we have the following signatures:\n# Forward: [m, gj] [j, gk] -> [m, gk]\n# LHS transpose: [m, gk] [k, gj] -> [m, gj]\n# --> implemented as feature grouping after transposing the group from the\n# kernel input features to the kernel output features.\n# RHS transpose: [gj, m] [m, gk] -> [j, gk]\n# --> which is batch grouping.\n#\n# With batch grouping, we have the following signatures:\n# Forward: [gm,j] [j,gk]->[m,gk]\n# LHS transpose: [m, gk][gk, j] -> [gm, j]\n# --> implemented as feature grouping with transposing the group on the kernel\n# and the output.\n# RHS transpose: [j, gm][m, gk] -> [j, gk]\n# --> which is feature grouping.\n\ndef _conv_general_dilated_transpose_lhs(\n g, rhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count, batch_group_count,\n lhs_shape, rhs_shape, precision):\n assert type(dimension_numbers) is ConvDimensionNumbers\n assert batch_group_count == 1 or feature_group_count == 1\n lhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n t_rhs_spec = _conv_spec_transpose(rhs_spec)\n if feature_group_count > 1:\n # in addition to switching the dims in the spec, need to move the feature\n # group axis into the transposed rhs's output feature dim\n rhs = _reshape_axis_out_of(rhs_spec[0], feature_group_count, rhs)\n rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[1], rhs)\n elif batch_group_count > 1:\n rhs = _reshape_axis_out_of(rhs_spec[0], batch_group_count, rhs)\n rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[1], rhs)\n feature_group_count = batch_group_count\n trans_dimension_numbers = ConvDimensionNumbers(out_spec, t_rhs_spec, lhs_spec)\n padding = _conv_general_vjp_lhs_padding(\n np.take(lhs_shape, lhs_sdims), np.take(rhs_shape, rhs_sdims),\n window_strides, np.take(g.shape, out_sdims), padding, lhs_dilation,\n rhs_dilation)\n revd_weights = rev(rhs, rhs_sdims)\n out = conv_general_dilated(\n g, revd_weights, window_strides=lhs_dilation, padding=padding,\n lhs_dilation=window_strides, rhs_dilation=rhs_dilation,\n dimension_numbers=trans_dimension_numbers,\n feature_group_count=feature_group_count,\n batch_group_count=1, precision=precision)\n if batch_group_count > 1:\n out = _reshape_axis_out_of(lhs_spec[1], batch_group_count, out)\n out = _reshape_axis_into(lhs_spec[1], lhs_spec[0], out)\n return out\n\ndef _conv_general_dilated_transpose_rhs(\n g, lhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers: ConvDimensionNumbers, feature_group_count: int,\n batch_group_count: int, lhs_shape, rhs_shape, precision):\n assert type(dimension_numbers) is ConvDimensionNumbers\n if np.size(g) == 0:\n # Avoids forming degenerate convolutions where the RHS has spatial size 0.\n return ad_util.Zero\n lhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\n lhs_trans, rhs_trans, out_trans = map(_conv_spec_transpose, dimension_numbers)\n assert batch_group_count == 1 or feature_group_count == 1\n if batch_group_count > 1:\n feature_group_count = batch_group_count\n batch_group_count = 1\n elif feature_group_count > 1:\n batch_group_count = feature_group_count\n feature_group_count = 1\n trans_dimension_numbers = ConvDimensionNumbers(lhs_trans, out_trans, rhs_trans)\n padding = _conv_general_vjp_rhs_padding(\n np.take(lhs_shape, lhs_sdims), np.take(rhs_shape, rhs_sdims),\n window_strides, np.take(g.shape, out_sdims), padding, lhs_dilation,\n rhs_dilation)\n return conv_general_dilated(\n lhs, g, window_strides=rhs_dilation, padding=padding,\n lhs_dilation=lhs_dilation, rhs_dilation=window_strides,\n dimension_numbers=trans_dimension_numbers,\n feature_group_count=feature_group_count,\n batch_group_count=batch_group_count, precision=precision)\n\n\ndef _conv_general_dilated_translation_rule(\n c, lhs, rhs, *, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers, feature_group_count,\n batch_group_count, precision, expand_complex_convolutions, **unused_kwargs):\n assert type(dimension_numbers) is ConvDimensionNumbers\n dimension_numbers = _conv_general_proto(dimension_numbers)\n precision_config = _precision_config(precision)\n dtype = c.get_shape(lhs).numpy_dtype()\n conv = lambda x, y: xops.ConvGeneralDilated(\n x, y, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count, batch_group_count,\n precision_config=precision_config)\n if expand_complex_convolutions and np.issubdtype(dtype, np.complexfloating):\n # We use a trick for complex multiplication due to Gauss which uses three\n # multiplications and five additions; instead of the naive method of four\n # multiplications and two additions.\n # https://en.wikipedia.org/wiki/Multiplication_algorithm#Complex_multiplication_algorithm\n #\n # This performance win comes with a trade-off in accuracy; especially in\n # cases when the real and imaginary differ hugely in magnitude. The relative\n # error bound (e.g. 1p-24 in case of float32) would be relative to the\n # maximum of real and imaginary parts of the result instead of being\n # satisfied by the real and imaginary parts independently of each other.\n lhs_real, lhs_imag = xops.Real(lhs), xops.Imag(lhs)\n rhs_real, rhs_imag = xops.Real(rhs), xops.Imag(rhs)\n k1 = conv(xops.Add(lhs_real, lhs_imag), rhs_real)\n k2 = conv(lhs_real, xops.Sub(rhs_imag, rhs_real))\n k3 = conv(lhs_imag, xops.Add(rhs_real, rhs_imag))\n return xops.Complex(xops.Sub(k1, k3), xops.Add(k1, k2))\n return conv(lhs, rhs)\n\ndef _conv_general_dilated_batch_rule(\n batched_args, batch_dims, *, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count, precision, **unused_kwargs):\n assert batch_group_count == 1 or feature_group_count == 1\n lhs, rhs = batched_args\n lhs_bdim, rhs_bdim = batch_dims\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n\n if lhs_bdim is not None and rhs_bdim is not None:\n assert lhs.shape[lhs_bdim] == rhs.shape[rhs_bdim]\n if batch_group_count > 1:\n new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[0], lhs)\n batch_group_count *= lhs.shape[lhs_bdim]\n else:\n new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[1], lhs)\n feature_group_count *= lhs.shape[lhs_bdim]\n new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\n out = conv_general_dilated(\n new_lhs, new_rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count=feature_group_count,\n batch_group_count=batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[1], lhs.shape[lhs_bdim], out)\n return out, out_spec[1]\n\n elif lhs_bdim is not None:\n if batch_group_count == 1:\n new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[0], lhs)\n out = conv_general_dilated(new_lhs, rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, precision=precision)\n out = _reshape_axis_out_of(out_spec[0], lhs.shape[lhs_bdim], out)\n return out, out_spec[0]\n else:\n new_lhs = _reshape_axis_out_of(lhs_spec[0] + int(lhs_bdim <= lhs_spec[0]),\n batch_group_count, lhs)\n new_lhs = _reshape_axis_into(lhs_bdim + int(lhs_spec[0] < lhs_bdim),\n lhs_spec[0] + 1,\n new_lhs)\n new_lhs = _reshape_axis_into(lhs_spec[0], lhs_spec[0], new_lhs)\n out = conv_general_dilated(new_lhs, rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[0], lhs.shape[lhs_bdim], out)\n return out, out_spec[0]\n\n elif rhs_bdim is not None:\n if feature_group_count == 1 and batch_group_count == 1:\n new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\n out = conv_general_dilated(lhs, new_rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[1], rhs.shape[rhs_bdim], out)\n return out, out_spec[1]\n else:\n # groups need to be outermost, so we need to factor them out of the\n # rhs output feature dim, then factor the batch dim into the remaining rhs\n # output feature dim, then put groups back in. We do something\n # similar on the output. An alternative which would require more FLOPs but\n # fewer reshapes would be to broadcast lhs.\n group_count = (feature_group_count if feature_group_count > 1\n else batch_group_count)\n new_rhs = _reshape_axis_out_of(rhs_spec[0] + int(rhs_bdim <= rhs_spec[0]),\n group_count, rhs)\n new_rhs = _reshape_axis_into(rhs_bdim + int(rhs_spec[0] < rhs_bdim),\n rhs_spec[0] + 1,\n new_rhs)\n new_rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[0], new_rhs)\n out = conv_general_dilated(lhs, new_rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[1], group_count, out)\n out = _reshape_axis_out_of(out_spec[1] + 1, rhs.shape[rhs_bdim], out)\n out = _reshape_axis_into(out_spec[1], out_spec[1] + 1, out)\n return out, out_spec[1]\n\ndef _masked(padded_value, logical_shape, dimensions, value=0):\n \"\"\"\n Sets all padding to the given value (default is 0) in the given dimensions.\n All values outside the logical shape are considered padding.\n \"\"\"\n if len(dimensions) == 0:\n return padded_value\n\n masks = [broadcasted_iota(np.int32, padded_value.shape, d) < logical_shape[d]\n for d in dimensions]\n mask_intersection = masks[0]\n for mask in masks[1:]:\n mask_intersection &= mask\n return select(mask_intersection, padded_value, full_like(padded_value, value))\n\ndef _conv_general_dilated_masking_rule(\n padded_vals, logical_shapes, window_strides, padding, lhs_dilation,\n rhs_dilation, dimension_numbers, feature_group_count, batch_group_count,\n lhs_shape, rhs_shape, precision):\n lhs, rhs = padded_vals\n logical_lhs_shape, logical_rhs_shape = logical_shapes\n\n o, i, *window_dimensions = dimension_numbers.rhs_spec\n assert (np.all(np.take(rhs.shape, window_dimensions)\n == np.take(logical_rhs_shape, window_dimensions))), \\\n \"Conv filter masking not yet implemented.\"\n\n n, c, *padded_dimensions = dimension_numbers.lhs_spec\n\n return conv_general_dilated(\n _masked(lhs, logical_lhs_shape, padded_dimensions),\n _masked(rhs, logical_rhs_shape, (i,)),\n window_strides=window_strides, padding=padding,\n lhs_dilation=lhs_dilation, rhs_dilation=rhs_dilation,\n dimension_numbers=dimension_numbers,\n feature_group_count=feature_group_count,\n batch_group_count=batch_group_count,\n precision=precision)\n\nconv_general_dilated_p = standard_primitive(\n _conv_general_dilated_shape_rule, _conv_general_dilated_dtype_rule,\n 'conv_general_dilated', partial(_conv_general_dilated_translation_rule,\n expand_complex_convolutions=False))\n\n# TODO(b/161124619, b/161126248): XLA does not support complex convolution on\n# CPU or GPU; on these backends, lower complex convolutions away.\nxla.backend_specific_translations['cpu'][conv_general_dilated_p] = partial(\n _conv_general_dilated_translation_rule, expand_complex_convolutions=True)\nxla.backend_specific_translations['gpu'][conv_general_dilated_p] = partial(\n _conv_general_dilated_translation_rule, expand_complex_convolutions=True)\n\nad.defbilinear(conv_general_dilated_p,\n _conv_general_dilated_transpose_lhs,\n _conv_general_dilated_transpose_rhs)\nbatching.primitive_batchers[conv_general_dilated_p] = \\\n _conv_general_dilated_batch_rule\nmasking.masking_rules[conv_general_dilated_p] = \\\n _conv_general_dilated_masking_rule\n\ndef _reshape_axis_into(src, dst, x):\n perm = [i for i in range(x.ndim) if i != src]\n perm.insert(dst, src)\n new_shape = list(np.delete(x.shape, src))\n new_shape[dst] *= x.shape[src]\n return reshape(x, new_shape, perm)\n\ndef _reshape_axis_out_of(src, size1, x):\n shape = list(x.shape)\n size2, ragged = divmod(shape[src], size1)\n assert not ragged\n shape[src:src+1] = [size1, size2]\n return reshape(x, shape)\n\ndef _precision_config(precision):\n if precision is not None:\n config = xla_client.PrecisionConfig()\n if isinstance(precision, tuple):\n config.operand_precision.extend(precision)\n else:\n config.operand_precision.extend((precision, precision))\n return config\n return None\n\n\ndef _dot_general_shape_rule(lhs, rhs, *, dimension_numbers, precision):\n (lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n if not all(np.all(np.greater_equal(d, 0)) and np.all(np.less(d, lhs.ndim))\n for d in (lhs_contracting, lhs_batch)):\n msg = (\"dot_general requires lhs dimension numbers to be nonnegative and \"\n \"less than the number of axes of the lhs value, got \"\n f\"lhs_batch of {lhs_batch} and lhs_contracting of {lhs_contracting} \"\n f\"for lhs of rank {lhs.ndim}\")\n raise TypeError(msg)\n if not all(np.all(np.greater_equal(d, 0)) and np.all(np.less(d, rhs.ndim))\n for d in (rhs_contracting, rhs_batch)):\n msg = (\"dot_general requires rhs dimension numbers to be nonnegative and \"\n \"less than the number of axes of the rhs value, got \"\n f\"rhs_batch of {rhs_batch} and rhs_contracting of {rhs_contracting} \"\n f\"for rhs of rank {rhs.ndim}\")\n raise TypeError(msg)\n if len(lhs_batch) != len(rhs_batch):\n msg = (\"dot_general requires equal numbers of lhs_batch and rhs_batch \"\n \"dimensions, got lhs_batch {} and rhs_batch {}.\")\n raise TypeError(msg.format(lhs_batch, rhs_batch))\n lhs_contracting_set, lhs_batch_set = set(lhs_contracting), set(lhs_batch)\n rhs_contracting_set, rhs_batch_set = set(rhs_contracting), set(rhs_batch)\n if len(lhs_batch_set) != len(lhs_batch):\n msg = (\"dot_general requires lhs batch dimensions to be distinct, got \"\n f\"lhs_batch {lhs_batch}.\")\n raise TypeError(msg)\n if len(rhs_batch_set) != len(rhs_batch):\n msg = (\"dot_general requires rhs batch dimensions to be distinct, got \"\n f\"rhs_batch {rhs_batch}.\")\n raise TypeError(msg)\n if len(lhs_contracting_set) != len(lhs_contracting):\n msg = (\"dot_general requires lhs contracting dimensions to be distinct, \"\n f\"got lhs_contracting {lhs_contracting}.\")\n raise TypeError(msg)\n if len(rhs_contracting_set) != len(rhs_contracting):\n msg = (\"dot_general requires rhs contracting dimensions to be distinct, \"\n f\"got rhs_contracting {rhs_contracting}.\")\n raise TypeError(msg)\n if lhs_contracting_set & lhs_batch_set:\n msg = (\"dot_general requires lhs batch dimensions to be disjoint from \"\n \"contracting dimensions, got lhs_batch {} and lhs_contracting {}.\")\n raise TypeError(msg.format(lhs_batch, lhs_contracting))\n if rhs_contracting_set & rhs_batch_set:\n msg = (\"dot_general requires rhs batch dimensions to be disjoint from \"\n \"contracting dimensions, got rhs_batch {} and rhs_contracting {}.\")\n raise TypeError(msg.format(rhs_batch, rhs_contracting))\n lhs_batch_shape = np.take(lhs.shape, lhs_batch)\n rhs_batch_shape = np.take(rhs.shape, rhs_batch)\n if not np.all(np.equal(lhs_batch_shape, rhs_batch_shape)):\n msg = (\"dot_general requires lhs batch dimensions and rhs batch dimensions \"\n \"to have the same shape, got {} and {}.\")\n raise TypeError(msg.format(lhs_batch_shape, rhs_batch_shape))\n lhs_contracting_shape = np.take(lhs.shape, lhs_contracting)\n rhs_contracting_shape = np.take(rhs.shape, rhs_contracting)\n if not np.all(np.equal(lhs_contracting_shape, rhs_contracting_shape)):\n msg = (\"dot_general requires contracting dimensions to have the same \"\n \"shape, got {} and {}.\")\n raise TypeError(msg.format(lhs_contracting_shape, rhs_contracting_shape))\n\n batch_shape = tuple(lhs_batch_shape)\n lhs_contract_or_batch = tuple(sorted(tuple(lhs_contracting) + tuple(lhs_batch)))\n lhs_tensored_shape = tuple(np.delete(lhs.shape, lhs_contract_or_batch))\n rhs_contract_or_batch = tuple(sorted(tuple(rhs_contracting) + tuple(rhs_batch)))\n rhs_tensored_shape = tuple(np.delete(rhs.shape, rhs_contract_or_batch))\n return batch_shape + lhs_tensored_shape + rhs_tensored_shape\n\n\ndef _dot_general_dtype_rule(lhs, rhs, *, dimension_numbers, precision):\n return naryop_dtype_rule(_input_dtype, [_any, _any], 'dot_general', lhs, rhs)\n\n\ndef _dot_general_transpose_lhs(g, y, *, dimension_numbers, precision,\n swap_ans=False):\n (x_contract, y_contract), (x_batch, y_batch) = dimension_numbers\n x_ndim = g.ndim - y.ndim + len(x_batch) + 2 * len(x_contract)\n x_kept = remaining(range(x_ndim), x_contract, x_batch)\n y_kept = remaining(range(y.ndim), y_contract, y_batch)\n if swap_ans:\n ans_batch, ans_y, _ = ranges_like(x_batch, y_kept, x_kept)\n else:\n ans_batch, _, ans_y = ranges_like(x_batch, x_kept, y_kept)\n dims = ((ans_y, y_kept), (ans_batch, y_batch))\n x_contract_sorted_by_y = list(np.take(x_contract, np.argsort(y_contract)))\n out_axes = np.argsort(list(x_batch) + x_kept + x_contract_sorted_by_y)\n return transpose(dot_general(g, y, dims, precision=precision),\n tuple(out_axes))\n\ndef _dot_general_transpose_rhs(g, x, *, dimension_numbers, precision):\n (x_contract, y_contract), (x_batch, y_batch) = dimension_numbers\n swapped_dimension_numbers = ((y_contract, x_contract), (y_batch, x_batch))\n return _dot_general_transpose_lhs(\n g, x, dimension_numbers=swapped_dimension_numbers, precision=precision,\n swap_ans=True)\n\n\ndef _dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\n precision):\n # there are three kinds of dimensions in a dot_general:\n # - contraction dimensions appear in lhs and rhs but not the result\n # - batch dimensions appear in lhs, rhs, and result\n # - tensor product dimensions appear in the result and one of lhs or rhs\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n lhs, rhs = batched_args\n lbd, rbd = batch_dims\n assert lbd is not None or rbd is not None\n def bump_dims(dims, b):\n return tuple(np.add(dims, np.greater_equal(dims, b)))\n\n if lbd is not None and rbd is not None:\n # adding a batch dimension\n lhs_batch = (lbd,) + bump_dims(lhs_batch, lbd)\n rhs_batch = (rbd,) + bump_dims(rhs_batch, rbd)\n lhs_contract = bump_dims(lhs_contract, lbd)\n rhs_contract = bump_dims(rhs_contract, rbd)\n result_batch_dim = 0\n else:\n # adding a tensor product dimension\n if lbd is not None:\n other = tuple(d for d in range(lhs.ndim)\n if d not in lhs_batch and d not in lhs_contract)\n result_batch_dim = (len(lhs_batch) + sum(np.less(other, lbd)))\n lhs_batch = bump_dims(lhs_batch, lbd)\n lhs_contract = bump_dims(lhs_contract, lbd)\n else:\n other = tuple(d for d in range(rhs.ndim)\n if d not in rhs_batch and d not in rhs_contract)\n result_batch_dim = (lhs.ndim - len(lhs_contract) +\n sum(np.less(other, rbd)))\n rhs_batch = bump_dims(rhs_batch, rbd)\n rhs_contract = bump_dims(rhs_contract, rbd)\n\n new_dimension_numbers = ((lhs_contract, rhs_contract), (lhs_batch, rhs_batch))\n batched_out = dot_general(lhs, rhs, new_dimension_numbers,\n precision=precision)\n return batched_out, int(result_batch_dim)\n\ndef _dot_using_sum_of_products(lhs, rhs, *, dimension_numbers):\n contract_dims, batch_dims = dimension_numbers\n lhs_contract_dims, rhs_contract_dims = contract_dims\n lhs_batch_dims, rhs_batch_dims = batch_dims\n lhs_noncontract_dims = tuple(sorted(\n set(range(np.ndim(lhs))) - set(lhs_batch_dims) - set(lhs_contract_dims)))\n rhs_noncontract_dims = tuple(sorted(\n set(range(np.ndim(rhs))) - set(rhs_batch_dims) - set(rhs_contract_dims)))\n lhs = transpose(lhs,\n lhs_batch_dims + lhs_noncontract_dims + lhs_contract_dims)\n rhs = transpose(rhs,\n rhs_batch_dims + rhs_noncontract_dims + rhs_contract_dims)\n\n lhs_start_expand = len(lhs_batch_dims) + len(lhs_noncontract_dims)\n lhs_end_expand = lhs_start_expand + len(rhs_noncontract_dims)\n lhs = expand_dims(lhs, tuple(range(lhs_start_expand, lhs_end_expand)))\n\n rhs_start_expand = len(lhs_batch_dims)\n rhs_end_expand = rhs_start_expand + len(lhs_noncontract_dims)\n rhs = expand_dims(rhs, tuple(range(rhs_start_expand, rhs_end_expand)))\n\n out_ndim = (len(lhs_batch_dims) + len(lhs_noncontract_dims) +\n len(rhs_noncontract_dims))\n op_product = bitwise_and if lhs.dtype == np.bool_ else mul\n op_sum = bitwise_or if lhs.dtype == np.bool_ else add\n return reduce(op_product(lhs, rhs), _zero(lhs), op_sum,\n tuple(range(out_ndim, out_ndim + len(lhs_contract_dims))))\n\ndef _dot_general_translation_rule(c, lhs, rhs, *, dimension_numbers, precision):\n dtype = c.get_shape(lhs).numpy_dtype()\n if dtypes.issubdtype(dtype, np.inexact):\n return xops.DotGeneral(lhs, rhs,\n xc.make_dot_dimension_numbers(dimension_numbers),\n precision_config=_precision_config(precision))\n else:\n # TODO(b/134526360): XLA doesn't support bool or integer dots, so we emit a\n # sum of products instead.\n translation = xla.lower_fun(_dot_using_sum_of_products,\n multiple_results=False)\n return translation(c, lhs, rhs, dimension_numbers=dimension_numbers)\n\ndef _dot_general_masking_rule(padded_vals, logical_shapes, *, dimension_numbers,\n precision):\n lhs, rhs = padded_vals\n # Only need to mask off contraction dims of one side - we mask the lhs here\n # but this is arbitrary. Could check the sizes of lhs and rhs and mask\n # whichever is smallest.\n lhs_shape, _ = logical_shapes\n (lhs_contract, _), _ = dimension_numbers\n return dot_general(_masked(lhs, lhs_shape, lhs_contract),\n rhs, dimension_numbers, precision=precision)\n\ndot_general_p = standard_primitive(_dot_general_shape_rule,\n _dot_general_dtype_rule, 'dot_general',\n _dot_general_translation_rule)\nad.defbilinear(dot_general_p,\n _dot_general_transpose_lhs, _dot_general_transpose_rhs)\nbatching.primitive_batchers[dot_general_p] = _dot_general_batch_rule\nmasking.masking_rules[dot_general_p] = _dot_general_masking_rule\n\n\ndef _broadcast_shape_rule(operand, sizes):\n _check_shapelike('broadcast', 'sizes', sizes)\n return tuple(sizes) + operand.shape\n\ndef _broadcast_batch_rule(batched_args, batch_dims, *, sizes):\n operand, = batched_args\n bdim, = batch_dims\n new_bdim = None if bdim is None else bdim + len(sizes)\n return broadcast(operand, sizes), new_bdim\n\nbroadcast_p = standard_primitive(\n _broadcast_shape_rule, _input_dtype, 'broadcast')\nad.deflinear(broadcast_p, lambda t, sizes: [_reduce_sum(t, range(len(sizes)))])\nbatching.primitive_batchers[broadcast_p] = _broadcast_batch_rule\n\ndef _broadcast_in_dim_impl(operand, *, shape, broadcast_dimensions):\n if type(operand) is np.ndarray:\n operand = _device_put_raw(operand)\n if xla.type_is_device_array(operand) and np.all(\n np.equal(operand.shape, np.take(shape, broadcast_dimensions))):\n shape = _broadcast_in_dim_shape_rule(\n operand, shape=shape, broadcast_dimensions=broadcast_dimensions)\n aval = ShapedArray(shape, _dtype(operand))\n if operand._lazy_expr is None:\n lazy_expr = lazy.broadcast(lazy.array(operand), shape, broadcast_dimensions)\n else:\n lazy_expr = lazy.broadcast(operand._lazy_expr, shape, broadcast_dimensions)\n return xla.make_device_array(aval, operand._device, lazy_expr, operand.device_buffer)\n else:\n return xla.apply_primitive(broadcast_in_dim_p, operand, shape=shape,\n broadcast_dimensions=broadcast_dimensions)\n\ndef _broadcast_in_dim_shape_rule(operand, *, shape, broadcast_dimensions):\n _check_shapelike('broadcast_in_dim', 'shape', shape)\n _check_shapelike('broadcast_in_dim', 'broadcast_dimensions',\n broadcast_dimensions)\n operand_ndim = np.ndim(operand)\n if operand_ndim != len(broadcast_dimensions):\n msg = ('broadcast_in_dim broadcast_dimensions must have length equal to '\n 'operand ndim; got broadcast_dimensions {} for operand ndim {}.')\n raise TypeError(msg.format(broadcast_dimensions, operand_ndim))\n if len(shape) < operand_ndim:\n msg = ('broadcast_in_dim target broadcast shape must have equal or higher rank '\n 'to the operand shape; got operand ndim {} and target broadcast ndim {}.')\n raise TypeError(msg.format(operand_ndim, len(shape)))\n if not set(broadcast_dimensions).issubset(set(range(len(shape)))):\n msg = ('broadcast_in_dim broadcast_dimensions must be a subset of output '\n 'dimensions, got {} for operand ndim {} and shape {}.')\n raise TypeError(msg.format(broadcast_dimensions, operand_ndim, shape))\n if any(operand.shape[i] != shape[broadcast_dimensions[i]] and\n operand.shape[i] != 1 for i in range(operand_ndim)):\n msg = (\n \"broadcast_in_dim operand dimension sizes must either be 1, or be \"\n \"equal to their corresponding dimensions in the target broadcast \"\n \"shape; got operand of shape {}, target broadcast shape {}, \"\n \"broadcast_dimensions {} \")\n raise TypeError(msg.format(operand.shape, shape, broadcast_dimensions))\n if (len(broadcast_dimensions) != len(set(broadcast_dimensions)) or\n tuple(broadcast_dimensions) != tuple(sorted(broadcast_dimensions))):\n msg = (\"broadcast_in_dim broadcast_dimensions must be strictly increasing; \"\n \"got broadcast_dimensions {}\")\n raise TypeError(msg.format(broadcast_dimensions))\n\n return shape\n\ndef _broadcast_in_dim_transpose_rule(t, *, shape, broadcast_dimensions):\n axes = tuple(np.delete(range(len(shape)), broadcast_dimensions))\n return [_reduce_sum(t, axes)]\n\ndef _broadcast_in_dim_batch_rule(batched_args, batch_dims, *, shape,\n broadcast_dimensions):\n operand, = batched_args\n bdim, = batch_dims\n new_operand = batching.moveaxis(operand, bdim, 0)\n new_shape = (operand.shape[bdim],) + shape\n new_broadcast_dimensions = (0,) + tuple(np.add(1, broadcast_dimensions))\n return broadcast_in_dim(new_operand, new_shape, new_broadcast_dimensions), 0\n\n\nbroadcast_in_dim_p = standard_primitive(\n _broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\nbroadcast_in_dim_p.def_impl(_broadcast_in_dim_impl)\nad.deflinear(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\n\n\ndef _clamp_shape_rule(min, operand, max):\n if min.shape and min.shape != operand.shape:\n m = \"clamp requires min.shape == operand.shape or min.shape == (), got {}.\"\n raise TypeError(m.format(min.shape))\n if max.shape and max.shape != operand.shape:\n m = \"clamp requires max.shape == operand.shape or max.shape == (), got {}.\"\n raise TypeError(m.format(max.shape))\n return operand.shape\n\n_clamp_dtype_rule = partial(naryop_dtype_rule, _input_dtype, [_any, _any, _any],\n 'clamp')\n\nclamp_p = standard_primitive(_clamp_shape_rule, _clamp_dtype_rule, 'clamp')\nad.defjvp(clamp_p,\n lambda g, min, operand, max:\n select(bitwise_and(gt(min, operand), lt(min, max)),\n _brcast(g, operand), _zeros(operand)),\n lambda g, min, operand, max:\n select(bitwise_and(gt(operand, min), lt(operand, max)),\n g, _zeros(operand)),\n lambda g, min, operand, max:\n select(lt(max, operand), _brcast(g, operand), _zeros(operand)))\nbatching.defbroadcasting(clamp_p)\n\n\ndef _concatenate_shape_rule(*operands, **kwargs):\n dimension = kwargs.pop('dimension')\n if not operands:\n msg = \"concatenate expects at least one operand, got 0.\"\n raise TypeError(msg)\n if not all(isinstance(operand, UnshapedArray) for operand in operands):\n msg = \"All objects to concatenate must be arrays, got {}.\"\n op = next(op for op in operands if not isinstance(op, UnshapedArray))\n raise TypeError(msg.format(type(op)))\n if len({operand.ndim for operand in operands}) != 1:\n msg = \"Cannot concatenate arrays with different ranks, got {}.\"\n raise TypeError(msg.format(\", \".join(str(o.ndim) for o in operands)))\n if not 0 <= dimension < operands[0].ndim:\n msg = \"concatenate dimension out of bounds: dimension {} for shapes {}.\"\n raise TypeError(msg.format(dimension, \", \".join([str(o.shape) for o in operands])))\n shapes = [operand.shape[:dimension] + operand.shape[dimension+1:]\n for operand in operands]\n if not shapes[:-1] == shapes[1:]:\n msg = (\"Cannot concatenate arrays with shapes that differ in dimensions \"\n \"other than the one being concatenated: concatenating along \"\n \"dimension {} for shapes {}.\")\n shapes = [operand.shape for operand in operands]\n raise TypeError(msg.format(dimension, \", \".join(map(str, shapes))))\n\n concat_size = sum(o.shape[dimension] for o in operands)\n ex_shape = operands[0].shape\n return ex_shape[:dimension] + (concat_size,) + ex_shape[dimension+1:]\n\ndef _concatenate_dtype_rule(*operands, **kwargs):\n _check_same_dtypes('concatenate', False, *(o.dtype for o in operands))\n return operands[0].dtype\n\ndef _concatenate_translation_rule(c, *operands, **kwargs):\n dimension = kwargs.pop('dimension')\n return xops.ConcatInDim(c, operands, dimension)\n\ndef _concatenate_transpose_rule(t, *operands, dimension):\n operand_shapes = [o.aval.shape if ad.is_undefined_primal(o) else o.shape\n for o in operands]\n if type(t) is ad_util.Zero:\n return ad_util.Zero\n else:\n limit_points = np.cumsum([shape[dimension] for shape in operand_shapes])\n starts = np.zeros((len(operands), t.ndim), dtype=int)\n starts[1:, dimension] = limit_points[:-1]\n limits = np.tile(t.shape, (len(operands), 1))\n limits[:, dimension] = limit_points\n\n return [slice(t, start, limit) if ad.is_undefined_primal(o) else None\n for o, start, limit in zip(operands, starts, limits)]\n\ndef _concatenate_batch_rule(batched_args, batch_dims, *, dimension):\n size = next(op.shape[bdim] for op, bdim in zip(batched_args, batch_dims)\n if bdim is not None)\n operands = [batching.moveaxis(op, bdim, 0) if bdim is not None\n else broadcast(op, (size,))\n for op, bdim in zip(batched_args, batch_dims)]\n return concatenate(operands, dimension + 1), 0\n\n# The concatenate_p masking rule requires use of a while-loop construct and so\n# is defined in lax_control_flow.py\n\nconcatenate_p = standard_primitive(\n _concatenate_shape_rule, _concatenate_dtype_rule, 'concatenate',\n _concatenate_translation_rule)\nad.deflinear(concatenate_p, _concatenate_transpose_rule)\nad.primitive_transposes[concatenate_p] = _concatenate_transpose_rule\nbatching.primitive_batchers[concatenate_p] = _concatenate_batch_rule\n\n\ndef _pad_dtype_rule(operand, padding_value, *, padding_config):\n if operand.dtype != padding_value.dtype:\n msg = \"pad operand and padding_value must be same dtype: got {} and {}.\"\n raise TypeError(msg.format(operand.dtype, padding_value.dtype))\n\n return _input_dtype(operand, padding_value)\n\ndef _pad_shape_rule(operand, padding_value, *, padding_config):\n del padding_value\n if not len(padding_config) == np.ndim(operand):\n raise ValueError(\"length of padding_config must equal the number of axes \"\n f\"of operand, got padding_config {padding_config} \"\n f\"for operand shape {np.shape(operand)}\")\n if not all(i >= 0 for _, _, i in padding_config):\n raise ValueError(\"interior padding in padding_config must be nonnegative, \"\n f\"got padding_config {padding_config}\")\n return tuple(l + h + d + (_max(0, d - 1) * i if i > 0 else 0)\n for (l, h, i), d in zip(padding_config, np.shape(operand)))\n\ndef _pad_transpose(t, operand, padding_value, *, padding_config):\n if type(t) is ad_util.Zero:\n return ad_util.Zero\n\n lo, hi, interior = zip(*padding_config)\n total = lambda x: _reduce_sum(x, list(range(t.ndim)))\n\n def t_op():\n unpad_config = safe_zip(np.negative(lo), np.negative(hi),\n np.zeros_like(interior))\n unpadded = pad(t, np.array(0., t.dtype), unpad_config)\n return slice(unpadded, np.zeros_like(lo), unpadded.shape, np.add(interior, 1))\n\n t_operand = t_op() if ad.is_undefined_primal(operand) else None\n t_padv = sub(total(t), total(t_operand)) if ad.is_undefined_primal(padding_value) else None\n\n return [t_operand, t_padv]\n\ndef _pad_batch_rule(batched_args, batch_dims, *, padding_config):\n operand, padding_value = batched_args\n operand_bdim, padding_value_bdim = batch_dims\n if padding_value_bdim is None:\n assert operand_bdim is not None\n padding_config = list(padding_config)\n padding_config.insert(operand_bdim, (0, 0, 0))\n return pad(operand, padding_value, padding_config), operand_bdim\n else:\n raise NotImplementedError # loop and stack\n\ndef _pad_translation_rule(c, operand, padding_value, *, padding_config):\n return xops.Pad(operand, padding_value,\n xc.make_padding_config(padding_config))\n\ndef _pad_masking_rule(padded_vals, logical_shapes, padding_config):\n operand, padding_value = padded_vals\n shape, _ = logical_shapes\n\n out = pad(operand, padding_value, padding_config)\n out_shape = [lo + shape[i] * (interior + 1)\n for i, (lo, hi, interior) in enumerate(padding_config)]\n padded_dims = [i for i, config in enumerate(padding_config)\n if config != (0, 0, 0)]\n return _masked(out, out_shape, padded_dims, padding_value)\n\npad_p = standard_primitive(_pad_shape_rule, _pad_dtype_rule, 'pad',\n translation_rule=_pad_translation_rule)\nad.deflinear(pad_p, _pad_transpose)\nad.primitive_transposes[pad_p] = _pad_transpose\nbatching.primitive_batchers[pad_p] = _pad_batch_rule\nmasking.masking_rules[pad_p] = _pad_masking_rule\n\n\n# The squeeze primitive exists for the benefit of masking and other\n# transformations that need to keep track of axis identity.\n# For example, consider reshaping a 2D array with shape (1, N) into a 1D array\n# with shape (N,). This results in the following JAXpr:\n# reshape[ dimension=None new_sizes=(N,) ]\n# For N > 1, we can match up the output array axis with the second axis of the\n# input. But for N = 1, it is not clear how axes match up: all we know from the\n# JAXpr is that we are reshaping from (1, 1) to (1,).\n# In constrast, squeeze[ dimensions=(0,) ] is unambiguous.\n\ndef squeeze(array: Array, dimensions: Tuple[int, ...]) -> Array:\n \"\"\"Squeeze any number of size 1 dimensions from an array.\"\"\"\n ndim = np.ndim(array)\n dimensions = tuple(sorted(canonicalize_axis(i, ndim) for i in dimensions))\n if not dimensions:\n return array\n return squeeze_p.bind(array, dimensions=dimensions)\n\ndef _squeeze_dtype_rule(operand, *, dimensions):\n return operand.dtype\n\ndef _squeeze_shape_rule(operand, *, dimensions):\n return _compute_squeeze_shape(np.shape(operand), dimensions)\n\ndef _compute_squeeze_shape(shape, dimensions):\n dims_set = set(dimensions)\n if len(dims_set) != len(dimensions):\n raise ValueError(f\"dimensions are not unique: {dimensions}\")\n if not all(0 <= d < len(shape) for d in dims_set):\n raise ValueError(f\"dimensions outside range [0, ndim): {dimensions}\")\n if any(shape[d] != 1 for d in dimensions):\n raise ValueError(\n \"cannot select an axis to squeeze out which has size not equal to \"\n f\"one, got shape={shape} and dimensions={dimensions}\")\n return tuple(s for i, s in enumerate(shape) if i not in dims_set)\n\ndef _squeeze_translation_rule(c, arg, *, dimensions):\n new_shape = _compute_squeeze_shape(c.get_shape(arg).dimensions(), dimensions)\n return xops.Reshape(arg, new_shape)\n\ndef _squeeze_transpose_rule(t, operand, *, dimensions):\n assert ad.is_undefined_primal(operand)\n return [expand_dims(t, dimensions)]\n\ndef _squeeze_batch_rule(batched_args, batch_dims, *, dimensions):\n operand, = batched_args\n bdim, = batch_dims\n operand = batching.moveaxis(operand, bdim, 0)\n dimensions = tuple(np.add(1, dimensions))\n return squeeze(operand, dimensions=dimensions), 0\n\nsqueeze_p = standard_primitive(_squeeze_shape_rule, _squeeze_dtype_rule,\n 'squeeze', _squeeze_translation_rule)\nad.deflinear2(squeeze_p, _squeeze_transpose_rule)\nbatching.primitive_batchers[squeeze_p] = _squeeze_batch_rule\n\n\ndef expand_dims(array: Array, dimensions: Tuple[int, ...]) -> Array:\n \"\"\"Insert any number of size 1 dimensions into an array.\"\"\"\n ndim_out = np.ndim(array) + len(dimensions)\n dims_set = frozenset(canonicalize_axis(i, ndim_out) for i in dimensions)\n result_shape = list(np.shape(array))\n for i in sorted(dims_set):\n result_shape.insert(i, 1)\n broadcast_dims = [i for i in range(ndim_out) if i not in dims_set]\n return broadcast_in_dim(array, result_shape, broadcast_dims)\n\n\n# We have a nonstandard reshape impl so that we can be lazy about data movement.\ndef _reshape_impl(operand, *, new_sizes, dimensions):\n old_sizes = np.shape(operand)\n if xla.type_is_device_array(operand) and dimensions is None:\n bcast_dims = _is_singleton_reshape(old_sizes, new_sizes)\n if bcast_dims is not None:\n aval = ShapedArray(new_sizes, operand.dtype)\n if operand._lazy_expr is None:\n lazy_expr = lazy.broadcast(lazy.array(operand), new_sizes, bcast_dims)\n else:\n lazy_expr = lazy.broadcast(operand._lazy_expr, new_sizes, bcast_dims)\n return xla.make_device_array(aval, operand._device, lazy_expr, operand.device_buffer)\n return xla.apply_primitive(reshape_p, operand, new_sizes=new_sizes,\n dimensions=dimensions)\n\ndef _is_singleton_reshape(old, new):\n # A singleton reshape is one where only singleton dimensions are added. We\n # want to detect them because they can be expressed as (lazy) broadcasts.\n old, new = iter(old), iter(new)\n d1, d2 = next(old, None), next(new, None)\n bcast_dims = []\n i = 0\n while True:\n if d1 is d2 is None:\n return bcast_dims\n elif d1 == d2:\n bcast_dims.append(i)\n i += 1\n d1, d2 = next(old, None), next(new, None)\n elif d2 == 1:\n i += 1\n d2 = next(new, None)\n else:\n return None\n\ndef _reshape_shape_rule(operand, *, new_sizes, dimensions):\n if not np.all(np.greater_equal(new_sizes, 0)):\n msg = 'reshape new_sizes must all be positive, got {}.'\n raise TypeError(msg.format(new_sizes))\n if prod(np.shape(operand)) != prod(new_sizes):\n msg = 'reshape total size must be unchanged, got new_sizes {} for shape {}.'\n raise TypeError(msg.format(new_sizes, np.shape(operand)))\n if dimensions is not None:\n if set(dimensions) != set(range(np.ndim(operand))):\n msg = ('reshape dimensions must be a permutation of operand dimensions, '\n 'got dimensions {} for shape {}.')\n raise TypeError(msg.format(dimensions, np.shape(operand)))\n return tuple(new_sizes)\n\ndef _reshape_dtype_rule(operand, *, new_sizes, dimensions):\n return operand.dtype\n\ndef _reshape_translation_rule(c, operand, *, new_sizes, dimensions):\n if dimensions is None:\n return xops.Reshape(operand, new_sizes)\n else:\n return xops.Reshape(operand, dimensions, new_sizes)\n\ndef _reshape_transpose_rule(t, operand, *, new_sizes, dimensions):\n assert ad.is_undefined_primal(operand)\n if dimensions is None:\n return [reshape(t, operand.aval.shape)]\n else:\n return [transpose(reshape(t, np.take(operand.aval.shape, dimensions)),\n np.argsort(dimensions))]\n\ndef _reshape_batch_rule(batched_args, batch_dims, *, new_sizes, dimensions):\n operand, = batched_args\n bdim, = batch_dims\n operand = batching.moveaxis(operand, bdim, 0)\n if dimensions is not None:\n dimensions = (0,) + tuple(np.add(1, dimensions))\n return reshape(operand, operand.shape[:1] + new_sizes, dimensions), 0\n\ndef _reshape_masking_rule(padded_args, logical_shapes, polymorphic_shapes,\n new_sizes, dimensions):\n operand, = padded_args\n old_shape, = polymorphic_shapes\n def is_poly(size): return type(size) is masking.Poly and not size.is_constant\n def merge_const_sizes(shape):\n \"\"\"Merges all nonpolymorphic sizes into the previous polymorphic size.\"\"\"\n poly_dims = [i for i, size in enumerate(shape) if is_poly(size)]\n return [prod(shape[start:stop])\n for start, stop in zip([0] + poly_dims, poly_dims + [len(shape)])]\n if merge_const_sizes(old_shape) != merge_const_sizes(new_sizes):\n raise NotImplementedError(\n \"Reshape on padded dimensions causing fragmentation is not supported.\")\n\n return reshape(operand,\n new_sizes=masking.padded_shape_as_value(new_sizes),\n dimensions=dimensions)\n\nreshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n 'reshape', _reshape_translation_rule)\nreshape_p.def_impl(_reshape_impl)\nad.deflinear2(reshape_p, _reshape_transpose_rule)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\nmasking.masking_rules[reshape_p] = _reshape_masking_rule\n\ndef _rev_shape_rule(operand, *, dimensions):\n _check_shapelike('rev', 'dimensions', dimensions)\n if len(set(dimensions)) != len(dimensions):\n msg = 'rev dimensions must be unique, got {}.'\n raise TypeError(msg.format(dimensions))\n if dimensions and not _max(dimensions) < operand.ndim:\n msg = ('rev dimensions must all be less than operand ndim, got dimensions '\n '{} for operand ndim {}.')\n raise TypeError(msg.format(dimensions, operand.ndim))\n return operand.shape\n\ndef _rev_batch_rule(batched_args, batch_dims, *, dimensions):\n operand, = batched_args\n bdim, = batch_dims\n new_dimensions = [i + 1 if i >= bdim else i for i in dimensions]\n return rev(operand, new_dimensions), bdim\n\nrev_p = standard_primitive(_rev_shape_rule, _input_dtype, 'rev')\nad.deflinear(rev_p, lambda t, dimensions: [rev(t, dimensions)])\nbatching.primitive_batchers[rev_p] = _rev_batch_rule\n\n\ndef _transpose_impl(operand, *, permutation):\n if xla.type_is_device_array(operand):\n if operand._lazy_expr is None:\n lazy_expr = lazy.transpose(lazy.array(operand), permutation)\n else:\n lazy_expr = lazy.transpose(operand._lazy_expr, permutation)\n aval = ShapedArray(lazy_expr.shape, operand.dtype)\n return xla.make_device_array(aval, operand._device, lazy_expr, operand.device_buffer)\n else:\n return xla.apply_primitive(transpose_p, operand, permutation=permutation)\n\ndef _transpose_shape_rule(operand, *, permutation):\n if not isinstance(permutation, (tuple, list, np.ndarray)):\n msg = \"transpose permutation must be a tuple/list/ndarray, got {}.\"\n raise TypeError(msg.format(type(permutation)))\n if tuple(sorted(permutation)) != tuple(range(operand.ndim)):\n msg = (\"transpose permutation isn't a permutation of operand dimensions, \"\n \"got permutation {} for operand shape {}.\")\n raise TypeError(msg.format(permutation, operand.shape))\n return tuple(np.take(operand.shape, permutation))\n\ndef _transpose_batch_rule(batched_args, batch_dims, *, permutation):\n operand, = batched_args\n bdim, = batch_dims\n perm = (bdim,) + tuple(i if i < bdim else i+1 for i in permutation)\n return transpose(operand, perm), 0\n\ndef _transpose_masking_rule(padded_vals, logical_shapes, permutation):\n return transpose(*padded_vals, permutation=permutation)\n\ntranspose_p = standard_primitive(_transpose_shape_rule, _input_dtype,\n 'transpose')\ntranspose_p.def_impl(_transpose_impl)\nad.deflinear(transpose_p,\n lambda t, permutation: [transpose(t, np.argsort(permutation))])\nbatching.primitive_batchers[transpose_p] = _transpose_batch_rule\nmasking.masking_rules[transpose_p] = _transpose_masking_rule\n\n\ndef _select_shape_rule(pred, on_true, on_false):\n if on_true.shape != on_false.shape:\n msg = \"select on_true and on_false must have the same shape, got {} and {}.\"\n raise TypeError(msg.format(on_true.shape, on_false.shape))\n if pred.shape and pred.shape != on_true.shape:\n msg = (\"select pred must be scalar or have the same shape as on_true and \"\n \"on_false, got pred shape {} for on_true and on_false of shape {}.\")\n raise TypeError(msg.format(pred.shape, on_true.shape))\n return on_true.shape\n\ndef _select_dtype_rule(pred, on_true, on_false):\n _check_same_dtypes(\"select\", False, on_true.dtype, on_false.dtype)\n if not dtypes.issubdtype(pred.dtype, np.bool_):\n msg = \"select pred must be boolean type, got {}.\"\n raise TypeError(msg.format(pred.dtype))\n return on_true.dtype\n\ndef _select_transpose_rule(t, pred, on_true, on_false):\n assert not ad.is_undefined_primal(pred)\n if type(t) is ad_util.Zero:\n return ad_util.Zero\n else:\n zeros = full_like(t, 0)\n return [None,\n select(pred, t, zeros) if ad.is_undefined_primal(on_true) else None,\n select(pred, zeros, t) if ad.is_undefined_primal(on_false) else None]\n\ndef _select_batch_rule(batched_args, batch_dims, **unused_kwargs):\n pred, on_true, on_false, = batched_args\n pred_bdim, ot_bdim, of_bdim = batch_dims\n size = next(x.shape[i] for x, i in zip(batched_args, batch_dims)\n if i is not None)\n\n # avoid transposes and some broadcasts in special cases\n if pred_bdim == ot_bdim == of_bdim:\n if np.shape(pred) == np.shape(on_true):\n return select(pred, on_true, on_false), pred_bdim\n else:\n # vmapped function had a scalar pred with nonscalar args\n assert np.ndim(pred) == 1\n pred = broadcast_in_dim(pred, on_true.shape, [pred_bdim])\n return select(pred, on_true, on_false), pred_bdim\n elif np.ndim(pred) == 0 and ot_bdim is not None and of_bdim is not None:\n if ot_bdim == of_bdim:\n return select(pred, on_true, on_false), ot_bdim\n elif np.shape(on_true) == np.shape(on_false):\n on_false = batching.moveaxis(on_false, of_bdim, ot_bdim)\n return select(pred, on_true, on_false), ot_bdim\n\n pred = batching.bdim_at_front(pred, pred_bdim, size) if np.shape(pred) else pred\n if not np.shape(on_true) == np.shape(on_false) == ():\n on_true = batching.bdim_at_front(on_true, ot_bdim, size)\n on_false = batching.bdim_at_front(on_false, of_bdim, size)\n assert np.shape(on_true) == np.shape(on_false)\n if 0 < np.ndim(pred) < np.ndim(on_true):\n # vmapped function had a scalar pred with nonscalar args\n assert np.ndim(pred) == 1\n pred = broadcast_in_dim(pred, on_true.shape, [0])\n if np.ndim(pred) > np.ndim(on_true):\n assert np.ndim(on_true) == 0\n on_true = broadcast(on_true, pred.shape)\n on_false = broadcast(on_false, pred.shape)\n return select(pred, on_true, on_false), 0\n\ndef _select_masking_rule(padded_vals, logical_shapes):\n pred_shape, true_shape, false_shape = [\n masking.padded_shape_as_value(val.shape) for val in padded_vals]\n assert np.array_equal(pred_shape, true_shape)\n assert np.array_equal(pred_shape, false_shape)\n return select(*padded_vals)\n\ndef _select_jvp(primals, tangents):\n pred, on_true, on_false = primals\n _, on_true_dot, on_false_dot = tangents\n out = select(pred, on_true, on_false)\n if type(on_true_dot) is ad_util.Zero:\n out_dot = select(pred, _zeros(on_false_dot), on_false_dot)\n elif type(on_false_dot) is ad_util.Zero:\n out_dot = select(pred, on_true_dot, _zeros(on_true_dot))\n else:\n out_dot = select(pred, on_true_dot, on_false_dot)\n return out, out_dot\n\nselect_p = standard_primitive(_select_shape_rule, _select_dtype_rule, 'select')\nad.primitive_jvps[select_p] = _select_jvp\nad.primitive_transposes[select_p] = _select_transpose_rule\nbatching.primitive_batchers[select_p] = _select_batch_rule\nmasking.masking_rules[select_p] = _select_masking_rule\n\n\ndef _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\n _check_shapelike(\"slice\", \"start_indices\", start_indices)\n _check_shapelike(\"slice\", \"limit_indices\", limit_indices)\n if operand.ndim != len(start_indices):\n msg = (\"slice start_indices must have length equal to the number of \"\n \"dimensions of the operand, got indices {} for operand shape {}.\")\n raise TypeError(msg.format(start_indices, operand.shape))\n if len(start_indices) != len(limit_indices):\n msg = (\"slice limit_indices must have the same length as start_indices, \"\n \"got start_inidices {} and limit_indices {}.\")\n raise TypeError(msg.format(start_indices, limit_indices))\n if (not masking.is_polymorphic(limit_indices) and\n not masking.is_polymorphic(operand.shape) and\n not np.all(np.less_equal(limit_indices, operand.shape))):\n msg = (\"slice limit_indices must be less than or equal to operand shape, \"\n \"got limit_indices {} for operand shape {}.\")\n raise TypeError(msg.format(limit_indices, operand.shape))\n if not np.all(np.greater_equal(start_indices, 0)):\n msg = (\"slice start_indices must be greater than or equal to zero, \"\n \"got start_indices of {}.\")\n raise TypeError(msg.format(start_indices))\n if (not masking.is_polymorphic(limit_indices) and\n not np.all(np.greater_equal(limit_indices, start_indices))):\n msg = (\"slice limit_indices must be greater than or equal to start_indices,\"\n \" got start_indices {} and limit_indices {}.\")\n raise TypeError(msg.format(start_indices, limit_indices))\n if strides is None:\n strides = np.ones(operand.ndim, np.int32)\n else:\n _check_shapelike(\"slice\", \"strides\", strides)\n if len(strides) != operand.ndim:\n msg = (\"slice strides must have length equal to the number of dimensions \"\n \"of the operand, got strides {} for operand shape {}.\")\n raise TypeError(msg.format(strides, operand.shape))\n if not np.all(np.greater(strides, 0)):\n msg = \"slice strides must be positive, got {}\"\n raise TypeError(msg.format(strides))\n\n diff = np.subtract(limit_indices, start_indices)\n # Not np.divmod since Poly.__rdivmod__ is ignored by NumPy, breaks poly stride\n return tuple(q + (r > 0) for q, r in map(divmod, diff, strides))\n\ndef _slice_translation_rule(c, operand, *, start_indices, limit_indices,\n strides):\n return xops.Slice(operand, start_indices, limit_indices,\n strides or [1] * len(start_indices))\n\ndef _slice_transpose_rule(t, operand, *, start_indices, limit_indices, strides):\n assert ad.is_undefined_primal(operand)\n operand_shape = operand.aval.shape\n if strides is None or np.all(np.equal(strides, 1)):\n pads = zip(start_indices, np.subtract(operand_shape, limit_indices),\n (0,) * len(start_indices))\n else:\n real_limits = np.add(\n start_indices,\n np.where(np.array(t.shape) == 0, 0,\n np.add(1, np.multiply(np.subtract(t.shape, 1), strides))))\n pads = safe_zip(start_indices, np.subtract(operand_shape, real_limits),\n np.subtract(strides, 1))\n result = pad(t, _const(t, 0), pads)\n assert result.shape == operand_shape, (\n f\"result.shape={result.shape} operand_shape={operand_shape}\")\n return [result]\n\n\ndef _slice_batching_rule(batched_args, batch_dims, *, start_indices,\n limit_indices, strides):\n operand, = batched_args\n bdim, = batch_dims\n\n new_start_indices = list(start_indices)\n new_start_indices.insert(bdim, 0)\n\n new_limit_indices = list(limit_indices)\n new_limit_indices.insert(bdim, operand.shape[bdim])\n\n if strides is None:\n new_strides = None\n else:\n new_strides = list(strides)\n new_strides.insert(bdim, 1)\n\n out = slice(operand, new_start_indices, new_limit_indices, new_strides)\n return out, bdim\n\ndef _slice_masking_rule(\n padded_vals, logical_shapes, start_indices, limit_indices, strides):\n operand, = padded_vals\n strides = masking.padded_shape_as_value(strides) if strides else None\n return slice(operand,\n start_indices=masking.padded_shape_as_value(start_indices),\n limit_indices=masking.padded_shape_as_value(limit_indices),\n strides=strides)\n\nslice_p = standard_primitive(_slice_shape_rule, _input_dtype, 'slice',\n _slice_translation_rule)\nad.deflinear2(slice_p, _slice_transpose_rule)\nbatching.primitive_batchers[slice_p] = _slice_batching_rule\nmasking.masking_rules[slice_p] = _slice_masking_rule\n\n\ndef _dynamic_slice_shape_rule(operand, *start_indices, slice_sizes):\n if operand.ndim != len(start_indices):\n msg = (\"dynamic_slice start_indices must have length equal to the number \"\n \"of dimensions of the operand, got indices {} for operand shape {}.\")\n raise TypeError(msg.format(start_indices, operand.shape))\n if len(start_indices) != len(slice_sizes):\n msg = (\"dynamic_slice slice_sizes must have the same length as \"\n \"start_indices, got start_inidices length {} and slice_sizes {}.\")\n raise TypeError(msg.format(len(start_indices), slice_sizes))\n if not np.all(np.less_equal(slice_sizes, operand.shape)):\n msg = (\"slice slice_sizes must be less than or equal to operand shape, \"\n \"got slice_sizes {} for operand shape {}.\")\n raise TypeError(msg.format(slice_sizes, operand.shape))\n if not np.all(np.greater_equal(slice_sizes, 0)):\n msg = (\"slice slice_sizes must be greater than or equal to zero, \"\n \"got slice_sizes of {}.\")\n raise TypeError(msg.format(slice_sizes))\n return tuple(slice_sizes)\n\ndef _dynamic_slice_dtype_rule(operand, *start_indices, slice_sizes):\n if any(i.dtype != start_indices[0].dtype or\n not dtypes.issubdtype(i.dtype, np.integer) for i in start_indices):\n msg = (\"index arguments to dynamic_slice must be integers of the same \"\n \"type, got: {}\")\n raise TypeError(msg.format(\", \".join(i.dtype.name for i in start_indices)))\n return operand.dtype\n\ndef _dynamic_slice_translation_rule(c, operand, *start_indices, slice_sizes):\n return xops.DynamicSlice(operand, start_indices, slice_sizes)\n\ndef _dynamic_slice_jvp(primals, tangents, *, slice_sizes):\n tangent_out = tangents[0]\n if type(tangent_out) is not ad_util.Zero:\n tangent_out = dynamic_slice(tangent_out, primals[1:], slice_sizes)\n return dynamic_slice(primals[0], primals[1:], slice_sizes), tangent_out\n\ndef _dynamic_slice_transpose_rule(t, operand, *start_indices, slice_sizes):\n assert ad.is_undefined_primal(operand)\n assert all(not ad.is_undefined_primal(s) for s in start_indices)\n operand_shape, operand_dtype = operand.aval.shape, operand.aval.dtype\n if config.omnistaging_enabled:\n zeros = full(operand_shape, 0, operand_dtype)\n else:\n zeros = full(operand_shape, tie_in(t, _zero(t)))\n if type(t) is ad_util.Zero:\n return [zeros] + [None] * len(start_indices)\n else:\n return ([dynamic_update_slice(zeros, t, start_indices)] +\n [None] * len(start_indices))\n\ndef _batch_dynamic_slice_indices(indices, bdims):\n if len(indices) == 0:\n return np.array([], 'int32'), None\n size = next((x.shape[i] for x, i in zip(indices, bdims) if i is not None), -1)\n if size < 0:\n return concatenate([broadcast(i, (1,)) for i in indices], 0), None\n indices = concatenate(\n [broadcast_in_dim(x, (size, 1),\n broadcast_dimensions=((0,) if i is not None else ()))\n for x, i in zip(indices, bdims)],\n dimension=1)\n return indices, 0\n\ndef _dynamic_slice_batching_rule(batched_args, batch_dims, *, slice_sizes):\n # A dynamic slice is a special case of gather; we can delegate to the gather\n # batching rule.\n # TODO(phawkins): consider removing dynamic_slice entirely and using gather\n # always.\n operand, *start_indices = batched_args\n operand_bd, *start_idx_bds = batch_dims\n operand_shape = (operand.shape if operand_bd is batching.not_mapped\n else tuple(np.delete(operand.shape, operand_bd)))\n dims = tuple(range(len(operand_shape)))\n dnums = GatherDimensionNumbers(offset_dims=dims, collapsed_slice_dims=(),\n start_index_map=dims)\n index, index_bdim = _batch_dynamic_slice_indices(start_indices, start_idx_bds)\n return _gather_batching_rule(\n [operand, index], [operand_bd, index_bdim], dimension_numbers=dnums,\n slice_sizes=slice_sizes)\n\n\ndynamic_slice_p = standard_primitive(\n _dynamic_slice_shape_rule, _dynamic_slice_dtype_rule, 'dynamic_slice',\n _dynamic_slice_translation_rule)\nad.primitive_jvps[dynamic_slice_p] = _dynamic_slice_jvp # TODO\nad.primitive_transposes[dynamic_slice_p] = _dynamic_slice_transpose_rule\nbatching.primitive_batchers[dynamic_slice_p] = _dynamic_slice_batching_rule\n\n\ndef _dynamic_update_slice_shape_rule(operand, update, *start_indices):\n if operand.ndim != update.ndim:\n msg = (\"dynamic_update_slice update must have the same rank as operand, \"\n \"got update shape {} for operand shape {}.\")\n raise TypeError(msg.format(update.shape, operand.shape))\n if operand.ndim != len(start_indices):\n msg = (\"dynamic_update_slice start_indices must have length equal to the \"\n \"rank of operand, got indices {} for operand shape {}.\")\n raise TypeError(msg.format(start_indices, operand.shape))\n if not np.all(np.less_equal(update.shape, operand.shape)):\n msg = (\"dynamic_update_slice update shape must be smaller than operand \"\n \"shape, got update shape {} for operand shape {}.\")\n raise TypeError(msg.format(update.shape, operand.shape))\n return operand.shape\n\ndef _dynamic_update_slice_dtype_rule(operand, update, *start_indices):\n _check_same_dtypes(\"dynamic_update_slice\", False, operand.dtype, update.dtype)\n if any(i.dtype != start_indices[0].dtype or\n not dtypes.issubdtype(i.dtype, np.integer) for i in start_indices):\n msg = (\"index arguments to dynamic_update_slice must be integers of the \"\n \"same type, got {}\")\n raise TypeError(msg.format(\", \".join(i.dtype.name for i in start_indices)))\n return operand.dtype\n\ndef _dynamic_update_slice_jvp(primals, tangents):\n operand, update = primals[:2]\n start_indices = primals[2:]\n g_operand, g_update = tangents[:2]\n val_out = dynamic_update_slice(operand, update, start_indices)\n if type(g_operand) is ad_util.Zero and type(g_update) is ad_util.Zero:\n tangent_out = ad_util.Zero.from_value(val_out)\n else:\n g_operand = ad.instantiate_zeros(g_operand)\n g_update = ad.instantiate_zeros(g_update)\n tangent_out = dynamic_update_slice(g_operand, g_update, start_indices)\n return val_out, tangent_out\n\ndef _dynamic_update_slice_transpose_rule(t, operand, update, *start_indices):\n assert all(not ad.is_undefined_primal(x) for x in start_indices)\n if ad.is_undefined_primal(update):\n update_shape = update.aval.shape\n else:\n update_shape = update.shape\n dus = dynamic_update_slice\n ds = dynamic_slice\n zeros = _zeros(t, shape=update_shape)\n operand_t = dus(t, zeros, start_indices) if ad.is_undefined_primal(operand) else None\n update_t = ds(t, start_indices, update_shape) if ad.is_undefined_primal(update) else None\n return [operand_t, update_t] + [None] * len(start_indices)\n\ndef _dynamic_update_slice_translation_rule(c, operand, update, *start_indices):\n return xops.DynamicUpdateSlice(operand, update, start_indices)\n\ndef _dynamic_update_slice_batching_rule(batched_args, batch_dims):\n # A dynamic update slice is a special case of scatter; we can delegate to the\n # scatter batching rule.\n # TODO(phawkins): consider removing dynamic_update_slice entirely and using\n # scatter always.\n operand, update, *start_idx = batched_args\n operand_bd, update_bd, *start_idx_bd = batch_dims\n update_shape = (np.shape(update) if update_bd is batching.not_mapped\n else tuple(np.delete(np.shape(update), update_bd)))\n dims = tuple(range(len(update_shape)))\n dnums = ScatterDimensionNumbers(update_window_dims=dims,\n inserted_window_dims=(),\n scatter_dims_to_operand_dims=dims)\n index, index_bdim = _batch_dynamic_slice_indices(start_idx, start_idx_bd)\n return _scatter_batching_rule(\n scatter, (operand, index, update), (operand_bd, index_bdim, update_bd),\n update_jaxpr=None, update_consts=None, dimension_numbers=dnums,\n indices_are_sorted=True, unique_indices=True)\n\n\ndynamic_update_slice_p = standard_primitive(\n _dynamic_update_slice_shape_rule, _dynamic_update_slice_dtype_rule,\n 'dynamic_update_slice', _dynamic_update_slice_translation_rule)\nad.primitive_jvps[dynamic_update_slice_p] = _dynamic_update_slice_jvp\nad.primitive_transposes[dynamic_update_slice_p] = \\\n _dynamic_update_slice_transpose_rule\nbatching.primitive_batchers[dynamic_update_slice_p] = \\\n _dynamic_update_slice_batching_rule\n\n\ndef _gather_dimensions_proto(indices_shape, dimension_numbers):\n assert type(dimension_numbers) is GatherDimensionNumbers\n proto = xla_client.GatherDimensionNumbers()\n proto.offset_dims.extend(dimension_numbers.offset_dims)\n proto.collapsed_slice_dims.extend(dimension_numbers.collapsed_slice_dims)\n proto.start_index_map.extend(dimension_numbers.start_index_map)\n assert indices_shape.rank() > 0\n proto.index_vector_dim = indices_shape.rank() - 1\n return proto\n\ndef _gather_dtype_rule(operand, start_indices, **kwargs):\n if not dtypes.issubdtype(start_indices.dtype, np.integer):\n raise ValueError(\"start_indices must have an integer type\")\n return dtypes.canonicalize_dtype(operand.dtype)\n\n_rank = lambda arr: len(arr.shape)\n\ndef _is_sorted(dims, op_name, name):\n for i in range(1, len(dims)):\n if dims[i] < dims[i - 1]:\n raise TypeError(f\"{name} in {op_name} op must be sorted; got {dims}\")\n\ndef _sorted_dims_in_range(dims, rank, op_name, name):\n if len(dims) == 0:\n return\n invalid_dim = None\n if dims[0] < 0:\n invalid_dim = dims[0]\n elif dims[-1] >= rank:\n invalid_dim = dims[-1]\n if invalid_dim:\n raise TypeError(f\"Invalid {name} set in {op_name} op; valid range is \"\n f\"[0, {rank}); got: {invalid_dim}.\")\n\ndef _no_duplicate_dims(dims, op_name, name):\n if len(set(dims)) != len(dims):\n raise TypeError(f\"{name} in {op_name} op must not repeat; got: {dims}.\")\n\ndef _gather_shape_rule(operand, start_indices, *, dimension_numbers,\n slice_sizes):\n \"\"\"Validates the well-formedness of the arguments to Gather.\n\n The code implements the checks based on the detailed operation semantics of\n XLA's `Gather <https://www.tensorflow.org/xla/operation_semantics#gather>`_\n operator and following the outline of the implementation of\n ShapeInference::InferGatherShape in TensorFlow.\n \"\"\"\n\n offset_dims = dimension_numbers.offset_dims\n collapsed_slice_dims = dimension_numbers.collapsed_slice_dims\n start_index_map = dimension_numbers.start_index_map\n\n # Note: in JAX, index_vector_dim is always computed as below, cf. the\n # documentation of the GatherDimensionNumbers class.\n index_vector_dim = _rank(start_indices) - 1\n\n # This case should never happen in JAX, due to the implicit construction of\n # index_vector_dim, but is included for completeness.\n if _rank(start_indices) < index_vector_dim or index_vector_dim < 0:\n raise TypeError(f\"Gather index leaf dimension must be within [0, rank(\"\n f\"start_indices) + 1). rank(start_indices) is \"\n f\"{_rank(start_indices)} and gather index leaf dimension \"\n f\"is {index_vector_dim}.\")\n\n expanded_start_indices_shape = list(start_indices.shape)\n\n # This case should never happen in JAX, due to the implicit construction of\n # index_vector_dim, but is included for completeness.\n if len(expanded_start_indices_shape) == index_vector_dim:\n expanded_start_indices_shape.append(1)\n\n # Start ValidateGatherDimensions\n # In the error messages output by XLA, \"offset_dims\" is called \"Output window\n # dimensions\" in error messages. For consistency's sake, our error messages\n # stick to \"offset_dims\".\n _is_sorted(offset_dims, \"gather\", \"offset_dims\")\n _no_duplicate_dims(offset_dims, \"gather\", \"offset_dims\")\n\n output_offset_dim_count = len(offset_dims)\n output_shape_rank = len(offset_dims) + _rank(start_indices) - 1\n\n for i in range(output_offset_dim_count):\n offset_dim = offset_dims[i]\n if offset_dim < 0 or offset_dim >= output_shape_rank:\n raise TypeError(f\"Offset dimension {i} in gather op is out of bounds; \"\n f\"got {offset_dim}, but should have been in \"\n f\"[0, {output_shape_rank})\")\n\n if len(start_index_map) != start_indices.shape[index_vector_dim]:\n raise TypeError(f\"Gather op has {len(start_index_map)} elements in \"\n f\"start_index_map and the bound of dimension \"\n f\"index_vector_dim={index_vector_dim} of start_indices is \"\n f\"{start_indices.shape[index_vector_dim]}. These two \"\n f\"numbers must be equal.\")\n\n for i in range(len(start_index_map)):\n operand_dim_for_start_index_i = start_index_map[i]\n if (operand_dim_for_start_index_i < 0 or\n operand_dim_for_start_index_i >= _rank(operand)):\n raise TypeError(f\"Invalid start_index_map; domain is \"\n f\"[0, {_rank(operand)}), got: \"\n f\"{i}->{operand_dim_for_start_index_i}.\")\n\n _no_duplicate_dims(start_index_map, \"gather\", \"start_index_map\")\n\n # _is_sorted and _sorted_dims_in_range are checked in the opposite order\n # compared to the XLA implementation. In cases when the input is not sorted\n # AND there are problematic collapsed_slice_dims, the error message will thus\n # be different.\n _is_sorted(collapsed_slice_dims, \"gather\", \"collapsed_slice_dims\")\n _sorted_dims_in_range(collapsed_slice_dims, _rank(operand), \"gather\",\n \"collapsed_slice_dims\")\n _no_duplicate_dims(collapsed_slice_dims, \"gather\", \"collapsed_slice_dims\")\n # End ValidateGatherDimensions\n\n if _rank(operand) != len(slice_sizes):\n raise TypeError(f\"Gather op must have one slice size for every input \"\n f\"dimension; got: len(slice_sizes)={len(slice_sizes)}, \"\n f\"input_shape.rank={_rank(operand)}\")\n\n if len(slice_sizes) != len(offset_dims) + len(collapsed_slice_dims):\n raise TypeError(f\"All components of the offset index in a gather op must \"\n f\"either be a offset dimension or explicitly collapsed; \"\n f\"got len(slice_sizes)={len(slice_sizes)}, \"\n f\"output_slice_sizes={offset_dims}, collapsed_slice_dims=\"\n f\"{collapsed_slice_dims}.\")\n\n for i in range(len(slice_sizes)):\n slice_size = slice_sizes[i]\n corresponding_input_size = operand.shape[i]\n\n if slice_size < 0 or slice_size > corresponding_input_size:\n raise TypeError(f\"Slice size at index {i} in gather op is out of range, \"\n f\"must be within [0, {corresponding_input_size + 1}), \"\n f\"got {slice_size}.\")\n\n for i in range(len(collapsed_slice_dims)):\n bound = slice_sizes[collapsed_slice_dims[i]]\n if bound > 1:\n raise TypeError(f\"Gather op can only collapse slice dims with bound 1 \"\n f\"or 0, but bound is {bound} for index \"\n f\"{collapsed_slice_dims[i]} at position {i}.\")\n\n expanded_start_indices_shape.pop(index_vector_dim)\n start_indices_shape = iter(expanded_start_indices_shape)\n\n slice_sizes = iter(np.delete(slice_sizes, collapsed_slice_dims))\n return tuple(next(slice_sizes) if i in offset_dims\n else next(start_indices_shape) for i in range(output_shape_rank))\n\ndef _gather_translation_rule(c, operand, start_indices, *, dimension_numbers,\n slice_sizes):\n indices_shape = c.get_shape(start_indices)\n return xops.Gather(\n operand, start_indices,\n _gather_dimensions_proto(indices_shape, dimension_numbers), slice_sizes,\n indices_are_sorted=False)\n\ndef _gather_jvp_rule(g, operand, start_indices, *, dimension_numbers,\n slice_sizes):\n return gather(g, start_indices, dimension_numbers, slice_sizes)\n\ndef _gather_transpose_rule(t, operand, start_indices, *, dimension_numbers,\n slice_sizes):\n assert ad.is_undefined_primal(operand)\n operand_shape = operand.aval.shape\n if type(t) is ad_util.Zero:\n return ad_util.Zero\n if config.omnistaging_enabled:\n zeros = full(operand_shape, _zero(t))\n else:\n zeros = full(operand_shape, tie_in(t, _zero(t)))\n scatter_dnums = ScatterDimensionNumbers(\n update_window_dims=dimension_numbers.offset_dims,\n inserted_window_dims=dimension_numbers.collapsed_slice_dims,\n scatter_dims_to_operand_dims=dimension_numbers.start_index_map)\n out = scatter_add(zeros, start_indices, t, scatter_dnums,\n indices_are_sorted=False,\n unique_indices=False)\n return [out, ad_util.Zero.from_value(start_indices)]\n\ndef _gather_batching_rule(batched_args, batch_dims, *, dimension_numbers,\n slice_sizes):\n operand, start_indices = batched_args\n operand_bdim, start_indices_bdim = batch_dims\n\n if operand_bdim is not None and start_indices_bdim is None:\n operand = batching.moveaxis(operand, operand_bdim, 0)\n slice_sizes = (operand.shape[0],) + slice_sizes\n offset_dims = (0,) + tuple(np.add(1, dimension_numbers.offset_dims))\n collapsed_slice_dims = tuple(np.add(1, dimension_numbers.collapsed_slice_dims))\n start_index_map = tuple(np.add(1, dimension_numbers.start_index_map))\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=collapsed_slice_dims,\n start_index_map=start_index_map)\n return gather(operand, start_indices, dimension_numbers=dnums,\n slice_sizes=slice_sizes), 0\n\n elif operand_bdim is None and start_indices_bdim is not None:\n start_indices = batching.moveaxis(start_indices, start_indices_bdim, 0)\n offset_dims = tuple(np.add(1, dimension_numbers.offset_dims))\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=dimension_numbers.collapsed_slice_dims,\n start_index_map=dimension_numbers.start_index_map)\n return gather(operand, start_indices, dimension_numbers=dnums,\n slice_sizes=slice_sizes), 0\n\n else:\n # move batch dimensions to the front to simplify logic\n operand = batching.moveaxis(operand, operand_bdim, 0)\n start_indices = batching.moveaxis(start_indices, start_indices_bdim, 0)\n\n # Example: user code had start_indices shape (3, 4, 5), and we have to deal\n # with start_indices shape (7, 3, 4, 5). We transform that to a\n # start_indices of shape (7, 3, 4, 6) where we concatenated an iota that\n # counts along our batch dimension to the front of the ndindex.\n count_shape = list(start_indices.shape)\n count_shape[-1] = 1\n counts = broadcasted_iota(start_indices.dtype, tuple(count_shape), 0)\n start_indices = concatenate([counts, start_indices], len(count_shape) - 1)\n\n slice_sizes = (1,) + slice_sizes\n collapsed_slice_dims = (0,) + tuple(np.add(1, dimension_numbers.collapsed_slice_dims))\n offset_dims = tuple(np.add(1, dimension_numbers.offset_dims))\n start_index_map = (0,) + tuple(np.add(1, dimension_numbers.start_index_map))\n\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=collapsed_slice_dims,\n start_index_map=start_index_map)\n return gather(operand, start_indices, dimension_numbers=dnums,\n slice_sizes=slice_sizes), 0\n\ngather_p = standard_primitive(\n _gather_shape_rule, _gather_dtype_rule, 'gather',\n _gather_translation_rule)\nad.defjvp(gather_p, _gather_jvp_rule, None)\n\nad.primitive_transposes[gather_p] = _gather_transpose_rule\nbatching.primitive_batchers[gather_p] = _gather_batching_rule\n\n\ndef _scatter_dimensions_proto(indices_shape, dimension_numbers):\n assert type(dimension_numbers) is ScatterDimensionNumbers\n proto = xla_client.ScatterDimensionNumbers()\n proto.update_window_dims.extend(dimension_numbers.update_window_dims)\n proto.inserted_window_dims.extend(dimension_numbers.inserted_window_dims)\n proto.scatter_dims_to_operand_dims.extend(\n dimension_numbers.scatter_dims_to_operand_dims)\n assert indices_shape.rank() > 0\n proto.index_vector_dim = indices_shape.rank() - 1\n return proto\n\ndef _scatter_dtype_rule(operand, scatter_indices, updates, **kwargs):\n if not dtypes.issubdtype(scatter_indices.dtype, np.integer):\n raise ValueError(\"scatter_indices must have an integer type\")\n _check_same_dtypes(\"scatter\", False, operand.dtype, updates.dtype)\n return dtypes.canonicalize_dtype(operand.dtype)\n\ndef _scatter_shape_rule(operand, scatter_indices, updates, *, update_jaxpr,\n update_consts, dimension_numbers, indices_are_sorted,\n unique_indices):\n \"\"\"Validates the well-formedness of the ``dimension_numbers`` argument to\n Scatter.\n\n The code implements the checks based on the detailed operation semantics of\n XLA's `Scatter <https://www.tensorflow.org/xla/operation_semantics#scatter>`_\n operator and following the outline of the implementation of\n ShapeInference::InferScatterShape in TensorFlow.\n \"\"\"\n\n update_window_dims = dimension_numbers.update_window_dims\n inserted_window_dims = dimension_numbers.inserted_window_dims\n scatter_dims_to_operand_dims = dimension_numbers.scatter_dims_to_operand_dims\n # Note: in JAX, index_vector_dim is always computed as below, cf. the\n # documentation of the ScatterDimensionNumbers class.\n index_vector_dim = _rank(scatter_indices) - 1\n\n # This case should never happen in JAX, due to the implicit construction of\n # index_vector_dim, but is included for completeness.\n if _rank(scatter_indices) < index_vector_dim or index_vector_dim < 0:\n raise TypeError(f\"Scatter index leaf dimension must be within [0, \"\n f\"rank(scatter_indices) + 1). rank(scatter_indices) is \"\n f\"{_rank(scatter_indices)} and scatter index leaf \"\n f\"dimension is {index_vector_dim}.\")\n\n expanded_scatter_indices_shape = list(scatter_indices.shape)\n # This case should never happen in JAX, due to the implicit construction of\n # index_vector_dim, but is included for completeness.\n if len(expanded_scatter_indices_shape) == index_vector_dim:\n expanded_scatter_indices_shape.append(1)\n\n expected_updates_rank = (len(expanded_scatter_indices_shape) - 1 +\n len(update_window_dims))\n\n if _rank(updates) != expected_updates_rank:\n raise TypeError(f\"Updates tensor must be of rank {expected_updates_rank}; \"\n f\"got {_rank(updates)}.\")\n\n # Validate update_window_dims\n _is_sorted(update_window_dims, \"scatter\", \"update_window_dims\")\n _no_duplicate_dims(update_window_dims, \"scatter\", \"update_window_dims\")\n _sorted_dims_in_range(update_window_dims, _rank(updates), \"scatter\",\n \"update_window_dims\")\n\n # Validate inserted_window_dims\n _is_sorted(inserted_window_dims, \"scatter\", \"inserted_window_dims\")\n _no_duplicate_dims(inserted_window_dims, \"scatter\", \"inserted_window_dims\")\n _sorted_dims_in_range(inserted_window_dims, _rank(operand), \"scatter\",\n \"inserted_window_dims\")\n\n # Validate window_size\n window_size = len(update_window_dims) + len(inserted_window_dims)\n if _rank(operand) != window_size:\n raise TypeError(f\"Scatter op has window of size {window_size}; doesn't \"\n f\"match operand of rank {_rank(operand)}.\")\n\n # Validate scatter_dims_to_operand_dims\n if (len(scatter_dims_to_operand_dims) !=\n scatter_indices.shape[index_vector_dim]):\n raise TypeError(f\"Scatter op has {len(scatter_dims_to_operand_dims)} \"\n f\"elements in scatter_dims_to_operand_dims and the bound \"\n f\"of dimension index_vector_dim={index_vector_dim} of \"\n f\"scatter_indices is \"\n f\"{scatter_indices.shape[index_vector_dim]}. These two \"\n f\"numbers must be equal\")\n\n for i in range(len(scatter_dims_to_operand_dims)):\n dim = scatter_dims_to_operand_dims[i]\n if dim < 0 or dim >= _rank(operand):\n raise TypeError(f\"Invalid scatter_dims_to_operand_dims mapping; domain \"\n f\"is [0, {_rank(operand)}), got: {i}->{dim}.\")\n\n _no_duplicate_dims(scatter_dims_to_operand_dims, \"scatter\",\n \"scatter_dims_to_operand_dims\")\n\n max_update_slice_sizes = [operand.shape[i] for i in range(len(operand.shape))\n if not i in set(inserted_window_dims)]\n\n for i in range(len(update_window_dims)):\n update_window_dim = update_window_dims[i]\n if updates.shape[update_window_dim] > max_update_slice_sizes[i]:\n raise TypeError(f\"Bounds of the window dimensions of updates must not \"\n f\"exceed the bounds of the corresponding dimensions of \"\n f\"operand. For dimension {update_window_dim}, updates \"\n f\"bound is {updates.shape[update_window_dim]}, operand \"\n f\"bound is {max_update_slice_sizes[i]}.\")\n\n update_scatter_dims = [dim for dim in range(_rank(updates)) if dim not in\n set(update_window_dims)]\n\n scatter_dims_seen = 0\n for i in update_scatter_dims:\n if scatter_dims_seen == index_vector_dim:\n scatter_dims_seen += 1\n if updates.shape[i] != expanded_scatter_indices_shape[scatter_dims_seen]:\n raise TypeError(f\"Bounds of the scatter dimensions of updates must be \"\n f\"the same as the bounds of the corresponding dimensions \"\n f\"of scatter indices. For scatter dimension {i}, updates \"\n f\"bound is {updates.shape[i]}, scatter_indices bound is \"\n f\"{expanded_scatter_indices_shape[scatter_dims_seen]}.\")\n scatter_dims_seen += 1\n\n return operand.shape\n\ndef _scatter_translation_rule(c, operand, scatter_indices, updates, *,\n update_jaxpr, update_consts, dimension_numbers,\n indices_are_sorted, unique_indices):\n dtype = c.get_shape(operand).numpy_dtype()\n init_value = xb.constant(c, np.array(0, dtype))\n update_computation = _reduction_computation(\n c, update_jaxpr, update_consts, init_value)\n indices_shape = c.get_shape(scatter_indices)\n return xops.Scatter(operand, scatter_indices, updates, update_computation,\n _scatter_dimensions_proto(indices_shape, dimension_numbers),\n indices_are_sorted, unique_indices)\n\ndef _scatter_add_translation_rule(\n c, operand, scatter_indices, updates, *, update_jaxpr, update_consts,\n dimension_numbers, indices_are_sorted, unique_indices,\n expand_complex128=False):\n dtype = c.get_shape(operand).numpy_dtype()\n scatter_dims = _scatter_dimensions_proto(c.get_shape(scatter_indices),\n dimension_numbers)\n\n def _make_reducer(dtype):\n subc = xla_bridge.make_computation_builder(\"scatter_add_reducer\")\n shape = xc.Shape.array_shape(np.dtype(dtype), ())\n args = [xb.parameter(subc, 0, shape), xb.parameter(subc, 1, shape)]\n out = xops.Add(args[0], args[1])\n return subc.build(out)\n\n if expand_complex128 and dtype == np.complex128:\n update_computation = _make_reducer(np.float64)\n re = xops.Scatter(xops.Real(operand), scatter_indices, xops.Real(updates),\n update_computation, scatter_dims, indices_are_sorted,\n unique_indices)\n im = xops.Scatter(xops.Imag(operand), scatter_indices, xops.Imag(updates),\n update_computation, scatter_dims, indices_are_sorted,\n unique_indices)\n return xops.Complex(re, im)\n else:\n update_computation = _make_reducer(dtype)\n return xops.Scatter(operand, scatter_indices, updates, update_computation,\n scatter_dims, indices_are_sorted, unique_indices)\n\ndef _scatter_add_jvp(primals, tangents, *, update_jaxpr, update_consts,\n dimension_numbers, indices_are_sorted, unique_indices):\n operand, scatter_indices, updates = primals\n g_operand, g_scatter_indices, g_updates = tangents\n val_out = scatter_add_p.bind(\n operand, scatter_indices, updates, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n if type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\n tangent_out = ad_util.Zero.from_value(val_out)\n else:\n g_operand = ad.instantiate_zeros(g_operand)\n g_updates = ad.instantiate_zeros(g_updates)\n tangent_out = scatter_add_p.bind(\n g_operand, scatter_indices, g_updates, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n return val_out, tangent_out\n\ndef _scatter_add_transpose_rule(t, operand, scatter_indices, updates, *,\n update_jaxpr, update_consts, dimension_numbers,\n indices_are_sorted, unique_indices):\n assert not ad.is_undefined_primal(scatter_indices)\n if ad.is_undefined_primal(updates):\n updates_shape = updates.aval.shape\n else:\n updates_shape = updates.shape\n if type(t) is ad_util.Zero:\n return ad_util.Zero\n\n operand_t = update_t = None\n if ad.is_undefined_primal(operand):\n operand_t = t\n\n if ad.is_undefined_primal(updates):\n gather_dnums = GatherDimensionNumbers(\n offset_dims=dimension_numbers.update_window_dims,\n collapsed_slice_dims=dimension_numbers.inserted_window_dims,\n start_index_map=dimension_numbers.scatter_dims_to_operand_dims)\n slice_sizes = []\n pos = 0\n for i in range(len(t.shape)):\n if i in dimension_numbers.inserted_window_dims:\n slice_sizes.append(1)\n else:\n slice_sizes.append(updates_shape[dimension_numbers.update_window_dims[pos]])\n pos += 1\n update_t = gather(t, scatter_indices, dimension_numbers=gather_dnums,\n slice_sizes=slice_sizes)\n return [operand_t, None, update_t]\n\ndef _scatter_mul_transpose_rule(t, operand, scatter_indices, updates, *,\n update_jaxpr, update_consts, dimension_numbers,\n indices_are_sorted, unique_indices):\n assert not ad.is_undefined_primal(scatter_indices)\n if ad.is_undefined_primal(updates):\n updates_shape = updates.aval.shape\n else:\n updates_shape = updates.shape\n if type(t) is ad_util.Zero:\n return ad_util.Zero\n\n operand_t = update_t = None\n if ad.is_undefined_primal(operand):\n operand_t = scatter_mul(\n t, scatter_indices, updates, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n\n if ad.is_undefined_primal(updates):\n gather_dnums = GatherDimensionNumbers(\n offset_dims=dimension_numbers.update_window_dims,\n collapsed_slice_dims=dimension_numbers.inserted_window_dims,\n start_index_map=dimension_numbers.scatter_dims_to_operand_dims)\n slice_sizes = []\n pos = 0\n for i in range(len(t.shape)):\n if i in dimension_numbers.inserted_window_dims:\n slice_sizes.append(1)\n else:\n slice_sizes.append(updates_shape[dimension_numbers.update_window_dims[pos]])\n pos += 1\n update_t = gather(mul(t, operand), scatter_indices,\n dimension_numbers=gather_dnums, slice_sizes=slice_sizes)\n return [operand_t, None, update_t]\n\n\ndef _scatter_batching_rule(scatter_op, batched_args, batch_dims, *,\n update_jaxpr, update_consts, dimension_numbers,\n indices_are_sorted, unique_indices):\n operand, scatter_indices, updates = batched_args\n operand_bdim, scatter_indices_bdim, updates_bdim = batch_dims\n del update_jaxpr, update_consts # Unused.\n\n # move the operand batch dim to the front if it is not None, otherwise create\n # it at the front (so that we can scatter into it)\n size = next(x.shape[ax] for x, ax in zip(batched_args, batch_dims)\n if ax is not None)\n operand = batching.bdim_at_front(operand, operand_bdim, size)\n operand_bdim = 0\n\n updates = batching.bdim_at_front(updates, updates_bdim, size)\n\n if scatter_indices_bdim is None:\n inserted_window_dims = tuple(np.add(1, dimension_numbers.inserted_window_dims))\n update_window_dims = (0,) + tuple(np.add(1, dimension_numbers.update_window_dims))\n scatter_dims_to_operand_dims = tuple(np.add(1, dimension_numbers.scatter_dims_to_operand_dims))\n dnums = ScatterDimensionNumbers(\n update_window_dims=update_window_dims,\n inserted_window_dims=inserted_window_dims,\n scatter_dims_to_operand_dims=scatter_dims_to_operand_dims)\n return scatter_op(\n operand, scatter_indices, updates, dnums,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices), 0\n\n\n # see the third case in _gather_batching_rule for comparison and comments\n scatter_indices = batching.bdim_at_front(\n scatter_indices, scatter_indices_bdim, size)\n\n count_shape = list(scatter_indices.shape)\n count_shape[-1] = 1\n counts = broadcasted_iota(scatter_indices.dtype, tuple(count_shape), 0)\n scatter_indices = concatenate([counts, scatter_indices],\n len(count_shape) - 1)\n\n update_window_dims = tuple(np.add(1, dimension_numbers.update_window_dims))\n inserted_window_dims = (0,) + tuple(np.add(1, dimension_numbers.inserted_window_dims))\n scatter_dims_to_operand_dims = (0,) + tuple(np.add(1, dimension_numbers.scatter_dims_to_operand_dims))\n\n dnums = ScatterDimensionNumbers(\n update_window_dims=update_window_dims,\n inserted_window_dims=inserted_window_dims,\n scatter_dims_to_operand_dims=scatter_dims_to_operand_dims)\n return scatter_op(\n operand, scatter_indices, updates, dnums,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices), 0\n\nscatter_add_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-add',\n _scatter_add_translation_rule)\nad.primitive_jvps[scatter_add_p] = _scatter_add_jvp\nad.primitive_transposes[scatter_add_p] = _scatter_add_transpose_rule\nbatching.primitive_batchers[scatter_add_p] = (\n partial(_scatter_batching_rule, scatter_add))\n\nxla.backend_specific_translations['gpu'][scatter_add_p] = partial(\n _scatter_add_translation_rule, expand_complex128=True)\n\nscatter_mul_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-mul',\n _scatter_translation_rule)\n\ndef _scatter_mul_jvp_rhs(g, x, i, y, *, dimension_numbers,\n indices_are_sorted, unique_indices, **kw):\n return mul(x, scatter_add(\n zeros_like_array(x), i, g, dimension_numbers=dimension_numbers,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices))\n\nad.defjvp(scatter_mul_p,\n lambda g, x, i, y, **kw: scatter_mul_p.bind(g, i, y, **kw),\n None,\n _scatter_mul_jvp_rhs)\nad.primitive_transposes[scatter_mul_p] = _scatter_mul_transpose_rule\nbatching.primitive_batchers[scatter_mul_p] = (\n partial(_scatter_batching_rule, scatter_mul))\n\ndef _scatter_extremal_jvp(scatter_op, primals, tangents, update_jaxpr,\n update_consts, dimension_numbers,\n indices_are_sorted, unique_indices):\n operand, scatter_indices, updates = primals\n g_operand, g_scatter_indices, g_updates = tangents\n\n scatter_dnums = dimension_numbers\n updates_shape = updates.shape\n\n val_out = scatter_op.bind(\n operand, scatter_indices, updates, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=scatter_dnums,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\n if type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\n tangent_out = ad_util.Zero.from_value(val_out)\n else:\n g_operand = ad.instantiate_zeros(g_operand)\n g_updates = ad.instantiate_zeros(g_updates)\n\n # gather_dnums and slice_sizes define the gather op that is the inverse of\n # the scatter op specified by scatter_dnums\n gather_dnums = GatherDimensionNumbers(\n offset_dims=scatter_dnums.update_window_dims,\n collapsed_slice_dims=scatter_dnums.inserted_window_dims,\n start_index_map=scatter_dnums.scatter_dims_to_operand_dims)\n\n slice_sizes = []\n pos = 0\n for i in range(len(operand.shape)):\n if i in scatter_dnums.inserted_window_dims:\n slice_sizes.append(1)\n else:\n slice_sizes.append(updates_shape[scatter_dnums.update_window_dims[pos]])\n pos += 1\n\n # For consistency with other max operations, if there are two or more values\n # in updates that are contending to replace the same index location, the\n # resulting tangent at that location will be the average of the associated\n # tangents for the values in updates.\n\n initial_vals = gather(\n operand, scatter_indices, gather_dnums, np.array(slice_sizes))\n\n target_vals = gather(\n val_out, scatter_indices, gather_dnums, np.array(slice_sizes))\n\n successful_updates = (updates == target_vals)\n retained_values = (initial_vals == target_vals)\n\n num_updates = gather(\n scatter_add(_zeros(operand),\n scatter_indices,\n select(successful_updates, _ones(updates), _zeros(updates)),\n scatter_dnums),\n scatter_indices,\n gather_dnums,\n np.array(slice_sizes))\n\n num_refs = gather(\n scatter_add(_zeros(operand),\n scatter_indices,\n _ones(updates),\n scatter_dnums),\n scatter_indices,\n gather_dnums,\n np.array(slice_sizes))\n\n updates_normalizer = select(retained_values,\n 1.0 / (num_updates + 1),\n 1.0 / num_updates)\n\n updates_coef = select(successful_updates,\n updates_normalizer,\n _zeros(updates))\n\n operand_normalizer = select(retained_values,\n 1.0 / (num_updates + 1),\n _zeros(num_updates))\n\n operand_coef = (-1.0 + operand_normalizer) / num_refs\n\n # This can be simplified once scatter has transpose implemented\n target_tangents = gather(\n g_operand, scatter_indices, gather_dnums, np.array(slice_sizes))\n\n tangent_updates = (target_tangents * operand_coef +\n g_updates * updates_coef)\n\n tangent_out = scatter_add(g_operand,\n scatter_indices,\n tangent_updates,\n scatter_dnums,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\n return val_out, tangent_out\n\nscatter_min_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-min',\n _scatter_translation_rule)\nbatching.primitive_batchers[scatter_min_p] = (\n partial(_scatter_batching_rule, scatter_min))\nad.primitive_jvps[scatter_min_p] = partial(_scatter_extremal_jvp, scatter_min_p)\n\nscatter_max_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-max',\n _scatter_translation_rule)\nbatching.primitive_batchers[scatter_max_p] = (\n partial(_scatter_batching_rule, scatter_max))\nad.primitive_jvps[scatter_max_p] = partial(_scatter_extremal_jvp, scatter_max_p)\n\ndef _scatter_jvp(primals, tangents, *, update_jaxpr, update_consts,\n dimension_numbers, indices_are_sorted, unique_indices):\n operand, scatter_indices, updates = primals\n g_operand, g_scatter_indices, g_updates = tangents\n dnums = dimension_numbers\n\n if type(g_operand) is ad_util.Zero and type(g_updates) is ad_util.Zero:\n val_out = scatter_p.bind(\n operand, scatter_indices, updates, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=dnums,\n indices_are_sorted=indices_are_sorted, unique_indices=unique_indices)\n return val_out, ad_util.Zero.from_value(val_out)\n\n g_operand = ad.instantiate_zeros(g_operand)\n g_updates = ad.instantiate_zeros(g_updates)\n\n # If there are overlapping indices in the scatter, it is unspecified which\n # update \"wins\". So we use the following perhaps surprising scheme:\n # a) attach a positive ID to each update in updates, and perform the scatter\n # on the IDs\n # b) perform the inverse gather on the scattered IDs (similar to\n # _scatter_add_transpose).\n # c) use the gathered IDs to mask the primal and tangent values.\n # d) perform a scatter-add on the masked primal and tangent values. A benefit\n # of using scatter-add here is that we don't need a `scatter` transpose\n # rule.\n\n\n # a) attach a positive ID to each update in `updates`, and perform a scatter\n # on the IDs.\n ids_shape = np.array(updates.shape, dtype=np.int64)\n ids_shape[dnums.update_window_dims,] = 1\n num_ids = np.prod(ids_shape)\n id_dtype = np.uint32 if (num_ids + 1) < np.iinfo(np.uint32).max else np.uint64\n update_ids = add(reshape(iota(id_dtype, num_ids), ids_shape),\n _ones(updates, dtype=id_dtype))\n\n scattered_ids = scatter(full(operand.shape, 0, id_dtype),\n scatter_indices, update_ids, dnums,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n\n # b) compute the inverse gather that \"undoes\" the scatter on the id values.\n gather_dnums = GatherDimensionNumbers(\n offset_dims=dnums.update_window_dims,\n collapsed_slice_dims=dnums.inserted_window_dims,\n start_index_map=dnums.scatter_dims_to_operand_dims)\n slice_sizes = []\n pos = 0\n for i in range(len(scattered_ids.shape)):\n if i in dnums.inserted_window_dims:\n slice_sizes.append(1)\n else:\n slice_sizes.append(updates.shape[dnums.update_window_dims[pos]])\n pos += 1\n gathered_update_ids = gather(scattered_ids, scatter_indices,\n dimension_numbers=gather_dnums,\n slice_sizes=slice_sizes)\n\n # c) mask off input elements that do not correspond to a primal output.\n masked_operand = select(eq(scattered_ids, _zeros(scattered_ids)),\n operand, _zeros(operand))\n masked_updates = select(eq(update_ids, gathered_update_ids),\n updates, _zeros(updates))\n masked_g_operand = select(eq(scattered_ids, _zeros(scattered_ids)),\n g_operand, _zeros(g_operand))\n masked_g_updates = select(eq(update_ids, gathered_update_ids),\n g_updates, _zeros(g_updates))\n\n # d) perform scatter-adds to compute the primal and tangent outputs.\n val_out = scatter_add(masked_operand, scatter_indices, masked_updates,\n dimension_numbers=dnums,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n tangent_out = scatter_add(masked_g_operand, scatter_indices, masked_g_updates,\n dimension_numbers=dnums,\n indices_are_sorted=indices_are_sorted,\n unique_indices=unique_indices)\n return val_out, tangent_out\n\n\nscatter_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter',\n _scatter_translation_rule)\nad.primitive_jvps[scatter_p] = _scatter_jvp\nbatching.primitive_batchers[scatter_p] = (\n partial(_scatter_batching_rule, scatter))\n\n\ndef _reduce_shape_rule(*args, computation, jaxpr, consts, dimensions):\n operand_args, init_value_args = split_list(args, [len(args) // 2])\n if any(arg.shape != () for arg in init_value_args):\n init_value_shapes = [a.shape for a in init_value_args]\n raise ValueError(f'Found non-scalar init_value: {init_value_shapes}')\n return [\n tuple(np.delete(op_arg.shape, dimensions))\n for op_arg in operand_args\n ]\n\n\ndef _reduce_dtype_rule(*args, computation, jaxpr, consts, dimensions):\n _, init_value_args = split_list(args, [len(args) // 2])\n return [\n dtypes.canonicalize_dtype(in_arg.dtype)\n for in_arg in init_value_args\n ]\n\n\ndef _reduce_translation_rule(c, *values, computation, jaxpr,\n consts, dimensions):\n operands, init_values = split_list(values, [len(values) // 2])\n if len(operands) == 1:\n init_value = init_values[0]\n xla_computation = _reduction_computation(c, jaxpr, consts, init_value)\n out = xops.Reduce(c, operands, init_values, xla_computation, dimensions)\n return xops.Tuple(c, (out,))\n xla_computation = _reduction_computation(c, jaxpr, consts, init_values, singleton=False)\n return xops.Reduce(c, operands, init_values, xla_computation, dimensions)\n\n\ndef _reduce_batch_rule(batched_args, batch_dims, *, computation, jaxpr,\n consts, dimensions):\n num_operands = len(batched_args) // 2\n operands, init_values = split_list(batched_args, [num_operands])\n operand_bdims, init_value_bdims = split_list(batch_dims, [num_operands])\n if all(init_value_bdim is None for init_value_bdim in init_value_bdims):\n # Assume all batch dims are the same for each of the operands\n assert all(operand_bdim is not None for operand_bdim in operand_bdims)\n assert all(operand_bdim == operand_bdims[0] for operand_bdim in operand_bdims)\n # TODO(sharadmv): handle the case when batch dims are different across\n # operands or when some are unbatched\n operand_bdim = operand_bdims[0]\n new_dimensions = [d + bool(d >= operand_bdim) for d in dimensions]\n new_operand_bdim = operand_bdim - int(np.sum(np.less(dimensions, operand_bdim)))\n new_operand_bdims = [new_operand_bdim] * num_operands\n return reduce_p.bind(*(operands + init_values),\n computation=computation, dimensions=tuple(new_dimensions),\n consts=consts,\n jaxpr=jaxpr), new_operand_bdims\n else:\n raise NotImplementedError # loop and stack\n\n\ndef _reduction_computation(c, jaxpr, consts, init_values, singleton=True):\n if singleton:\n init_values = [init_values]\n shapes = safe_map(c.get_shape, init_values + init_values)\n axis_env = xla.AxisEnv(1, (), ()) # no parallel primitives inside reductions\n subc = xla_bridge.make_computation_builder(\"reduction_computation\")\n assert len(consts) == 0, \"Reduction computations cannot have constants\"\n args = [xb.parameter(subc, i, shape) for i, shape in enumerate(shapes)]\n out_nodes = xla.jaxpr_subcomp(subc, jaxpr, None, axis_env, consts, '', *args)\n if singleton:\n return subc.build(out_nodes[0])\n out_nodes = xops.Tuple(subc, out_nodes)\n return subc.build(out_nodes)\n\ndef _masking_defreducer(prim, identity):\n masking.masking_rules[prim] = partial(_reducer_masking_rule, prim, identity)\n\ndef _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,\n axes, input_shape=None, **reduce_kwargs):\n (padded_val,), (logical_shape,) = padded_vals, logical_shapes\n padded_shape = masking.padded_shape_as_value(padded_val.shape)\n masks = [broadcasted_iota(np.int32, padded_shape, i) < d\n for i, d in enumerate(logical_shape) if i in axes]\n mask = _reduce(operator.and_, masks)\n masked_val = select(mask, padded_val, identity(padded_shape, padded_val.dtype))\n prim_bind = partial(prim.bind, **reduce_kwargs)\n bind = prim_bind if input_shape is None else partial(prim_bind, input_shape=padded_shape)\n return bind(masked_val, axes=axes)\n\nreduce_p = standard_primitive(_reduce_shape_rule, _reduce_dtype_rule,\n 'reduce', translation_rule=_reduce_translation_rule,\n multiple_results=True)\nbatching.primitive_batchers[reduce_p] = _reduce_batch_rule\n\n\ndef _reduce_number_dtype_rule(name, operand, *args, **kw):\n if not dtypes.issubdtype(operand.dtype, np.number):\n raise TypeError(\"{} does not accept dtype {}. Accepted dtypes are subtypes \"\n \"of number.\".format(name, np.dtype(operand.dtype).name))\n return dtypes.canonicalize_dtype(operand.dtype)\n\ndef _reduce_sum_shape_rule(operand, *, axes):\n return _reduce_op_shape_rule(operand, axes=axes)\n\ndef _reduce_sum_translation_rule(c, operand, *, axes):\n shape = c.get_shape(operand)\n dtype = shape.numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.Reduce(c, [operand], [xb.constant(c, np.array(0, dtype))],\n xla.primitive_subcomputation(add_p, scalar, scalar),\n axes)\n\ndef _reduce_sum_transpose_rule(cotangent, operand, *, axes):\n assert ad.is_undefined_primal(operand)\n input_shape = operand.aval.shape\n broadcast_dimensions = tuple(np.delete(np.arange(len(input_shape)), axes))\n result = broadcast_in_dim(cotangent, input_shape, broadcast_dimensions)\n assert result.shape == input_shape\n return [result]\n\nreduce_sum_p = standard_primitive(\n _reduce_sum_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_sum'),\n 'reduce_sum', _reduce_sum_translation_rule)\nad.deflinear2(reduce_sum_p, _reduce_sum_transpose_rule)\nbatching.defreducer(reduce_sum_p)\n_masking_defreducer(reduce_sum_p,\n lambda shape, dtype: np.broadcast_to(np.array(0, dtype), shape))\n\n\ndef _reduce_op_shape_rule(operand, *, axes, input_shape=None):\n del input_shape # Unused.\n if len(axes) != len(set(axes)):\n raise ValueError(f\"duplicate value in 'axes' of reduction: {axes}\")\n return tuple(np.delete(operand.shape, axes))\n\ndef _reduce_prod_translation_rule(c, operand, *, axes):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.Reduce(c, [operand], [xb.constant(c, np.array(1, dtype))],\n xla.primitive_subcomputation(mul_p, scalar, scalar), axes)\n\ndef _reduce_prod_jvp_rule(primals, tangents, *, axes):\n operand, = primals\n tangent, = tangents\n input_shape = np.array(operand.shape)\n\n n = np.prod(input_shape[list(axes)])\n non_axes = np.delete(np.arange(len(input_shape)), axes)\n\n # Move the reduced axes to the front, and flatten them to 1D.\n permutation = axes + tuple(non_axes)\n new_shape = (n,) + tuple(input_shape[non_axes])\n operand = reshape(operand, new_shape, permutation)\n tangent = reshape(tangent, new_shape, permutation)\n\n def _reduce_prod_tree(x, axis=0):\n \"\"\"Reduce by repeatedly splitting the array and multiplying.\"\"\"\n while x.shape[axis] > 1:\n n = x.shape[axis]\n n1 = (n + 1) // 2\n n2 = n - n1\n x1 = slice_in_dim(x, 0, n1)\n x2 = slice_in_dim(x, n1, None)\n if n2 != n1:\n paddings = [(0, 0, 0)] * len(x.shape)\n paddings[axis] = (0, 1, 0)\n x2 = pad(x2, _const(x, 1), paddings)\n x = x1 * x2\n if x.shape[axis] == 0:\n return full(input_shape[non_axes], _one(x))\n return squeeze(x, (axis,))\n\n return api.jvp(_reduce_prod_tree, (operand,), (tangent,))\n\n\nreduce_prod_p = standard_primitive(\n _reduce_op_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_prod'),\n 'reduce_prod', _reduce_prod_translation_rule)\nad.primitive_jvps[reduce_prod_p] = _reduce_prod_jvp_rule\nbatching.defreducer(reduce_prod_p)\n_masking_defreducer(reduce_prod_p,\n lambda shape, dtype: np.broadcast_to(np.array(1, dtype), shape))\n\n\ndef _reduce_chooser_shape_rule(operand, *, axes):\n return tuple(np.delete(operand.shape, axes))\n\ndef _reduce_chooser_translation_rule(prim, identity, c, operand, *, axes):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.Reduce(c, [operand], [xb.constant(c, identity(dtype))],\n xla.primitive_subcomputation(prim, scalar, scalar), axes)\n\ndef _reduce_chooser_jvp_rule(g, ans, operand, *, axes):\n # TODO(mattjj): an alternative is to use variadic reduce to compute the chosen\n # locations in a single pass (rather than comparing equality) and use a\n # gather, and/or even push along the chosen elements of g (b/112040122)\n shape = [1 if i in axes else d for i, d in enumerate(operand.shape)]\n location_indicators = convert_element_type(\n _eq_meet(operand, reshape(ans, shape)), g.dtype)\n counts = _reduce_sum(location_indicators, axes)\n return div(_reduce_sum(mul(g, location_indicators), axes), counts)\n\n_reduce_max_translation_rule = partial(_reduce_chooser_translation_rule, max_p,\n _get_max_identity)\nreduce_max_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n 'reduce_max', _reduce_max_translation_rule)\nad.defjvp2(reduce_max_p, _reduce_chooser_jvp_rule)\nbatching.defreducer(reduce_max_p)\n_masking_defreducer(reduce_max_p,\n lambda shape, dtype: np.broadcast_to(np.array(-np.inf, dtype), shape))\n\n\n_reduce_min_translation_rule = partial(\n _reduce_chooser_translation_rule, min_p, _get_min_identity)\nreduce_min_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n 'reduce_min', _reduce_min_translation_rule)\nad.defjvp2(reduce_min_p, _reduce_chooser_jvp_rule)\nbatching.defreducer(reduce_min_p)\n_masking_defreducer(reduce_min_p,\n lambda shape, dtype: np.broadcast_to(np.array(np.inf, dtype), shape))\n\n\n\ndef _argminmax_shape_rule(operand, *, axes, index_dtype):\n axis, = axes\n return tuple(np.delete(operand.shape, axis))\n\ndef _argminmax_dtype_rule(operand, *, axes, index_dtype):\n if not dtypes.issubdtype(index_dtype, np.integer):\n raise TypeError(\"index_dtype must be an integer type, but got {}\"\n .format(np.dtype(index_dtype).name))\n return index_dtype\n\ndef _argminmax_translation_rule(value_comparator, identity,\n c, operand, *, axes, index_dtype):\n axis, = axes\n shape = c.get_shape(operand)\n dtype = shape.numpy_dtype()\n\n subc = xb.make_computation_builder(\"argminmax_comparator\")\n value_shape = xc.Shape.array_shape(shape.xla_element_type(), ())\n index_shape = xc.Shape.array_shape(index_dtype, ())\n x_value = xb.parameter(subc, 0, value_shape)\n x_index = xb.parameter(subc, 1, index_shape)\n y_value = xb.parameter(subc, 2, value_shape)\n y_index = xb.parameter(subc, 3, index_shape)\n which_value = value_comparator(x_value, y_value)\n which_index = xops.Or(which_value, xops.And(xops.Eq(x_value, y_value),\n xops.Lt(x_index, y_index)))\n xops.Tuple(subc, [xops.Select(which_value, x_value, y_value),\n xops.Select(which_index, x_index, y_index)])\n comparator = subc.build()\n\n iota_shape = xc.Shape.array_shape(index_dtype, shape.dimensions())\n iota = xc.ops.Iota(c, iota_shape, axis)\n out = xops.Reduce(\n c, [operand, iota],\n [xb.constant(c, identity(dtype)),\n xb.constant(c, np.array(0, index_dtype))], comparator, [axis])\n return xops.GetTupleElement(out, 1)\n\ndef _argminmax_gpu_translation_rule(op, a, *, axes, index_dtype):\n axis, = axes\n idxs = tie_in(a, broadcasted_iota(index_dtype, a.shape, axis))\n maxval = np.array(dtypes.iinfo(index_dtype).max, dtype=index_dtype)\n maxval = broadcast(tie_in(a, maxval), a.shape)\n mask_idxs = select(eq(a, expand_dims(op(a, (axis,)), (axis,))), idxs,\n maxval)\n return _reduce_min(mask_idxs, (axis,))\n\n_argmin_translation_rule = partial(_argminmax_translation_rule, xops.Lt,\n _get_min_identity)\n_argmax_translation_rule = partial(_argminmax_translation_rule, xops.Gt,\n _get_max_identity)\n\nargmin_p = standard_primitive(_argminmax_shape_rule, _argminmax_dtype_rule,\n 'argmin', _argmin_translation_rule)\nbatching.defreducer(argmin_p)\nad.defjvp_zero(argmin_p)\nxla.backend_specific_translations['gpu'][argmin_p] = xla.lower_fun(\n partial(_argminmax_gpu_translation_rule, _reduce_min),\n multiple_results=False)\n\nargmax_p = standard_primitive(_argminmax_shape_rule, _argminmax_dtype_rule,\n 'argmax', _argmax_translation_rule)\nbatching.defreducer(argmax_p)\nad.defjvp_zero(argmax_p)\nxla.backend_specific_translations['gpu'][argmax_p] = xla.lower_fun(\n partial(_argminmax_gpu_translation_rule, _reduce_max),\n multiple_results=False)\n\n\ndef _reduce_logical_shape_rule(operand, *, axes):\n if operand.dtype != np.bool_:\n msg = \"logical reduction requires operand dtype bool, got {}.\"\n raise TypeError(msg.format(operand.dtype))\n return tuple(np.delete(operand.shape, axes))\n\ndef _reduce_logical_translation_rule(prim, identity, c, operand, *, axes):\n scalar = ShapedArray((), np.bool_)\n return xops.Reduce(c, [operand], [xb.constant(c, identity(np.bool_))],\n xla.primitive_subcomputation(prim, scalar, scalar), axes)\n\n_reduce_or_translation_rule = partial(_reduce_logical_translation_rule,\n or_p, _get_max_identity)\nreduce_or_p = standard_primitive(_reduce_logical_shape_rule, _fixed_dtype(np.bool_),\n 'reduce_or', _reduce_or_translation_rule)\nbatching.defreducer(reduce_or_p)\n\n\n_reduce_and_translation_rule = partial(_reduce_logical_translation_rule,\n and_p, _get_min_identity)\nreduce_and_p = standard_primitive(_reduce_logical_shape_rule, _fixed_dtype(np.bool_),\n 'reduce_and', _reduce_and_translation_rule)\nbatching.defreducer(reduce_and_p)\n\ndef _reduce_window_shape_rule(operand, init_value, *, jaxpr, consts,\n window_dimensions, window_strides, padding,\n base_dilation, window_dilation):\n if operand.dtype != init_value.dtype:\n msg = (\"reduce_window got inconsistent dtypes for operand and init_value: \"\n \" got operand dtype {} and init_value dtype {}.\")\n raise TypeError(msg.format(operand.dtype, init_value.dtype))\n if init_value.shape != ():\n msg = (\"reduce_window expected init_value to be a scalar but init_value \"\n \"has shape {}.\")\n raise TypeError(msg.format(init_value.shape))\n return _common_reduce_window_shape_rule(\n operand, window_dimensions, window_strides, padding, base_dilation,\n window_dilation)\n\ndef _reduce_window_translation_rule(c, operand, init_value, *, jaxpr, consts,\n window_dimensions, window_strides, padding,\n base_dilation, window_dilation):\n xla_computation = _reduction_computation(c, jaxpr, consts, init_value)\n return xops.ReduceWindowWithGeneralPadding(\n operand, init_value, xla_computation, window_dimensions,\n window_strides, base_dilation, window_dilation, padding)\n\ndef _generic_reduce_window_batch_rule(\n batched_args, batch_dims, *, jaxpr, consts, window_dimensions,\n window_strides, padding, base_dilation, window_dilation):\n operand, init = batched_args\n bdim, init_bdim = batch_dims\n if init_bdim is not None:\n raise NotImplementedError(\"reduce_window batching is not implemented for \"\n \"initial values\")\n\n def reduce_window(x, window_dimensions, window_strides, padding, base_dilation,\n window_dilation):\n return reduce_window_p.bind(\n x, init, jaxpr=jaxpr, consts=consts, window_dimensions=window_dimensions,\n window_strides=window_strides, padding=padding, base_dilation=base_dilation,\n window_dilation=window_dilation)\n return _reduce_window_batch_rule(\n reduce_window, (operand,), (bdim,), window_dimensions=window_dimensions,\n window_strides=window_strides, padding=padding, base_dilation=base_dilation,\n window_dilation=window_dilation)\n\n\nreduce_window_p = standard_primitive(\n _reduce_window_shape_rule, _input_dtype, 'reduce_window',\n _reduce_window_translation_rule)\nbatching.primitive_batchers[reduce_window_p] = _generic_reduce_window_batch_rule\n\n\ndef _reduce_window_sum_shape_rule(operand, *, window_dimensions, window_strides,\n padding, base_dilation, window_dilation):\n if not dtypes.issubdtype(operand.dtype, np.number):\n msg = \"operand to reduce_window_sum must have a number dtype, got {}\"\n raise TypeError(msg.format(np.dtype(operand.dtype).name))\n return _common_reduce_window_shape_rule(operand, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation)\n\ndef _reduce_window_sum_translation_rule(c, operand, *, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.ReduceWindowWithGeneralPadding(\n operand, xb.constant(c, np.array(0, dtype)),\n xla.primitive_subcomputation(add_p, scalar, scalar), window_dimensions,\n window_strides, base_dilation, window_dilation, padding)\n\ndef _reduce_window_sum_transpose_rule(cotangent, operand, *, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation):\n assert ad.is_undefined_primal(operand)\n input_shape = operand.aval.shape\n pads = _conv_general_vjp_lhs_padding(\n input_shape, window_dimensions, window_strides, cotangent.shape, padding,\n base_dilation, window_dilation)\n ones = [1] * len(input_shape)\n padding_config = [(lo, hi, stride - 1)\n for (lo, hi), stride in zip(pads, window_strides)]\n pad_cotangent = pad(cotangent, _zero(cotangent), padding_config)\n result = _reduce_window_sum(pad_cotangent, window_dimensions, base_dilation,\n [(0, 0)] * len(input_shape),\n base_dilation=ones,\n window_dilation=window_dilation)\n assert result.shape == input_shape, (result.shape, input_shape)\n return [result]\n\ndef _reduce_window_batch_rule(reduce_window, batched_args, bdims, *,\n window_dimensions, window_strides, padding,\n base_dilation, window_dilation):\n operand, = batched_args\n bdim, = bdims\n\n if bdim is not None:\n window_dimensions = \\\n window_dimensions[:bdim] + (1,) + window_dimensions[bdim:]\n window_strides = window_strides[:bdim] + (1,) + window_strides[bdim:]\n padding = padding[:bdim] + ((0, 0),) + padding[bdim:]\n base_dilation = base_dilation[:bdim] + (1,) + base_dilation[bdim:]\n window_dilation = window_dilation[:bdim] + (1,) + window_dilation[bdim:]\n\n operand = reduce_window(operand, window_dimensions, window_strides, padding,\n base_dilation, window_dilation)\n return operand, bdim\n\nreduce_window_sum_p = standard_primitive(\n _reduce_window_sum_shape_rule, _input_dtype, 'reduce_window_sum',\n _reduce_window_sum_translation_rule)\nad.deflinear2(reduce_window_sum_p, _reduce_window_sum_transpose_rule)\nbatching.primitive_batchers[reduce_window_sum_p] = partial(\n _reduce_window_batch_rule, _reduce_window_sum)\n\ndef _reduce_window_chooser_translation_rule(\n prim, identity, c, operand, *, window_dimensions, window_strides, padding,\n base_dilation, window_dilation):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.ReduceWindowWithGeneralPadding(\n operand, xb.constant(c, identity(dtype)),\n xla.primitive_subcomputation(prim, scalar, scalar), window_dimensions,\n window_strides, base_dilation, window_dilation, padding)\n\ndef _reduce_window_chooser_jvp_rule(prim, g, operand, *, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation):\n assert prim is max_p or prim is min_p\n select_prim = ge_p if prim is max_p else le_p\n return _select_and_gather_add(g, operand, select_prim, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation)\n\n\ndef _common_reduce_window_shape_rule(operand, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation):\n _check_shapelike(\"reduce_window\", \"window_dimensions\", window_dimensions,\n non_zero_shape=True)\n _check_shapelike(\"reduce_window\", \"window_strides\", window_strides,\n non_zero_shape=True)\n _check_shapelike(\"reduce_window\", \"base_dilation\", base_dilation)\n _check_shapelike(\"reduce_window\", \"window_dilation\", window_dilation)\n if operand.ndim != len(window_dimensions):\n msg = (\"reduce_window got the wrong number of window_dimensions for \"\n \"operand: got operand shape {} with window_dimensions {}.\")\n raise TypeError(msg.format(operand.shape, window_dimensions))\n if len(window_strides) != len(window_dimensions):\n msg = (\"reduce_window got inconsistent window_strides and \"\n \"window_dimensions: got window_strides {} and window_dimensions {}.\")\n raise TypeError(msg.format(window_strides, window_dimensions))\n if len(base_dilation) != len(window_dimensions):\n msg = (\"reduce_window got inconsistent base_dilation and \"\n \"window_dimensions: got base_dilation {} and window_dimensions {}.\")\n raise TypeError(msg.format(base_dilation, window_dimensions))\n if len(window_dilation) != len(window_dimensions):\n msg = (\"reduce_window got inconsistent window_dilation and \"\n \"window_dimensions: got window_dilation {} and window_dimensions \"\n \"{}.\")\n raise TypeError(msg.format(window_dilation, window_dimensions))\n\n return reduce_window_shape_tuple(operand.shape, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation)\n\ndef reduce_window_shape_tuple(operand_shape, window_dimensions, window_strides,\n padding, base_dilation=None,\n window_dilation=None):\n if base_dilation is not None:\n operand_shape = _dilate_shape(operand_shape, base_dilation)\n if window_dilation is not None:\n window_dimensions = _dilate_shape(window_dimensions, window_dilation)\n operand_padded = np.add(operand_shape, np.add(*zip(*padding)))\n t = np.floor_divide(\n np.subtract(operand_padded, window_dimensions), window_strides) + 1\n return tuple(t)\n\n_reduce_window_max_translation_rule = partial(\n _reduce_window_chooser_translation_rule, max_p, _get_max_identity)\nreduce_window_max_p = standard_primitive(\n _common_reduce_window_shape_rule, _input_dtype, 'reduce_window_max',\n _reduce_window_max_translation_rule)\nad.defjvp(reduce_window_max_p, partial(_reduce_window_chooser_jvp_rule, max_p))\nbatching.primitive_batchers[reduce_window_max_p] = partial(\n _reduce_window_batch_rule, _reduce_window_max)\n\n_reduce_window_min_translation_rule = partial(\n _reduce_window_chooser_translation_rule, min_p, _get_min_identity)\nreduce_window_min_p = standard_primitive(\n _common_reduce_window_shape_rule, _input_dtype, 'reduce_window_min',\n _reduce_window_min_translation_rule)\nad.defjvp(reduce_window_min_p, partial(_reduce_window_chooser_jvp_rule, min_p))\n\n_reduce_window_min_batch_rule = partial(_reduce_window_batch_rule,\n _reduce_window_min)\nbatching.primitive_batchers[reduce_window_min_p] = partial(\n _reduce_window_batch_rule, _reduce_window_min)\n\n\ndef _select_and_scatter_shape_rule(\n operand, source, init_value, *, select_jaxpr, select_consts, scatter_jaxpr,\n scatter_consts, window_dimensions, window_strides, padding):\n _check_shapelike(\"select_and_scatter\", \"window_dimensions\", window_dimensions)\n _check_shapelike(\"select_and_scatter\", \"window_strides\", window_strides)\n if len(window_dimensions) != len(window_strides):\n msg = (\"select_and_scatter got inconsistent window_strides and \"\n \"window_dimensions: got window_strides {} and window_dimensions {}.\")\n raise TypeError(msg.format(window_strides, window_dimensions))\n return operand.shape\n\ndef _select_and_scatter_translation(\n c, operand, source, init_value, *, select_jaxpr, select_consts, scatter_jaxpr,\n scatter_consts, window_dimensions, window_strides, padding):\n select = _reduction_computation(c, select_jaxpr, select_consts, init_value)\n scatter = _reduction_computation(c, scatter_jaxpr, scatter_consts, init_value)\n return xops.SelectAndScatterWithGeneralPadding(\n operand, select, window_dimensions, window_strides, padding, source,\n init_value, scatter)\n\nselect_and_scatter_p = standard_primitive(\n _select_and_scatter_shape_rule, _input_dtype, 'select_and_scatter',\n _select_and_scatter_translation)\n\n\ndef _select_and_scatter_add_shape_rule(\n source, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n return operand.shape\n\ndef _select_and_scatter_add_translation(\n c, source, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n select = xla.primitive_subcomputation(select_prim, scalar, scalar)\n scatter = xla.primitive_subcomputation(add_p, scalar, scalar)\n zero = xb.constant(c, np.array(0, dtype))\n return xops.SelectAndScatterWithGeneralPadding(\n operand, select, window_dimensions, window_strides, padding, source, zero,\n scatter)\n\ndef _select_and_scatter_add_jvp(\n primals, tangents, *, select_prim, window_dimensions, window_strides,\n padding):\n source, operand = primals\n g_source, g_operand = tangents\n val_out = _select_and_scatter_add(\n source, operand, select_prim, window_dimensions, window_strides,\n padding)\n del g_operand\n if type(g_source) is ad_util.Zero:\n tangent_out = ad_util.Zero.from_value(val_out)\n else:\n tangent_out = _select_and_scatter_add(\n g_source, operand, select_prim, window_dimensions,\n window_strides, padding)\n return val_out, tangent_out\n\ndef _select_and_scatter_add_transpose(\n t, source, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n assert ad.is_undefined_primal(source) and not ad.is_undefined_primal(operand)\n ones = (1,) * len(window_dimensions)\n source_t = _select_and_gather_add(t, operand, select_prim, window_dimensions,\n window_strides, padding, ones, ones)\n return [source_t, None]\n\ndef _select_and_scatter_add_batch_rule(\n batched_args, batch_dims, *, select_prim, window_dimensions, window_strides,\n padding):\n source, operand = batched_args\n s_bdim, o_bdim = batch_dims\n size = next(a.shape[bdim] for a, bdim in zip(batched_args, batch_dims)\n if bdim is not None)\n source = batching.bdim_at_front(source, s_bdim, size)\n operand = batching.bdim_at_front(operand, o_bdim, size)\n\n window_dimensions = (1,) + window_dimensions\n window_strides = (1,) + window_strides\n padding = ((0, 0),) + padding\n out = _select_and_scatter_add(source, operand, select_prim, window_dimensions,\n window_strides, padding)\n return out, 0\n\nselect_and_scatter_add_p = standard_primitive(\n _select_and_scatter_add_shape_rule, _input_dtype, 'select_and_scatter_add',\n _select_and_scatter_add_translation)\nad.primitive_transposes[select_and_scatter_add_p] = \\\n _select_and_scatter_add_transpose\nad.primitive_jvps[select_and_scatter_add_p] = _select_and_scatter_add_jvp\nbatching.primitive_batchers[select_and_scatter_add_p] = \\\n _select_and_scatter_add_batch_rule\n\ndef _select_and_gather_add_shape_rule(\n tangents, operand, *, select_prim, window_dimensions, window_strides,\n padding, base_dilation, window_dilation):\n if tangents.shape != operand.shape:\n msg = (\"select_and_gather_add tangents and operand shapes must match, \"\n \"got {} and {}.\")\n raise TypeError(msg.format(tangents.shape, operand.shape))\n return _common_reduce_window_shape_rule(\n operand, window_dimensions, window_strides, padding, base_dilation,\n window_dilation)\n\n\n_UINT_DTYPES = {\n 16: np.uint16,\n 32: np.uint32,\n 64: np.uint64,\n}\n\n_INT_DTYPES = {\n 16: np.int16,\n 32: np.int32,\n 64: np.int64,\n}\n\ndef _select_and_gather_add_translation(\n c, tangents, operand, *, select_prim, window_dimensions, window_strides,\n padding, base_dilation, window_dilation, max_bits=64):\n shape = c.get_shape(operand)\n dtype = shape.numpy_dtype()\n etype = shape.xla_element_type()\n nbits = dtypes.finfo(dtype).bits\n\n assert nbits <= max_bits\n double_word_reduction = nbits * 2 <= max_bits\n\n const = lambda c, dtype, x: xb.constant(c, np.array(x, dtype=dtype),\n canonicalize_types=False)\n\n if double_word_reduction:\n # TODO(b/73062247): XLA doesn't yet implement ReduceWindow on tuples, so\n # we implement a pair-wise ReduceWindow by packing two k-bit values into\n # 2k-bit unsigned integer using bit tricks.\n word_dtype = _UINT_DTYPES[nbits]\n double_word_dtype = _UINT_DTYPES[nbits * 2]\n word_type = xla_client.dtype_to_etype(word_dtype)\n double_word_type = xla_client.dtype_to_etype(double_word_dtype)\n\n # Packs two values into a tuple.\n def pack(a, b):\n a = xops.BitcastConvertType(a, word_type)\n b = xops.BitcastConvertType(b, word_type)\n a = xops.ConvertElementType(a, double_word_type)\n b = xops.ConvertElementType(b, double_word_type)\n a = xops.ShiftLeft(a, const(c, double_word_dtype, nbits))\n return xops.Or(a, b)\n\n # Unpacks the first element of a tuple.\n def fst(c, t):\n st = xops.ShiftRightLogical(t, const(c, double_word_dtype, nbits))\n return xops.BitcastConvertType(xops.ConvertElementType(st, word_type), etype)\n\n # Unpacks the second element of a tuple.\n def snd(t):\n return xops.BitcastConvertType(xops.ConvertElementType(t, word_type), etype)\n\n else:\n # The double-word trick above only works if we have a sufficiently large\n # type. As an alternative, we can pack two half words into a single word,\n # at the cost of precision.\n # TODO(b/73062247): add support for tuple reductions and remove this case.\n warnings.warn(\"Using reduced precision for gradient of reduce-window \"\n \"min/max operator to work around missing XLA support for \"\n \"pair-reductions. This is likely from a second or \"\n \"higher derivative of a max-pooling operation.\")\n r_nbits = nbits // 2\n # Drop/round the bottom mantissa bits.\n nexp = dtypes.finfo(dtype).nexp\n nmant = r_nbits - nexp - 1\n\n double_word_dtype = word_dtype = _UINT_DTYPES[nbits]\n word_type = xla_client.dtype_to_etype(word_dtype)\n\n # Packs two values into a tuple.\n def pack(a, b):\n a = xops.ReducePrecision(a, exponent_bits=nexp, mantissa_bits=nmant)\n b = xops.ReducePrecision(b, exponent_bits=nexp, mantissa_bits=nmant)\n a = xops.BitcastConvertType(a, word_type)\n b = xops.BitcastConvertType(b, word_type)\n b = xops.ShiftRightLogical(b, const(c, word_dtype, r_nbits))\n return xops.Or(a, b)\n\n # Unpacks the first element of a tuple.\n def fst(c, t):\n st = xops.And(t, const(c, word_dtype, ((1 << r_nbits) - 1) << r_nbits))\n return xops.BitcastConvertType(st, etype)\n\n # Unpacks the second element of a tuple.\n def snd(t):\n return xops.BitcastConvertType(xops.ShiftLeft(t, const(c, word_dtype, r_nbits)),\n etype)\n\n def reducer():\n c = xla_bridge.make_computation_builder(\"select_and_gather_pair_reducer\")\n x = xb.parameter(c, 0,\n xla_client.Shape.array_shape(np.dtype(double_word_dtype), ()))\n y = xb.parameter(c, 1,\n xla_client.Shape.array_shape(np.dtype(double_word_dtype), ()))\n assert select_prim is ge_p or select_prim is le_p\n which = xops.Ge if select_prim is ge_p else xops.Le\n xops.Select(which(fst(c, x), fst(c, y)), x, y)\n return c.build()\n\n\n assert select_prim is ge_p or select_prim is le_p, select_prim\n init = -np.inf if select_prim is ge_p else np.inf\n out = xops.ReduceWindowWithGeneralPadding(\n pack(operand, tangents), pack(const(c, dtype, init), const(c, dtype, 0)),\n reducer(), window_dimensions, window_strides, base_dilation,\n window_dilation, padding)\n return snd(out)\n\ndef _select_and_gather_add_jvp(\n primals, tangents, *, select_prim, window_dimensions, window_strides,\n padding, base_dilation, window_dilation):\n source, operand = primals\n g_source, g_operand = tangents\n val_out = _select_and_gather_add(\n source, operand, select_prim, window_dimensions, window_strides,\n padding, base_dilation, window_dilation)\n del g_operand\n if type(g_source) is ad_util.Zero:\n tangent_out = ad_util.Zero.from_value(val_out)\n else:\n tangent_out = _select_and_gather_add(\n g_source, operand, select_prim, window_dimensions,\n window_strides, padding, base_dilation, window_dilation)\n return val_out, tangent_out\n\ndef _select_and_gather_add_transpose(\n t, tangents, operand, *, select_prim, window_dimensions, window_strides,\n padding, base_dilation, window_dilation):\n assert select_prim in (le_p, ge_p)\n assert ad.is_undefined_primal(tangents) and not ad.is_undefined_primal(operand)\n if any(d != 1 for d in window_dilation):\n msg = (\"VJP not implemented for select_and_gather (MaxPool) with window \"\n \"dilation, got window_dilation={}.\")\n raise NotImplementedError(msg.format(window_dilation))\n if type(t) is ad_util.Zero:\n return [ad_util.Zero, None]\n has_base_dilation = any(d != 1 for d in base_dilation)\n if has_base_dilation:\n select_identity = (_get_max_identity if select_prim is ge_p\n else _get_min_identity)\n operand = pad(operand, select_identity(operand.dtype),\n tuple((0, 0, d - 1) for d in base_dilation))\n result = _select_and_scatter_add(t, operand, select_prim, window_dimensions,\n window_strides, padding)\n if has_base_dilation:\n result = slice(operand, (0,) * len(operand.shape), operand.shape,\n base_dilation)\n return [result, None]\n\ndef _select_and_gather_add_batching_rule(\n batched_args, batch_dims, *, select_prim, window_dimensions, window_strides,\n padding, base_dilation, window_dilation):\n t, x = batched_args\n t_bdim, x_bdim = batch_dims\n size = next(a.shape[bdim] for a, bdim in zip(batched_args, batch_dims)\n if bdim is not None)\n t = batching.bdim_at_front(t, t_bdim, size)\n x = batching.bdim_at_front(x, x_bdim, size)\n window_dimensions = (1,) + window_dimensions\n window_strides = (1,) + window_strides\n padding = ((0, 0),) + padding\n base_dilation = (1,) + base_dilation\n window_dilation = (1,) + window_dilation\n out = _select_and_gather_add(t, x, select_prim, window_dimensions,\n window_strides, padding, base_dilation,\n window_dilation)\n return (out, 0)\n\n\nselect_and_gather_add_p = standard_primitive(\n _select_and_gather_add_shape_rule, _input_dtype, 'select_and_gather_add',\n _select_and_gather_add_translation)\nad.primitive_jvps[select_and_gather_add_p] = _select_and_gather_add_jvp\nad.primitive_transposes[select_and_gather_add_p] = \\\n _select_and_gather_add_transpose\nbatching.primitive_batchers[select_and_gather_add_p] = \\\n _select_and_gather_add_batching_rule\nxla.backend_specific_translations['tpu'][select_and_gather_add_p] = partial(\n _select_and_gather_add_translation,\n max_bits=32)\n\ndef _sort_abstract_eval(*args, **kwargs):\n args = tuple(raise_to_shaped(arg) for arg in args)\n if any(arg.shape != args[0].shape for arg in args[1:]):\n shapes = \" \".join(str(a.shape) for a in args)\n raise TypeError(f\"Arguments to sort must have equal shapes, got: {shapes}\")\n return args\n\n\ndef _float_to_int_for_sort(x):\n # Switch from a floating point value to a integer value in such a way that\n # when using the integer value to compare, we get the same result for normal\n # values, and -nan is treated as the smallest value, and nan is treated as\n # the largest value.\n # If f is a float, and\n # x = bit_cast<int32>(f);\n # y = x < 0 ? int32_max - x : x;\n # then y is ordered as an int32 such that finite values have the obvious\n # order, -0 is ordered before 0, and -NaN and NaN appear at the beginning\n # and end of the ordering.\n # Note that in order to avoid -x to overflow, we calculate\n # int32_max - x as unsigned, and then convert back to signed.\n if x.dtype == dtypes.bfloat16:\n x = convert_element_type(x, np.float32)\n nbits = np.finfo(x).bits\n signed_dtype = _INT_DTYPES[nbits]\n unsigned_dtype = _UINT_DTYPES[nbits]\n\n signed = bitcast_convert_type(x, signed_dtype)\n unsigned = bitcast_convert_type(x, unsigned_dtype)\n flipped = bitcast_convert_type(\n sub(unsigned_dtype(np.iinfo(signed_dtype).max), unsigned), signed_dtype)\n return select(lt(signed, _zero(signed)), flipped, signed)\n\n# Default comparator that sorts the operands lexicographically on the\n# first `num_keys` arguments.\n# For floating point types, a total order is created where\n# -NaN < -infinity < ... < -0 < 0 < ... < infinity < NaN.\n# For complex types, the (real, imag) pairs are sorted lexicographically\n# (following NumPy's semantics).\n# This code adds complex-number support and lexicographic ordering to the algorithm from:\n# https://github.com/tensorflow/tensorflow/blob/ba43780830f09da72081fe5061c436f1c6203a92/tensorflow/compiler/xla/client/lib/comparators.h#L33\ndef _sort_lt_comparator(*operands, num_keys=1):\n assert len(operands) >= 2 and len(operands) % 2 == 0, operands\n assert len(operands) // 2 >= num_keys, (operands, num_keys)\n x_keys, y_keys = [], []\n for x, y in zip(operands[:2*num_keys:2], operands[1:2*num_keys:2]):\n assert x.dtype == y.dtype, (x.dtype, y.dtype)\n if np.issubdtype(x.dtype, np.complexfloating):\n x_keys.extend([_float_to_int_for_sort(real(x)), _float_to_int_for_sort(imag(x))])\n y_keys.extend([_float_to_int_for_sort(real(y)), _float_to_int_for_sort(imag(y))])\n elif np.issubdtype(x.dtype, np.floating):\n x_keys.append(_float_to_int_for_sort(x))\n y_keys.append(_float_to_int_for_sort(y))\n else:\n x_keys.append(x)\n y_keys.append(y)\n\n p = None\n for xk, yk in zip(x_keys[::-1], y_keys[::-1]):\n p = (bitwise_or(lt(xk, yk), bitwise_and(eq(xk, yk), p)) if p is not None\n else lt(xk, yk))\n return p\n\n\ndef _sort_translation_rule(c, *operands, dimension, is_stable, num_keys):\n types = [c.get_shape(x).xla_element_type() for x in operands]\n subc = xla_bridge.make_computation_builder(\"sort_lt_comparator\")\n params = [xb.parameter(subc, 2 * i + j, xc.Shape.array_shape(typ, ()))\n for i, typ in enumerate(types) for j in range(2)]\n result = xla.lower_fun(partial(_sort_lt_comparator, num_keys=num_keys),\n multiple_results=False)(subc, *params)\n comparator = subc.build(result)\n out = xops.Sort(c, operands, dimension=dimension, is_stable=is_stable,\n comparator=comparator)\n return out if len(operands) != 1 else xops.Tuple(c, [out])\n\ndef _sort_jvp(primals, tangents, *, dimension, is_stable, num_keys):\n shape = primals[0].shape\n iotas = []\n for dim, size in enumerate(shape):\n dtype = np.int32 if size < np.iinfo(np.int32).max else np.int64\n iotas.append(broadcasted_iota(dtype, shape, dim))\n primals = sort_p.bind(*(primals + (iotas[dimension],)), dimension=dimension,\n is_stable=is_stable, num_keys=num_keys)\n idx = tuple(primals[-1] if i == dimension else iotas[i]\n for i in range(len(shape)))\n tangents_out = tuple(t if type(t) is ad_util.Zero else t[idx] for t in tangents)\n return tuple(primals[:-1]), tangents_out\n\ndef _sort_batch_rule(batched_args, batch_dims, *, dimension, is_stable, num_keys):\n prototype_arg, new_bdim = next(\n (a, b) for a, b in zip(batched_args, batch_dims) if b is not None)\n new_args = []\n for arg, bdim in zip(batched_args, batch_dims):\n if bdim is None:\n dims = np.delete(np.arange(prototype_arg.ndim), new_bdim)\n new_args.append(broadcast_in_dim(arg, prototype_arg.shape, dims))\n else:\n new_args.append(batching.moveaxis(arg, bdim, new_bdim))\n new_dimension = dimension + (new_bdim <= dimension)\n bdims = (new_bdim,) * len(new_args)\n return (sort_p.bind(*new_args, dimension=new_dimension, is_stable=is_stable, num_keys=num_keys),\n bdims)\n\n\nsort_p = Primitive('sort')\nsort_p.multiple_results = True\nsort_p.def_impl(partial(xla.apply_primitive, sort_p))\nsort_p.def_abstract_eval(_sort_abstract_eval)\nxla.translations[sort_p] = _sort_translation_rule\nad.primitive_jvps[sort_p] = _sort_jvp\nbatching.primitive_batchers[sort_p] = _sort_batch_rule\n\n\ndef _top_k_abstract_eval(operand, *, k):\n if k < 0:\n raise ValueError(\"k argument to top_k must be nonnegative, got {}\".format(k))\n if len(operand.shape) == 0:\n raise TypeError(\"top_k operand must have >= 1 dimension, got {}\"\n .format(operand.shape))\n shape = list(operand.shape)\n if shape[-1] < k:\n msg = \"k argument to top_k must be no larger than minor dimension; {} vs {}\"\n raise ValueError(msg.format(k, shape))\n shape[-1] = k\n return (ShapedArray(shape, operand.dtype),\n ShapedArray(shape, np.dtype(np.int32)))\n\ndef _top_k_jvp(primals, tangents, *, k):\n operand, = primals\n tangent, = tangents\n primals_out = top_k(operand, k)\n if type(tangent) is ad_util.Zero:\n tangent_out = ad_util.Zero.from_value(primals_out[0])\n else:\n _, k_idxs = primals_out\n idx_shape = k_idxs.shape\n rank = len(idx_shape)\n gather_index_shape = idx_shape + (1,)\n gather_indices = []\n for i in range(rank-1):\n _iota = iota(k_idxs.dtype, idx_shape[i])\n if not config.omnistaging_enabled:\n _iota = tie_in(operand, _iota)\n _iota = broadcast_in_dim(_iota, gather_index_shape, (i,))\n gather_indices.append(_iota)\n gather_indices.append(reshape(k_idxs, gather_index_shape))\n gather_indices = concatenate(gather_indices, dimension=rank)\n slice_sizes = (1,) * rank\n dnums = GatherDimensionNumbers(\n offset_dims=(),\n collapsed_slice_dims=tuple(range(rank)),\n start_index_map=tuple(range(rank)))\n tangent_out = gather(tangent, gather_indices, dnums, slice_sizes)\n return primals_out, (tangent_out, ad_util.Zero.from_value(primals_out[1]))\n\ndef _top_k_batch_rule(batched_args, batch_dims, *, k):\n operand, = batched_args\n bdim, = batch_dims\n if bdim == operand.ndim-1:\n perm = np.arange(operand.ndim)\n perm[bdim-1], perm[bdim] = perm[bdim], perm[bdim-1]\n top_k_v, top_k_i = top_k(transpose(operand, perm), k=k)\n return (transpose(top_k_v, perm),\n transpose(top_k_i, perm)), (bdim, bdim)\n else:\n return top_k(operand, k=k), (bdim, bdim)\n\ntop_k_p = Primitive('top_k')\ntop_k_p.multiple_results = True\ntop_k_p.def_impl(partial(xla.apply_primitive, top_k_p))\ntop_k_p.def_abstract_eval(_top_k_abstract_eval)\nxla.translations[top_k_p] = partial(standard_translate, 'top_k')\nad.primitive_jvps[top_k_p] = _top_k_jvp\nbatching.primitive_batchers[top_k_p] = _top_k_batch_rule\n\ndef _stop_gradient_jvp_rule(primals, tangents):\n # if we don't call stop_gradient here, we'd only peel off one autodiff tracer\n x, = primals\n return stop_gradient(x), ad_util.Zero.from_value(x)\n\ndef _stop_gradient_batch_rule(batched_args, batch_dims):\n x, = batched_args\n dim, = batch_dims\n return stop_gradient(x), dim\n\nad.primitive_jvps[ad_util.stop_gradient_p] = _stop_gradient_jvp_rule\nbatching.primitive_batchers[ad_util.stop_gradient_p] = _stop_gradient_batch_rule\n\n\ndef create_token(x):\n \"\"\"Creates an XLA token value with no preconditions for sequencing effects.\n\n Experimental.\n\n Args:\n x: a dummy argument used to tie the CreateToken operator into a trace. The\n value of `x` is ignored.\n \"\"\"\n # x is a dummy argument used to tie the operator into a trace.\n return create_token_p.bind(stop_gradient(x))\n\ncreate_token_p = Primitive(\"create_token\")\ncreate_token_p.def_impl(partial(xla.apply_primitive, create_token_p))\ncreate_token_p.def_abstract_eval(lambda _: abstract_token)\nxla.translations[create_token_p] = lambda c, *_: xops.CreateToken(c)\n\ndef after_all(*operands):\n \"\"\"Merges one or more XLA token values. Experimental.\n\n Wraps the XLA AfterAll operator.\"\"\"\n return after_all_p.bind(*operands)\n\ndef _after_all_abstract_eval(*operands):\n if any(x is not abstract_token for x in operands):\n raise TypeError(\"Arguments to after_all must be tokens\")\n return abstract_token\n\n\ndef _after_all_translation_rule(c, *operands):\n return xops.AfterAll(c, operands)\n\nafter_all_p = Primitive(\"after_all\")\nafter_all_p.def_impl(partial(xla.apply_primitive, after_all_p))\nafter_all_p.def_abstract_eval(_after_all_abstract_eval)\nxla.translations[after_all_p] = _after_all_translation_rule\n\n\ndef infeed(token, shape=None, partitions=None):\n \"\"\"Consumes an infeed value of `shape` from the host. Experimental.\n\n `token` is used to sequence infeed and outfeed effects.\n `partitions` may be specifed inside a `sharded_jit` function.\n \"\"\"\n flat_shapes, treedef = pytree.flatten(shape)\n for shape in flat_shapes:\n if not isinstance(shape, ShapedArray):\n raise TypeError(\"shape argument to infeed must be a pytree of \"\n \"ShapedArray values, got {}\".format(shape))\n if partitions is not None:\n # Always replicate token.\n # We specifically use type() to raise an error for PartitionSpecs.\n if type(partitions) != tuple: # pylint: disable=unidiomatic-typecheck\n raise ValueError(f\"'partitions' argument to infeed should be a tuple, \"\n f\"got {partitions}\")\n partitions = partitions + (None,)\n xs_and_token = infeed_p.bind(token, shapes=tuple(flat_shapes),\n partitions=partitions)\n return (treedef.unflatten(xs_and_token[:-1]), xs_and_token[-1])\n\ndef _infeed_abstract_eval(token, *, shapes, partitions):\n if token is not abstract_token:\n raise TypeError(\"First argument to infeed must be a token\")\n return shapes + (abstract_token,)\n\n\ndef _infeed_translation_rule(c, token, *, shapes, partitions):\n shape = tuple(shape.with_major_to_minor_layout_if_absent()\n for x in shapes for shape in xla.aval_to_xla_shapes(x))\n build_infeed = partial(xops.InfeedWithToken, token,\n xla_client.Shape.tuple_shape(shape))\n if partitions:\n xs_and_token = xb.with_sharding(c, partitions, build_infeed)\n else:\n # Note that infeed will default to replication if inside a sharded\n # computation and no sharding is specified.\n xs_and_token = build_infeed()\n xs = xops.GetTupleElement(xs_and_token, 0)\n token = xops.GetTupleElement(xs_and_token, 1)\n outs = [xops.GetTupleElement(xs, i) for i in range(len(shapes))] + [token]\n return xops.Tuple(c, outs)\n\ninfeed_p = Primitive(\"infeed\")\ninfeed_p.multiple_results = True\ninfeed_p.def_impl(partial(xla.apply_primitive, infeed_p))\ninfeed_p.def_abstract_eval(_infeed_abstract_eval)\nxla.translations[infeed_p] = _infeed_translation_rule\n\ndef outfeed(token, xs):\n \"\"\"Outfeeds value `xs` to the host. Experimental.\n\n `token` is used to sequence infeed and outfeed effects.\n \"\"\"\n flat_xs, _ = pytree.flatten(xs)\n return outfeed_p.bind(token, *flat_xs)\n\ndef _outfeed_abstract_eval(token, *xs):\n if token is not abstract_token:\n raise TypeError(\"First argument to outfeed must be a token\")\n return abstract_token\n\n\ndef _outfeed_translation_rule(c, token, *xs):\n t = xops.Tuple(c, xs)\n return xops.OutfeedWithToken(t, token, c.get_shape(t))\n\noutfeed_p = Primitive(\"outfeed\")\noutfeed_p.def_impl(partial(xla.apply_primitive, outfeed_p))\noutfeed_p.def_abstract_eval(_outfeed_abstract_eval)\nxla.translations[outfeed_p] = _outfeed_translation_rule\n\ndef rng_uniform(a, b, shape):\n \"\"\"Stateful PRNG generator. Experimental and its use is discouraged.\n\n Returns uniformly distributed random numbers in the range [a, b)\n\n You should use jax.random for most purposes; this function exists only for\n niche use cases with special performance requirements.\n\n This API may be removed at any time.\n \"\"\"\n return rng_uniform_p.bind(a, b, shape=tuple(shape))\n\ndef _rng_uniform_abstract_eval(a, b, *, shape):\n if a.dtype != b.dtype:\n raise ValueError(\n \"Arguments to rng_uniform must have identical dtypes, got {} \"\n \"and {}.\".format(a.dtype, b.dtype))\n if a.shape != () or b.shape != ():\n raise ValueError(\n \"Arguments to rng_uniform must be scalars; got shapes {} and {}.\"\n .format(a.shape, b.shape))\n return ShapedArray(shape, a.dtype)\n\ndef _rng_uniform_translation_rule(c, a, b, *, shape):\n xla_shape = xc.Shape.array_shape(c.get_shape(a).xla_element_type(), shape)\n return xops.RngUniform(a, b, xla_shape)\n\nrng_uniform_p = Primitive(\"rng_uniform\")\nrng_uniform_p.def_impl(partial(xla.apply_primitive, rng_uniform_p))\nrng_uniform_p.def_abstract_eval(_rng_uniform_abstract_eval)\nxla.translations[rng_uniform_p] = _rng_uniform_translation_rule\n\n\ndef _iota_abstract_eval(*, dtype, shape, dimension):\n _check_shapelike(\"iota\", \"shape\", shape)\n if not any(dtypes.issubdtype(dtype, t) for t in _num):\n msg = 'iota does not accept dtype {}. Accepted dtypes are subtypes of {}.'\n typename = str(np.dtype(dtype).name)\n accepted_typenames = (t.__name__ for t in _num)\n raise TypeError(msg.format(typename, ', '.join(accepted_typenames)))\n if not 0 <= dimension < len(shape):\n raise ValueError(\"iota dimension must be between 0 and len(shape), got \"\n f\"dimension={dimension} for shape {shape}\")\n return ShapedArray(shape, dtype)\n\ndef _iota_translation_rule(c, dtype, shape, dimension):\n etype = xla_client.dtype_to_etype(dtype)\n xla_shape = xc.Shape.array_shape(etype, shape)\n return xops.Iota(c, xla_shape, dimension)\n\niota_p = Primitive('iota')\niota_p.def_impl(partial(xla.apply_primitive, iota_p))\niota_p.def_abstract_eval(_iota_abstract_eval)\nxla.translations[iota_p] = _iota_translation_rule\n\n\n### util\n\n_ndim = np.ndim\n\n\ndef _dilate_shape(shape, dilation):\n \"\"\"Utility function for computing the shape resulting from a dilation.\"\"\"\n if not np.all(np.greater(dilation, 0)):\n msg = \"All dilations must be positive, got {}.\"\n raise TypeError(msg.format(dilation))\n dilation = (1,) * (len(shape) - len(dilation)) + tuple(dilation)\n return np.where(shape == 0, 0,\n np.multiply(dilation, np.subtract(shape, 1)) + 1)\n\ndef _ceil_divide(x1, x2):\n return -np.floor_divide(np.negative(x1), x2)\n\ndef padtype_to_pads(in_shape, window_shape, window_strides, padding):\n \"\"\"Convert padding string to list of pairs of pad values.\"\"\"\n PaddingType = xla_client.PaddingType\n\n if isinstance(padding, str):\n mapping = {'VALID': PaddingType.VALID, 'SAME': PaddingType.SAME}\n try:\n padding = mapping[padding.upper()]\n except KeyError as err:\n msg = \"Unrecognized padding type: expected 'VALID' or 'SAME', got {}.\"\n raise RuntimeError(msg.format(padding)) from err\n\n if padding == PaddingType.SAME:\n out_shape = _ceil_divide(in_shape, window_strides)\n pad_sizes = np.maximum(0, (out_shape - 1) * window_strides +\n window_shape - in_shape)\n return [(pad_size // 2, pad_size - pad_size // 2) for pad_size in pad_sizes]\n elif padding == PaddingType.VALID:\n return [(0, 0)] * len(in_shape)\n else:\n msg = \"Unknown padding type: {}.\"\n raise TypeError(msg.format(padding))\n\n\ndef _check_same_dtypes(name, ignore_fp_precision, *ttypes):\n \"\"\"Check that dtypes agree, possibly ignoring float precision.\"\"\"\n # the `ignore_fp_precision` flag exists because the XLA shape inference logic\n # allows mixed floating point precision, but the HLO verifier often rejects it\n types = list(map(np.dtype, ttypes)) # canonicalize\n if ignore_fp_precision:\n types = [\n np.floating if dtypes.issubdtype(dtype, np.floating)\n else np.complexfloating if dtypes.issubdtype(dtype, np.complexfloating)\n else dtype for dtype in types]\n if len({dtypes.canonicalize_dtype(t) for t in types}) != 1:\n if ignore_fp_precision:\n msg = (\"{} requires arguments to have same dtypes up to floating point \"\n \"precision, got {}.\")\n else:\n msg = \"{} requires arguments to have the same dtypes, got {}.\"\n raise TypeError(msg.format(name, \", \".join(map(str, types))))\n\n\ndef _check_conv_shapes(name, lhs_shape, rhs_shape, window_strides):\n \"\"\"Check that conv shapes are valid and are consistent with window_strides.\"\"\"\n if len(lhs_shape) != len(rhs_shape):\n msg = \"Arguments to {} must have same rank, got {} and {}.\"\n raise TypeError(msg.format(name, len(lhs_shape), len(rhs_shape)))\n if len(lhs_shape) < 2:\n msg = \"Arguments to {} must have rank at least 2, got {} and {}.\"\n raise TypeError(msg.format(name, len(lhs_shape), len(rhs_shape)))\n if lhs_shape[1] != rhs_shape[1]:\n msg = \"Arguments to {} must agree on input feature size, got {} and {}.\"\n raise TypeError(msg.format(name, lhs_shape[1], rhs_shape[1]))\n _check_shapelike(name, \"window_strides\", window_strides)\n if not np.all(np.greater(window_strides, 0)):\n msg = \"All elements of window_strides must be positive, got {}.\"\n raise TypeError(msg.format(window_strides))\n if len(window_strides) != len(lhs_shape) - 2:\n msg = \"{} window_strides has wrong length: expected {}, got {}.\"\n expected_length = len(lhs_shape) - 2\n raise TypeError(msg.format(name, expected_length, len(window_strides)))\n\n\ndef conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):\n \"\"\"Compute the shape tuple of a conv given input shapes in canonical order.\"\"\"\n if isinstance(pads, str):\n pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)\n if len(pads) != len(lhs_shape) - 2:\n msg = \"Wrong number of explicit pads for convolution: expected {}, got {}.\"\n raise TypeError(msg.format(len(lhs_shape) - 2, len(pads)))\n\n lhs_padded = np.add(lhs_shape[2:], np.sum(np.array(pads).reshape(-1, 2),\n axis=1))\n out_space = np.floor_divide(\n np.subtract(lhs_padded, rhs_shape[2:]), strides) + 1\n out_space = np.maximum(0, out_space)\n assert lhs_shape[0] % batch_group_count == 0\n out_shape = (lhs_shape[0] // batch_group_count, rhs_shape[0])\n return tuple(out_shape + tuple(out_space))\n\n\ndef conv_general_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\n dimension_numbers):\n lhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)\n lhs_trans = np.take(lhs_shape, lhs_perm)\n rhs_trans = np.take(rhs_shape, rhs_perm)\n out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)\n return tuple(np.take(out_trans, np.argsort(out_perm)))\n\n\ndef conv_transpose_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\n dimension_numbers):\n lhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)\n lhs_trans = np.take(lhs_shape, lhs_perm)\n rhs_trans = np.take(rhs_shape, rhs_perm)\n if isinstance(padding, str):\n padding = [_conv_transpose_padding(k, s, padding)\n for k,s in zip(rhs_trans[2:], window_strides)]\n padding = list(map(np.sum, padding))\n unpad_out_space = [(i-1) * s - k + 2\n for i, k, s in zip(lhs_trans[2:],\n rhs_trans[2:],\n window_strides)]\n out_space = np.sum([unpad_out_space, padding], axis=0).tolist()\n out_trans = tuple((lhs_trans[0], rhs_trans[0]) + tuple(out_space))\n return tuple(np.take(out_trans, np.argsort(out_perm)))\n\n\ndef _check_shapelike(fun_name, arg_name, obj, non_zero_shape=False):\n \"\"\"Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints).\"\"\"\n if not isinstance(obj, (tuple, list, np.ndarray)):\n msg = \"{} {} must be of type tuple/list/ndarray, got {}.\"\n raise TypeError(msg.format(fun_name, arg_name, type(obj)))\n # bool(obj) for an ndarray raises an error, so we check len\n if not len(obj): # pylint: disable=g-explicit-length-test\n return\n obj_arr = np.array(obj)\n if obj_arr.ndim != 1:\n msg = \"{} {} must be rank 1, got {}.\"\n raise TypeError(msg.format(obj_arr.ndim))\n try:\n canonicalize_shape(obj_arr)\n except TypeError as err:\n msg = \"{} {} must have every element be an integer type, got {}.\"\n raise TypeError(msg.format(fun_name, arg_name, tuple(map(type, obj)))) from err\n lower_bound, bound_error = (\n (1, \"strictly positive\") if non_zero_shape else (0, \"nonnegative\"))\n if not (obj_arr >= lower_bound).all():\n msg = \"{} {} must have every element be {}, got {}.\"\n raise TypeError(msg.format(fun_name, arg_name, bound_error, obj))\n\n\ndef _dynamic_slice_indices(operand, start_indices):\n if len(start_indices) != operand.ndim:\n msg = (\"Length of slice indices must match number of operand dimensions ({} \"\n \"vs {})\")\n raise ValueError(msg.format(len(start_indices), operand.shape))\n # map int over operand.shape to raise any dynamic-shape errors\n safe_map(int, operand.shape)\n if not isinstance(start_indices, (tuple, list)):\n if start_indices.ndim != 1:\n raise ValueError(\"Slice indices must be a 1D sequence, got {}\"\n .format(start_indices.shape))\n return select(lt(start_indices, _zeros(start_indices)),\n add(start_indices, _const(start_indices, operand.shape)),\n start_indices)\n else:\n return [np.asarray(i + d if i < 0 else i, getattr(i, 'dtype', dtypes.int_))\n if isinstance(i, (int, np.integer))\n else select(lt(i, _const(i, 0)), add(i, _const(i, d)), i)\n for i, d in zip(start_indices, operand.shape)]\n\n\n\ndef _const(example, val):\n if dtypes.is_python_scalar(example):\n return dtypes.scalar_type_of(example)(val)\n return np.array(val, _dtype(example))\n\n_zeros: Callable = partial(full_like, fill_value=0)\n_zero: Callable = partial(full_like, shape=(), fill_value=0)\n_ones: Callable = partial(full_like, fill_value=1)\n_one: Callable = partial(full_like, shape=(), fill_value=1)\n_twos: Callable = partial(full_like, fill_value=2)\n_two: Callable = partial(full_like, shape=(), fill_value=2)\n\ndtype: Callable = dtypes.result_type\n_dtype: Callable = dtypes.result_type\n\ndef _iscomplex(x) -> bool:\n return dtypes.issubdtype(_dtype(x), np.complexfloating)\n\n\ndef ranges_like(*xs):\n start = 0\n for x in xs:\n x_len = len(x)\n yield range(start, start + x_len)\n start += x_len\n\n\ndef remaining(original, *removed_lists):\n removed = set(itertools.chain(*removed_lists))\n return [i for i in original if i not in removed]\n\n\ndef _canonicalize_precision(precision):\n if precision is None:\n return None\n if isinstance(precision, Precision) or (\n isinstance(precision, tuple)\n and len(precision) == 2\n and all(isinstance(p, Precision) for p in precision)\n ):\n return precision\n else:\n raise ValueError(\"Precision argument must be None, a lax.Precision value \"\n f\"or a tuple of two lax.Precision values; got {precision}\")\n\n\ndef conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers\n ) -> ConvDimensionNumbers:\n \"\"\"Converts convolution `dimension_numbers` to a `ConvDimensionNumbers`.\n\n Args:\n lhs_shape: tuple of nonnegative integers, shape of the convolution input.\n rhs_shape: tuple of nonnegative integers, shape of the convolution kernel.\n dimension_numbers: None or a tuple/list of strings or a ConvDimensionNumbers\n object following the convolution dimension number specification format in\n xla_client.py.\n\n Returns:\n A `ConvDimensionNumbers` object that represents `dimension_numbers` in the\n canonical form used by lax functions.\n \"\"\"\n if isinstance(dimension_numbers, ConvDimensionNumbers):\n return dimension_numbers\n if len(lhs_shape) != len(rhs_shape):\n msg = \"convolution requires lhs and rhs ndim to be equal, got {} and {}.\"\n raise TypeError(msg.format(len(lhs_shape), len(rhs_shape)))\n\n if dimension_numbers is None:\n iota = tuple(range(len(lhs_shape)))\n return ConvDimensionNumbers(iota, iota, iota)\n elif isinstance(dimension_numbers, (list, tuple)):\n if len(dimension_numbers) != 3:\n msg = \"convolution dimension_numbers list/tuple must be length 3, got {}.\"\n raise TypeError(msg.format(len(dimension_numbers)))\n if not all(isinstance(elt, str) for elt in dimension_numbers):\n msg = \"convolution dimension_numbers elements must be strings, got {}.\"\n raise TypeError(msg.format(tuple(map(type, dimension_numbers))))\n msg = (\"convolution dimension_numbers[{}] must have len equal to the ndim \"\n \"of lhs and rhs, got {} for lhs and rhs shapes {} and {}.\")\n for i, elt in enumerate(dimension_numbers):\n if len(elt) != len(lhs_shape):\n raise TypeError(msg.format(i, len(elt), lhs_shape, rhs_shape))\n\n lhs_spec, rhs_spec, out_spec = conv_general_permutations(dimension_numbers)\n return ConvDimensionNumbers(lhs_spec, rhs_spec, out_spec)\n else:\n msg = \"convolution dimension_numbers must be tuple/list or None, got {}.\"\n raise TypeError(msg.format(type(dimension_numbers)))\n\n\ndef conv_general_permutations(dimension_numbers):\n \"\"\"Utility for convolution dimension permutations relative to Conv HLO.\"\"\"\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n lhs_char, rhs_char, out_char = charpairs = (\"N\", \"C\"), (\"O\", \"I\"), (\"N\", \"C\")\n for i, (a, b) in enumerate(charpairs):\n if not dimension_numbers[i].count(a) == dimension_numbers[i].count(b) == 1:\n msg = (\"convolution dimension_numbers[{}] must contain the characters \"\n \"'{}' and '{}' exactly once, got {}.\")\n raise TypeError(msg.format(i, a, b, dimension_numbers[i]))\n if len(dimension_numbers[i]) != len(set(dimension_numbers[i])):\n msg = (\"convolution dimension_numbers[{}] cannot have duplicate \"\n \"characters, got {}.\")\n raise TypeError(msg.format(i, dimension_numbers[i]))\n if not (set(lhs_spec) - set(lhs_char) == set(rhs_spec) - set(rhs_char) ==\n set(out_spec) - set(out_char)):\n msg = (\"convolution dimension_numbers elements must each have the same \"\n \"set of spatial characters, got {}.\")\n raise TypeError(msg.format(dimension_numbers))\n\n def getperm(spec, charpair):\n spatial = (i for i, c in enumerate(spec) if c not in charpair)\n if spec is not rhs_spec:\n spatial = sorted(spatial, key=lambda i: rhs_spec.index(spec[i]))\n return (spec.index(charpair[0]), spec.index(charpair[1])) + tuple(spatial)\n\n lhs_perm, rhs_perm, out_perm = map(getperm, dimension_numbers, charpairs)\n return lhs_perm, rhs_perm, out_perm\n\n\ndef _conv_general_proto(dimension_numbers):\n assert type(dimension_numbers) is ConvDimensionNumbers\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n proto = xla_client.ConvolutionDimensionNumbers()\n proto.input_batch_dimension = lhs_spec[0]\n proto.input_feature_dimension = lhs_spec[1]\n proto.output_batch_dimension = out_spec[0]\n proto.output_feature_dimension = out_spec[1]\n proto.kernel_output_feature_dimension = rhs_spec[0]\n proto.kernel_input_feature_dimension = rhs_spec[1]\n proto.input_spatial_dimensions.extend(lhs_spec[2:])\n proto.kernel_spatial_dimensions.extend(rhs_spec[2:])\n proto.output_spatial_dimensions.extend(out_spec[2:])\n return proto\n\n\ndef _conv_general_vjp_lhs_padding(\n in_shape, window_dimensions, window_strides, out_shape, padding,\n lhs_dilation, rhs_dilation) -> List[Tuple[int, int]]:\n lhs_dilated_shape = _dilate_shape(in_shape, lhs_dilation)\n rhs_dilated_shape = _dilate_shape(window_dimensions, rhs_dilation)\n out_dilated_shape = _dilate_shape(out_shape, window_strides)\n pad_before = np.subtract(rhs_dilated_shape, [lo for lo, _ in padding]) - 1\n pad_after = (np.add(lhs_dilated_shape, rhs_dilated_shape) - 1\n - out_dilated_shape - pad_before)\n return safe_zip(pad_before, pad_after)\n\n\ndef _conv_general_vjp_rhs_padding(\n in_shape, window_dimensions, window_strides, out_shape, padding,\n lhs_dilation, rhs_dilation):\n lhs_dilated_shape = _dilate_shape(in_shape, lhs_dilation)\n rhs_dilated_shape = _dilate_shape(window_dimensions, rhs_dilation)\n out_dilated_shape = _dilate_shape(out_shape, window_strides)\n total_in_pad = out_dilated_shape + rhs_dilated_shape - lhs_dilated_shape - 1\n return [(pad[0], tot - pad[0]) for pad, tot in zip(padding, total_in_pad)]\n\n\ndef _balanced_eq(x, z, y):\n return div(select(_eq_meet(x, z), _ones(z), _zeros(z)),\n select(_eq_meet(y, z), _twos(z), _ones(z)))\n\n\ndef _eq_meet(a, b):\n a_dtype, b_dtype = _dtype(a), _dtype(b)\n if a_dtype != b_dtype:\n higher_dtype = dtypes.promote_types(a_dtype, b_dtype)\n if higher_dtype == a_dtype:\n a = convert_element_type(a, b_dtype)\n else:\n b = convert_element_type(b, a_dtype)\n return eq(a, b)\n\n\ndef _abstractify(x):\n return raise_to_shaped(core.get_aval(x))\n\n\ndef _check_user_dtype_supported(dtype, fun_name=None):\n # Avoid using `dtype in [...]` becuase of numpy dtype equality overloading.\n if isinstance(dtype, type) and dtype in {bool, int, float, complex}:\n return\n np_dtype = np.dtype(dtype)\n if np_dtype.kind not in \"biufc\" and np_dtype.type != dtypes.bfloat16:\n msg = f\"JAX only supports number and bool dtypes, got dtype {dtype}\"\n msg += f\" in {fun_name}\" if fun_name else \"\"\n raise TypeError(msg)\n if dtype is not None and np_dtype != dtypes.canonicalize_dtype(dtype):\n msg = (\"Explicitly requested dtype {} {} is not available, \"\n \"and will be truncated to dtype {}. To enable more dtypes, set the \"\n \"jax_enable_x64 configuration option or the JAX_ENABLE_X64 shell \"\n \"environment variable. \"\n \"See https://github.com/google/jax#current-gotchas for more.\")\n fun_name = f\"requested in {fun_name}\" if fun_name else \"\"\n truncated_dtype = dtypes.canonicalize_dtype(dtype).name\n warnings.warn(msg.format(dtype, fun_name , truncated_dtype))\n\n\ndef _canonicalize_axis(axis, num_dims):\n \"\"\"Canonicalize an axis in [-num_dims, num_dims) to [0, num_dims).\"\"\"\n axis = operator.index(axis)\n if not -num_dims <= axis < num_dims:\n raise ValueError(\n \"axis {} is out of bounds for array of dimension {}\".format(\n axis, num_dims))\n if axis < 0:\n axis = axis + num_dims\n return axis\n\n\ntie_in_p = Primitive('tie_in')\n\[email protected]_omnistaging_disabler\ndef omnistaging_disabler() -> None:\n global tie_in\n\n def tie_in(x: Array, y: Array) -> Array:\n \"\"\"Returns the value of ``y`` but with a fake data dependence on ``x``.\n\n When staging to XLA (e.g. running under jit or pmap), values that don't depend\n on computation inputs are computed op-by-op, and folded into the XLA\n computation as constants.\n\n ``tie_in`` provides a way to explicitly stage values into the computation.\n When staging to XLA and ``x`` is already staged, then the result of ``tie_in``\n is ``y``, but staged to XLA. Downstream use of the result will also be staged\n to XLA.\n\n For example, ``lax.sin(const)`` would be constant-folded if ``const`` is\n a constant array, but ``lax.sin(lax.tie_in(x, const))``, will be staged to\n XLA as long as ``x`` is staged to XLA.\n \"\"\"\n if config.omnistaging_enabled:\n return y\n else:\n return tie_in_p.bind(x, y)\n\n # If lax has already been imported, we need to monkey-patch the\n # lax/__init__.py import of tie_in. If not (i.e. if this is running at lax\n # module creation time) then we'll get an import error.\n try:\n jax.lax.tie_in = tie_in\n except AttributeError:\n pass\n\n def _tie_in_transpose_rule(t, x, y):\n if ad.is_undefined_primal(x):\n return [ad_util.Zero(x.aval), t]\n else:\n return [ad_util.Zero.from_value(x), t]\n\n def _tie_in_batch_rule(batched_args, batch_dims):\n y = tie_in(*batched_args)\n _, bdim_y = batch_dims\n return y, bdim_y\n\n def _tie_in_impl(x, y):\n core.check_valid_jaxtype(x)\n core.check_valid_jaxtype(y)\n return y\n\n def _tie_in_jvp(primals, tangents):\n x, y = primals\n x_dot, y_dot = tangents\n if type(y_dot) is ad_util.Zero or core.get_aval(y_dot).dtype is dtypes.float0:\n return y, y_dot # skip tying in in this case\n else:\n return ad.linear_jvp(tie_in_p, primals, tangents)\n\n tie_in_p.def_impl(_tie_in_impl)\n tie_in_p.def_abstract_eval(lambda x, y: raise_to_shaped(y))\n xla.translations[tie_in_p] = lambda c, x, y: y\n ad.primitive_jvps[tie_in_p] = _tie_in_jvp\n ad.primitive_transposes[tie_in_p] = partial(ad.linear_transpose2, _tie_in_transpose_rule)\n batching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\n masking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]\n" ]
[ [ "numpy.ones", "numpy.sum", "numpy.subtract", "numpy.take", "numpy.dtype", "numpy.less", "numpy.issubdtype", "numpy.argsort", "numpy.asarray", "numpy.size", "numpy.greater_equal", "numpy.add", "numpy.delete", "numpy.negative", "numpy.sqrt", "numpy.ceil", "numpy.zeros", "numpy.equal", "numpy.greater", "numpy.arange", "numpy.int32", "numpy.ndim", "numpy.prod", "numpy.maximum", "numpy.finfo", "numpy.zeros_like", "numpy.cumsum", "numpy.swapaxes", "numpy.not_equal", "numpy.iinfo", "numpy.shape", "numpy.less_equal", "numpy.flip", "numpy.array_equal", "numpy.array" ] ]
Seledriac/A-small-python-library-for-deep-learning
[ "c041287b04ba217910f621d34c7739365c36ad48" ]
[ "hd_recognition/GUI.py" ]
[ "\n# -*- coding:utf-8 -*-\n\n\"\"\"Handwritten digits recognition Graphic interface module : training done with the mnist dataset\"\"\"\n\n# Third-party gui/system/plotting Libraries\nimport numpy as np\nimport tkinter as tk\nimport tkinter.font as tkFont\nfrom tkinter import messagebox\nfrom tkinter import filedialog\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.figure import Figure\nfrom PIL import ImageTk, Image\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QLabel\nfrom PyQt5.QtGui import QPainter, QPixmap, QPen, QScreen\nimport pickle\nimport webbrowser\nimport os\nimport sys\nsys.path.insert(1, str(os.getcwd()))\n\n# Neural network module\nimport network\n\n\n\n# ------------------------------------------------------------------------------tkinter GUI---------------------------------------------------------------------------------------------\nclass Interface(tk.Frame):\n \"\"\"graphic interface class\"\"\"\n\n\n# ------------------------------------------------------------------------------__init__------------------------------------------------------------------------------------------------\n\n def __init__(self, window, **kwargs):\n \"\"\"Displays the main menu\"\"\"\n # Fonts\n self.big_font_button = tkFont.Font(family='Calibri', size=20, weight='bold')\n self.medium_large_font_button = tkFont.Font(family='Calibri', size=16, weight='bold')\n self.medium_font_button = tkFont.Font(family='Calibri', size=14, weight='bold')\n self.font_title = tkFont.Font(family='Calibri', size=36, weight='bold')\n self.number_button_font = tkFont.Font(family='Calibri', size=25, weight='bold')\n\n # Display main menu\n self.main_menu(window, **kwargs)\n\n\n# ------------------------------------------------------------------------------Main Menu Interface--------------------------------------------------------------------------------------\n\n def main_menu(self, window, **kwargs):\n \"\"\"Main menu Frame\"\"\"\n # Frame creation\n if hasattr(self, 'children'):\n self.destroy()\n tk.Frame.__init__(self, window, width=1180, height=620, bg=\"#fff2f2\", **kwargs)\n self.pack()\n\n # Github Button\n img_github = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/github.jpg\").resize((50,50)))\n btn_github = tk.Button(self, image=img_github, command=lambda: webbrowser.open(\"https://github.com/Seledriac/A-small-pedagogic-python-library-for-supervised-neural-networks/\"))\n btn_github.img = img_github\n btn_github.grid(column=0, row=0, padx=50, pady=(0,50))\n\n # Title\n title = tk.Label(self, text=\"Supervised neural networks\\n applied to handwritten digits recognition\", bg=\"#fff2f2\", font=self.font_title)\n title.grid(column=1, row=0, pady=25)\n\n # Readme Button\n img_readme = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/readme.png\").resize((50,50)))\n btn_readme = tk.Button(self, image=img_readme, command=lambda: os.startfile(\"README.md\"))\n btn_readme.img = img_readme\n btn_readme.grid(column=2, row=0, padx=60, pady=(0,50))\n\n # Button selection frame\n btns_frames = tk.LabelFrame(self, padx=50, pady=50, borderwidth=5)\n btns_frames.grid(row=1, column=1, columnspan=3, pady=(65,80), padx=(0,180))\n\n # Menu Buttons\n create_model_button = tk.Button(btns_frames, text=\"Create a model\", font=self.big_font_button, command=lambda: self.create_model(window, **kwargs))\n create_model_button.grid(column=0, row=0, padx=10, pady=10)\n \n train_model_button = tk.Button(btns_frames, text=\"Train a model\", font=self.big_font_button, command=lambda: self.train_model(window, **kwargs))\n train_model_button.grid(column = 1, row = 0, padx=10, pady=10)\n\n evaluate_button = tk.Button(btns_frames, text=\"Accuracy Ladder\", font=self.big_font_button, command=lambda: self.models_ladder(window, **kwargs))\n evaluate_button.grid(column = 0, row = 1, padx=10, pady=10)\n \n predict_button = tk.Button(btns_frames, text=\"Predict\", font=self.big_font_button, command=lambda: self.choose_prediction(window, **kwargs))\n predict_button.grid(column = 1, row = 1, padx=10, pady=10)\n\n\n# ------------------------------------------------------------------------------Model Creation Interface------------------------------------------------------------------------------------\n\n def create_model(self, window, **kwargs):\n \"\"\"Model creation Frame\"\"\"\n # Frame creation\n self.destroy()\n if hasattr(self, 'hidden_layers_label'):\n delattr(self, 'hidden_layers_label')\n tk.Frame.__init__(self, window, width=1180, height=620, bg=\"#fff2f2\", **kwargs)\n self.pack()\n\n # Main menu Button\n img_home = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/home.png\").resize((95,50)))\n btn_home = tk.Button(self, image=img_home, command=lambda: self.main_menu(window, **kwargs))\n btn_home.img = img_home\n btn_home.grid(column=0, row=0)\n \n # Title\n title = tk.Label(self, text=\"Model Creation\", bg=\"#fff2f2\", font=self.font_title)\n title.grid(column=1, row=0)\n\n # Model Validation frame\n model_creation_validation_frame = tk.LabelFrame(self, borderwidth=3)\n model_creation_validation_frame.grid(row=0, column=2, pady=(20,0))\n model_creation_validation_label = tk.Label(model_creation_validation_frame, text=\"Model name\", font=self.medium_font_button)\n model_creation_validation_label.pack()\n self.model_creation_validation_entry = tk.Entry(model_creation_validation_frame)\n self.model_creation_validation_entry.pack()\n model_creation_validation_button = tk.Button(model_creation_validation_frame, text=\"Create Model\", font=self.medium_font_button, command=self.model_creation_validation)\n model_creation_validation_button.pack()\n\n # Model customization frame\n creation_custom_frame = tk.LabelFrame(self, padx=50, pady=50, borderwidth=5)\n creation_custom_frame.grid(row=1, column=0, columnspan=3, pady=(30,0))\n\n # Input layer Frame\n input_layer_frame = tk.LabelFrame(creation_custom_frame)\n input_layer_frame.grid(row=0, column=0)\n input_layer_label = tk.Label(input_layer_frame, text=\"Input Layer\", font=self.medium_font_button)\n input_layer_label.pack()\n self.input_layer_number = tk.Entry(input_layer_frame)\n self.input_layer_number.insert(0,784)\n self.input_layer_number.pack()\n\n # Hidden layers Frame\n self.hidden_layers = []\n self.hidden_layers_frame = tk.LabelFrame(creation_custom_frame)\n self.hidden_layers_frame.grid(row=0, column=1)\n self.add_hidden_layer()\n self.add_hidden_layer()\n\n # Output layer Frame\n output_layer_frame = tk.LabelFrame(creation_custom_frame)\n output_layer_frame.grid(row=0, column=2, padx=70)\n output_layer_label = tk.Label(output_layer_frame, text=\"Output Layer\", font=self.medium_font_button)\n output_layer_label.pack()\n self.output_layer_number = tk.Entry(output_layer_frame)\n self.output_layer_number.insert(0,10)\n self.output_layer_number.pack()\n\n # Hidden layer adding/deleting buttons\n add_hidden_layer_button = tk.Button(creation_custom_frame, text=\"Add a hidden layer\", font=self.medium_font_button, command=self.add_hidden_layer)\n add_hidden_layer_button.grid(column = 0, row = 1, padx=50, pady=40)\n del_hidden_layer_button = tk.Button(creation_custom_frame, text=\"Delete the last hidden layer\", font=self.medium_font_button, command=self.del_hidden_layer)\n del_hidden_layer_button.grid(column = 1, row = 1, padx=50, pady=40, columnspan=2) \n\n def add_hidden_layer(self):\n \"\"\"Add a hidden layer in the model creation Frame\"\"\"\n if not hasattr(self, 'hidden_layers_label'):\n self.hidden_layers_label = tk.Label(self.hidden_layers_frame, text=\"Hidden Layer(s)\", font=self.medium_font_button)\n self.hidden_layers_label.grid(row=0, column=0, columnspan=10)\n if len(self.hidden_layers) < 5:\n new_hidden_layer = tk.Scale(self.hidden_layers_frame, from_=1, to=128, length=150)\n new_hidden_layer.grid(row=1,column=len(self.hidden_layers), padx=(0,20))\n self.hidden_layers.append(new_hidden_layer)\n \n def del_hidden_layer(self):\n \"\"\"Delete a hidden layer in the model creation Frame\"\"\"\n if len(self.hidden_layers) > 1:\n self.hidden_layers[-1].destroy()\n del self.hidden_layers[-1]\n elif hasattr(self, 'hidden_layers_label'):\n self.hidden_layers[-1].destroy()\n del self.hidden_layers[-1]\n self.hidden_layers_label.destroy()\n delattr(self, 'hidden_layers_label')\n \n def model_creation_validation(self):\n \"\"\"This method is executed when the model creation validation button is clicked. It creates the model, serlializes it, and shows a recap od the model in a message box to the user\"\"\"\n model_name = self.model_creation_validation_entry.get()\n try:\n input_number = int(self.input_layer_number.get())\n output_number = int(self.output_layer_number.get())\n except ValueError:\n messagebox.showerror(\"Error\", \"Error : enter a number of neurons for all the layers\")\n if model_name and input_number and output_number:\n sizes = [input_number]\n msg = \"Model \\\"{}\\\" successfully created.\\n\\nInput layer : {} neurons\\n\".format(str(self.model_creation_validation_entry.get()), str(input_number))\n for i,layer in enumerate(self.hidden_layers):\n nb_neurons = int(layer.get())\n sizes.append(nb_neurons)\n msg = msg + \"Hidden layer {} : {} neurons\\n\".format(str(i + 1), str(nb_neurons))\n sizes.append(output_number)\n msg = msg + \"Output layer : {} neurons\\n\\nActivation function : sigmoid (by default)\".format(str(output_number))\n net = network.Network(model_name, sizes)\n with open(\"models/hd_recognition/{}.pickle\".format(model_name), \"wb\") as fic:\n pickler = pickle.Pickler(fic)\n pickler.dump(net)\n messagebox.showinfo(\"Model Info\", msg)\n else:\n messagebox.showerror(\"Error\", \"Error : missing required fields\")\n\n\n# ------------------------------------------------------------------------------Model Training Interface------------------------------------------------------------------------------------\n\n def train_model(self, window, **kwargs):\n \"\"\"Model training specs Frame\"\"\"\n # Frame creation\n self.destroy()\n tk.Frame.__init__(self, window, width=1180, height=620, bg=\"#fff2f2\", **kwargs)\n self.pack()\n\n # Chosing the model which we will train\n self.open_model_file()\n\n # Main menu Button\n img_home = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/home.png\").resize((95,50)))\n btn_home = tk.Button(self, image=img_home, command=lambda: self.main_menu(window, **kwargs))\n btn_home.img = img_home\n btn_home.grid(column=0, row=0, padx=(25,0))\n \n # Title\n title = tk.Label(self, text=\"Model Training\\n(mnist dataset)\", bg=\"#fff2f2\", font=self.font_title)\n title.grid(column=1, row=0, pady=80, padx=(200,0))\n\n # Model training validation frame\n model_training_validation_frame = tk.LabelFrame(self, borderwidth=3)\n model_training_validation_frame.grid(row=0, column=2, padx=(200,0), pady=(10,0))\n model_training_validation_button = tk.Button(model_training_validation_frame, text=\"Train\", font=self.medium_large_font_button, command=lambda: self.model_training(window, **kwargs))\n model_training_validation_button.pack()\n\n # Model training customization frame\n training_custom_frame = tk.LabelFrame(self, padx=50, pady=50, borderwidth=5)\n training_custom_frame.grid(row=1, column=0, columnspan=100, padx=(0,15))\n\n # Epochs Frame\n epochs_frame = tk.LabelFrame(training_custom_frame)\n epochs_frame.grid(row=0, column=0)\n epochs_label = tk.Label(epochs_frame, text=\"Epochs\", font=self.medium_font_button)\n epochs_label.pack()\n self.epochs_number = tk.Entry(epochs_frame)\n self.epochs_number.insert(0,3)\n self.epochs_number.pack()\n\n # Batch size Frame\n batch_size_frame = tk.LabelFrame(training_custom_frame)\n batch_size_frame.grid(row=0, column=2, padx=70)\n batch_size_label = tk.Label(batch_size_frame, text=\"batch size\", font=self.medium_font_button)\n batch_size_label.pack()\n self.batch_size_number = tk.Entry(batch_size_frame)\n self.batch_size_number.insert(0,10)\n self.batch_size_number.pack()\n\n # Display weights checkbox\n display_weights_frame = tk.LabelFrame(training_custom_frame)\n display_weights_frame.grid(row=0, column=3)\n self.display_weights_value = tk.IntVar()\n display_weights_cb = tk.Checkbutton(display_weights_frame, text=\"Dynamically display the weights of the first layer\", font=self.medium_font_button, variable=self.display_weights_value)\n display_weights_cb.pack()\n\n def model_training(self, window, **kwargs):\n \"\"\"Model training Frame\"\"\"\n\n # Training values retrieving\n disp_weights = bool(self.display_weights_value.get())\n try:\n epochs = int(self.epochs_number.get())\n batch_size = int(self.batch_size_number.get())\n except ValueError:\n messagebox.showerror(\"Error\", \"Error : please enter a numeric value for each field\")\n \n if epochs and batch_size:\n # Frame creation\n self.destroy()\n tk.Frame.__init__(self, window, width=1180, height=620, bg=\"#fff2f2\", **kwargs)\n\n # Main menu Button\n img_home = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/home.png\").resize((95,50)))\n btn_home = tk.Button(self, image=img_home, command=lambda: self.main_menu(window, **kwargs))\n btn_home.img = img_home\n btn_home.grid(column=0, row=0)\n\n # Training trigger button\n doIt = tk.Button(self, text=\"Start the Training\", command=lambda: self.start_training(epochs, batch_size, disp_weights), font=self.big_font_button)\n doIt.grid(row=0, column=1, pady=20)\n\n # Training logs textbox\n textbox_frame = tk.LabelFrame(self)\n textbox_frame.grid(row=1, column=0, columnspan=2)\n self.output = tk.Text(textbox_frame, width=110, height=30, bg='black', fg='white')\n self.output.pack(side=tk.LEFT)\n\n # Scrollbar\n scrollbar = tk.Scrollbar(textbox_frame, orient=\"vertical\", command = self.output.yview)\n scrollbar.pack(side=tk.RIGHT, fill=\"y\")\n self.output['yscrollcommand'] = scrollbar.set\n\n self.pack()\n else:\n messagebox.showerror(\"Error\", \"Error : missing required fields\")\n\n def start_training(self, epochs, batch_size, disp_weights):\n \"\"\"This method executes the SGD training method on a given model\"\"\"\n # Importing the mnist dataset\n import mnist_loader\n training_data, validation_data, test_data = mnist_loader.load_data_wrapper()\n training_data = list(training_data)\n validation_data = list(validation_data)\n test_data = list(test_data)\n\n # Model training via SGD\n net = self.model_file\n self.output.insert(tk.END, \"\\n\" + str(net) + \"\\n\")\n self.update_idletasks()\n net.SGD(training_data, epochs, batch_size, test_data=test_data, display_weights=disp_weights, gui=self)\n\n # Model saving\n with open(\"models/hd_recognition/{}.pickle\".format(net.id), \"wb\") as saving:\n saver = pickle.Pickler(saving)\n saver.dump(net)\n\n # Performance test of the network on the validation data\n accuracy = str(100 * net.evaluate(validation_data) / 10000)\n self.output.insert(tk.END, \"\\nTest on the validation data -> Accuracy : {0}%\\n\".format(accuracy))\n self.update_idletasks()\n self.output.see(\"end\")\n\n # Ladder update\n with open(\"models/hd_recognition/accuracy_ladder.md\", \"a\") as ladder:\n adding = str(net) + \" --> accuracy = \" + accuracy + \"\\n\"\n ladder.write(adding)\n with open(\"models/hd_recognition/accuracy_ladder.md\", \"r\") as ladder:\n shove_percent = ladder.read().replace(\"%\", \"\")\n content = [net.split(\"= \") for net in shove_percent.split('\\n')]\n content.pop()\n content_updated = sorted([(acc,net) for net,acc in content], reverse = True)\n tostring = \"%\\n\".join([\"= \".join((net,acc)) for acc,net in content_updated]) + \"%\\n\"\n with open(\"models/hd_recognition/accuracy_ladder.md\", \"w\") as ladder:\n ladder.write(tostring)\n\n\n# ------------------------------------------------------------------------------Models Ladder Interface------------------------------------------------------------------------------------\n\n def models_ladder(self, window, **kwargs):\n \"\"\"Models ladder frame\"\"\"\n # Frame creation\n self.destroy()\n tk.Frame.__init__(self, window, width=1180, height=620, bg=\"#fff2f2\", **kwargs)\n\n # Main menu Button\n img_home = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/home.png\").resize((95,50)))\n btn_home = tk.Button(self, image=img_home, command=lambda: self.main_menu(window, **kwargs))\n btn_home.img = img_home\n btn_home.grid(column=0, row=0)\n\n # Ladder label\n ladder_label = tk.Label(self, text=\"Models Accuracy Ladder\", font=self.font_title, bg=\"#fff2f2\")\n ladder_label.grid(row=0, column=1, padx=(0,150), pady=20)\n\n # Ladder textbox\n textbox_frame = tk.LabelFrame(self)\n textbox_frame.grid(row=1, column=0, columnspan=2)\n output = tk.Text(textbox_frame, width=100, height=20, font=self.medium_font_button)\n output.pack(side=tk.LEFT)\n with open(\"models/hd_recognition/accuracy_ladder.md\", \"r\") as ladder:\n content = ladder.read()\n output.insert(tk.END, content)\n self.update_idletasks()\n output.see(\"end\")\n\n # Scrollbar\n scrollbar = tk.Scrollbar(textbox_frame, orient=\"vertical\", command = output.yview)\n scrollbar.pack(side=tk.RIGHT, fill=\"y\")\n output['yscrollcommand'] = scrollbar.set\n\n self.pack()\n\n\n# ------------------------------------------------------------------------------Prediction Interface---------------------------------------------------------------------------------------\n\n def choose_prediction(self, window, **kwargs):\n \"\"\"Prediction style choice frame\"\"\"\n # Frame creation\n self.destroy()\n tk.Frame.__init__(self, window, width=1180, height=620, bg=\"#fff2f2\", **kwargs)\n self.pack()\n\n # Opening the model which will predict\n self.open_model_file()\n\n # Main menu Button\n img_home = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/home.png\").resize((95,50)))\n btn_home = tk.Button(self, image=img_home, command=lambda: self.main_menu(window, **kwargs))\n btn_home.img = img_home\n btn_home.grid(column=0, row=0, padx=(0,125), pady=(15,100))\n\n # Ladder label\n choice_label = tk.Label(self, text=\"Choose the prediction style\", font=self.font_title, bg=\"#fff2f2\")\n choice_label.grid(row=0, column=1, columnspan=10, padx=(50,250), pady=50)\n\n # Choice buttons\n choice_custom = tk.Button(self, text=\"Predict with custom test images\", font=self.big_font_button, command=lambda: self.custom_prediction_frame(window, **kwargs))\n choice_custom.grid(row=1, column=1, padx=(0,0), pady=(100))\n choice_live = tk.Button(self, text=\"Live prediction\", font=self.big_font_button, command=lambda: self.live_prediction_frame(window, **kwargs))\n choice_live.grid(row=1, column=2, padx=(50,200), pady=(100))\n \n def custom_prediction_frame(self, window, **kwargs):\n \"\"\"Custom images prediction frame\"\"\"\n\n # Frame creation\n self.destroy()\n tk.Frame.__init__(self, window, width=1180, height=620, bg=\"#fff2f2\", **kwargs)\n self.pack()\n\n # Main menu Button\n img_home = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/home.png\").resize((95,50)))\n btn_home = tk.Button(self, image=img_home, command=lambda: self.main_menu(window, **kwargs))\n btn_home.img = img_home\n btn_home.grid(column=0, row=0, pady=(10,30))\n\n # Title label\n title_label = tk.Label(self, text=\"Custom images prediction\\nChoose the number to predict\", font=self.number_button_font, bg=\"#fff2f2\")\n title_label.grid(row=0, column=1, columnspan=2, padx=(0,150), pady=10)\n \n # Number buttons Frame\n number_buttons_frame = tk.LabelFrame(self, borderwidth=3, bg='white', pady=10)\n number_buttons_frame.grid(row=1,column=1, columnspan=2, padx=(0,150))\n\n # Number buttons\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"0\", command=lambda: self.number_button_click(0))\n btn_home.grid(column=0, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"1\", command=lambda: self.number_button_click(1))\n btn_home.grid(column=1, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"2\", command=lambda: self.number_button_click(2))\n btn_home.grid(column=2, row=1, padx=15) \n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"3\", command=lambda: self.number_button_click(3))\n btn_home.grid(column=3, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"4\", command=lambda: self.number_button_click(4))\n btn_home.grid(column=4, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"5\", command=lambda: self.number_button_click(5))\n btn_home.grid(column=5, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"6\", command=lambda: self.number_button_click(6))\n btn_home.grid(column=6, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"7\", command=lambda: self.number_button_click(7))\n btn_home.grid(column=7, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"8\", command=lambda: self.number_button_click(8))\n btn_home.grid(column=8, row=1, padx=15)\n\n btn_home = tk.Button(number_buttons_frame, font=self.number_button_font, text=\"9\", command=lambda: self.number_button_click(9))\n btn_home.grid(column=9, row=1, padx=15)\n\n def number_button_click(self, number):\n \"\"\"This method is executed when a number button is clicked. It displays the model's prediction on a matplotlib figure\"\"\"\n\n # Opening the corresponding custom image\n img_filename_bmp = \"hd_recognition/custom_test_images/test_image_\"+str(number)+\".bmp\"\n test_image = Image.open(img_filename_bmp)\n\n # Predicting based on the custom image\n image_array = 1 - (np.array(test_image).reshape(784,1) / 255)\n model_activations = self.model_file.feedforward(image_array)\n\n # Custom image display\n img_filename_png = \"hd_recognition/custom_test_images/test_image_\"+str(number)+\".png\"\n custom_image = ImageTk.PhotoImage(Image.open(img_filename_png))\n custom_image_label = tk.Label(self, image=custom_image, relief='ridge')\n custom_image_label.image=custom_image\n custom_image_label.grid(row=2, column=1, padx=10, pady=(5,5))\n\n # Prediction plot frame \n prediction_frame = tk.LabelFrame(self)\n prediction_frame.grid(row=2,column=2, padx=(10,150), pady=(5,5))\n\n # Plotting the model activations\n self.plot_model_activation(model_activations, prediction_frame)\n\n\n def live_prediction_frame(self, window, **kwargs):\n \"\"\"Live prediction of the numbers drew by the user\"\"\"\n # Frame creation\n self.destroy()\n window.geometry(\"1500x800\")\n tk.Frame.__init__(self, window, width=1500, height=800, bg=\"#fff2f2\", **kwargs)\n self.pack()\n\n # Main menu Button\n img_home = ImageTk.PhotoImage(Image.open(\"hd_recognition/assets/home.png\").resize((95,50)))\n btn_home = tk.Button(self, image=img_home, command=lambda: self.main_menu(window, **kwargs))\n btn_home.img = img_home\n btn_home.grid(column=0, row=0, padx=100)\n \n # Title\n title = tk.Label(self, text=\"Live prediction\\nDraw the number to predict\", bg=\"#fff2f2\", font=self.font_title)\n title.grid(column=1, row=0, pady=80)\n\n # Start button frame\n live_prediction_starting_frame = tk.LabelFrame(self, borderwidth=3)\n live_prediction_starting_frame.grid(row=0, column=2, padx=100)\n live_prediction_starting_button = tk.Button(live_prediction_starting_frame, text=\"Start\", font=self.medium_large_font_button, command=lambda: self.start_live_prediction(window))\n live_prediction_starting_button.pack()\n\n def start_live_prediction(self, window):\n \"\"\"Live prediction Qt drawing window display\"\"\"\n # DrawingWindow creation\n App = QApplication(sys.argv)\n QtWindow = DrawingWindow(App, self)\n QtWindow.setWindowTitle(\"Digit drawing window\")\n QtWindow.show()\n sys.exit(App.exec())\n\n\n# ------------------------------------------------------------------------------Miscellaneous Methods--------------------------------------------------------------------------------------\n\n def open_model_file(self):\n \"\"\"Prompts the user to choose a model file\"\"\"\n re = True\n while re:\n try:\n # Model file opening prompt\n self.model_filename = filedialog.askopenfilename(initialdir=\"models/hd_recognition\", title=\"Choose the model\", filetypes=((\"pickle files\",\"*.pickle\"), (\"model files\",\"*.model\"), (\"all files\", \"*.*\")))\n assert self.model_filename\n re = False\n except:\n messagebox.showerror(\"Error\", \"Error : please select a model file\")\n with open(self.model_filename, \"rb\") as fic:\n unpickler = pickle.Unpickler(fic)\n self.model_file = unpickler.load()\n\n def plot_model_activation(self, model_activations, frame):\n \"\"\"Plots the current model activations in a given frame (in a prediction context)\"\"\"\n fig = Figure(figsize = (4, 4))\n fig.clf()\n fig.add_subplot(111).plot(range(10), model_activations)\n fig.suptitle(\"corresponding model activations\")\n axes = fig.gca()\n axes.set_xlabel(\"digit\")\n axes.set_ylabel(\"activation\") \n axes.set_ylim([0, 1])\n axes.set_xticks(range(10))\n axes.set_yticks(np.array(range(11))/10)\n canvas = FigureCanvasTkAgg(fig, master=frame)\n canvas.draw()\n canvas.flush_events()\n canvas.get_tk_widget().grid(row=0, column=1)\n self.annot_max(range(10), model_activations, axes)\n\n def annot_max(x, y, ax):\n \"\"\"Max network activation anotation for a number image\"\"\"\n xmax = x[np.argmax(y)]\n ymax = y.max() \n text = \"digit = {}, activation = {:.3f}\".format(xmax,ymax)\n if xmax <= 4:\n orientation = str((1 / abs(5 - (xmax + 1))) / 10)\n else:\n orientation = str(-(1 / abs(5 - (xmax + 1))) / 10)\n bbox_props = dict(boxstyle=\"square,pad=0.3\", fc=\"w\", ec=\"k\", lw=1)\n arrowprops=dict(arrowstyle=\"-|>\",connectionstyle=\"arc3,rad=\"+orientation)\n kw = dict(xycoords='data',textcoords=\"axes fraction\",\n arrowprops=arrowprops, bbox=bbox_props, ha=\"right\", va=\"top\")\n # ax.annotate(text, xy=(xmax, ymax), xytext=(xmax/10 - 0.1, ymax - 0.1), **kw)\n ax.annotate(text, xy=(xmax, ymax), xytext=(0.8, 0.5), **kw)\n annot_max = staticmethod(annot_max)\n\n\n\n# ------------------------------------------------------------------------------PyQt drawing window----------------------------------------------------------------------------------------\n\nclass DrawingWindow(QMainWindow):\n\n \"\"\"Drawing window for live model prediction\"\"\"\n\n def __init__(self, App, tkinter_root):\n \"\"\"Initialization of the Drawing Window : we create a label centered in the window, in which we put a blank pixmap\"\"\"\n super().__init__()\n self.label = QLabel() \n self.blank()\n self.setCentralWidget(self.label)\n self.App = App\n self.tkinter_root = tkinter_root\n\n self.last_x, self.last_y = None, None\n\n def blank(self):\n \"\"\"This method clears the QtWindow, setting the content of the centered label to a white pixmap\"\"\"\n self.label.setPixmap(QPixmap(\"hd_recognition/assets/white.png\"))\n\n def mouseMoveEvent(self, e):\n \"\"\"This method is executed while the click button is held\"\"\"\n if self.last_x is None: \n self.last_x = e.x()\n self.last_y = e.y()\n return \n\n painter = QPainter(self.label.pixmap())\n painter.drawLine(self.last_x, self.last_y, e.x(), e.y())\n painter.end()\n self.update()\n\n # Updating the origin for next time\n self.last_x = e.x()\n self.last_y = e.y()\n\n # Saving the screenshot and compressing it to a 28x28 image\n QScreen.grabWindow(self.App.primaryScreen(), self.winId()).save(\"hd_recognition/tmp/screenshot.png\", 'png')\n resize_img = Image.open(\"hd_recognition/tmp/screenshot.png\")\n resize_img = resize_img.resize((28,28))\n resize_img.save(\"hd_recognition/tmp/screenshot.png\", 'png')\n \n # Converting from standard png to greyscale \n img_array = np.array(Image.open(\"hd_recognition/tmp/screenshot.png\"))\n img_array = np.array([[pixel[0] for pixel in line] for line in img_array])\n image_array = 1 - (img_array.reshape(784,1) / 255)\n\n # Predicting the number \n model_activations = self.tkinter_root.model_file.feedforward(image_array)\n\n # Prediction plot frame\n prediction_frame = tk.LabelFrame(self.tkinter_root)\n prediction_frame.grid(row=2,column=2)\n\n # Plotting the model activations\n self.tkinter_root.plot_model_activation(model_activations, prediction_frame)\n\n def mouseReleaseEvent(self, e):\n self.last_x = None\n self.last_y = None\n\n\n\n# -----------------------------------------------------------------------------Tkinter Window creation-------------------------------------------------------------------------------------\n\nwindow = tk.Tk()\nwindow.geometry(\"1180x620\")\nwindow.title(\"Neural Networks\")\nwindow.configure(bg=\"#fff2f2\")\ninterface = Interface(window)\ninterface.mainloop()\n\n" ]
[ [ "numpy.array", "matplotlib.figure.Figure", "numpy.argmax", "matplotlib.backends.backend_tkagg.FigureCanvasTkAgg" ] ]
tsubedy/web-scraping-challenge
[ "785faf0b9855086dedaef1c1df2ea7b81a0dde4b" ]
[ "scrape_mars.py" ]
[ "\n# Dependencies\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time \nimport pandas as pd\nfrom pprint import pprint\nfrom urllib.parse import urlsplit\nimport pymongo\n\n# Initialize PyMongo to work with MongoDBs\nconn = 'mongodb://localhost:27017'\nclient = pymongo.MongoClient(conn)\n\n# Define database and collection\ndb = client.mars_db\ncollection = db.items\n\n\ndef init_browser():\n # capture path to chrome driver \n executable_path = {'executable_path': ChromeDriverManager().install()}\n return Browser('chrome', **executable_path, headless=False)\n\ndef scrape_info():\n browser = init_browser()\n mars_info = {}\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n\n # scrape latest news headline and para\n news_title=soup.find('ul', class_='item_list').\\\n find('li', class_='slide').\\\n find('div', class_= 'content_title').text\n\n news_para=soup.find(\"div\", class_='article_teaser_body').text\n\n mars_info['news_title'] = news_title\n mars_info['news_para'] = news_para \n \n\n # Featured image\n\n featured_image = \"https://www.nasa.gov/image-feature/jpl/perseverance-s-first-full-color-look-at-mars\"\n browser.visit(featured_image)\n\n base_url = \"{0.scheme}://{0.netloc}/\".format(urlsplit(featured_image))\n \n # click on featured image using xpath\n xpath = '//*[@id=\"468477\"]/div[2]/div[2]/a/img'\n results = browser.find_by_xpath(xpath)\n img = results[0]\n img.click()\n\n time.sleep(1)\n\n #get image url using BeautifulSoup\n html_image = browser.html\n soup = BeautifulSoup(html_image, \"html.parser\")\n\n featured_img_url = soup.find('img')['src']\n mars_info['featured_img_url'] = featured_img_url\n\n\n # Mars Facts\n url_facts = \"https://space-facts.com/mars/\"\n table = pd.read_html(url_facts)\n table[0]\n\n df_mars_facts = table[0]\n df_mars_facts.columns = [\"Parameter\", \"Values\"]\n fact_table = df_mars_facts.set_index([\"Parameter\"])\n\n mars_html_table = fact_table.to_html()\n mars_html_table = mars_html_table.replace(\"\\n\", \"\")\n mars_info['mars_facts_table'] = mars_html_table\n\n # Mars Hemisphere\n hemisphere_url = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n browser.visit(hemisphere_url)\n\n #Get base url\n hemisphere_base_url = \"{0.scheme}://{0.netloc}/\".format(urlsplit(hemisphere_url))\n \n # list of xpaths for mars hemispheres\n xpaths = ['//*[@id=\"product-section\"]/div[2]/div[1]/a/img', '//*[@id=\"product-section\"]/div[2]/div[2]/a/img', '//*[@id=\"product-section\"]/div[2]/div[3]/a/img', '//*[@id=\"product-section\"]/div[2]/div[4]/a/img']\n hemisphere_img_urls = []\n\n for xpath in xpaths:\n hemisphere_url = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n browser.visit(hemisphere_url)\n\n results = browser.find_by_xpath(xpath)\n img = results[0]\n img.click()\n time.sleep(1)\n\n #get image url using BeautifulSoup\n html_image = browser.html\n soup = BeautifulSoup(html_image, \"html.parser\")\n img_url = soup.find(\"img\", class_='wide-image')[\"src\"]\n\n time.sleep(1)\n img_url = hemisphere_base_url + img_url\n title = soup.find(\"h2\",class_=\"title\").text\n\n hemisphere_img_urls.append({'title': title, 'image_url':img_url})\n \n mars_info['hemisphere_img_urls'] = hemisphere_img_urls\n \n browser.quit()\n\n # collection.insert_one(mars_info)\n \n return mars_info\n\n \n\n\n" ]
[ [ "pandas.read_html" ] ]
danielamassiceti/geneval_visdial
[ "fbbe12b1e4ed7e21a002b16a87bdf42b2af3b35e" ]
[ "clusters/dataset_utils.py" ]
[ "import sys\nimport utils\nimport torch\nfrom datasets import VisualDialogDataset\nimport torchvision.transforms as transforms\n\ndef build_dataset(mode, args, shared_dictionary=None, with_options=True):\n \n normalize = transforms.Normalize(mean=[0.4711, 0.4475, 0.4080], std=[0.1223, 0.1221, 0.1450]) #visdial \n transform = transforms.Compose([ transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize])\n \n dataset = VisualDialogDataset(mode, args, with_options, transform)\n dataset.load_dictionary(shared_dictionary)\n dataset.load_data()\n\n return dataset\n\ndef get_dataloader(mode, args, shared_dictionary=None, with_options=True):\n\n loader = torch.utils.data.DataLoader(\n build_dataset(mode, args, shared_dictionary, with_options),\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=False)\n \n nelements = len(loader.dataset)\n \n return loader\n\ndef get_mask(human_set_mask, human_set_only=True):\n if human_set_only:\n if torch.sum(human_set_mask) == 0:\n return None\n else:\n return human_set_mask\n else:\n return torch.ones_like(human_set_mask)\n\ndef get_flat_features(loader, args, human_set_only=False):\n \n print('flattening {:} features...'.format(loader.dataset.mode))\n\n if human_set_only:\n return get_flat_human_features(loader, args)\n else:\n return get_flat_full_features(loader, args)\n\ndef get_flat_human_features(loader, args):\n \n avg_fn = loader.dataset.get_avg_embedding\n E = loader.dataset.dictionary.emb_size\n questions, answers = [], []\n for i, batch in enumerate(loader):\n\n sys.stdout.write('\\r{}/{} --> {:3.1f}%'.format(str(i+1), str(len(loader)), (i+1)/float(len(loader))*100))\n sys.stdout.flush()\n\n mask = get_mask(batch['in_human_set'])\n\n if isinstance(mask, torch.Tensor):\n bsz = mask.sum()\n batch = utils.send_to_device(batch, args.gpu)\n human_scores = batch['answer_options_scores'][mask].view(bsz,-1,100)\n cluster_mask = (human_scores > 0)\n cluster_mask.scatter_(2, batch['gtidxs'][mask].view(bsz,-1, 1), 1)\n cluster_sizes = cluster_mask.sum(dim=2).view(bsz)\n\n emb_question = avg_fn(batch['questions_ids'][mask].view(bsz,-1,args.S), batch['questions_length'][mask].view(bsz,-1)).cpu()\n emb_answer_set = avg_fn(batch['answer_options_ids'][mask].view(-1,100,args.S), batch['answer_options_length'][mask].view(-1,100))\n emb_answer_set = emb_answer_set.view(bsz,-1,100,E)\n emb_cluster_set = emb_answer_set[cluster_mask].cpu()\n\n batch_idx, counter = 0, 1\n acc_cluster_sizes = torch.cumsum(cluster_sizes, dim=0)\n for emb_answer in emb_cluster_set:\n questions.append(emb_question[batch_idx])\n answers.append(emb_answer)\n if counter == acc_cluster_sizes[batch_idx]:\n batch_idx += 1\n counter += 1\n \n sys.stdout.write(\"\\n\")\n questions = torch.stack(questions)\n answers = torch.stack(answers)\n \n return [ answers.view(-1, E), questions.view(-1, E)]\n\ndef get_flat_full_features(loader, args):\n\n avg_fn = loader.dataset.get_avg_embedding\n E = loader.dataset.dictionary.emb_size\n questions = torch.FloatTensor(loader.dataset.N, args.D, E)\n answers = torch.FloatTensor(loader.dataset.N, args.D, E)\n for i, batch in enumerate(loader):\n\n sys.stdout.write('\\r{}/{} --> {:3.1f}%'.format(str(i+1), str(len(loader)), (i+1)/float(len(loader))*100))\n sys.stdout.flush()\n\n batch = utils.send_to_device(batch, args.gpu)\n bsz = batch['questions_ids'].size(0)\n questions[i*loader.batch_size:i*loader.batch_size+bsz] = avg_fn(batch['questions_ids'], batch['questions_length']).cpu()\n answers[i*loader.batch_size:i*loader.batch_size+bsz] = avg_fn(batch['answers_ids'], batch['answers_length']).cpu()\n \n sys.stdout.write(\"\\n\")\n \n return [ answers.view(-1, E), questions.view(-1, E)]\n" ]
[ [ "torch.ones_like", "torch.sum", "torch.FloatTensor", "torch.stack", "torch.cumsum" ] ]
jbeomlee93/BBAM
[ "bebd2358d0497960c9a8415e5dca8de4a25fd899" ]
[ "tools/BBAM/BBAM_utils.py" ]
[ "import torch\nfrom torch.autograd import Variable\nfrom torchvision import models\nimport cv2\nimport sys\nimport numpy as np\nimport os\nimport math\nimport torch.nn.functional as F\n\nidx_to_class = {0 : 'aeroplane', 1 : 'bicycle', 2 : 'bird', 3 : 'boat', 4 : 'bottle', 5 : 'bus', 6 : 'car', 7 : 'cat',\n 8 : 'chair', 9 : 'cow', 10 : 'table', 11 : 'dog', 12 : 'horse', 13 : 'motorbike', 14 : 'person',\n 15 : 'plant', 16 : 'sheep', 17 : 'sofa', 18 : 'train', 19 : 'monitor'}\n\n\ndef tv_norm(input, tv_beta, diagonal=False, sum=False):\n # print(input.shape)\n img = input[0, :]\n if sum:\n row_grad = torch.sum(torch.abs((img[:-1 , :] - img[1 :, :])).pow(tv_beta))\n col_grad = torch.sum(torch.abs((img[: , :-1] - img[: , 1 :])).pow(tv_beta))\n else:\n row_grad = torch.mean(torch.abs((img[:-1, :] - img[1:, :])).pow(tv_beta))\n col_grad = torch.mean(torch.abs((img[:, :-1] - img[:, 1:])).pow(tv_beta))\n if diagonal:\n diag = 0\n if sum:\n diag += torch.sum(torch.abs((img[:-1, :-1] - img[1:, 1:])).pow(tv_beta))\n diag += torch.sum(torch.abs((img[1:, :-1] - img[:-1, 1:])).pow(tv_beta))\n diag += torch.sum(torch.abs((img[:-1, 1:] - img[1:, :-1])).pow(tv_beta))\n diag += torch.sum(torch.abs((img[1:, 1:] - img[:-1, :-1])).pow(tv_beta))\n else:\n diag += torch.mean(torch.abs((img[:-1, :-1] - img[1:, 1:])).pow(tv_beta))\n diag += torch.mean(torch.abs((img[1:, :-1] - img[:-1, 1:])).pow(tv_beta))\n diag += torch.mean(torch.abs((img[:-1, 1:] - img[1:, :-1])).pow(tv_beta))\n diag += torch.mean(torch.abs((img[1:, 1:] - img[:-1, :-1])).pow(tv_beta))\n return row_grad + col_grad + diag\n return row_grad + col_grad\n\n\ndef numpy_to_torch(img, requires_grad = True, cuda_device=None):\n\n use_cuda = torch.cuda.is_available()\n if len(img.shape) < 3:\n output = np.float32([img])\n else:\n output = np.expand_dims(img, axis=1)\n # output = np.transpose(img, (2, 0, 1))\n\n output = torch.from_numpy(output)\n if use_cuda:\n if cuda_device==None:\n output = output.cuda()\n else:\n output = output.cuda(cuda_device)\n\n\n # output = output.repeat(3, 1, 1)\n v = Variable(output, requires_grad = requires_grad)\n # v = v.repeat(3, 1, 1)\n\n return v\ncolor_dicts = [\n [0.6, 0, 0.05],\n [0.03, 0.19, 0.42],\n [0, 0.27, 0.11],\n [0.24, 0, 0.49],\n [0.5, 0.25, 0.02],\n [1, 0.5, 0],\n [0.2, 0.2, 0.2],\n [1, 0.1, 0.6],\n [0.8, 0.8, 0]\n]\ndef save_pred(image, boxes, save_path, image_id):\n image[0] += 102.9801\n image[1] += 115.9465\n image[2] += 122.7717\n image = image.data.cpu().numpy().transpose(1, 2, 0).astype('uint8')\n\n for coord_idx, coords in enumerate(boxes):\n image = cv2.UMat(image).get()\n color = color_dicts[coord_idx%len(color_dicts)]\n color = [int(c*255.0) for c in color]\n color = color[::-1]\n image = cv2.rectangle(image, (int(coords[0]), int(coords[1])),\n (int(coords[2]), int(coords[3])), color, 5)\n\n save_name = '%s/%s/box_prediction.jpg' % (save_path, image_id)\n cv2.imwrite(save_name, image)\n\ndef save_mask(mask, masked_img=None, proposal=None, original_coord=None, perturbed_coord=None, iteration=None, proposal_idx=None, image_id=None, class_name=None, save_path_root=None, single_p_idx=None):\n\n if not (masked_img is None):\n masked_img[0] += 102.9801\n masked_img[1] += 115.9465\n masked_img[2] += 122.7717\n masked_img = masked_img.data.cpu().numpy().transpose(1, 2, 0).astype('uint8')\n mask = (255*mask.data.cpu().numpy().transpose(1, 2, 0)).astype('uint8')\n color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] # blue: proposal, green: unturbed, red_ perturbed\n\n if (proposal is not None) and (original_coord is not None) and (perturbed_coord is None):\n for coord_idx, coords in enumerate([proposal, original_coord]):\n coords = coords.detach().data.cpu().numpy()\n\n masked_img = cv2.UMat(masked_img).get()\n masked_img = cv2.rectangle(masked_img, (int(coords[0]), int(coords[1])),\n (int(coords[2]), int(coords[3])), color[coord_idx], 5)\n\n\n if not((proposal is None) or (original_coord is None) or (perturbed_coord is None)):\n for coord_idx, coords in enumerate([proposal, original_coord, perturbed_coord]):\n coords = coords.detach().data.cpu().numpy()\n\n masked_img = cv2.UMat(masked_img).get()\n masked_img = cv2.rectangle(masked_img, (int(coords[0]), int(coords[1])),\n (int(coords[2]), int(coords[3])), color[coord_idx], 5)\n\n\n\n if not (masked_img is None):\n masked_img = cv2.resize(masked_img, None, fx=0.5, fy=0.5)\n mask = cv2.resize(mask, (masked_img.shape[1], masked_img.shape[0]))\n if single_p_idx is None:\n save_path = '%s/%s/pidx_%04d_%s/' % (save_path_root, image_id, proposal_idx, class_name)\n else:\n save_path = '%s/%s/pidx_%04d_%s/' % (save_path_root, image_id, proposal_idx, class_name)\n\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n if single_p_idx is None:\n if not (masked_img is None):\n cv2.imwrite('%s/iter_%04d.jpg' % (save_path, iteration), masked_img)\n cv2.imwrite('%s/iter_%04d_mask.jpg' % (save_path, iteration), mask)\n else:\n if not (masked_img is None):\n cv2.imwrite('%s/pidx_%04d_img.jpg' % (save_path, single_p_idx), masked_img)\n cv2.imwrite('%s/pidx_%04d_mask.jpg' % (save_path, single_p_idx), mask)\n\n\ndef get_max_iou(source, targets):\n # target: multiple boxes\n\n maxIoU = 0\n for target in targets.bbox:\n bb1, bb2 = {}, {}\n bb1['x1'], bb1['x2'] = int(source[0]), int(source[2])\n bb1['y1'], bb1['y2'] = int(source[1]), int(source[3])\n bb2['x1'], bb2['x2'] = int(target[0]), int(target[2])\n bb2['y1'], bb2['y2'] = int(target[1]), int(target[3])\n # determine the coordinates of the intersection rectangle\n x_left = max(bb1['x1'], bb2['x1'])\n y_top = max(bb1['y1'], bb2['y1'])\n x_right = min(bb1['x2'], bb2['x2'])\n y_bottom = min(bb1['y2'], bb2['y2'])\n\n if not(x_right < x_left or y_bottom < y_top):\n\n # The intersection of two axis-aligned bounding boxes is always an\n # axis-aligned bounding box\n intersection_area = (x_right - x_left) * (y_bottom - y_top)\n\n # compute the area of both AABBs\n bb1_area = (bb1['x2'] - bb1['x1']) * (bb1['y2'] - bb1['y1'])\n bb2_area = (bb2['x2'] - bb2['x1']) * (bb2['y2'] - bb2['y1'])\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = intersection_area / float(bb1_area + bb2_area - intersection_area)\n assert iou >= 0.0\n assert iou <= 1.0\n if maxIoU < iou:\n maxIoU = iou\n return maxIoU\n\ndef get_single_iou(source, target):\n # target: multiple boxes\n\n maxIoU = 0\n\n\n bb1, bb2 = {}, {}\n bb1['x1'], bb1['x2'] = int(source[0]), int(source[2])\n bb1['y1'], bb1['y2'] = int(source[1]), int(source[3])\n bb2['x1'], bb2['x2'] = int(target[0]), int(target[2])\n bb2['y1'], bb2['y2'] = int(target[1]), int(target[3])\n # determine the coordinates of the intersection rectangle\n x_left = max(bb1['x1'], bb2['x1'])\n y_top = max(bb1['y1'], bb2['y1'])\n x_right = min(bb1['x2'], bb2['x2'])\n y_bottom = min(bb1['y2'], bb2['y2'])\n\n if x_right < x_left or y_bottom < y_top:\n return 0.0\n\n # The intersection of two axis-aligned bounding boxes is always an\n # axis-aligned bounding box\n intersection_area = (x_right - x_left) * (y_bottom - y_top)\n\n # compute the area of both AABBs\n bb1_area = (bb1['x2'] - bb1['x1']) * (bb1['y2'] - bb1['y1'])\n bb2_area = (bb2['x2'] - bb2['x1']) * (bb2['y2'] - bb2['y1'])\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = intersection_area / float(bb1_area + bb2_area - intersection_area)\n\n return iou\n\ndef selected_positives(ious, pred_classes, displacements, proposal_iter):\n ious, pred_classes, displacements = np.array(ious), np.array(pred_classes), np.array(displacements)\n top_ious = np.argsort(-ious)\n top_displacement = np.argsort(-displacements)\n\n\n # include top 30%\n positive_idxs = list(top_ious[:int(proposal_iter * 0.3)])\n for d in top_displacement:\n if ious[d] > 0.8:\n positive_idxs.append(d)\n\n return positive_idxs[:proposal_iter]\n\ndef imsmooth(tensor,\n sigma,\n stride=1,\n padding=0,\n padding_mode='constant',\n padding_value=0):\n \"From TorchRay (https://github.com/facebookresearch/TorchRay)\"\n assert sigma >= 0\n width = math.ceil(4 * sigma)\n SQRT_TWO_DOUBLE = torch.tensor(math.sqrt(2), dtype=torch.float32)\n SQRT_TWO_SINGLE = SQRT_TWO_DOUBLE.to(torch.float32)\n EPSILON_SINGLE = torch.tensor(1.19209290E-07, dtype=torch.float32)\n\n filt = (torch.arange(-width,\n width + 1,\n dtype=torch.float32,\n device=tensor.device) /\n (SQRT_TWO_SINGLE * sigma + EPSILON_SINGLE))\n filt = torch.exp(-filt * filt)\n filt /= torch.sum(filt)\n num_channels = tensor.shape[1]\n width = width + padding\n if padding_mode == 'constant' and padding_value == 0:\n other_padding = width\n x = tensor\n else:\n # pad: (before, after) pairs starting from last dimension backward\n x = F.pad(tensor,\n (width, width, width, width),\n mode=padding_mode,\n value=padding_value)\n other_padding = 0\n padding = 0\n x = F.conv2d(x,\n filt.reshape((1, 1, -1, 1)).expand(num_channels, -1, -1, -1),\n padding=(other_padding, padding),\n stride=(stride, 1),\n groups=num_channels)\n x = F.conv2d(x,\n filt.reshape((1, 1, 1, -1)).expand(num_channels, -1, -1, -1),\n padding=(padding, other_padding),\n stride=(1, stride),\n groups=num_channels)\n return x\n\n\nclass MaskGenerator:\n r\"\"\"Mask generator.\n The class takes as input the mask parameters and returns\n as output a mask.\n Args:\n shape (tuple of int): output shape.\n step (int): parameterization step in pixels.\n sigma (float): kernel size.\n clamp (bool, optional): whether to clamp the mask to [0,1]. Defaults to True.\n pooling_mehtod (str, optional): `'softmax'` (default), `'sum'`, '`sigmoid`'.\n Attributes:\n shape (tuple): the same as the specified :attr:`shape` parameter.\n shape_in (tuple): spatial size of the parameter tensor.\n shape_out (tuple): spatial size of the output mask including margin.\n \"\"\"\n\n def __init__(self, shape, step, sigma, clamp=True, pooling_method='softmax'):\n self.shape = shape\n self.step = step\n self.sigma = sigma\n self.coldness = 20\n self.clamp = clamp\n self.pooling_method = pooling_method\n\n assert int(step) == step\n\n # self.kernel = lambda z: (z < 1).float()\n self.kernel = lambda z: torch.exp(-2 * ((z - .5).clamp(min=0)**2))\n\n self.margin = self.sigma\n # self.margin = 0\n self.padding = 1 + math.ceil((self.margin + sigma) / step)\n self.radius = 1 + math.ceil(sigma / step)\n self.shape_in = [math.ceil(z / step) for z in self.shape]\n self.shape_mid = [\n z + 2 * self.padding - (2 * self.radius + 1) + 1\n for z in self.shape_in\n ]\n self.shape_up = [self.step * z for z in self.shape_mid]\n self.shape_out = [z - step + 1 for z in self.shape_up]\n\n self.weight = torch.zeros((\n 1,\n (2 * self.radius + 1)**2,\n self.shape_out[0],\n self.shape_out[1]\n ))\n\n step_inv = [\n torch.tensor(zm, dtype=torch.float32) /\n torch.tensor(zo, dtype=torch.float32)\n for zm, zo in zip(self.shape_mid, self.shape_up)\n ]\n\n for ky in range(2 * self.radius + 1):\n for kx in range(2 * self.radius + 1):\n uy, ux = torch.meshgrid(\n torch.arange(self.shape_out[0], dtype=torch.float32),\n torch.arange(self.shape_out[1], dtype=torch.float32)\n )\n iy = torch.floor(step_inv[0] * uy) + ky - self.padding\n ix = torch.floor(step_inv[1] * ux) + kx - self.padding\n\n delta = torch.sqrt(\n (uy - (self.margin + self.step * iy))**2 +\n (ux - (self.margin + self.step * ix))**2\n )\n\n k = ky * (2 * self.radius + 1) + kx\n\n self.weight[0, k] = self.kernel(delta / sigma)\n\n def generate(self, mask_in):\n r\"\"\"Generate a mask.\n The function takes as input a parameter tensor :math:`\\bar m` for\n :math:`K` masks, which is a :math:`K\\times 1\\times H_i\\times W_i`\n tensor where `H_i\\times W_i` are given by :attr:`shape_in`.\n Args:\n mask_in (:class:`torch.Tensor`): mask parameters.\n Returns:\n tuple: a pair of mask, cropped and full. The cropped mask is a\n :class:`torch.Tensor` with the same spatial shape :attr:`shape`\n as specfied upon creating this object. The second mask is the same,\n but with an additional margin and shape :attr:`shape_out`.\n \"\"\"\n mask = F.unfold(mask_in,\n (2 * self.radius + 1,) * 2,\n padding=(self.padding,) * 2)\n mask = mask.reshape(\n len(mask_in), -1, self.shape_mid[0], self.shape_mid[1])\n mask = F.interpolate(mask, size=self.shape_up, mode='nearest')\n mask = F.pad(mask, (0, -self.step + 1, 0, -self.step + 1))\n mask = self.weight * mask\n\n if self.pooling_method == 'sigmoid':\n if self.coldness == float('+Inf'):\n mask = (mask.sum(dim=1, keepdim=True) - 5 > 0).float()\n else:\n mask = torch.sigmoid(\n self.coldness * mask.sum(dim=1, keepdim=True) - 3\n )\n elif self.pooling_method == 'softmax':\n if self.coldness == float('+Inf'):\n mask = mask.max(dim=1, keepdim=True)[0]\n else:\n mask = (\n mask * F.softmax(self.coldness * mask, dim=1)\n ).sum(dim=1, keepdim=True)\n\n elif self.pooling_method == 'sum':\n mask = mask.sum(dim=1, keepdim=True)\n else:\n assert False, f\"Unknown pooling method {self.pooling_method}\"\n m = round(self.margin)\n if self.clamp:\n mask = mask.clamp(min=0, max=1)\n cropped = mask[:, :, m:m + self.shape[0], m:m + self.shape[1]]\n return cropped, mask\n\n def to(self, dev):\n \"\"\"Switch to another device.\n Args:\n dev: PyTorch device.\n Returns:\n MaskGenerator: self.\n \"\"\"\n self.weight = self.weight.to(dev)\n return self\n\n" ]
[ [ "torch.nn.functional.softmax", "numpy.argsort", "torch.sqrt", "torch.cuda.is_available", "torch.floor", "torch.nn.functional.pad", "torch.autograd.Variable", "torch.from_numpy", "numpy.expand_dims", "torch.arange", "torch.nn.functional.unfold", "torch.tensor", "numpy.float32", "numpy.array", "torch.sum", "torch.exp", "torch.abs", "torch.zeros", "torch.nn.functional.interpolate" ] ]
rdenaux/acred
[ "ee45840c942ef2fac4f26da8d756b7c47e42847c" ]
[ "scripts/pred_coinfo250.py" ]
[ "#\n# 2020 ExpertSystem\n#\n'''Script for generating predictions for the coinform250 dataset\n using the acred predictor\n\nSee https://github.com/co-inform/Datasets\n\nSee also scripts/fetch-data.sh, which should download the input json file\nand place it in the `data/evaluation/` folder.\n'''\nimport argparse\nimport time\nimport json\nimport os\nimport os.path as osp\nimport requests\nimport traceback\nimport pandas as pd\n\n\ndef ensure_req_tweet_content(req):\n for t in req['tweets']:\n c = t['content']\n if c is None:\n t['content'] = ''\n print('Fixed null content')\n\ndef acred_as_coinfo_label(credreview, thresh=0.4):\n assert thresh >= 0.0\n assert thresh <= 1.0\n conf = credreview['reviewRating']['confidence']\n if conf <= thresh:\n return 'not_verifiable'\n \n val = credreview['reviewRating']['ratingValue']\n if val >= 0.5:\n return 'credible'\n if val >= 0.25:\n return 'mostly_credible'\n if val >= -0.25:\n return 'credible_uncertain'\n if val >= -0.5:\n return 'credible_uncertain'\n return 'not_credible'\n\n\ndef exec_req(i, req, args):\n print('\\n\\nExecuting request %s' % (i))\n\n ensure_req_tweet_content(req)\n req['reviewFormat'] = 'schema.org'\n\n start = time.time()\n resp = requests.post(args.credpred_url, json=req,\n verify=False,\n timeout=args.req_timeout)\n result = []\n if resp.ok:\n respd = resp.json()\n result = [{\n 'tweet_id': request['tweet_id'],\n 'ratingValue': r['reviewRating']['ratingValue'],\n 'confidence': r['reviewRating']['confidence'],\n 'label': acred_as_coinfo_label(r)\n } for request, r in zip(req['tweets'], respd)]\n resp_f = 'coinform250_%s.json' % i\n with open('%s/%s' % (args.outDir, resp_f), 'w') as outf:\n json.dump(respd, outf)\n else:\n print(\"Failed: %s %s\" % (str(resp), resp.text)) \n\n print('Processed in %ss.' % (time.time() - start))\n return result\n\n\ndef as_acred_requests(tweets, batchSize=5):\n batch = []\n for i, t in enumerate(tweets):\n batch.append({\n 'content': t['full_text'],\n 'tweet_id': t['id'],\n 'url': 'https://twitter.com/x/status/%s' % (t['id'])})\n if len(batch) == batchSize:\n yield {'tweets': batch,\n 'source': 'coinform250.json',\n 'batch_id': '%s-%s' % (i-batchSize, i)}\n batch = []\n if len(batch) > 0:\n yield {'tweets': batch,\n 'source': 'coinform250.json',\n 'batch_id': '%s-%s' % (len(tweets) - len(batch), len(tweets))}\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Generate tweet credibility predictions for a dir with requests',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n '-inputJson',\n help='Path to the coinform250.json file',\n required=True)\n parser.add_argument(\n '-batchSize', type=int, default=5,\n help='Number of tweets to send per request to acred endpoint')\n parser.add_argument(\n '-outDir',\n help='Path to a local dir where the CredibilityReviews will be stored',\n required=True)\n parser.add_argument(\n '-credpred_url',\n help='URL of the acred endpoint for the tweet credibility')\n parser.add_argument(\n '-credpred_id',\n help='ID of the generation task')\n parser.add_argument(\n '-req_timeout',\n type=int, default=90,\n help='Seconds to wait for a response')\n\n args = parser.parse_args()\n\n all_start = time.time()\n\n assert osp.isdir(osp.join(args.outDir))\n assert osp.isfile(args.inputJson)\n tweets = []\n with open(args.inputJson) as jsonl_file:\n tweets = [json.loads(line) for line in jsonl_file]\n assert len(tweets) > 0, '%s' % (len(tweets))\n \n print('Reviewing credibility of %s tweets using batchSize %s' % (len(tweets), args.batchSize))\n\n preds = []\n for i, req in enumerate(as_acred_requests(tweets, args.batchSize)):\n try:\n preds.extend(exec_req(i, req, args))\n except Exception as e:\n print('Error executing request %s %s %s' % (i, req, str(e)))\n print(traceback.format_exc())\n\n pd.DataFrame(preds).to_csv('%s/%s.csv' % (args.outDir, 'predictions'), index=False)\n print('Finished in %.3fs' % (time.time() - all_start))\n" ]
[ [ "pandas.DataFrame" ] ]
xcnick/TurboTransformers
[ "48b6ba09af2219616c6b97cc5c09222408e080c2" ]
[ "turbo_transformers/python/tests/bert_model_test.py" ]
[ "# Copyright (C) 2020 THL A29 Limited, a Tencent company.\n# All rights reserved.\n# Licensed under the BSD 3-Clause License (the \"License\"); you may\n# not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n# https://opensource.org/licenses/BSD-3-Clause\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\n# implied. See the License for the specific language governing\n# permissions and limitations under the License.\n# See the AUTHORS file for names of contributors.\n\nimport unittest\nimport torch\nfrom transformers.modeling_bert import BertModel, BertConfig\nimport numpy\nimport turbo_transformers\nimport sys\nimport os\n\nsys.path.append(os.path.dirname(__file__))\nimport test_helper\n\n\nclass TestBertModel(unittest.TestCase):\n def init_data(self, use_cuda) -> None:\n torch.set_grad_enabled(False)\n torch.set_num_threads(4)\n turbo_transformers.set_num_threads(4)\n self.test_device = torch.device('cuda:0') if use_cuda else \\\n torch.device('cpu:0')\n\n self.cfg = BertConfig()\n self.torch_model = BertModel(self.cfg)\n self.torch_model.eval()\n\n if torch.cuda.is_available():\n self.torch_model.to(self.test_device)\n\n self.turbo_model = turbo_transformers.BertModel.from_torch(\n self.torch_model, self.test_device, \"turbo\", use_memory_opt=True)\n\n def check_torch_and_turbo(self,\n use_cuda,\n batch_size,\n seq_len,\n use_memory_opt=True):\n self.init_data(use_cuda)\n num_iter = 1\n device_name = \"GPU\" if use_cuda else \"CPU\"\n input_ids = torch.randint(low=0,\n high=self.cfg.vocab_size - 1,\n size=(batch_size, seq_len),\n dtype=torch.long,\n device=self.test_device)\n\n torch_model = lambda: self.torch_model(input_ids)\n torch_result, torch_qps, torch_time = \\\n test_helper.run_model(torch_model, use_cuda, num_iter)\n print(f'BertModel PyTorch({device_name}) QPS {torch_qps}')\n\n turbo_model = (lambda: self.turbo_model(input_ids))\n\n if use_memory_opt:\n turbo_transformers.bert_opt_mem_allocate_api(\n input_ids.size()[0], # batch\n input_ids.size()[1], # seq_len\n self.cfg.num_attention_heads,\n self.cfg.hidden_size,\n self.cfg.num_hidden_layers,\n \"GPU\" if 'cuda' in input_ids.device.type else \"CPU\")\n\n with turbo_transformers.pref_guard(\"bert_perf\") as perf:\n turbo_result, turbo_qps, turbo_time = \\\n test_helper.run_model(turbo_model, use_cuda, num_iter)\n print(f'BertModel TurboTransformer({device_name}) QPS {turbo_qps}')\n\n # set the allocator back to naive, otherwise it will affect\n # the other inference processes.\n if use_memory_opt:\n turbo_transformers.reset_allocator_schema(\"naive\")\n\n print(f\"batch {batch_size} seq_len {seq_len}\")\n print(torch.max(torch_result[0].cpu() - turbo_result[0].cpu()))\n self.assertTrue(\n numpy.allclose(torch_result[0].cpu(),\n turbo_result[0].cpu(),\n atol=1e-2,\n rtol=1e-3))\n\n def test_bert_model_helper(self, use_memory_opt=False):\n if use_memory_opt:\n turbo_transformers.reset_allocator_schema(\"model-aware\")\n\n for batch_size in [1, 4, 20]:\n for seq_len in [50, 4, 16]:\n if torch.cuda.is_available() and \\\n turbo_transformers.config.is_compiled_with_cuda():\n self.check_torch_and_turbo(use_cuda=True,\n batch_size=batch_size,\n seq_len=seq_len,\n use_memory_opt=use_memory_opt)\n self.check_torch_and_turbo(use_cuda=False,\n batch_size=batch_size,\n seq_len=seq_len,\n use_memory_opt=use_memory_opt)\n\n if use_memory_opt:\n turbo_transformers.reset_allocator_schema(\"naive\")\n\n def test_bert_model(self, use_memory_opt=False):\n self.test_bert_model_helper(True)\n self.test_bert_model_helper(False)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "torch.randint", "torch.set_grad_enabled", "torch.set_num_threads", "torch.cuda.is_available", "torch.device" ] ]
evgeny-izutov/open_model_zoo
[ "2cd6145ef342fc9b7ccf32676af73f4a1cb8d9ba" ]
[ "tools/accuracy_checker/accuracy_checker/annotation_converters/cluttered_mnist.py" ]
[ "\"\"\"\nCopyright (c) 2018-2020 Intel Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\nfrom .format_converter import BaseFormatConverter, ConverterReturn\nfrom ..config import PathField, StringField, BoolField\nfrom ..representation import ClassificationAnnotation\n\n\nclass ClutteredMNISTConverter(BaseFormatConverter):\n __provider__ = 'cluttered_mnist'\n\n @classmethod\n def parameters(cls):\n params = super().parameters()\n params.update({\n 'data_file': PathField(),\n 'split': StringField(optional=True, default='test', choices=['train', 'valid', 'test']),\n 'convert_images': BoolField(optional=True, default=True),\n 'images_dir': PathField(is_directory=True, optional=True)\n\n })\n return params\n\n def configure(self):\n self.data_file = self.get_value_from_config('data_file')\n self.split = self.get_value_from_config('split')\n self.convert_images = self.get_value_from_config('convert_images')\n self.images_dir = self.get_value_from_config('images_dir') or self.data_file.parent / 'converted_images'\n if self.convert_images and not self.images_dir.exists():\n self.images_dir.mkdir(parents=True)\n\n def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs):\n data = np.load(str(self.data_file))\n x_values = data['x_{}'.format(self.split)]\n y_values = data['y_{}'.format(self.split)]\n annotations = []\n for idx, y in enumerate(y_values):\n identifier = '{}_{}.png'.format(self.split, idx)\n y_label = np.argmax(y)\n if self.convert_images:\n x = x_values[idx].reshape((60, 60)) * 255\n image = Image.fromarray(x)\n image = image.convert(\"L\")\n image.save(str(self.images_dir / identifier))\n annotations.append(ClassificationAnnotation(identifier, y_label))\n return ConverterReturn(annotations, None, None)\n" ]
[ [ "numpy.argmax" ] ]
esayyari/empress
[ "092044d4444a1569784cd9d336eb2a2a44a92abc" ]
[ "empress/tree.py" ]
[ "# ----------------------------------------------------------------------------\n# Copyright (c) 2016-2020, empress development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport warnings\nfrom skbio import TreeNode\nimport numpy as np\nfrom bp import BP, from_skbio_treenode\n\n\nclass TreeFormatWarning(Warning):\n pass\n\n\nclass Tree:\n \"\"\"\n Attributes\n ----------\n length\n leafcount\n height\n depth\n\n Notes\n -----\n `length` refers to the branch length of a node to its parent.\n `leafcount` is the number of tips within a subtree. `height` refers\n to the longest path from root to the deepst leaf in that subtree.\n `depth` is the number of nodes found in the longest path.\n \"\"\"\n\n def __init__(self, bp_tree):\n \"\"\" Constructs a Dendrogram object for visualization.\n\n Parameters\n ----------\n bp_tree: bp.BP\n BP tree object\n\n Returns\n -------\n\n \"\"\"\n self.bp_tree = bp_tree\n self.B = self.bp_tree.B\n self.leafcounts = np.zeros(self.B.size, np.int)\n self.depths = np.zeros(self.B.size, np.double)\n self.heights = np.zeros(self.B.size, np.double)\n self.yr = np.zeros(self.B.size, np.double)\n self.xr = np.zeros(self.B.size, np.double)\n self.highest_child_yr = np.zeros(self.B.size, np.float)\n self.lowest_child_yr = np.zeros(self.B.size, np.float)\n self.clangle = np.zeros(self.B.size, np.double)\n self.clradius = np.zeros(self.B.size, np.double)\n self.xc0 = np.zeros(self.B.size, np.double)\n self.yc0 = np.zeros(self.B.size, np.double)\n self.xc1 = np.zeros(self.B.size, np.double)\n self.yc1 = np.zeros(self.B.size, np.double)\n self.highest_child_clangle = np.zeros(self.B.size, np.float)\n self.lowest_child_clangle = np.zeros(self.B.size, np.float)\n self.arcx0 = np.zeros(self.B.size, np.double)\n self.arcy0 = np.zeros(self.B.size, np.double)\n self.arcx1 = np.zeros(self.B.size, np.double)\n self.arcy1 = np.zeros(self.B.size, np.double)\n self.x1 = np.zeros(self.B.size, np.double)\n self.y1 = np.zeros(self.B.size, np.double)\n self.x2 = np.zeros(self.B.size, np.double)\n self.y2 = np.zeros(self.B.size, np.double)\n self.angle = np.zeros(self.B.size, np.double)\n self.childRem = -1\n\n @classmethod\n def from_tree(cls, tree, use_lengths=True):\n \"\"\" Creates an Tree object from a skbio tree.\n\n Parameters\n ----------\n tree : skbio.TreeNode\n Input skbio tree\n use_lengths: Boolean\n Specify if the branch length should be incorporated into\n the geometry calculations for visualization.\n Returns\n -------\n Tree: bp.BP\n\n \"\"\"\n bp_tree = from_skbio_treenode(tree)\n if sum(bp_tree.B) <= 1:\n raise ValueError(\"Tree must contain at least 2 nodes.\")\n\n # While traversing the tree, record tip / internal node names\n # (Nodes without names are ignored, since we'll assign those later\n # using tools.fill_missing_node_names())\n tip_names = []\n internal_node_names = []\n max_branch_length = 0\n for i in range(sum(bp_tree.B)):\n node_idx = bp_tree.postorderselect(i)\n name = bp_tree.name(node_idx)\n length = bp_tree.length(node_idx)\n if name is not None:\n # NOTE: This should eventually be taken out when\n # fill_missing_node_names() is refactored. However, for now,\n # this makes sure that users can't accidentally break things by\n # naming nodes identical to our default names for missing nodes\n if name.startswith(\"EmpressNode\"):\n raise ValueError(\n 'Node names can\\'t start with \"EmpressNode\".'\n )\n if isleaf(bp_tree, node_idx):\n tip_names.append(name)\n else:\n internal_node_names.append(name)\n if length is None:\n raise ValueError(\n \"Non-root branches of the tree must have lengths.\"\n )\n if length < 0:\n raise ValueError(\n \"Non-root branches of the tree must have nonnegative \"\n \"lengths.\"\n )\n\n max_branch_length = max(length, max_branch_length)\n\n # We didn't consider the root node in the above traversal since we\n # don't care about its length. However, we do care about its name,\n # so we add the root's name to internal_node_names.\n\n if max_branch_length == 0:\n raise ValueError(\n \"At least one non-root branch of the tree must have a \"\n \"positive length.\"\n )\n unique_tip_name_set = set(tip_names)\n if len(unique_tip_name_set) != len(tip_names):\n raise ValueError(\"Tip names in the tree must be unique.\")\n\n unique_internal_node_name_set = set(internal_node_names)\n if len(unique_tip_name_set & unique_internal_node_name_set) > 0:\n raise ValueError(\n \"Tip names in the tree cannot overlap with internal node \"\n \"names.\"\n )\n\n if len(unique_internal_node_name_set) != len(internal_node_names):\n warnings.warn(\n \"Internal node names in the tree are not unique.\",\n TreeFormatWarning\n )\n bp_tree = Tree(bp_tree)\n bp_tree.update_geometry(use_lengths)\n return bp_tree\n\n def postorder(self, include_self=True):\n e = sum(self.B) if include_self else sum(self.B) - 1\n for i in range(e):\n node_idx = self.bp_tree.postorderselect(i)\n yield node_idx\n\n def preorder(self, include_self=True):\n s = 0 if include_self else 1\n for i in range(s, sum(self.B)):\n node_idx = self.bp_tree.preorderselect(i)\n yield node_idx\n\n def bp_tree_tips(self):\n \"\"\" Extracts tip names in the tree, ignoring unnamed tips.\n\n Parameters\n ----------\n bp_tree : bp.BP\n Input BP tree\n Returns\n -------\n tips : list of strings\n list of tip names in the tree\n \"\"\"\n tips = []\n # Iterate through all open and closing parentheses and extract tip names\n for i in range(self.B.size):\n pos_name = self.bp_tree.name(i)\n # Check if this is a leaf node with a label\n if self.isleaf(i) and (pos_name is not None):\n tips.append(pos_name)\n return tips\n\n def bp_tree_non_tips(self):\n \"\"\" Extracts internal node names in the tree, ignoring unnamed nodes.\n\n Parameters\n ----------\n bp_tree : bp.BP\n Input BP tree\n Returns\n -------\n non_tips : list of strings\n list of internal node names in the tree\n \"\"\"\n non_tips = []\n for i in range(self.B.size):\n pos_name = self.bp_tree.name(i)\n # Check if this is an opening parenthesis, is not a leaf, and\n # has a node label\n if self.B[i] and not self.isleaf(i) and pos_name is not None:\n non_tips.append(pos_name)\n return non_tips\n\n def update_geometry(self, use_lengths, depth=None):\n \"\"\"Calculate tree node attributes such as height and depth.\n\n Parameters\n ----------\n use_lengths: bool\n Specify if the branch length should be incorporated into\n the geometry calculations for visualization.\n depth: int\n The number of nodes in the longest path from root to leaf.\n This is agnostic to scale and orientation.\n\n \"\"\"\n new_heights = np.zeros(self.B.size, dtype=np.double)\n new_leaf_count = np.zeros(self.B.size, dtype=np.int)\n new_depths = np.zeros(self.B.size, dtype=np.double)\n for node_idx in self.postorder():\n length = self.bp_tree.length(node_idx)\n if length is None or not use_lengths:\n if not use_lengths:\n if self.isleaf(node_idx):\n length = 5\n else:\n length = 1\n else:\n length = 0\n new_depths[node_idx] = (depth or 0) + length\n\n if self.isleaf(node_idx):\n new_heights[node_idx] = length\n new_leaf_count[node_idx] = 1\n else:\n idx = self.bp_tree.fchild(node_idx)\n height = 0\n leafcount = 0\n while idx:\n height = max(height, new_heights[idx])\n leafcount += new_leaf_count[idx]\n idx = self.bp_tree.nsibling(idx)\n height += length\n new_heights[node_idx] = height\n new_leaf_count[node_idx] = leafcount\n self.leafcounts = new_leaf_count\n self.heights = new_heights\n self.depths = new_depths\n\n def coords(self, height, width):\n \"\"\" Computes the coordinates of nodes to be rendered in plot.\n\n This runs multiple layout algorithms and saves all of the resulting\n coordinates for each node, so that layout algorithms can be rapidly\n toggled between in the JS interface.\n\n Also adds on .highest_child_yr and .lowest_child_yr attributes to\n internal nodes so that vertical bars for these nodes can be drawn in\n the rectangular layout.\n\n Parameters\n ----------\n height : int\n The height of the canvas.\n width : int\n The width of the canvas.\n\n Returns\n -------\n dict:\n Mapping between layout and the coordinate suffix.\n str:\n Name of the default layout.\n \"\"\"\n\n layout_to_coordsuffix = {}\n layout_algs = (\n self.layout_unrooted,\n self.layout_rectangular,\n self.layout_circular,\n )\n # We set the default layout to whatever the first layout in\n # layout_algs is, but this behavior is of course modifiable\n default_layout = None\n for alg in layout_algs:\n name, suffix = alg(width, height)\n layout_to_coordsuffix[name] = suffix\n self.alter_coordinates_relative_to_root(suffix)\n if name == \"Circular\":\n self.alter_coordinates_relative_to_root(\"c0\")\n if default_layout is None:\n default_layout = name\n\n # Determine highest and lowest child y-position for internal nodes in\n # the rectangular layout; used to draw vertical lines for these nodes.\n #\n # NOTE / TODO: This will have the effect of drawing vertical lines even\n # for nodes with only 1 child -- in this case lowest_child_yr ==\n # highest_child_yr for this node, so all of the stuff drawn in WebGL\n # for this vertical line shouldn't show up. I don't think this should\n # cause any problems, but it may be worth detecting these cases and not\n # drawing vertical lines for them in the future.\n for node_idx in self.preorder():\n if not self.isleaf(node_idx):\n # wow, child does not look like a word any more\n self.highest_child_yr[node_idx] = float(\"-inf\")\n self.lowest_child_yr[node_idx] = float(\"inf\")\n for c_idx in self.children(node_idx):\n if self.yr[c_idx] > self.highest_child_yr[node_idx]:\n self.highest_child_yr[node_idx] = self.yr[c_idx]\n if self.yr[c_idx] < self.lowest_child_yr[node_idx]:\n self.lowest_child_yr[node_idx] = self.yr[c_idx]\n\n return layout_to_coordsuffix, default_layout\n\n def alter_coordinates_relative_to_root(self, suffix):\n \"\"\" Subtracts the root node's x- and y- coords from all nodes' coords.\n\n This was previously done within coords(), but I moved it here so that\n this logic can be used after arbitrary layout computations.\n\n Parameters\n ----------\n suffix : str\n The suffix of the x- and y-coordinates to adjust.\n\n For example, this is \"2\" for the unrooted layout since coordinates\n are stored in the x2 and y2 attributes for every node; and it's \"r\"\n for the rectangular layout since the coordinate attributes are now\n xr and yr.\n \"\"\"\n\n xname = \"x\" + suffix\n yname = \"y\" + suffix\n\n centersX = getattr(self, xname)\n centersY = getattr(self, yname)\n\n centerX = centersX[0]\n centerY = centersY[0]\n\n for node_idx in self.postorder():\n # This code might look sort of intimidating, but it's really just\n # another way to write out:\n # node.x2 = node.x2 - centerX\n # node.y2 = node.y2 - centerY\n # ...when we don't know what \"x2\" or \"y2\" will be named beforehand.\n centersX[node_idx] = centersX[node_idx] - centerX\n centersY[node_idx] = centersY[node_idx] - centerY\n setattr(self, xname, centersX)\n setattr(self, yname, centersY)\n\n def isleaf(self, i):\n \"\"\" Checks if node at position i belongs to a leaf node or not\n\n Parameters\n ----------\n bp_tree : bp.BP\n Input BP tree\n i : int\n The query node index\n Returns\n -------\n bool\n True if this is a leaf node, False otherwise\n \"\"\"\n return self.B[i] and (not self.B[i + 1])\n\n def children(self, i):\n children = []\n child = self.bp_tree.fchild(i)\n while child > 0:\n children.append(child)\n child = self.bp_tree.nsibling(child)\n return children\n\n def layout_rectangular(self, width, height):\n \"\"\" Rectangular layout.\n\n In this sort of layout, each tip has a distinct y-position, and parent\n y-positions are centered over their descendant tips' positions.\n x-positions are computed based on nodes' branch lengths.\n\n Following this algorithm, nodes' rectangular layout coordinates are\n accessible at [node].xr and [node].yr.\n\n For a simple tree, this layout should look something like:\n __\n ___|\n ___| |__\n | |___\n | ___\n |___|\n |___\n\n Parameters\n ----------\n width : float\n width of the canvas\n height : float\n height of the canvas\n\n References\n ----------\n https://rachel53461.wordpress.com/2014/04/20/algorithm-for-drawing-trees/\n Clear explanation of Reingold-Tilford that I used a lot\n https://github.com/qiime/Topiary-Explorer/blob/master/src/topiaryexplorer/TreeVis.java\n Derived from the \"Rectangular\" layout algorithm code.\n \"\"\"\n # NOTE: This doesn't draw a horizontal line leading to the root \"node\"\n # of the graph. See https://github.com/biocore/empress/issues/141 for\n # context.\n max_width = 0\n max_height = 0\n prev_y = 0\n for node_idx in self.postorder():\n if self.isleaf(node_idx):\n\n self.yr[node_idx] = prev_y\n prev_y += 1\n if self.yr[node_idx] > max_height:\n max_height = self.yr[node_idx]\n else:\n # Center internal nodes above their children\n # We could also center them above their tips, but (IMO) this\n # looks better ;)\n children = self.children(node_idx)\n self.yr[node_idx] = sum([self.yr[c_idx] for\n c_idx in children]) / len(children)\n\n for node_idx in self.preorder(include_self=False):\n self.xr[node_idx] = self.xr[self.bp_tree.parent(node_idx)] + \\\n self.bp_tree.length(node_idx)\n if self.xr[node_idx] > max_width:\n max_width = self.xr[node_idx]\n\n # We don't check if max_width == 0 here, because we check when\n # constructing an Empress tree that it has at least one positive\n # branch length and no negative branch lengths. (And if this is the\n # case, then max_width must be > 0.)\n x_scaling_factor = width / max_width\n\n if max_height > 0:\n # Having a max_height of 0 could actually happen, in the funky case\n # where the entire tree is a straight line (e.g. A -> B -> C). In\n # this case our \"rectangular layout\" drawing places all nodes on\n # the same y-coordinate (0), resulting in max_height = 0.\n # ... So, that's why we only do y-scaling if this *isn't* the case.\n y_scaling_factor = height / max_height\n else:\n # Since this will be multiplied by 0 for every node, we can set\n # this to any real number and get the intended \"effect\" of keeping\n # every node's y-coordinate at 0.\n y_scaling_factor = 1\n\n for node_idx in self.preorder():\n self.xr[node_idx] *= x_scaling_factor\n self.yr[node_idx] *= y_scaling_factor\n\n # Now we have the layout! In the JS we'll need to draw each internal\n # node as a vertical line ranging from its lowest child y-position to\n # its highest child y-position, and then draw horizontal lines from\n # this line to all of its child nodes (where the length of the\n # horizontal line is proportional to the node length in question).\n return \"Rectangular\", \"r\"\n\n def layout_circular(self, width, height):\n \"\"\" Circular layout version of the rectangular layout.\n\n Works analogously to the rectangular layout:\n\n -Each tip is assigned a unique angle from the \"center\"/root of\n the tree (out of the range [0, 2pi] in radians), and internal\n nodes are set to an angle equal to the average of their\n children's. This mirrors the assignment of y-coordinates for\n the rectangular layout.\n\n -All nodes are then assigned a radius equal to the sum of their\n branch lengths descending from the root (but not including\n the root's branch length, if provided -- the root is represented\n as just a single point in the center of the layout). This mirrors\n the assignment of x-coordinates for the rectangular layout.\n\n -Lastly, we'll draw arcs for every internal node (except for the\n root) connecting the \"start points\" of the child nodes of that\n node with the minimum and maximum angle. (These points should\n occur at the radius equal to the \"end\" of the given internal\n node.)\n We don't draw this arc for the root node because we don't draw\n the root the same way we do the other nodes in the tree:\n the root is represented as just a single point at the center\n of the layout. Due to this, there isn't a way to draw an arc\n from the root, since the root's \"end\" is at the same point as\n its beginning (so the arc wouldn't be visible).\n\n Following this algorithm, nodes' circular layout coordinates are\n accessible at [node].xc and [node].yc. Angles will also be available\n at [node].clangle, and radii will be available at [node].clradius; and\n for non-root internal nodes, arc start and end coordinates will be\n available at [node].arcx0, [node].arcy0, [node].arcx1, & [node].arcy1.\n\n Parameters\n ----------\n width : float\n width of the canvas\n height : float\n height of the canvas\n\n References\n ----------\n https://github.com/qiime/Topiary-Explorer/blob/master/src/topiaryexplorer/TreeVis.java\n Description above + the implementation of this algorithm\n derived from the Polar layout algorithm code.\n \"\"\"\n anglepernode = (2 * np.pi) / self.leafcounts[0]\n prev_clangle = 0\n for node_idx in self.postorder():\n if self.isleaf(node_idx):\n self.clangle[node_idx] = prev_clangle\n prev_clangle += anglepernode\n else:\n # Center internal nodes at an angle above their children\n children = self.children(node_idx)\n child_clangle_sum = sum([self.clangle[c_idx] for c_idx\n in children])\n self.clangle[node_idx] = child_clangle_sum / len(children)\n\n max_clradius = 0\n for node_idx in self.preorder(include_self=False):\n self.clradius[node_idx] = self.clradius[self.bp_tree.parent(node_idx)] + \\\n self.bp_tree.length(node_idx)\n if self.clradius[node_idx] > max_clradius:\n max_clradius = self.clradius[node_idx]\n\n # Now that we have the polar coordinates of the nodes, convert these\n # coordinates to normal x/y coordinates.\n # NOTE that non-root nodes will actually have two x/y coordinates we\n # need to keep track of: one for the \"end\" of the node's line, and\n # another for the \"start\" of the node's line. The latter of these is\n # needed because the node's line begins at the parent node's radius but\n # the child node's angle, if that makes sense -- and since converting\n # from polar to x/y and back is annoying, it's easiest to just compute\n # this in python.\n max_x = max_y = float(\"-inf\")\n min_x = min_y = float(\"inf\")\n for node_idx in self.postorder():\n self.xc1[node_idx] = self.clradius[node_idx] * \\\n np.cos(self.clangle[node_idx])\n self.yc1[node_idx] = self.clradius[node_idx] * \\\n np.sin(self.clangle[node_idx])\n if self.isleaf(node_idx):\n # NOTE that the root has a clradius of 0 (since it's just\n # represented as a point at the center of the layout). We don't\n # even bother drawing the root in the Empress JS code, but for\n # the purposes of alter_coordinates_relative_to_root() we need\n # to explicitly position the root at (0, 0).\n self.xc0[node_idx] = 0\n self.yc0[node_idx] = 0\n else:\n self.xc0[node_idx] = self.clradius[\n self.bp_tree.parent(node_idx)] *\\\n np.cos(self.clangle[node_idx])\n self.yc0[node_idx] = self.clradius[\n self.bp_tree.parent(node_idx)] *\\\n np.sin(self.clangle[node_idx])\n # NOTE: We don't bother testing the xc0 / yc0 coordinates as\n # \"extrema\" because they should always be further \"within\" the\n # tree than the xc1 / yc1 coordinates.\n # TODO: verify that the \"tree is a line\" case doesn't mess this up.\n if self.xc1[node_idx] > max_x:\n max_x = self.xc1[node_idx]\n if self.yc1[node_idx] > max_y:\n max_y = self.yc1[node_idx]\n if self.xc1[node_idx] < min_x:\n min_x = self.xc1[node_idx]\n if self.yc1[node_idx] < min_y:\n min_y = self.yc1[node_idx]\n\n # TODO: raise error if the maximum and minimum are same for x or y.\n # may happen if the tree is a straight line.\n\n # set scaling factors\n # normalize the coordinate based on the largest dimension\n width_scale = width / (max_x - min_x)\n height_scale = height / (max_y - min_y)\n scale_factor = width_scale if width_scale > height_scale else \\\n height_scale\n x_scaling_factor = scale_factor\n y_scaling_factor = scale_factor\n\n for node_idx in self.preorder():\n self.xc0[node_idx] *= x_scaling_factor\n self.yc0[node_idx] *= y_scaling_factor\n self.xc1[node_idx] *= x_scaling_factor\n self.yc1[node_idx] *= y_scaling_factor\n if not self.isleaf(node_idx) and (node_idx != 0):\n self.highest_child_clangle[node_idx] = float(\"-inf\")\n self.lowest_child_clangle[node_idx] = float(\"inf\")\n for c_idx in self.children(node_idx):\n if self.clangle[c_idx] >\\\n self.highest_child_clangle[node_idx]:\n self.highest_child_clangle[node_idx] =\\\n self.clangle[c_idx]\n if self.clangle[c_idx] < \\\n self.lowest_child_clangle[node_idx]:\n self.lowest_child_clangle[node_idx] =\\\n self.clangle[c_idx]\n # Figure out \"arc\" endpoints for the circular layout\n # NOTE: As with the \"vertical lines\" for internal nodes in the\n # rectangular layout, these arcs will be drawn for nodes with\n # only one child. Here, this case would mean that the\n # highest_child_clangle would equal the lowest_child_clangle,\n # so arcx0 would equal arcx1 and arcy0 would equal arcy1. So\n # nothing should show up (but it may be worth addressing this\n # in the future).\n self.arcx0[node_idx] = self.clradius[node_idx] * \\\n np.cos(\n self.highest_child_clangle[node_idx])\n self.arcy0[node_idx] = self.clradius[node_idx] * \\\n np.sin(\n self.highest_child_clangle[node_idx])\n self.arcx1[node_idx] = self.clradius[node_idx] * \\\n np.cos(\n self.lowest_child_clangle[node_idx])\n self.arcy1[node_idx] = self.clradius[node_idx] * \\\n np.sin(\n self.lowest_child_clangle[node_idx])\n self.arcx0[node_idx] *= x_scaling_factor\n self.arcy0[node_idx] *= y_scaling_factor\n self.arcx1[node_idx] *= x_scaling_factor\n self.arcy1[node_idx] *= y_scaling_factor\n\n return \"Circular\", \"c1\"\n\n def layout_unrooted(self, width, height):\n \"\"\" Find best scaling factor for fitting the tree in the figure.\n This method will find the best orientation and scaling possible to\n fit the tree within the dimensions specified by width and height, using\n an unrooted layout algorithm.\n\n Following this algorithm, nodes' unrooted layout coordinates are\n accessible at [node].x2 and [node].y2.\n\n Parameters\n ----------\n width : float\n width of the canvas\n height : float\n height of the canvas\n\n Returns\n -------\n best_scaling : float\n largest scaling factor in which the tree can fit in the canvas.\n\n Notes\n -----\n\n \"\"\"\n # Recall that 360 degrees is equal to (2 * pi) radians.\n # You can think of this variable as \"the maximum angle we can 'give' to\n # each leaf of the tree\".\n angle = (2 * np.pi) / self.leafcounts[0]\n\n best_scale = 0\n for i in range(60):\n direction = i / 60.0 * np.pi\n\n (max_x, min_x, max_y, min_y) = self.update_unrooted_coords(\n 1.0, 0, 0, direction, angle)\n\n x_diff = max_x - min_x\n width_min = 0\n if x_diff != 0:\n width_min = float(width) / x_diff\n y_diff = max_y - min_y\n height_min = 0\n if y_diff != 0:\n height_min = float(height) / y_diff\n scale = min(width_min, height_min)\n scale *= 0.95 # extra margin for labels\n if scale >= best_scale:\n best_scale = scale\n mid_x = width / 2 - ((max_x + min_x) / 2) * scale\n mid_y = height / 2 - ((max_y + min_y) / 2) * scale\n best_args = (scale, mid_x, mid_y, direction, angle)\n\n self.update_unrooted_coords(*best_args)\n return \"Unrooted\", \"2\"\n\n def update_unrooted_coords(self, s, x1, y1, a, da):\n \"\"\" Update x, y coordinates of tree nodes in canvas.\n\n This function will update the x1, y1, x2, y2, and angle attributes\n for all of the nodes within the tree. Note that (once the unrooted\n layout has finished) all that is really used are the x2 and y2\n attributes.\n\n In a server-based version of Empress, this could be applied when\n the tree becomes modified (i.e. pruning or collapsing) and the\n resulting coordinates would be modified to reflect the changes\n to the tree structure. (In practice, we just run this once on the\n Python side of things in order to precompute the layout.)\n\n Parameters\n ----------\n s : float\n scaling\n x1 : float\n x midpoint\n y1 : float\n y midpoint\n a : float\n angle (degrees)\n da : float\n angle resolution (degrees)\n\n Returns\n -------\n points : list of tuple\n 2D coordinates of all of the nodes.\n \"\"\"\n\n max_x = float('-inf')\n min_x = float('inf')\n max_y = float('-inf')\n min_y = float('inf')\n\n # calculates self coords/angle\n # Constant angle algorithm. Should add maximum daylight step.\n x2 = x1 + self.bp_tree.length(0) * s * np.sin(a)\n y2 = y1 + self.bp_tree.length(0) * s * np.cos(a)\n (self.x1[0], self.y1[0], self.x2[0], self.y2[0], self.angle[0]) = \\\n (x1, y1, x2, y2, a)\n node_indices = [node_idx for node_idx in\n self.postorder(include_self=False)]\n node_indices.reverse()\n # for node in self.preorder(include_self=False):\n for node_idx in node_indices:\n x1 = self.x2[self.bp_tree.parent(node_idx)]\n y1 = self.y2[self.bp_tree.parent(node_idx)]\n\n # init a\n a = self.angle[self.bp_tree.parent(node_idx)]\n\n # same modify across nodes\n a = a - self.leafcounts[self.bp_tree.parent(node_idx)] * da / 2\n\n # check for conditional higher order\n for sib_idx in self.children(self.bp_tree.parent(node_idx)):\n if sib_idx != node_idx:\n a += self.leafcounts[sib_idx] * da\n else:\n a += (self.leafcounts[node_idx] * da) / 2\n break\n\n # Constant angle algorithm. Should add maximum daylight step.\n x2 = x1 + self.bp_tree.length(node_idx) * s * np.sin(a)\n y2 = y1 + self.bp_tree.length(node_idx) * s * np.cos(a)\n (self.x1[node_idx], self.y1[node_idx], self.x2[node_idx],\n self.y2[node_idx], self.angle[node_idx]) = (x1, y1, x2, y2, a)\n\n max_x, min_x = max(max_x, x2), min(min_x, x2)\n max_y, min_y = max(max_y, y2), min(min_y, y2)\n\n return (max_x, min_x, max_y, min_y)\n\n\ndef isleaf(bp_tree, i):\n \"\"\" Checks if node at position i belongs to a leaf node or not\n\n Parameters\n ----------\n bp_tree : bp.BP\n Input BP tree\n i : int\n The query node index\n Returns\n -------\n bool\n True if this is a leaf node, False otherwise\n \"\"\"\n return bp_tree.B[i] and (not bp_tree.B[i + 1])\n" ]
[ [ "numpy.sin", "numpy.cos", "numpy.zeros" ] ]
gustavoeso/img_manipulation
[ "3d1d8705820cae39d5be956836a94c7884ab490d" ]
[ "auxiliar.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n Atenção: usado no notebook da aula. \n Não precisa ser usado diretamente\n\"\"\"\n\nprint(\"Este script não deve ser executado diretamente\")\n\nfrom ipywidgets import widgets, interact, interactive, FloatSlider, IntSlider\nimport numpy as np\nimport cv2\n\n\n\n\ndef make_widgets_mat(m, n):\n \"\"\"\n Makes a m rows x n columns \n matriz of integer Jupyter Widgets\n all values initialized to zero\n \"\"\"\n list_elements = []\n for i in range(m):\n row = []\n for j in range(n):\n row.append(widgets.IntText(value=0))\n list_elements.append(row)\n\n rows = []\n for row in list_elements:\n rows.append(widgets.HBox(row))\n \n widgets_mat = widgets.VBox(rows)\n \n return list_elements, widgets_mat\n\ndef make_widgets_mat_from_data(data):\n \"\"\"\n Creates a matriz of int Widgets given 2D-data\n \"\"\"\n n = len(data)\n m = len(data[0])\n elements, mat = makeMat(n, m)\n for i in range(n):\n for j in range(m):\n elements[i][j].value = data[i][j]\n return elements, mat\n \ndef make_np_from_widgets_list(widgets_list):\n \"\"\"\n Takes as input a list of lists of widgets and initializes a matrix\n \"\"\"\n widgets = widgets_list\n n = len(widgets)\n m = len(widgets[0])\n array = np.zeros((n,m), dtype=np.float32)\n for i in range(n):\n for j in range(m):\n array[i][j] = widgets[i][j].value\n return array\n\n\ndef convert_to_tuple(html_color):\n colors = html_color.split(\"#\")[1]\n r = int(colors[0:2],16)\n g = int(colors[2:4],16)\n b = int(colors[4:],16)\n return (r,g,b)\n\ndef to_1px(tpl):\n img = np.zeros((1,1,3), dtype=np.uint8)\n img[0,0,0] = tpl[0]\n img[0,0,1] = tpl[1]\n img[0,0,2] = tpl[2]\n return img\n\ndef to_hsv(html_color):\n tupla = convert_to_tuple(html_color)\n hsv = cv2.cvtColor(to_1px(tupla), cv2.COLOR_RGB2HSV)\n return hsv[0][0]\n\ndef ranges(value):\n hsv = to_hsv(value)\n hsv2 = np.copy(hsv)\n hsv[0] = max(0, hsv[0]-10)\n hsv2[0] = min(180, hsv[0]+ 10)\n hsv[1:] = 50\n hsv2[1:] = 255\n return hsv, hsv2 \n\n\n\n\n\n" ]
[ [ "numpy.zeros", "numpy.copy" ] ]
m4xst3r/Udacity-AdvancedLaneLines
[ "c95a1831a418726ad374a1ebd65d4ec5e9900ab9" ]
[ "claib_cam.py" ]
[ "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport pickle\n\n# read in all the images in the calibration folder\ncalib_images = glob.glob(\".\\camera_cal\\*.jpg\")\n\n#define chess board parameters:\nnx = 9\nny = 6\n\n# Arrays to store image point and opbject points\nimgpoints = []\nobjpoints = []\n\ndef get_points_chessboard(img, nx, ny):\n \"\"\"\n returns the obj and img points from one chessboard image\n \"\"\"\n #Genreate obj points based on the chessboar from (0,0) to (nx-1, ny-1)\n objp = np.zeros((nx*ny,3), np.float32)\n #np.mgrid cretes two arrays with 9x5 which are than merged together using T (transpose) and reshape. Only the first 2 columns of objp are replaced\n objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2)\n\n #convert Image to gray scale \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n #get chess board corners\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n\n return ret, objp, corners\n\ndef calc_cam_values(img, objpoints, imgpoints):\n \"\"\"\n Calculates camera matrix etc. using the fucntio cv2.calibrateCamera\n \"\"\"\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img.shape[:2], None, None)\n\n return ret, mtx, dist, rvecs, tvecs\n\n#Iterate thorugh images and extract there image points\nfor image_path in calib_images:\n \n image = cv2.imread(image_path)\n\n ret, objp, imgp = get_points_chessboard(image, nx, ny)\n\n if ret == True:\n imgpoints.append(imgp)\n objpoints.append(objp)\n\n else:\n print(\"image is not usable: \", image_path)\n\nret, mtx, dist, rvecs, tvecs = calc_cam_values(image, objpoints, imgpoints)\n\n#write cam values into a dict\ncam_values = { \"mtx\": mtx, \"dist\": dist,\"rvecs\": rvecs,\"tvecs\": tvecs}\n\n#Save cam values in a pickle\npickle.dump(cam_values, open(\"cam_values.p\", \"wb\"))" ]
[ [ "numpy.zeros" ] ]
savazeb/cosmos-ai
[ "4606e959396ebedca73086601078aa9c0ed77b31", "4606e959396ebedca73086601078aa9c0ed77b31" ]
[ "sample/pid/wall_follower_pid.py", "api/control/getitem.py" ]
[ "import sys\nsys.path.append(\"../..\")\n\nfrom api.control.PID import PID\nfrom api.control.sensor import sensor\nfrom api.control.robot import robot\nimport posix_ipc as ipc\nimport time\nimport threading\nimport math\nimport numpy as np\n\ngraphq = ipc.MessageQueue('/graphQueue', ipc.O_CREAT)\nmq = ipc.MessageQueue('/keyQueue', ipc.O_CREAT)\nmq.block = False\n\nlidar = sensor('lidar', '/pointQueue')\n\n\"\"\" THREAD CLASS \"\"\"\nclass sensor_thread(threading.Thread):\n def __init__(self, name, delay,*args, **kwargs):\n super(sensor_thread, self).__init__(*args, **kwargs)\n self._stopper = threading.Event()\n self.name = name\n self.delay = delay\n def stopit(self):\n self._stopper.set()\n def stopped(self):\n return self._stopper.isSet()\n def run(self):\n while True:\n if self.stopped():\n return\n if self.name == 'cam':\n cam.set_data()\n if self.name == 'ir':\n ir.set_data()\n if self.name == 'lidar':\n lidar.set_data()\n time.sleep(self.delay)\n\ndef getPressed():\n try:\n mes = mq.receive()\n key = list((mes[0].decode()).split(\",\"))\n key = int(key[0]), list(map(int, key[1:3])), list(map(float, key[3:]))\n return key\n except:\n return None\n\n\"\"\" GLOBAL VARIABLE HERE \"\"\"\nSENSOR_TYPE = [('lidar', 0.0)]\nATTRIBUTE = 'data'\n\nDELTA_ANGLE = 50\nRIGHT_HAND_ANGLE = 90\nHELPER_HAND_ANGLE = RIGHT_HAND_ANGLE + DELTA_ANGLE\nFACE_ANGLE = 180\n\nWALL_THRES = 1\nWALL_DISTANCE = 60\nWALL_LEFT_BOUND = WALL_DISTANCE - WALL_THRES\nWALL_RIGHT_BOUND = WALL_DISTANCE + WALL_THRES\n\nAVOIDER_POWER = 35\nSTOP = 0, 0, 0\n\nclass power:\n value = 0, 0, 0\n def set(self, x, y, turn):\n self.value = x, y ,turn\n\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx\n\ndef main():\n start = 0\n last_start = start\n min_power = 20\n max_power = 50\n kp = 1\n ki = 0\n kd = 0\n\n lidar_pid = PID(kp, ki, kd, WALL_DISTANCE)\n workers = []\n for name, delay in SENSOR_TYPE:\n print('[info] start thread : ' , name)\n thread = sensor_thread(name, delay)\n workers.append(thread)\n thread.start()\n try:\n rc = robot('/serialWriteQueue')\n time.sleep(5)\n rc.connect()\n time.sleep(0.5)\n pwr = power()\n while True:\n key = getPressed()\n if key:\n print(key)\n start, (min_power, max_power), (kp, ki, kd) = key\n lidar_pid.setOutputLimits((-max_power, max_power))\n lidar_pid.setKValue(kp, ki ,kd)\n if start != last_start:\n rx_distance = 0\n graphq.send(\",\".join(map(str, [start, rx_distance, WALL_DISTANCE])))\n last_start = start\n if start:\n point = lidar.data\n print(type(point))\n if type(point) is np.ndarray:\n print(\"ye\")\n angles, ranges = point\n right_hand = float(ranges[find_nearest(angles, RIGHT_HAND_ANGLE)])\n helper_hand = float(ranges[find_nearest(angles, HELPER_HAND_ANGLE)])\n face = float(ranges[find_nearest(angles, FACE_ANGLE)])\n teta = math.radians(DELTA_ANGLE)\n if face < 50:\n print(\"50\")\n pwr.set(0, 0, AVOIDER_POWER)\n elif right_hand > 0 and helper_hand > 0:\n print(\"ye\")\n alpha = math.atan((right_hand * math.cos(teta) - helper_hand)/ (right_hand * math.sin(teta)))\n rx_distance = helper_hand * math.cos(math.radians(alpha))\n graphq.send(\",\".join(map(str, [start, rx_distance, WALL_DISTANCE])))\n if rx_distance > WALL_RIGHT_BOUND or rx_distance < WALL_LEFT_BOUND:\n out = lidar_pid.update(rx_distance)\n if out < min_power and out > 0:\n out = min_power\n if out > -min_power and out < 0:\n out = -min_power\n print(rx_distance, out)\n pwr.set(0, max_power, out)\n else:\n pwr.set(0, max_power, 0)\n else:\n pwr.set(*STOP) \n else:\n pwr.set(*STOP)\n else:\n pwr.set(*STOP)\n rc.drive(*pwr.value)\n time.sleep(0.001)\n except KeyboardInterrupt:\n print('[info] interrupt pressed')\n print('[main] work finished')\n for worker in workers:\n worker.stopit()\n time.sleep(3)\n worker.join()\n #lidar.cleanup()\n #ir.cleanup()\n #cam.cleanup()\n #rc.disconnect()\n print('[main] end')\n\nmain()\n", "import json\nimport numpy as np\n\nclass stride():\n def __init__(self, size = 1):\n self.size = size\n self.list = self.init_list()\n def init_list(self):\n return []\n def add(self, value):\n self.list.append(value)\n if len(self.list) > self.size:\n self.list = self.list[1:self.size+1]\n\ndirections = [\n \"not found\", # 0b0000\n \"left\", # 0b0001\n \"left back\", # 0b0010\n \"left back\", # 0b0011\n \"right back\", # 0b0100\n \"undefined\", # 0b0101\n \"back\", # 0b0110\n \"left back\", # 0b0111\n \"right\", # 0b1000\n \"undefined\", # 0b1001\n \"undefined\", # 0b1010\n \"undefined\", # 0b1011\n \"right back\", # 0b1100\n \"undefined\", # 0b1101\n \"right back\", # 0b1110\n \"undefined\", # 0b1111\n None\n]\n\ndef most_frequent(List):\n return max(set(List), key = List.count)\n\nir_s = stride()\ndef getDirection(ir, stride_length):\n ir_s.size = stride_length\n direction = int.from_bytes(ir[0], 'little') & 0xf if ir else 16\n ir_s.add(direction)\n print(ir_s.list)\n #print(\"[api] dir list\", ir_s.list)\n return directions[most_frequent(ir_s.list)]\n\n\ndef find(List):\n if sum(x is not None for x in List) >= int(len(List)/2):\n return max(index for index, item in enumerate(List) if item)\n return max(index for index, item in enumerate(List) if not item)\n\ncam_s = stride()\nOBJ_BUFF = None, [None,None]\ndef getDetectedObject(cam, stride_length):\n cam_s.size = stride_length\n if cam:\n obj = json.loads(cam[0].decode())\n cam_s.add(list((obj[\"confidence\"], obj[\"center\"])))\n else:\n cam_s.add(list(OBJ_BUFF))\n # print('[api] obj list', cam_s.list)\n return cam_s.list[find(cam_s.list)]\n\ndef getPoint(lidar):\n angles = []\n ranges = []\n if lidar:\n point = lidar[0].decode()\n point = json.loads(point)\n for key, val in point.items():\n angles.append(int(key))\n ranges.append(float(val))\n return np.array([angles, ranges])\n\n\n" ]
[ [ "numpy.abs", "numpy.asarray" ], [ "numpy.array" ] ]
Tensaiz/DyNSimF
[ "6288ff83f1b3f56fa626f741b55ade57b7c1b358" ]
[ "dynsimf/examples/school_segregation.py" ]
[ "import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nimport math\n\nfrom dynsimf.models.Model import Model\nfrom dynsimf.models.Model import ModelConfiguration\nfrom dynsimf.models.components.Memory import MemoryConfiguration\nfrom dynsimf.models.components.Memory import MemoryConfigurationType\nfrom dynsimf.models.components.conditions.Condition import ConditionType\nfrom dynsimf.models.components.conditions.ThresholdCondition import ThresholdCondition\nfrom dynsimf.models.components.conditions.CustomCondition import CustomCondition\nfrom dynsimf.models.components.conditions.ThresholdCondition import ThresholdOperator\nfrom dynsimf.models.components.conditions.ThresholdCondition import ThresholdConfiguration\n\nif __name__ == \"__main__\":\n # Network definition\n g_list = pickle.load(open(r\"C:/Users/Admin/MEGA/Uni/Master/Thesis/data/g_list.pkl\", 'rb'))\n X_list = pickle.load(open(r\"C:/Users/Admin/MEGA/Uni/Master/Thesis/data/x_list.pkl\", 'rb'))\n\n school = 3\n\n X = X_list[school]\n\n n = len(X['sex'])\n avg_initial_links = 5 # desired average degree in initial network\n link_prop = avg_initial_links/n\n\n g = np.random.choice([0, 1], size=(n, n),\n p=[1 - link_prop,\n link_prop])\n np.fill_diagonal(g, 0)\n g = nx.convert_matrix.from_numpy_array(g, create_using=nx.DiGraph)\n\n cfg = {\n 'adjacency_memory_config': \\\n MemoryConfiguration(MemoryConfigurationType.ADJACENCY, {\n 'memory_size': 0\n }),\n 'edge_values_memory_config': \\\n MemoryConfiguration(MemoryConfigurationType.EDGE_VALUES, {\n 'memory_size': 0\n })\n }\n model = Model(g, ModelConfiguration(cfg))\n\n constants = {\n 'n': n,\n\n 'delta': 0.05,\n 'gamma': 0.65,\n 'c': 0.175,\n 'B1': 0.1,\n 'B2': 0.1,\n 'B3': 0.2,\n 'sigma': 0.035,\n 'alpha': 2,\n\n 'min_prop': 1000,\n\n 'X': X\n }\n\n def initial_utility():\n utility = np.zeros((constants['n'], constants['n']))\n\n race = list(constants['X']['race'])\n sex = list(constants['X']['sex'])\n grade = list(constants['X']['grade'])\n\n for i in range(constants['n']):\n for j in range(constants['n']):\n weighted_diffs = [constants['B1']*abs(sex[i] - sex[j]),\n constants['B2'] * (0 if grade[i] == grade[j] else 1),\n constants['B3'] * (0 if race[i] == race[j] else 1)]\n utility[i, j] = math.exp(-sum(weighted_diffs))\n\n return utility\n\n def initial_prop():\n prop = np.zeros((constants['n'], constants['n']))\n utility = initial_utility()\n\n # Loop over the person and their peers\n for i in range(constants['n']):\n for j in range(constants['n']):\n if i == j:\n prop[i, j] = 0\n else:\n prop[i, j] = utility[i, j] + constants['min_prop']\n\n # Normalize\n prop[i, :] = prop[i, :] / np.sum(prop[i, :])\n\n return prop\n\n constants['probability'] = initial_prop()\n constants['utility'] = initial_utility()\n\n def nb_update():\n adj = model.get_adjacency()\n\n return {'Neighbors': np.sum(adj, axis=1)}\n\n def node_utility(node, adj):\n utility = constants['utility']\n\n # degree, connection gain and cost calculations\n d_i = adj[node].sum()\n direct_u = np.sum(adj[node] * utility[node])\n mutual_u = np.sum(adj[node] * adj.T[node] * utility[node])\n\n # indirect connection gain\n a = (adj.T.dot(adj[node, :]) * utility)[node]\n a[node] = 0\n indirect_u = np.sum(a)\n\n return direct_u + constants['gamma'] * mutual_u + constants['delta'] * indirect_u - d_i ** constants['alpha'] * constants['c']\n\n def network_update(nodes):\n adj = model.get_adjacency()\n order = nodes.copy()\n\n eps = np.random.normal(scale=constants['sigma'], size=constants['n']*2)\n\n np.random.shuffle(order)\n\n changes = {}\n\n P = constants['probability']\n\n for node in order:\n\n other_node = node\n while other_node == node:\n other_node = np.random.choice(nodes, p=P[node])\n\n existing_connection = not not adj[node, other_node]\n\n adj[node, other_node] = 0\n U_without = node_utility(node, adj) + eps[node]\n\n adj[node, other_node] = 1\n U_with = node_utility(node, adj) + eps[-node]\n\n if U_without > U_with and existing_connection:\n changes[node] = {'remove': [other_node]}\n elif U_without < U_with and not existing_connection:\n changes[node] = {'add': [other_node]}\n\n return {\n 'edge_change': changes\n }\n\n\n # Model definition\n model.constants = constants\n model.set_states(['Neighbors'])\n model.add_update(nb_update)\n model.set_edge_values(['utility'])\n model.set_initial_edge_values({\n 'utility': initial_utility,\n })\n\n model.add_network_update(network_update, get_nodes=True)\n\n output = model.simulate(500)\n\n visualization_config = {\n 'plot_interval': 10,\n 'edge_values': 'utility',\n 'plot_variable': 'Neighbors',\n 'variable_limits': {\n 'Neighbors': [0, 55]\n },\n 'color_scale': 'Reds',\n 'show_plot': False,\n 'repeat': True,\n 'plot_output': '../animations/school_segregation/school_' + str(school) + '.gif',\n 'plot_title': 'School segregation'\n }\n\n model.configure_visualization(visualization_config, output)\n model.visualize('animation')\n" ]
[ [ "numpy.sum", "numpy.random.shuffle", "numpy.zeros", "numpy.random.choice", "numpy.fill_diagonal", "numpy.random.normal" ] ]
zhaoaite/CorrMNN
[ "f88a70a199b462e9f3648da3ffdc5ee80a3e5f02" ]
[ "fusionmodel.py" ]
[ "#-*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 10 12:48:22 2018\n\n@author: Aite Zhao\n\"\"\"\n\nfrom __future__ import print_function\n#import random\nimport tensorflow as tf\n#from tensorflow.python.ops import rnn, rnn_cell\nimport numpy as np\n#import plot_confusion_matrix\nimport rnn_cell_GRU as rnn_cell\nimport rnn\nfrom sklearn import preprocessing\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nimport matplotlib.pyplot as plt\nimport os\nfrom tensorflow.contrib.tensor_forest.python import tensor_forest\nfrom tensorflow.python.ops import resources\n#from EvoloPy import *\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.metrics import accuracy_score\nfrom hmmlearn import hmm\nfrom sklearn.linear_model import BayesianRidge\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.learning_curve import validation_curve\nfrom sklearn.svm import SVC\nfrom hmmexm import hmm_4model_classification,hmm_3model_classification\nfrom sklearn.model_selection import LeaveOneOut, KFold,cross_val_score\nfrom deep_CCA_model import *\nfrom linear_cca import linear_cca\n\nn_classes = 52\n\ndef labelprocess(label,n_class=n_classes):\n label_length=len(label)\n label_matrix=np.zeros((label_length,n_class))\n for i,j in enumerate(label): \n label_matrix[i,int(j)]=1\n return label_matrix\n \n# \n#def kfold_validation(data,label,n_splits=5):\n# # K fold cross validation\n# x_trains = []\n# y_trains = []\n# x_tests = []\n# y_tests = []\n# k_fold = KFold(n_splits)\n# for train_index, test_index in k_fold.split(data):\n# X_train, X_test = data[train_index], data[test_index]\n# y_train, y_test = label[train_index], label[test_index]\n# x_trains.append(X_train)\n# y_trains.append(y_train)\n# x_tests.append(X_test)\n# y_tests.append(y_test)\n# return x_trains,y_trains,x_tests,y_tests\n\n#\n\ndef next_batch(batch_size,train_x,train_y,newli_train,force):\n global batchid_force, batchid_time\n if force==True:\n if batchid_force+batch_size > len(train_x):\n batchid_force = 0\n batch_data = (train_x[batchid_force:min(batchid_force +batch_size, len(train_y)),:])\n batch_labels = (newli_train[batchid_force:min(batchid_force + batch_size, len(newli_train)),:])\n batch_labels_1d = (train_y[batchid_force:min(batchid_force + batch_size, len(train_y))])\n batchid_force = min(batchid_force + batch_size, len(train_y))\n return batch_data, batch_labels,batch_labels_1d\n else:\n if batchid_time+batch_size > len(train_x):\n batchid_time = 0\n batch_data = (train_x[batchid_time:min(batchid_time +batch_size, len(train_y)),:])\n batch_labels = (newli_train[batchid_time:min(batchid_time + batch_size, len(newli_train)),:])\n batch_labels_1d = (train_y[batchid_time:min(batchid_time + batch_size, len(train_y))])\n batchid_time = min(batchid_time + batch_size, len(train_y))\n return batch_data, batch_labels,batch_labels_1d\n\n\n\ndef RNN(x, weights, biases, n_input):\n x = tf.transpose(x, [1, 0, 2])\n # Reshaping to (n_steps*batch_size, n_input)\n x = tf.reshape(tensor=x, shape=[-1, n_input])\n # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input)\n x = tf.split(value=x, num_or_size_splits=n_steps, axis=0)\n # Define a lstm cell with tensorflow\n #lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1)\n lstm_cell = rnn_cell.GRUCell(n_hidden)\n #lstm_cell = rnn_cell.LSTMCell(n_hidden,use_peepholes=True)\n # avoid overfitting\n lstm_cell = rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.5)\n # 2 layers lstm\n# num_units = [256, 256]\n# cells = [rnn_cell.GRUCell(num_units=n) for n in num_units]\n# lstm_cell = rnn_cell.MultiRNNCell(cells)\n lstm_cell = rnn_cell.MultiRNNCell([lstm_cell] * 2) \n # Get lstm cell output\n# print(x)\n outputs, states = rnn.rnn(cell=lstm_cell, inputs=x, dtype=tf.float32)\n return tf.matmul(outputs[-1], weights) + biases, outputs\n\n\ndef feature_connect(a_time,a_force):\n a=np.array([])\n for j in range(int(11340/15)):\n f=np.array([])\n for i in range(15):\n f = np.concatenate((f, a_force[j*15+i,:]), axis=0) if f.size else a_force[j*15+i,:]\n a=np.c_[a,f] if a.size else f \n# np.savetxt('./feature_extract/fusionfeature_data.txt', np.c_[a_time,np.transpose(a)],fmt='%.4f')\n return np.c_[a_time,np.transpose(a)],np.transpose(a)\n\ndef DCCA():\n # LSTM CCA\n outdim_size = 10\n input_size1 = n_hidden\n input_size2 = n_hidden\n# input_size2 = 256\n layer_sizes1 = [1024, 1024, 1024, outdim_size]\n layer_sizes2 = [1024, 1024, 1024, outdim_size]\n \n layer_sizes3 = [1024, 1024, 1024, n_classes]\n layer_sizes4 = [1024, 1024, 1024, n_classes]\n reg_par = 1e-4\n use_all_singular_values = True\n dcca_model = DeepCCA(layer_sizes1, layer_sizes2,layer_sizes3,layer_sizes4,\n input_size1, input_size2,\n outdim_size,\n reg_par, use_all_singular_values)\n \n return dcca_model\n\ndef softmax(x): \n x_exp = np.exp(x) \n x_sum = np.sum(x_exp, axis = 1, keepdims = True) \n s = x_exp / x_sum \n return s\n\n\nif __name__=='__main__':\n #remove cpu occupation\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n\n \n# load data \n a_force=np.loadtxt(\"/home/zat/zresearch/ndds-corrlstm/data/sdugait/12023f.txt\")\n a_force=a_force[:,0:60]\n b_force=np.loadtxt(\"/home/zat/zresearch/ndds-corrlstm/data/sdugait/12023label.txt\")\n b_force=b_force-1\n \n a_time=np.loadtxt(\"/home/zat/zresearch/ndds-corrlstm/results/sdu/feature/out256_sdu_img.txt\")\n b_time=np.loadtxt(\"/home/zat/zresearch/ndds-corrlstm/data/sdugait/12023label.txt\")\n# a_time=a_time[:,270:330]\n b_time=b_time-1\n# a_time=preprocessing.normalize(a_time+1) \n \n \n \n all_fea_force=labelprocess(b_force)\n all_fea_time=labelprocess(b_time)\n \n \n## train_test_split 20% testing\n# train_x_time,test_x_time,train_y_time,test_y_time = train_test_split(a_time,b_time,test_size=0.2)\n# train_x_force,test_x_force,train_y_force,test_y_force = train_test_split(a_force,b_force,test_size=0.2)\n# print(train_x_time.shape,test_x_time.shape,train_x_force.shape,test_x_force.shape)\n# newli_train_time=labelprocess(train_y_time)\n# newli_test_time=labelprocess(test_y_time)\n# newli_train_force=labelprocess(train_y_force)\n# newli_test_force=labelprocess(test_y_force)\n\n## 10 Fold cross validation\n# x_trains_force,y_trains_force,x_tests_force,y_tests_force = kfold_validation(a_force,b_force)\n# x_trains_time,y_trains_time,x_tests_time,y_tests_time = kfold_validation(a_time,b_time)\n \n \n # Parameters\n learning_rate = 0.001\n training_iters_force = 5000000\n# training_iters_time = 500000\n batch_size = 256\n display_step = 100\n batchid_time = 0\n batchid_force = 0\n \n # Network Parameters\n n_input_force = 15\n n_input_time = 32\n n_steps = 4\n n_hidden = 128\n\n # reset graph\n tf.reset_default_graph()\n\n# force_channel Graph\n G_force=tf.Graph()\n Sess_force=tf.Session(graph=G_force)\n with Sess_force.as_default(): \n with G_force.as_default():\n with tf.variable_scope(\"force_channel\") as scope:\n x_force = tf.placeholder(\"float\", [None, n_steps, n_input_force],name='x_force')\n y_force = tf.placeholder(\"float\", [None, n_classes])\n weights = {\n 'weights_out_force': tf.Variable(tf.random_normal([n_hidden, n_classes]),name='weights_out_force')\n }\n biases= {\n 'biases_out_force': tf.Variable(tf.random_normal([n_classes]),name='biases_out_force')\n }\n pred_force, out_force = RNN(x_force, weights['weights_out_force'], biases['biases_out_force'], n_input_force)\n logits_scaled_force=tf.nn.softmax(pred_force)\n cost_force = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred_force, labels=y_force))\n optimizer_force = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost_force)\n correct_pred_force = tf.equal(tf.argmax(pred_force,1), tf.argmax(y_force,1))\n accuracy_force = tf.reduce_mean(tf.cast(correct_pred_force, tf.float32))\n Sess_force.run(tf.global_variables_initializer()) \n saverf = tf.train.Saver()\n\n# time_channel Graph\n G_time=tf.Graph()\n Sess_time=tf.Session(graph=G_time)\n with Sess_time.as_default(): \n with G_time.as_default():\n with tf.variable_scope(\"time_channel\") as scope:\n x_time = tf.placeholder(\"float\", [None, n_steps, n_input_time],name='x_time')\n y_time = tf.placeholder(\"float\", [None, n_classes])\n weights = {\n 'weights_out_time': tf.Variable(tf.random_normal([n_hidden, n_classes]),name='weights_out_time'),\n }\n biases= {\n 'biases_out_time': tf.Variable(tf.random_normal([n_classes]),name='biases_out_time'),\n }\n pred_time, out_time = RNN(x_time, weights['weights_out_time'], biases['biases_out_time'], n_input_time)\n logits_scaled_time=tf.nn.softmax(pred_time)\n cost_time = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred_time, labels=y_time))\n optimizer_time = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost_time)\n correct_pred_time = tf.equal(tf.argmax(pred_time,1), tf.argmax(y_time,1))\n accuracy_time = tf.reduce_mean(tf.cast(correct_pred_time, tf.float32))\n Sess_time.run(tf.global_variables_initializer()) \n savert = tf.train.Saver()\n \n# dcca_model Graph\n G_dcca=tf.Graph()\n Sess_dcca=tf.Session(graph=G_dcca)\n with Sess_dcca.as_default(): \n with G_dcca.as_default():\n dcca_model=DCCA()\n input_view1 = dcca_model.input_view1\n input_view2 = dcca_model.input_view2\n hidden_view1 = dcca_model.output_view1\n hidden_view2 = dcca_model.output_view2\n hidden_view1_pred = dcca_model.output_view1_class\n hidden_view2_pred = dcca_model.output_view2_class\n label1 = dcca_model.label1\n label2 = dcca_model.label2\n neg_corr = dcca_model.neg_corr\n value= dcca_model.value\n# gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)\n# Sess_dcca = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options))\n \n# maxmize the correlation between two data unsupervised learning(minimize -corr)\n# train_op = tf.train.MomentumOptimizer(learning_rate, 0.99).minimize(neg_corr,var_list=tf.trainable_variables())\n train_op = tf.train.AdamOptimizer(learning_rate).minimize(neg_corr,var_list=tf.trainable_variables())\n# minimize the cost between different classes supervised learning\n cross_entropy1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=label1, logits=hidden_view1_pred))\n optimizer1 = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cross_entropy1)\n accuracy1 = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(hidden_view1_pred, 1), tf.argmax(label1, 1)), tf.float32))\n \n cross_entropy2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=label2, logits=hidden_view2_pred))\n optimizer2 = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cross_entropy2)\n accuracy2 = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(hidden_view2_pred, 1), tf.argmax(label2, 1)), tf.float32))\n \n lossfuse=cross_entropy1+cross_entropy2+tf.exp(neg_corr)\n optimizerfuse=tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(lossfuse)\n\n## supervised learning\n# cross_entropy1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=cnnlabel1, logits=hidden_view1))\n# optimizer1 = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cross_entropy1)\n# cnnaccuracy1 = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(hidden_view1, 1), tf.argmax(cnnlabel1, 1)), tf.float32))\n# \n# cross_entropy2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=cnnlabel2, logits=hidden_view2))\n# optimizer2 = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cross_entropy2)\n# cnnaccuracy2 = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(hidden_view2, 1), tf.argmax(cnnlabel2, 1)), tf.float32))\n \n Sess_dcca.run(tf.global_variables_initializer()) \n saverd = tf.train.Saver()\n# tf.InteractiveSession.close()\n \n\n\n \n# weights = {\n# 'weights_out_time': tf.Variable(tf.random_normal([n_hidden, n_classes]),name='weights_out_time'),\n# 'weights_out_force': tf.Variable(tf.random_normal([n_hidden, n_classes]),name='weights_out_force')\n# }\n# biases= {\n# 'biases_out_time': tf.Variable(tf.random_normal([n_classes]),name='biases_out_time'),\n# 'biases_out_force': tf.Variable(tf.random_normal([n_classes]),name='biases_out_force')\n# }\n \n# weights = {\n# 'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))\n# }\n# biases= {\n# 'out': tf.Variable(tf.random_normal([n_classes]))\n# }\n \n \n# \n# with tf.variable_scope(\"force_channel\") as scope:\n# pred_force, out_force = RNN(x_force, weights['weights_out_force'], biases['biases_out_force'], n_input_force)\n# pred_force, out_force = RNN(x_force, weights['out'], biases['out'], n_input_force)\n# logits_scaled_force=tf.nn.softmax(pred_force)\n# cost_force = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred_force, labels=y_force))\n# optimizer_force = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost_force)\n# correct_pred_force = tf.equal(tf.argmax(pred_force,1), tf.argmax(y_force,1))\n# accuracy_force = tf.reduce_mean(tf.cast(correct_pred_force, tf.float32))\n# \n# with tf.variable_scope(\"time_channel\") as scope:\n## pred_time, out_time = RNN(x_time, weights['weights_out_time'], biases['biases_out_time'], n_input_time)\n# pred_time, out_time = RNN(x_time, weights['out'], biases['out'], n_input_time)\n# logits_scaled_time=tf.nn.softmax(pred_time)\n# cost_time = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred_time, labels=y_time))\n# optimizer_time = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost_time)\n# correct_pred_time = tf.equal(tf.argmax(pred_time,1), tf.argmax(y_time,1))\n# accuracy_time = tf.reduce_mean(tf.cast(correct_pred_time, tf.float32))\n \n \n \n\n accuracys_force=[]\n accuracys_time=[]\n \n for i in range(1):\n #20% split\n train_x_time,test_x_time,train_y_time,test_y_time = train_test_split(a_time,b_time,test_size=0.2,random_state=1)\n train_x_force,test_x_force,train_y_force,test_y_force = train_test_split(a_force,b_force,test_size=0.2,random_state=1)\n print(train_x_time.shape,test_x_time.shape,train_x_force.shape,test_x_force.shape)\n newli_train_time=labelprocess(train_y_time)\n newli_test_time=labelprocess(test_y_time)\n newli_train_force=labelprocess(train_y_force)\n newli_test_force=labelprocess(test_y_force)\n \n #10 fold \n# train_x_force=x_trains_force[i]\n# train_y_force=y_trains_force[i]\n# test_x_force=x_tests_force[i]\n# test_y_force=y_tests_force[i]\n# \n# train_x_time=x_trains_time[i]\n# train_y_time=y_trains_time[i]\n# test_x_time=x_tests_time[i]\n# test_y_time=y_tests_time[i]\n# \n# newli_train_force=labelprocess(train_y_force)\n# newli_train_time=labelprocess(train_y_time)\n# \n# newli_test_force=labelprocess(test_y_force)\n# newli_test_time=labelprocess(test_y_time)\n\n\n # Initializing the variables\n# init = tf.global_variables_initializer()\n# saver = tf.train.Saver()\n \n # Launch the graph\n# with tf.Session() as sess:\n# #rnn\n# sess.run(init)\n# #rf\n# # sess.run(rf_init_vars)\n# tf.device('/gpu:0')\n \n step = 1\n acc_forces=[]\n loss_forces=[]\n acc_times=[]\n loss_times=[]\n dccaloss=[]\n fuseloss=[]\n \n out_force256=None\n out_time256=None\n tf.device('/gpu:0')\n \n while step * batch_size < training_iters_force:\n with tf.variable_scope(\"force_channel\") as scope:\n rf_batch_x_force, batch_y_force, rf_batch_y_force= next_batch(batch_size,train_x_force,train_y_force,newli_train_force,True)\n batch_x_force = rf_batch_x_force.reshape((batch_size, n_steps, n_input_force))\n _,out_force256=Sess_force.run([optimizer_force,out_force], \n feed_dict={x_force: batch_x_force, y_force: batch_y_force})\n if step % display_step == 0:\n acc_force,loss_force= Sess_force.run([accuracy_force,cost_force],\n feed_dict={x_force: batch_x_force, y_force: batch_y_force})\n print(\"Iter \" + str(step*batch_size) + \", Minibatch loss_force= \" + \\\n \"{:.6f}\".format(loss_force) + \", Training Accuracy= \" + \\\n \"{:.5f}\".format(acc_force)) \n acc_forces.append(acc_force)\n loss_forces.append(loss_force)\n \n# step += 1 \n# step = 1\n# while step * batch_size < training_iters_time: \n with tf.variable_scope(\"time_channel\") as scope:\n rf_batch_x_time, batch_y_time, rf_batch_y_time= next_batch(batch_size,train_x_time,train_y_time,newli_train_time,False)\n batch_x_time = rf_batch_x_time.reshape((batch_size, n_steps, n_input_time))\n _,out_time256=Sess_time.run([optimizer_time,out_time], \n feed_dict={x_time: batch_x_time, y_time: batch_y_time})\n if step % display_step == 0:\n acc_time,loss_time = Sess_time.run([accuracy_time,cost_time], \n feed_dict={x_time: batch_x_time, y_time: batch_y_time})\n print(\"Iter \" + str(step*batch_size) + \", Minibatch loss_time= \" + \\\n \"{:.6f}\".format(loss_time) + \", Training Accuracy= \" + \\\n \"{:.5f}\".format(acc_time)) \n acc_times.append(acc_time)\n loss_times.append(loss_time)\n \n ################# Deep CCA maxmize the correlation #############################\n# correlation in each node\n# for force256,time256 in zip(out_force256,out_time256):\n# _, neg_corr_val,_,_= Sess_dcca.run([train_op, neg_corr,optimizer1,optimizer2],\n# feed_dict={input_view1:force256,input_view2:time256,\n# label1:batch_y_force,\n# label2:batch_y_time})\n# acc1,acc2 = Sess_dcca.run([accuracy1, accuracy2],\n# feed_dict={input_view1:force256,input_view2:time256,\n# label1:batch_y_force,\n# label2:batch_y_time})\n \n for force256,time256 in zip(out_force256,out_time256):\n# print(force256.shape,time256.shape)\n _, neg_corr_val,_,lossfuseprint,corvalue= Sess_dcca.run([train_op, neg_corr,optimizerfuse,lossfuse,value],\n feed_dict={input_view1:force256,input_view2:time256,\n label1:batch_y_force,\n label2:batch_y_time})\n \n# acc1,acc2 = Sess_dcca.run([accuracy1, accuracy2],\n# feed_dict={input_view1:force256,input_view2:time256,\n# label1:batch_y_force,\n# label2:batch_y_time})\n# print(corvalue)\n if step % display_step == 0:\n dccaloss.append(np.exp(neg_corr_val))\n fuseloss.append(lossfuseprint)\n \n# print('corr_val',-neg_corr_val)\n# print(\"fuse_loss_for_train:\", lossfuseprint)\n# print(\"accuracy1:\", acc1)\n# print(\"accuracy2:\", acc2)\n \n \n step += 1\n \n# save the training process \n# np.savetxt('./results/train_loss_dcca'+str(i)+'.csv',dccaloss,delimiter=',')\n# np.savetxt('./results/train_loss_fuse'+str(i)+'.csv',fuseloss,delimiter=',')\n# \n# \n# np.savetxt('./results/train_acc_force'+str(i)+'.csv',acc_forces,delimiter=',')\n# np.savetxt('./results/train_loss_force'+str(i)+'.csv',loss_forces,delimiter=',')\n# np.savetxt('./results/train_acc_time'+str(i)+'.csv',acc_times,delimiter=',')\n# np.savetxt('./results/train_loss_time'+str(i)+'.csv',loss_times,delimiter=',')\n\n\n ################# Linear CCA #############################\n# Using CCA to extract feature in each node in LSTM\n data_time=a_time.reshape((-1,n_steps, n_input_time))\n out256_time=Sess_time.run(out_time,feed_dict={x_time: data_time, y_time: all_fea_time})\n data_force=a_force.reshape((-1,n_steps, n_input_force))\n out256_force=Sess_force.run(out_force,feed_dict={x_force: data_force, y_force: all_fea_force})\n fusionfeature_data=np.c_[out256_time[-1],out256_force[-1]] \n np.savetxt('./fusionfeature_Corrmnn_sdu.csv', fusionfeature_data, fmt='%.4f')\n# compute the correlation in each node in LSTM (timestep* batchsize * 256d)\n X1projlist=np.array([])\n X2projlist=np.array([])\n for eachnode_force,eachnode_time in zip(out256_force,out256_time):\n X1proj, X2proj = Sess_dcca.run([hidden_view1, hidden_view2],\n feed_dict={\n input_view1: eachnode_force,\n input_view2: eachnode_time})\n# (11340, 10) (756, 10)\n X1projlist=np.c_[X1projlist,X1proj] if X1projlist.size else X1proj \n X2projlist=np.c_[X2projlist,X2proj] if X2projlist.size else X2proj\n# ccafuse_data,_ = feature_connect(X2projlist,X1projlist)\n ccafuse_data=np.c_[X2projlist,X1projlist] \n print('----------ccafuse_data '+str(i)+'-----------')\n# (756, 1600) (756, 1600)\n np.savetxt('./ccafuse_sdu.csv', ccafuse_data, fmt='%.4f')\n \n \n \n# print(\"Linear CCA started!\")\n# w = [None, None]\n# m = [None, None]\n# print(X1proj.shape, X2proj.shape)\n# w[0], w[1], m[0], m[1] = linear_cca(X1proj, X2proj, 10)\n# print(\"Linear CCA ended!\")\n# X1proj -= m[0].reshape([1, -1]).repeat(len(X1proj), axis=0)\n# X1proj = np.dot(X1proj, w[0])\n# X1projlist=np.c_[X1projlist,X1proj] if X1projlist.size else X1proj \n# print(X1projlist.shape)\n\n ################# testing LSTM #############################\n test_data=test_x_force.reshape((-1,n_steps, n_input_force))\n test_label=newli_test_force\n accuracy_force_out=Sess_force.run(accuracy_force, feed_dict={x_force: test_data, y_force: test_label})\n print(\"Force Testing Accuracy:\",accuracy_force_out) \n \n test_data=test_x_time.reshape((-1,n_steps, n_input_time))\n test_label=newli_test_time\n accuracy_time_out=Sess_time.run(accuracy_time, feed_dict={x_time: test_data, y_time: test_label})\n print(\"Time Testing Accuracy:\",accuracy_time_out)\n \n accuracys_force.append(accuracy_force_out) \n accuracys_time.append(accuracy_time_out)\n \n \n print(accuracys_force,accuracys_time)\n print('accuracys_force_mean:',np.mean(accuracys_force)) \n print('accuracys_time_mean:',np.mean(accuracys_time))\n accuracys_force.append(np.mean(accuracys_force))\n accuracys_time.append(np.mean(accuracys_time))\n \n# np.savetxt('./test_result_fog.csv',[accuracys_force,accuracys_time])\n \n \n## extract the last output of the lstm in all data\n# data_time=a_time.reshape((-1,n_steps, n_input_time))\n# out256_time=Sess_time.run(out_time,feed_dict={x_time: data_time, y_time: all_fea_time})\n# \n# data_force=a_force.reshape((-1,n_steps, n_input_force))\n# out256_force=Sess_force.run(out_force,feed_dict={x_force: data_force, y_force: all_fea_force})\n#\n# np.savetxt('./out256_time.txt', out256_time, fmt='%.4f')\n# np.savetxt('./out256_force.txt', out256_force, fmt='%.4f')\n# \n# saver.save(sess, './modelcache/fusemodel.ckpt')\n# writer=tf.summary.FileWriter('./fusemodel_graph',sess.graph)\n# writer.flush()\n# writer.close()\n# sess.close()\n# saverf.save(Sess_force, './modelcache/forcemodel.ckpt')\n# writerf=tf.summary.FileWriter('./graphs/forcemodel_graph',Sess_force.graph)\n# savert.save(Sess_time, './modelcache/timemodel.ckpt')\n# writert=tf.summary.FileWriter('./graphs/timemodel_graph',Sess_time.graph) \n# saverd.save(Sess_dcca, './modelcache/dccamodel.ckpt')\n# writerd=tf.summary.FileWriter('./graphs/dccamodel_graph',Sess_dcca.graph)\n# writerf.flush()\n# writerf.close()\n# Sess_force.close()\n# writert.flush()\n# writert.close()\n# Sess_time.close()\n# writerd.flush()\n# writerd.close()\n# Sess_dcca.close()\n \n \n# align the two types of data \n# fusionfeature_data,force_data = feature_connect(out256_time,out256_force)\n# fusionfeature_data=np.c_[out256_time[-1],out256_force[-1]] \n# np.savetxt('./fusionfeature_Corrmnn.txt', fusionfeature_data, fmt='%.4f')\n# hmm_accuracy = hmm_4model_classification(fusionfeature_data,b_time)\n \n # combine the lda feature(2d) with ccafuse_data\n# ldafeature=np.loadtxt('./feature_extract/ldafeature_data.txt')\n# ldafeature=softmax(ldafeature)\n# ldafeature=preprocessing.normalize(ldafeature)\n# print(ldafeature)\n# ccafuse_data=np.c_[ccafuse_data,ldafeature]\n#\n# hmm_accuracy = hmm_4model_classification(ccafuse_data,b_time)\n# print('Total hmm accuracy:',hmm_accuracy)\n\n\n\n# fuse_data=np.loadtxt('/home/zat/zresearch/ndds-corrlstm/results/fog/fusefea.csv')\n# \n# hmm_accuracy = hmm_3model_classification(fuse_data,b_time)\n# print('Total hmm accuracy:',hmm_accuracy)" ]
[ [ "numpy.sum", "tensorflow.reshape", "numpy.savetxt", "tensorflow.variable_scope", "tensorflow.matmul", "tensorflow.nn.softmax", "tensorflow.split", "tensorflow.random_normal", "numpy.transpose", "tensorflow.global_variables_initializer", "tensorflow.device", "sklearn.cross_validation.train_test_split", "tensorflow.Graph", "tensorflow.transpose", "numpy.mean", "numpy.zeros", "tensorflow.cast", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.reset_default_graph", "tensorflow.placeholder", "tensorflow.train.AdamOptimizer", "numpy.exp", "tensorflow.trainable_variables", "tensorflow.exp", "tensorflow.nn.softmax_cross_entropy_with_logits_v2", "tensorflow.argmax", "numpy.array", "numpy.concatenate", "numpy.loadtxt" ] ]
kking423/digital_library
[ "643c396991bbc9664312826e849d3b9baae98c0d" ]
[ "workflow/workflow_inventory.py" ]
[ "import datetime\nimport shutil\nimport services.inventory\nimport workflow\nimport pandas as pd\nimport os\nimport file_system\nimport file_system.images as images\nimport json\nfrom file_system.file_system_object import FileSystemObject\nfrom services import inventory, library\nfrom tabulate import tabulate\nimport cv2\n\n\nTEMP_FOLDER = \"tmp/eval\"\nRECYCLE_BIN = \"tmp/recycle_bin\"\n\n\ndef inventory_menu():\n library_id = prompt_for_library()\n\n while True:\n print(\"\\n\")\n print(\"###############################################\")\n print(\"Digital Library Utility - Inventory Management \")\n print(\"###############################################\")\n print(\"[0] Return to Main Menu\")\n print(\"[1] Add/Update (Refresh) Inventory\")\n print(\"[3] View Inventory\")\n print(\"[4] Reconcile (Library) Inventory\")\n print(\"[5] Update Inventory Compare Scores\")\n print(\"[6] Manage Duplicate Inventory\")\n print(\"[7] Restore files from Recycle Bin\")\n print(\"[8] Classify Inventory\")\n\n choice = input(\"> \")\n\n if choice.isnumeric() and int(choice) in range(10):\n if int(choice) == 0:\n workflow.main_menu()\n\n elif int(choice) == 1: # add/update inventory\n refresh_inventory(library_id=library_id)\n reconcile_inventory(library_id=library_id, calculate_compare_score=False)\n\n elif int(choice) == 3: # view inventory by library\n display_library_inventory(library_id)\n\n elif int(choice) == 4: # reconcile inventory\n reconcile_inventory(library_id=library_id, calculate_compare_score=False)\n\n elif int(choice) == 5: # reconcile inventory with compare score calculation\n reconcile_inventory(library_id=library_id, calculate_compare_score=True)\n\n elif int(choice) == 6: # manage duplicate inventory\n refresh_inventory(library_id=library_id)\n reconcile_inventory(library_id=library_id, calculate_compare_score=True)\n get_comparable_inventory(library_id=library_id)\n move_files_to_recycle_bin(library_id=library_id)\n clear_eval_folder(TEMP_FOLDER)\n refresh_inventory(library_id=library_id)\n\n elif int(choice) == 7:\n restore_from_recycle_bin()\n reconcile_inventory(library_id=library_id, calculate_compare_score=False)\n\n elif int(choice) == 8:\n display_library_inventory(library_id)\n update_classification()\n\n else:\n print(\"Selection not valid. Please try again.\")\n\n\ndef refresh_inventory(library_id):\n src = get_library_base_path(library_id)\n exclusion_list = ['.map', 'venv', '.pyc', '__pycache__', '.DS_Store', 'ignore', '.idea', 'git']\n restricted_list = []\n\n data = file_system.search(search_path=src,\n recursive=True,\n exclusion_list=exclusion_list,\n restricted_list=restricted_list)\n\n for idx, item in enumerate(data):\n data[idx]['library_id'] = library_id\n if not data[idx]['is_hidden']:\n inventory.refresh_inventory(**data[idx])\n\n\ndef prompt_for_library():\n workflow.workflow_library.display_user_libraries()\n prompt = input(\"Select Library ID: \")\n if lib := services.library.get_library(prompt):\n return lib.library_id\n print(f\"{prompt} is not a valid Library ID\")\n prompt_for_library()\n\n\ndef get_library_base_path(library_id):\n lib = library.get_library(library_id)\n return lib.base_path\n\n\ndef update_inventory_compare_scores(inventory_id, full_path):\n fso = FileSystemObject(full_path).to_dict()\n if fso and fso['is_found'] and not fso['is_hidden']:\n fso['inventory_removed_date'] = None\n inv = inventory.get_inventory_item(inventory_id)\n\n if not inv.compare_score or inv.compare_score == 0 or inv.compare_score_dt < inv.modified_dt:\n fso['compare_score'] = (update_compare_score(full_path, size=fso['size']))\n fso['compare_score_dt'] = datetime.datetime.now()\n\n inventory.update_inventory(inventory_id, **fso)\n else:\n data = {'inventory_removed_date': datetime.datetime.now()}\n inventory.update_inventory(inventory_id, **data)\n\n\ndef update_compare_score(full_path, size):\n return images.calculate_compare_score(full_path, size=size)\n\n\ndef get_inventory(library_id):\n return inventory.get_library_inventory(library_id=library_id)\n\n\ndef display_all_inventory():\n results = inventory.get_all_inventory()\n df = pd.DataFrame(results)\n # df = df.drop(['_sa_instance_state'], axis=1)\n df.sort_values(by=['library_id', 'directory', 'full_path'])\n print(tabulate(df.head(500), headers='keys', tablefmt='psql'))\n\n\ndef display_library_inventory(library_id):\n if results := inventory.get_library_inventory(library_id):\n df = pd.DataFrame(results)\n # df = df.drop(['_sa_instance_state'], axis=1)\n df.sort_values(by=['library_id', 'directory', 'full_path'])\n print(tabulate(df.head(500), headers='keys', tablefmt='psql'))\n else:\n return None\n\n\ndef reconcile_inventory(library_id, calculate_compare_score: bool = False):\n # Purpose: Identify files/folders that no longer exist and update DB accordingly\n # library_id = prompt_for_library()\n results = inventory.get_library_inventory(library_id)\n\n for idx, item in enumerate(results):\n if results[idx]['file']:\n src_path = results[idx]['full_path']\n inventory_id = results[idx]['inventory_id']\n\n fso = FileSystemObject(src_path).to_dict()\n if fso and fso['is_found'] and not fso['is_hidden']:\n data = {\n 'inventory_removed_date': None,\n 'inventory_removed_reason': None,\n 'is_missing': False\n }\n else:\n data = {'inventory_removed_date': datetime.datetime.now(),\n 'is_missing': True\n }\n\n inventory.update_inventory(inventory_id, **data)\n\n if calculate_compare_score:\n update_inventory_compare_scores(inventory_id, src_path)\n\n\ndef restore_from_recycle_bin():\n path = RECYCLE_BIN\n for root, folders, files in os.walk(path, topdown=True):\n for file in files:\n recycled_file = os.path.splitext(file)[0]\n src = os.path.join(root, file)\n original_file = services.inventory.get_inventory_item(recycled_file)\n dest = original_file.full_path\n\n shutil.move(src, dest)\n\n\ndef get_comparable_inventory(library_id):\n try:\n if data := inventory.get_comparable_inventory(library_id):\n df = pd.DataFrame(data)\n # df = df.drop(['_sa_instance_state'], axis=1)\n df[\"file\"] = df[\"file\"].str.lower()\n df['compare_score_frequency'] = df.groupby('compare_score')['compare_score'].transform('count')\n df = df[df.groupby('compare_score')['compare_score'].transform('count') > 1]\n df = df[['inventory_id', 'library_id', 'directory', 'full_path', 'file', 'file_extension',\n 'size', 'created_dt', 'modified_dt',\n 'compare_score_dt', 'compare_score', 'compare_score_frequency']]\n # df.sort_values(by=['compare_score', 'size'])\n # print(tabulate(df, headers='keys', tablefmt='psql'))\n group_duplicates(df)\n clear_eval_folder(TEMP_FOLDER)\n else:\n print(\"No duplicates were found.\")\n except:\n print(\"An unexpected error has occurred\")\n\n\ndef group_duplicates(df: pd.DataFrame):\n distinct_scores = list(df['compare_score'].unique())\n count = len(distinct_scores)\n\n for counter, score in enumerate(distinct_scores, 1):\n sample = df[df[\"compare_score\"] == score]\n sample = pd.DataFrame(sample, columns=['inventory_id', 'file', 'file_extension', 'full_path', 'directory',\n 'size', 'created_dt', 'modified_dt'])\n sample.reset_index(drop=True, inplace=True)\n print(\"###############################################\")\n print(f\"Potential Duplicate Group {counter} of {count}\")\n print(f\"Compare Score: {score}\")\n print(\"###############################################\")\n\n evaluate_duplicates_by_group(sample)\n\n\ndef evaluate_duplicates_by_group(sample: pd.DataFrame):\n clear_eval_folder(path=TEMP_FOLDER)\n group = []\n # print(tabulate(sample.head(), headers='keys', tablefmt='psql'))\n\n for idx, row in sample.iterrows():\n group.append(row['inventory_id'])\n inventory_id = row['inventory_id']\n created = row['created_dt']\n modified = row['modified_dt']\n size = row['size']\n src = row['full_path']\n dest = f'{TEMP_FOLDER}/' + inventory_id + row['file_extension']\n print(f\"InventoryID: {inventory_id} | File: {row['file']} | Created: {created} | \"\n f\"Modified: {modified} | Size: {size}\")\n\n shutil.copy2(src, dest)\n\n if retain := input(\"Enter Inventory IDs you wish to keep (separate by comma): \").split(\",\"):\n for idx, item in enumerate(retain):\n retain[idx] = item.strip()\n\n for inv_id in group:\n if inv_id not in retain:\n reason = input(f\"Enter reason for removal of {inv_id}: \")\n services.inventory.remove_inventory_item(inv_id.strip(), reason.strip())\n\n\ndef move_files_to_recycle_bin(library_id):\n reconcile_inventory(library_id, calculate_compare_score=False)\n if data := inventory.get_removed_inventory(library_id):\n for idx, item in enumerate(data):\n src = data[idx]['full_path']\n inventory_id = data[idx]['inventory_id']\n file_extension = data[idx]['file_extension']\n dest = f'{RECYCLE_BIN}/' + inventory_id + file_extension\n\n try:\n shutil.move(src, dest)\n except FileNotFoundError:\n print(\"A FileNotFound error has occurred.\")\n\n\ndef remove_inventory(group: list, retain: list):\n for idx, item in enumerate(retain):\n retain[idx] = item.strip()\n\n for inv_id in group:\n if inv_id not in retain:\n reason = input(f\"Enter reason for removal of {inv_id}: \")\n services.inventory.remove_inventory_item(inv_id.strip(), reason.strip())\n\n\ndef clear_eval_folder(path: str):\n mypath = path\n for root, dirs, files in os.walk(mypath):\n for file in files:\n os.remove(os.path.join(root, file))\n\n\ndef select_inventory_item():\n return input(\"Input Inventory ID: \")\n\n\ndef get_inventory_item(inventory_id):\n return services.inventory.get_inventory_item(inventory_id=inventory_id)\n\n\ndef update_classification(library_id, incl_assignment: bool = False):\n inv = workflow.workflow_inventory.get_inventory(library_id=library_id)\n\n try:\n for file in inv:\n inventory_id = file['inventory_id']\n\n if file['is_image']:\n # inv = services.inventory.get_inventory_item(inventory_id=inventory_id).to_dict()\n cv2.imshow(file['file'], cv2.imread(file['full_path']))\n cv2.waitKey(1)\n\n if file['classification']:\n print(f\"Current Tags: {file['classification']['tags']}\")\n\n tag_values = [item.strip() for item in input(\"Input Tags (separated by comma): \").split(',')]\n data = {\n 'inventory_id': inventory_id,\n 'classification': {'tags': tag_values},\n 'model_assignment': input(\"Model Assignment Name: \") if incl_assignment else file['model_assignment']\n }\n\n services.inventory.update_inventory_classification(**data)\n cv2.destroyAllWindows()\n\n cv2.destroyAllWindows()\n except:\n raise\n\n\ndef update_classification_from_model(inventory_id, tags: str):\n file = workflow.workflow_inventory.get_inventory_item(inventory_id).to_dict()\n classification = file['classification']['tags'] if file['classification'] else []\n classification.append(tags)\n classification = list(set(classification))\n data = {\n 'inventory_id': inventory_id,\n 'classification': {'tags': classification}\n }\n services.inventory.update_inventory_classification(**data)\n\n # for image in inv:\n # inventory_id = image['inventory_id']\n #\n # try:\n # if inv := services.inventory.get_inventory_item(inventory_id=inventory_id).to_dict():\n # cv2.imshow(image['file'], image['full_path'])\n # # cv2.imwrite(\"tests/samples/ml/test/output.jpg\", image)\n # cv2.waitKey(0)\n # # cv2.destroyAllWindows()\n # if inv['classification']:\n # print(f\"Current Tags: {inv['classification']['tags']}\")\n #\n # tag_values = [item.strip() for item in input(\"Input Tags (separated by comma): \").split(',')]\n # data = {\n # 'inventory_id': inventory_id,\n # 'classification': {'tags': tag_values},\n # 'model_assignment': input(\"Model Assignment Name: \") if incl_assignment else inv['model_assignment']\n # }\n # services.inventory.update_inventory_classification(**data)\n #\n # cv2.destroyAllWindows()\n # except:\n # raise\n\n#5351dd023ef1440393b81ec0acbe2f4a\n" ]
[ [ "pandas.DataFrame" ] ]
toothlessLi/crnn_keras
[ "1179a82a732b83482c40176350062b3aca4fc0ab" ]
[ "testing/test.py" ]
[ "import keras\nimport tensorflow as tf\nimport keras.backend.tensorflow_backend as K\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n# config.gpu_options.per_process_gpu_memory_fraction = 0.9\nsess = tf.Session(config=config)\nK.set_session(sess)\n\nimport os\nimport sys\n\nsys.path.insert(0, '../')\nfrom models.crnn import crnn\nfrom data_utils.transform import reshape_to_target, pre_processing\nfrom .ctc_decode import ctc_decode as cd\n\nimport yaml\nimport cv2\nimport numpy as np\nfrom easydict import EasyDict as ET\nfrom tqdm import tqdm\nimport difflib\n\n\ndef main(args):\n f = open(args.config)\n cfgs = yaml.load(f)\n f.close()\n cfgs = ET(cfgs)\n test_list = cfgs.TEST_LIST\n image_size = cfgs.IMAGE_SIZE\n charset = cfgs.CHARSET\n weight = cfgs.WEIGHT\n\n h, w, c = image_size.split(',')\n image_size = (int(h), int(w), int(c))\n\n with open(charset) as f:\n charset = f.readline().strip('\\n')\n f.close()\n nb_classes = len(charset) + 1\n\n model, *_ = crnn(nb_classes, image_size)\n model.load_weights(weight, by_name=True)\n\n test_list = open(test_list).readlines()\n line_acc = 0.\n char_acc = 0.\n total_test = 0\n print('start test..')\n for item in tqdm(test_list):\n img_path, label_str = item.strip('\\n').split('\\t')\n img = cv2.imread(img_path)\n if img is None:\n continue\n img = reshape_to_target(img, image_size)\n if img is None:\n continue\n img = pre_processing(img)\n img = np.expand_dims(img, axis=0)\n\n prob = model.predict(img)\n result_str = cd(prob, charset)\n\n # compute str score\n score = difflib.SequenceMatcher(None, result_str, label_str).ratio()\n if score == 1.0:\n line_acc += 1.0\n char_acc += score\n total_test += 1\n print('test done..')\n print('Line-wise acc: {}%'.format((line_acc/total_test)*100))\n print('Char-wise acc: {}%'.format((char_acc/total_test)*100))\n" ]
[ [ "numpy.expand_dims", "tensorflow.ConfigProto", "tensorflow.Session" ] ]
jiyuanzFB/pytorch
[ "d047e475f830631d8fcc877ea17eac8fb34748d7" ]
[ "torch/distributed/algorithms/model_averaging/hierarchical_model_averager.py" ]
[ "# Copyright 2022 Cruise LLC\nimport warnings\nfrom collections import OrderedDict\nimport logging\n\nimport torch.distributed as dist\nimport torch.distributed.algorithms.model_averaging.utils as utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass HierarchicalModelAverager:\n r\"\"\"\n A group of model averagers used for hierarchical model averaging (hierarchical SGD).\n Process groups of different sizes are organized in a hierarhicy, and they average parameters\n by using different periods concurrently after the warm-up stage.\n This is an extension of :class:`~torch.distributed.algorithms.model_averaging.averagers.PeriodicModelAverager`\n that supports `post-local SGD <https://arxiv.org/abs/1808.07217>`_, which essentially only supports\n a two-level hierarchy: the intra-machine level and the global level, where the intra-machine\n level is usually embedded in :meth:`~torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook`.\n Similarly, the process groups within this class do not have such an intra-machine process\n subgroup, which should be embedded by the post-local SGD communication hook instead.\n\n Args:\n period_group_size_dict: An ordered dict mapping keys of model averaging period to\n process group size, used for initializing process groups of\n different sizes in a hierarchy to average parameters concurrently.\n Particularly, at each iteration, there will be at most a single\n process group that runs averaging -- the period of such group should\n have the largest period which the current step can be divided by.\n For example, if the dict has three keys: 2, 4, and 8,\n then this means totally three process groups will be created to\n average parameters every 2, 4, and 8 iterations, respectively.\n At the 4th iteration, only the second process group will run\n averaging, because the first process group should be a\n subset of the second process group, and no need to execute the first\n process group redundantly.\n On the other hand, the third process group can only be triggered\n every 8 iterations, so it will not be triggered at the 4th iteration.\n warmup_steps (int): The number of warm-up steps. During this stage, model averaging is skipped.\n process_group (ProcessGroup, optional): The overall process group containing all the processes that runs model averaging.\n If ``None``, the default process group, which is created\n by :func:`torch.distributed.init_process_group`, will be used.\n (default: ``None``)\n\n Example::\n >>> from collections import OrderedDict\n >>> import torch\n >>> import torch.distributed as dist\n >>> from torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook import (\n >>> PostLocalSGDState,\n >>> post_localSGD_hook,\n >>> )\n >>> import torch.distributed.algorithms.model_averaging.hierarchical_model_averager as hierarchicalSGD\n >>> import torch.nn as nn\n >>>\n >>> dist.init_process_group(\"nccl\", rank=rank, world_size=16)\n >>> torch.cuda.set_device(rank)\n >>> module = nn.Linear(1, 1, bias=False).to(rank)\n >>> model = nn.parallel.DistributedDataParallel(\n >>> module, device_ids=[rank], output_device=rank\n >>> )\n >>> # Register a post-localSGD communication hook.\n >>> # Assume that each machine has 4 GPUs, then each intra-machine subgroup has a size of 4.\n >>> subgroup, _ = dist.new_subgroups()\n >>> state = PostLocalSGDState(subgroup=subgroup, start_localSGD_iter=100)\n >>> model.register_comm_hook(state, post_localSGD_hook)\n >>>\n >>> # Average parameters among each group of 8 processes every 4 iterations, and among all\n >>> # the 16 processes every 16 iterations.\n >>> averager = hierarchicalSGD.HierarchicalModelAverager(\n >>> period_group_size_dict=OrderedDict([(4, 8), (16, 16)]), warmup_steps=100)\n >>> # Note that ``warmup_steps`` must be the same as ``start_localSGD_iter`` used in ``PostLocalSGDState``.\n >>> # In the first 100 steps, run global gradient averaging like normal DDP at every step.\n >>> # After 100 steps, run model averaging at two levels.\n >>> for step in range(0, 200):\n >>> optimizer.zero_grad()\n >>> loss = loss_fn(output, labels)\n >>> loss.backward()\n >>> optimizer.step()\n >>> # Average parameters after ``optimizer.step()``.\n >>> # Thus, the inter-node communication only occurs periodically after ``warmup_steps``.\n >>> averager.average_parameters(model.parameters())\n\n .. warning ::\n The last group size in the dict must be the size of the provided ``process_group``,\n which indicates model averaging at the highest level of the hierarchy.\n If ``process_group`` is not provided, then the last group size should be equal to the world size.\n\n .. warning ::\n `HierarchicalModelAverager` is experimental and subject to change.\n \"\"\"\n\n def __init__(self, period_group_size_dict=None, warmup_steps=0, process_group=None):\n if not period_group_size_dict:\n raise ValueError(\"Arg ``period_group_size_dict`` must not be empty.\")\n self._periods = list(period_group_size_dict.keys())\n if self._periods[0] <= 0:\n raise ValueError(\"The minimum period in arg ``period_group_size_dict`` must be a positive value.\")\n elif self._periods[-1] == 1:\n warnings.warn(\n \"When the maximum period in arg ``period_group_size_dict`` is 1, \"\n \"no need to use model averaging because the communication cost \"\n \"of all-reducing parameters will be no less than the cost of all-reducing gradients \"\n \"by DistributedDataParallel in the backward pass. Therefore, only \"\n \"DistributedDataParallel should be used for this case.\"\n )\n ovall_group : dist.ProcessGroup = (\n process_group if process_group is not None else dist.group.WORLD\n )\n overall_group_size = dist.get_world_size(group=ovall_group)\n if list(period_group_size_dict.values())[-1] != overall_group_size:\n raise ValueError(\n \"The last value in arg ``period_process_group_dict`` \"\n \"must be equal to the size of arg ``process_group``.\")\n\n self.period_process_group_dict = OrderedDict()\n logger.info(\"Model averaging hierarchy:\")\n for period, group_size in period_group_size_dict.items():\n logger.info(\n f\"\\tEach group that has {group_size} processes average parameters every {period} iterations, \"\n \"if no higher-level averaging.\")\n if group_size != overall_group_size:\n self.period_process_group_dict[period], _ = dist.new_subgroups(\n group_size=group_size, group=ovall_group)\n else:\n self.period_process_group_dict[period] = ovall_group\n\n if warmup_steps < 0:\n raise ValueError(\"Arg ``warmup_steps`` must be a non-negative number.\")\n self.warmup_steps = warmup_steps\n self.step = 0\n\n def _find_process_group(self):\n \"\"\"\n Returns a tuple consisting of whether ``step`` can be divided by\n a period in the keys of ``period_process_group_dict`` and the associated process group if any.\n If ``step`` can be divided by multiple periods in the keys of ``period_process_group_dict``,\n then the returned process group is the one corresponding to the largest period,\n since this process group will be used for averaging parameters at this ``step``.\n \"\"\"\n for period in reversed(self._periods):\n if self.step % period == 0:\n return (True, self.period_process_group_dict[period])\n return (False, None)\n\n def average_parameters(self, params):\n r\"\"\"\n Averages parameters if ``step`` is no less than ``warmup_steps``\n and it can be divided by a period in the keys of ``period_process_group_dict``,\n where ``step`` is increased by 1 at each iteration in the training loop.\n If ``step`` can be divided by multiple periods in the keys of ``period_process_group_dict``,\n only the largest period is used, and the corresponding process group is used for averaging parameters.\n \"\"\"\n if self.step >= self.warmup_steps:\n found, group = self._find_process_group()\n if found:\n utils.average_parameters(iter(params), group)\n self.step += 1\n" ]
[ [ "torch.distributed.get_world_size", "torch.distributed.new_subgroups" ] ]
AnthonyNg404/Deep-Learning
[ "ef1dafaa1d07e9c9b574ba1722a7954c16ef463d", "ef1dafaa1d07e9c9b574ba1722a7954c16ef463d" ]
[ "assignment2/deeplearning/gradient_check.py", "assignment1/deeplearning/gradient_check.py" ]
[ "import numpy as np\nfrom random import randrange\n\ndef eval_numerical_gradient(f, x, verbose=True, h=0.00001):\n \"\"\"\n a naive implementation of numerical gradient of f at x\n - f should be a function that takes a single argument\n - x is the point (numpy array) to evaluate the gradient at\n \"\"\"\n\n fx = f(x) # evaluate function value at original point\n grad = np.zeros_like(x)\n # iterate over all indexes in x\n it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n while not it.finished:\n\n # evaluate function at x+h\n ix = it.multi_index\n oldval = x[ix]\n x[ix] = oldval + h # increment by h\n fxph = f(x) # evalute f(x + h)\n x[ix] = oldval - h\n fxmh = f(x) # evaluate f(x - h)\n x[ix] = oldval # restore\n\n # compute the partial derivative with centered formula\n grad[ix] = (fxph - fxmh) / (2 * h) # the slope\n if verbose:\n print(ix, grad[ix])\n it.iternext() # step to next dimension\n\n return grad\n\n\ndef eval_numerical_gradient_array(f, x, df, h=1e-5):\n \"\"\"\n Evaluate a numeric gradient for a function that accepts a numpy\n array and returns a numpy array.\n \"\"\"\n grad = np.zeros_like(x)\n it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n while not it.finished:\n ix = it.multi_index\n\n oldval = x[ix]\n x[ix] = oldval + h\n pos = f(x).copy()\n x[ix] = oldval - h\n neg = f(x).copy()\n x[ix] = oldval\n\n grad[ix] = np.sum((pos - neg) * df) / (2 * h)\n it.iternext()\n return grad\n\n\ndef eval_numerical_gradient_blobs(f, inputs, output, h=1e-5):\n \"\"\"\n Compute numeric gradients for a function that operates on input\n and output blobs.\n\n We assume that f accepts several input blobs as arguments, followed by a\n blob where outputs will be written. For example, f might be called like:\n\n f(x, w, out)\n\n where x and w are input Blobs, and the result of f will be written to out.\n\n Inputs:\n - f: function\n - inputs: tuple of input blobs\n - output: output blob\n - h: step size\n \"\"\"\n numeric_diffs = []\n for input_blob in inputs:\n diff = np.zeros_like(input_blob.diffs)\n it = np.nditer(input_blob.vals, flags=['multi_index'],\n op_flags=['readwrite'])\n while not it.finished:\n idx = it.multi_index\n orig = input_blob.vals[idx]\n\n input_blob.vals[idx] = orig + h\n f(*(inputs + (output,)))\n pos = np.copy(output.vals)\n input_blob.vals[idx] = orig - h\n f(*(inputs + (output,)))\n neg = np.copy(output.vals)\n input_blob.vals[idx] = orig\n\n diff[idx] = np.sum((pos - neg) * output.diffs) / (2.0 * h)\n\n it.iternext()\n numeric_diffs.append(diff)\n return numeric_diffs\n\n\ndef eval_numerical_gradient_net(net, inputs, output, h=1e-5):\n return eval_numerical_gradient_blobs(lambda *args: net.forward(),\n inputs, output, h=h)\n\n\ndef grad_check_sparse(f, x, analytic_grad, num_checks=10, h=1e-5):\n \"\"\"\n sample a few random elements and only return numerical\n in this dimensions.\n \"\"\"\n\n for i in range(num_checks):\n ix = tuple([randrange(m) for m in x.shape])\n\n oldval = x[ix]\n x[ix] = oldval + h # increment by h\n fxph = f(x) # evaluate f(x + h)\n x[ix] = oldval - h # increment by h\n fxmh = f(x) # evaluate f(x - h)\n x[ix] = oldval # reset\n\n grad_numerical = (fxph - fxmh) / (2 * h)\n grad_analytic = analytic_grad[ix]\n rel_error = (abs(grad_numerical - grad_analytic) /\n (abs(grad_numerical) + abs(grad_analytic)))\n print('numerical: %f analytic: %f, relative error: %e'\n %(grad_numerical, grad_analytic, rel_error))\n", "import numpy as np\nfrom random import randrange\n\n\ndef eval_numerical_gradient(f, x, verbose=True, h=0.00001):\n \"\"\"\n a naive implementation of numerical gradient of f at x\n - f should be a function that takes a single argument\n - x is the point (numpy array) to evaluate the gradient at\n \"\"\"\n\n fx = f(x) # evaluate function value at original point\n grad = np.zeros_like(x)\n # iterate over all indexes in x\n it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n while not it.finished:\n\n # evaluate function at x+h\n ix = it.multi_index\n oldval = x[ix]\n x[ix] = oldval + h # increment by h\n fxph = f(x) # evalute f(x + h)\n x[ix] = oldval - h\n fxmh = f(x) # evaluate f(x - h)\n x[ix] = oldval # restore\n\n # compute the partial derivative with centered formula\n grad[ix] = (fxph - fxmh) / (2 * h) # the slope\n if verbose:\n print(ix, grad[ix])\n it.iternext() # step to next dimension\n\n return grad\n\n\ndef eval_numerical_gradient_array(f, x, df, h=1e-5):\n \"\"\"\n Evaluate a numeric gradient for a function that accepts a numpy\n array and returns a numpy array.\n \"\"\"\n grad = np.zeros_like(x)\n it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])\n while not it.finished:\n ix = it.multi_index\n\n oldval = x[ix]\n x[ix] = oldval + h\n pos = f(x).copy()\n x[ix] = oldval - h\n neg = f(x).copy()\n x[ix] = oldval\n\n grad[ix] = np.sum((pos - neg) * df) / (2 * h)\n it.iternext()\n return grad\n\n\ndef eval_numerical_gradient_blobs(f, inputs, output, h=1e-5):\n \"\"\"\n Compute numeric gradients for a function that operates on input\n and output blobs.\n\n We assume that f accepts several input blobs as arguments, followed by a blob\n into which outputs will be written. For example, f might be called like this:\n\n f(x, w, out)\n\n where x and w are input Blobs, and the result of f will be written to out.\n\n Inputs:\n - f: function\n - inputs: tuple of input blobs\n - output: output blob\n - h: step size\n \"\"\"\n numeric_diffs = []\n for input_blob in inputs:\n diff = np.zeros_like(input_blob.diffs)\n it = np.nditer(input_blob.vals, flags=['multi_index'],\n op_flags=['readwrite'])\n while not it.finished:\n idx = it.multi_index\n orig = input_blob.vals[idx]\n\n input_blob.vals[idx] = orig + h\n f(*(inputs + (output,)))\n pos = np.copy(output.vals)\n input_blob.vals[idx] = orig - h\n f(*(inputs + (output,)))\n neg = np.copy(output.vals)\n input_blob.vals[idx] = orig\n\n diff[idx] = np.sum((pos - neg) * output.diffs) / (2.0 * h)\n\n it.iternext()\n numeric_diffs.append(diff)\n return numeric_diffs\n\n\ndef eval_numerical_gradient_net(net, inputs, output, h=1e-5):\n return eval_numerical_gradient_blobs(lambda *args: net.forward(),\n inputs, output, h=h)\n\n\ndef grad_check_sparse(f, x, analytic_grad, num_checks=10, h=1e-5):\n \"\"\"\n sample a few random elements and only return numerical\n in this dimensions.\n \"\"\"\n\n for i in range(num_checks):\n ix = tuple([randrange(m) for m in x.shape])\n\n oldval = x[ix]\n x[ix] = oldval + h # increment by h\n fxph = f(x) # evaluate f(x + h)\n x[ix] = oldval - h # increment by h\n fxmh = f(x) # evaluate f(x - h)\n x[ix] = oldval # reset\n\n grad_numerical = (fxph - fxmh) / (2 * h)\n grad_analytic = analytic_grad[ix]\n rel_error = abs(grad_numerical - grad_analytic) / (abs(grad_numerical) + abs(grad_analytic))\n print('numerical: %f analytic: %f, relative error: %e' % (grad_numerical, grad_analytic, rel_error))\n" ]
[ [ "numpy.nditer", "numpy.zeros_like", "numpy.sum", "numpy.copy" ], [ "numpy.nditer", "numpy.zeros_like", "numpy.sum", "numpy.copy" ] ]
kmaterna/Utility_Code
[ "f713a3ce2a80d2e6dbdc42596451405bb873adbb" ]
[ "Tectonic_Utils/read_write/test/test_conversion_functions.py" ]
[ "# Testing code\n\nimport numpy as np\nimport unittest\nimport subprocess\nfrom .. import netcdf_read_write\n\n\nclass Tests(unittest.TestCase):\n\n def test_pixel_node_writer(self):\n \"\"\"\n See if the writing function for pixel-node files produces a pixel-node file.\n The behavior has been finicky for float32 vs float64\n Writing a full test for float32 would be good (although the example grd file gets pretty close)\n \"\"\"\n grid_def = [-120, -114, 32, 37];\n inc = [0.02, 0.02];\n filename = 'test_outfile.nc'\n lons = np.arange(grid_def[0], grid_def[1] + 0.00001, inc[0])\n lats = np.arange(grid_def[2], grid_def[3] + 0.00001, inc[1])\n\n # Test a write function\n grid = np.zeros((len(lats), len(lons)));\n netcdf_read_write.write_netcdf4(lons, lats, grid, filename);\n netcdf_read_write.parse_pixelnode_registration(filename);\n subprocess.call(['rm', filename], shell=False);\n subprocess.call(['rm', 'gmt.history'], shell=False);\n\n # Test a read-write cycle on an example grid\n [x, y, z] = netcdf_read_write.read_any_grd(\"Tectonic_Utils/read_write/test/example_grd.grd\");\n netcdf_read_write.write_netcdf4(x, y, z, \"Tectonic_Utils/read_write/test/written_example.grd\");\n netcdf_read_write.parse_pixelnode_registration(\"Tectonic_Utils/read_write/test/written_example.grd\");\n subprocess.call(['rm', 'gmt.history'], shell=False);\n\n return;\n\n\nif __name__ == \"__main__\":\n unittest.main();\n" ]
[ [ "numpy.arange" ] ]
davisidarta/dynamo-release
[ "0dbd769f52ea07f3cdaa8fb31022ceb89938c382" ]
[ "dynamo/tools/_dynamics_deprecated.py" ]
[ "import warnings\nimport numpy as np\nfrom .utils_moments import moments\nfrom .velocity import velocity, ss_estimation\nfrom .utils import (\n get_mapper,\n get_valid_bools,\n get_data_for_kin_params_estimation,\n get_U_S_for_velocity_estimation,\n)\nfrom .utils import set_velocity, set_param_ss, set_param_kinetic\nfrom .moments import moment_model\n\n# incorporate the model selection code soon\ndef _dynamics(\n adata,\n tkey=None,\n filter_gene_mode=\"final\",\n mode=\"moment\",\n use_smoothed=True,\n group=None,\n protein_names=None,\n experiment_type=None,\n assumption_mRNA=None,\n assumption_protein=\"ss\",\n NTR_vel=True,\n concat_data=False,\n log_unnormalized=True,\n one_shot_method=\"combined\",\n):\n \"\"\"Inclusive model of expression dynamics considers splicing, metabolic labeling and protein translation. It supports\n learning high-dimensional velocity vector samples for droplet based (10x, inDrop, drop-seq, etc), scSLAM-seq, NASC-seq\n sci-fate, scNT-seq or cite-seq datasets.\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData`\n AnnData object.\n tkey: `str` or None (default: None)\n The column key for the time label of cells in .obs. Used for either \"steady_state\" or non-\"steady_state\" mode or `moment`\n mode with labeled data.\n filter_gene_mode: `str` (default: `final`)\n The string for indicating which mode (one of, {'final', 'basic', 'no'}) of gene filter will be used.\n mode: `str` (default: `deterministic`)\n String indicates which estimation mode will be used. This parameter should be used in conjunction with assumption_mRNA.\n * Available options when the `assumption_mRNA` is 'ss' include:\n (1) 'linear_regression': The canonical method from the seminar RNA velocity paper based on deterministic ordinary\n differential equations;\n (2) 'gmm': The new generalized methods of moments from us that is based on master equations, similar to the\n \"moment\" mode in the excellent scvelo package;\n (3) 'negbin': The new method from us that models steady state RNA expression as a negative binomial distribution,\n also built upons on master equations.\n Note that all those methods require using extreme data points (except negbin) for the estimation. Extreme data points\n are defined as the data from cells where the expression of unspliced / spliced or new / total RNA, etc. are in the\n top or bottom, 5%, for example. `linear_regression` only considers the mean of RNA species (based on the deterministic\n ordinary different equations) while moment based methods (`gmm`, `negbin`) considers both first moment (mean) and\n second moment (uncentered variance) of RNA species (based on the stochastic master equations).\n * Available options when the `assumption_mRNA` is 'kinetic' include:\n (1) 'deterministic': The method based on deterministic ordinary differential equations;\n (2) 'stochastic' or `moment`: The new method from us that is based on master equations;\n Note that `kinetic` model implicitly assumes the `experiment_type` is not `conventional`. Thus `deterministic`,\n `stochastic` (equivalent to `moment`) models are only possible for the labeling experiments.\n A \"model_selection\" mode will be supported soon in which alpha, beta and gamma will be modeled as a function of time.\n use_smoothed: `bool` (default: `True`)\n Whether to use the smoothed data when calculating velocity for each gene. `use_smoothed` is only relevant when\n mode is `linear_regression` (and experiment_type and assumption_mRNA correspond to `conventional` and `ss` implicitly).\n group: `str` or None (default: `None`)\n The column key/name that identifies the grouping information (for example, clusters that correspond to different cell types)\n of cells. This will be used to estimate group-specific (i.e cell-type specific) kinetic parameters.\n protein_names: `List`\n A list of gene names corresponds to the rows of the measured proteins in the `X_protein` of the `obsm` attribute.\n The names have to be included in the adata.var.index.\n experiment_type: `str`\n single cell RNA-seq experiment type. Available options are:\n (1) 'conventional': conventional single-cell RNA-seq experiment;\n (2) 'deg': chase/degradation experiment;\n (3) 'kin': pulse/synthesis/kinetics experiment;\n (4) 'one-shot': one-shot kinetic experiment.\n assumption_mRNA: `str`\n Parameter estimation assumption for mRNA. Available options are:\n (1) 'ss': pseudo steady state;\n (2) 'kinetic' or None: degradation and kinetic data without steady state assumption.\n If no labelling data exists, assumption_mRNA will automatically set to be 'ss'. For one-shot experiment, assumption_mRNA\n is set to be None. However we will use steady state assumption to estimate parameters alpha and gamma either by a deterministic\n linear regression or the first order decay approach in line of the sci-fate paper.\n assumption_protein: `str`\n Parameter estimation assumption for protein. Available options are:\n (1) 'ss': pseudo steady state;\n NTR_vel: `bool` (default: `True`)\n Whether to use NTR (new/total ratio) velocity for labeling datasets.\n concat_data: `bool` (default: `False`)\n Whether to concatenate data before estimation. If your data is a list of matrices for each time point, this need to be set as True.\n log_unnormalized: `bool` (default: `True`)\n Whether to log transform the unnormalized data.\n\n Returns\n -------\n adata: :class:`~anndata.AnnData`\n A updated AnnData object with estimated kinetic parameters and inferred velocity included.\n \"\"\"\n\n if (\n \"use_for_dynamics\" not in adata.var.columns\n and \"pass_basic_filter\" not in adata.var.columns\n ):\n filter_gene_mode = \"no\"\n\n valid_ind = get_valid_bools(adata, filter_gene_mode)\n\n if mode == \"moment\" or (\n use_smoothed and len([i for i in adata.layers.keys() if i.startswith(\"M_\")]) < 2\n ):\n if experiment_type == \"kin\":\n use_smoothed = False\n else:\n moments(adata)\n\n valid_adata = adata[:, valid_ind].copy()\n if group is not None and group in adata.obs[group]:\n _group = adata.obs[group].unique()\n else:\n _group = [\"_all_cells\"]\n\n for cur_grp in _group:\n if cur_grp == \"_all_cells\":\n kin_param_pre = \"\"\n cur_cells_bools = np.ones(valid_adata.shape[0], dtype=bool)\n subset_adata = valid_adata[cur_cells_bools]\n else:\n kin_param_pre = group + \"_\" + cur_grp + \"_\"\n cur_cells_bools = (valid_adata.obs[group] == cur_grp).values\n subset_adata = valid_adata[cur_cells_bools]\n\n (\n U,\n Ul,\n S,\n Sl,\n P,\n US,\n S2,\n t,\n normalized,\n has_splicing,\n has_labeling,\n has_protein,\n ind_for_proteins,\n assumption_mRNA,\n exp_type,\n ) = get_data_for_kin_params_estimation(\n subset_adata,\n mode,\n use_smoothed,\n tkey,\n protein_names,\n experiment_type,\n log_unnormalized,\n NTR_vel,\n )\n\n if exp_type is not None:\n if experiment_type != exp_type:\n warnings.warn(\n \"dynamo detects the experiment type of your data as {}, but your input experiment_type \"\n \"is {}\".format(exp_type, experiment_type)\n )\n\n experiment_type = exp_type\n assumption_mRNA = (\n \"ss\" if exp_type == \"conventional\" and mode == \"deterministic\" else None\n )\n NTR_vel = False\n\n if mode == \"moment\" and experiment_type not in [\"conventional\", \"kin\"]:\n \"\"\"\n # temporially convert to deterministic mode as moment mode for one-shot, \n degradation and other types of labeling experiment is ongoing.\"\"\"\n\n mode = \"deterministic\"\n\n if mode == \"deterministic\" or (\n experiment_type != \"kin\" and mode == \"moment\"\n ):\n est = ss_estimation(\n U=U,\n Ul=Ul,\n S=S,\n Sl=Sl,\n P=P,\n US=US,\n S2=S2,\n t=t,\n ind_for_proteins=ind_for_proteins,\n experiment_type=experiment_type,\n assumption_mRNA=assumption_mRNA,\n assumption_protein=assumption_protein,\n concat_data=concat_data,\n )\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n if experiment_type in [\"one-shot\", \"one_shot\"]:\n est.fit(one_shot_method=one_shot_method)\n else:\n est.fit()\n\n alpha, beta, gamma, eta, delta = est.parameters.values()\n\n U, S = get_U_S_for_velocity_estimation(\n subset_adata,\n use_smoothed,\n has_splicing,\n has_labeling,\n log_unnormalized,\n NTR_vel,\n )\n vel = velocity(estimation=est)\n vel_U = vel.vel_u(U)\n vel_S = vel.vel_s(U, S)\n vel_P = vel.vel_p(S, P)\n\n adata = set_velocity(\n adata,\n vel_U,\n vel_S,\n vel_P,\n _group,\n cur_grp,\n cur_cells_bools,\n valid_ind,\n ind_for_proteins,\n )\n\n adata = set_param_ss(\n adata,\n est,\n alpha,\n beta,\n gamma,\n eta,\n delta,\n experiment_type,\n _group,\n cur_grp,\n kin_param_pre,\n valid_ind,\n ind_for_proteins,\n )\n\n elif mode == \"moment\":\n adata, Est, t_ind = moment_model(\n adata, subset_adata, _group, cur_grp, log_unnormalized, tkey\n )\n t_ind += 1\n\n params, costs = Est.fit()\n a, b, alpha_a, alpha_i, beta, gamma = (\n params[:, 0],\n params[:, 1],\n params[:, 2],\n params[:, 3],\n params[:, 4],\n params[:, 5],\n )\n\n def fbar(x_a, x_i, a, b):\n return b / (a + b) * x_a + a / (a + b) * x_i\n\n alpha = fbar(alpha_a, alpha_i, a, b)[:, None]\n\n params = {\"alpha\": alpha, \"beta\": beta, \"gamma\": gamma, \"t\": t}\n vel = velocity(**params)\n\n U, S = get_U_S_for_velocity_estimation(\n subset_adata,\n use_smoothed,\n has_splicing,\n has_labeling,\n log_unnormalized,\n NTR_vel,\n )\n vel_U = vel.vel_u(U)\n vel_S = vel.vel_s(U, S)\n vel_P = vel.vel_p(S, P)\n\n adata = set_velocity(\n adata,\n vel_U,\n vel_S,\n vel_P,\n _group,\n cur_grp,\n cur_cells_bools,\n valid_ind,\n ind_for_proteins,\n )\n\n adata = set_param_kinetic(\n adata,\n alpha,\n a,\n b,\n alpha_a,\n alpha_i,\n beta,\n gamma,\n kin_param_pre,\n _group,\n cur_grp,\n valid_ind,\n )\n # add protein related parameters in the moment model below:\n elif mode == \"model_selection\":\n warnings.warn(\"Not implemented yet.\")\n\n if group is not None and group in adata.obs[group]:\n uns_key = group + \"_dynamics\"\n else:\n uns_key = \"dynamics\"\n\n if has_splicing and has_labeling:\n adata.layers['X_U'], adata.layers['X_S'] = adata.layers['X_uu'] + adata.layers['X_ul'], adata.layers['X_su'] + adata.layers['X_sl']\n\n adata.uns[uns_key] = {\n \"t\": t,\n \"group\": group,\n \"asspt_mRNA\": assumption_mRNA,\n \"experiment_type\": experiment_type,\n \"normalized\": normalized,\n \"mode\": mode,\n \"has_splicing\": has_splicing,\n \"has_labeling\": has_labeling,\n \"has_protein\": has_protein,\n \"use_smoothed\": use_smoothed,\n \"NTR_vel\": NTR_vel,\n \"log_unnormalized\": log_unnormalized,\n }\n\n return adata\n" ]
[ [ "numpy.ones" ] ]
victor-tuda/chatbot
[ "3cadd018759344991c77e2aa86b8965ed0271789" ]
[ "training.py" ]
[ "import random\nimport json\nimport pickle\nimport numpy as np\n\nimport nltk\nnltk.download('punkt')\nnltk.download('wordnet')\nfrom nltk.stem import WordNetLemmatizer\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation, Dropout\nfrom tensorflow.keras.optimizers import SGD\n\nlemmatizer = WordNetLemmatizer()\n\nintents = json.loads(open('./intents.json').read())\n\nwords = []\nclasses = []\ndocuments = []\nignore_letters = ['?', '!', '@', ',', ';', '.']\n\nfor intent in intents['intents']:\n for pattern in intent['patterns']:\n word_list = nltk.word_tokenize(pattern)\n words.extend(word_list)\n documents.append((word_list, intent['tag']))\n if intent['tag'] not in classes:\n classes.append(intent['tag'])\n\nwords = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]\nwords = sorted(set(words))\n\nclasses = sorted(set(classes))\n\npickle.dump(words, open('words.pkl', 'wb'))\npickle.dump(classes, open('classes.pkl', 'wb'))\n\ntraining = []\noutput_empty = [0] * len(classes)\n\nfor document in documents:\n bag = []\n word_patterns = document[0]\n word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]\n for word in word_patterns:\n bag.append(1) if word in word_patterns else bag.append(0)\n\n output_row = list(output_empty)\n output_row[classes.index(document[1])] = 1\n training.append([bag, output_row])\n\nrandom.shuffle(training)\ntraining = np.array(training)\n\ntrain_x = list(training[:, 0])\ntrain_y = list(training[:, 1])\n\nmodel = Sequential()\nmodel.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(len(train_y[0]), activation='softmax'))\n\nsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\nmodel.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n\nhist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)\nmodel.save('chatbot_model.model.h5', hist)\n\nprint('Done')\n" ]
[ [ "tensorflow.keras.models.Sequential", "tensorflow.keras.layers.Dropout", "tensorflow.keras.optimizers.SGD", "tensorflow.keras.layers.Dense", "numpy.array" ] ]
ppplinday/Situation-Awareness-Visualization
[ "13b233a1119b21f55e61d81d7d584d45d57a7385" ]
[ "myapp.py" ]
[ "import os\nimport json\nimport numpy as np\nimport pandas as pd\nimport datetime\n\nimport SAVIZ.situation_awareness_visualization as saviz\n\nwith open(\"tempfile.json\", 'r') as f:\n\n\tjson_file = f.readlines()[0]\n\nhas_type = True\nhas_time = False\ntimeRange = [0, 1]\n\nwith open(\"tempconfig.json\", 'r') as f:\n\n\tconfig = f.readlines()[0]\n\thas_type = json.loads(config)['has_type']\n\thas_time = json.loads(config)['has_time']\n\n\tif has_time == True:\n\t\ttimeRange[0] = json.loads(config)['time_min']\n\t\ttimeRange[1] = json.loads(config)['time_max']\n\t\ttimeRange[0] = datetime.datetime.strptime(timeRange[0], \"%Y-%m-%dT%H:%M:%S\")\n\t\ttimeRange[1] = datetime.datetime.strptime(timeRange[1], \"%Y-%m-%dT%H:%M:%S\")\n\ndata = json.loads(json_file)\nif \"time_value\" in data:\n\tfor i in range(len(data[\"time_value\"])):\n\t\tdata[\"time_value\"][i] = datetime.datetime.strptime(data[\"time_value\"][i], \"%Y-%m-%dT%H:%M:%S\")\n\n# convert the json to dataframe\n\npd_data = pd.DataFrame.from_dict(data)\nif \"time_value\" in data:\n\tpd_data['time_value'] = pd.to_datetime(pd_data['time_value'])\nsav = saviz.saviz_visualization(pd_data, has_type, has_time, timeRange)\n\n# build tooltips\ntp = sav.set_tooltips()\n\nsp = sav.build()\n\t" ]
[ [ "pandas.to_datetime", "pandas.DataFrame.from_dict" ] ]
MortisHuang/VIFFI-image-analysis
[ "ad144970e9cb53d61119dd96370157251c03cc07" ]
[ "SFig11_Whitecell_Cell_Area.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 14 11:30:55 2019\r\n\r\n@author: Mortis Huang\r\n\"\"\"\r\n\r\n# import the necessary packages\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport datetime\r\nimport os\r\nimport pandas as pd\r\n#%% Set the output file location\r\nrun_data = datetime.datetime.now().strftime(\"%Y_%m_%d\")\r\nresult_path=r\"SFig11_{}/\".format(run_data)\r\nif not os.path.exists(result_path):\r\n os.makedirs(result_path)\r\n \r\n#%% Read Traget Folders' Path\r\nlabels=['neutrophyl','lymphocyte']\r\n#base_path = r'E:\\DeepLearning\\Mikami\\Generate\\White Cell'\r\nbase_path = r'.\\Whitecell'\r\n\r\nfile_list_lym = []\r\nfile_list_neu = []\r\nfor root, dirs, files in os.walk(base_path):\r\n for file in files:\r\n if file.endswith(\".tif\"):\r\n filename = os.path.join(root, file)\r\n file_size = os.path.getsize(filename)\r\n category_name = os.path.basename(root)\r\n if category_name == labels[0]:\r\n file_list_neu.append(filename)\r\n\r\n else :\r\n file_list_lym.append(filename)\r\n#%% Sort the file list\r\n#file_list_lym = sorted(file_list_lym, key=lambda x:int(x.split('_')[-1].split('.')[0]))\r\n#files_name_lym = sorted(files, key=lambda x:int(x.split('_')[-1].split('.')[0]))\r\n#%% Read image files and put in a list\r\ndata_number = 11000\r\n\r\nlabel='lymphocyte' # 'lymphocyte' or 'neutrophyl'\r\ndata_of_lym_cell = []\r\nfor i, filename in enumerate(file_list_lym[:data_number]):\r\n \r\n # Read the image file again (for insure) and calculate the nucleus area \r\n im = Image.open(filename)\r\n imarray = np.array(im)\r\n threadhold = np.max(imarray)*0.35\r\n imarray[imarray<threadhold]=0\r\n image = imarray[:,:,0]\r\n cell_area=np.count_nonzero(imarray) \r\n \r\n # Temp. the resluts\r\n\r\n data_of_lym_cell.append(cell_area)\r\n\r\nlabel='neutrophyl' # 'lymphocyte' or 'neutrophyl'\r\ndata_of_neu_name = []\r\ndata_of_neu_cell = []\r\n\r\n\r\nfor i, filename in enumerate(file_list_neu[:data_number]): \r\n # Read the image file again (for insure) and calculate the nucleus area \r\n im = Image.open(filename)\r\n imarray = np.array(im)\r\n threadhold = np.max(imarray)*0.35\r\n imarray[imarray<threadhold]=0\r\n image = imarray[:,:,0]\r\n cell_area=np.count_nonzero(imarray) \r\n \r\n # Temp. the resluts\r\n data_of_neu_cell.append(cell_area)\r\n\r\n\r\n#%% Remove zeros \r\ndata_of_lym_cell=np.asarray(data_of_lym_cell)\r\ndata_of_neu_cell=np.asarray(data_of_neu_cell)\r\ndata_of_lym_cell=data_of_lym_cell[data_of_lym_cell>0]\r\ndata_of_neu_cell=data_of_neu_cell[data_of_neu_cell>0]\r\n\r\n#%% Save the Results\r\ndata = {'lymphocyte':data_of_lym_cell}\r\ndf1 = pd.DataFrame(data)\r\ndata = {'neutrophyl':data_of_neu_cell}\r\ndf2 = pd.DataFrame(data)\r\ndf_all = pd.concat([df1,df2], ignore_index=True, axis=1)\r\ndf_all.columns = [\"Lymphocyte\",\"Neutrophyl\"] \r\nwriter = pd.ExcelWriter('{}SFig11_35_CellArea.xlsx'.format(result_path))\r\n#writer = pd.ExcelWriter('CellArea.xlsx')\r\ndf_all.to_excel(writer,'Sheet 1',float_format='%.2f') # float_format \r\nwriter.save()\r\n" ]
[ [ "pandas.DataFrame", "numpy.asarray", "numpy.count_nonzero", "numpy.max", "pandas.concat", "numpy.array" ] ]
tchaye59/torchutils
[ "ca7b01bf63b6c3adaa36a4a66dfd87e927ef2460" ]
[ "torchutils/losses/losses.py" ]
[ "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom torchutils import to_device\n\n\nclass FocalLoss(nn.Module):\n \"\"\"weighted version of Focal Loss\"\"\"\n\n def __init__(self, alpha=.25, gamma=2, device=None):\n super(FocalLoss, self).__init__()\n self.alpha = torch.tensor([alpha, 1 - alpha])\n # self.alpha = to_device(self.alpha, device=device)\n self.gamma = gamma\n\n def forward(self, inputs, targets):\n BCE_loss = F.binary_cross_entropy(inputs, targets.float(), reduction='none')\n targets = targets.long()\n at = self.alpha.to(targets.device).gather(0, targets.view(-1))\n pt = torch.exp(-BCE_loss)\n F_loss = at * (1 - pt) ** self.gamma * BCE_loss\n return F_loss.mean()\n\n\ndef binary_cross_entropy_weighted_focal_loss(y_pred, y_true, alpha=0.25, gamma=6, mask=None):\n return FocalLoss(alpha=alpha, gamma=gamma, )(y_pred, y_true)\n\n\ndef cross_entropy_focal_loss(y_pred, y_true, weight=None, alpha=0.25, gamma=6, mask=None):\n # important to add reduction='none' to keep per-batch-item loss\n ce_loss = F.cross_entropy(y_pred, y_true, reduction='none', weight=weight)\n pt = torch.exp(-ce_loss)\n focal_loss = (alpha * (1 - pt) ** gamma * ce_loss).mean() # mean over the batch\n return focal_loss\n\n\ndef binary_cross_entropy_focal_loss___(y_pred, y_true, alpha=0.25, gamma=6, mask=None):\n # important to add reduction='none' to keep per-batch-item loss\n ce_loss = F.binary_cross_entropy(y_pred, y_true, reduction='none')\n pt = torch.exp(-ce_loss)\n focal_loss = (alpha * (1 - pt) ** gamma * ce_loss).mean() # mean over the batch\n return focal_loss\n\n\ndef bce_focal_loss(alpha=0.25, gamma=6):\n def fn(y_pred, y_true, mask=None):\n return binary_cross_entropy_focal_loss___(y_pred, y_true, alpha, gamma, mask=mask)\n\n return fn\n\n\ndef ce_focal_loss(alpha=0.25, gamma=6):\n def fn(y_pred, y_true, mask=None):\n return cross_entropy_focal_loss(y_pred, y_true, alpha, gamma, mask=mask)\n\n return fn\n" ]
[ [ "torch.exp", "torch.tensor", "torch.nn.functional.binary_cross_entropy", "torch.nn.functional.cross_entropy" ] ]
Kenneth-Schroeder/pytorch_geometric
[ "f7ec9e964bfae1ce5fb21d9b2b30e9e717bf8e24", "f7ec9e964bfae1ce5fb21d9b2b30e9e717bf8e24" ]
[ "test/nn/functional/test_gini.py", "examples/proteins_mincut_pool.py" ]
[ "import torch\n\nfrom torch_geometric.nn.functional import gini\n\n\ndef test_gini():\n w = torch.tensor(\n [\n [0., 0., 0., 0.],\n [0., 0., 0., 1000.0]\n ]\n )\n assert torch.isclose(gini(w), torch.tensor(0.5))\n", "import os.path as osp\nfrom math import ceil\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Linear\nfrom torch_geometric.datasets import TUDataset\nfrom torch_geometric.loader import DataLoader\nfrom torch_geometric.nn import GCNConv, DenseGraphConv, dense_mincut_pool\nfrom torch_geometric.utils import to_dense_batch, to_dense_adj\n\npath = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'PROTEINS')\ndataset = TUDataset(path, name='PROTEINS').shuffle()\naverage_nodes = int(dataset.data.x.size(0) / len(dataset))\nn = (len(dataset) + 9) // 10\ntest_dataset = dataset[:n]\nval_dataset = dataset[n:2 * n]\ntrain_dataset = dataset[2 * n:]\ntest_loader = DataLoader(test_dataset, batch_size=20)\nval_loader = DataLoader(val_dataset, batch_size=20)\ntrain_loader = DataLoader(train_dataset, batch_size=20)\n\n\nclass Net(torch.nn.Module):\n def __init__(self, in_channels, out_channels, hidden_channels=32):\n super(Net, self).__init__()\n\n self.conv1 = GCNConv(in_channels, hidden_channels)\n num_nodes = ceil(0.5 * average_nodes)\n self.pool1 = Linear(hidden_channels, num_nodes)\n\n self.conv2 = DenseGraphConv(hidden_channels, hidden_channels)\n num_nodes = ceil(0.5 * num_nodes)\n self.pool2 = Linear(hidden_channels, num_nodes)\n\n self.conv3 = DenseGraphConv(hidden_channels, hidden_channels)\n\n self.lin1 = Linear(hidden_channels, hidden_channels)\n self.lin2 = Linear(hidden_channels, out_channels)\n\n def forward(self, x, edge_index, batch):\n x = F.relu(self.conv1(x, edge_index))\n\n x, mask = to_dense_batch(x, batch)\n adj = to_dense_adj(edge_index, batch)\n\n s = self.pool1(x)\n x, adj, mc1, o1 = dense_mincut_pool(x, adj, s, mask)\n\n x = F.relu(self.conv2(x, adj))\n s = self.pool2(x)\n\n x, adj, mc2, o2 = dense_mincut_pool(x, adj, s)\n\n x = self.conv3(x, adj)\n\n x = x.mean(dim=1)\n x = F.relu(self.lin1(x))\n x = self.lin2(x)\n return F.log_softmax(x, dim=-1), mc1 + mc2, o1 + o2\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = Net(dataset.num_features, dataset.num_classes).to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=5e-4, weight_decay=1e-4)\n\n\ndef train(epoch):\n model.train()\n loss_all = 0\n\n for data in train_loader:\n data = data.to(device)\n optimizer.zero_grad()\n out, mc_loss, o_loss = model(data.x, data.edge_index, data.batch)\n loss = F.nll_loss(out, data.y.view(-1)) + mc_loss + o_loss\n loss.backward()\n loss_all += data.y.size(0) * loss.item()\n optimizer.step()\n return loss_all / len(train_dataset)\n\n\[email protected]_grad()\ndef test(loader):\n model.eval()\n correct = 0\n loss_all = 0\n\n for data in loader:\n data = data.to(device)\n pred, mc_loss, o_loss = model(data.x, data.edge_index, data.batch)\n loss = F.nll_loss(pred, data.y.view(-1)) + mc_loss + o_loss\n loss_all += data.y.size(0) * loss.item()\n correct += pred.max(dim=1)[1].eq(data.y.view(-1)).sum().item()\n\n return loss_all / len(loader.dataset), correct / len(loader.dataset)\n\n\nbest_val_acc = test_acc = 0\nbest_val_loss = float('inf')\npatience = start_patience = 50\nfor epoch in range(1, 15000):\n train_loss = train(epoch)\n _, train_acc = test(train_loader)\n val_loss, val_acc = test(val_loader)\n if val_loss < best_val_loss:\n test_loss, test_acc = test(test_loader)\n best_val_acc = val_acc\n patience = start_patience\n else:\n patience -= 1\n if patience == 0:\n break\n print('Epoch: {:03d}, '\n 'Train Loss: {:.3f}, Train Acc: {:.3f}, '\n 'Val Loss: {:.3f}, Val Acc: {:.3f}, '\n 'Test Loss: {:.3f}, Test Acc: {:.3f}'.format(epoch, train_loss,\n train_acc, val_loss,\n val_acc, test_loss,\n test_acc))\n" ]
[ [ "torch.tensor" ], [ "torch.nn.functional.log_softmax", "torch.no_grad", "torch.nn.Linear", "torch.cuda.is_available" ] ]
BoyDun/tensorflow-tensorrt
[ "6fa64812fbbc441f59e4c68f174f8c835cac7d05" ]
[ "Tensorflow-JSON.py" ]
[ "import numpy as np\nimport json\n\n\nprefixes = ['softmax', 'fc', 'conv', 'max_pool', 'avg_pool', 'relu'] # TODO: ADD CONCAT\n\n# Validate that every dictionary key is the name of a valid layer format\ndef validate_prefixes(names):\n for name in names:\n index = name.rfind('/')\n if index != -1: section = name[index + 1:]\n else: section = name\n hasPrefix = False\n for prefix in prefixes:\n if (section.startswith(prefix)):\n hasPrefix = True\n break\n\n if not hasPrefix:\n return False\n\n return True\n\n# Prefix of the namespaces in the dictionary\nprefix = '/home/peter/Desktop/'\n\n# Max pool must have entry in dict mapped to a list of the format [windowHeight, windowWidth, strideHeight, strideWidth]\n # Also must be named 'max_pool' + etc.\n# Average pool must have entry in dict mapped to a list of the format [windowHeight, windowWidth, strideHeight, strideWidth].\n # Also must be named 'avg_pool' + etc.\n# Softmax must be named 'softmax' + etc.\n# Full connected must be named 'fc' + etc.\n# Convolutional layer must have entry in dict mapped to a list of the format [strideHeight, strideWidth, padding]\n # Padding is an optional entry for if you want custom padding, not 'SAME' padding,\ndef convert_separate(graph, namescopes, dict, session, channels, height, width):\n if not validate_prefixes(namescopes):\n return None\n # Create a model specification file named \"input\" that specifies input tensor parameters\n json_object = {}\n json_object['num_input_channels'] = channels\n json_object['input_height'] = height\n json_object['input_width'] = width\n with open(prefix + 'input', 'w') as outfile:\n json.dump(json_object, outfile)\n outfile.close()\n counter = 0\n\n # Create a model specification file for each layer in the network\n for namescope in namescopes:\n counter += 1\n index = namescope.rfind('/')\n if index != -1: section = namescope[index + 1:]\n else: section = namescope\n print(section)\n layer = {}\n if section.startswith(prefixes[0]):\n # If layer is softmax\n layer['name'] = 'softmax'\n elif section.startswith(prefixes[1]) and namescope not in dict:\n # If layer is fully connected\n layer['name'] = 'fc'\n for variable in graph.get_collection('trainable_variables', namescope):\n name = variable.name[len(namescope) + 1:]\n if name.startswith('weight'):\n weight = session.run(variable)\n layer['weights'] = weight.tolist()\n if name.startswith('bias'):\n bias = session.run(variable)\n layer['biases'] = bias.tolist()\n layer['num_outputs'] = len(bias)\n elif section.startswith(prefixes[2]) or (namescope in dict and (len(dict[namescope]) == 2 or len(dict[namescope]) == 3)):\n # If layer is convolutional\n layer['name'] = 'conv'\n for variable in graph.get_collection('trainable_variables', namescope):\n name = variable.name[len(namescope) + 1:]\n if name.startswith('weight'):\n weight = session.run(variable)\n shape = weight.shape\n layer['weights_hwio'] = np.transpose(weight, (3,2,0,1)).tolist() # Rearrange order to be compatible with TensorRT\n layer['filter_height'] = shape[0]\n layer['filter_width'] = shape[1]\n layer['out_maps'] = shape[3]\n if name.startswith('bias'):\n bias = session.run(variable)\n layer['biases'] = bias.tolist()\n layer['num_outputs'] = len(bias)\n properties = dict[namescope]\n layer['stride_height'] = properties[0]\n layer['stride_width'] = properties[1]\n if (len(properties) == 3): layer['padding'] = properties[2]\n else: layer['padding'] = -1\n print(layer['padding'])\n elif section.startswith(prefixes[3]):\n # If layer is max pool\n layer['name'] = 'max_pool'\n properties = dict[namescope]\n layer['window_height'] = properties[0]\n layer['window_width'] = properties[1]\n layer['stride_height'] = properties[2]\n layer['stride_width'] = properties[3]\n elif section.startswith(prefixes[4]):\n # If layer is average pool\n layer['name'] = 'avg_pool'\n properties = dict[namescope]\n layer['window_height'] = properties[0]\n layer['window_width'] = properties[1]\n layer['stride_height'] = properties[2]\n layer['stride_width'] = properties[3]\n elif section.startswith(prefixes[5]):\n # If layer is a ReLU activation\n layer['name'] = 'relu'\n\n with open(prefix + str(counter), 'w') as outfile:\n json.dump(layer, outfile)\n outfile.close()\n\n\ndef convert_entire(graph, namescopes, dict, session, channels, height, width):\n if not validate_prefixes(namescopes):\n return None\n # Create a model specification file named \"input\" that specifies input tensor parameters\n json_object = {}\n json_object['num_input_channels'] = channels\n json_object['input_height'] = height\n json_object['input_width'] = width\n json_object['layers'] = []\n\n # Create a model specification file for each layer in the network\n for namescope in namescopes:\n index = namescope.rfind('/')\n if index != -1: section = namescope[index + 1:]\n else: section = namescope\n print(section)\n layer = {}\n if section.startswith(prefixes[0]):\n # If layer is softmax\n layer['name'] = 'softmax'\n elif section.startswith(prefixes[1]) and namescope not in dict:\n # If layer is fully connected\n layer['name'] = 'fc'\n for variable in graph.get_collection('trainable_variables', namescope):\n name = variable.name[len(namescope) + 1:]\n if name.startswith('weight'):\n weight = session.run(variable)\n layer['weights'] = weight.tolist()\n if name.startswith('bias'):\n bias = session.run(variable)\n layer['biases'] = bias.tolist()\n layer['num_outputs'] = len(bias)\n elif section.startswith(prefixes[2]) or (namescope in dict and (len(dict[namescope]) == 2 or len(dict[namescope]) == 3)):\n # If layer is convolutional\n layer['name'] = 'conv'\n for variable in graph.get_collection('trainable_variables', namescope):\n name = variable.name[len(namescope) + 1:]\n if name.startswith('weight'):\n weight = session.run(variable)\n shape = weight.shape\n layer['weights_hwio'] = np.transpose(weight, (3,2,0,1)).tolist() # Rearrange order to be compatible with TensorRT\n layer['filter_height'] = shape[0]\n layer['filter_width'] = shape[1]\n layer['out_maps'] = shape[3]\n if name.startswith('bias'):\n bias = session.run(variable)\n layer['biases'] = bias.tolist()\n layer['num_outputs'] = len(bias)\n properties = dict[namescope]\n layer['stride_height'] = properties[0]\n layer['stride_width'] = properties[1]\n if (len(properties) == 3): layer['padding'] = properties[2]\n else: layer['padding'] = -1\n print(layer['padding'])\n elif section.startswith(prefixes[3]):\n # If layer is max pool\n layer['name'] = 'max_pool'\n properties = dict[namescope]\n layer['window_height'] = properties[0]\n layer['window_width'] = properties[1]\n layer['stride_height'] = properties[2]\n layer['stride_width'] = properties[3]\n elif section.startswith(prefixes[4]):\n # If layer is average pool\n layer['name'] = 'avg_pool'\n properties = dict[namescope]\n layer['window_height'] = properties[0]\n layer['window_width'] = properties[1]\n layer['stride_height'] = properties[2]\n layer['stride_width'] = properties[3]\n elif section.startswith(prefixes[5]):\n # If layer is a ReLU activation\n layer['name'] = 'relu'\n\n json_object['layers'].append(layer)\n\n with open(\"mnist_final\", 'w') as outfile:\n json.dump(json_object, outfile)\n outfile.close()\n" ]
[ [ "numpy.transpose" ] ]
ian-ludden/redist-vis
[ "af8cae8e849b04aa4409a82e11cf5da831d5934b" ]
[ "metrics.py" ]
[ "import pandas as pd\nimport geopandas\nimport json\nimport altair as alt\n\ndef make_metrics_df():\n GEOJSON = 'geojson/wi_map_plan_{}.geojson'\n mm_gaps = []\n sl_indices = []\n efficiency_gaps = []\n plan_number = [i for i in range(1,84)]\n for i in range(1,84):\n plan = geopandas.read_file(GEOJSON.format(i))\n mm_gaps.append(plan['mm_gap'].iloc[0])\n sl_indices.append(plan['SL_index'].iloc[0])\n efficiency_gaps.append(plan['efficiency_gap'].iloc[0])\n metrics_dict = {'plan_number':plan_number,'mm_gap':mm_gaps,'sl_index':sl_indices,'efficiency_gap':efficiency_gaps}\n metrics_df = pd.DataFrame(metrics_dict, columns = ['plan_number','mm_gap','sl_index','efficiency_gap']) \n return metrics_df\n\n\ndef make_metrics_plot(metric_df, variable, variable_title, plot_title, scale):\n plot = alt.Chart(metric_df).mark_line(interpolate = 'basis').encode(\n alt.X('plan_number', title = \"Plan Number\"),\n alt.Y(variable, title = variable_title, scale = alt.Scale(domain = scale))).properties(\n title = plot_title,\n width = 300,\n height = 300\n )\n return plot" ]
[ [ "pandas.DataFrame" ] ]
sanbeichahegongheguo/pinyinwork
[ "eb32244db90a549aa03866e892ab7507ca49f0df" ]
[ "src/pinyin3.py" ]
[ "import sys, fileinput, json\nimport numpy as np\n\n\nfir_p = {} # 某字符出现在句首的概率对数 {str: float}\ndou_count = {} # 字符的二元出现次数 {(str, str): int}\ntri_count = {} # 字符的三元出现次数 {str: {str: {str: int}}}\nsin_count = {} # 字符出现计数 {str: int}\npch = {} # 拼音到字符的dict {pinyin: [chs]}\nsin_total = 396468407\n\n\ndef preload3():\n def add3(dict, ch1, ch2, ch3):\n if ch1 in dict:\n d2 = dict[ch1]\n if ch2 in d2:\n d3 = d2[ch2]\n if ch3 in d3:\n d3[ch3] += 1\n else:\n d3[ch3] = 1\n else:\n d2[ch2] = {ch3: 1}\n else:\n dict[ch1] = {ch2: {ch3: 1}}\n\n count = 0\n for line in fileinput.input(['../data/sentences.txt']):\n if count % 100000 == 0:\n print('line:', count)\n if count > 31000000: break\n count += 1\n for i in range(len(line) - 3):\n add3(tri_count, line[i], line[i+1], line[i+2])\n with open('../data/tri_count.json', 'w') as f:\n json.dump(tri_count, f)\n\n\ndef load3():\n global pch\n global fir_p\n global sin_count\n global dou_count\n global tri_count\n with open('../data/pch.txt') as f:\n pch = eval(f.read())\n with open('../data/fir_p.txt') as f:\n fir_p = eval(f.read())\n with open('../data/sin_count.txt') as f:\n sin_count = eval(f.read())\n with open('../data/dou_count.json') as f:\n dou_count = json.load(fp=f)\n with open('../data/tri_count.json') as f:\n tri_count = json.load(fp=f)\n\n\nclass node():\n def __init__(self, ch, pr, prev):\n self.ch = ch\n self.pr = pr\n self.prev = prev\n\n\ndef getpr(ch1, ch2, lam):\n dd = {}\n douc = dou_count.get(ch1, dd).get(ch2, 0)\n sinc1 = sin_count.get(ch1, 0)\n if sinc1 > 0:\n sinc2 = sin_count.get(ch2, 0)\n res = np.log(lam * douc / sinc1 + (1 - lam) * sinc2 / sin_total)\n else:\n res = -50\n return res\n\n\ndef getpr3(ch1, ch2, ch3, lam):\n lam2 = 0.99\n dd = {}\n tric = tri_count.get(ch1, dd).get(ch2, dd).get(ch3, 0)\n douc = dou_count.get(ch1, dd).get(ch2, 0)\n if douc > 0:\n sinc3 = sin_count.get(ch3, 0)\n res = np.log(lam2 * tric / douc + (1 - lam2) * sinc3 / sin_total)\n else:\n res = -20\n res += getpr(ch2, ch3, lam)\n return res\n\n\ndef run3(pylist, lam=0.99):\n for py in pylist:\n if py not in pch:\n return ['Wrong pinyin format.']\n nodes = []\n\n # first layer\n nodes.append([node(x, fir_p.get(x, -20.0), None) for x in pch[pylist[0]]])\n\n # second layer\n if len(pylist) > 1:\n nodes.append([node(x, 0, None) for x in pch[pylist[1]]])\n for nd in nodes[1]:\n nd.pr = nodes[0][0].pr + getpr(nodes[1][0].ch, nd.ch, lam)\n nd.prev = nodes[0][0]\n for prend in nodes[0]:\n pr = getpr(prend.ch, nd.ch, lam)\n if prend.pr + pr > nd.pr:\n nd.pr = prend.pr + pr\n nd.prev = prend\n\n # middle layers\n for i in range(len(pylist)):\n if i < 2:\n continue\n nodes.append([node(x, 0, None) for x in pch[pylist[i]]])\n for nd in nodes[i]:\n nd.pr = nodes[i - 1][0].pr + getpr3(nodes[i - 1][0].prev.ch, nodes[i - 1][0].ch, nd.ch, lam)\n nd.prev = nodes[i - 1][0]\n for prend in nodes[i - 1]:\n pr3 = getpr3(prend.prev.ch, prend.ch, nd.ch, lam)\n if prend.pr + pr3 > nd.pr:\n nd.pr = prend.pr + pr3\n nd.prev = prend\n\n # back propagation\n nd = max(nodes[-1], key=lambda x: x.pr)\n chs = []\n while nd is not None:\n chs.append(nd.ch)\n nd = nd.prev\n return list(reversed(chs))\n\n\ndef pinyin2hanzi3(str):\n return ''.join(run3(str.lower().split()))\n\n\n#自己测试用\ndef test3(input, output='../data/output.txt'):\n chcount = 0\n chcorrect = 0\n sencount = 0\n sencorrect = 0\n with open(input) as f:\n lines = [line for line in f]\n pys = ''\n chs = ''\n mychs = ''\n f = open(output, 'w')\n for i in range(len(lines)):\n if i % 2 == 0:\n pys = lines[i]\n else:\n chs = lines[i]\n mychs = pinyin2hanzi3(pys)\n f.write(pys+mychs+'\\n')\n if chs[: len(mychs)] == mychs:\n sencorrect += 1\n sencount += 1\n for j in range(len(mychs)):\n if chs[j] == mychs[j]:\n chcorrect += 1\n chcount += 1\n print('Sentences:{}, Correct sentences:{}, Correct rate:{}%'\n .format(sencount, sencorrect, round(100.0 * sencorrect / sencount, 2)))\n print('Characters:{},Correct characters:{}, Correct rate:{}%'\n .format(chcount, chcorrect, round(100.0 * chcorrect / chcount, 2)))\n f.close()\n\n\n# 课程测试用\ndef test3_class(input, output='../data/output.txt'):\n with open(input) as f:\n lines = [line for line in f]\n f = open(output, 'w')\n for i in range(len(lines)):\n pys = lines[i]\n mychs = pinyin2hanzi3(pys)\n f.write(mychs+'\\n')\n f.close()\n\n\nif __name__ == '__main__':\n # preload3()\n print('Pinyin(3-gram) is loading data...٩(๑>◡<๑)۶')\n load3()\n print('Begin testヾ(=・ω・=)o')\n if len(sys.argv) == 3:\n test3_class(sys.argv[1], sys.argv[2])\n else:\n print('Wrong form.')\n" ]
[ [ "numpy.log" ] ]
AnkitKumar2698/scikit-learn
[ "589329e5130de48b4a88b707213cf92a3112e236" ]
[ "sklearn/linear_model/_logistic.py" ]
[ "\"\"\"\nLogistic Regression\n\"\"\"\n\n# Author: Gael Varoquaux <[email protected]>\n# Fabian Pedregosa <[email protected]>\n# Alexandre Gramfort <[email protected]>\n# Manoj Kumar <[email protected]>\n# Lars Buitinck\n# Simon Wu <[email protected]>\n# Arthur Mensch <[email protected]\n\nimport numbers\nimport warnings\n\nimport numpy as np\nfrom scipy import optimize, sparse\nfrom scipy.special import expit, logsumexp\nfrom joblib import Parallel, effective_n_jobs\n\nfrom ._base import LinearClassifierMixin, SparseCoefMixin, BaseEstimator\nfrom ._sag import sag_solver\nfrom ..preprocessing import LabelEncoder, LabelBinarizer\nfrom ..svm._base import _fit_liblinear\nfrom ..utils import check_array, check_consistent_length, compute_class_weight\nfrom ..utils import check_random_state\nfrom ..utils.extmath import log_logistic, safe_sparse_dot, softmax, squared_norm\nfrom ..utils.extmath import row_norms\nfrom ..utils.optimize import _newton_cg, _check_optimize_result\nfrom ..utils.validation import check_is_fitted, _check_sample_weight\nfrom ..utils.multiclass import check_classification_targets\nfrom ..utils.fixes import _joblib_parallel_args\nfrom ..utils.fixes import delayed\nfrom ..model_selection import check_cv\nfrom ..metrics import get_scorer\n\n\n_LOGISTIC_SOLVER_CONVERGENCE_MSG = (\n \"Please also refer to the documentation for alternative solver options:\\n\"\n \" https://scikit-learn.org/stable/modules/linear_model.html\"\n \"#logistic-regression\"\n)\n\n\n# .. some helper functions for logistic_regression_path ..\ndef _intercept_dot(w, X, y):\n \"\"\"Computes y * np.dot(X, w).\n\n It takes into consideration if the intercept should be fit or not.\n\n Parameters\n ----------\n w : ndarray of shape (n_features,) or (n_features + 1,)\n Coefficient vector.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n y : ndarray of shape (n_samples,)\n Array of labels.\n\n Returns\n -------\n w : ndarray of shape (n_features,)\n Coefficient vector without the intercept weight (w[-1]) if the\n intercept should be fit. Unchanged otherwise.\n\n c : float\n The intercept.\n\n yz : float\n y * np.dot(X, w).\n \"\"\"\n c = 0.0\n if w.size == X.shape[1] + 1:\n c = w[-1]\n w = w[:-1]\n\n z = safe_sparse_dot(X, w) + c\n yz = y * z\n return w, c, yz\n\n\ndef _logistic_loss_and_grad(w, X, y, alpha, sample_weight=None):\n \"\"\"Computes the logistic loss and gradient.\n\n Parameters\n ----------\n w : ndarray of shape (n_features,) or (n_features + 1,)\n Coefficient vector.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n y : ndarray of shape (n_samples,)\n Array of labels.\n\n alpha : float\n Regularization parameter. alpha is equal to 1 / C.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Array of weights that are assigned to individual samples.\n If not provided, then each sample is given unit weight.\n\n Returns\n -------\n out : float\n Logistic loss.\n\n grad : ndarray of shape (n_features,) or (n_features + 1,)\n Logistic gradient.\n \"\"\"\n n_samples, n_features = X.shape\n grad = np.empty_like(w)\n\n w, c, yz = _intercept_dot(w, X, y)\n\n if sample_weight is None:\n sample_weight = np.ones(n_samples)\n\n # Logistic loss is the negative of the log of the logistic function.\n out = -np.sum(sample_weight * log_logistic(yz)) + 0.5 * alpha * np.dot(w, w)\n\n z = expit(yz)\n z0 = sample_weight * (z - 1) * y\n\n grad[:n_features] = safe_sparse_dot(X.T, z0) + alpha * w\n\n # Case where we fit the intercept.\n if grad.shape[0] > n_features:\n grad[-1] = z0.sum()\n return out, grad\n\n\ndef _logistic_loss(w, X, y, alpha, sample_weight=None):\n \"\"\"Computes the logistic loss.\n\n Parameters\n ----------\n w : ndarray of shape (n_features,) or (n_features + 1,)\n Coefficient vector.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n y : ndarray of shape (n_samples,)\n Array of labels.\n\n alpha : float\n Regularization parameter. alpha is equal to 1 / C.\n\n sample_weight : array-like of shape (n_samples,) default=None\n Array of weights that are assigned to individual samples.\n If not provided, then each sample is given unit weight.\n\n Returns\n -------\n out : float\n Logistic loss.\n \"\"\"\n w, c, yz = _intercept_dot(w, X, y)\n\n if sample_weight is None:\n sample_weight = np.ones(y.shape[0])\n\n # Logistic loss is the negative of the log of the logistic function.\n out = -np.sum(sample_weight * log_logistic(yz)) + 0.5 * alpha * np.dot(w, w)\n return out\n\n\ndef _logistic_grad_hess(w, X, y, alpha, sample_weight=None):\n \"\"\"Computes the gradient and the Hessian, in the case of a logistic loss.\n\n Parameters\n ----------\n w : ndarray of shape (n_features,) or (n_features + 1,)\n Coefficient vector.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n y : ndarray of shape (n_samples,)\n Array of labels.\n\n alpha : float\n Regularization parameter. alpha is equal to 1 / C.\n\n sample_weight : array-like of shape (n_samples,) default=None\n Array of weights that are assigned to individual samples.\n If not provided, then each sample is given unit weight.\n\n Returns\n -------\n grad : ndarray of shape (n_features,) or (n_features + 1,)\n Logistic gradient.\n\n Hs : callable\n Function that takes the gradient as a parameter and returns the\n matrix product of the Hessian and gradient.\n \"\"\"\n n_samples, n_features = X.shape\n grad = np.empty_like(w)\n fit_intercept = grad.shape[0] > n_features\n\n w, c, yz = _intercept_dot(w, X, y)\n\n if sample_weight is None:\n sample_weight = np.ones(y.shape[0])\n\n z = expit(yz)\n z0 = sample_weight * (z - 1) * y\n\n grad[:n_features] = safe_sparse_dot(X.T, z0) + alpha * w\n\n # Case where we fit the intercept.\n if fit_intercept:\n grad[-1] = z0.sum()\n\n # The mat-vec product of the Hessian\n d = sample_weight * z * (1 - z)\n if sparse.issparse(X):\n dX = safe_sparse_dot(sparse.dia_matrix((d, 0), shape=(n_samples, n_samples)), X)\n else:\n # Precompute as much as possible\n dX = d[:, np.newaxis] * X\n\n if fit_intercept:\n # Calculate the double derivative with respect to intercept\n # In the case of sparse matrices this returns a matrix object.\n dd_intercept = np.squeeze(np.array(dX.sum(axis=0)))\n\n def Hs(s):\n ret = np.empty_like(s)\n if sparse.issparse(X):\n ret[:n_features] = X.T.dot(dX.dot(s[:n_features]))\n else:\n ret[:n_features] = np.linalg.multi_dot([X.T, dX, s[:n_features]])\n ret[:n_features] += alpha * s[:n_features]\n\n # For the fit intercept case.\n if fit_intercept:\n ret[:n_features] += s[-1] * dd_intercept\n ret[-1] = dd_intercept.dot(s[:n_features])\n ret[-1] += d.sum() * s[-1]\n return ret\n\n return grad, Hs\n\n\ndef _multinomial_loss(w, X, Y, alpha, sample_weight):\n \"\"\"Computes multinomial loss and class probabilities.\n\n Parameters\n ----------\n w : ndarray of shape (n_classes * n_features,) or\n (n_classes * (n_features + 1),)\n Coefficient vector.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n Y : ndarray of shape (n_samples, n_classes)\n Transformed labels according to the output of LabelBinarizer.\n\n alpha : float\n Regularization parameter. alpha is equal to 1 / C.\n\n sample_weight : array-like of shape (n_samples,)\n Array of weights that are assigned to individual samples.\n\n Returns\n -------\n loss : float\n Multinomial loss.\n\n p : ndarray of shape (n_samples, n_classes)\n Estimated class probabilities.\n\n w : ndarray of shape (n_classes, n_features)\n Reshaped param vector excluding intercept terms.\n\n Reference\n ---------\n Bishop, C. M. (2006). Pattern recognition and machine learning.\n Springer. (Chapter 4.3.4)\n \"\"\"\n n_classes = Y.shape[1]\n n_features = X.shape[1]\n fit_intercept = w.size == (n_classes * (n_features + 1))\n w = w.reshape(n_classes, -1)\n sample_weight = sample_weight[:, np.newaxis]\n if fit_intercept:\n intercept = w[:, -1]\n w = w[:, :-1]\n else:\n intercept = 0\n p = safe_sparse_dot(X, w.T)\n p += intercept\n p -= logsumexp(p, axis=1)[:, np.newaxis]\n loss = -(sample_weight * Y * p).sum()\n loss += 0.5 * alpha * squared_norm(w)\n p = np.exp(p, p)\n return loss, p, w\n\n\ndef _multinomial_loss_grad(w, X, Y, alpha, sample_weight):\n \"\"\"Computes the multinomial loss, gradient and class probabilities.\n\n Parameters\n ----------\n w : ndarray of shape (n_classes * n_features,) or\n (n_classes * (n_features + 1),)\n Coefficient vector.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n Y : ndarray of shape (n_samples, n_classes)\n Transformed labels according to the output of LabelBinarizer.\n\n alpha : float\n Regularization parameter. alpha is equal to 1 / C.\n\n sample_weight : array-like of shape (n_samples,)\n Array of weights that are assigned to individual samples.\n\n Returns\n -------\n loss : float\n Multinomial loss.\n\n grad : ndarray of shape (n_classes * n_features,) or \\\n (n_classes * (n_features + 1),)\n Ravelled gradient of the multinomial loss.\n\n p : ndarray of shape (n_samples, n_classes)\n Estimated class probabilities\n\n Reference\n ---------\n Bishop, C. M. (2006). Pattern recognition and machine learning.\n Springer. (Chapter 4.3.4)\n \"\"\"\n n_classes = Y.shape[1]\n n_features = X.shape[1]\n fit_intercept = w.size == n_classes * (n_features + 1)\n grad = np.zeros((n_classes, n_features + bool(fit_intercept)), dtype=X.dtype)\n loss, p, w = _multinomial_loss(w, X, Y, alpha, sample_weight)\n sample_weight = sample_weight[:, np.newaxis]\n diff = sample_weight * (p - Y)\n grad[:, :n_features] = safe_sparse_dot(diff.T, X)\n grad[:, :n_features] += alpha * w\n if fit_intercept:\n grad[:, -1] = diff.sum(axis=0)\n return loss, grad.ravel(), p\n\n\ndef _multinomial_grad_hess(w, X, Y, alpha, sample_weight):\n \"\"\"\n Computes the gradient and the Hessian, in the case of a multinomial loss.\n\n Parameters\n ----------\n w : ndarray of shape (n_classes * n_features,) or\n (n_classes * (n_features + 1),)\n Coefficient vector.\n\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n Y : ndarray of shape (n_samples, n_classes)\n Transformed labels according to the output of LabelBinarizer.\n\n alpha : float\n Regularization parameter. alpha is equal to 1 / C.\n\n sample_weight : array-like of shape (n_samples,)\n Array of weights that are assigned to individual samples.\n\n Returns\n -------\n grad : ndarray of shape (n_classes * n_features,) or \\\n (n_classes * (n_features + 1),)\n Ravelled gradient of the multinomial loss.\n\n hessp : callable\n Function that takes in a vector input of shape (n_classes * n_features)\n or (n_classes * (n_features + 1)) and returns matrix-vector product\n with hessian.\n\n References\n ----------\n Barak A. Pearlmutter (1993). Fast Exact Multiplication by the Hessian.\n http://www.bcl.hamilton.ie/~barak/papers/nc-hessian.pdf\n \"\"\"\n n_features = X.shape[1]\n n_classes = Y.shape[1]\n fit_intercept = w.size == (n_classes * (n_features + 1))\n\n # `loss` is unused. Refactoring to avoid computing it does not\n # significantly speed up the computation and decreases readability\n loss, grad, p = _multinomial_loss_grad(w, X, Y, alpha, sample_weight)\n sample_weight = sample_weight[:, np.newaxis]\n\n # Hessian-vector product derived by applying the R-operator on the gradient\n # of the multinomial loss function.\n def hessp(v):\n v = v.reshape(n_classes, -1)\n if fit_intercept:\n inter_terms = v[:, -1]\n v = v[:, :-1]\n else:\n inter_terms = 0\n # r_yhat holds the result of applying the R-operator on the multinomial\n # estimator.\n r_yhat = safe_sparse_dot(X, v.T)\n r_yhat += inter_terms\n r_yhat += (-p * r_yhat).sum(axis=1)[:, np.newaxis]\n r_yhat *= p\n r_yhat *= sample_weight\n hessProd = np.zeros((n_classes, n_features + bool(fit_intercept)))\n hessProd[:, :n_features] = safe_sparse_dot(r_yhat.T, X)\n hessProd[:, :n_features] += v * alpha\n if fit_intercept:\n hessProd[:, -1] = r_yhat.sum(axis=0)\n return hessProd.ravel()\n\n return grad, hessp\n\n\ndef _check_solver(solver, penalty, dual):\n all_solvers = [\"liblinear\", \"newton-cg\", \"lbfgs\", \"sag\", \"saga\"]\n if solver not in all_solvers:\n raise ValueError(\n \"Logistic Regression supports only solvers in %s, got %s.\"\n % (all_solvers, solver)\n )\n\n all_penalties = [\"l1\", \"l2\", \"elasticnet\", \"none\"]\n if penalty not in all_penalties:\n raise ValueError(\n \"Logistic Regression supports only penalties in %s, got %s.\"\n % (all_penalties, penalty)\n )\n\n if solver not in [\"liblinear\", \"saga\"] and penalty not in (\"l2\", \"none\"):\n raise ValueError(\n \"Solver %s supports only 'l2' or 'none' penalties, got %s penalty.\"\n % (solver, penalty)\n )\n if solver != \"liblinear\" and dual:\n raise ValueError(\n \"Solver %s supports only dual=False, got dual=%s\" % (solver, dual)\n )\n\n if penalty == \"elasticnet\" and solver != \"saga\":\n raise ValueError(\n \"Only 'saga' solver supports elasticnet penalty, got solver={}.\".format(\n solver\n )\n )\n\n if solver == \"liblinear\" and penalty == \"none\":\n raise ValueError(\"penalty='none' is not supported for the liblinear solver\")\n\n return solver\n\n\ndef _check_multi_class(multi_class, solver, n_classes):\n if multi_class == \"auto\":\n if solver == \"liblinear\":\n multi_class = \"ovr\"\n elif n_classes > 2:\n multi_class = \"multinomial\"\n else:\n multi_class = \"ovr\"\n if multi_class not in (\"multinomial\", \"ovr\"):\n raise ValueError(\n \"multi_class should be 'multinomial', 'ovr' or 'auto'. Got %s.\"\n % multi_class\n )\n if multi_class == \"multinomial\" and solver == \"liblinear\":\n raise ValueError(\"Solver %s does not support a multinomial backend.\" % solver)\n return multi_class\n\n\ndef _logistic_regression_path(\n X,\n y,\n pos_class=None,\n Cs=10,\n fit_intercept=True,\n max_iter=100,\n tol=1e-4,\n verbose=0,\n solver=\"lbfgs\",\n coef=None,\n class_weight=None,\n dual=False,\n penalty=\"l2\",\n intercept_scaling=1.0,\n multi_class=\"auto\",\n random_state=None,\n check_input=True,\n max_squared_sum=None,\n sample_weight=None,\n l1_ratio=None,\n):\n \"\"\"Compute a Logistic Regression model for a list of regularization\n parameters.\n\n This is an implementation that uses the result of the previous model\n to speed up computations along the set of solutions, making it faster\n than sequentially calling LogisticRegression for the different parameters.\n Note that there will be no speedup with liblinear solver, since it does\n not handle warm-starting.\n\n Read more in the :ref:`User Guide <logistic_regression>`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Input data.\n\n y : array-like of shape (n_samples,) or (n_samples, n_targets)\n Input data, target values.\n\n pos_class : int, default=None\n The class with respect to which we perform a one-vs-all fit.\n If None, then it is assumed that the given problem is binary.\n\n Cs : int or array-like of shape (n_cs,), default=10\n List of values for the regularization parameter or integer specifying\n the number of regularization parameters that should be used. In this\n case, the parameters will be chosen in a logarithmic scale between\n 1e-4 and 1e4.\n\n fit_intercept : bool, default=True\n Whether to fit an intercept for the model. In this case the shape of\n the returned array is (n_cs, n_features + 1).\n\n max_iter : int, default=100\n Maximum number of iterations for the solver.\n\n tol : float, default=1e-4\n Stopping criterion. For the newton-cg and lbfgs solvers, the iteration\n will stop when ``max{|g_i | i = 1, ..., n} <= tol``\n where ``g_i`` is the i-th component of the gradient.\n\n verbose : int, default=0\n For the liblinear and lbfgs solvers set verbose to any positive\n number for verbosity.\n\n solver : {'lbfgs', 'newton-cg', 'liblinear', 'sag', 'saga'}, \\\n default='lbfgs'\n Numerical solver to use.\n\n coef : array-like of shape (n_features,), default=None\n Initialization value for coefficients of logistic regression.\n Useless for liblinear solver.\n\n class_weight : dict or 'balanced', default=None\n Weights associated with classes in the form ``{class_label: weight}``.\n If not given, all classes are supposed to have weight one.\n\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``.\n\n Note that these weights will be multiplied with sample_weight (passed\n through the fit method) if sample_weight is specified.\n\n dual : bool, default=False\n Dual or primal formulation. Dual formulation is only implemented for\n l2 penalty with liblinear solver. Prefer dual=False when\n n_samples > n_features.\n\n penalty : {'l1', 'l2', 'elasticnet'}, default='l2'\n Used to specify the norm used in the penalization. The 'newton-cg',\n 'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is\n only supported by the 'saga' solver.\n\n intercept_scaling : float, default=1.\n Useful only when the solver 'liblinear' is used\n and self.fit_intercept is set to True. In this case, x becomes\n [x, self.intercept_scaling],\n i.e. a \"synthetic\" feature with constant value equal to\n intercept_scaling is appended to the instance vector.\n The intercept becomes ``intercept_scaling * synthetic_feature_weight``.\n\n Note! the synthetic feature weight is subject to l1/l2 regularization\n as all other features.\n To lessen the effect of regularization on synthetic feature weight\n (and therefore on the intercept) intercept_scaling has to be increased.\n\n multi_class : {'ovr', 'multinomial', 'auto'}, default='auto'\n If the option chosen is 'ovr', then a binary problem is fit for each\n label. For 'multinomial' the loss minimised is the multinomial loss fit\n across the entire probability distribution, *even when the data is\n binary*. 'multinomial' is unavailable when solver='liblinear'.\n 'auto' selects 'ovr' if the data is binary, or if solver='liblinear',\n and otherwise selects 'multinomial'.\n\n .. versionadded:: 0.18\n Stochastic Average Gradient descent solver for 'multinomial' case.\n .. versionchanged:: 0.22\n Default changed from 'ovr' to 'auto' in 0.22.\n\n random_state : int, RandomState instance, default=None\n Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the\n data. See :term:`Glossary <random_state>` for details.\n\n check_input : bool, default=True\n If False, the input arrays X and y will not be checked.\n\n max_squared_sum : float, default=None\n Maximum squared sum of X over samples. Used only in SAG solver.\n If None, it will be computed, going through all the samples.\n The value should be precomputed to speed up cross validation.\n\n sample_weight : array-like of shape(n_samples,), default=None\n Array of weights that are assigned to individual samples.\n If not provided, then each sample is given unit weight.\n\n l1_ratio : float, default=None\n The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only\n used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent\n to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent\n to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a\n combination of L1 and L2.\n\n Returns\n -------\n coefs : ndarray of shape (n_cs, n_features) or (n_cs, n_features + 1)\n List of coefficients for the Logistic Regression model. If\n fit_intercept is set to True then the second dimension will be\n n_features + 1, where the last item represents the intercept. For\n ``multiclass='multinomial'``, the shape is (n_classes, n_cs,\n n_features) or (n_classes, n_cs, n_features + 1).\n\n Cs : ndarray\n Grid of Cs used for cross-validation.\n\n n_iter : array of shape (n_cs,)\n Actual number of iteration for each Cs.\n\n Notes\n -----\n You might get slightly different results with the solver liblinear than\n with the others since this uses LIBLINEAR which penalizes the intercept.\n\n .. versionchanged:: 0.19\n The \"copy\" parameter was removed.\n \"\"\"\n if isinstance(Cs, numbers.Integral):\n Cs = np.logspace(-4, 4, Cs)\n\n solver = _check_solver(solver, penalty, dual)\n\n # Preprocessing.\n if check_input:\n X = check_array(\n X,\n accept_sparse=\"csr\",\n dtype=np.float64,\n accept_large_sparse=solver not in [\"liblinear\", \"sag\", \"saga\"],\n )\n y = check_array(y, ensure_2d=False, dtype=None)\n check_consistent_length(X, y)\n _, n_features = X.shape\n\n classes = np.unique(y)\n random_state = check_random_state(random_state)\n\n multi_class = _check_multi_class(multi_class, solver, len(classes))\n if pos_class is None and multi_class != \"multinomial\":\n if classes.size > 2:\n raise ValueError(\"To fit OvR, use the pos_class argument\")\n # np.unique(y) gives labels in sorted order.\n pos_class = classes[1]\n\n # If sample weights exist, convert them to array (support for lists)\n # and check length\n # Otherwise set them to 1 for all examples\n sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype, copy=True)\n\n # If class_weights is a dict (provided by the user), the weights\n # are assigned to the original labels. If it is \"balanced\", then\n # the class_weights are assigned after masking the labels with a OvR.\n le = LabelEncoder()\n if isinstance(class_weight, dict) or multi_class == \"multinomial\":\n class_weight_ = compute_class_weight(class_weight, classes=classes, y=y)\n sample_weight *= class_weight_[le.fit_transform(y)]\n\n # For doing a ovr, we need to mask the labels first. for the\n # multinomial case this is not necessary.\n if multi_class == \"ovr\":\n w0 = np.zeros(n_features + int(fit_intercept), dtype=X.dtype)\n mask_classes = np.array([-1, 1])\n mask = y == pos_class\n y_bin = np.ones(y.shape, dtype=X.dtype)\n y_bin[~mask] = -1.0\n # for compute_class_weight\n\n if class_weight == \"balanced\":\n class_weight_ = compute_class_weight(\n class_weight, classes=mask_classes, y=y_bin\n )\n sample_weight *= class_weight_[le.fit_transform(y_bin)]\n\n else:\n if solver not in [\"sag\", \"saga\"]:\n lbin = LabelBinarizer()\n Y_multi = lbin.fit_transform(y)\n if Y_multi.shape[1] == 1:\n Y_multi = np.hstack([1 - Y_multi, Y_multi])\n else:\n # SAG multinomial solver needs LabelEncoder, not LabelBinarizer\n le = LabelEncoder()\n Y_multi = le.fit_transform(y).astype(X.dtype, copy=False)\n\n w0 = np.zeros(\n (classes.size, n_features + int(fit_intercept)), order=\"F\", dtype=X.dtype\n )\n\n if coef is not None:\n # it must work both giving the bias term and not\n if multi_class == \"ovr\":\n if coef.size not in (n_features, w0.size):\n raise ValueError(\n \"Initialization coef is of shape %d, expected shape %d or %d\"\n % (coef.size, n_features, w0.size)\n )\n w0[: coef.size] = coef\n else:\n # For binary problems coef.shape[0] should be 1, otherwise it\n # should be classes.size.\n n_classes = classes.size\n if n_classes == 2:\n n_classes = 1\n\n if coef.shape[0] != n_classes or coef.shape[1] not in (\n n_features,\n n_features + 1,\n ):\n raise ValueError(\n \"Initialization coef is of shape (%d, %d), expected \"\n \"shape (%d, %d) or (%d, %d)\"\n % (\n coef.shape[0],\n coef.shape[1],\n classes.size,\n n_features,\n classes.size,\n n_features + 1,\n )\n )\n\n if n_classes == 1:\n w0[0, : coef.shape[1]] = -coef\n w0[1, : coef.shape[1]] = coef\n else:\n w0[:, : coef.shape[1]] = coef\n\n if multi_class == \"multinomial\":\n # scipy.optimize.minimize and newton-cg accepts only\n # ravelled parameters.\n if solver in [\"lbfgs\", \"newton-cg\"]:\n w0 = w0.ravel()\n target = Y_multi\n if solver == \"lbfgs\":\n\n def func(x, *args):\n return _multinomial_loss_grad(x, *args)[0:2]\n\n elif solver == \"newton-cg\":\n\n def func(x, *args):\n return _multinomial_loss(x, *args)[0]\n\n def grad(x, *args):\n return _multinomial_loss_grad(x, *args)[1]\n\n hess = _multinomial_grad_hess\n warm_start_sag = {\"coef\": w0.T}\n else:\n target = y_bin\n if solver == \"lbfgs\":\n func = _logistic_loss_and_grad\n elif solver == \"newton-cg\":\n func = _logistic_loss\n\n def grad(x, *args):\n return _logistic_loss_and_grad(x, *args)[1]\n\n hess = _logistic_grad_hess\n warm_start_sag = {\"coef\": np.expand_dims(w0, axis=1)}\n\n coefs = list()\n n_iter = np.zeros(len(Cs), dtype=np.int32)\n for i, C in enumerate(Cs):\n if solver == \"lbfgs\":\n iprint = [-1, 50, 1, 100, 101][\n np.searchsorted(np.array([0, 1, 2, 3]), verbose)\n ]\n opt_res = optimize.minimize(\n func,\n w0,\n method=\"L-BFGS-B\",\n jac=True,\n args=(X, target, 1.0 / C, sample_weight),\n options={\"iprint\": iprint, \"gtol\": tol, \"maxiter\": max_iter},\n )\n n_iter_i = _check_optimize_result(\n solver,\n opt_res,\n max_iter,\n extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG,\n )\n w0, loss = opt_res.x, opt_res.fun\n elif solver == \"newton-cg\":\n args = (X, target, 1.0 / C, sample_weight)\n w0, n_iter_i = _newton_cg(\n hess, func, grad, w0, args=args, maxiter=max_iter, tol=tol\n )\n elif solver == \"liblinear\":\n coef_, intercept_, n_iter_i, = _fit_liblinear(\n X,\n target,\n C,\n fit_intercept,\n intercept_scaling,\n None,\n penalty,\n dual,\n verbose,\n max_iter,\n tol,\n random_state,\n sample_weight=sample_weight,\n )\n if fit_intercept:\n w0 = np.concatenate([coef_.ravel(), intercept_])\n else:\n w0 = coef_.ravel()\n\n elif solver in [\"sag\", \"saga\"]:\n if multi_class == \"multinomial\":\n target = target.astype(X.dtype, copy=False)\n loss = \"multinomial\"\n else:\n loss = \"log\"\n # alpha is for L2-norm, beta is for L1-norm\n if penalty == \"l1\":\n alpha = 0.0\n beta = 1.0 / C\n elif penalty == \"l2\":\n alpha = 1.0 / C\n beta = 0.0\n else: # Elastic-Net penalty\n alpha = (1.0 / C) * (1 - l1_ratio)\n beta = (1.0 / C) * l1_ratio\n\n w0, n_iter_i, warm_start_sag = sag_solver(\n X,\n target,\n sample_weight,\n loss,\n alpha,\n beta,\n max_iter,\n tol,\n verbose,\n random_state,\n False,\n max_squared_sum,\n warm_start_sag,\n is_saga=(solver == \"saga\"),\n )\n\n else:\n raise ValueError(\n \"solver must be one of {'liblinear', 'lbfgs', \"\n \"'newton-cg', 'sag'}, got '%s' instead\" % solver\n )\n\n if multi_class == \"multinomial\":\n n_classes = max(2, classes.size)\n multi_w0 = np.reshape(w0, (n_classes, -1))\n if n_classes == 2:\n multi_w0 = multi_w0[1][np.newaxis, :]\n coefs.append(multi_w0.copy())\n else:\n coefs.append(w0.copy())\n\n n_iter[i] = n_iter_i\n\n return np.array(coefs), np.array(Cs), n_iter\n\n\n# helper function for LogisticCV\ndef _log_reg_scoring_path(\n X,\n y,\n train,\n test,\n pos_class=None,\n Cs=10,\n scoring=None,\n fit_intercept=False,\n max_iter=100,\n tol=1e-4,\n class_weight=None,\n verbose=0,\n solver=\"lbfgs\",\n penalty=\"l2\",\n dual=False,\n intercept_scaling=1.0,\n multi_class=\"auto\",\n random_state=None,\n max_squared_sum=None,\n sample_weight=None,\n l1_ratio=None,\n):\n \"\"\"Computes scores across logistic_regression_path\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training data.\n\n y : array-like of shape (n_samples,) or (n_samples, n_targets)\n Target labels.\n\n train : list of indices\n The indices of the train set.\n\n test : list of indices\n The indices of the test set.\n\n pos_class : int, default=None\n The class with respect to which we perform a one-vs-all fit.\n If None, then it is assumed that the given problem is binary.\n\n Cs : int or list of floats, default=10\n Each of the values in Cs describes the inverse of\n regularization strength. If Cs is as an int, then a grid of Cs\n values are chosen in a logarithmic scale between 1e-4 and 1e4.\n If not provided, then a fixed set of values for Cs are used.\n\n scoring : callable, default=None\n A string (see model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``. For a list of scoring functions\n that can be used, look at :mod:`sklearn.metrics`. The\n default scoring option used is accuracy_score.\n\n fit_intercept : bool, default=False\n If False, then the bias term is set to zero. Else the last\n term of each coef_ gives us the intercept.\n\n max_iter : int, default=100\n Maximum number of iterations for the solver.\n\n tol : float, default=1e-4\n Tolerance for stopping criteria.\n\n class_weight : dict or 'balanced', default=None\n Weights associated with classes in the form ``{class_label: weight}``.\n If not given, all classes are supposed to have weight one.\n\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``\n\n Note that these weights will be multiplied with sample_weight (passed\n through the fit method) if sample_weight is specified.\n\n verbose : int, default=0\n For the liblinear and lbfgs solvers set verbose to any positive\n number for verbosity.\n\n solver : {'lbfgs', 'newton-cg', 'liblinear', 'sag', 'saga'}, \\\n default='lbfgs'\n Decides which solver to use.\n\n penalty : {'l1', 'l2', 'elasticnet'}, default='l2'\n Used to specify the norm used in the penalization. The 'newton-cg',\n 'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is\n only supported by the 'saga' solver.\n\n dual : bool, default=False\n Dual or primal formulation. Dual formulation is only implemented for\n l2 penalty with liblinear solver. Prefer dual=False when\n n_samples > n_features.\n\n intercept_scaling : float, default=1.\n Useful only when the solver 'liblinear' is used\n and self.fit_intercept is set to True. In this case, x becomes\n [x, self.intercept_scaling],\n i.e. a \"synthetic\" feature with constant value equals to\n intercept_scaling is appended to the instance vector.\n The intercept becomes intercept_scaling * synthetic feature weight\n Note! the synthetic feature weight is subject to l1/l2 regularization\n as all other features.\n To lessen the effect of regularization on synthetic feature weight\n (and therefore on the intercept) intercept_scaling has to be increased.\n\n multi_class : {'auto', 'ovr', 'multinomial'}, default='auto'\n If the option chosen is 'ovr', then a binary problem is fit for each\n label. For 'multinomial' the loss minimised is the multinomial loss fit\n across the entire probability distribution, *even when the data is\n binary*. 'multinomial' is unavailable when solver='liblinear'.\n\n random_state : int, RandomState instance, default=None\n Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the\n data. See :term:`Glossary <random_state>` for details.\n\n max_squared_sum : float, default=None\n Maximum squared sum of X over samples. Used only in SAG solver.\n If None, it will be computed, going through all the samples.\n The value should be precomputed to speed up cross validation.\n\n sample_weight : array-like of shape(n_samples,), default=None\n Array of weights that are assigned to individual samples.\n If not provided, then each sample is given unit weight.\n\n l1_ratio : float, default=None\n The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only\n used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent\n to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent\n to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a\n combination of L1 and L2.\n\n Returns\n -------\n coefs : ndarray of shape (n_cs, n_features) or (n_cs, n_features + 1)\n List of coefficients for the Logistic Regression model. If\n fit_intercept is set to True then the second dimension will be\n n_features + 1, where the last item represents the intercept.\n\n Cs : ndarray\n Grid of Cs used for cross-validation.\n\n scores : ndarray of shape (n_cs,)\n Scores obtained for each Cs.\n\n n_iter : ndarray of shape(n_cs,)\n Actual number of iteration for each Cs.\n \"\"\"\n X_train = X[train]\n X_test = X[test]\n y_train = y[train]\n y_test = y[test]\n\n if sample_weight is not None:\n sample_weight = _check_sample_weight(sample_weight, X)\n sample_weight = sample_weight[train]\n\n coefs, Cs, n_iter = _logistic_regression_path(\n X_train,\n y_train,\n Cs=Cs,\n l1_ratio=l1_ratio,\n fit_intercept=fit_intercept,\n solver=solver,\n max_iter=max_iter,\n class_weight=class_weight,\n pos_class=pos_class,\n multi_class=multi_class,\n tol=tol,\n verbose=verbose,\n dual=dual,\n penalty=penalty,\n intercept_scaling=intercept_scaling,\n random_state=random_state,\n check_input=False,\n max_squared_sum=max_squared_sum,\n sample_weight=sample_weight,\n )\n\n log_reg = LogisticRegression(solver=solver, multi_class=multi_class)\n\n # The score method of Logistic Regression has a classes_ attribute.\n if multi_class == \"ovr\":\n log_reg.classes_ = np.array([-1, 1])\n elif multi_class == \"multinomial\":\n log_reg.classes_ = np.unique(y_train)\n else:\n raise ValueError(\n \"multi_class should be either multinomial or ovr, got %d\" % multi_class\n )\n\n if pos_class is not None:\n mask = y_test == pos_class\n y_test = np.ones(y_test.shape, dtype=np.float64)\n y_test[~mask] = -1.0\n\n scores = list()\n\n scoring = get_scorer(scoring)\n for w in coefs:\n if multi_class == \"ovr\":\n w = w[np.newaxis, :]\n if fit_intercept:\n log_reg.coef_ = w[:, :-1]\n log_reg.intercept_ = w[:, -1]\n else:\n log_reg.coef_ = w\n log_reg.intercept_ = 0.0\n\n if scoring is None:\n scores.append(log_reg.score(X_test, y_test))\n else:\n scores.append(scoring(log_reg, X_test, y_test))\n\n return coefs, Cs, np.array(scores), n_iter\n\n\nclass LogisticRegression(LinearClassifierMixin, SparseCoefMixin, BaseEstimator):\n \"\"\"\n Logistic Regression (aka logit, MaxEnt) classifier.\n\n In the multiclass case, the training algorithm uses the one-vs-rest (OvR)\n scheme if the 'multi_class' option is set to 'ovr', and uses the\n cross-entropy loss if the 'multi_class' option is set to 'multinomial'.\n (Currently the 'multinomial' option is supported only by the 'lbfgs',\n 'sag', 'saga' and 'newton-cg' solvers.)\n\n This class implements regularized logistic regression using the\n 'liblinear' library, 'newton-cg', 'sag', 'saga' and 'lbfgs' solvers. **Note\n that regularization is applied by default**. It can handle both dense\n and sparse input. Use C-ordered arrays or CSR matrices containing 64-bit\n floats for optimal performance; any other input format will be converted\n (and copied).\n\n The 'newton-cg', 'sag', and 'lbfgs' solvers support only L2 regularization\n with primal formulation, or no regularization. The 'liblinear' solver\n supports both L1 and L2 regularization, with a dual formulation only for\n the L2 penalty. The Elastic-Net regularization is only supported by the\n 'saga' solver.\n\n Read more in the :ref:`User Guide <logistic_regression>`.\n\n Parameters\n ----------\n penalty : {'l1', 'l2', 'elasticnet', 'none'}, default='l2'\n Specify the norm of the penalty:\n\n - `'none'`: no penalty is added;\n - `'l2'`: add a L2 penalty term and it is the default choice;\n - `'l1'`: add a L1 penalty term;\n - `'elasticnet'`: both L1 and L2 penalty terms are added.\n\n .. warning::\n Some penalties may not work with some solvers. See the parameter\n `solver` below, to know the compatibility between the penalty and\n solver.\n\n .. versionadded:: 0.19\n l1 penalty with SAGA solver (allowing 'multinomial' + L1)\n\n dual : bool, default=False\n Dual or primal formulation. Dual formulation is only implemented for\n l2 penalty with liblinear solver. Prefer dual=False when\n n_samples > n_features.\n\n tol : float, default=1e-4\n Tolerance for stopping criteria.\n\n C : float, default=1.0\n Inverse of regularization strength; must be a positive float.\n Like in support vector machines, smaller values specify stronger\n regularization.\n\n fit_intercept : bool, default=True\n Specifies if a constant (a.k.a. bias or intercept) should be\n added to the decision function.\n\n intercept_scaling : float, default=1\n Useful only when the solver 'liblinear' is used\n and self.fit_intercept is set to True. In this case, x becomes\n [x, self.intercept_scaling],\n i.e. a \"synthetic\" feature with constant value equal to\n intercept_scaling is appended to the instance vector.\n The intercept becomes ``intercept_scaling * synthetic_feature_weight``.\n\n Note! the synthetic feature weight is subject to l1/l2 regularization\n as all other features.\n To lessen the effect of regularization on synthetic feature weight\n (and therefore on the intercept) intercept_scaling has to be increased.\n\n class_weight : dict or 'balanced', default=None\n Weights associated with classes in the form ``{class_label: weight}``.\n If not given, all classes are supposed to have weight one.\n\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``.\n\n Note that these weights will be multiplied with sample_weight (passed\n through the fit method) if sample_weight is specified.\n\n .. versionadded:: 0.17\n *class_weight='balanced'*\n\n random_state : int, RandomState instance, default=None\n Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the\n data. See :term:`Glossary <random_state>` for details.\n\n solver : {'newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'}, \\\n default='lbfgs'\n\n Algorithm to use in the optimization problem. Default is 'lbfgs'.\n To choose a solver, you might want to consider the following aspects:\n\n - For small datasets, 'liblinear' is a good choice, whereas 'sag'\n and 'saga' are faster for large ones;\n - For multiclass problems, only 'newton-cg', 'sag', 'saga' and\n 'lbfgs' handle multinomial loss;\n - 'liblinear' is limited to one-versus-rest schemes.\n\n .. warning::\n The choice of the algorithm depends on the penalty chosen:\n Supported penalties by solver:\n\n - 'newton-cg' - ['l2', 'none']\n - 'lbfgs' - ['l2', 'none']\n - 'liblinear' - ['l1', 'l2']\n - 'sag' - ['l2', 'none']\n - 'saga' - ['elasticnet', 'l1', 'l2', 'none']\n\n .. note::\n 'sag' and 'saga' fast convergence is only guaranteed on\n features with approximately the same scale. You can\n preprocess the data with a scaler from :mod:`sklearn.preprocessing`.\n\n .. seealso::\n Refer to the User Guide for more information regarding\n :class:`LogisticRegression` and more specifically the\n `Table <https://scikit-learn.org/dev/modules/linear_model.html#logistic-regression>`_\n summarazing solver/penalty supports.\n <!--\n # noqa: E501\n -->\n\n .. versionadded:: 0.17\n Stochastic Average Gradient descent solver.\n .. versionadded:: 0.19\n SAGA solver.\n .. versionchanged:: 0.22\n The default solver changed from 'liblinear' to 'lbfgs' in 0.22.\n\n max_iter : int, default=100\n Maximum number of iterations taken for the solvers to converge.\n\n multi_class : {'auto', 'ovr', 'multinomial'}, default='auto'\n If the option chosen is 'ovr', then a binary problem is fit for each\n label. For 'multinomial' the loss minimised is the multinomial loss fit\n across the entire probability distribution, *even when the data is\n binary*. 'multinomial' is unavailable when solver='liblinear'.\n 'auto' selects 'ovr' if the data is binary, or if solver='liblinear',\n and otherwise selects 'multinomial'.\n\n .. versionadded:: 0.18\n Stochastic Average Gradient descent solver for 'multinomial' case.\n .. versionchanged:: 0.22\n Default changed from 'ovr' to 'auto' in 0.22.\n\n verbose : int, default=0\n For the liblinear and lbfgs solvers set verbose to any positive\n number for verbosity.\n\n warm_start : bool, default=False\n When set to True, reuse the solution of the previous call to fit as\n initialization, otherwise, just erase the previous solution.\n Useless for liblinear solver. See :term:`the Glossary <warm_start>`.\n\n .. versionadded:: 0.17\n *warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers.\n\n n_jobs : int, default=None\n Number of CPU cores used when parallelizing over classes if\n multi_class='ovr'\". This parameter is ignored when the ``solver`` is\n set to 'liblinear' regardless of whether 'multi_class' is specified or\n not. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`\n context. ``-1`` means using all processors.\n See :term:`Glossary <n_jobs>` for more details.\n\n l1_ratio : float, default=None\n The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only\n used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent\n to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent\n to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a\n combination of L1 and L2.\n\n Attributes\n ----------\n\n classes_ : ndarray of shape (n_classes, )\n A list of class labels known to the classifier.\n\n coef_ : ndarray of shape (1, n_features) or (n_classes, n_features)\n Coefficient of the features in the decision function.\n\n `coef_` is of shape (1, n_features) when the given problem is binary.\n In particular, when `multi_class='multinomial'`, `coef_` corresponds\n to outcome 1 (True) and `-coef_` corresponds to outcome 0 (False).\n\n intercept_ : ndarray of shape (1,) or (n_classes,)\n Intercept (a.k.a. bias) added to the decision function.\n\n If `fit_intercept` is set to False, the intercept is set to zero.\n `intercept_` is of shape (1,) when the given problem is binary.\n In particular, when `multi_class='multinomial'`, `intercept_`\n corresponds to outcome 1 (True) and `-intercept_` corresponds to\n outcome 0 (False).\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n n_iter_ : ndarray of shape (n_classes,) or (1, )\n Actual number of iterations for all classes. If binary or multinomial,\n it returns only 1 element. For liblinear solver, only the maximum\n number of iteration across all classes is given.\n\n .. versionchanged:: 0.20\n\n In SciPy <= 1.0.0 the number of lbfgs iterations may exceed\n ``max_iter``. ``n_iter_`` will now report at most ``max_iter``.\n\n See Also\n --------\n SGDClassifier : Incrementally trained logistic regression (when given\n the parameter ``loss=\"log\"``).\n LogisticRegressionCV : Logistic regression with built-in cross validation.\n\n Notes\n -----\n The underlying C implementation uses a random number generator to\n select features when fitting the model. It is thus not uncommon,\n to have slightly different results for the same input data. If\n that happens, try with a smaller tol parameter.\n\n Predict output may not match that of standalone liblinear in certain\n cases. See :ref:`differences from liblinear <liblinear_differences>`\n in the narrative documentation.\n\n References\n ----------\n\n L-BFGS-B -- Software for Large-scale Bound-constrained Optimization\n Ciyou Zhu, Richard Byrd, Jorge Nocedal and Jose Luis Morales.\n http://users.iems.northwestern.edu/~nocedal/lbfgsb.html\n\n LIBLINEAR -- A Library for Large Linear Classification\n https://www.csie.ntu.edu.tw/~cjlin/liblinear/\n\n SAG -- Mark Schmidt, Nicolas Le Roux, and Francis Bach\n Minimizing Finite Sums with the Stochastic Average Gradient\n https://hal.inria.fr/hal-00860051/document\n\n SAGA -- Defazio, A., Bach F. & Lacoste-Julien S. (2014).\n :arxiv:`\"SAGA: A Fast Incremental Gradient Method With Support\n for Non-Strongly Convex Composite Objectives\" <1407.0202>`\n\n Hsiang-Fu Yu, Fang-Lan Huang, Chih-Jen Lin (2011). Dual coordinate descent\n methods for logistic regression and maximum entropy models.\n Machine Learning 85(1-2):41-75.\n https://www.csie.ntu.edu.tw/~cjlin/papers/maxent_dual.pdf\n\n Examples\n --------\n >>> from sklearn.datasets import load_iris\n >>> from sklearn.linear_model import LogisticRegression\n >>> X, y = load_iris(return_X_y=True)\n >>> clf = LogisticRegression(random_state=0).fit(X, y)\n >>> clf.predict(X[:2, :])\n array([0, 0])\n >>> clf.predict_proba(X[:2, :])\n array([[9.8...e-01, 1.8...e-02, 1.4...e-08],\n [9.7...e-01, 2.8...e-02, ...e-08]])\n >>> clf.score(X, y)\n 0.97...\n \"\"\"\n\n def __init__(\n self,\n penalty=\"l2\",\n *,\n dual=False,\n tol=1e-4,\n C=1.0,\n fit_intercept=True,\n intercept_scaling=1,\n class_weight=None,\n random_state=None,\n solver=\"lbfgs\",\n max_iter=100,\n multi_class=\"auto\",\n verbose=0,\n warm_start=False,\n n_jobs=None,\n l1_ratio=None,\n ):\n\n self.penalty = penalty\n self.dual = dual\n self.tol = tol\n self.C = C\n self.fit_intercept = fit_intercept\n self.intercept_scaling = intercept_scaling\n self.class_weight = class_weight\n self.random_state = random_state\n self.solver = solver\n self.max_iter = max_iter\n self.multi_class = multi_class\n self.verbose = verbose\n self.warm_start = warm_start\n self.n_jobs = n_jobs\n self.l1_ratio = l1_ratio\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"\n Fit the model according to the given training data.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training vector, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : array-like of shape (n_samples,)\n Target vector relative to X.\n\n sample_weight : array-like of shape (n_samples,) default=None\n Array of weights that are assigned to individual samples.\n If not provided, then each sample is given unit weight.\n\n .. versionadded:: 0.17\n *sample_weight* support to LogisticRegression.\n\n Returns\n -------\n self\n Fitted estimator.\n\n Notes\n -----\n The SAGA solver supports both float64 and float32 bit arrays.\n \"\"\"\n solver = _check_solver(self.solver, self.penalty, self.dual)\n\n if not isinstance(self.C, numbers.Number) or self.C < 0:\n raise ValueError(\"Penalty term must be positive; got (C=%r)\" % self.C)\n if self.penalty == \"elasticnet\":\n if (\n not isinstance(self.l1_ratio, numbers.Number)\n or self.l1_ratio < 0\n or self.l1_ratio > 1\n ):\n raise ValueError(\n \"l1_ratio must be between 0 and 1; got (l1_ratio=%r)\"\n % self.l1_ratio\n )\n elif self.l1_ratio is not None:\n warnings.warn(\n \"l1_ratio parameter is only used when penalty is \"\n \"'elasticnet'. Got \"\n \"(penalty={})\".format(self.penalty)\n )\n if self.penalty == \"none\":\n if self.C != 1.0: # default values\n warnings.warn(\n \"Setting penalty='none' will ignore the C and l1_ratio parameters\"\n )\n # Note that check for l1_ratio is done right above\n C_ = np.inf\n penalty = \"l2\"\n else:\n C_ = self.C\n penalty = self.penalty\n if not isinstance(self.max_iter, numbers.Number) or self.max_iter < 0:\n raise ValueError(\n \"Maximum number of iteration must be positive; got (max_iter=%r)\"\n % self.max_iter\n )\n if not isinstance(self.tol, numbers.Number) or self.tol < 0:\n raise ValueError(\n \"Tolerance for stopping criteria must be positive; got (tol=%r)\"\n % self.tol\n )\n\n if solver == \"lbfgs\":\n _dtype = np.float64\n else:\n _dtype = [np.float64, np.float32]\n\n X, y = self._validate_data(\n X,\n y,\n accept_sparse=\"csr\",\n dtype=_dtype,\n order=\"C\",\n accept_large_sparse=solver not in [\"liblinear\", \"sag\", \"saga\"],\n )\n check_classification_targets(y)\n self.classes_ = np.unique(y)\n\n multi_class = _check_multi_class(self.multi_class, solver, len(self.classes_))\n\n if solver == \"liblinear\":\n if effective_n_jobs(self.n_jobs) != 1:\n warnings.warn(\n \"'n_jobs' > 1 does not have any effect when\"\n \" 'solver' is set to 'liblinear'. Got 'n_jobs'\"\n \" = {}.\".format(effective_n_jobs(self.n_jobs))\n )\n self.coef_, self.intercept_, n_iter_ = _fit_liblinear(\n X,\n y,\n self.C,\n self.fit_intercept,\n self.intercept_scaling,\n self.class_weight,\n self.penalty,\n self.dual,\n self.verbose,\n self.max_iter,\n self.tol,\n self.random_state,\n sample_weight=sample_weight,\n )\n self.n_iter_ = np.array([n_iter_])\n return self\n\n if solver in [\"sag\", \"saga\"]:\n max_squared_sum = row_norms(X, squared=True).max()\n else:\n max_squared_sum = None\n\n n_classes = len(self.classes_)\n classes_ = self.classes_\n if n_classes < 2:\n raise ValueError(\n \"This solver needs samples of at least 2 classes\"\n \" in the data, but the data contains only one\"\n \" class: %r\"\n % classes_[0]\n )\n\n if len(self.classes_) == 2:\n n_classes = 1\n classes_ = classes_[1:]\n\n if self.warm_start:\n warm_start_coef = getattr(self, \"coef_\", None)\n else:\n warm_start_coef = None\n if warm_start_coef is not None and self.fit_intercept:\n warm_start_coef = np.append(\n warm_start_coef, self.intercept_[:, np.newaxis], axis=1\n )\n\n # Hack so that we iterate only once for the multinomial case.\n if multi_class == \"multinomial\":\n classes_ = [None]\n warm_start_coef = [warm_start_coef]\n if warm_start_coef is None:\n warm_start_coef = [None] * n_classes\n\n path_func = delayed(_logistic_regression_path)\n\n # The SAG solver releases the GIL so it's more efficient to use\n # threads for this solver.\n if solver in [\"sag\", \"saga\"]:\n prefer = \"threads\"\n else:\n prefer = \"processes\"\n fold_coefs_ = Parallel(\n n_jobs=self.n_jobs,\n verbose=self.verbose,\n **_joblib_parallel_args(prefer=prefer),\n )(\n path_func(\n X,\n y,\n pos_class=class_,\n Cs=[C_],\n l1_ratio=self.l1_ratio,\n fit_intercept=self.fit_intercept,\n tol=self.tol,\n verbose=self.verbose,\n solver=solver,\n multi_class=multi_class,\n max_iter=self.max_iter,\n class_weight=self.class_weight,\n check_input=False,\n random_state=self.random_state,\n coef=warm_start_coef_,\n penalty=penalty,\n max_squared_sum=max_squared_sum,\n sample_weight=sample_weight,\n )\n for class_, warm_start_coef_ in zip(classes_, warm_start_coef)\n )\n\n fold_coefs_, _, n_iter_ = zip(*fold_coefs_)\n self.n_iter_ = np.asarray(n_iter_, dtype=np.int32)[:, 0]\n\n n_features = X.shape[1]\n if multi_class == \"multinomial\":\n self.coef_ = fold_coefs_[0][0]\n else:\n self.coef_ = np.asarray(fold_coefs_)\n self.coef_ = self.coef_.reshape(\n n_classes, n_features + int(self.fit_intercept)\n )\n\n if self.fit_intercept:\n self.intercept_ = self.coef_[:, -1]\n self.coef_ = self.coef_[:, :-1]\n else:\n self.intercept_ = np.zeros(n_classes)\n\n return self\n\n def predict_proba(self, X):\n \"\"\"\n Probability estimates.\n\n The returned estimates for all classes are ordered by the\n label of classes.\n\n For a multi_class problem, if multi_class is set to be \"multinomial\"\n the softmax function is used to find the predicted probability of\n each class.\n Else use a one-vs-rest approach, i.e calculate the probability\n of each class assuming it to be positive using the logistic function.\n and normalize these values across all the classes.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Vector to be scored, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n Returns\n -------\n T : array-like of shape (n_samples, n_classes)\n Returns the probability of the sample for each class in the model,\n where classes are ordered as they are in ``self.classes_``.\n \"\"\"\n check_is_fitted(self)\n\n ovr = self.multi_class in [\"ovr\", \"warn\"] or (\n self.multi_class == \"auto\"\n and (self.classes_.size <= 2 or self.solver == \"liblinear\")\n )\n if ovr:\n return super()._predict_proba_lr(X)\n else:\n decision = self.decision_function(X)\n if decision.ndim == 1:\n # Workaround for multi_class=\"multinomial\" and binary outcomes\n # which requires softmax prediction with only a 1D decision.\n decision_2d = np.c_[-decision, decision]\n else:\n decision_2d = decision\n return softmax(decision_2d, copy=False)\n\n def predict_log_proba(self, X):\n \"\"\"\n Predict logarithm of probability estimates.\n\n The returned estimates for all classes are ordered by the\n label of classes.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Vector to be scored, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n Returns\n -------\n T : array-like of shape (n_samples, n_classes)\n Returns the log-probability of the sample for each class in the\n model, where classes are ordered as they are in ``self.classes_``.\n \"\"\"\n return np.log(self.predict_proba(X))\n\n\nclass LogisticRegressionCV(LogisticRegression, LinearClassifierMixin, BaseEstimator):\n \"\"\"Logistic Regression CV (aka logit, MaxEnt) classifier.\n\n See glossary entry for :term:`cross-validation estimator`.\n\n This class implements logistic regression using liblinear, newton-cg, sag\n of lbfgs optimizer. The newton-cg, sag and lbfgs solvers support only L2\n regularization with primal formulation. The liblinear solver supports both\n L1 and L2 regularization, with a dual formulation only for the L2 penalty.\n Elastic-Net penalty is only supported by the saga solver.\n\n For the grid of `Cs` values and `l1_ratios` values, the best hyperparameter\n is selected by the cross-validator\n :class:`~sklearn.model_selection.StratifiedKFold`, but it can be changed\n using the :term:`cv` parameter. The 'newton-cg', 'sag', 'saga' and 'lbfgs'\n solvers can warm-start the coefficients (see :term:`Glossary<warm_start>`).\n\n Read more in the :ref:`User Guide <logistic_regression>`.\n\n Parameters\n ----------\n Cs : int or list of floats, default=10\n Each of the values in Cs describes the inverse of regularization\n strength. If Cs is as an int, then a grid of Cs values are chosen\n in a logarithmic scale between 1e-4 and 1e4.\n Like in support vector machines, smaller values specify stronger\n regularization.\n\n fit_intercept : bool, default=True\n Specifies if a constant (a.k.a. bias or intercept) should be\n added to the decision function.\n\n cv : int or cross-validation generator, default=None\n The default cross-validation generator used is Stratified K-Folds.\n If an integer is provided, then it is the number of folds used.\n See the module :mod:`sklearn.model_selection` module for the\n list of possible cross-validation objects.\n\n .. versionchanged:: 0.22\n ``cv`` default value if None changed from 3-fold to 5-fold.\n\n dual : bool, default=False\n Dual or primal formulation. Dual formulation is only implemented for\n l2 penalty with liblinear solver. Prefer dual=False when\n n_samples > n_features.\n\n penalty : {'l1', 'l2', 'elasticnet'}, default='l2'\n Specify the norm of the penalty:\n\n - `'l2'`: add a L2 penalty term (used by default);\n - `'l1'`: add a L1 penalty term;\n - `'elasticnet'`: both L1 and L2 penalty terms are added.\n\n .. warning::\n Some penalties may not work with some solvers. See the parameter\n `solver` below, to know the compatibility between the penalty and\n solver.\n\n scoring : str or callable, default=None\n A string (see model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``. For a list of scoring functions\n that can be used, look at :mod:`sklearn.metrics`. The\n default scoring option used is 'accuracy'.\n\n solver : {'newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'}, \\\n default='lbfgs'\n\n Algorithm to use in the optimization problem. Default is 'lbfgs'.\n To choose a solver, you might want to consider the following aspects:\n\n - For small datasets, 'liblinear' is a good choice, whereas 'sag'\n and 'saga' are faster for large ones;\n - For multiclass problems, only 'newton-cg', 'sag', 'saga' and\n 'lbfgs' handle multinomial loss;\n - 'liblinear' might be slower in :class:`LogisticRegressionCV`\n because it does not handle warm-starting. 'liblinear' is\n limited to one-versus-rest schemes.\n\n .. warning::\n The choice of the algorithm depends on the penalty chosen:\n\n - 'newton-cg' - ['l2']\n - 'lbfgs' - ['l2']\n - 'liblinear' - ['l1', 'l2']\n - 'sag' - ['l2']\n - 'saga' - ['elasticnet', 'l1', 'l2']\n\n .. note::\n 'sag' and 'saga' fast convergence is only guaranteed on features\n with approximately the same scale. You can preprocess the data with\n a scaler from :mod:`sklearn.preprocessing`.\n\n .. versionadded:: 0.17\n Stochastic Average Gradient descent solver.\n .. versionadded:: 0.19\n SAGA solver.\n\n tol : float, default=1e-4\n Tolerance for stopping criteria.\n\n max_iter : int, default=100\n Maximum number of iterations of the optimization algorithm.\n\n class_weight : dict or 'balanced', default=None\n Weights associated with classes in the form ``{class_label: weight}``.\n If not given, all classes are supposed to have weight one.\n\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``.\n\n Note that these weights will be multiplied with sample_weight (passed\n through the fit method) if sample_weight is specified.\n\n .. versionadded:: 0.17\n class_weight == 'balanced'\n\n n_jobs : int, default=None\n Number of CPU cores used during the cross-validation loop.\n ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.\n ``-1`` means using all processors. See :term:`Glossary <n_jobs>`\n for more details.\n\n verbose : int, default=0\n For the 'liblinear', 'sag' and 'lbfgs' solvers set verbose to any\n positive number for verbosity.\n\n refit : bool, default=True\n If set to True, the scores are averaged across all folds, and the\n coefs and the C that corresponds to the best score is taken, and a\n final refit is done using these parameters.\n Otherwise the coefs, intercepts and C that correspond to the\n best scores across folds are averaged.\n\n intercept_scaling : float, default=1\n Useful only when the solver 'liblinear' is used\n and self.fit_intercept is set to True. In this case, x becomes\n [x, self.intercept_scaling],\n i.e. a \"synthetic\" feature with constant value equal to\n intercept_scaling is appended to the instance vector.\n The intercept becomes ``intercept_scaling * synthetic_feature_weight``.\n\n Note! the synthetic feature weight is subject to l1/l2 regularization\n as all other features.\n To lessen the effect of regularization on synthetic feature weight\n (and therefore on the intercept) intercept_scaling has to be increased.\n\n multi_class : {'auto, 'ovr', 'multinomial'}, default='auto'\n If the option chosen is 'ovr', then a binary problem is fit for each\n label. For 'multinomial' the loss minimised is the multinomial loss fit\n across the entire probability distribution, *even when the data is\n binary*. 'multinomial' is unavailable when solver='liblinear'.\n 'auto' selects 'ovr' if the data is binary, or if solver='liblinear',\n and otherwise selects 'multinomial'.\n\n .. versionadded:: 0.18\n Stochastic Average Gradient descent solver for 'multinomial' case.\n .. versionchanged:: 0.22\n Default changed from 'ovr' to 'auto' in 0.22.\n\n random_state : int, RandomState instance, default=None\n Used when `solver='sag'`, 'saga' or 'liblinear' to shuffle the data.\n Note that this only applies to the solver and not the cross-validation\n generator. See :term:`Glossary <random_state>` for details.\n\n l1_ratios : list of float, default=None\n The list of Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``.\n Only used if ``penalty='elasticnet'``. A value of 0 is equivalent to\n using ``penalty='l2'``, while 1 is equivalent to using\n ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a combination\n of L1 and L2.\n\n Attributes\n ----------\n classes_ : ndarray of shape (n_classes, )\n A list of class labels known to the classifier.\n\n coef_ : ndarray of shape (1, n_features) or (n_classes, n_features)\n Coefficient of the features in the decision function.\n\n `coef_` is of shape (1, n_features) when the given problem\n is binary.\n\n intercept_ : ndarray of shape (1,) or (n_classes,)\n Intercept (a.k.a. bias) added to the decision function.\n\n If `fit_intercept` is set to False, the intercept is set to zero.\n `intercept_` is of shape(1,) when the problem is binary.\n\n Cs_ : ndarray of shape (n_cs)\n Array of C i.e. inverse of regularization parameter values used\n for cross-validation.\n\n l1_ratios_ : ndarray of shape (n_l1_ratios)\n Array of l1_ratios used for cross-validation. If no l1_ratio is used\n (i.e. penalty is not 'elasticnet'), this is set to ``[None]``\n\n coefs_paths_ : ndarray of shape (n_folds, n_cs, n_features) or \\\n (n_folds, n_cs, n_features + 1)\n dict with classes as the keys, and the path of coefficients obtained\n during cross-validating across each fold and then across each Cs\n after doing an OvR for the corresponding class as values.\n If the 'multi_class' option is set to 'multinomial', then\n the coefs_paths are the coefficients corresponding to each class.\n Each dict value has shape ``(n_folds, n_cs, n_features)`` or\n ``(n_folds, n_cs, n_features + 1)`` depending on whether the\n intercept is fit or not. If ``penalty='elasticnet'``, the shape is\n ``(n_folds, n_cs, n_l1_ratios_, n_features)`` or\n ``(n_folds, n_cs, n_l1_ratios_, n_features + 1)``.\n\n scores_ : dict\n dict with classes as the keys, and the values as the\n grid of scores obtained during cross-validating each fold, after doing\n an OvR for the corresponding class. If the 'multi_class' option\n given is 'multinomial' then the same scores are repeated across\n all classes, since this is the multinomial class. Each dict value\n has shape ``(n_folds, n_cs`` or ``(n_folds, n_cs, n_l1_ratios)`` if\n ``penalty='elasticnet'``.\n\n C_ : ndarray of shape (n_classes,) or (n_classes - 1,)\n Array of C that maps to the best scores across every class. If refit is\n set to False, then for each class, the best C is the average of the\n C's that correspond to the best scores for each fold.\n `C_` is of shape(n_classes,) when the problem is binary.\n\n l1_ratio_ : ndarray of shape (n_classes,) or (n_classes - 1,)\n Array of l1_ratio that maps to the best scores across every class. If\n refit is set to False, then for each class, the best l1_ratio is the\n average of the l1_ratio's that correspond to the best scores for each\n fold. `l1_ratio_` is of shape(n_classes,) when the problem is binary.\n\n n_iter_ : ndarray of shape (n_classes, n_folds, n_cs) or (1, n_folds, n_cs)\n Actual number of iterations for all classes, folds and Cs.\n In the binary or multinomial cases, the first dimension is equal to 1.\n If ``penalty='elasticnet'``, the shape is ``(n_classes, n_folds,\n n_cs, n_l1_ratios)`` or ``(1, n_folds, n_cs, n_l1_ratios)``.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n See Also\n --------\n LogisticRegression : Logistic regression without tuning the\n hyperparameter `C`.\n\n Examples\n --------\n >>> from sklearn.datasets import load_iris\n >>> from sklearn.linear_model import LogisticRegressionCV\n >>> X, y = load_iris(return_X_y=True)\n >>> clf = LogisticRegressionCV(cv=5, random_state=0).fit(X, y)\n >>> clf.predict(X[:2, :])\n array([0, 0])\n >>> clf.predict_proba(X[:2, :]).shape\n (2, 3)\n >>> clf.score(X, y)\n 0.98...\n \"\"\"\n\n def __init__(\n self,\n *,\n Cs=10,\n fit_intercept=True,\n cv=None,\n dual=False,\n penalty=\"l2\",\n scoring=None,\n solver=\"lbfgs\",\n tol=1e-4,\n max_iter=100,\n class_weight=None,\n n_jobs=None,\n verbose=0,\n refit=True,\n intercept_scaling=1.0,\n multi_class=\"auto\",\n random_state=None,\n l1_ratios=None,\n ):\n self.Cs = Cs\n self.fit_intercept = fit_intercept\n self.cv = cv\n self.dual = dual\n self.penalty = penalty\n self.scoring = scoring\n self.tol = tol\n self.max_iter = max_iter\n self.class_weight = class_weight\n self.n_jobs = n_jobs\n self.verbose = verbose\n self.solver = solver\n self.refit = refit\n self.intercept_scaling = intercept_scaling\n self.multi_class = multi_class\n self.random_state = random_state\n self.l1_ratios = l1_ratios\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit the model according to the given training data.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training vector, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : array-like of shape (n_samples,)\n Target vector relative to X.\n\n sample_weight : array-like of shape (n_samples,) default=None\n Array of weights that are assigned to individual samples.\n If not provided, then each sample is given unit weight.\n\n Returns\n -------\n self : object\n Fitted LogisticRegressionCV estimator.\n \"\"\"\n solver = _check_solver(self.solver, self.penalty, self.dual)\n\n if not isinstance(self.max_iter, numbers.Number) or self.max_iter < 0:\n raise ValueError(\n \"Maximum number of iteration must be positive; got (max_iter=%r)\"\n % self.max_iter\n )\n if not isinstance(self.tol, numbers.Number) or self.tol < 0:\n raise ValueError(\n \"Tolerance for stopping criteria must be positive; got (tol=%r)\"\n % self.tol\n )\n if self.penalty == \"elasticnet\":\n if (\n self.l1_ratios is None\n or len(self.l1_ratios) == 0\n or any(\n (\n not isinstance(l1_ratio, numbers.Number)\n or l1_ratio < 0\n or l1_ratio > 1\n )\n for l1_ratio in self.l1_ratios\n )\n ):\n raise ValueError(\n \"l1_ratios must be a list of numbers between \"\n \"0 and 1; got (l1_ratios=%r)\"\n % self.l1_ratios\n )\n l1_ratios_ = self.l1_ratios\n else:\n if self.l1_ratios is not None:\n warnings.warn(\n \"l1_ratios parameter is only used when penalty \"\n \"is 'elasticnet'. Got (penalty={})\".format(self.penalty)\n )\n\n l1_ratios_ = [None]\n\n if self.penalty == \"none\":\n raise ValueError(\n \"penalty='none' is not useful and not supported by \"\n \"LogisticRegressionCV.\"\n )\n\n X, y = self._validate_data(\n X,\n y,\n accept_sparse=\"csr\",\n dtype=np.float64,\n order=\"C\",\n accept_large_sparse=solver not in [\"liblinear\", \"sag\", \"saga\"],\n )\n check_classification_targets(y)\n\n class_weight = self.class_weight\n\n # Encode for string labels\n label_encoder = LabelEncoder().fit(y)\n y = label_encoder.transform(y)\n if isinstance(class_weight, dict):\n class_weight = {\n label_encoder.transform([cls])[0]: v for cls, v in class_weight.items()\n }\n\n # The original class labels\n classes = self.classes_ = label_encoder.classes_\n encoded_labels = label_encoder.transform(label_encoder.classes_)\n\n multi_class = _check_multi_class(self.multi_class, solver, len(classes))\n\n if solver in [\"sag\", \"saga\"]:\n max_squared_sum = row_norms(X, squared=True).max()\n else:\n max_squared_sum = None\n\n # init cross-validation generator\n cv = check_cv(self.cv, y, classifier=True)\n folds = list(cv.split(X, y))\n\n # Use the label encoded classes\n n_classes = len(encoded_labels)\n\n if n_classes < 2:\n raise ValueError(\n \"This solver needs samples of at least 2 classes\"\n \" in the data, but the data contains only one\"\n \" class: %r\"\n % classes[0]\n )\n\n if n_classes == 2:\n # OvR in case of binary problems is as good as fitting\n # the higher label\n n_classes = 1\n encoded_labels = encoded_labels[1:]\n classes = classes[1:]\n\n # We need this hack to iterate only once over labels, in the case of\n # multi_class = multinomial, without changing the value of the labels.\n if multi_class == \"multinomial\":\n iter_encoded_labels = iter_classes = [None]\n else:\n iter_encoded_labels = encoded_labels\n iter_classes = classes\n\n # compute the class weights for the entire dataset y\n if class_weight == \"balanced\":\n class_weight = compute_class_weight(\n class_weight, classes=np.arange(len(self.classes_)), y=y\n )\n class_weight = dict(enumerate(class_weight))\n\n path_func = delayed(_log_reg_scoring_path)\n\n # The SAG solver releases the GIL so it's more efficient to use\n # threads for this solver.\n if self.solver in [\"sag\", \"saga\"]:\n prefer = \"threads\"\n else:\n prefer = \"processes\"\n\n fold_coefs_ = Parallel(\n n_jobs=self.n_jobs,\n verbose=self.verbose,\n **_joblib_parallel_args(prefer=prefer),\n )(\n path_func(\n X,\n y,\n train,\n test,\n pos_class=label,\n Cs=self.Cs,\n fit_intercept=self.fit_intercept,\n penalty=self.penalty,\n dual=self.dual,\n solver=solver,\n tol=self.tol,\n max_iter=self.max_iter,\n verbose=self.verbose,\n class_weight=class_weight,\n scoring=self.scoring,\n multi_class=multi_class,\n intercept_scaling=self.intercept_scaling,\n random_state=self.random_state,\n max_squared_sum=max_squared_sum,\n sample_weight=sample_weight,\n l1_ratio=l1_ratio,\n )\n for label in iter_encoded_labels\n for train, test in folds\n for l1_ratio in l1_ratios_\n )\n\n # _log_reg_scoring_path will output different shapes depending on the\n # multi_class param, so we need to reshape the outputs accordingly.\n # Cs is of shape (n_classes . n_folds . n_l1_ratios, n_Cs) and all the\n # rows are equal, so we just take the first one.\n # After reshaping,\n # - scores is of shape (n_classes, n_folds, n_Cs . n_l1_ratios)\n # - coefs_paths is of shape\n # (n_classes, n_folds, n_Cs . n_l1_ratios, n_features)\n # - n_iter is of shape\n # (n_classes, n_folds, n_Cs . n_l1_ratios) or\n # (1, n_folds, n_Cs . n_l1_ratios)\n coefs_paths, Cs, scores, n_iter_ = zip(*fold_coefs_)\n self.Cs_ = Cs[0]\n if multi_class == \"multinomial\":\n coefs_paths = np.reshape(\n coefs_paths,\n (len(folds), len(l1_ratios_) * len(self.Cs_), n_classes, -1),\n )\n # equiv to coefs_paths = np.moveaxis(coefs_paths, (0, 1, 2, 3),\n # (1, 2, 0, 3))\n coefs_paths = np.swapaxes(coefs_paths, 0, 1)\n coefs_paths = np.swapaxes(coefs_paths, 0, 2)\n self.n_iter_ = np.reshape(\n n_iter_, (1, len(folds), len(self.Cs_) * len(l1_ratios_))\n )\n # repeat same scores across all classes\n scores = np.tile(scores, (n_classes, 1, 1))\n else:\n coefs_paths = np.reshape(\n coefs_paths,\n (n_classes, len(folds), len(self.Cs_) * len(l1_ratios_), -1),\n )\n self.n_iter_ = np.reshape(\n n_iter_, (n_classes, len(folds), len(self.Cs_) * len(l1_ratios_))\n )\n scores = np.reshape(scores, (n_classes, len(folds), -1))\n self.scores_ = dict(zip(classes, scores))\n self.coefs_paths_ = dict(zip(classes, coefs_paths))\n\n self.C_ = list()\n self.l1_ratio_ = list()\n self.coef_ = np.empty((n_classes, X.shape[1]))\n self.intercept_ = np.zeros(n_classes)\n for index, (cls, encoded_label) in enumerate(\n zip(iter_classes, iter_encoded_labels)\n ):\n\n if multi_class == \"ovr\":\n scores = self.scores_[cls]\n coefs_paths = self.coefs_paths_[cls]\n else:\n # For multinomial, all scores are the same across classes\n scores = scores[0]\n # coefs_paths will keep its original shape because\n # logistic_regression_path expects it this way\n\n if self.refit:\n # best_index is between 0 and (n_Cs . n_l1_ratios - 1)\n # for example, with n_cs=2 and n_l1_ratios=3\n # the layout of scores is\n # [c1, c2, c1, c2, c1, c2]\n # l1_1 , l1_2 , l1_3\n best_index = scores.sum(axis=0).argmax()\n\n best_index_C = best_index % len(self.Cs_)\n C_ = self.Cs_[best_index_C]\n self.C_.append(C_)\n\n best_index_l1 = best_index // len(self.Cs_)\n l1_ratio_ = l1_ratios_[best_index_l1]\n self.l1_ratio_.append(l1_ratio_)\n\n if multi_class == \"multinomial\":\n coef_init = np.mean(coefs_paths[:, :, best_index, :], axis=1)\n else:\n coef_init = np.mean(coefs_paths[:, best_index, :], axis=0)\n\n # Note that y is label encoded and hence pos_class must be\n # the encoded label / None (for 'multinomial')\n w, _, _ = _logistic_regression_path(\n X,\n y,\n pos_class=encoded_label,\n Cs=[C_],\n solver=solver,\n fit_intercept=self.fit_intercept,\n coef=coef_init,\n max_iter=self.max_iter,\n tol=self.tol,\n penalty=self.penalty,\n class_weight=class_weight,\n multi_class=multi_class,\n verbose=max(0, self.verbose - 1),\n random_state=self.random_state,\n check_input=False,\n max_squared_sum=max_squared_sum,\n sample_weight=sample_weight,\n l1_ratio=l1_ratio_,\n )\n w = w[0]\n\n else:\n # Take the best scores across every fold and the average of\n # all coefficients corresponding to the best scores.\n best_indices = np.argmax(scores, axis=1)\n if multi_class == \"ovr\":\n w = np.mean(\n [coefs_paths[i, best_indices[i], :] for i in range(len(folds))],\n axis=0,\n )\n else:\n w = np.mean(\n [\n coefs_paths[:, i, best_indices[i], :]\n for i in range(len(folds))\n ],\n axis=0,\n )\n\n best_indices_C = best_indices % len(self.Cs_)\n self.C_.append(np.mean(self.Cs_[best_indices_C]))\n\n if self.penalty == \"elasticnet\":\n best_indices_l1 = best_indices // len(self.Cs_)\n self.l1_ratio_.append(np.mean(l1_ratios_[best_indices_l1]))\n else:\n self.l1_ratio_.append(None)\n\n if multi_class == \"multinomial\":\n self.C_ = np.tile(self.C_, n_classes)\n self.l1_ratio_ = np.tile(self.l1_ratio_, n_classes)\n self.coef_ = w[:, : X.shape[1]]\n if self.fit_intercept:\n self.intercept_ = w[:, -1]\n else:\n self.coef_[index] = w[: X.shape[1]]\n if self.fit_intercept:\n self.intercept_[index] = w[-1]\n\n self.C_ = np.asarray(self.C_)\n self.l1_ratio_ = np.asarray(self.l1_ratio_)\n self.l1_ratios_ = np.asarray(l1_ratios_)\n # if elasticnet was used, add the l1_ratios dimension to some\n # attributes\n if self.l1_ratios is not None:\n # with n_cs=2 and n_l1_ratios=3\n # the layout of scores is\n # [c1, c2, c1, c2, c1, c2]\n # l1_1 , l1_2 , l1_3\n # To get a 2d array with the following layout\n # l1_1, l1_2, l1_3\n # c1 [[ . , . , . ],\n # c2 [ . , . , . ]]\n # We need to first reshape and then transpose.\n # The same goes for the other arrays\n for cls, coefs_path in self.coefs_paths_.items():\n self.coefs_paths_[cls] = coefs_path.reshape(\n (len(folds), self.l1_ratios_.size, self.Cs_.size, -1)\n )\n self.coefs_paths_[cls] = np.transpose(\n self.coefs_paths_[cls], (0, 2, 1, 3)\n )\n for cls, score in self.scores_.items():\n self.scores_[cls] = score.reshape(\n (len(folds), self.l1_ratios_.size, self.Cs_.size)\n )\n self.scores_[cls] = np.transpose(self.scores_[cls], (0, 2, 1))\n\n self.n_iter_ = self.n_iter_.reshape(\n (-1, len(folds), self.l1_ratios_.size, self.Cs_.size)\n )\n self.n_iter_ = np.transpose(self.n_iter_, (0, 1, 3, 2))\n\n return self\n\n def score(self, X, y, sample_weight=None):\n \"\"\"Score using the `scoring` option on the given test data and labels.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Test samples.\n\n y : array-like of shape (n_samples,)\n True labels for X.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n Returns\n -------\n score : float\n Score of self.predict(X) wrt. y.\n \"\"\"\n scoring = self.scoring or \"accuracy\"\n scoring = get_scorer(scoring)\n\n return scoring(self, X, y, sample_weight=sample_weight)\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n" ]
[ [ "numpy.ones", "numpy.asarray", "scipy.sparse.dia_matrix", "numpy.transpose", "numpy.append", "numpy.reshape", "numpy.empty_like", "numpy.expand_dims", "numpy.unique", "numpy.mean", "numpy.tile", "numpy.zeros", "scipy.optimize.minimize", "numpy.linalg.multi_dot", "numpy.argmax", "numpy.hstack", "scipy.special.logsumexp", "numpy.empty", "scipy.sparse.issparse", "numpy.swapaxes", "numpy.exp", "scipy.special.expit", "numpy.logspace", "numpy.array", "numpy.dot" ] ]
shoz/ProtLearn
[ "2c6edac2c3cfdc4aeeb2b55bb3cb5e4407e2065e" ]
[ "tests/test_length.py" ]
[ "import os\nimport sys\npath = os.environ.get('TRAVIS_BUILD_DIR')\nsys.path.insert(0, path+'/protlearn')\nimport numpy as np\n\nfrom preprocessing import txt_to_df\nfrom feature_engineering import length\n\n\ndef test_lengths():\n \"Test sequence lengths\"\n \n # load data\n df = txt_to_df(path+'/tests/docs/test_seq.txt', 0)\n \n # test integer lengths\n len_int = length(df, 'int')\n assert np.array_equal(len_int, np.array([6, 9, 7, 6]))\n \n # test one-hot-encoded lengths\n len_ohe = length(df, 'ohe')\n # columns: [6, 7, 9]\n assert np.array_equal(len_ohe, np.array([[1., 0., 0.],\n [0., 0., 1.],\n [0., 1., 0.],\n [1., 0., 0.]]))" ]
[ [ "numpy.array" ] ]
harwiltz/bach-robot-suite
[ "1126a665266cc5819d331af79effd03f3efe043f" ]
[ "examples/rocket_lander_test.py" ]
[ "import gym\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\nimport brs_envs\n\nenv = gym.make('RocketLanderBRSEnv-v0',\n render=True,\n max_lateral_offset=0,\n max_pitch_offset=0,\n max_roll_offset=0,\n max_yaw_offset=0,\n mean_robot_start_height=100)\ns = env.reset()\n\nzero_action = np.zeros(env.action_space.shape)\n\nvels = []\n\ninput(\"Press ENTER to start...\")\ntarget = 80\nfor i in range(1800):\n time.sleep(1/60)\n if s[2] < target:\n a = np.array([min(1.0, (s[2] - target)**2), 0.0, 0.0])\n else:\n a = np.array([0.3, 0.0, 0.0])\n a += np.array([0.0, 0.15 * np.sin(0.1 * i), 0.8])\n s, r, done, _ = env.step(a)\n# vels.append(np.linalg.norm(s[7:10]))\n vels.append(s[2])\n# s, r, done, _ = env.step(env.action_space.sample())\n if done:\n print(\"Reward in final frame: {}\".format(r))\n break\n\nplt.plot(np.arange(len(vels)) / 60, vels)\nplt.xlabel('Time (s)')\nplt.ylabel('Position (m)')\nplt.show()\n" ]
[ [ "numpy.zeros", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.array", "numpy.sin", "matplotlib.pyplot.xlabel" ] ]
CarlChenCC/TradingStockWeb
[ "da8ab0163daa980b9506686d25465da2a34c029d" ]
[ "TradingSystemApp/ML.py" ]
[ "from IPython.display import Image\n#%matplotlib inline\n\nfrom distutils.version import LooseVersion as Version\nfrom sklearn import __version__ as sklearn_version\n#Image(filename='./images/10_01.png', width=500)\n\n\nimport pandas as pd\n\ndf = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/'\n 'housing/housing.data',\n header=None,\n sep='\\s+')\n\ndf.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS', \n 'NOX', 'RM', 'AGE', 'DIS', 'RAD', \n 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']\ndf.head()\n\ndf = pd.read_csv('https://raw.githubusercontent.com/rasbt/python-machine-learning-book/master/code/datasets/housing/housing.data',\n header=None, sep='\\s+')\n\ndf.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS', \n 'NOX', 'RM', 'AGE', 'DIS', 'RAD', \n 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']\ndf.head()\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\nsns.set(style='whitegrid', context='notebook')\ncols = ['LSTAT', 'INDUS', 'NOX', 'RM', 'MEDV']\n\nsns.pairplot(df[cols], size=2.5)\nplt.tight_layout()\n# plt.savefig('./figures/scatter.png', dpi=300)\nplt.show()\n\nimport numpy as np\n\n\ncm = np.corrcoef(df[cols].values.T)\nsns.set(font_scale=1.5)\nhm = sns.heatmap(cm,\n cbar=True,\n annot=True,\n square=True,\n fmt='.2f',\n annot_kws={'size': 15},\n yticklabels=cols,\n xticklabels=cols)\n\n# plt.tight_layout()\n# plt.savefig('./figures/corr_mat.png', dpi=300)\nplt.show()\n\n\nsns.reset_orig()\n#%matplotlib inline\n\nclass LinearRegressionGD(object):\n\n def __init__(self, eta=0.001, n_iter=20):\n self.eta = eta\n self.n_iter = n_iter\n\n def fit(self, X, y):\n self.w_ = np.zeros(1 + X.shape[1])\n self.cost_ = []\n\n for i in range(self.n_iter):\n output = self.net_input(X)\n errors = (y - output)\n self.w_[1:] += self.eta * X.T.dot(errors)\n self.w_[0] += self.eta * errors.sum()\n cost = (errors**2).sum() / 2.0\n self.cost_.append(cost)\n return self\n\n def net_input(self, X):\n return np.dot(X, self.w_[1:]) + self.w_[0]\n\n def predict(self, X):\n return self.net_input(X)\n\nX = df[['RM']].values\ny = df['MEDV'].values\n\n\n\nfrom sklearn.preprocessing import StandardScaler\n\n\nsc_x = StandardScaler()\nsc_y = StandardScaler()\nX_std = sc_x.fit_transform(X)\ny_std = sc_y.fit_transform(y[:, np.newaxis]).flatten()\n\n\n\nlr = LinearRegressionGD()\nlr.fit(X_std, y_std)\n\nplt.plot(range(1, lr.n_iter+1), lr.cost_)\nplt.ylabel('SSE')\nplt.xlabel('Epoch')\nplt.tight_layout()\n# plt.savefig('./figures/cost.png', dpi=300)\nplt.show()\n\n\ndef lin_regplot(X, y, model):\n plt.scatter(X, y, c='lightblue')\n plt.plot(X, model.predict(X), color='red', linewidth=2) \n return\nlin_regplot(X_std, y_std, lr)\nplt.xlabel('Average number of rooms [RM] (standardized)')\nplt.ylabel('Price in $1000\\'s [MEDV] (standardized)')\nplt.tight_layout()\n# plt.savefig('./figures/gradient_fit.png', dpi=300)\nplt.show()\n" ]
[ [ "numpy.zeros", "pandas.read_csv", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "sklearn.preprocessing.StandardScaler", "numpy.dot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.scatter", "numpy.corrcoef" ] ]
nbechor/SlipperySlope
[ "5a456a9632b73e2f5ff0d90fe080aeec1ec3cc3a" ]
[ "src/features/built_events_w_weather_features_labels0.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom weatherClass import weatherClass\nfrom IdentifierClass import identifierClass\nfrom eventsClass import eventsClass\nimport datetime\n\n### load some data:\n\n#read the ticket+complaint data, combined for location:\n# events fields: date, lat, lng, address, identifier, index\ntemp = pd.read_csv('/Users/nbechor/Insight/noslipwalk/noslipwalk/features/negative_labels_5_d_15_with_identifier.csv')\nevents = eventsClass(temp)\n\n\n# read the identifier to weather data:\n# this is the the result of the nearest neighbor for weather. Each\n# key address has an identifier, that identifier is tied to the different\n# lat longs of a given address, and to the closest weather data grid point\n# fields: lat, lon, identifier as index\ntemp = pd.read_csv('/Users/nbechor/Insight/noslipwalk/noslipwalk/features/identifier2weatherloc.csv')\nidentifier2weatherloc = identifierClass(temp)\n\n\n# weather_features fields:\n# fields: time, lat, lon, frost indicator,thaw indicator, rain indicator,\n# snow indicator, rain amount, snow amount\ntemp = pd.read_csv('/Users/nbechor/Insight/noslipwalk/noslipwalk/features/weather_features.csv')\nweather_features = weatherClass(temp)\nweather_features.df = weather_features.df.fillna(0)\nprint(weather_features.df)\n\nnewPointEvents = pd.DataFrame() # we'll add to this in the loop (the main output)\n\n# going over all identifiers, and events for each:\nidentifiers = events.df['identifier'].unique().astype('int').tolist()\n\n\nnew_events = pd.DataFrame()\nfor identifier in identifiers:\n pointEvents = events.df[events.df['identifier'] == identifier]\n lat,lon,errFlag = identifierClass.latLonFromRecord(identifier2weatherloc,identifier)\n if (~errFlag):\n pointWeather = weatherClass.weatherByLatLon(weather_features,lat,lon)\n\n # now need to go over events and get weather for each of them:\n for i in range(0,pointEvents.shape[0]):\n date = pointEvents['date'].iloc[i]\n time_struct = date.timetuple()\n year = time_struct.tm_year\n doy = time_struct.tm_yday\n weather = pointWeather[pointWeather['date']==date]\n if (~weather.empty):\n # switch the lat lon in the weather for the lat lon of the event:\n try:\n weather['lat'] = pointEvents['lat'].iloc[i]\n weather['lon'] = pointEvents['lng'].iloc[i]\n weather['address'] = pointEvents['address'].iloc[i]\n weather['label'] = 0\n weather['year'] = year\n weather['day of year'] = doy\n weather['year + day of year'] = year+doy\n new_events = new_events.append(weather)\n except:\n print(weather.shape)\n print('something off for date',date,'identifier',identifier)\n\n\nprint(new_events)\nnew_events.to_csv('/Users/nbechor/Insight/noslipwalk/noslipwalk/features/features_label0.csv')\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
Tensor46/TensorMONK
[ "1785132b82c685c3b3fc05b00dec46b1fccfc948" ]
[ "tensormonk/layers/routingcapsule.py" ]
[ "\"\"\" TensorMONK :: layers :: RoutingCapsule \"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom ..activations import Activations\n\n\nclass RoutingCapsule(nn.Module):\n r\"\"\" Routing capsule from Dynamic Routing Between Capsules.\n Implemented -- https://arxiv.org/pdf/1710.09829.pdf\n\n Args:\n tensor_size: 5D shape of tensor from PrimaryCapsule\n (None/any integer >0, capsule_length, height, width, n_capsules)\n n_capsules (int, required): number of capsules, usually, number of\n labels per paper\n capsule_length (int, required): length of capsules\n iterations (int, required): routing iterations, default = 3\n\n Return:\n 3D torch.Tensor of shape\n (None/any integer >0, n_capsules, capsule_length)\n \"\"\"\n def __init__(self,\n tensor_size,\n n_capsules: int = 10,\n capsule_length: int = 32,\n iterations: int = 3,\n *args, **kwargs):\n super(RoutingCapsule, self).__init__()\n self.iterations = iterations\n # Ex from paper\n # For tensor_size=(1,32,6,6,8), n_capsules=10 and capsule_length=16\n # weight_size = (tensor_size[1]*tensor_size[2]*tensor_size[3], \\\n # tensor_size[4], n_capsules*capsule_length)\n # = (32*6*6, 8 , 10*16)\n weight_size = (int(np.prod(tensor_size[1:-1])), tensor_size[-1],\n n_capsules*capsule_length)\n self.weight = nn.Parameter(torch.randn(*weight_size).normal_(0., 0.1))\n self.activation = Activations((None, int(np.prod(tensor_size[1:-1])),\n tensor_size[-1]), \"squash\")\n self.tensor_size = (6, n_capsules, capsule_length)\n\n def forward(self, tensor):\n batch_size, primary_capsule_length, h, w, n_primary_capsules = \\\n tensor.size()\n # Initial squash\n tensor = tensor.view(batch_size, -1, n_primary_capsules)\n tensor = self.activation(tensor)\n\n # from the given example:\n # tensor is of size _ x 32 x 6 x 6 x 8\n # after matrix mulitplication the size of u is _x32x6x6x10x16\n # essentially, each of the pixel from 8 primary capsules is project\n # to a dimension of n_capsules x capsule_length\n u = tensor.view(batch_size, -1, 1,\n n_primary_capsules).matmul(self.weight)\n u = u.view(*((batch_size, primary_capsule_length, h, w) +\n self.tensor_size[1:]))\n\n bias = torch.zeros(batch_size, primary_capsule_length, h, w,\n self.tensor_size[1])\n if tensor.is_cuda:\n bias = bias.to(tensor.device)\n\n # routing\n for i in range(self.iterations):\n # softmax\n # initial softmax gives equal probabilities (since bias is\n # initialized with zeros), eventually, bias updates will change\n # the probabilities\n c = F.softmax(bias, 4) # size = _ x 32 x 6 x 6 x 10\n # could be done with a single sum after reorganizing the tensor's,\n # however, retaining dimensions can explain better\n # s size without sum's = _ x 32 x 6 x 6 x 10 x 16\n # s size = _ x 10 x 16\n s = (c.unsqueeze(5)*u).sum(3).sum(2).sum(1)\n # squash -- v size = _ x 10 x 16\n v = self.activation(s)\n # bias update -- size = _ x 32 x 6 x 6 x 10\n if i < self.iterations-1:\n bias = bias + (u * v.view(batch_size, 1, 1, 1,\n self.tensor_size[1],\n self.tensor_size[2])).sum(5)\n return v\n\n def flops(self):\n # activations\n flops = self.activation.flops() * (1 + self.iterations)\n # matmul\n flops += np.prod(self.weight.shape) * self.weight.shape[1]\n # softmax\n flops += (self.weight.shape[0] * self.tensor_size[1] * 3) * \\\n self.iterations\n # s computation\n flops += (self.weight.shape[0] * (self.weight.shape[2] + 1)) * \\\n self.iterations\n # bias update _x32x6x6x10x16\n flops += self.weight.shape[0] * (self.weight.shape[2] + 2)\n return flops\n\n# from tensormonk.activations import Activations\n# x = torch.rand(3, 32, 10, 10, 8)\n# test = RoutingCapsule((3, 32, 10, 10, 8), 10, 16, 3,)\n# test(x).size()\n# test.flops()\n" ]
[ [ "torch.zeros", "torch.nn.functional.softmax", "torch.randn", "numpy.prod" ] ]
cgrinaldi/pocket_analytics
[ "7a79458de82b186fd4d5078b28d765d3bafe12aa" ]
[ "storage.py" ]
[ "import os\nimport logging\nimport pandas as pd\n\nfrom pathlib import Path\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nDIR_PATH = Path(os.path.dirname(os.path.abspath(__file__)))\nSINCE_PATH = DIR_PATH / Path('data/since.txt')\nARTICLES_PATH = DIR_PATH / Path('data/articles.csv')\n\n\ndef record_data_pull_time(timestamp):\n with open(SINCE_PATH, 'a+') as f:\n f.write('{}\\n'.format(timestamp))\n\n\ndef read_times_api_queried():\n try:\n with open(SINCE_PATH, 'r+') as f:\n sinces = f.readlines()\n return [s.split('\\n')[0] for s in sinces]\n except FileNotFoundError:\n return []\n\n\ndef get_most_recent_since():\n sinces = read_times_api_queried()\n if len(sinces) == 0:\n return None\n return sinces[-1]\n\n\ndef save_articles(articles):\n if articles is None:\n logger.info(f'no new articles found.')\n return\n logger.info(f'saving {len(articles)} articles.')\n try:\n articles_prev = pd.read_csv(ARTICLES_PATH)\n articles = pd.concat([articles_prev, articles])\n articles_deduped = articles.drop_duplicates(subset=['resolved_id'])\n articles_deduped.to_csv(ARTICLES_PATH, index=False, encoding='utf8')\n except FileNotFoundError:\n articles.to_csv(ARTICLES_PATH, index=False, encoding='utf8')\n" ]
[ [ "pandas.read_csv", "pandas.concat" ] ]
phunc20/dsp
[ "e7c496eb5fd4b8694eab0fc049cf98a5e3dfd886" ]
[ "stanford/sms-tools/lectures/07-Sinusoidal-plus-residual-model/plots-code/hpsModel-sax-phrase.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import hamming, hanning, triang, blackmanharris, resample\nimport math\nimport sys, os, time\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/'))\nimport utilFunctions as UF\nimport hpsModel as HPS\n\n\n(fs, x) = UF.wavread(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../sounds/sax-phrase-short.wav'))\nw = np.blackman(601)\nN = 1024\nt = -100\nnH = 100\nminf0 = 350\nmaxf0 = 700\nf0et = 5\nminSineDur = .1\nharmDevSlope = 0.01\nNs = 512\nH = Ns//4\nstocf = .2\nhfreq, hmag, hphase, mYst = HPS.hpsModelAnal(x, fs, w, N, H, t, nH, minf0, maxf0, f0et, harmDevSlope, minSineDur, Ns, stocf)\ny, yh, yst = HPS.hpsModelSynth(hfreq, hmag, hphase, mYst, Ns, H, fs)\n\nmaxplotfreq = 10000.0\nplt.figure(1, figsize=(9, 7))\n\nplt.subplot(311)\nplt.plot(np.arange(x.size)/float(fs), x, 'b')\nplt.autoscale(tight=True)\nplt.title('x (sax-phrase-short.wav)')\n\nplt.subplot(312)\nnumFrames = int(mYst[:,0].size)\nsizeEnv = int(mYst[0,:].size)\nfrmTime = H*np.arange(numFrames)/float(fs)\nbinFreq = (.5*fs)*np.arange(sizeEnv*maxplotfreq/(.5*fs))/sizeEnv \nplt.pcolormesh(frmTime, binFreq, np.transpose(mYst[:,:int(sizeEnv*maxplotfreq/(.5*fs)+1)]))\n\nharms = hfreq*np.less(hfreq,maxplotfreq)\nharms[harms==0] = np.nan\nnumFrames = int(harms[:,0].size)\nfrmTime = H*np.arange(numFrames)/float(fs) \nplt.plot(frmTime, harms, color='k', ms=3, alpha=1)\nplt.autoscale(tight=True)\nplt.title('harmonics + stochastic')\n\nplt.subplot(313)\nplt.plot(np.arange(y.size)/float(fs), y, 'b')\nplt.autoscale(tight=True)\nplt.title('y')\n\nplt.tight_layout()\nplt.savefig('hpsModel-sax-phrase.png')\nUF.wavwrite(y, fs, 'sax-phrase-hps-synthesis.wav')\nUF.wavwrite(yh, fs, 'sax-phrase-harmonic.wav')\nUF.wavwrite(yst, fs, 'sax-phrase-stochastic.wav')\nplt.show()\n" ]
[ [ "matplotlib.pyplot.autoscale", "numpy.blackman", "numpy.less", "matplotlib.pyplot.figure", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.savefig", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.plot" ] ]
neilswainston/gae
[ "00ce67b8dd25e79055f55133f7775b20476c8995" ]
[ "gae/chem/sparse/chem_train_single.py" ]
[ "'''\n(c) University of Liverpool 2020\n\nAll rights reserved.\n\n@author: neilswainston\n'''\n# pylint: disable=invalid-name\n# pylint: disable=no-member\n# pylint: disable=wrong-import-order\nfrom rdkit import Chem\nimport scipy\n\nfrom gae.tf import train_single\nimport numpy as np\nimport pandas as pd\n\n\ndef _load_data(filename):\n '''Load data.'''\n df = pd.read_csv(filename)\n smiles = df['smiles'][0]\n adj, features = _get_data(smiles)\n return adj, features\n\n\ndef _get_data(smiles):\n '''Get data from SMILES.'''\n mol = Chem.MolFromSmiles(smiles)\n\n adj = scipy.sparse.lil_matrix(\n (mol.GetNumAtoms(), mol.GetNumAtoms()), dtype=int)\n\n for bond in mol.GetBonds():\n adj[bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()] = 1\n\n features = np.array([[atom.GetAtomicNum(),\n atom.GetMass(),\n atom.GetExplicitValence(),\n atom.GetFormalCharge()]\n for atom in mol.GetAtoms()])\n\n return scipy.sparse.csr_matrix(adj), scipy.sparse.lil_matrix(features)\n\n\ndef main():\n '''main method.'''\n\n # Load data:\n filename = 'data/spectra.csv'\n adj, features = _load_data(filename)\n\n # Train:\n train_single.train(adj, features, epochs=10000)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.read_csv", "scipy.sparse.csr_matrix", "scipy.sparse.lil_matrix" ] ]
noegroup/membrane_kinetics
[ "ee2da9e076e402dc83e886aac129144d7c58a69f" ]
[ "diffusion_tensors/surface_integration.py" ]
[ "import numpy as np\n\ndef build_local_integration_grid_circle(n_quad_points, r_c):\n # Guass-Legendre quadrature on the unit disk (by KyoungJoong Kim and ManSuk Song)\n\n if n_quad_points == 1:\n\n w_1 = 3.141592653589793\n x_1 = 0.0\n\n quad_point_x = np.array([x_1]) * r_c\n\n quad_point_y = np.array([x_1]) * r_c\n\n quad_weight = np.array([w_1]) * r_c * r_c\n\n elif n_quad_points == 4:\n\n w_1 = 0.785398163397448\n x_1 = 0.5\n\n quad_point_x = np.array([x_1, -x_1, -x_1, x_1]) * r_c\n\n quad_point_y = np.array([x_1, x_1, -x_1, -x_1]) * r_c\n\n quad_weight = np.array([w_1, w_1, w_1, w_1]) * r_c * r_c\n\n elif n_quad_points == 8:\n\n w_1 = 0.732786462492640\n w_2 = 0.052611700904808\n x_1 = 0.650115167343736\n x_2 = 0.888073833977115\n\n quad_point_x = np.array([x_1, 0.0, -x_1, 0.0, x_2, -x_2, -x_2, x_2]) * r_c\n\n quad_point_y = np.array([0.0, x_1, 0.0, -x_1, x_2, x_2, -x_2, -x_2]) * r_c\n\n quad_weight = np.array([w_1, w_1, w_1, w_1, w_2, w_2, w_2, w_2]) * r_c * r_c\n\n elif n_quad_points == 12:\n\n w_1 = 0.232710566932577\n w_2 = 0.387077796006226\n w_3 = 0.165609800458645\n\n x_1 = 0.866025403784439\n x_2 = 0.322914992067400\n x_3 = 0.644171310389465\n\n quad_point_x = np.array([x_1, 0.0, -x_1, 0.0, x_2, -x_2, -x_2, x_2, x_3, -x_3, -x_3, x_3]) * r_c\n\n quad_point_y = np.array([0.0, x_1, 0.0, -x_1, x_2, x_2, -x_2, -x_2, x_3, x_3, -x_3, -x_3]) * r_c\n\n quad_weight = np.array([w_1, w_1, w_1, w_1, w_2, w_2, w_2, w_2, w_3, w_3, w_3, w_3]) * r_c * r_c\n\n elif n_quad_points == 20:\n\n w_1 = 0.071488826617391\n w_2 = 0.327176874928167\n w_3 = 0.005591341512851\n w_4 = 0.190570560169519\n\n x_1 = 0.952458896434417\n x_2 = 0.415187657878755\n x_3 = 0.834794942216211\n x_4 = 0.740334457173511\n y_4 = 0.379016937530835\n\n quad_point_x = np.array(\n [x_1, 0.0, -x_1, 0.0, x_2, 0.0, -x_2, 0.0, x_3, -x_3, -x_3, x_3, x_4, -x_4, -x_4, x_4, y_4, y_4, -y_4,\n -y_4]) * r_c\n\n quad_point_y = np.array(\n [0.0, x_1, 0.0, -x_1, 0.0, x_2, 0.0, -x_2, x_3, x_3, -x_3, -x_3, y_4, y_4, -y_4, -y_4, x_4, -x_4, -x_4,\n x_4]) * r_c\n\n quad_weight = np.array(\n [w_1, w_1, w_1, w_1, w_2, w_2, w_2, w_2, w_3, w_3, w_3, w_3, w_4, w_4, w_4, w_4, w_4, w_4, w_4,\n w_4]) * r_c * r_c\n\n elif n_quad_points == 44:\n\n x_1 = 0.252863797091293\n x_2 = 0.989746802511614\n x_3 = 0.577728928444958\n x_4 = 0.873836956645035\n x_5 = 0.689299380791136\n x_6 = 0.597614304667208\n x_7 = 0.375416824626170\n x_8 = 0.883097111318591\n y_8 = 0.365790800400663\n x_9 = 0.707438744960070\n y_9 = 0.293030722710664\n\n w_1 = 0.125290208564338\n w_2 = 0.016712625496982\n w_3 = 0.109500391126365\n w_4 = 0.066237455796397\n w_5 = 0.026102860184358\n w_6 = 0.066000934661100\n w_7 = 0.127428372681720\n w_8 = 0.042523065826681\n w_9 = 0.081539591616413\n\n quad_point_x = np.array(\n [x_1, 0.0, -x_1, 0.0, x_2, 0.0, -x_2, 0.0, x_3, 0.0, -x_3, 0.0, x_4, 0.0, -x_4, 0.0,\n x_5, -x_5, -x_5, x_5, x_6, -x_6, -x_6, x_6, x_7, -x_7, -x_7, x_7,\n x_8, -x_8, -x_8, x_8, y_8, y_8, -y_8, -y_8,\n x_9, -x_9, -x_9, x_9, y_9, y_9, -y_9, -y_9]) * r_c\n\n quad_point_y = np.array(\n [0.0, x_1, 0.0, -x_1, 0.0, x_2, 0.0, -x_2, 0.0, x_3, 0.0, -x_3, 0.0, x_4, 0.0, -x_4,\n x_5, x_5, -x_5, -x_5, x_6, x_6, -x_6, -x_6, x_7, x_7, -x_7, -x_7,\n y_8, y_8, -y_8, -y_8, x_8, -x_8, -x_8, x_8,\n y_9, y_9, -y_9, -y_9, x_9, -x_9, -x_9, x_9]) * r_c\n\n quad_weight = np.array(\n [w_1, w_1, w_1, w_1, w_2, w_2, w_2, w_2, w_3, w_3, w_3, w_3, w_4, w_4, w_4, w_4,\n w_5, w_5, w_5, w_5, w_6, w_6, w_6, w_6, w_7, w_7, w_7, w_7,\n w_8, w_8, w_8, w_8, w_8, w_8, w_8, w_8,\n w_9, w_9, w_9, w_9, w_9, w_9, w_9, w_9]) * r_c * r_c\n\n elif n_quad_points == 72:\n\n w_1 = 0.082558858859169\n x_1 = 0.204668989256100\n\n w_2 = 0.009721593541193\n x_2 = 0.992309839464756\n\n w_3 = 0.061920685878045\n x_3 = 0.740931035494388\n\n w_4 = 0.079123279187043\n x_4 = 0.477987648986077\n\n w_5 = 0.087526733002317\n x_5 = 0.306138805262459\n\n w_6 = 0.057076811471306\n x_6 = 0.524780156099700\n\n w_7 = 0.020981864256888\n x_7 = 0.921806074110042\n y_7 = 0.310920075968188\n\n w_8 = 0.015226392255721\n x_8 = 0.790235832571934\n y_8 = 0.579897645710646\n\n w_9 = 0.033136884897617\n x_9 = 0.725790566968788\n y_9 = 0.525045580895713\n\n w_10 = 0.044853730819348\n x_10 = 0.788230650371813\n y_10 = 0.290244481132460\n\n w_11 = 0.065321481701811\n x_11 = 0.584894890453686\n y_11 = 0.264317463415838\n\n w_12 = 0.024214746797802\n x_12 = 0.909637445684200\n y_12 = 0.09257113237088\n\n quad_point_x = np.array(\n [x_1, 0.0, -x_1, 0.0, x_2, 0.0, -x_2, 0.0, x_3, 0.0, -x_3, 0.0, x_4, 0.0, -x_4, 0.0,\n x_5, -x_5, -x_5, x_5, x_6, -x_6, -x_6, x_6,\n x_7, -x_7, -x_7, x_7, y_7, y_7, -y_7, -y_7,\n x_8, -x_8, -x_8, x_8, y_8, y_8, -y_8, -y_8,\n x_9, -x_9, -x_9, x_9, y_9, y_9, -y_9, -y_9,\n x_10, -x_10, -x_10, x_10, y_10, y_10, -y_10, -y_10,\n x_11, -x_11, -x_11, x_11, y_11, y_11, -y_11, -y_11,\n x_12, -x_12, -x_12, x_12, y_12, y_12, -y_12, -y_12]) * r_c\n\n quad_point_y = np.array(\n [0.0, x_1, 0.0, -x_1, 0.0, x_2, 0.0, -x_2, 0.0, x_3, 0.0, -x_3, 0.0, x_4, 0.0, -x_4,\n x_5, x_5, -x_5, -x_5, x_6, x_6, -x_6, -x_6,\n y_7, y_7, -y_7, -y_7, x_7, -x_7, -x_7, x_7,\n y_8, y_8, -y_8, -y_8, x_8, -x_8, -x_8, x_8,\n y_9, y_9, -y_9, -y_9, x_9, -x_9, -x_9, x_9,\n y_10, y_10, -y_10, -y_10, x_10, -x_10, -x_10, x_10,\n y_11, y_11, -y_11, -y_11, x_11, -x_11, -x_11, x_11,\n y_12, y_12, -y_12, -y_12, x_12, -x_12, -x_12, x_12]) * r_c\n\n quad_weight = np.array(\n [w_1, w_1, w_1, w_1, w_2, w_2, w_2, w_2, w_3, w_3, w_3, w_3, w_4, w_4, w_4, w_4,\n w_5, w_5, w_5, w_5, w_6, w_6, w_6, w_6,\n w_7, w_7, w_7, w_7, w_7, w_7, w_7, w_7,\n w_8, w_8, w_8, w_8, w_8, w_8, w_8, w_8,\n w_9, w_9, w_9, w_9, w_9, w_9, w_9, w_9,\n w_10, w_10, w_10, w_10, w_10, w_10, w_10, w_10,\n w_11, w_11, w_11, w_11, w_11, w_11, w_11, w_11,\n w_12, w_12, w_12, w_12, w_12, w_12, w_12, w_12]) * r_c * r_c\n\n else:\n\n raise ValueError(\"No set of points/weights for the choice of \" + str(n_quad_points) + \" quadrature point!\")\n\n return quad_point_x, quad_point_y, quad_weight\n" ]
[ [ "numpy.array" ] ]
cutebomb/ta
[ "2d3d292c6513f8dc30b277bffa6246475a8d27b1" ]
[ "ta/volume.py" ]
[ "\"\"\"\n.. module:: volume\n :synopsis: Volume Indicators.\n\n.. moduleauthor:: Dario Lopez Padial (Bukosabino)\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nfrom ta.utils import IndicatorMixin, ema\n\n\nclass AccDistIndexIndicator(IndicatorMixin):\n \"\"\"Accumulation/Distribution Index (ADI)\n\n Acting as leading indicator of price movements.\n\n https://school.stockcharts.com/doku.php?id=technical_indicators:accumulation_distribution_line\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, volume: pd.Series, fillna: bool = False):\n self._high = high\n self._low = low\n self._close = close\n self._volume = volume\n self._fillna = fillna\n self._run()\n\n def _run(self):\n clv = ((self._close - self._low) - (self._high - self._close)) / (self._high - self._low)\n clv = clv.fillna(0.0) # float division by zero\n ad = clv * self._volume\n self._ad = ad.cumsum()\n\n def acc_dist_index(self) -> pd.Series:\n \"\"\"Accumulation/Distribution Index (ADI)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n ad = self._check_fillna(self._ad, value=0)\n return pd.Series(ad, name='adi')\n\n\nclass OnBalanceVolumeIndicator(IndicatorMixin):\n \"\"\"On-balance volume (OBV)\n\n It relates price and volume in the stock market. OBV is based on a\n cumulative total volume.\n\n https://en.wikipedia.org/wiki/On-balance_volume\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, volume: pd.Series, fillna: bool = False):\n self._close = close\n self._volume = volume\n self._fillna = fillna\n self._run()\n\n def _run(self):\n obv = np.where(self._close < self._close.shift(1), -self._volume, self._volume)\n self._obv = pd.Series(obv, index=self._close.index).cumsum()\n\n def on_balance_volume(self) -> pd.Series:\n \"\"\"On-balance volume (OBV)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n obv = self._check_fillna(self._obv, value=0)\n return pd.Series(obv, name='obv')\n\n\nclass ChaikinMoneyFlowIndicator(IndicatorMixin):\n \"\"\"Chaikin Money Flow (CMF)\n\n It measures the amount of Money Flow Volume over a specific period.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow_cmf\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series,\n volume: pd.Series, n: int = 20, fillna: bool = False):\n self._high = high\n self._low = low\n self._close = close\n self._volume = volume\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n mfv = ((self._close - self._low) - (self._high - self._close)) / (self._high - self._low)\n mfv = mfv.fillna(0.0) # float division by zero\n mfv *= self._volume\n self._cmf = mfv.rolling(self._n, min_periods=0).sum() / self._volume.rolling(self._n, min_periods=0).sum()\n\n def chaikin_money_flow(self) -> pd.Series:\n \"\"\"Chaikin Money Flow (CMF)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n cmf = self._check_fillna(self._cmf, value=0)\n return pd.Series(cmf, name='cmf')\n\n\nclass ForceIndexIndicator(IndicatorMixin):\n \"\"\"Force Index (FI)\n\n It illustrates how strong the actual buying or selling pressure is. High\n positive values mean there is a strong rising trend, and low values signify\n a strong downward trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:force_index\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, volume: pd.Series, n: int = 13, fillna: bool = False):\n self._close = close\n self._volume = volume\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n fi = (self._close - self._close.shift(1)) * self._volume\n self._fi = ema(fi, self._n, fillna=self._fillna)\n\n def force_index(self) -> pd.Series:\n \"\"\"Force Index (FI)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n fi = self._check_fillna(self._fi, value=0)\n return pd.Series(fi, name=f'fi_{self._n}')\n\n\nclass EaseOfMovementIndicator(IndicatorMixin):\n \"\"\"Ease of movement (EoM, EMV)\n\n It relate an asset's price change to its volume and is particularly useful\n for assessing the strength of a trend.\n\n https://en.wikipedia.org/wiki/Ease_of_movement\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n volume(pandas.Series): dataset 'Volume' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, high: pd.Series, low: pd.Series, volume: pd.Series, n: int = 14, fillna: bool = False):\n self._high = high\n self._low = low\n self._volume = volume\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n self._emv = (self._high.diff(1) + self._low.diff(1)) * (self._high - self._low) / (2 * self._volume)\n self._emv *= 100000000\n\n def ease_of_movement(self) -> pd.Series:\n \"\"\"Ease of movement (EoM, EMV)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n emv = self._check_fillna(self._emv, value=0)\n return pd.Series(emv, name=f'eom_{self._n}')\n\n def sma_ease_of_movement(self) -> pd.Series:\n \"\"\"Signal Ease of movement (EoM, EMV)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n emv = self._emv.rolling(self._n, min_periods=0).mean()\n emv = self._check_fillna(emv, value=0)\n return pd.Series(emv, name=f'sma_eom_{self._n}')\n\n\nclass VolumePriceTrendIndicator(IndicatorMixin):\n \"\"\"Volume-price trend (VPT)\n\n Is based on a running cumulative volume that adds or substracts a multiple\n of the percentage change in share price trend and current volume, depending\n upon the investment's upward or downward movements.\n\n https://en.wikipedia.org/wiki/Volume%E2%80%93price_trend\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, volume: pd.Series, fillna: bool = False):\n self._close = close\n self._volume = volume\n self._fillna = fillna\n self._run()\n\n def _run(self):\n vpt = (self._volume * ((self._close - self._close.shift(1, fill_value=self._close.mean()))\n / self._close.shift(1, fill_value=self._close.mean())))\n self._vpt = vpt.shift(1, fill_value=vpt.mean()) + vpt\n\n def volume_price_trend(self) -> pd.Series:\n \"\"\"Volume-price trend (VPT)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n vpt = self._check_fillna(self._vpt, value=0)\n return pd.Series(vpt, name='vpt')\n\n\nclass NegativeVolumeIndexIndicator(IndicatorMixin):\n \"\"\"Negative Volume Index (NVI)\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:negative_volume_inde\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values with 1000.\n \"\"\"\n\n def __init__(self, close: pd.Series, volume: pd.Series, fillna: bool = False):\n self._close = close\n self._volume = volume\n self._fillna = fillna\n self._run()\n\n def _run(self):\n price_change = self._close.pct_change()\n vol_decrease = (self._volume.shift(1) > self._volume)\n self._nvi = pd.Series(data=np.nan, index=self._close.index, dtype='float64', name='nvi')\n self._nvi.iloc[0] = 1000\n for i in range(1, len(self._nvi)):\n if vol_decrease.iloc[i]:\n self._nvi.iloc[i] = self._nvi.iloc[i - 1] * (1.0 + price_change.iloc[i])\n else:\n self._nvi.iloc[i] = self._nvi.iloc[i - 1]\n\n def negative_volume_index(self) -> pd.Series:\n \"\"\"Negative Volume Index (NVI)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n # IDEA: There shouldn't be any na; might be better to throw exception\n nvi = self._check_fillna(self._nvi, value=1000)\n return pd.Series(nvi, name='nvi')\n\n\ndef acc_dist_index(high, low, close, volume, fillna=False):\n \"\"\"Accumulation/Distribution Index (ADI)\n\n Acting as leading indicator of price movements.\n\n https://en.wikipedia.org/wiki/Accumulation/distribution_index\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return AccDistIndexIndicator(high=high, low=low, close=close, volume=volume, fillna=fillna).acc_dist_index()\n\n\ndef on_balance_volume(close, volume, fillna=False):\n \"\"\"On-balance volume (OBV)\n\n It relates price and volume in the stock market. OBV is based on a\n cumulative total volume.\n\n https://en.wikipedia.org/wiki/On-balance_volume\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return OnBalanceVolumeIndicator(close=close, volume=volume, fillna=fillna).on_balance_volume()\n\n\ndef chaikin_money_flow(high, low, close, volume, n=20, fillna=False):\n \"\"\"Chaikin Money Flow (CMF)\n\n It measures the amount of Money Flow Volume over a specific period.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow_cmf\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return ChaikinMoneyFlowIndicator(\n high=high, low=low, close=close, volume=volume, n=n, fillna=fillna).chaikin_money_flow()\n\n\ndef force_index(close, volume, n=13, fillna=False):\n \"\"\"Force Index (FI)\n\n It illustrates how strong the actual buying or selling pressure is. High\n positive values mean there is a strong rising trend, and low values signify\n a strong downward trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:force_index\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return ForceIndexIndicator(close=close, volume=volume, n=n, fillna=fillna).force_index()\n\n\ndef ease_of_movement(high, low, volume, n=14, fillna=False):\n \"\"\"Ease of movement (EoM, EMV)\n\n It relate an asset's price change to its volume and is particularly useful\n for assessing the strength of a trend.\n\n https://en.wikipedia.org/wiki/Ease_of_movement\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n volume(pandas.Series): dataset 'Volume' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return EaseOfMovementIndicator(\n high=high, low=low, volume=volume, n=n, fillna=fillna).ease_of_movement()\n\n\ndef sma_ease_of_movement(high, low, volume, n=14, fillna=False):\n \"\"\"Ease of movement (EoM, EMV)\n\n It relate an asset's price change to its volume and is particularly useful\n for assessing the strength of a trend.\n\n https://en.wikipedia.org/wiki/Ease_of_movement\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n volume(pandas.Series): dataset 'Volume' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return EaseOfMovementIndicator(\n high=high, low=low, volume=volume, n=n, fillna=fillna).sma_ease_of_movement()\n\n\ndef volume_price_trend(close, volume, fillna=False):\n \"\"\"Volume-price trend (VPT)\n\n Is based on a running cumulative volume that adds or substracts a multiple\n of the percentage change in share price trend and current volume, depending\n upon the investment's upward or downward movements.\n\n https://en.wikipedia.org/wiki/Volume%E2%80%93price_trend\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return VolumePriceTrendIndicator(close=close, volume=volume, fillna=fillna).volume_price_trend()\n\n\ndef negative_volume_index(close, volume, fillna=False):\n \"\"\"Negative Volume Index (NVI)\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:negative_volume_inde\n\n The Negative Volume Index (NVI) is a cumulative indicator that uses the\n change in volume to decide when the smart money is active. Paul Dysart\n first developed this indicator in the 1930s. [...] Dysart's Negative Volume\n Index works under the assumption that the smart money is active on days\n when volume decreases and the not-so-smart money is active on days when\n volume increases.\n\n The cumulative NVI line was unchanged when volume increased from one\n period to the other. In other words, nothing was done. Norman Fosback, of\n Stock Market Logic, adjusted the indicator by substituting the percentage\n price change for Net Advances.\n\n This implementation is the Fosback version.\n\n If today's volume is less than yesterday's volume then:\n nvi(t) = nvi(t-1) * ( 1 + (close(t) - close(t-1)) / close(t-1) )\n Else\n nvi(t) = nvi(t-1)\n\n Please note: the \"stockcharts.com\" example calculation just adds the\n percentange change of price to previous NVI when volumes decline; other\n sources indicate that the same percentage of the previous NVI value should\n be added, which is what is implemented here.\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n volume(pandas.Series): dataset 'Volume' column.\n fillna(bool): if True, fill nan values with 1000.\n\n Returns:\n pandas.Series: New feature generated.\n\n See also:\n https://en.wikipedia.org/wiki/Negative_volume_index\n \"\"\"\n return NegativeVolumeIndexIndicator(close=close, volume=volume, fillna=fillna).negative_volume_index()\n\n\n# TODO\ndef put_call_ratio():\n \"\"\"Put/Call ratio (PCR)\n https://en.wikipedia.org/wiki/Put/call_ratio\n \"\"\"\n # TODO\n pass\n" ]
[ [ "pandas.Series" ] ]
kekeblom/Doubly-Stochastic-DGP
[ "64e40a8c22514c9b7917f0c6b79ca11b2bd67ea3" ]
[ "doubly_stochastic_dgp/layers.py" ]
[ "# Copyright 2017 Hugh Salimbeni\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 tensorflow as tf\nimport numpy as np\n\nimport gpflow\nfrom gpflow.params import Parameter, Parameterized\nfrom gpflow.conditionals import conditional, Kuu\nfrom gpflow.features import InducingPoints\nfrom gpflow.kullback_leiblers import gauss_kl\nfrom gpflow.priors import Gaussian as Gaussian_prior\nfrom gpflow import transforms\nfrom gpflow import settings\nfrom gpflow.models.gplvm import BayesianGPLVM\nfrom gpflow.expectations import expectation\nfrom gpflow.probability_distributions import DiagonalGaussian\nfrom gpflow.logdensities import multivariate_normal\nfrom gpflow import conditionals\n\n\n\nfrom doubly_stochastic_dgp.utils import reparameterize\n\n\nclass Layer(Parameterized):\n def __init__(self, input_prop_dim=None, **kwargs):\n \"\"\"\n A base class for GP layers. Basic functionality for multisample conditional, and input propagation\n :param input_prop_dim: the first dimensions of X to propagate. If None (or zero) then no input prop\n :param kwargs:\n \"\"\"\n Parameterized.__init__(self, **kwargs)\n self.input_prop_dim = input_prop_dim\n\n def conditional_ND(self, X, full_cov=False):\n raise NotImplementedError\n\n def KL(self):\n return tf.cast(0., dtype=settings.float_type)\n\n def conditional_SND(self, X, full_cov=False):\n \"\"\"\n A multisample conditional, where X is shape (S,N,D_out), independent over samples S\n\n if full_cov is True\n mean is (S,N,D_out), var is (S,N,N,D_out)\n\n if full_cov is False\n mean and var are both (S,N,D_out)\n\n :param X: The input locations (S,N,D_in)\n :param full_cov: Whether to calculate full covariance or just diagonal\n :return: mean (S,N,D_out), var (S,N,D_out or S,N,N,D_out)\n \"\"\"\n if full_cov is True:\n f = lambda a: self.conditional_ND(a, full_cov=full_cov)\n mean, var = tf.map_fn(f, X, dtype=(settings.float_type, settings.float_type))\n return tf.stack(mean), tf.stack(var)\n else:\n X_shape = tf.shape(X)\n S, N, D = X_shape[0], X_shape[1], X_shape[2]\n X_flat = tf.reshape(X, [S * N, D])\n mean, var = self.conditional_ND(X_flat)\n return [tf.reshape(m, [S, N, self.num_outputs]) for m in [mean, var]]\n\n def sample_from_conditional(self, X, z=None, full_cov=False):\n \"\"\"\n Calculates self.conditional and also draws a sample, adding input propagation if necessary\n\n If z=None then the tensorflow random_normal function is used to generate the\n N(0, 1) samples, otherwise z are used for the whitened sample points\n\n :param X: Input locations (S,N,D_in)\n :param full_cov: Whether to compute correlations between outputs\n :param z: None, or the sampled points in whitened representation\n :return: mean (S,N,D), var (S,N,N,D or S,N,D), samples (S,N,D)\n \"\"\"\n mean, var = self.conditional_SND(X, full_cov=full_cov)\n\n # set shapes\n S = tf.shape(X)[0]\n N = tf.shape(X)[1]\n D = self.num_outputs\n\n mean = tf.reshape(mean, (S, N, D))\n if full_cov:\n var = tf.reshape(var, (S, N, N, D))\n else:\n var = tf.reshape(var, (S, N, D))\n\n if z is None:\n z = tf.random_normal(tf.shape(mean), dtype=settings.float_type)\n samples = reparameterize(mean, var, z, full_cov=full_cov)\n\n if self.input_prop_dim:\n shape = [tf.shape(X)[0], tf.shape(X)[1], self.input_prop_dim]\n X_prop = tf.reshape(X[:, :, :self.input_prop_dim], shape)\n\n samples = tf.concat([X_prop, samples], 2)\n mean = tf.concat([X_prop, mean], 2)\n\n if full_cov:\n shape = (tf.shape(X)[0], tf.shape(X)[1], tf.shape(X)[1], tf.shape(var)[3])\n zeros = tf.zeros(shape, dtype=settings.float_type)\n var = tf.concat([zeros, var], 3)\n else:\n var = tf.concat([tf.zeros_like(X_prop), var], 2)\n\n return samples, mean, var\n\n\nclass SVGP_Layer(Layer):\n def __init__(self, kern, num_outputs, mean_function,\n Z=None,\n feature=None,\n white=False, input_prop_dim=None,\n q_mu=None,\n q_sqrt=None, **kwargs):\n \"\"\"\n A sparse variational GP layer in whitened representation. This layer holds the kernel,\n variational parameters, inducing points and mean function.\n\n The underlying model at inputs X is\n f = Lv + mean_function(X), where v \\sim N(0, I) and LL^T = kern.K(X)\n\n The variational distribution over the inducing points is\n q(v) = N(q_mu, q_sqrt q_sqrt^T)\n\n The layer holds D_out independent GPs with the same kernel and inducing points.\n\n :param kern: The kernel for the layer (input_dim = D_in)\n :param Z: Inducing points (M, D_in)\n :param num_outputs: The number of GP outputs (q_mu is shape (M, num_outputs))\n :param mean_function: The mean function\n :return:\n \"\"\"\n Layer.__init__(self, input_prop_dim, **kwargs)\n if feature is None:\n feature = InducingPoints(Z)\n\n self.num_inducing = len(feature)\n\n self.feature = feature\n self.kern = kern\n self.mean_function = mean_function\n\n self.num_outputs = num_outputs\n self.white = white\n\n if q_mu is None:\n q_mu = np.zeros((self.num_inducing, num_outputs), dtype=settings.float_type)\n self.q_mu = Parameter(q_mu)\n\n if q_sqrt is None:\n if not self.white: # initialize to prior\n with gpflow.params_as_tensors_for(feature):\n Ku = conditionals.Kuu(feature, self.kern, jitter=settings.jitter)\n Lu = tf.linalg.cholesky(Ku)\n Lu = self.enquire_session().run(Lu)\n q_sqrt = np.tile(Lu[None, :, :], [num_outputs, 1, 1])\n else:\n q_sqrt = np.tile(np.eye(self.num_inducing, dtype=settings.float_type)[None, :, :], [num_outputs, 1, 1])\n\n transform = transforms.LowerTriangular(self.num_inducing, num_matrices=num_outputs)\n self.q_sqrt = Parameter(q_sqrt, transform=transform)\n\n self.needs_build_cholesky = True\n\n def build_cholesky_if_needed(self):\n # make sure we only compute this once\n if self.needs_build_cholesky:\n self.Ku = conditionals.Kuu(self.feature, self.kern, jitter=settings.jitter)\n self.Lu = tf.cholesky(self.Ku)\n self.Ku_tiled = tf.tile(self.Ku[None, :, :], [self.num_outputs, 1, 1])\n self.Lu_tiled = tf.tile(self.Lu[None, :, :], [self.num_outputs, 1, 1])\n self.needs_build_cholesky = False\n\n\n def conditional_ND(self, X, full_cov=False):\n self.build_cholesky_if_needed()\n\n Kuf = conditionals.Kuf(self.feature, self.kern, X)\n\n A = tf.matrix_triangular_solve(self.Lu, Kuf, lower=True)\n if not self.white:\n A = tf.matrix_triangular_solve(tf.transpose(self.Lu), A, lower=False)\n\n mean = tf.matmul(A, self.q_mu, transpose_a=True)\n\n A_tiled = tf.tile(A[None, :, :], [self.num_outputs, 1, 1])\n I = tf.eye(self.num_inducing, dtype=settings.float_type)[None, :, :]\n\n if self.white:\n SK = -I\n else:\n SK = -self.Ku_tiled\n\n if self.q_sqrt is not None:\n SK += tf.matmul(self.q_sqrt, self.q_sqrt, transpose_b=True)\n\n\n B = tf.matmul(SK, A_tiled)\n\n if full_cov:\n # (num_latent, num_X, num_X)\n delta_cov = tf.matmul(A_tiled, B, transpose_a=True)\n Kff = self.kern.K(X)\n else:\n # (num_latent, num_X)\n delta_cov = tf.reduce_sum(A_tiled * B, 1)\n Kff = self.kern.Kdiag(X)\n\n # either (1, num_X) + (num_latent, num_X) or (1, num_X, num_X) + (num_latent, num_X, num_X)\n var = tf.expand_dims(Kff, 0) + delta_cov\n var = tf.transpose(var)\n\n return mean + self.mean_function(X), var\n\n def KL(self):\n \"\"\"\n The KL divergence from the variational distribution to the prior\n\n :return: KL divergence from N(q_mu, q_sqrt) to N(0, I), independently for each GP\n \"\"\"\n # if self.white:\n # return gauss_kl(self.q_mu, self.q_sqrt)\n # else:\n # return gauss_kl(self.q_mu, self.q_sqrt, self.Ku)\n\n self.build_cholesky_if_needed()\n\n KL = -0.5 * self.num_outputs * self.num_inducing\n KL -= 0.5 * tf.reduce_sum(tf.log(tf.matrix_diag_part(self.q_sqrt) ** 2))\n\n if not self.white:\n KL += tf.reduce_sum(tf.log(tf.matrix_diag_part(self.Lu))) * self.num_outputs\n KL += 0.5 * tf.reduce_sum(tf.square(tf.matrix_triangular_solve(self.Lu_tiled, self.q_sqrt, lower=True)))\n Kinv_m = tf.cholesky_solve(self.Lu, self.q_mu)\n KL += 0.5 * tf.reduce_sum(self.q_mu * Kinv_m)\n else:\n KL += 0.5 * tf.reduce_sum(tf.square(self.q_sqrt))\n KL += 0.5 * tf.reduce_sum(self.q_mu**2)\n\n return KL\n\n\nclass SGPMC_Layer(SVGP_Layer):\n def __init__(self, *args, **kwargs):\n \"\"\"\n A sparse layer for sampling over the inducing point values\n \"\"\"\n SVGP_Layer.__init__(self, *args, **kwargs)\n self.q_mu.prior = Gaussian_prior(0., 1.)\n del self.q_sqrt\n self.q_sqrt = None\n\n def KL(self):\n return tf.cast(0., dtype=settings.float_type)\n\n\nclass GPMC_Layer(Layer):\n def __init__(self, kern, X, num_outputs, mean_function, input_prop_dim=None, **kwargs):\n \"\"\"\n A dense layer with fixed inputs. NB X does not change here, and must be the inputs. Minibatches not possible\n \"\"\"\n Layer.__init__(self, input_prop_dim, **kwargs)\n self.num_data = X.shape[0]\n q_mu = np.zeros((self.num_data, num_outputs))\n self.q_mu = Parameter(q_mu)\n self.q_mu.prior = Gaussian_prior(0., 1.)\n self.kern = kern\n self.mean_function = mean_function\n\n self.num_outputs = num_outputs\n\n Ku = self.kern.compute_K_symm(X) + np.eye(self.num_data) * settings.jitter\n self.Lu = tf.constant(np.linalg.cholesky(Ku))\n self.X = tf.constant(X)\n\n def build_latents(self):\n f = tf.matmul(self.Lu, self.q_mu)\n f += self.mean_function(self.X)\n if self.input_prop_dim:\n f = tf.concat([self.X[:, :self.input_prop_dim], f], 1)\n return f\n\n def conditional_ND(self, Xnew, full_cov=False):\n mu, var = conditional(Xnew, self.X, self.kern, self.q_mu,\n full_cov=full_cov,\n q_sqrt=None, white=True)\n return mu + self.mean_function(Xnew), var\n\n\nclass Collapsed_Layer(Layer):\n \"\"\"\n Extra functions for a collapsed layer\n \"\"\"\n def set_data(self, X_mean, X_var, Y, lik_variance):\n self._X_mean = X_mean\n self._X_var = X_var\n self._Y = Y\n self._lik_variance = lik_variance\n\n def build_likelihood(self):\n raise NotImplementedError\n\n\nclass GPR_Layer(Collapsed_Layer):\n def __init__(self, kern, mean_function, num_outputs, **kwargs):\n \"\"\"\n A dense GP layer with a Gaussian likelihood, where the GP is integrated out\n \"\"\"\n Collapsed_Layer.__init__(self, **kwargs)\n self.kern = kern\n self.mean_function = mean_function\n self.num_outputs = num_outputs\n\n def conditional_ND(self, Xnew, full_cov=False):\n ## modified from GPR\n Kx = self.kern.K(self._X_mean, Xnew)\n K = self.kern.K(self._X_mean) + tf.eye(tf.shape(self._X_mean)[0], dtype=settings.float_type) * self._lik_variance\n L = tf.cholesky(K)\n A = tf.matrix_triangular_solve(L, Kx, lower=True)\n V = tf.matrix_triangular_solve(L, self._Y - self.mean_function(self._X_mean))\n fmean = tf.matmul(A, V, transpose_a=True) + self.mean_function(Xnew)\n if full_cov:\n fvar = self.kern.K(Xnew) - tf.matmul(A, A, transpose_a=True)\n shape = tf.stack([1, 1, tf.shape(self._Y)[1]])\n fvar = tf.tile(tf.expand_dims(fvar, 2), shape)\n else:\n fvar = self.kern.Kdiag(Xnew) - tf.reduce_sum(tf.square(A), 0)\n fvar = tf.tile(tf.reshape(fvar, (-1, 1)), [1, tf.shape(self._Y)[1]])\n return fmean, fvar\n\n def build_likelihood(self):\n ## modified from GPR\n K = self.kern.K(self._X_mean) + tf.eye(tf.shape(self._X_mean)[0], dtype=settings.float_type) * self._lik_variance\n L = tf.cholesky(K)\n m = self.mean_function(self._X_mean)\n return tf.reduce_sum(multivariate_normal(self._Y, m, L))\n\n\nclass SGPR_Layer(Collapsed_Layer):\n def __init__(self, kern, Z, num_outputs, mean_function, **kwargs):\n \"\"\"\n A sparse variational GP layer with a Gaussian likelihood, where the\n GP is integrated out\n\n :kern: The kernel for the layer (input_dim = D_in)\n :param Z: Inducing points (M, D_in)\n :param mean_function: The mean function\n :return:\n \"\"\"\n\n Collapsed_Layer.__init__(self, **kwargs)\n self.feature = InducingPoints(Z)\n self.kern = kern\n self.mean_function = mean_function\n self.num_outputs = num_outputs\n\n def conditional_ND(self, Xnew, full_cov=False):\n return gplvm_build_predict(self, Xnew, self._X_mean, self._X_var, self._Y, self._lik_variance, full_cov=full_cov)\n\n def build_likelihood(self):\n return gplvm_build_likelihood(self, self._X_mean, self._X_var, self._Y, self._lik_variance)\n\n\n################## From gpflow (with KL removed)\ndef gplvm_build_likelihood(self, X_mean, X_var, Y, variance):\n if X_var is None:\n # SGPR\n num_inducing = len(self.feature)\n num_data = tf.cast(tf.shape(Y)[0], settings.float_type)\n output_dim = tf.cast(tf.shape(Y)[1], settings.float_type)\n\n err = Y - self.mean_function(X_mean)\n Kdiag = self.kern.Kdiag(X_mean)\n Kuf = conditionals.Kuf(self.feature, self.kern, X_mean)\n Kuu = conditionals.Kuu(self.feature, self.kern, jitter=settings.numerics.jitter_level)\n L = tf.cholesky(Kuu)\n sigma = tf.sqrt(variance)\n\n # Compute intermediate matrices\n A = tf.matrix_triangular_solve(L, Kuf, lower=True) / sigma\n AAT = tf.matmul(A, A, transpose_b=True)\n B = AAT + tf.eye(num_inducing, dtype=settings.float_type)\n LB = tf.cholesky(B)\n Aerr = tf.matmul(A, err)\n c = tf.matrix_triangular_solve(LB, Aerr, lower=True) / sigma\n\n # compute log marginal bound\n bound = -0.5 * num_data * output_dim * np.log(2 * np.pi)\n bound += tf.negative(output_dim) * tf.reduce_sum(tf.log(tf.matrix_diag_part(LB)))\n bound -= 0.5 * num_data * output_dim * tf.log(variance)\n bound += -0.5 * tf.reduce_sum(tf.square(err)) / variance\n bound += 0.5 * tf.reduce_sum(tf.square(c))\n bound += -0.5 * output_dim * tf.reduce_sum(Kdiag) / variance\n bound += 0.5 * output_dim * tf.reduce_sum(tf.matrix_diag_part(AAT))\n\n return bound\n\n\n else:\n\n X_cov = tf.matrix_diag(X_var)\n pX = DiagonalGaussian(X_mean, X_var)\n num_inducing = len(self.feature)\n if hasattr(self.kern, 'X_input_dim'):\n psi0 = tf.reduce_sum(self.kern.eKdiag(X_mean, X_cov))\n psi1 = self.kern.eKxz(self.feature.Z, X_mean, X_cov)\n psi2 = tf.reduce_sum(self.kern.eKzxKxz(self.feature.Z, X_mean, X_cov), 0)\n else:\n psi0 = tf.reduce_sum(expectation(pX, self.kern))\n psi1 = expectation(pX, (self.kern, self.feature))\n psi2 = tf.reduce_sum(expectation(pX, (self.kern, self.feature), (self.kern, self.feature)), axis=0)\n Kuu = conditionals.Kuu(self.feature, self.kern, jitter=settings.numerics.jitter_level)\n L = tf.cholesky(Kuu)\n sigma2 = variance\n sigma = tf.sqrt(sigma2)\n\n # Compute intermediate matrices\n A = tf.matrix_triangular_solve(L, tf.transpose(psi1), lower=True) / sigma\n tmp = tf.matrix_triangular_solve(L, psi2, lower=True)\n AAT = tf.matrix_triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2\n B = AAT + tf.eye(num_inducing, dtype=settings.float_type)\n LB = tf.cholesky(B)\n log_det_B = 2. * tf.reduce_sum(tf.log(tf.matrix_diag_part(LB)))\n c = tf.matrix_triangular_solve(LB, tf.matmul(A, Y), lower=True) / sigma\n\n # KL[q(x) || p(x)]\n # dX_var = self.X_var if len(self.X_var.get_shape()) == 2 else tf.matrix_diag_part(self.X_var)\n # NQ = tf.cast(tf.size(self.X_mean), settings.float_type)\n D = tf.cast(tf.shape(Y)[1], settings.float_type)\n # KL = -0.5 * tf.reduce_sum(tf.log(dX_var)) \\\n # + 0.5 * tf.reduce_sum(tf.log(self.X_prior_var)) \\\n # - 0.5 * NQ \\\n # + 0.5 * tf.reduce_sum((tf.square(self.X_mean - self.X_prior_mean) + dX_var) / self.X_prior_var)\n\n # compute log marginal bound\n ND = tf.cast(tf.size(Y), settings.float_type)\n bound = -0.5 * ND * tf.log(2 * np.pi * sigma2)\n bound += -0.5 * D * log_det_B\n bound += -0.5 * tf.reduce_sum(tf.square(Y)) / sigma2\n bound += 0.5 * tf.reduce_sum(tf.square(c))\n bound += -0.5 * D * (tf.reduce_sum(psi0) / sigma2 -\n tf.reduce_sum(tf.matrix_diag_part(AAT)))\n # bound -= KL # don't need this term\n return bound\n\n############# Exactly from gpflow\ndef gplvm_build_predict(self, Xnew, X_mean, X_var, Y, variance, full_cov=False):\n if X_var is None:\n # SGPR\n num_inducing = len(self.feature)\n err = Y - self.mean_function(X_mean)\n Kuf = conditionals.Kuf(self.feature, self.kern, X_mean)\n Kuu = conditionals.Kuu(self.feature, self.kern, jitter=settings.numerics.jitter_level)\n Kus = conditionals.Kuf(self.feature, self.kern, Xnew)\n sigma = tf.sqrt(variance)\n L = tf.cholesky(Kuu)\n A = tf.matrix_triangular_solve(L, Kuf, lower=True) / sigma\n B = tf.matmul(A, A, transpose_b=True) + tf.eye(num_inducing, dtype=settings.float_type)\n LB = tf.cholesky(B)\n Aerr = tf.matmul(A, err)\n c = tf.matrix_triangular_solve(LB, Aerr, lower=True) / sigma\n tmp1 = tf.matrix_triangular_solve(L, Kus, lower=True)\n tmp2 = tf.matrix_triangular_solve(LB, tmp1, lower=True)\n mean = tf.matmul(tmp2, c, transpose_a=True)\n if full_cov:\n var = self.kern.K(Xnew) + tf.matmul(tmp2, tmp2, transpose_a=True) \\\n - tf.matmul(tmp1, tmp1, transpose_a=True)\n shape = tf.stack([1, 1, tf.shape(Y)[1]])\n var = tf.tile(tf.expand_dims(var, 2), shape)\n else:\n var = self.kern.Kdiag(Xnew) + tf.reduce_sum(tf.square(tmp2), 0) \\\n - tf.reduce_sum(tf.square(tmp1), 0)\n shape = tf.stack([1, tf.shape(Y)[1]])\n var = tf.tile(tf.expand_dims(var, 1), shape)\n return mean + self.mean_function(Xnew), var\n\n else:\n # gplvm\n pX = DiagonalGaussian(X_mean, X_var)\n num_inducing = len(self.feature)\n\n X_cov = tf.matrix_diag(X_var)\n\n if hasattr(self.kern, 'X_input_dim'):\n psi1 = self.kern.eKxz(self.feature.Z, X_mean, X_cov)\n psi2 = tf.reduce_sum(self.kern.eKzxKxz(self.feature.Z, X_mean, X_cov), 0)\n else:\n psi1 = expectation(pX, (self.kern, self.feature))\n psi2 = tf.reduce_sum(expectation(pX, (self.kern, self.feature), (self.kern, self.feature)), axis=0)\n\n Kuu = conditionals.Kuu(self.feature, self.kern, jitter=settings.numerics.jitter_level)\n Kus = conditionals.Kuf(self.feature, self.kern, Xnew)\n sigma2 = variance\n sigma = tf.sqrt(sigma2)\n L = tf.cholesky(Kuu)\n\n A = tf.matrix_triangular_solve(L, tf.transpose(psi1), lower=True) / sigma\n tmp = tf.matrix_triangular_solve(L, psi2, lower=True)\n AAT = tf.matrix_triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2\n B = AAT + tf.eye(num_inducing, dtype=settings.float_type)\n LB = tf.cholesky(B)\n c = tf.matrix_triangular_solve(LB, tf.matmul(A, Y), lower=True) / sigma\n tmp1 = tf.matrix_triangular_solve(L, Kus, lower=True)\n tmp2 = tf.matrix_triangular_solve(LB, tmp1, lower=True)\n mean = tf.matmul(tmp2, c, transpose_a=True)\n if full_cov:\n var = self.kern.K(Xnew) + tf.matmul(tmp2, tmp2, transpose_a=True) \\\n - tf.matmul(tmp1, tmp1, transpose_a=True)\n shape = tf.stack([1, 1, tf.shape(Y)[1]])\n var = tf.tile(tf.expand_dims(var, 2), shape)\n else:\n var = self.kern.Kdiag(Xnew) + tf.reduce_sum(tf.square(tmp2), 0) \\\n - tf.reduce_sum(tf.square(tmp1), 0)\n shape = tf.stack([1, tf.shape(Y)[1]])\n var = tf.tile(tf.expand_dims(var, 1), shape)\n return mean + self.mean_function(Xnew), var\n" ]
[ [ "tensorflow.reshape", "tensorflow.eye", "tensorflow.matmul", "numpy.log", "tensorflow.concat", "tensorflow.reduce_sum", "tensorflow.cholesky_solve", "tensorflow.constant", "tensorflow.transpose", "numpy.eye", "numpy.tile", "tensorflow.matrix_diag", "tensorflow.shape", "numpy.zeros", "tensorflow.stack", "tensorflow.expand_dims", "tensorflow.zeros_like", "tensorflow.cholesky", "tensorflow.cast", "numpy.linalg.cholesky", "tensorflow.tile", "tensorflow.linalg.cholesky", "tensorflow.size", "tensorflow.negative", "tensorflow.zeros", "tensorflow.matrix_diag_part", "tensorflow.map_fn", "tensorflow.matrix_triangular_solve", "tensorflow.sqrt", "tensorflow.square", "tensorflow.log" ] ]
jinsoo9595/LeNet_5-pytorch
[ "188cdeaf81bdd259f8a0d4686ffbaf5210ae5ce2" ]
[ "lenet.py" ]
[ "import torch.nn as nn\r\nfrom collections import OrderedDict\r\n\r\n\r\nclass C1(nn.Module):\r\n def __init__(self):\r\n super(C1, self).__init__()\r\n\r\n self.c1 = nn.Sequential(OrderedDict([\r\n ('c1', nn.Conv2d(1, 6, kernel_size=(5, 5))),\r\n ('relu1', nn.ReLU()),\r\n ('s2', nn.MaxPool2d(kernel_size=(2, 2), stride=2))\r\n ]))\r\n\r\n def forward(self, img):\r\n output = self.c1(img)\r\n return output\r\n\r\n\r\nclass C3(nn.Module):\r\n def __init__(self):\r\n super(C3, self).__init__()\r\n\r\n self.c3 = nn.Sequential(OrderedDict([\r\n ('c3', nn.Conv2d(6, 16, kernel_size=(5, 5))),\r\n ('relu2', nn.ReLU()),\r\n ('s4', nn.MaxPool2d(kernel_size=(2, 2), stride=2))\r\n ]))\r\n\r\n def forward(self, img):\r\n output = self.c3(img)\r\n return output\r\n\r\n\r\nclass C5(nn.Module):\r\n def __init__(self):\r\n super(C5, self).__init__()\r\n\r\n self.c5 = nn.Sequential(OrderedDict([\r\n ('c5', nn.Conv2d(16, 120, kernel_size=(5, 5))),\r\n ('relu3', nn.ReLU())\r\n ]))\r\n\r\n def forward(self, img):\r\n output = self.c5(img)\r\n return output\r\n\r\n\r\nclass F6(nn.Module):\r\n def __init__(self):\r\n super(F6, self).__init__()\r\n \r\n self.f6 = nn.Sequential(OrderedDict([\r\n ('f6', nn.Linear(120, 84)),\r\n ('relu4', nn.ReLU())\r\n ]))\r\n \r\n def forward(self, img):\r\n output = self.f6(img)\r\n return output\r\n \r\n \r\nclass FCoutput(nn.Module):\r\n def __init__(self):\r\n super(FCoutput, self).__init__()\r\n\r\n self.fcoutput = nn.Sequential(OrderedDict([\r\n ('fcoutput7', nn.Linear(84, 10)),\r\n ('sig1', nn.LogSoftmax(dim=-1))\r\n ]))\r\n\r\n def forward(self, img):\r\n output = self.fcoutput(img)\r\n return output\r\n\r\n\r\nclass LeNet5(nn.Module):\r\n \"\"\"\r\n Input - 1x32x32\r\n Output - 10\r\n \"\"\"\r\n def __init__(self):\r\n super(LeNet5, self).__init__()\r\n \r\n self.c1 = C1()\r\n self.c3 = C3()\r\n self.c5 = C5()\r\n self.f6 = F6()\r\n self.fcoutput = FCoutput()\r\n \r\n def forward(self, img):\r\n \r\n # Conv Layer(C1)\r\n # - input: 32x32x1\r\n # - output: 28x28x6\r\n # - weights: (5x5x1 + 1)x6\r\n # Sub-sampling(S2)\r\n # - input: 28x28x6\r\n # - output: 14x14x6\r\n # - weights: 2x2x1\r\n output = self.c1(img)\r\n \r\n # Conv Layer(C3)\r\n # - input: 14x14x6\r\n # - output: 10x10x16\r\n # - weights: (5x5x6 + 1)x16\r\n # Sub-sampling(S4)\r\n # - input: 10x10x16\r\n # - output: 5x5x16\r\n # - weights: 2x2x1\r\n output = self.c3(output)\r\n \r\n # Conv Layer(C5)\r\n # - input: 5x5x16\r\n # - output: 1x1x120\r\n # - weights: (5x5x16 + 1)x120\r\n output = self.c5(output)\r\n \r\n # Flatten Layer\r\n output = output.view(img.size(0), -1)\r\n \r\n # Fully Connected Layer(F6)\r\n # - input: 120\r\n # - output: 84\r\n output = self.f6(output)\r\n \r\n # Fully Connected Layer(F7)\r\n # - input: 84\r\n # - output: 10\r\n output = self.fcoutput(output)\r\n return output\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" ]
[ [ "torch.nn.MaxPool2d", "torch.nn.Linear", "torch.nn.LogSoftmax", "torch.nn.Conv2d", "torch.nn.ReLU" ] ]
naisy/donkeycar
[ "11f7598d51c1c085db2a76943c86132bf1eb9e30" ]
[ "donkeycar/templates/complete.py" ]
[ "#!/usr/bin/env python3\n\"\"\"\nScripts to drive a donkey 2 car\n\nUsage:\n manage.py (drive) [--model=<model>] [--js] [--type=(linear|categorical)] [--camera=(single|stereo)] [--meta=<key:value> ...] [--myconfig=<filename>]\n manage.py (train) [--tubs=tubs] (--model=<model>) [--type=(linear|inferred|tensorrt_linear|tflite_linear)]\n\nOptions:\n -h --help Show this screen.\n --js Use physical joystick.\n -f --file=<file> A text file containing paths to tub files, one per line. Option may be used more than once.\n --meta=<key:value> Key/Value strings describing describing a piece of meta data about this drive. Option may be used more than once.\n --myconfig=filename Specify myconfig file to use. \n [default: myconfig.py]\n\"\"\"\nimport os\nimport time\nimport logging\nfrom docopt import docopt\n\n\nimport donkeycar as dk\nfrom donkeycar.parts.transform import TriggeredCallback, DelayedTrigger\nfrom donkeycar.parts.tub_v2 import TubWriter\nfrom donkeycar.parts.datastore import TubHandler\nfrom donkeycar.parts.controller import LocalWebController, WebFpv, JoystickController\nfrom donkeycar.parts.throttle_filter import ThrottleFilter\nfrom donkeycar.parts.behavior import BehaviorPart\nfrom donkeycar.parts.file_watcher import FileWatcher\nfrom donkeycar.parts.launch import AiLaunch\nfrom donkeycar.pipeline.augmentations import ImageAugmentation\nfrom donkeycar.utils import *\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\ndef drive(cfg, model_path=None, use_joystick=False, model_type=None,\n camera_type='single', meta=[]):\n \"\"\"\n Construct a working robotic vehicle from many parts. Each part runs as a\n job in the Vehicle loop, calling either it's run or run_threaded method\n depending on the constructor flag `threaded`. All parts are updated one\n after another at the framerate given in cfg.DRIVE_LOOP_HZ assuming each\n part finishes processing in a timely manner. Parts may have named outputs\n and inputs. The framework handles passing named outputs to parts\n requesting the same named input.\n \"\"\"\n logger.info(f'PID: {os.getpid()}')\n if cfg.DONKEY_GYM:\n #the simulator will use cuda and then we usually run out of resources\n #if we also try to use cuda. so disable for donkey_gym.\n #os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\n pass\n\n if model_type is None:\n if cfg.TRAIN_LOCALIZER:\n model_type = \"localizer\"\n elif cfg.TRAIN_BEHAVIORS:\n model_type = \"behavior\"\n else:\n model_type = cfg.DEFAULT_MODEL_TYPE\n\n #Initialize car\n V = dk.vehicle.Vehicle()\n\n #Initialize logging before anything else to allow console logging\n if cfg.HAVE_CONSOLE_LOGGING:\n logger.setLevel(logging.getLevelName(cfg.LOGGING_LEVEL))\n ch = logging.StreamHandler()\n ch.setFormatter(logging.Formatter(cfg.LOGGING_FORMAT))\n logger.addHandler(ch)\n\n if cfg.HAVE_MQTT_TELEMETRY:\n from donkeycar.parts.telemetry import MqttTelemetry\n tel = MqttTelemetry(cfg)\n \n if cfg.HAVE_ODOM:\n if cfg.ENCODER_TYPE == \"GPIO\":\n from donkeycar.parts.encoder import RotaryEncoder\n enc = RotaryEncoder(mm_per_tick=0.306096, pin = cfg.ODOM_PIN, debug = cfg.ODOM_DEBUG)\n V.add(enc, inputs=['throttle'], outputs=['enc/speed'], threaded=True)\n elif cfg.ENCODER_TYPE == \"arduino\":\n from donkeycar.parts.encoder import ArduinoEncoder\n enc = ArduinoEncoder()\n V.add(enc, outputs=['enc/speed'], threaded=True)\n else:\n print(\"No supported encoder found\")\n\n logger.info(\"cfg.CAMERA_TYPE %s\"%cfg.CAMERA_TYPE)\n if camera_type == \"stereo\":\n\n if cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam\n\n camA = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n\n camA = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n else:\n raise(Exception(\"Unsupported camera type: %s\" % cfg.CAMERA_TYPE))\n\n V.add(camA, outputs=['cam/image_array_a'], threaded=True)\n V.add(camB, outputs=['cam/image_array_b'], threaded=True)\n\n from donkeycar.parts.image import StereoPair\n\n V.add(StereoPair(), inputs=['cam/image_array_a', 'cam/image_array_b'],\n outputs=['cam/image_array'])\n elif cfg.CAMERA_TYPE == \"D435\":\n from donkeycar.parts.realsense435i import RealSense435i\n cam = RealSense435i(\n enable_rgb=cfg.REALSENSE_D435_RGB,\n enable_depth=cfg.REALSENSE_D435_DEPTH,\n enable_imu=cfg.REALSENSE_D435_IMU,\n device_id=cfg.REALSENSE_D435_ID)\n V.add(cam, inputs=[],\n outputs=['cam/image_array', 'cam/depth_array',\n 'imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z'],\n threaded=True)\n\n else:\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv\n\n inputs = []\n outputs = ['cam/image_array']\n threaded = True\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv \n #rbx\n cam = DonkeyGymEnv(cfg.DONKEY_SIM_PATH, host=cfg.SIM_HOST, env_name=cfg.DONKEY_GYM_ENV_NAME, conf=cfg.GYM_CONF, record_location=cfg.SIM_RECORD_LOCATION, record_gyroaccel=cfg.SIM_RECORD_GYROACCEL, record_velocity=cfg.SIM_RECORD_VELOCITY, record_lidar=cfg.SIM_RECORD_LIDAR, delay=cfg.SIM_ARTIFICIAL_LATENCY)\n threaded = True\n inputs = ['angle', 'throttle']\n elif cfg.CAMERA_TYPE == \"PICAM\":\n from donkeycar.parts.camera import PiCamera\n cam = PiCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, vflip=cfg.CAMERA_VFLIP, hflip=cfg.CAMERA_HFLIP)\n elif cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam\n cam = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n cam = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CSIC\":\n from donkeycar.parts.camera import CSICamera\n cam = CSICamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, gstreamer_flip=cfg.CSIC_CAM_GSTREAMER_FLIP_PARM)\n elif cfg.CAMERA_TYPE == \"V4L\":\n from donkeycar.parts.camera import V4LCamera\n cam = V4LCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE)\n elif cfg.CAMERA_TYPE == \"MOCK\":\n from donkeycar.parts.camera import MockCamera\n cam = MockCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"IMAGE_LIST\":\n from donkeycar.parts.camera import ImageListCamera\n cam = ImageListCamera(path_mask=cfg.PATH_MASK)\n elif cfg.CAMERA_TYPE == \"LEOPARD\":\n from donkeycar.parts.leopard_imaging import LICamera\n cam = LICamera(width=cfg.IMAGE_W, height=cfg.IMAGE_H, fps=cfg.CAMERA_FRAMERATE)\n else:\n raise(Exception(\"Unkown camera type: %s\" % cfg.CAMERA_TYPE))\n\n \n # Donkey gym part will output position information if it is configured\n if cfg.DONKEY_GYM:\n if cfg.SIM_RECORD_LOCATION:\n outputs += ['pos/pos_x', 'pos/pos_y', 'pos/pos_z', 'pos/speed', 'pos/cte']\n if cfg.SIM_RECORD_GYROACCEL:\n outputs += ['gyro/gyro_x', 'gyro/gyro_y', 'gyro/gyro_z', 'accel/accel_x', 'accel/accel_y', 'accel/accel_z']\n if cfg.SIM_RECORD_VELOCITY:\n outputs += ['vel/vel_x', 'vel/vel_y', 'vel/vel_z']\n if cfg.SIM_RECORD_LIDAR:\n outputs += ['lidar/dist_array']\n \n V.add(cam, inputs=inputs, outputs=outputs, threaded=threaded)\n\n # add lidar\n if cfg.USE_LIDAR:\n from donkeycar.parts.lidar import RPLidar\n if cfg.LIDAR_TYPE == 'RP':\n print(\"adding RP lidar part\")\n lidar = RPLidar(lower_limit = cfg.LIDAR_LOWER_LIMIT, upper_limit = cfg.LIDAR_UPPER_LIMIT)\n V.add(lidar, inputs=[],outputs=['lidar/dist_array'], threaded=True)\n if cfg.LIDAR_TYPE == 'YD':\n print(\"YD Lidar not yet supported\")\n \n#This web controller will create a web server that is capable\n #of managing steering, throttle, and modes, and more.\n ctr = LocalWebController(port=cfg.WEB_CONTROL_PORT, mode=cfg.WEB_INIT_MODE)\n \n V.add(ctr,\n inputs=['cam/image_array', 'tub/num_records'],\n outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],\n threaded=True)\n \n if use_joystick or cfg.USE_JOYSTICK_AS_DEFAULT:\n #modify max_throttle closer to 1.0 to have more power\n #modify steering_scale lower than 1.0 to have less responsive steering\n if cfg.CONTROLLER_TYPE == \"pigpio_rc\": # an RC controllers read by GPIO pins. They typically don't have buttons\n from donkeycar.parts.controller import RCReceiver\n ctr = RCReceiver(cfg)\n V.add(ctr, outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],threaded=False)\n else:\n if cfg.CONTROLLER_TYPE == \"custom\": #custom controller created with `donkey createjs` command\n from my_joystick import MyJoystickController\n ctr = MyJoystickController(\n throttle_dir=cfg.JOYSTICK_THROTTLE_DIR,\n throttle_scale=cfg.JOYSTICK_MAX_THROTTLE,\n steering_scale=cfg.JOYSTICK_STEERING_SCALE,\n auto_record_on_throttle=cfg.AUTO_RECORD_ON_THROTTLE)\n ctr.set_deadzone(cfg.JOYSTICK_DEADZONE) \n elif cfg.CONTROLLER_TYPE == \"MM1\":\n from donkeycar.parts.robohat import RoboHATController \n ctr = RoboHATController(cfg)\n else:\n from donkeycar.parts.controller import get_js_controller\n ctr = get_js_controller(cfg)\n if cfg.USE_NETWORKED_JS:\n from donkeycar.parts.controller import JoyStickSub\n netwkJs = JoyStickSub(cfg.NETWORK_JS_SERVER_IP)\n V.add(netwkJs, threaded=True)\n ctr.js = netwkJs\n V.add(ctr, inputs=['cam/image_array'], outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],threaded=True)\n \n\n #this throttle filter will allow one tap back for esc reverse\n th_filter = ThrottleFilter()\n V.add(th_filter, inputs=['user/throttle'], outputs=['user/throttle'])\n\n #See if we should even run the pilot module.\n #This is only needed because the part run_condition only accepts boolean\n class PilotCondition:\n def run(self, mode):\n if mode == 'user':\n return False\n else:\n return True\n\n V.add(PilotCondition(), inputs=['user/mode'], outputs=['run_pilot'])\n\n class LedConditionLogic:\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, mode, recording, recording_alert, behavior_state, model_file_changed, track_loc):\n #returns a blink rate. 0 for off. -1 for on. positive for rate.\n\n if track_loc is not None:\n led.set_rgb(*self.cfg.LOC_COLORS[track_loc])\n return -1\n\n if model_file_changed:\n led.set_rgb(self.cfg.MODEL_RELOADED_LED_R, self.cfg.MODEL_RELOADED_LED_G, self.cfg.MODEL_RELOADED_LED_B)\n return 0.1\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n\n if recording_alert:\n led.set_rgb(*recording_alert)\n return self.cfg.REC_COUNT_ALERT_BLINK_RATE\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n\n if behavior_state is not None and model_type == 'behavior':\n r, g, b = self.cfg.BEHAVIOR_LED_COLORS[behavior_state]\n led.set_rgb(r, g, b)\n return -1 #solid on\n\n if recording:\n return -1 #solid on\n elif mode == 'user':\n return 1\n elif mode == 'local_angle':\n return 0.5\n elif mode == 'local':\n return 0.1\n return 0\n\n if cfg.HAVE_RGB_LED and not cfg.DONKEY_GYM:\n from donkeycar.parts.led_status import RGB_LED\n led = RGB_LED(cfg.LED_PIN_R, cfg.LED_PIN_G, cfg.LED_PIN_B, cfg.LED_INVERT)\n led.set_rgb(cfg.LED_R, cfg.LED_G, cfg.LED_B)\n\n V.add(LedConditionLogic(cfg), inputs=['user/mode', 'recording', \"records/alert\", 'behavior/state', 'modelfile/modified', \"pilot/loc\"],\n outputs=['led/blink_rate'])\n\n V.add(led, inputs=['led/blink_rate'])\n\n def get_record_alert_color(num_records):\n col = (0, 0, 0)\n for count, color in cfg.RECORD_ALERT_COLOR_ARR:\n if num_records >= count:\n col = color\n return col\n\n class RecordTracker:\n def __init__(self):\n self.last_num_rec_print = 0\n self.dur_alert = 0\n self.force_alert = 0\n\n def run(self, num_records):\n if num_records is None:\n return 0\n\n if self.last_num_rec_print != num_records or self.force_alert:\n self.last_num_rec_print = num_records\n\n if num_records % 10 == 0:\n print(\"recorded\", num_records, \"records\")\n\n if num_records % cfg.REC_COUNT_ALERT == 0 or self.force_alert:\n self.dur_alert = num_records // cfg.REC_COUNT_ALERT * cfg.REC_COUNT_ALERT_CYC\n self.force_alert = 0\n\n if self.dur_alert > 0:\n self.dur_alert -= 1\n\n if self.dur_alert != 0:\n return get_record_alert_color(num_records)\n\n return 0\n\n rec_tracker_part = RecordTracker()\n V.add(rec_tracker_part, inputs=[\"tub/num_records\"], outputs=['records/alert'])\n\n if cfg.AUTO_RECORD_ON_THROTTLE:\n def show_record_count_status():\n rec_tracker_part.last_num_rec_print = 0\n rec_tracker_part.force_alert = 1\n if (cfg.CONTROLLER_TYPE != \"pigpio_rc\") and (cfg.CONTROLLER_TYPE != \"MM1\"): # these controllers don't use the joystick class\n if isinstance(ctr, JoystickController):\n ctr.set_button_down_trigger('circle', show_record_count_status) #then we are not using the circle button. hijack that to force a record count indication\n else:\n \n show_record_count_status()\n\n #Sombrero\n if cfg.HAVE_SOMBRERO:\n from donkeycar.parts.sombrero import Sombrero\n s = Sombrero()\n\n #IMU\n if cfg.HAVE_IMU:\n from donkeycar.parts.imu import IMU\n imu = IMU(sensor=cfg.IMU_SENSOR, dlp_setting=cfg.IMU_DLP_CONFIG)\n V.add(imu, outputs=['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z'], threaded=True)\n\n # Use the FPV preview, which will show the cropped image output, or the full frame.\n if cfg.USE_FPV:\n V.add(WebFpv(), inputs=['cam/image_array'], threaded=True)\n\n #Behavioral state\n if cfg.TRAIN_BEHAVIORS:\n bh = BehaviorPart(cfg.BEHAVIOR_LIST)\n V.add(bh, outputs=['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"])\n try:\n ctr.set_button_down_trigger('L1', bh.increment_state)\n except:\n pass\n\n inputs = ['cam/image_array', \"behavior/one_hot_state_array\"]\n #IMU\n elif cfg.USE_LIDAR:\n inputs = ['cam/image_array', 'lidar/dist_array']\n\n elif cfg.HAVE_ODOM:\n inputs = ['cam/image_array', 'enc/speed']\n\n elif model_type == \"imu\":\n assert cfg.HAVE_IMU, 'Missing imu parameter in config'\n # Run the pilot if the mode is not user.\n inputs = ['cam/image_array',\n 'imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n\n else:\n inputs = ['cam/image_array']\n\n def load_model(kl, model_path):\n start = time.time()\n print('loading model', model_path)\n kl.load(model_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n\n def load_weights(kl, weights_path):\n start = time.time()\n try:\n print('loading model weights', weights_path)\n kl.model.load_weights(weights_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print('ERR>> problems loading weights', weights_path)\n\n def load_model_json(kl, json_fnm):\n start = time.time()\n print('loading model json', json_fnm)\n from tensorflow.python import keras\n try:\n with open(json_fnm, 'r') as handle:\n contents = handle.read()\n kl.model = keras.models.model_from_json(contents)\n print('finished loading json in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print(\"ERR>> problems loading model json\", json_fnm)\n\n if model_path:\n # When we have a model, first create an appropriate Keras part\n kl = dk.utils.get_model_by_type(model_type, cfg)\n\n model_reload_cb = None\n\n if '.h5' in model_path or '.trt' in model_path or '.tflite' in \\\n model_path or '.savedmodel' in model_path:\n # load the whole model with weigths, etc\n load_model(kl, model_path)\n\n def reload_model(filename):\n load_model(kl, filename)\n\n model_reload_cb = reload_model\n\n elif '.json' in model_path:\n # when we have a .json extension\n # load the model from there and look for a matching\n # .wts file with just weights\n load_model_json(kl, model_path)\n weights_path = model_path.replace('.json', '.weights')\n load_weights(kl, weights_path)\n\n def reload_weights(filename):\n weights_path = filename.replace('.json', '.weights')\n load_weights(kl, weights_path)\n\n model_reload_cb = reload_weights\n\n else:\n print(\"ERR>> Unknown extension type on model file!!\")\n return\n\n # this part will signal visual LED, if connected\n V.add(FileWatcher(model_path, verbose=True),\n outputs=['modelfile/modified'])\n\n # these parts will reload the model file, but only when ai is running\n # so we don't interrupt user driving\n V.add(FileWatcher(model_path), outputs=['modelfile/dirty'],\n run_condition=\"ai_running\")\n V.add(DelayedTrigger(100), inputs=['modelfile/dirty'],\n outputs=['modelfile/reload'], run_condition=\"ai_running\")\n V.add(TriggeredCallback(model_path, model_reload_cb),\n inputs=[\"modelfile/reload\"], run_condition=\"ai_running\")\n\n outputs = ['pilot/angle', 'pilot/throttle']\n\n if cfg.TRAIN_LOCALIZER:\n outputs.append(\"pilot/loc\")\n # Add image transformations like crop or trapezoidal mask\n if hasattr(cfg, 'TRANSFORMATIONS') and cfg.TRANSFORMATIONS:\n V.add(ImageAugmentation(cfg, 'TRANSFORMATIONS'),\n inputs=['cam/image_array'], outputs=['cam/image_array_trans'])\n inputs = ['cam/image_array_trans'] + inputs[1:]\n\n V.add(kl, inputs=inputs, outputs=outputs, run_condition='run_pilot')\n\n if cfg.STOP_SIGN_DETECTOR:\n from donkeycar.parts.object_detector.stop_sign_detector \\\n import StopSignDetector\n V.add(StopSignDetector(cfg.STOP_SIGN_MIN_SCORE,\n cfg.STOP_SIGN_SHOW_BOUNDING_BOX),\n inputs=['cam/image_array', 'pilot/throttle'],\n outputs=['pilot/throttle', 'cam/image_array'])\n\n # Choose what inputs should change the car.\n class DriveMode:\n drive_start = time.time()\n def run(self, mode,\n user_angle, user_throttle,\n pilot_angle, pilot_throttle):\n if mode == 'user':\n current_time = time.time()\n if current_time - self.drive_start >= 1.0:\n print(f\"user_angle: {user_angle}, user_throttle: {user_throttle}\")\n self.drive_start = current_time\n return user_angle, user_throttle\n\n elif mode == 'local_angle':\n return pilot_angle if pilot_angle else 0.0, user_throttle\n\n else:\n return pilot_angle if pilot_angle else 0.0, \\\n pilot_throttle * cfg.AI_THROTTLE_MULT \\\n if pilot_throttle else 0.0\n\n V.add(DriveMode(),\n inputs=['user/mode', 'user/angle', 'user/throttle',\n 'pilot/angle', 'pilot/throttle'],\n outputs=['angle', 'throttle'])\n\n\n #to give the car a boost when starting ai mode in a race.\n aiLauncher = AiLaunch(cfg.AI_LAUNCH_DURATION, cfg.AI_LAUNCH_THROTTLE, cfg.AI_LAUNCH_KEEP_ENABLED)\n\n V.add(aiLauncher,\n inputs=['user/mode', 'throttle'],\n outputs=['throttle'])\n\n if (cfg.CONTROLLER_TYPE != \"pigpio_rc\") and (cfg.CONTROLLER_TYPE != \"MM1\"):\n if isinstance(ctr, JoystickController):\n ctr.set_button_down_trigger(cfg.AI_LAUNCH_ENABLE_BUTTON, aiLauncher.enable_ai_launch)\n\n class AiRunCondition:\n '''\n A bool part to let us know when ai is running.\n '''\n def run(self, mode):\n if mode == \"user\":\n return False\n return True\n\n V.add(AiRunCondition(), inputs=['user/mode'], outputs=['ai_running'])\n\n # Ai Recording\n class AiRecordingCondition:\n '''\n return True when ai mode, otherwize respect user mode recording flag\n '''\n def run(self, mode, recording):\n if mode == 'user':\n return recording\n return True\n\n if cfg.RECORD_DURING_AI:\n V.add(AiRecordingCondition(), inputs=['user/mode', 'recording'], outputs=['recording'])\n\n # Drive train setup\n if cfg.DONKEY_GYM or cfg.DRIVE_TRAIN_TYPE == \"MOCK\":\n pass\n elif cfg.DRIVE_TRAIN_TYPE == \"I2C_SERVO\":\n from donkeycar.parts.actuator import PCA9685, PWMSteering, PWMThrottle\n\n steering_controller = PCA9685(cfg.STEERING_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM,\n steering_zero_pulse=cfg.STEERING_STOPPED_PWM,\n right_pulse=cfg.STEERING_RIGHT_PWM)\n\n throttle_controller = PCA9685(cfg.THROTTLE_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n throttle_zero_pulse=cfg.THROTTLE_STOPPED_PWM,\n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n\n V.add(steering, inputs=['angle'], threaded=False)\n V.add(throttle, inputs=['throttle'], threaded=False)\n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_STEER_THROTTLE\":\n from donkeycar.parts.actuator import Mini_HBridge_DC_Motor_PWM\n\n steering = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT, cfg.HBRIDGE_PIN_RIGHT)\n throttle = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL\":\n from donkeycar.parts.actuator import TwoWheelSteeringThrottle, Mini_HBridge_DC_Motor_PWM\n\n left_motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT_FWD, cfg.HBRIDGE_PIN_LEFT_BWD)\n right_motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_RIGHT_FWD, cfg.HBRIDGE_PIN_RIGHT_BWD)\n two_wheel_control = TwoWheelSteeringThrottle()\n\n V.add(two_wheel_control,\n inputs=['throttle', 'angle'],\n outputs=['left_motor_speed', 'right_motor_speed'])\n\n V.add(left_motor, inputs=['left_motor_speed'])\n V.add(right_motor, inputs=['right_motor_speed'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL_L298N\":\n from donkeycar.parts.actuator import TwoWheelSteeringThrottle, L298N_HBridge_DC_Motor\n\n left_motor = L298N_HBridge_DC_Motor(cfg.HBRIDGE_L298N_PIN_LEFT_FWD, cfg.HBRIDGE_L298N_PIN_LEFT_BWD, cfg.HBRIDGE_L298N_PIN_LEFT_EN)\n right_motor = L298N_HBridge_DC_Motor(cfg.HBRIDGE_L298N_PIN_RIGHT_FWD, cfg.HBRIDGE_L298N_PIN_RIGHT_BWD, cfg.HBRIDGE_L298N_PIN_RIGHT_EN)\n two_wheel_control = TwoWheelSteeringThrottle()\n\n V.add(two_wheel_control,\n inputs=['throttle', 'angle'],\n outputs=['left_motor_speed', 'right_motor_speed'])\n\n V.add(left_motor, inputs=['left_motor_speed'])\n V.add(right_motor, inputs=['right_motor_speed'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_PWM\":\n from donkeycar.parts.actuator import ServoBlaster, PWMSteering\n steering_controller = ServoBlaster(cfg.STEERING_CHANNEL) #really pin\n # PWM pulse values should be in the range of 100 to 200\n assert(cfg.STEERING_LEFT_PWM <= 200)\n assert(cfg.STEERING_RIGHT_PWM <= 200)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM,\n right_pulse=cfg.STEERING_RIGHT_PWM)\n\n from donkeycar.parts.actuator import Mini_HBridge_DC_Motor_PWM\n motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(motor, inputs=[\"throttle\"])\n \n elif cfg.DRIVE_TRAIN_TYPE == \"MM1\":\n from donkeycar.parts.robohat import RoboHATDriver\n V.add(RoboHATDriver(cfg), inputs=['angle', 'throttle'])\n \n elif cfg.DRIVE_TRAIN_TYPE == \"PIGPIO_PWM\":\n from donkeycar.parts.actuator import PWMSteering, PWMThrottle, PiGPIO_PWM\n steering_controller = PiGPIO_PWM(cfg.STEERING_PWM_PIN, freq=cfg.STEERING_PWM_FREQ, inverted=cfg.STEERING_PWM_INVERTED)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n steering_zero_pulse=cfg.STEERING_STOPPED_PWM,\n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n throttle_controller = PiGPIO_PWM(cfg.THROTTLE_PWM_PIN, freq=cfg.THROTTLE_PWM_FREQ, inverted=cfg.THROTTLE_PWM_INVERTED)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n throttle_zero_pulse=cfg.THROTTLE_STOPPED_PWM, \n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(throttle, inputs=['throttle'], threaded=True)\n\n # OLED setup\n if cfg.USE_SSD1306_128_32:\n from donkeycar.parts.oled import OLEDPart\n auto_record_on_throttle = cfg.USE_JOYSTICK_AS_DEFAULT and cfg.AUTO_RECORD_ON_THROTTLE\n oled_part = OLEDPart(cfg.SSD1306_128_32_I2C_ROTATION, cfg.SSD1306_RESOLUTION, auto_record_on_throttle)\n V.add(oled_part, inputs=['recording', 'tub/num_records', 'user/mode'], outputs=[], threaded=True)\n\n # add tub to save data\n\n inputs = ['cam/image_array', 'user/angle', 'user/throttle', 'user/mode',]\n types = ['image_array', 'float', 'float', 'str']\n \n if cfg.USE_LIDAR:\n inputs += ['lidar/dist_array']\n types += ['nparray']\n\n if cfg.HAVE_ODOM:\n inputs += ['enc/speed']\n types += ['float']\n\n if cfg.TRAIN_BEHAVIORS:\n inputs += ['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"]\n types += ['int', 'str', 'vector']\n\n if cfg.CAMERA_TYPE == \"D435\" and cfg.REALSENSE_D435_DEPTH:\n inputs += ['cam/depth_array']\n types += ['gray16_array']\n\n if cfg.HAVE_IMU or (cfg.CAMERA_TYPE == \"D435\" and cfg.REALSENSE_D435_IMU):\n inputs += ['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n\n types +=['float', 'float', 'float',\n 'float', 'float', 'float']\n\n # rbx\n if cfg.DONKEY_GYM:\n if cfg.SIM_RECORD_LOCATION: \n inputs += ['pos/pos_x', 'pos/pos_y', 'pos/pos_z', 'pos/speed', 'pos/cte']\n types += ['float', 'float', 'float', 'float', 'float']\n if cfg.SIM_RECORD_GYROACCEL: \n inputs += ['gyro/gyro_x', 'gyro/gyro_y', 'gyro/gyro_z', 'accel/accel_x', 'accel/accel_y', 'accel/accel_z']\n types += ['float', 'float', 'float', 'float', 'float', 'float']\n if cfg.SIM_RECORD_VELOCITY: \n inputs += ['vel/vel_x', 'vel/vel_y', 'vel/vel_z']\n types += ['float', 'float', 'float']\n if cfg.SIM_RECORD_LIDAR:\n inputs += ['lidar/dist_array']\n types += ['nparray']\n\n if cfg.RECORD_DURING_AI:\n inputs += ['pilot/angle', 'pilot/throttle']\n types += ['float', 'float']\n\n if cfg.HAVE_PERFMON:\n from donkeycar.parts.perfmon import PerfMonitor\n mon = PerfMonitor(cfg)\n perfmon_outputs = ['perf/cpu', 'perf/mem', 'perf/freq']\n inputs += perfmon_outputs\n types += ['float', 'float', 'float']\n V.add(mon, inputs=[], outputs=perfmon_outputs, threaded=True)\n\n # do we want to store new records into own dir or append to existing\n tub_path = TubHandler(path=cfg.DATA_PATH).create_tub_path() if \\\n cfg.AUTO_CREATE_NEW_TUB else cfg.DATA_PATH\n tub_writer = TubWriter(tub_path, inputs=inputs, types=types, metadata=meta)\n V.add(tub_writer, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n\n # Telemetry (we add the same metrics added to the TubHandler\n if cfg.HAVE_MQTT_TELEMETRY:\n telem_inputs, _ = tel.add_step_inputs(inputs, types)\n V.add(tel, inputs=telem_inputs, outputs=[\"tub/queue_size\"], threaded=True)\n\n if cfg.PUB_CAMERA_IMAGES:\n from donkeycar.parts.network import TCPServeValue\n from donkeycar.parts.image import ImgArrToJpg\n pub = TCPServeValue(\"camera\")\n V.add(ImgArrToJpg(), inputs=['cam/image_array'], outputs=['jpg/bin'])\n V.add(pub, inputs=['jpg/bin'])\n\n if type(ctr) is LocalWebController:\n if cfg.DONKEY_GYM:\n print(\"You can now go to http://localhost:%d to drive your car.\" % cfg.WEB_CONTROL_PORT)\n else:\n print(\"You can now go to <your hostname.local>:%d to drive your car.\" % cfg.WEB_CONTROL_PORT) \n elif (cfg.CONTROLLER_TYPE != \"pigpio_rc\") and (cfg.CONTROLLER_TYPE != \"MM1\"):\n if isinstance(ctr, JoystickController):\n print(\"You can now move your joystick to drive your car.\")\n ctr.set_tub(tub_writer.tub)\n ctr.print_controls()\n\n # run the vehicle\n V.start(rate_hz=cfg.DRIVE_LOOP_HZ, max_loop_count=cfg.MAX_LOOPS)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n cfg = dk.load_config(myconfig=args['--myconfig'])\n\n if args['drive']:\n model_type = args['--type']\n camera_type = args['--camera']\n drive(cfg, model_path=args['--model'], use_joystick=args['--js'],\n model_type=model_type, camera_type=camera_type,\n meta=args['--meta'])\n elif args['train']:\n print('Use python train.py instead.\\n')\n" ]
[ [ "tensorflow.python.keras.models.model_from_json" ] ]
yongyuwen/mbti_rnn
[ "3f67cd90d76ab82d65afc3c155728e3d349a1107" ]
[ "src/rnn.py" ]
[ "\"\"\"rnn.py\r\n~~~~~~~~~~~~~~\r\nWritten by Yong Yu Wen, 2018\r\n\r\n(Built using tensorflow-gpu 1.6.0)\r\n\r\nA TensorFlow-based many-to-one recurrent neural network specifically\r\nfor the classification of MBTI types based on social media posts.\r\nRaw un-processed dataset used for this task can be found at\r\nhttps://www.kaggle.com/datasnaek/mbti-type\r\n\r\nSupports several cell types (Basic RNN, GRUs, LSTMs), multiple layer,\r\ntraining with word embeddings, as well as dropout regularization.\r\n\r\nThis program incorporates ideas from Denny Britz and Spitis (Github display name)\r\nand their websites http://www.wildml.com and https://r2rt.com\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport time\r\nimport pickle\r\n\r\n\r\nclass RNN(object):\r\n def __init__(self, cell_type, state_size, num_steps, num_layers,\r\n num_classes, embedding=None, build_with_dropout=False):\r\n \"\"\"\r\n Creates the RNN object\r\n :param cell_type: Type of RNN cell. Supports Basic RNN, GRUs and LSTMs\r\n :param state_size: Number of hidden states\r\n :param num_steps: Number of time steps\r\n :param num_layers: Number of layers\r\n :param num_classes: Number of classes in the output\r\n :param embedding: Word embedding\r\n :param build_with_dropout: Whether to use dropout in the RNN\r\n \"\"\"\r\n self.x = tf.placeholder(tf.int32, [None, num_steps], name='input_placeholder')\r\n self.y = tf.placeholder(tf.int32, [None, num_classes], name='labels_placeholder')\r\n with tf.name_scope(\"embedding\"):\r\n self.embeddings = tf.get_variable(name=\"embeddings\", shape=embedding.shape,\r\n initializer=tf.constant_initializer(embedding), trainable=True)\r\n self.state_size = state_size\r\n self.num_steps = num_steps\r\n self.num_layers = num_layers\r\n self.num_classes = num_classes\r\n self.build_with_dropout = build_with_dropout\r\n self.dropout = tf.placeholder_with_default(tf.constant(1.0, dtype=tf.float32), ())\r\n self.cell_type = cell_type\r\n self.cell = self._make_MultiRNNCell()\r\n self.saver = tf.train.Saver()\r\n\r\n def _make_cell(self):\r\n \"\"\"\r\n Private function to create RNN cell. Required for TensorFlow's MultiRNNCell function\r\n \"\"\"\r\n if self.cell_type == 'GRU':\r\n cell = tf.nn.rnn_cell.GRUCell(self.state_size)\r\n elif self.cell_type == 'LSTM':\r\n cell = tf.nn.rnn_cell.LSTMCell(self.state_size, state_is_tuple=True)\r\n else:\r\n cell = tf.nn.rnn_cell.BasicRNNCell(self.state_size)\r\n if self.build_with_dropout:\r\n return tf.nn.rnn_cell.DropoutWrapper(cell, input_keep_prob=self.dropout)\r\n else:\r\n return cell\r\n\r\n def _make_MultiRNNCell(self):\r\n \"\"\"\r\n Private function to create multi-layer RNNs\r\n \"\"\"\r\n cell = tf.nn.rnn_cell.MultiRNNCell([self._make_cell() for _ in range(self.num_layers)])\r\n\r\n if self.build_with_dropout:\r\n cell = tf.nn.rnn_cell.DropoutWrapper(cell, output_keep_prob=self.dropout)\r\n return cell\r\n\r\n\r\n def train(self, sess, epochs, learning_rate, pipeline, training_data, validation_data,\r\n SGDR=False, store_accuracies = False, dropout=1.0, checkpoint=None, save=None):\r\n \"\"\"\r\n Trains the neural network using the Adam Optimizer (by default)\r\n :param sess: TensorFlow Session\r\n :param epochs: Number of epochs\r\n :param learning_rate: Learning rate for the optimizer\r\n :param pipeline: Pipeline object to feed data into the network for training\r\n :param training_data: Training dataset (in Numpy array format, labels one-hot encoded)\r\n :param validation_data: Validation dataset (in Numpy array format, labels one-hot encoded)\r\n :param SGDR: Stochastic Gradient Descent with Restarts. See https://arxiv.org/abs/1608.03983\r\n :param store_accuracies: Save & store train and validation accuracies to be exported\r\n :param dropout: Dropout keep probability (1.0 for no dropout)\r\n :param checkpoint: Location to save model checkpoint\r\n :param save: Location to save trained model\r\n \"\"\"\r\n #~~Read data\r\n training_x, training_y = training_data\r\n validation_x, validation_y = validation_data\r\n \r\n rnn_inputs = tf.nn.embedding_lookup(self.embeddings, self.x)\r\n rnn_outputs, final_state = tf.nn.dynamic_rnn(self.cell, rnn_inputs, dtype=tf.float32) #initial_state=init_state\r\n with tf.variable_scope('softmax'):\r\n W = tf.get_variable('W', [self.state_size, self.num_classes])\r\n b = tf.get_variable('b', [self.num_classes], initializer=tf.constant_initializer(0.0))\r\n rnn_outputs = tf.transpose(rnn_outputs, [1, 0, 2])\r\n last = tf.reshape(rnn_outputs[-1], [-1, self.state_size])\r\n predictions = (tf.matmul(last, W) + b)\r\n\r\n y_reshaped = tf.reshape(self.y, [-1, self.num_classes])\r\n total_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predictions, labels=y_reshaped))\r\n\r\n #Create Global step\r\n global_step = tf.Variable(0, trainable=False, name='global_step')\r\n\r\n #SGDR\r\n if SGDR:\r\n first_decay_steps = int(training_x.shape[0]/pipeline.batch_size)\r\n learning_rate = tf.train.cosine_decay_restarts(learning_rate, global_step,\r\n first_decay_steps)\r\n\r\n train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)\r\n\r\n #model evaluation\r\n correct_prediction=tf.equal(tf.argmax(predictions,1),tf.argmax(y_reshaped,1))\r\n model_accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\r\n\r\n #~~~~~~~~~~~~~~Training of the actual dataset~~~~~~~~~~~~~~~~~~\r\n \r\n\r\n sess.run(tf.global_variables_initializer())\r\n\r\n if save:\r\n try:\r\n self.saver.restore(sess, save)\r\n print(\"Save restored \\n\")\r\n except:\r\n print(\"No Save found. Running new training cycle\")\r\n \r\n start_time = time.time() #Track time taken for model\r\n\r\n training_accuracies = []\r\n validation_accuracies = []\r\n \r\n for epoch in range(epochs):\r\n sess.run(pipeline.iterator_train.initializer, feed_dict={pipeline.features_placeholder: training_x,\r\n pipeline.labels_placeholder: training_y})\r\n training_loss = 0\r\n steps = 0\r\n training_state = None\r\n avg_loss = []\r\n accuracies = []\r\n if epoch >0 and checkpoint:\r\n self.saver.save(sess, checkpoint)\r\n print(\"Saving checkpoint for epoch\", epoch)\r\n\r\n while True:\r\n try:\r\n steps += 1\r\n batch_x, batch_y = sess.run(pipeline.next_element_train)\r\n feed_dict={self.x: batch_x, self.y: batch_y,\r\n self.dropout: dropout}\r\n\r\n training_loss_, _, accuracy = sess.run([total_loss,\r\n train_step,\r\n model_accuracy],\r\n feed_dict)\r\n avg_loss.append(training_loss_)\r\n accuracies.append(accuracy)\r\n if steps%100 == 0:\r\n print(\"Avg training_loss_ for Epoh {} step {} =\".format(epoch, steps), tf.reduce_mean(avg_loss).eval())\r\n avg_loss = []\r\n accuracies = []\r\n\r\n except tf.errors.OutOfRangeError:\r\n print(\"End of training dataset.\")\r\n print(\"Avg accuracy for Epoch {} step {} =\".format(epoch, steps), tf.reduce_mean(accuracies).eval())\r\n if store_accuracies:\r\n training_accuracies.append(tf.reduce_mean(accuracies).eval())\r\n accuracies = []\r\n break\r\n\r\n #Print Validation Accuracy per Epoch\r\n sess.run(pipeline.iterator_val.initializer, feed_dict={pipeline.features_placeholder: validation_x,\r\n pipeline.labels_placeholder: validation_y})\r\n val_accuracies = []\r\n while True:\r\n try:\r\n val_x, val_y = sess.run(pipeline.next_element_val)\r\n feed_dict={self.x: val_x, self.y: val_y}\r\n accuracy = sess.run(model_accuracy, feed_dict)\r\n val_accuracies.append(accuracy)\r\n except tf.errors.OutOfRangeError:\r\n print(\"Validation Accuracy for epoch {} is \".format(epoch), tf.reduce_mean(val_accuracies).eval())\r\n if store_accuracies:\r\n validation_accuracies.append(tf.reduce_mean(val_accuracies).eval())\r\n break\r\n\r\n end_time = time.time()\r\n total_time = end_time - start_time\r\n print(\"Finished training network.\")\r\n print(\"Time to train network: {}s\".format(total_time))\r\n if store_accuracies:\r\n pickle.dump((training_accuracies, validation_accuracies), open( \"accuracies.p\", \"wb\" ) )\r\n print(\"Pickled Accuracies\")\r\n\r\n if save:\r\n self.saver.save(sess, save)\r\n print(\"Model is saved in\", save)\r\n\r\n \r\n\r\n\r\nclass data_pipeline(object):\r\n def __init__(self, batch_size, shuffle_buffer_size):\r\n \"\"\"\r\n Pipeline Object to shuffle and split data into batches before feeding into neural network\r\n :param batch_size: Integer Value of the desired batch size\r\n :param shuffle_buffer_size: Buffer Size for shuffling dataset. See TensorFlow docs for mroe information\r\n \"\"\"\r\n self.features_placeholder = tf.placeholder(tf.int32)\r\n self.labels_placeholder = tf.placeholder(tf.int32)\r\n self.batch_size = batch_size\r\n self.dataset = tf.data.Dataset.from_tensor_slices((self.features_placeholder, self.labels_placeholder))\r\n\r\n #Train input pipeline\r\n self.dataset_train = self.dataset.shuffle(buffer_size=shuffle_buffer_size).batch(batch_size)\r\n self.iterator_train = self.dataset_train.make_initializable_iterator()\r\n self.next_element_train = self.iterator_train.get_next()\r\n\r\n #Val input pipeline\r\n self.dataset_val = self.dataset.batch(batch_size)\r\n self.iterator_val = self.dataset_val.make_initializable_iterator()\r\n self.next_element_val = self.iterator_val.get_next()\r\n\r\n\r\n" ]
[ [ "tensorflow.reshape", "tensorflow.variable_scope", "tensorflow.nn.dynamic_rnn", "tensorflow.matmul", "tensorflow.name_scope", "tensorflow.Variable", "tensorflow.global_variables_initializer", "tensorflow.train.cosine_decay_restarts", "tensorflow.nn.rnn_cell.LSTMCell", "tensorflow.constant", "tensorflow.transpose", "tensorflow.constant_initializer", "tensorflow.nn.rnn_cell.BasicRNNCell", "tensorflow.cast", "tensorflow.nn.rnn_cell.DropoutWrapper", "tensorflow.train.Saver", "tensorflow.nn.embedding_lookup", "tensorflow.placeholder", "tensorflow.nn.rnn_cell.GRUCell", "tensorflow.train.AdamOptimizer", "tensorflow.reduce_mean", "tensorflow.nn.softmax_cross_entropy_with_logits_v2", "tensorflow.argmax", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.get_variable" ] ]
wzthu/NeuronMotif
[ "0f7f786e4b75916039388824d04d2041747fd299" ]
[ "dcnn/demo/demo2/simu.py" ]
[ "import h5py\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\n\n\nimport keras\n\n\nimport h5py\nimport numpy as np\nfrom keras.layers import Input, Dense, Conv1D, MaxPooling2D, MaxPooling1D, BatchNormalization\nfrom keras.layers.core import Dropout, Activation, Flatten\nfrom keras.layers.merge import Concatenate\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.optimizers import Adam\nfrom keras.utils import multi_gpu_model\n\nfrom keras.regularizers import l1,l2, l1_l2\nfrom keras.constraints import MaxNorm\nfrom keras.optimizers import SGD\n\nfrom keras.activations import relu\n\n\nimport os\nimport tensorflow as tf\nimport keras.backend.tensorflow_backend as KTF\n\n\n\n\ninput_bp = 82\n\nbatch_size=128\n\n\n\n\nseqInput = Input(shape=(input_bp, 4), name='seqInput')\n\nseq = Conv1D(5, 7)(seqInput)\nseq = BatchNormalization()(seq)\nseq = Activation('relu')(seq)\nseq = MaxPooling1D(2)(seq)\nseq = Conv1D(5, 3)(seq)\nseq = BatchNormalization()(seq)\nseq = Activation('relu')(seq)\nseq = MaxPooling1D(2)(seq)\nseq = Conv1D(6, 3)(seq)\nseq = BatchNormalization()(seq)\nseq = Activation('relu')(seq)\nseq = MaxPooling1D(2)(seq)\nseq = Conv1D(6, 3)(seq)\nseq = BatchNormalization()(seq)\nseq = Activation('relu')(seq)\nseq = MaxPooling1D(2)(seq)\nseq = Conv1D(1, 3)(seq)\nseq = BatchNormalization()(seq)\nseq = Activation('sigmoid')(seq)\nseq = Flatten()(seq)\n\nmodel = Model(inputs = [seqInput], outputs = [seq])\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\n\n#from keras.optimizers import RMSprop\nmodel.compile('adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n\nPWM0 = np.loadtxt('PWM')\n \nPWM = np.ones((4,input_bp))*0.25\nPWM1 = np.zeros((4,5))*0.25\nPWM1[1:2,:] = 0.5\n\nprint(PWM0.shape)\nprint(PWM.shape)\n\ndef pwm_to_sample(PWM, n = 1000):\n PWM /= PWM.sum(axis=0)\n PWM = PWM.T\n PWM = PWM[::-1,:]\n PWM = PWM[:,::-1]\n sample = np.zeros((n,PWM.shape[0],PWM.shape[1]))\n for i in range(n):\n for j in range(sample.shape[1]):\n sample[i,j,np.random.choice(4,1,p=PWM[j,:])] = 1\n return sample\n\nsize = 10000\n\nsp0 = pwm_to_sample(PWM0,n=size)\nsp1 = pwm_to_sample(PWM0,n=size)\nsp2 = pwm_to_sample(PWM0,n=size)\nsp3 = pwm_to_sample(PWM1,n=size)\nsp4 = pwm_to_sample(PWM0,n=size)\nspp = pwm_to_sample(PWM,n=size)\nspn = pwm_to_sample(PWM,n=size)\npos0 = np.random.randint(0,16,size)\npos1 = np.random.randint(44,60,size)\npos2 = np.r_[np.random.randint(0,16,int(size/2)),np.random.randint(46,62,int(size/2))]\npos4 = np.random.randint(17,45,size)\npos3 = np.random.randint(0,76,size)\n\nprint(sp0.shape)\nprint(sp1.shape)\nprint(spp.shape)\n\n\nfor i in range(size):\n spp[i,pos0[i]:(pos0[i]+PWM0.shape[1]),:] = sp0[i,:,:]\n spp[i,pos1[i]:(pos1[i]+PWM0.shape[1]),:] = sp1[i,:,:] \n\nfor i in range(size):\n spn[i,pos2[i]:(pos2[i]+PWM0.shape[1]),:] = sp2[i,:,:]\n spn[i,pos4[i]:(pos4[i]+PWM0.shape[1]),:] = sp4[i,:,:]\n# spn[i,pos3[i]:(pos3[i]+PWM1.shape[1]),:] = sp3[i,:,:]\n\nsp = np.concatenate([spp,spn],axis=0)\n\nlabel = np.r_[np.ones(size),np.zeros(size)] \n\ncallbacks=[]\ncallbacks.append(ModelCheckpoint(filepath='weight.hdf5',save_best_only=True))\ncallbacks.append(EarlyStopping(patience=15))\n\n\nhistory = model.fit(x= sp, y=label, epochs=100,validation_split=0.1,callbacks=callbacks) \n\n\nhistory_dict=history.history\nloss_values = history_dict['loss']\nval_loss_values=history_dict['val_loss']\nplt.figure()\nplt.plot(loss_values,'bo',label='training loss')\nplt.plot(val_loss_values,'r',label='val training loss')\n\nplt.savefig('history.pdf')\n#rs = model.predict(oh)[0,:]\n\n\nwith h5py.File('history.h5','w') as f:\n f['loss_values'] =loss_values\n f['val_loss'] = val_loss_values\n f['sample'] = sp\n f['label'] = label\n" ]
[ [ "numpy.ones", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "numpy.random.choice", "matplotlib.use", "matplotlib.pyplot.plot", "numpy.concatenate", "numpy.random.randint", "numpy.loadtxt" ] ]
pally2409/viral-diseases-simulator
[ "488168a481c277d99d758d2a9851df6524a9a57b" ]
[ "src/movements.py" ]
[ "'''\nCreated on Nov 29, 2020\n@author: manik\n'''\n'''\nFile with classes and code which control how a particular person\nwill move and to where\n'''\nfrom src.population import Population\nimport numpy as np\nimport src.person_properties_util as idx\n\nclass Movement():\n \"\"\"\n Class providing abstraction into each movement of the population\n \"\"\" \n \n def update_persons(self, persons: np.ndarray, size: int, speed: float = 0.1, heading_update_chance: float = 0.02) -> np.ndarray:\n \"\"\"\n Randomly updates/initializes the destination each person is headed to and corresponding speed randomly\n\n Parameters\n ----------\n person : np.ndarray\n The NumPy array containing the details of the persons to be updated\n size : int\n The size of the array of the persons to be updated to \n speed : float, optional\n Mean of the speed to be generated randomly, by default 0.1\n heading_update_chance : float, optional\n The odds of updating the destination of each person, by default 0.02\n\n Returns\n -------\n np.ndarray\n The upated NumPy array with updated values\n \"\"\" \n\n #For updating the x position \n #Generate a random array with update chance for each person in the population \n update = np.random.random(size=(size,))\n\n #Get the persons in the population who have a lower or equal to chance of getting updated in this epoch\n shp = update[update <= heading_update_chance].shape\n\n #Update the position for the direction in which they are heading\n persons[:,idx.x_dir][update <= heading_update_chance] = np.random.normal(loc = 0, scale = 1/3, size = shp)\n\n #For updating the y position, do the same\n update = np.random.random(size=(size,))\n shp = update[update <= heading_update_chance].shape\n persons[:,idx.y_dir][update <= heading_update_chance] = np.random.normal(loc = 0, scale = 1/3, size = shp)\n \n #Update the speed by generating a random normal distribution using the argument speed as the parameter\n update = np.random.random(size=(size,))\n shp = update[update <= heading_update_chance].shape\n persons[:,idx.speed][update <= heading_update_chance] = np.random.normal(loc = speed, scale = speed / 3, size = shp)\n persons[:,idx.speed] = np.clip(persons[:,idx.speed], a_min=0.0005, a_max=0.01)\n\n #Return the updated array\n return persons\n\n \n def out_of_bounds(self, persons: np.ndarray, xbounds, ybounds):\n \"\"\"\n Check if the individual is heading out of bounds of the specified bounds.\n\n Parameters\n ----------\n person : np.ndarray\n The NumPy array containing the details of the individuals\n xbounds : list\n List containing bounds for X axis.\n ybounds : list\n List containing bounds for Y axis.\n\n Returns\n -------\n np.ndarray\n The upated NumPy array with updated values\n \"\"\" \n\n # Store shape of list of people who are heading out of bounds based on X bound [0]\n shp = persons[:,4][(persons[:,2] <= xbounds[:,0]) &\n (persons[:,4] < 0)].shape\n # Update them randomly using a normal distribution\n persons[:,4][(persons[:,2] <= xbounds[:,0]) &\n (persons[:,4] < 0)] = np.clip(np.random.normal(loc = 0.5, \n scale = 0.5/3,\n size = shp),\n a_min = 0.05, a_max = 1)\n\n # Store shape of list of people who are heading out of bounds based on X bound [1]\n shp = persons[:,4][(persons[:,2] >= xbounds[:,1]) &\n (persons[:,4] > 0)].shape\n # Update them randomly using a normal distribution\n persons[:,4][(persons[:,2] >= xbounds[:,1]) &\n (persons[:,4] > 0)] = np.clip(-np.random.normal(loc = 0.5, \n scale = 0.5/3,\n size = shp),\n a_min = -1, a_max = -0.05)\n\n # Store shape of list of people who are heading out of bounds based on Y bound [0]\n shp = persons[:,5][(persons[:,3] <= ybounds[:,0]) &\n (persons[:,5] < 0)].shape \n # Update them randomly using a normal distribution \n persons[:,5][(persons[:,3] <= ybounds[:,0]) &\n (persons[:,5] < 0)] = np.clip(np.random.normal(loc = 0.5, \n scale = 0.5/3,\n size = shp),\n a_min = 0.05, a_max = 1)\n\n # Store shape of list of people who are heading out of bounds based on Y bound [1]\n shp = persons[:,5][(persons[:,3] >= ybounds[:,1]) &\n (persons[:,5] > 0)].shape\n # Update them randomly using a normal distribution\n persons[:,5][(persons[:,3] >= ybounds[:,1]) &\n (persons[:,5] > 0)] = np.clip(-np.random.normal(loc = 0.5, \n scale = 0.5/3,\n size = shp),\n a_min = -1, a_max = -0.05)\n \n return persons\n\n def update_pop(self, persons):\n \"\"\"\n Update function to move people physically in the graph.\n This function adds the X and Y direction value to the current postion of\n the individual to move them.\n\n Parameters\n ----------\n person : np.ndarray\n The NumPy array containing the details of the persons to be updated\n \n Returns\n -------\n np.ndarray\n The upated NumPy array with updated values\n \"\"\" \n filter = (persons[:, idx.current_state] != 3) & (persons[:, idx.social_distance] == 0)\n \n\n #x\n persons[:,2][filter] = persons[:,2][filter] + (persons[:,4][filter] * persons[:,6][filter])\n #y\n persons[:,3][filter] = persons[:,3][filter] + (persons [:,5][filter] * persons[:,6][filter])\n\n return persons\n" ]
[ [ "numpy.random.random", "numpy.clip", "numpy.random.normal" ] ]
hunterowens/pandas
[ "bb468f86d57f4eb0e65d75c3161d9e3209ea2c05" ]
[ "pandas/tests/test_multilevel.py" ]
[ "# -*- coding: utf-8 -*-\n# pylint: disable-msg=W0612,E1101,W0141\nimport datetime\nimport itertools\nimport nose\n\nfrom numpy.random import randn\nimport numpy as np\n\nfrom pandas.core.index import Index, MultiIndex\nfrom pandas import Panel, DataFrame, Series, notnull, isnull, Timestamp\n\nfrom pandas.util.testing import (assert_almost_equal,\n assert_series_equal,\n assert_frame_equal,\n assertRaisesRegexp)\nimport pandas.core.common as com\nimport pandas.util.testing as tm\nfrom pandas.compat import (range, lrange, StringIO, lzip, u,\n product as cart_product, zip)\nimport pandas as pd\n\nimport pandas.index as _index\n\n\nclass TestMultiLevel(tm.TestCase):\n\n _multiprocess_can_split_ = True\n\n def setUp(self):\n import warnings\n warnings.filterwarnings(action='ignore', category=FutureWarning)\n\n index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],\n ['one', 'two', 'three']],\n labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],\n [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],\n names=['first', 'second'])\n self.frame = DataFrame(np.random.randn(10, 3), index=index,\n columns=Index(['A', 'B', 'C'], name='exp'))\n\n self.single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']],\n labels=[[0, 1, 2, 3]],\n names=['first'])\n\n # create test series object\n arrays = [['bar', 'bar', 'baz', 'baz', 'qux', 'qux', 'foo', 'foo'],\n ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]\n tuples = lzip(*arrays)\n index = MultiIndex.from_tuples(tuples)\n s = Series(randn(8), index=index)\n s[3] = np.NaN\n self.series = s\n\n tm.N = 100\n self.tdf = tm.makeTimeDataFrame()\n self.ymd = self.tdf.groupby([lambda x: x.year, lambda x: x.month,\n lambda x: x.day]).sum()\n\n # use Int64Index, to make sure things work\n self.ymd.index.set_levels([lev.astype('i8')\n for lev in self.ymd.index.levels],\n inplace=True)\n self.ymd.index.set_names(['year', 'month', 'day'],\n inplace=True)\n\n def test_append(self):\n a, b = self.frame[:5], self.frame[5:]\n\n result = a.append(b)\n tm.assert_frame_equal(result, self.frame)\n\n result = a['A'].append(b['A'])\n tm.assert_series_equal(result, self.frame['A'])\n\n def test_append_index(self):\n tm._skip_if_no_pytz()\n\n idx1 = Index([1.1, 1.2, 1.3])\n idx2 = pd.date_range('2011-01-01', freq='D', periods=3, tz='Asia/Tokyo')\n idx3 = Index(['A', 'B', 'C'])\n\n midx_lv2 = MultiIndex.from_arrays([idx1, idx2])\n midx_lv3 = MultiIndex.from_arrays([idx1, idx2, idx3])\n\n result = idx1.append(midx_lv2)\n\n # GH 7112\n import pytz\n tz = pytz.timezone('Asia/Tokyo')\n expected_tuples = [(1.1, datetime.datetime(2011, 1, 1, tzinfo=tz)),\n (1.2, datetime.datetime(2011, 1, 2, tzinfo=tz)),\n (1.3, datetime.datetime(2011, 1, 3, tzinfo=tz))]\n expected = Index([1.1, 1.2, 1.3] + expected_tuples)\n self.assert_(result.equals(expected))\n\n result = midx_lv2.append(idx1)\n expected = Index(expected_tuples + [1.1, 1.2, 1.3])\n self.assert_(result.equals(expected))\n\n result = midx_lv2.append(midx_lv2)\n expected = MultiIndex.from_arrays([idx1.append(idx1), idx2.append(idx2)])\n self.assert_(result.equals(expected))\n\n result = midx_lv2.append(midx_lv3)\n self.assert_(result.equals(expected))\n\n result = midx_lv3.append(midx_lv2)\n expected = Index._simple_new(\n np.array([(1.1, datetime.datetime(2011, 1, 1, tzinfo=tz), 'A'),\n (1.2, datetime.datetime(2011, 1, 2, tzinfo=tz), 'B'),\n (1.3, datetime.datetime(2011, 1, 3, tzinfo=tz), 'C')]\n + expected_tuples), None)\n self.assert_(result.equals(expected))\n\n def test_dataframe_constructor(self):\n multi = DataFrame(np.random.randn(4, 4),\n index=[np.array(['a', 'a', 'b', 'b']),\n np.array(['x', 'y', 'x', 'y'])])\n tm.assert_isinstance(multi.index, MultiIndex)\n self.assertNotIsInstance(multi.columns, MultiIndex)\n\n multi = DataFrame(np.random.randn(4, 4),\n columns=[['a', 'a', 'b', 'b'],\n ['x', 'y', 'x', 'y']])\n tm.assert_isinstance(multi.columns, MultiIndex)\n\n def test_series_constructor(self):\n multi = Series(1., index=[np.array(['a', 'a', 'b', 'b']),\n np.array(['x', 'y', 'x', 'y'])])\n tm.assert_isinstance(multi.index, MultiIndex)\n\n multi = Series(1., index=[['a', 'a', 'b', 'b'],\n ['x', 'y', 'x', 'y']])\n tm.assert_isinstance(multi.index, MultiIndex)\n\n multi = Series(lrange(4), index=[['a', 'a', 'b', 'b'],\n ['x', 'y', 'x', 'y']])\n tm.assert_isinstance(multi.index, MultiIndex)\n\n def test_reindex_level(self):\n # axis=0\n month_sums = self.ymd.sum(level='month')\n result = month_sums.reindex(self.ymd.index, level=1)\n expected = self.ymd.groupby(level='month').transform(np.sum)\n\n assert_frame_equal(result, expected)\n\n # Series\n result = month_sums['A'].reindex(self.ymd.index, level=1)\n expected = self.ymd['A'].groupby(level='month').transform(np.sum)\n assert_series_equal(result, expected)\n\n # axis=1\n month_sums = self.ymd.T.sum(axis=1, level='month')\n result = month_sums.reindex(columns=self.ymd.index, level=1)\n expected = self.ymd.groupby(level='month').transform(np.sum).T\n assert_frame_equal(result, expected)\n\n def test_binops_level(self):\n def _check_op(opname):\n op = getattr(DataFrame, opname)\n month_sums = self.ymd.sum(level='month')\n result = op(self.ymd, month_sums, level='month')\n\n broadcasted = self.ymd.groupby(level='month').transform(np.sum)\n expected = op(self.ymd, broadcasted)\n assert_frame_equal(result, expected)\n\n # Series\n op = getattr(Series, opname)\n result = op(self.ymd['A'], month_sums['A'], level='month')\n broadcasted = self.ymd['A'].groupby(\n level='month').transform(np.sum)\n expected = op(self.ymd['A'], broadcasted)\n assert_series_equal(result, expected)\n\n _check_op('sub')\n _check_op('add')\n _check_op('mul')\n _check_op('div')\n\n def test_pickle(self):\n\n def _test_roundtrip(frame):\n unpickled = self.round_trip_pickle(frame)\n assert_frame_equal(frame, unpickled)\n\n _test_roundtrip(self.frame)\n _test_roundtrip(self.frame.T)\n _test_roundtrip(self.ymd)\n _test_roundtrip(self.ymd.T)\n\n def test_reindex(self):\n reindexed = self.frame.ix[[('foo', 'one'), ('bar', 'one')]]\n expected = self.frame.ix[[0, 3]]\n assert_frame_equal(reindexed, expected)\n\n def test_reindex_preserve_levels(self):\n new_index = self.ymd.index[::10]\n chunk = self.ymd.reindex(new_index)\n self.assertIs(chunk.index, new_index)\n\n chunk = self.ymd.ix[new_index]\n self.assertIs(chunk.index, new_index)\n\n ymdT = self.ymd.T\n chunk = ymdT.reindex(columns=new_index)\n self.assertIs(chunk.columns, new_index)\n\n chunk = ymdT.ix[:, new_index]\n self.assertIs(chunk.columns, new_index)\n\n def test_sort_index_preserve_levels(self):\n result = self.frame.sort_index()\n self.assertEqual(result.index.names, self.frame.index.names)\n\n def test_sorting_repr_8017(self):\n\n np.random.seed(0)\n data = np.random.randn(3,4)\n\n for gen, extra in [([1.,3.,2.,5.],4.),\n ([1,3,2,5],4),\n ([Timestamp('20130101'),Timestamp('20130103'),Timestamp('20130102'),Timestamp('20130105')],Timestamp('20130104')),\n (['1one','3one','2one','5one'],'4one')]:\n columns = MultiIndex.from_tuples([('red', i) for i in gen])\n df = DataFrame(data, index=list('def'), columns=columns)\n df2 = pd.concat([df,DataFrame('world',\n index=list('def'),\n columns=MultiIndex.from_tuples([('red', extra)]))],axis=1)\n\n # check that the repr is good\n # make sure that we have a correct sparsified repr\n # e.g. only 1 header of read\n self.assertEqual(str(df2).splitlines()[0].split(),['red'])\n\n # GH 8017\n # sorting fails after columns added\n\n # construct single-dtype then sort\n result = df.copy().sort_index(axis=1)\n expected = df.iloc[:,[0,2,1,3]]\n assert_frame_equal(result, expected)\n\n result = df2.sort_index(axis=1)\n expected = df2.iloc[:,[0,2,1,4,3]]\n assert_frame_equal(result, expected)\n\n # setitem then sort\n result = df.copy()\n result[('red',extra)] = 'world'\n result = result.sort_index(axis=1)\n assert_frame_equal(result, expected)\n\n def test_repr_to_string(self):\n repr(self.frame)\n repr(self.ymd)\n repr(self.frame.T)\n repr(self.ymd.T)\n\n buf = StringIO()\n self.frame.to_string(buf=buf)\n self.ymd.to_string(buf=buf)\n self.frame.T.to_string(buf=buf)\n self.ymd.T.to_string(buf=buf)\n\n def test_repr_name_coincide(self):\n index = MultiIndex.from_tuples([('a', 0, 'foo'), ('b', 1, 'bar')],\n names=['a', 'b', 'c'])\n\n df = DataFrame({'value': [0, 1]}, index=index)\n\n lines = repr(df).split('\\n')\n self.assertTrue(lines[2].startswith('a 0 foo'))\n\n def test_getitem_simple(self):\n df = self.frame.T\n\n col = df['foo', 'one']\n assert_almost_equal(col.values, df.values[:, 0])\n self.assertRaises(KeyError, df.__getitem__, ('foo', 'four'))\n self.assertRaises(KeyError, df.__getitem__, 'foobar')\n\n def test_series_getitem(self):\n s = self.ymd['A']\n\n result = s[2000, 3]\n result2 = s.ix[2000, 3]\n expected = s.reindex(s.index[42:65])\n expected.index = expected.index.droplevel(0).droplevel(0)\n assert_series_equal(result, expected)\n\n result = s[2000, 3, 10]\n expected = s[49]\n self.assertEqual(result, expected)\n\n # fancy\n result = s.ix[[(2000, 3, 10), (2000, 3, 13)]]\n expected = s.reindex(s.index[49:51])\n assert_series_equal(result, expected)\n\n # key error\n self.assertRaises(KeyError, s.__getitem__, (2000, 3, 4))\n\n def test_series_getitem_corner(self):\n s = self.ymd['A']\n\n # don't segfault, GH #495\n # out of bounds access\n self.assertRaises(IndexError, s.__getitem__, len(self.ymd))\n\n # generator\n result = s[(x > 0 for x in s)]\n expected = s[s > 0]\n assert_series_equal(result, expected)\n\n def test_series_setitem(self):\n s = self.ymd['A']\n\n s[2000, 3] = np.nan\n self.assertTrue(isnull(s.values[42:65]).all())\n self.assertTrue(notnull(s.values[:42]).all())\n self.assertTrue(notnull(s.values[65:]).all())\n\n s[2000, 3, 10] = np.nan\n self.assertTrue(isnull(s[49]))\n\n def test_series_slice_partial(self):\n pass\n\n def test_frame_getitem_setitem_boolean(self):\n df = self.frame.T.copy()\n values = df.values\n\n result = df[df > 0]\n expected = df.where(df > 0)\n assert_frame_equal(result, expected)\n\n df[df > 0] = 5\n values[values > 0] = 5\n assert_almost_equal(df.values, values)\n\n df[df == 5] = 0\n values[values == 5] = 0\n assert_almost_equal(df.values, values)\n\n # a df that needs alignment first\n df[df[:-1] < 0] = 2\n np.putmask(values[:-1], values[:-1] < 0, 2)\n assert_almost_equal(df.values, values)\n\n with assertRaisesRegexp(TypeError, 'boolean values only'):\n df[df * 0] = 2\n\n def test_frame_getitem_setitem_slice(self):\n # getitem\n result = self.frame.ix[:4]\n expected = self.frame[:4]\n assert_frame_equal(result, expected)\n\n # setitem\n cp = self.frame.copy()\n cp.ix[:4] = 0\n\n self.assertTrue((cp.values[:4] == 0).all())\n self.assertTrue((cp.values[4:] != 0).all())\n\n def test_frame_getitem_setitem_multislice(self):\n levels = [['t1', 't2'], ['a', 'b', 'c']]\n labels = [[0, 0, 0, 1, 1], [0, 1, 2, 0, 1]]\n midx = MultiIndex(labels=labels, levels=levels, names=[None, 'id'])\n df = DataFrame({'value': [1, 2, 3, 7, 8]}, index=midx)\n\n result = df.ix[:, 'value']\n assert_series_equal(df['value'], result)\n\n result = df.ix[1:3, 'value']\n assert_series_equal(df['value'][1:3], result)\n\n result = df.ix[:, :]\n assert_frame_equal(df, result)\n\n result = df\n df.ix[:, 'value'] = 10\n result['value'] = 10\n assert_frame_equal(df, result)\n\n df.ix[:, :] = 10\n assert_frame_equal(df, result)\n\n def test_frame_getitem_multicolumn_empty_level(self):\n f = DataFrame({'a': ['1', '2', '3'],\n 'b': ['2', '3', '4']})\n f.columns = [['level1 item1', 'level1 item2'],\n ['', 'level2 item2'],\n ['level3 item1', 'level3 item2']]\n\n result = f['level1 item1']\n expected = DataFrame([['1'], ['2'], ['3']], index=f.index,\n columns=['level3 item1'])\n assert_frame_equal(result, expected)\n\n def test_frame_setitem_multi_column(self):\n df = DataFrame(randn(10, 4), columns=[['a', 'a', 'b', 'b'],\n [0, 1, 0, 1]])\n\n cp = df.copy()\n cp['a'] = cp['b']\n assert_frame_equal(cp['a'], cp['b'])\n\n # set with ndarray\n cp = df.copy()\n cp['a'] = cp['b'].values\n assert_frame_equal(cp['a'], cp['b'])\n\n #----------------------------------------\n # #1803\n columns = MultiIndex.from_tuples([('A', '1'), ('A', '2'), ('B', '1')])\n df = DataFrame(index=[1, 3, 5], columns=columns)\n\n # Works, but adds a column instead of updating the two existing ones\n df['A'] = 0.0 # Doesn't work\n self.assertTrue((df['A'].values == 0).all())\n\n # it broadcasts\n df['B', '1'] = [1, 2, 3]\n df['A'] = df['B', '1']\n assert_series_equal(df['A', '1'], df['B', '1'])\n assert_series_equal(df['A', '2'], df['B', '1'])\n\n def test_getitem_tuple_plus_slice(self):\n # GH #671\n df = DataFrame({'a': lrange(10),\n 'b': lrange(10),\n 'c': np.random.randn(10),\n 'd': np.random.randn(10)})\n\n idf = df.set_index(['a', 'b'])\n\n result = idf.ix[(0, 0), :]\n expected = idf.ix[0, 0]\n expected2 = idf.xs((0, 0))\n\n assert_series_equal(result, expected)\n assert_series_equal(result, expected2)\n\n def test_getitem_setitem_tuple_plus_columns(self):\n # GH #1013\n\n df = self.ymd[:5]\n\n result = df.ix[(2000, 1, 6), ['A', 'B', 'C']]\n expected = df.ix[2000, 1, 6][['A', 'B', 'C']]\n assert_series_equal(result, expected)\n\n def test_getitem_multilevel_index_tuple_unsorted(self):\n index_columns = list(\"abc\")\n df = DataFrame([[0, 1, 0, \"x\"], [0, 0, 1, \"y\"]],\n columns=index_columns + [\"data\"])\n df = df.set_index(index_columns)\n query_index = df.index[:1]\n rs = df.ix[query_index, \"data\"]\n xp = Series(['x'], index=MultiIndex.from_tuples([(0, 1, 0)]))\n assert_series_equal(rs, xp)\n\n def test_xs(self):\n xs = self.frame.xs(('bar', 'two'))\n xs2 = self.frame.ix[('bar', 'two')]\n\n assert_series_equal(xs, xs2)\n assert_almost_equal(xs.values, self.frame.values[4])\n\n # GH 6574\n # missing values in returned index should be preserrved\n acc = [\n ('a','abcde',1),\n ('b','bbcde',2),\n ('y','yzcde',25),\n ('z','xbcde',24),\n ('z',None,26),\n ('z','zbcde',25),\n ('z','ybcde',26),\n ]\n df = DataFrame(acc, columns=['a1','a2','cnt']).set_index(['a1','a2'])\n expected = DataFrame({ 'cnt' : [24,26,25,26] }, index=Index(['xbcde',np.nan,'zbcde','ybcde'],name='a2'))\n\n result = df.xs('z',level='a1')\n assert_frame_equal(result, expected)\n\n def test_xs_partial(self):\n result = self.frame.xs('foo')\n result2 = self.frame.ix['foo']\n expected = self.frame.T['foo'].T\n assert_frame_equal(result, expected)\n assert_frame_equal(result, result2)\n\n result = self.ymd.xs((2000, 4))\n expected = self.ymd.ix[2000, 4]\n assert_frame_equal(result, expected)\n\n # ex from #1796\n index = MultiIndex(levels=[['foo', 'bar'], ['one', 'two'], [-1, 1]],\n labels=[[0, 0, 0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 0, 0, 1, 1],\n [0, 1, 0, 1, 0, 1, 0, 1]])\n df = DataFrame(np.random.randn(8, 4), index=index,\n columns=list('abcd'))\n\n result = df.xs(['foo', 'one'])\n expected = df.ix['foo', 'one']\n assert_frame_equal(result, expected)\n\n def test_xs_level(self):\n result = self.frame.xs('two', level='second')\n expected = self.frame[self.frame.index.get_level_values(1) == 'two']\n expected.index = expected.index.droplevel(1)\n\n assert_frame_equal(result, expected)\n\n index = MultiIndex.from_tuples([('x', 'y', 'z'), ('a', 'b', 'c'),\n ('p', 'q', 'r')])\n df = DataFrame(np.random.randn(3, 5), index=index)\n result = df.xs('c', level=2)\n expected = df[1:2]\n expected.index = expected.index.droplevel(2)\n assert_frame_equal(result, expected)\n\n # this is a copy in 0.14\n result = self.frame.xs('two', level='second')\n\n # setting this will give a SettingWithCopyError\n # as we are trying to write a view\n def f(x):\n x[:] = 10\n self.assertRaises(com.SettingWithCopyError, f, result)\n\n def test_xs_level_multiple(self):\n from pandas import read_table\n text = \"\"\" A B C D E\none two three four\na b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640\na q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744\nx q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838\"\"\"\n\n df = read_table(StringIO(text), sep='\\s+', engine='python')\n\n result = df.xs(('a', 4), level=['one', 'four'])\n expected = df.xs('a').xs(4, level='four')\n assert_frame_equal(result, expected)\n\n # this is a copy in 0.14\n result = df.xs(('a', 4), level=['one', 'four'])\n\n # setting this will give a SettingWithCopyError\n # as we are trying to write a view\n def f(x):\n x[:] = 10\n self.assertRaises(com.SettingWithCopyError, f, result)\n\n # GH2107\n dates = lrange(20111201, 20111205)\n ids = 'abcde'\n idx = MultiIndex.from_tuples([x for x in cart_product(dates, ids)])\n idx.names = ['date', 'secid']\n df = DataFrame(np.random.randn(len(idx), 3), idx, ['X', 'Y', 'Z'])\n rs = df.xs(20111201, level='date')\n xp = df.ix[20111201, :]\n assert_frame_equal(rs, xp)\n\n def test_xs_level0(self):\n from pandas import read_table\n text = \"\"\" A B C D E\none two three four\na b 10.0032 5 -0.5109 -2.3358 -0.4645 0.05076 0.3640\na q 20 4 0.4473 1.4152 0.2834 1.00661 0.1744\nx q 30 3 -0.6662 -0.5243 -0.3580 0.89145 2.5838\"\"\"\n\n df = read_table(StringIO(text), sep='\\s+', engine='python')\n\n result = df.xs('a', level=0)\n expected = df.xs('a')\n self.assertEqual(len(result), 2)\n assert_frame_equal(result, expected)\n\n def test_xs_level_series(self):\n s = self.frame['A']\n result = s[:, 'two']\n expected = self.frame.xs('two', level=1)['A']\n assert_series_equal(result, expected)\n\n s = self.ymd['A']\n result = s[2000, 5]\n expected = self.ymd.ix[2000, 5]['A']\n assert_series_equal(result, expected)\n\n # not implementing this for now\n\n self.assertRaises(TypeError, s.__getitem__, (2000, slice(3, 4)))\n\n # result = s[2000, 3:4]\n # lv =s.index.get_level_values(1)\n # expected = s[(lv == 3) | (lv == 4)]\n # expected.index = expected.index.droplevel(0)\n # assert_series_equal(result, expected)\n\n # can do this though\n\n def test_get_loc_single_level(self):\n s = Series(np.random.randn(len(self.single_level)),\n index=self.single_level)\n for k in self.single_level.values:\n s[k]\n\n def test_getitem_toplevel(self):\n df = self.frame.T\n\n result = df['foo']\n expected = df.reindex(columns=df.columns[:3])\n expected.columns = expected.columns.droplevel(0)\n assert_frame_equal(result, expected)\n\n result = df['bar']\n result2 = df.ix[:, 'bar']\n\n expected = df.reindex(columns=df.columns[3:5])\n expected.columns = expected.columns.droplevel(0)\n assert_frame_equal(result, expected)\n assert_frame_equal(result, result2)\n\n def test_getitem_setitem_slice_integers(self):\n index = MultiIndex(levels=[[0, 1, 2], [0, 2]],\n labels=[[0, 0, 1, 1, 2, 2],\n [0, 1, 0, 1, 0, 1]])\n\n frame = DataFrame(np.random.randn(len(index), 4), index=index,\n columns=['a', 'b', 'c', 'd'])\n res = frame.ix[1:2]\n exp = frame.reindex(frame.index[2:])\n assert_frame_equal(res, exp)\n\n frame.ix[1:2] = 7\n self.assertTrue((frame.ix[1:2] == 7).values.all())\n\n series = Series(np.random.randn(len(index)), index=index)\n\n res = series.ix[1:2]\n exp = series.reindex(series.index[2:])\n assert_series_equal(res, exp)\n\n series.ix[1:2] = 7\n self.assertTrue((series.ix[1:2] == 7).values.all())\n\n def test_getitem_int(self):\n levels = [[0, 1], [0, 1, 2]]\n labels = [[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]]\n index = MultiIndex(levels=levels, labels=labels)\n\n frame = DataFrame(np.random.randn(6, 2), index=index)\n\n result = frame.ix[1]\n expected = frame[-3:]\n expected.index = expected.index.droplevel(0)\n assert_frame_equal(result, expected)\n\n # raises exception\n self.assertRaises(KeyError, frame.ix.__getitem__, 3)\n\n # however this will work\n result = self.frame.ix[2]\n expected = self.frame.xs(self.frame.index[2])\n assert_series_equal(result, expected)\n\n def test_getitem_partial(self):\n ymd = self.ymd.T\n result = ymd[2000, 2]\n\n expected = ymd.reindex(columns=ymd.columns[ymd.columns.labels[1] == 1])\n expected.columns = expected.columns.droplevel(0).droplevel(0)\n assert_frame_equal(result, expected)\n\n def test_getitem_slice_not_sorted(self):\n df = self.frame.sortlevel(1).T\n\n # buglet with int typechecking\n result = df.ix[:, :np.int32(3)]\n expected = df.reindex(columns=df.columns[:3])\n assert_frame_equal(result, expected)\n\n def test_setitem_change_dtype(self):\n dft = self.frame.T\n s = dft['foo', 'two']\n dft['foo', 'two'] = s > s.median()\n assert_series_equal(dft['foo', 'two'], s > s.median())\n # tm.assert_isinstance(dft._data.blocks[1].items, MultiIndex)\n\n reindexed = dft.reindex(columns=[('foo', 'two')])\n assert_series_equal(reindexed['foo', 'two'], s > s.median())\n\n def test_frame_setitem_ix(self):\n self.frame.ix[('bar', 'two'), 'B'] = 5\n self.assertEqual(self.frame.ix[('bar', 'two'), 'B'], 5)\n\n # with integer labels\n df = self.frame.copy()\n df.columns = lrange(3)\n df.ix[('bar', 'two'), 1] = 7\n self.assertEqual(df.ix[('bar', 'two'), 1], 7)\n\n def test_fancy_slice_partial(self):\n result = self.frame.ix['bar':'baz']\n expected = self.frame[3:7]\n assert_frame_equal(result, expected)\n\n result = self.ymd.ix[(2000, 2):(2000, 4)]\n lev = self.ymd.index.labels[1]\n expected = self.ymd[(lev >= 1) & (lev <= 3)]\n assert_frame_equal(result, expected)\n\n def test_getitem_partial_column_select(self):\n idx = MultiIndex(labels=[[0, 0, 0], [0, 1, 1], [1, 0, 1]],\n levels=[['a', 'b'], ['x', 'y'], ['p', 'q']])\n df = DataFrame(np.random.rand(3, 2), index=idx)\n\n result = df.ix[('a', 'y'), :]\n expected = df.ix[('a', 'y')]\n assert_frame_equal(result, expected)\n\n result = df.ix[('a', 'y'), [1, 0]]\n expected = df.ix[('a', 'y')][[1, 0]]\n assert_frame_equal(result, expected)\n\n self.assertRaises(KeyError, df.ix.__getitem__,\n (('a', 'foo'), slice(None, None)))\n\n def test_sortlevel(self):\n df = self.frame.copy()\n df.index = np.arange(len(df))\n assertRaisesRegexp(TypeError, 'hierarchical index', df.sortlevel, 0)\n\n # axis=1\n\n # series\n a_sorted = self.frame['A'].sortlevel(0)\n with assertRaisesRegexp(TypeError, 'hierarchical index'):\n self.frame.reset_index()['A'].sortlevel()\n\n # preserve names\n self.assertEqual(a_sorted.index.names, self.frame.index.names)\n\n # inplace\n rs = self.frame.copy()\n rs.sortlevel(0, inplace=True)\n assert_frame_equal(rs, self.frame.sortlevel(0))\n\n def test_sortlevel_large_cardinality(self):\n\n # #2684 (int64)\n index = MultiIndex.from_arrays([np.arange(4000)]*3)\n df = DataFrame(np.random.randn(4000), index=index, dtype = np.int64)\n\n # it works!\n result = df.sortlevel(0)\n self.assertTrue(result.index.lexsort_depth == 3)\n\n # #2684 (int32)\n index = MultiIndex.from_arrays([np.arange(4000)]*3)\n df = DataFrame(np.random.randn(4000), index=index, dtype = np.int32)\n\n # it works!\n result = df.sortlevel(0)\n self.assertTrue((result.dtypes.values == df.dtypes.values).all() == True)\n self.assertTrue(result.index.lexsort_depth == 3)\n\n def test_delevel_infer_dtype(self):\n tuples = [tuple for tuple in cart_product(['foo', 'bar'],\n [10, 20], [1.0, 1.1])]\n index = MultiIndex.from_tuples(tuples,\n names=['prm0', 'prm1', 'prm2'])\n df = DataFrame(np.random.randn(8, 3), columns=['A', 'B', 'C'],\n index=index)\n deleveled = df.reset_index()\n self.assertTrue(com.is_integer_dtype(deleveled['prm1']))\n self.assertTrue(com.is_float_dtype(deleveled['prm2']))\n\n def test_reset_index_with_drop(self):\n deleveled = self.ymd.reset_index(drop=True)\n self.assertEqual(len(deleveled.columns), len(self.ymd.columns))\n\n deleveled = self.series.reset_index()\n tm.assert_isinstance(deleveled, DataFrame)\n self.assertEqual(len(deleveled.columns),\n len(self.series.index.levels) + 1)\n\n deleveled = self.series.reset_index(drop=True)\n tm.assert_isinstance(deleveled, Series)\n\n def test_sortlevel_by_name(self):\n self.frame.index.names = ['first', 'second']\n result = self.frame.sortlevel(level='second')\n expected = self.frame.sortlevel(level=1)\n assert_frame_equal(result, expected)\n\n def test_sortlevel_mixed(self):\n sorted_before = self.frame.sortlevel(1)\n\n df = self.frame.copy()\n df['foo'] = 'bar'\n sorted_after = df.sortlevel(1)\n assert_frame_equal(sorted_before, sorted_after.drop(['foo'], axis=1))\n\n dft = self.frame.T\n sorted_before = dft.sortlevel(1, axis=1)\n dft['foo', 'three'] = 'bar'\n\n sorted_after = dft.sortlevel(1, axis=1)\n assert_frame_equal(sorted_before.drop([('foo', 'three')], axis=1),\n sorted_after.drop([('foo', 'three')], axis=1))\n\n def test_count_level(self):\n def _check_counts(frame, axis=0):\n index = frame._get_axis(axis)\n for i in range(index.nlevels):\n result = frame.count(axis=axis, level=i)\n expected = frame.groupby(axis=axis, level=i).count(axis=axis)\n expected = expected.reindex_like(result).astype('i8')\n assert_frame_equal(result, expected)\n\n self.frame.ix[1, [1, 2]] = np.nan\n self.frame.ix[7, [0, 1]] = np.nan\n self.ymd.ix[1, [1, 2]] = np.nan\n self.ymd.ix[7, [0, 1]] = np.nan\n\n _check_counts(self.frame)\n _check_counts(self.ymd)\n _check_counts(self.frame.T, axis=1)\n _check_counts(self.ymd.T, axis=1)\n\n # can't call with level on regular DataFrame\n df = tm.makeTimeDataFrame()\n assertRaisesRegexp(TypeError, 'hierarchical', df.count, level=0)\n\n self.frame['D'] = 'foo'\n result = self.frame.count(level=0, numeric_only=True)\n assert_almost_equal(result.columns, ['A', 'B', 'C'])\n\n def test_count_level_series(self):\n index = MultiIndex(levels=[['foo', 'bar', 'baz'],\n ['one', 'two', 'three', 'four']],\n labels=[[0, 0, 0, 2, 2],\n [2, 0, 1, 1, 2]])\n\n s = Series(np.random.randn(len(index)), index=index)\n\n result = s.count(level=0)\n expected = s.groupby(level=0).count()\n assert_series_equal(result.astype('f8'),\n expected.reindex(result.index).fillna(0))\n\n result = s.count(level=1)\n expected = s.groupby(level=1).count()\n assert_series_equal(result.astype('f8'),\n expected.reindex(result.index).fillna(0))\n\n def test_count_level_corner(self):\n s = self.frame['A'][:0]\n result = s.count(level=0)\n expected = Series(0, index=s.index.levels[0])\n assert_series_equal(result, expected)\n\n df = self.frame[:0]\n result = df.count(level=0)\n expected = DataFrame({}, index=s.index.levels[0],\n columns=df.columns).fillna(0).astype(np.int64)\n assert_frame_equal(result, expected)\n\n def test_get_level_number_out_of_bounds(self):\n with assertRaisesRegexp(IndexError, \"Too many levels\"):\n self.frame.index._get_level_number(2)\n with assertRaisesRegexp(IndexError, \"not a valid level number\"):\n self.frame.index._get_level_number(-3)\n\n def test_unstack(self):\n # just check that it works for now\n unstacked = self.ymd.unstack()\n unstacked2 = unstacked.unstack()\n\n # test that ints work\n unstacked = self.ymd.astype(int).unstack()\n\n # test that int32 work\n unstacked = self.ymd.astype(np.int32).unstack()\n\n def test_unstack_multiple_no_empty_columns(self):\n index = MultiIndex.from_tuples([(0, 'foo', 0), (0, 'bar', 0),\n (1, 'baz', 1), (1, 'qux', 1)])\n\n s = Series(np.random.randn(4), index=index)\n\n unstacked = s.unstack([1, 2])\n expected = unstacked.dropna(axis=1, how='all')\n assert_frame_equal(unstacked, expected)\n\n def test_stack(self):\n # regular roundtrip\n unstacked = self.ymd.unstack()\n restacked = unstacked.stack()\n assert_frame_equal(restacked, self.ymd)\n\n unlexsorted = self.ymd.sortlevel(2)\n\n unstacked = unlexsorted.unstack(2)\n restacked = unstacked.stack()\n assert_frame_equal(restacked.sortlevel(0), self.ymd)\n\n unlexsorted = unlexsorted[::-1]\n unstacked = unlexsorted.unstack(1)\n restacked = unstacked.stack().swaplevel(1, 2)\n assert_frame_equal(restacked.sortlevel(0), self.ymd)\n\n unlexsorted = unlexsorted.swaplevel(0, 1)\n unstacked = unlexsorted.unstack(0).swaplevel(0, 1, axis=1)\n restacked = unstacked.stack(0).swaplevel(1, 2)\n assert_frame_equal(restacked.sortlevel(0), self.ymd)\n\n # columns unsorted\n unstacked = self.ymd.unstack()\n unstacked = unstacked.sort(axis=1, ascending=False)\n restacked = unstacked.stack()\n assert_frame_equal(restacked, self.ymd)\n\n # more than 2 levels in the columns\n unstacked = self.ymd.unstack(1).unstack(1)\n\n result = unstacked.stack(1)\n expected = self.ymd.unstack()\n assert_frame_equal(result, expected)\n\n result = unstacked.stack(2)\n expected = self.ymd.unstack(1)\n assert_frame_equal(result, expected)\n\n result = unstacked.stack(0)\n expected = self.ymd.stack().unstack(1).unstack(1)\n assert_frame_equal(result, expected)\n\n # not all levels present in each echelon\n unstacked = self.ymd.unstack(2).ix[:, ::3]\n stacked = unstacked.stack().stack()\n ymd_stacked = self.ymd.stack()\n assert_series_equal(stacked, ymd_stacked.reindex(stacked.index))\n\n # stack with negative number\n result = self.ymd.unstack(0).stack(-2)\n expected = self.ymd.unstack(0).stack(0)\n\n def test_unstack_odd_failure(self):\n data = \"\"\"day,time,smoker,sum,len\nFri,Dinner,No,8.25,3.\nFri,Dinner,Yes,27.03,9\nFri,Lunch,No,3.0,1\nFri,Lunch,Yes,13.68,6\nSat,Dinner,No,139.63,45\nSat,Dinner,Yes,120.77,42\nSun,Dinner,No,180.57,57\nSun,Dinner,Yes,66.82,19\nThur,Dinner,No,3.0,1\nThur,Lunch,No,117.32,44\nThur,Lunch,Yes,51.51,17\"\"\"\n\n df = pd.read_csv(StringIO(data)).set_index(['day', 'time', 'smoker'])\n\n # it works, #2100\n result = df.unstack(2)\n\n recons = result.stack()\n assert_frame_equal(recons, df)\n\n def test_stack_mixed_dtype(self):\n df = self.frame.T\n df['foo', 'four'] = 'foo'\n df = df.sortlevel(1, axis=1)\n\n stacked = df.stack()\n assert_series_equal(stacked['foo'], df['foo'].stack())\n self.assertEqual(stacked['bar'].dtype, np.float_)\n\n def test_unstack_bug(self):\n df = DataFrame({'state': ['naive', 'naive', 'naive',\n 'activ', 'activ', 'activ'],\n 'exp': ['a', 'b', 'b', 'b', 'a', 'a'],\n 'barcode': [1, 2, 3, 4, 1, 3],\n 'v': ['hi', 'hi', 'bye', 'bye', 'bye', 'peace'],\n 'extra': np.arange(6.)})\n\n result = df.groupby(['state', 'exp', 'barcode', 'v']).apply(len)\n\n unstacked = result.unstack()\n restacked = unstacked.stack()\n assert_series_equal(restacked,\n result.reindex(restacked.index).astype(float))\n\n def test_stack_unstack_preserve_names(self):\n unstacked = self.frame.unstack()\n self.assertEqual(unstacked.index.name, 'first')\n self.assertEqual(unstacked.columns.names, ['exp', 'second'])\n\n restacked = unstacked.stack()\n self.assertEqual(restacked.index.names, self.frame.index.names)\n\n def test_unstack_level_name(self):\n result = self.frame.unstack('second')\n expected = self.frame.unstack(level=1)\n assert_frame_equal(result, expected)\n\n def test_stack_level_name(self):\n unstacked = self.frame.unstack('second')\n result = unstacked.stack('exp')\n expected = self.frame.unstack().stack(0)\n assert_frame_equal(result, expected)\n\n result = self.frame.stack('exp')\n expected = self.frame.stack()\n assert_series_equal(result, expected)\n\n def test_stack_unstack_multiple(self):\n unstacked = self.ymd.unstack(['year', 'month'])\n expected = self.ymd.unstack('year').unstack('month')\n assert_frame_equal(unstacked, expected)\n self.assertEqual(unstacked.columns.names,\n expected.columns.names)\n\n # series\n s = self.ymd['A']\n s_unstacked = s.unstack(['year', 'month'])\n assert_frame_equal(s_unstacked, expected['A'])\n\n restacked = unstacked.stack(['year', 'month'])\n restacked = restacked.swaplevel(0, 1).swaplevel(1, 2)\n restacked = restacked.sortlevel(0)\n\n assert_frame_equal(restacked, self.ymd)\n self.assertEqual(restacked.index.names, self.ymd.index.names)\n\n # GH #451\n unstacked = self.ymd.unstack([1, 2])\n expected = self.ymd.unstack(1).unstack(1).dropna(axis=1, how='all')\n assert_frame_equal(unstacked, expected)\n\n unstacked = self.ymd.unstack([2, 1])\n expected = self.ymd.unstack(2).unstack(1).dropna(axis=1, how='all')\n assert_frame_equal(unstacked, expected.ix[:, unstacked.columns])\n\n def test_stack_names_and_numbers(self):\n unstacked = self.ymd.unstack(['year', 'month'])\n\n # Can't use mixture of names and numbers to stack\n with assertRaisesRegexp(ValueError, \"level should contain\"):\n unstacked.stack([0, 'month'])\n\n def test_stack_multiple_out_of_bounds(self):\n # nlevels == 3\n unstacked = self.ymd.unstack(['year', 'month'])\n\n with assertRaisesRegexp(IndexError, \"Too many levels\"):\n unstacked.stack([2, 3])\n with assertRaisesRegexp(IndexError, \"not a valid level number\"):\n unstacked.stack([-4, -3])\n\n def test_unstack_period_series(self):\n # GH 4342\n idx1 = pd.PeriodIndex(['2013-01', '2013-01', '2013-02', '2013-02',\n '2013-03', '2013-03'], freq='M', name='period')\n idx2 = Index(['A', 'B'] * 3, name='str')\n value = [1, 2, 3, 4, 5, 6]\n\n idx = MultiIndex.from_arrays([idx1, idx2])\n s = Series(value, index=idx)\n\n result1 = s.unstack()\n result2 = s.unstack(level=1)\n result3 = s.unstack(level=0)\n\n e_idx = pd.PeriodIndex(['2013-01', '2013-02', '2013-03'], freq='M', name='period')\n expected = DataFrame({'A': [1, 3, 5], 'B': [2, 4, 6]}, index=e_idx,\n columns=['A', 'B'])\n expected.columns.name = 'str'\n\n assert_frame_equal(result1, expected)\n assert_frame_equal(result2, expected)\n assert_frame_equal(result3, expected.T)\n\n idx1 = pd.PeriodIndex(['2013-01', '2013-01', '2013-02', '2013-02',\n '2013-03', '2013-03'], freq='M', name='period1')\n\n idx2 = pd.PeriodIndex(['2013-12', '2013-11', '2013-10', '2013-09',\n '2013-08', '2013-07'], freq='M', name='period2')\n idx = pd.MultiIndex.from_arrays([idx1, idx2])\n s = Series(value, index=idx)\n\n result1 = s.unstack()\n result2 = s.unstack(level=1)\n result3 = s.unstack(level=0)\n\n e_idx = pd.PeriodIndex(['2013-01', '2013-02', '2013-03'], freq='M', name='period1')\n e_cols = pd.PeriodIndex(['2013-07', '2013-08', '2013-09', '2013-10',\n '2013-11', '2013-12'], freq='M', name='period2')\n expected = DataFrame([[np.nan, np.nan, np.nan, np.nan, 2, 1],\n [np.nan, np.nan, 4, 3, np.nan, np.nan],\n [6, 5, np.nan, np.nan, np.nan, np.nan]],\n index=e_idx, columns=e_cols)\n\n assert_frame_equal(result1, expected)\n assert_frame_equal(result2, expected)\n assert_frame_equal(result3, expected.T)\n\n def test_unstack_period_frame(self):\n # GH 4342\n idx1 = pd.PeriodIndex(['2014-01', '2014-02', '2014-02', '2014-02', '2014-01', '2014-01'],\n freq='M', name='period1')\n idx2 = pd.PeriodIndex(['2013-12', '2013-12', '2014-02', '2013-10', '2013-10', '2014-02'],\n freq='M', name='period2')\n value = {'A': [1, 2, 3, 4, 5, 6], 'B': [6, 5, 4, 3, 2, 1]}\n idx = pd.MultiIndex.from_arrays([idx1, idx2])\n df = pd.DataFrame(value, index=idx)\n\n result1 = df.unstack()\n result2 = df.unstack(level=1)\n result3 = df.unstack(level=0)\n\n e_1 = pd.PeriodIndex(['2014-01', '2014-02'], freq='M', name='period1')\n e_2 = pd.PeriodIndex(['2013-10', '2013-12', '2014-02', '2013-10',\n '2013-12', '2014-02'], freq='M', name='period2')\n e_cols = pd.MultiIndex.from_arrays(['A A A B B B'.split(), e_2])\n expected = DataFrame([[5, 1, 6, 2, 6, 1], [4, 2, 3, 3, 5, 4]],\n index=e_1, columns=e_cols)\n\n assert_frame_equal(result1, expected)\n assert_frame_equal(result2, expected)\n\n e_1 = pd.PeriodIndex(['2014-01', '2014-02', '2014-01',\n '2014-02'], freq='M', name='period1')\n e_2 = pd.PeriodIndex(['2013-10', '2013-12', '2014-02'], freq='M', name='period2')\n e_cols = pd.MultiIndex.from_arrays(['A A B B'.split(), e_1])\n expected = DataFrame([[5, 4, 2, 3], [1, 2, 6, 5], [6, 3, 1, 4]],\n index=e_2, columns=e_cols)\n\n assert_frame_equal(result3, expected)\n\n def test_stack_multiple_bug(self):\n \"\"\" bug when some uniques are not present in the data #3170\"\"\"\n id_col = ([1] * 3) + ([2] * 3)\n name = (['a'] * 3) + (['b'] * 3)\n date = pd.to_datetime(['2013-01-03', '2013-01-04', '2013-01-05'] * 2)\n var1 = np.random.randint(0, 100, 6)\n df = DataFrame(dict(ID=id_col, NAME=name, DATE=date, VAR1=var1))\n\n multi = df.set_index(['DATE', 'ID'])\n multi.columns.name = 'Params'\n unst = multi.unstack('ID')\n down = unst.resample('W-THU')\n\n rs = down.stack('ID')\n xp = unst.ix[:, ['VAR1']].resample('W-THU').stack('ID')\n xp.columns.name = 'Params'\n assert_frame_equal(rs, xp)\n\n def test_stack_dropna(self):\n # GH #3997\n df = pd.DataFrame({'A': ['a1', 'a2'],\n 'B': ['b1', 'b2'],\n 'C': [1, 1]})\n df = df.set_index(['A', 'B'])\n\n stacked = df.unstack().stack(dropna=False)\n self.assertTrue(len(stacked) > len(stacked.dropna()))\n\n stacked = df.unstack().stack(dropna=True)\n assert_frame_equal(stacked, stacked.dropna())\n\n def test_unstack_multiple_hierarchical(self):\n df = DataFrame(index=[[0, 0, 0, 0, 1, 1, 1, 1],\n [0, 0, 1, 1, 0, 0, 1, 1],\n [0, 1, 0, 1, 0, 1, 0, 1]],\n columns=[[0, 0, 1, 1], [0, 1, 0, 1]])\n\n df.index.names = ['a', 'b', 'c']\n df.columns.names = ['d', 'e']\n\n # it works!\n df.unstack(['b', 'c'])\n\n def test_groupby_transform(self):\n s = self.frame['A']\n grouper = s.index.get_level_values(0)\n\n grouped = s.groupby(grouper)\n\n applied = grouped.apply(lambda x: x * 2)\n expected = grouped.transform(lambda x: x * 2)\n assert_series_equal(applied.reindex(expected.index), expected)\n\n def test_unstack_sparse_keyspace(self):\n # memory problems with naive impl #2278\n # Generate Long File & Test Pivot\n NUM_ROWS = 1000\n\n df = DataFrame({'A': np.random.randint(100, size=NUM_ROWS),\n 'B': np.random.randint(300, size=NUM_ROWS),\n 'C': np.random.randint(-7, 7, size=NUM_ROWS),\n 'D': np.random.randint(-19, 19, size=NUM_ROWS),\n 'E': np.random.randint(3000, size=NUM_ROWS),\n 'F': np.random.randn(NUM_ROWS)})\n\n idf = df.set_index(['A', 'B', 'C', 'D', 'E'])\n\n # it works! is sufficient\n idf.unstack('E')\n\n def test_unstack_unobserved_keys(self):\n # related to #2278 refactoring\n levels = [[0, 1], [0, 1, 2, 3]]\n labels = [[0, 0, 1, 1], [0, 2, 0, 2]]\n\n index = MultiIndex(levels, labels)\n\n df = DataFrame(np.random.randn(4, 2), index=index)\n\n result = df.unstack()\n self.assertEqual(len(result.columns), 4)\n\n recons = result.stack()\n assert_frame_equal(recons, df)\n\n def test_groupby_corner(self):\n midx = MultiIndex(levels=[['foo'], ['bar'], ['baz']],\n labels=[[0], [0], [0]], names=['one', 'two', 'three'])\n df = DataFrame([np.random.rand(4)], columns=['a', 'b', 'c', 'd'],\n index=midx)\n # should work\n df.groupby(level='three')\n\n def test_groupby_level_no_obs(self):\n # #1697\n midx = MultiIndex.from_tuples([('f1', 's1'), ('f1', 's2'),\n ('f2', 's1'), ('f2', 's2'),\n ('f3', 's1'), ('f3', 's2')])\n df = DataFrame(\n [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx)\n df1 = df.select(lambda u: u[0] in ['f2', 'f3'], axis=1)\n\n grouped = df1.groupby(axis=1, level=0)\n result = grouped.sum()\n self.assertTrue((result.columns == ['f2', 'f3']).all())\n\n def test_join(self):\n a = self.frame.ix[:5, ['A']]\n b = self.frame.ix[2:, ['B', 'C']]\n\n joined = a.join(b, how='outer').reindex(self.frame.index)\n expected = self.frame.copy()\n expected.values[np.isnan(joined.values)] = np.nan\n\n self.assertFalse(np.isnan(joined.values).all())\n\n assert_frame_equal(joined, expected, check_names=False) # TODO what should join do with names ?\n\n def test_swaplevel(self):\n swapped = self.frame['A'].swaplevel(0, 1)\n swapped2 = self.frame['A'].swaplevel('first', 'second')\n self.assertFalse(swapped.index.equals(self.frame.index))\n assert_series_equal(swapped, swapped2)\n\n back = swapped.swaplevel(0, 1)\n back2 = swapped.swaplevel('second', 'first')\n self.assertTrue(back.index.equals(self.frame.index))\n assert_series_equal(back, back2)\n\n ft = self.frame.T\n swapped = ft.swaplevel('first', 'second', axis=1)\n exp = self.frame.swaplevel('first', 'second').T\n assert_frame_equal(swapped, exp)\n\n def test_swaplevel_panel(self):\n panel = Panel({'ItemA': self.frame,\n 'ItemB': self.frame * 2})\n\n result = panel.swaplevel(0, 1, axis='major')\n expected = panel.copy()\n expected.major_axis = expected.major_axis.swaplevel(0, 1)\n tm.assert_panel_equal(result, expected)\n\n def test_reorder_levels(self):\n result = self.ymd.reorder_levels(['month', 'day', 'year'])\n expected = self.ymd.swaplevel(0, 1).swaplevel(1, 2)\n assert_frame_equal(result, expected)\n\n result = self.ymd['A'].reorder_levels(['month', 'day', 'year'])\n expected = self.ymd['A'].swaplevel(0, 1).swaplevel(1, 2)\n assert_series_equal(result, expected)\n\n result = self.ymd.T.reorder_levels(['month', 'day', 'year'], axis=1)\n expected = self.ymd.T.swaplevel(0, 1, axis=1).swaplevel(1, 2, axis=1)\n assert_frame_equal(result, expected)\n\n with assertRaisesRegexp(TypeError, 'hierarchical axis'):\n self.ymd.reorder_levels([1, 2], axis=1)\n\n with assertRaisesRegexp(IndexError, 'Too many levels'):\n self.ymd.index.reorder_levels([1, 2, 3])\n\n def test_insert_index(self):\n df = self.ymd[:5].T\n df[2000, 1, 10] = df[2000, 1, 7]\n tm.assert_isinstance(df.columns, MultiIndex)\n self.assertTrue((df[2000, 1, 10] == df[2000, 1, 7]).all())\n\n def test_alignment(self):\n x = Series(data=[1, 2, 3],\n index=MultiIndex.from_tuples([(\"A\", 1), (\"A\", 2), (\"B\", 3)]))\n\n y = Series(data=[4, 5, 6],\n index=MultiIndex.from_tuples([(\"Z\", 1), (\"Z\", 2), (\"B\", 3)]))\n\n res = x - y\n exp_index = x.index.union(y.index)\n exp = x.reindex(exp_index) - y.reindex(exp_index)\n assert_series_equal(res, exp)\n\n # hit non-monotonic code path\n res = x[::-1] - y[::-1]\n exp_index = x.index.union(y.index)\n exp = x.reindex(exp_index) - y.reindex(exp_index)\n assert_series_equal(res, exp)\n\n def test_is_lexsorted(self):\n levels = [[0, 1], [0, 1, 2]]\n\n index = MultiIndex(levels=levels,\n labels=[[0, 0, 0, 1, 1, 1],\n [0, 1, 2, 0, 1, 2]])\n self.assertTrue(index.is_lexsorted())\n\n index = MultiIndex(levels=levels,\n labels=[[0, 0, 0, 1, 1, 1],\n [0, 1, 2, 0, 2, 1]])\n self.assertFalse(index.is_lexsorted())\n\n index = MultiIndex(levels=levels,\n labels=[[0, 0, 1, 0, 1, 1],\n [0, 1, 0, 2, 2, 1]])\n self.assertFalse(index.is_lexsorted())\n self.assertEqual(index.lexsort_depth, 0)\n\n def test_frame_getitem_view(self):\n df = self.frame.T.copy()\n\n # this works because we are modifying the underlying array\n # really a no-no\n df['foo'].values[:] = 0\n self.assertTrue((df['foo'].values == 0).all())\n\n # but not if it's mixed-type\n df['foo', 'four'] = 'foo'\n df = df.sortlevel(0, axis=1)\n\n # this will work, but will raise/warn as its chained assignment\n def f():\n df['foo']['one'] = 2\n return df\n self.assertRaises(com.SettingWithCopyError, f)\n\n try:\n df = f()\n except:\n pass\n self.assertTrue((df['foo', 'one'] == 0).all())\n\n def test_frame_getitem_not_sorted(self):\n df = self.frame.T\n df['foo', 'four'] = 'foo'\n\n arrays = [np.array(x) for x in zip(*df.columns._tuple_index)]\n\n result = df['foo']\n result2 = df.ix[:, 'foo']\n expected = df.reindex(columns=df.columns[arrays[0] == 'foo'])\n expected.columns = expected.columns.droplevel(0)\n assert_frame_equal(result, expected)\n assert_frame_equal(result2, expected)\n\n df = df.T\n result = df.xs('foo')\n result2 = df.ix['foo']\n expected = df.reindex(df.index[arrays[0] == 'foo'])\n expected.index = expected.index.droplevel(0)\n assert_frame_equal(result, expected)\n assert_frame_equal(result2, expected)\n\n def test_series_getitem_not_sorted(self):\n arrays = [['bar', 'bar', 'baz', 'baz', 'qux', 'qux', 'foo', 'foo'],\n ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]\n tuples = lzip(*arrays)\n index = MultiIndex.from_tuples(tuples)\n s = Series(randn(8), index=index)\n\n arrays = [np.array(x) for x in zip(*index._tuple_index)]\n\n result = s['qux']\n result2 = s.ix['qux']\n expected = s[arrays[0] == 'qux']\n expected.index = expected.index.droplevel(0)\n assert_series_equal(result, expected)\n assert_series_equal(result2, expected)\n\n def test_count(self):\n frame = self.frame.copy()\n frame.index.names = ['a', 'b']\n\n result = frame.count(level='b')\n expect = self.frame.count(level=1)\n assert_frame_equal(result, expect, check_names=False)\n\n result = frame.count(level='a')\n expect = self.frame.count(level=0)\n assert_frame_equal(result, expect, check_names=False)\n\n series = self.series.copy()\n series.index.names = ['a', 'b']\n\n result = series.count(level='b')\n expect = self.series.count(level=1)\n assert_series_equal(result, expect)\n\n result = series.count(level='a')\n expect = self.series.count(level=0)\n assert_series_equal(result, expect)\n\n self.assertRaises(KeyError, series.count, 'x')\n self.assertRaises(KeyError, frame.count, level='x')\n\n AGG_FUNCTIONS = ['sum', 'prod', 'min', 'max', 'median', 'mean', 'skew',\n 'mad', 'std', 'var', 'sem']\n\n def test_series_group_min_max(self):\n for op, level, skipna in cart_product(self.AGG_FUNCTIONS,\n lrange(2),\n [False, True]):\n grouped = self.series.groupby(level=level)\n aggf = lambda x: getattr(x, op)(skipna=skipna)\n # skipna=True\n leftside = grouped.agg(aggf)\n rightside = getattr(self.series, op)(level=level, skipna=skipna)\n assert_series_equal(leftside, rightside)\n\n def test_frame_group_ops(self):\n self.frame.ix[1, [1, 2]] = np.nan\n self.frame.ix[7, [0, 1]] = np.nan\n\n for op, level, axis, skipna in cart_product(self.AGG_FUNCTIONS,\n lrange(2), lrange(2),\n [False, True]):\n if axis == 0:\n frame = self.frame\n else:\n frame = self.frame.T\n\n grouped = frame.groupby(level=level, axis=axis)\n\n pieces = []\n\n def aggf(x):\n pieces.append(x)\n return getattr(x, op)(skipna=skipna, axis=axis)\n leftside = grouped.agg(aggf)\n rightside = getattr(frame, op)(level=level, axis=axis,\n skipna=skipna)\n\n # for good measure, groupby detail\n level_index = frame._get_axis(axis).levels[level]\n\n self.assertTrue(leftside._get_axis(axis).equals(level_index))\n self.assertTrue(rightside._get_axis(axis).equals(level_index))\n\n assert_frame_equal(leftside, rightside)\n\n def test_stat_op_corner(self):\n obj = Series([10.0], index=MultiIndex.from_tuples([(2, 3)]))\n\n result = obj.sum(level=0)\n expected = Series([10.0], index=[2])\n assert_series_equal(result, expected)\n\n def test_frame_any_all_group(self):\n df = DataFrame(\n {'data': [False, False, True, False, True, False, True]},\n index=[\n ['one', 'one', 'two', 'one', 'two', 'two', 'two'],\n [0, 1, 0, 2, 1, 2, 3]])\n\n result = df.any(level=0)\n ex = DataFrame({'data': [False, True]}, index=['one', 'two'])\n assert_frame_equal(result, ex)\n\n result = df.all(level=0)\n ex = DataFrame({'data': [False, False]}, index=['one', 'two'])\n assert_frame_equal(result, ex)\n\n def test_std_var_pass_ddof(self):\n index = MultiIndex.from_arrays([np.arange(5).repeat(10),\n np.tile(np.arange(10), 5)])\n df = DataFrame(np.random.randn(len(index), 5), index=index)\n\n for meth in ['var', 'std']:\n ddof = 4\n alt = lambda x: getattr(x, meth)(ddof=ddof)\n\n result = getattr(df[0], meth)(level=0, ddof=ddof)\n expected = df[0].groupby(level=0).agg(alt)\n assert_series_equal(result, expected)\n\n result = getattr(df, meth)(level=0, ddof=ddof)\n expected = df.groupby(level=0).agg(alt)\n assert_frame_equal(result, expected)\n\n def test_frame_series_agg_multiple_levels(self):\n result = self.ymd.sum(level=['year', 'month'])\n expected = self.ymd.groupby(level=['year', 'month']).sum()\n assert_frame_equal(result, expected)\n\n result = self.ymd['A'].sum(level=['year', 'month'])\n expected = self.ymd['A'].groupby(level=['year', 'month']).sum()\n assert_series_equal(result, expected)\n\n def test_groupby_multilevel(self):\n result = self.ymd.groupby(level=[0, 1]).mean()\n\n k1 = self.ymd.index.get_level_values(0)\n k2 = self.ymd.index.get_level_values(1)\n\n expected = self.ymd.groupby([k1, k2]).mean()\n\n assert_frame_equal(result, expected, check_names=False) # TODO groupby with level_values drops names\n self.assertEqual(result.index.names, self.ymd.index.names[:2])\n\n result2 = self.ymd.groupby(level=self.ymd.index.names[:2]).mean()\n assert_frame_equal(result, result2)\n\n def test_groupby_multilevel_with_transform(self):\n pass\n\n def test_multilevel_consolidate(self):\n index = MultiIndex.from_tuples([('foo', 'one'), ('foo', 'two'),\n ('bar', 'one'), ('bar', 'two')])\n df = DataFrame(np.random.randn(4, 4), index=index, columns=index)\n df['Totals', ''] = df.sum(1)\n df = df.consolidate()\n\n def test_ix_preserve_names(self):\n result = self.ymd.ix[2000]\n result2 = self.ymd['A'].ix[2000]\n self.assertEqual(result.index.names, self.ymd.index.names[1:])\n self.assertEqual(result2.index.names, self.ymd.index.names[1:])\n\n result = self.ymd.ix[2000, 2]\n result2 = self.ymd['A'].ix[2000, 2]\n self.assertEqual(result.index.name, self.ymd.index.names[2])\n self.assertEqual(result2.index.name, self.ymd.index.names[2])\n\n def test_partial_set(self):\n # GH #397\n df = self.ymd.copy()\n exp = self.ymd.copy()\n df.ix[2000, 4] = 0\n exp.ix[2000, 4].values[:] = 0\n assert_frame_equal(df, exp)\n\n df['A'].ix[2000, 4] = 1\n exp['A'].ix[2000, 4].values[:] = 1\n assert_frame_equal(df, exp)\n\n df.ix[2000] = 5\n exp.ix[2000].values[:] = 5\n assert_frame_equal(df, exp)\n\n # this works...for now\n df['A'].ix[14] = 5\n self.assertEqual(df['A'][14], 5)\n\n def test_unstack_preserve_types(self):\n # GH #403\n self.ymd['E'] = 'foo'\n self.ymd['F'] = 2\n\n unstacked = self.ymd.unstack('month')\n self.assertEqual(unstacked['A', 1].dtype, np.float64)\n self.assertEqual(unstacked['E', 1].dtype, np.object_)\n self.assertEqual(unstacked['F', 1].dtype, np.float64)\n\n def test_unstack_group_index_overflow(self):\n labels = np.tile(np.arange(500), 2)\n level = np.arange(500)\n\n index = MultiIndex(levels=[level] * 8 + [[0, 1]],\n labels=[labels] * 8 + [np.arange(2).repeat(500)])\n\n s = Series(np.arange(1000), index=index)\n result = s.unstack()\n self.assertEqual(result.shape, (500, 2))\n\n # test roundtrip\n stacked = result.stack()\n assert_series_equal(s,\n stacked.reindex(s.index))\n\n # put it at beginning\n index = MultiIndex(levels=[[0, 1]] + [level] * 8,\n labels=[np.arange(2).repeat(500)] + [labels] * 8)\n\n s = Series(np.arange(1000), index=index)\n result = s.unstack(0)\n self.assertEqual(result.shape, (500, 2))\n\n # put it in middle\n index = MultiIndex(levels=[level] * 4 + [[0, 1]] + [level] * 4,\n labels=([labels] * 4 + [np.arange(2).repeat(500)]\n + [labels] * 4))\n\n s = Series(np.arange(1000), index=index)\n result = s.unstack(4)\n self.assertEqual(result.shape, (500, 2))\n\n def test_getitem_lowerdim_corner(self):\n self.assertRaises(KeyError, self.frame.ix.__getitem__,\n (('bar', 'three'), 'B'))\n\n\n # in theory should be inserting in a sorted space????\n self.frame.ix[('bar','three'),'B'] = 0\n self.assertEqual(self.frame.sortlevel().ix[('bar','three'),'B'], 0)\n\n #----------------------------------------------------------------------\n # AMBIGUOUS CASES!\n\n def test_partial_ix_missing(self):\n raise nose.SkipTest(\"skipping for now\")\n\n result = self.ymd.ix[2000, 0]\n expected = self.ymd.ix[2000]['A']\n assert_series_equal(result, expected)\n\n # need to put in some work here\n\n # self.ymd.ix[2000, 0] = 0\n # self.assertTrue((self.ymd.ix[2000]['A'] == 0).all())\n\n # Pretty sure the second (and maybe even the first) is already wrong.\n self.assertRaises(Exception, self.ymd.ix.__getitem__, (2000, 6))\n self.assertRaises(Exception, self.ymd.ix.__getitem__, (2000, 6), 0)\n\n #----------------------------------------------------------------------\n\n def test_to_html(self):\n self.ymd.columns.name = 'foo'\n self.ymd.to_html()\n self.ymd.T.to_html()\n\n def test_level_with_tuples(self):\n index = MultiIndex(levels=[[('foo', 'bar', 0), ('foo', 'baz', 0),\n ('foo', 'qux', 0)],\n [0, 1]],\n labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]])\n\n series = Series(np.random.randn(6), index=index)\n frame = DataFrame(np.random.randn(6, 4), index=index)\n\n result = series[('foo', 'bar', 0)]\n result2 = series.ix[('foo', 'bar', 0)]\n expected = series[:2]\n expected.index = expected.index.droplevel(0)\n assert_series_equal(result, expected)\n assert_series_equal(result2, expected)\n\n self.assertRaises(KeyError, series.__getitem__, (('foo', 'bar', 0), 2))\n\n result = frame.ix[('foo', 'bar', 0)]\n result2 = frame.xs(('foo', 'bar', 0))\n expected = frame[:2]\n expected.index = expected.index.droplevel(0)\n assert_frame_equal(result, expected)\n assert_frame_equal(result2, expected)\n\n index = MultiIndex(levels=[[('foo', 'bar'), ('foo', 'baz'),\n ('foo', 'qux')],\n [0, 1]],\n labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]])\n\n series = Series(np.random.randn(6), index=index)\n frame = DataFrame(np.random.randn(6, 4), index=index)\n\n result = series[('foo', 'bar')]\n result2 = series.ix[('foo', 'bar')]\n expected = series[:2]\n expected.index = expected.index.droplevel(0)\n assert_series_equal(result, expected)\n assert_series_equal(result2, expected)\n\n result = frame.ix[('foo', 'bar')]\n result2 = frame.xs(('foo', 'bar'))\n expected = frame[:2]\n expected.index = expected.index.droplevel(0)\n assert_frame_equal(result, expected)\n assert_frame_equal(result2, expected)\n\n def test_int_series_slicing(self):\n s = self.ymd['A']\n result = s[5:]\n expected = s.reindex(s.index[5:])\n assert_series_equal(result, expected)\n\n exp = self.ymd['A'].copy()\n s[5:] = 0\n exp.values[5:] = 0\n self.assert_numpy_array_equal(s.values, exp.values)\n\n result = self.ymd[5:]\n expected = self.ymd.reindex(s.index[5:])\n assert_frame_equal(result, expected)\n\n def test_mixed_depth_get(self):\n arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'],\n ['', 'OD', 'OD', 'result1', 'result2', 'result1'],\n ['', 'wx', 'wy', '', '', '']]\n\n tuples = sorted(zip(*arrays))\n index = MultiIndex.from_tuples(tuples)\n df = DataFrame(randn(4, 6), columns=index)\n\n result = df['a']\n expected = df['a', '', '']\n assert_series_equal(result, expected)\n self.assertEqual(result.name, 'a')\n\n result = df['routine1', 'result1']\n expected = df['routine1', 'result1', '']\n assert_series_equal(result, expected)\n self.assertEqual(result.name, ('routine1', 'result1'))\n\n def test_mixed_depth_insert(self):\n arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'],\n ['', 'OD', 'OD', 'result1', 'result2', 'result1'],\n ['', 'wx', 'wy', '', '', '']]\n\n tuples = sorted(zip(*arrays))\n index = MultiIndex.from_tuples(tuples)\n df = DataFrame(randn(4, 6), columns=index)\n\n result = df.copy()\n expected = df.copy()\n result['b'] = [1, 2, 3, 4]\n expected['b', '', ''] = [1, 2, 3, 4]\n assert_frame_equal(result, expected)\n\n def test_mixed_depth_drop(self):\n arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'],\n ['', 'OD', 'OD', 'result1', 'result2', 'result1'],\n ['', 'wx', 'wy', '', '', '']]\n\n tuples = sorted(zip(*arrays))\n index = MultiIndex.from_tuples(tuples)\n df = DataFrame(randn(4, 6), columns=index)\n\n result = df.drop('a', axis=1)\n expected = df.drop([('a', '', '')], axis=1)\n assert_frame_equal(expected, result)\n\n result = df.drop(['top'], axis=1)\n expected = df.drop([('top', 'OD', 'wx')], axis=1)\n expected = expected.drop([('top', 'OD', 'wy')], axis=1)\n assert_frame_equal(expected, result)\n\n result = df.drop(('top', 'OD', 'wx'), axis=1)\n expected = df.drop([('top', 'OD', 'wx')], axis=1)\n assert_frame_equal(expected, result)\n\n expected = df.drop([('top', 'OD', 'wy')], axis=1)\n expected = df.drop('top', axis=1)\n\n result = df.drop('result1', level=1, axis=1)\n expected = df.drop([('routine1', 'result1', ''),\n ('routine2', 'result1', '')], axis=1)\n assert_frame_equal(expected, result)\n\n def test_drop_nonunique(self):\n df = DataFrame([[\"x-a\", \"x\", \"a\", 1.5], [\"x-a\", \"x\", \"a\", 1.2],\n [\"z-c\", \"z\", \"c\", 3.1], [\"x-a\", \"x\", \"a\", 4.1],\n [\"x-b\", \"x\", \"b\", 5.1], [\"x-b\", \"x\", \"b\", 4.1],\n [\"x-b\", \"x\", \"b\", 2.2],\n [\"y-a\", \"y\", \"a\", 1.2], [\"z-b\", \"z\", \"b\", 2.1]],\n columns=[\"var1\", \"var2\", \"var3\", \"var4\"])\n\n grp_size = df.groupby(\"var1\").size()\n drop_idx = grp_size.ix[grp_size == 1]\n\n idf = df.set_index([\"var1\", \"var2\", \"var3\"])\n\n # it works! #2101\n result = idf.drop(drop_idx.index, level=0).reset_index()\n expected = df[-df.var1.isin(drop_idx.index)]\n\n result.index = expected.index\n\n assert_frame_equal(result, expected)\n\n def test_mixed_depth_pop(self):\n arrays = [['a', 'top', 'top', 'routine1', 'routine1', 'routine2'],\n ['', 'OD', 'OD', 'result1', 'result2', 'result1'],\n ['', 'wx', 'wy', '', '', '']]\n\n tuples = sorted(zip(*arrays))\n index = MultiIndex.from_tuples(tuples)\n df = DataFrame(randn(4, 6), columns=index)\n\n df1 = df.copy()\n df2 = df.copy()\n result = df1.pop('a')\n expected = df2.pop(('a', '', ''))\n assert_series_equal(expected, result)\n assert_frame_equal(df1, df2)\n self.assertEqual(result.name, 'a')\n\n expected = df1['top']\n df1 = df1.drop(['top'], axis=1)\n result = df2.pop('top')\n assert_frame_equal(expected, result)\n assert_frame_equal(df1, df2)\n\n def test_reindex_level_partial_selection(self):\n result = self.frame.reindex(['foo', 'qux'], level=0)\n expected = self.frame.ix[[0, 1, 2, 7, 8, 9]]\n assert_frame_equal(result, expected)\n\n result = self.frame.T.reindex_axis(['foo', 'qux'], axis=1, level=0)\n assert_frame_equal(result, expected.T)\n\n result = self.frame.ix[['foo', 'qux']]\n assert_frame_equal(result, expected)\n\n result = self.frame['A'].ix[['foo', 'qux']]\n assert_series_equal(result, expected['A'])\n\n result = self.frame.T.ix[:, ['foo', 'qux']]\n assert_frame_equal(result, expected.T)\n\n def test_setitem_multiple_partial(self):\n expected = self.frame.copy()\n result = self.frame.copy()\n result.ix[['foo', 'bar']] = 0\n expected.ix['foo'] = 0\n expected.ix['bar'] = 0\n assert_frame_equal(result, expected)\n\n expected = self.frame.copy()\n result = self.frame.copy()\n result.ix['foo':'bar'] = 0\n expected.ix['foo'] = 0\n expected.ix['bar'] = 0\n assert_frame_equal(result, expected)\n\n expected = self.frame['A'].copy()\n result = self.frame['A'].copy()\n result.ix[['foo', 'bar']] = 0\n expected.ix['foo'] = 0\n expected.ix['bar'] = 0\n assert_series_equal(result, expected)\n\n expected = self.frame['A'].copy()\n result = self.frame['A'].copy()\n result.ix['foo':'bar'] = 0\n expected.ix['foo'] = 0\n expected.ix['bar'] = 0\n assert_series_equal(result, expected)\n\n def test_drop_level(self):\n result = self.frame.drop(['bar', 'qux'], level='first')\n expected = self.frame.ix[[0, 1, 2, 5, 6]]\n assert_frame_equal(result, expected)\n\n result = self.frame.drop(['two'], level='second')\n expected = self.frame.ix[[0, 2, 3, 6, 7, 9]]\n assert_frame_equal(result, expected)\n\n result = self.frame.T.drop(['bar', 'qux'], axis=1, level='first')\n expected = self.frame.ix[[0, 1, 2, 5, 6]].T\n assert_frame_equal(result, expected)\n\n result = self.frame.T.drop(['two'], axis=1, level='second')\n expected = self.frame.ix[[0, 2, 3, 6, 7, 9]].T\n assert_frame_equal(result, expected)\n\n def test_drop_preserve_names(self):\n index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1],\n [1, 2, 3, 1, 2, 3]],\n names=['one', 'two'])\n\n df = DataFrame(np.random.randn(6, 3), index=index)\n\n result = df.drop([(0, 2)])\n self.assertEqual(result.index.names, ('one', 'two'))\n\n def test_unicode_repr_issues(self):\n levels = [Index([u('a/\\u03c3'), u('b/\\u03c3'), u('c/\\u03c3')]),\n Index([0, 1])]\n labels = [np.arange(3).repeat(2), np.tile(np.arange(2), 3)]\n index = MultiIndex(levels=levels, labels=labels)\n\n repr(index.levels)\n\n # NumPy bug\n # repr(index.get_level_values(1))\n\n def test_unicode_repr_level_names(self):\n index = MultiIndex.from_tuples([(0, 0), (1, 1)],\n names=[u('\\u0394'), 'i1'])\n\n s = Series(lrange(2), index=index)\n df = DataFrame(np.random.randn(2, 4), index=index)\n repr(s)\n repr(df)\n\n def test_dataframe_insert_column_all_na(self):\n # GH #1534\n mix = MultiIndex.from_tuples(\n [('1a', '2a'), ('1a', '2b'), ('1a', '2c')])\n df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mix)\n s = Series({(1, 1): 1, (1, 2): 2})\n df['new'] = s\n self.assertTrue(df['new'].isnull().all())\n\n def test_join_segfault(self):\n # 1532\n df1 = DataFrame({'a': [1, 1], 'b': [1, 2], 'x': [1, 2]})\n df2 = DataFrame({'a': [2, 2], 'b': [1, 2], 'y': [1, 2]})\n df1 = df1.set_index(['a', 'b'])\n df2 = df2.set_index(['a', 'b'])\n # it works!\n for how in ['left', 'right', 'outer']:\n df1.join(df2, how=how)\n\n def test_set_column_scalar_with_ix(self):\n subset = self.frame.index[[1, 4, 5]]\n\n self.frame.ix[subset] = 99\n self.assertTrue((self.frame.ix[subset].values == 99).all())\n\n col = self.frame['B']\n col[subset] = 97\n self.assertTrue((self.frame.ix[subset, 'B'] == 97).all())\n\n def test_frame_dict_constructor_empty_series(self):\n s1 = Series([1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3),\n (2, 2), (2, 4)]))\n s2 = Series([1, 2, 3, 4],\n index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)]))\n s3 = Series()\n\n # it works!\n df = DataFrame({'foo': s1, 'bar': s2, 'baz': s3})\n df = DataFrame.from_dict({'foo': s1, 'baz': s3, 'bar': s2})\n\n def test_indexing_ambiguity_bug_1678(self):\n columns = MultiIndex.from_tuples([('Ohio', 'Green'), ('Ohio', 'Red'),\n ('Colorado', 'Green')])\n index = MultiIndex.from_tuples(\n [('a', 1), ('a', 2), ('b', 1), ('b', 2)])\n\n frame = DataFrame(np.arange(12).reshape((4, 3)), index=index,\n columns=columns)\n\n result = frame.ix[:, 1]\n exp = frame.icol(1)\n tm.assert_isinstance(result, Series)\n assert_series_equal(result, exp)\n\n def test_nonunique_assignment_1750(self):\n df = DataFrame([[1, 1, \"x\", \"X\"], [1, 1, \"y\", \"Y\"], [1, 2, \"z\", \"Z\"]],\n columns=list(\"ABCD\"))\n\n df = df.set_index(['A', 'B'])\n ix = MultiIndex.from_tuples([(1, 1)])\n\n df.ix[ix, \"C\"] = '_'\n\n self.assertTrue((df.xs((1, 1))['C'] == '_').all())\n\n def test_indexing_over_hashtable_size_cutoff(self):\n n = 10000\n\n old_cutoff = _index._SIZE_CUTOFF\n _index._SIZE_CUTOFF = 20000\n\n s = Series(np.arange(n),\n MultiIndex.from_arrays(([\"a\"] * n, np.arange(n))))\n\n # hai it works!\n self.assertEqual(s[(\"a\", 5)], 5)\n self.assertEqual(s[(\"a\", 6)], 6)\n self.assertEqual(s[(\"a\", 7)], 7)\n\n _index._SIZE_CUTOFF = old_cutoff\n\n def test_multiindex_na_repr(self):\n # only an issue with long columns\n\n from numpy import nan\n df3 = DataFrame({\n 'A' * 30: {('A', 'A0006000', 'nuit'): 'A0006000'},\n 'B' * 30: {('A', 'A0006000', 'nuit'): nan},\n 'C' * 30: {('A', 'A0006000', 'nuit'): nan},\n 'D' * 30: {('A', 'A0006000', 'nuit'): nan},\n 'E' * 30: {('A', 'A0006000', 'nuit'): 'A'},\n 'F' * 30: {('A', 'A0006000', 'nuit'): nan},\n })\n\n idf = df3.set_index(['A' * 30, 'C' * 30])\n repr(idf)\n\n def test_assign_index_sequences(self):\n # #2200\n df = DataFrame({\"a\": [1, 2, 3],\n \"b\": [4, 5, 6],\n \"c\": [7, 8, 9]}).set_index([\"a\", \"b\"])\n l = list(df.index)\n l[0] = (\"faz\", \"boo\")\n df.index = l\n repr(df)\n\n # this travels an improper code path\n l[0] = [\"faz\", \"boo\"]\n df.index = l\n repr(df)\n\n def test_tuples_have_na(self):\n index = MultiIndex(levels=[[1, 0], [0, 1, 2, 3]],\n labels=[[1, 1, 1, 1, -1, 0, 0, 0],\n [0, 1, 2, 3, 0, 1, 2, 3]])\n\n self.assertTrue(isnull(index[4][0]))\n self.assertTrue(isnull(index.values[4][0]))\n\n def test_duplicate_groupby_issues(self):\n idx_tp = [('600809', '20061231'), ('600809', '20070331'),\n ('600809', '20070630'), ('600809', '20070331')]\n dt = ['demo','demo','demo','demo']\n\n idx = MultiIndex.from_tuples(idx_tp,names = ['STK_ID','RPT_Date'])\n s = Series(dt, index=idx)\n\n result = s.groupby(s.index).first()\n self.assertEqual(len(result), 3)\n\n def test_duplicate_mi(self):\n # GH 4516\n df = DataFrame([['foo','bar',1.0,1],['foo','bar',2.0,2],['bah','bam',3.0,3],\n ['bah','bam',4.0,4],['foo','bar',5.0,5],['bah','bam',6.0,6]],\n columns=list('ABCD'))\n df = df.set_index(['A','B'])\n df = df.sortlevel(0)\n expected = DataFrame([['foo','bar',1.0,1],['foo','bar',2.0,2],['foo','bar',5.0,5]],\n columns=list('ABCD')).set_index(['A','B'])\n result = df.loc[('foo','bar')]\n assert_frame_equal(result,expected)\n\n def test_duplicated_drop_duplicates(self):\n # GH 4060\n idx = MultiIndex.from_arrays(([1, 2, 3, 1, 2 ,3], [1, 1, 1, 1, 2, 2]))\n\n expected = np.array([False, False, False, True, False, False], dtype=bool)\n duplicated = idx.duplicated()\n tm.assert_numpy_array_equal(duplicated, expected)\n self.assertTrue(duplicated.dtype == bool)\n expected = MultiIndex.from_arrays(([1, 2, 3, 2 ,3], [1, 1, 1, 2, 2]))\n tm.assert_index_equal(idx.drop_duplicates(), expected)\n\n expected = np.array([True, False, False, False, False, False])\n duplicated = idx.duplicated(take_last=True)\n tm.assert_numpy_array_equal(duplicated, expected)\n self.assertTrue(duplicated.dtype == bool)\n expected = MultiIndex.from_arrays(([2, 3, 1, 2 ,3], [1, 1, 1, 2, 2]))\n tm.assert_index_equal(idx.drop_duplicates(take_last=True), expected)\n\n def test_multiindex_set_index(self):\n # segfault in #3308\n d = {'t1': [2, 2.5, 3], 't2': [4, 5, 6]}\n df = DataFrame(d)\n tuples = [(0, 1), (0, 2), (1, 2)]\n df['tuples'] = tuples\n\n index = MultiIndex.from_tuples(df['tuples'])\n # it works!\n df.set_index(index)\n\n def test_datetimeindex(self):\n idx1 = pd.DatetimeIndex(['2013-04-01 9:00', '2013-04-02 9:00', '2013-04-03 9:00'] * 2, tz='Asia/Tokyo')\n idx2 = pd.date_range('2010/01/01', periods=6, freq='M', tz='US/Eastern')\n idx = MultiIndex.from_arrays([idx1, idx2])\n\n expected1 = pd.DatetimeIndex(['2013-04-01 9:00', '2013-04-02 9:00', '2013-04-03 9:00'], tz='Asia/Tokyo')\n\n self.assertTrue(idx.levels[0].equals(expected1))\n self.assertTrue(idx.levels[1].equals(idx2))\n\n # from datetime combos\n # GH 7888\n date1 = datetime.date.today()\n date2 = datetime.datetime.today()\n date3 = Timestamp.today()\n\n for d1, d2 in itertools.product([date1,date2,date3],[date1,date2,date3]):\n index = pd.MultiIndex.from_product([[d1],[d2]])\n self.assertIsInstance(index.levels[0],pd.DatetimeIndex)\n self.assertIsInstance(index.levels[1],pd.DatetimeIndex)\n\n def test_set_index_datetime(self):\n # GH 3950\n df = pd.DataFrame({'label':['a', 'a', 'a', 'b', 'b', 'b'],\n 'datetime':['2011-07-19 07:00:00', '2011-07-19 08:00:00',\n '2011-07-19 09:00:00', '2011-07-19 07:00:00',\n '2011-07-19 08:00:00', '2011-07-19 09:00:00'],\n 'value':range(6)})\n df.index = pd.to_datetime(df.pop('datetime'), utc=True)\n df.index = df.index.tz_localize('UTC').tz_convert('US/Pacific')\n\n expected = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00'])\n expected = expected.tz_localize('UTC').tz_convert('US/Pacific')\n\n df = df.set_index('label', append=True)\n self.assertTrue(df.index.levels[0].equals(expected))\n self.assertTrue(df.index.levels[1].equals(pd.Index(['a', 'b'])))\n\n df = df.swaplevel(0, 1)\n self.assertTrue(df.index.levels[0].equals(pd.Index(['a', 'b'])))\n self.assertTrue(df.index.levels[1].equals(expected))\n\n\n df = DataFrame(np.random.random(6))\n idx1 = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00',\n '2011-07-19 09:00:00', '2011-07-19 07:00:00',\n '2011-07-19 08:00:00', '2011-07-19 09:00:00'], tz='US/Eastern')\n idx2 = pd.DatetimeIndex(['2012-04-01 09:00', '2012-04-01 09:00', '2012-04-01 09:00',\n '2012-04-02 09:00', '2012-04-02 09:00', '2012-04-02 09:00'],\n tz='US/Eastern')\n idx3 = pd.date_range('2011-01-01 09:00', periods=6, tz='Asia/Tokyo')\n\n df = df.set_index(idx1)\n df = df.set_index(idx2, append=True)\n df = df.set_index(idx3, append=True)\n\n expected1 = pd.DatetimeIndex(['2011-07-19 07:00:00', '2011-07-19 08:00:00',\n '2011-07-19 09:00:00'], tz='US/Eastern')\n expected2 = pd.DatetimeIndex(['2012-04-01 09:00', '2012-04-02 09:00'], tz='US/Eastern')\n\n self.assertTrue(df.index.levels[0].equals(expected1))\n self.assertTrue(df.index.levels[1].equals(expected2))\n self.assertTrue(df.index.levels[2].equals(idx3))\n\n # GH 7092\n self.assertTrue(df.index.get_level_values(0).equals(idx1))\n self.assertTrue(df.index.get_level_values(1).equals(idx2))\n self.assertTrue(df.index.get_level_values(2).equals(idx3))\n\n def test_reset_index_datetime(self):\n # GH 3950\n for tz in ['UTC', 'Asia/Tokyo', 'US/Eastern']:\n idx1 = pd.date_range('1/1/2011', periods=5, freq='D', tz=tz, name='idx1')\n idx2 = pd.Index(range(5), name='idx2',dtype='int64')\n idx = pd.MultiIndex.from_arrays([idx1, idx2])\n df = pd.DataFrame({'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx)\n\n expected = pd.DataFrame({'idx1': [datetime.datetime(2011, 1, 1),\n datetime.datetime(2011, 1, 2),\n datetime.datetime(2011, 1, 3),\n datetime.datetime(2011, 1, 4),\n datetime.datetime(2011, 1, 5)],\n 'idx2': np.arange(5,dtype='int64'),\n 'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']},\n columns=['idx1', 'idx2', 'a', 'b'])\n expected['idx1'] = expected['idx1'].apply(lambda d: pd.Timestamp(d, tz=tz))\n\n assert_frame_equal(df.reset_index(), expected)\n\n idx3 = pd.date_range('1/1/2012', periods=5, freq='MS', tz='Europe/Paris', name='idx3')\n idx = pd.MultiIndex.from_arrays([idx1, idx2, idx3])\n df = pd.DataFrame({'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']}, index=idx)\n\n expected = pd.DataFrame({'idx1': [datetime.datetime(2011, 1, 1),\n datetime.datetime(2011, 1, 2),\n datetime.datetime(2011, 1, 3),\n datetime.datetime(2011, 1, 4),\n datetime.datetime(2011, 1, 5)],\n 'idx2': np.arange(5,dtype='int64'),\n 'idx3': [datetime.datetime(2012, 1, 1),\n datetime.datetime(2012, 2, 1),\n datetime.datetime(2012, 3, 1),\n datetime.datetime(2012, 4, 1),\n datetime.datetime(2012, 5, 1)],\n 'a': np.arange(5,dtype='int64'), 'b': ['A', 'B', 'C', 'D', 'E']},\n columns=['idx1', 'idx2', 'idx3', 'a', 'b'])\n expected['idx1'] = expected['idx1'].apply(lambda d: pd.Timestamp(d, tz=tz))\n expected['idx3'] = expected['idx3'].apply(lambda d: pd.Timestamp(d, tz='Europe/Paris'))\n assert_frame_equal(df.reset_index(), expected)\n\n # GH 7793\n idx = pd.MultiIndex.from_product([['a','b'], pd.date_range('20130101', periods=3, tz=tz)])\n df = pd.DataFrame(np.arange(6,dtype='int64').reshape(6,1), columns=['a'], index=idx)\n\n expected = pd.DataFrame({'level_0': 'a a a b b b'.split(),\n 'level_1': [datetime.datetime(2013, 1, 1),\n datetime.datetime(2013, 1, 2),\n datetime.datetime(2013, 1, 3)] * 2,\n 'a': np.arange(6, dtype='int64')},\n columns=['level_0', 'level_1', 'a'])\n expected['level_1'] = expected['level_1'].apply(lambda d: pd.Timestamp(d, offset='D', tz=tz))\n assert_frame_equal(df.reset_index(), expected)\n\n def test_reset_index_period(self):\n # GH 7746\n idx = pd.MultiIndex.from_product([pd.period_range('20130101', periods=3, freq='M'),\n ['a','b','c']], names=['month', 'feature'])\n\n df = pd.DataFrame(np.arange(9,dtype='int64').reshape(-1,1), index=idx, columns=['a'])\n expected = pd.DataFrame({'month': [pd.Period('2013-01', freq='M')] * 3 +\n [pd.Period('2013-02', freq='M')] * 3 +\n [pd.Period('2013-03', freq='M')] * 3,\n 'feature': ['a', 'b', 'c'] * 3,\n 'a': np.arange(9, dtype='int64')},\n columns=['month', 'feature', 'a'])\n assert_frame_equal(df.reset_index(), expected)\n\n def test_set_index_period(self):\n # GH 6631\n df = DataFrame(np.random.random(6))\n idx1 = pd.period_range('2011-01-01', periods=3, freq='M')\n idx1 = idx1.append(idx1)\n idx2 = pd.period_range('2013-01-01 09:00', periods=2, freq='H')\n idx2 = idx2.append(idx2).append(idx2)\n idx3 = pd.period_range('2005', periods=6, freq='Y')\n\n df = df.set_index(idx1)\n df = df.set_index(idx2, append=True)\n df = df.set_index(idx3, append=True)\n\n expected1 = pd.period_range('2011-01-01', periods=3, freq='M')\n expected2 = pd.period_range('2013-01-01 09:00', periods=2, freq='H')\n\n self.assertTrue(df.index.levels[0].equals(expected1))\n self.assertTrue(df.index.levels[1].equals(expected2))\n self.assertTrue(df.index.levels[2].equals(idx3))\n\n self.assertTrue(df.index.get_level_values(0).equals(idx1))\n self.assertTrue(df.index.get_level_values(1).equals(idx2))\n self.assertTrue(df.index.get_level_values(2).equals(idx3))\n\n\nif __name__ == '__main__':\n\n import nose\n nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],\n exit=False)\n" ]
[ [ "pandas.Series", "pandas.Period", "numpy.random.seed", "pandas.Timestamp.today", "pandas.compat.zip", "pandas.util.testing.assert_series_equal", "pandas.util.testing.assert_almost_equal", "pandas.DataFrame.from_dict", "pandas.period_range", "pandas.util.testing.makeTimeDataFrame", "pandas.PeriodIndex", "pandas.core.common.is_float_dtype", "pandas.util.testing._skip_if_no_pytz", "pandas.core.index.MultiIndex.from_arrays", "pandas.notnull", "pandas.core.index.MultiIndex", "pandas.compat.StringIO", "pandas.util.testing.assert_panel_equal", "pandas.to_datetime", "numpy.random.rand", "numpy.isnan", "pandas.isnull", "pandas.Timestamp", "pandas.compat.lzip", "numpy.random.randint", "pandas.date_range", "pandas.Panel", "pandas.util.testing.assert_numpy_array_equal", "pandas.MultiIndex.from_product", "pandas.compat.product", "numpy.arange", "pandas.core.common.is_integer_dtype", "numpy.int32", "pandas.util.testing.assertRaisesRegexp", "numpy.putmask", "pandas.Index", "numpy.array", "pandas.compat.u", "pandas.DatetimeIndex", "pandas.MultiIndex.from_arrays", "pandas.core.index.MultiIndex.from_tuples", "numpy.random.randn", "pandas.DataFrame", "pandas.core.index.Index", "numpy.random.random", "pandas.compat.range", "pandas.compat.lrange", "pandas.util.testing.assert_isinstance", "pandas.util.testing.assert_frame_equal" ] ]
driesvr/The-Photoswitch-Dataset
[ "fbc7858343b56ed8526ed6a3feeed260fac1963c" ]
[ "property_prediction/predict_with_RF.py" ]
[ "# Copyright Ryan-Rhys Griffiths and Aditya Raymond Thawani 2020\n# Author: Ryan-Rhys Griffiths\n\"\"\"\nProperty prediction on the photoswitch dataset using Random Forest.\n\"\"\"\n\nimport argparse\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n\nfrom data_utils import TaskDataLoader, transform_data, featurise_mols\n\n\ndef main(path, task, representation, use_pca, n_trials, test_set_size):\n \"\"\"\n :param path: str specifying path to dataset.\n :param task: str specifying the task. One of ['e_iso_pi', 'z_iso_pi', 'e_iso_n', 'z_iso_n']\n :param representation: str specifying the molecular representation. One of ['fingerprints, 'fragments', 'fragprints']\n :param use_pca: bool. If True apply PCA to perform Principal Components Regression.\n :param n_trials: int specifying number of random train/test splits to use\n :param test_set_size: float in range [0, 1] specifying fraction of dataset to use as test set.\n \"\"\"\n\n data_loader = TaskDataLoader(task, path)\n smiles_list, y = data_loader.load_property_data()\n\n X = featurise_mols(smiles_list, representation)\n\n if use_pca:\n n_components = 50\n else:\n n_components = None\n\n r2_list = []\n rmse_list = []\n mae_list = []\n\n print('\\nBeginning training loop...')\n\n for i in range(0, n_trials):\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_set_size, random_state=i)\n y_train = y_train.reshape(-1, 1)\n y_test = y_test.reshape(-1, 1)\n X_train, y_train, X_test, y_test, y_scaler = transform_data(X_train, y_train, X_test, y_test, n_components, use_pca)\n\n regr_rf = RandomForestRegressor(n_estimators=1000, max_depth=300, random_state=2)\n regr_rf.fit(X_train, y_train)\n\n # Output Standardised RMSE and RMSE on Train Set\n\n y_pred_train = regr_rf.predict(X_train)\n train_rmse_stan = np.sqrt(mean_squared_error(y_train, y_pred_train))\n train_rmse = np.sqrt(mean_squared_error(y_scaler.inverse_transform(y_train), y_scaler.inverse_transform(y_pred_train)))\n print(\"\\nStandardised Train RMSE: {:.3f}\".format(train_rmse_stan))\n print(\"Train RMSE: {:.3f}\".format(train_rmse))\n\n # Predict on new data\n y_rf = regr_rf.predict(X_test)\n y_rf = y_scaler.inverse_transform(y_rf)\n y_test = y_scaler.inverse_transform(y_test)\n score = r2_score(y_test, y_rf)\n rmse = np.sqrt(mean_squared_error(y_test, y_rf))\n mae = mean_absolute_error(y_test, y_rf)\n\n print(\"\\nR^2: {:.3f}\".format(score))\n print(\"RMSE: {:.3f}\".format(rmse))\n print(\"MAE: {:.3f}\".format(mae))\n\n r2_list.append(score)\n rmse_list.append(rmse)\n mae_list.append(mae)\n\n r2_list = np.array(r2_list)\n rmse_list = np.array(rmse_list)\n mae_list = np.array(mae_list)\n print(\"\\nmean R^2: {:.4f} +- {:.4f}\".format(np.mean(r2_list), np.std(r2_list)/np.sqrt(len(r2_list))))\n print(\"mean RMSE: {:.4f} +- {:.4f}\".format(np.mean(rmse_list), np.std(rmse_list)/np.sqrt(len(rmse_list))))\n print(\"mean MAE: {:.4f} +- {:.4f}\\n\".format(np.mean(mae_list), np.std(mae_list)/np.sqrt(len(mae_list))))\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-p', '--path', type=str, default='../dataset/photoswitches.csv',\n help='Path to the photoswitches.csv file.')\n parser.add_argument('-t', '--task', type=str, default='e_iso_pi',\n help='str specifying the task. One of [e_iso_pi, z_iso_pi, e_iso_n, z_iso_n].')\n parser.add_argument('-r', '--representation', type=str, default='fragprints',\n help='str specifying the molecular representation. '\n 'One of [fingerprints, fragments, fragprints].')\n parser.add_argument('-pca', '--use_pca', type=bool, default=False,\n help='If True apply PCA to perform Principal Components Regression.')\n parser.add_argument('-n', '--n_trials', type=int, default=20,\n help='int specifying number of random train/test splits to use')\n parser.add_argument('-ts', '--test_set_size', type=float, default=0.2,\n help='float in range [0, 1] specifying fraction of dataset to use as test set')\n\n args = parser.parse_args()\n\n main(args.path, args.task, args.representation, args.use_pca, args.n_trials, args.test_set_size)\n" ]
[ [ "sklearn.metrics.mean_squared_error", "sklearn.metrics.mean_absolute_error", "sklearn.ensemble.RandomForestRegressor", "numpy.array", "numpy.std", "sklearn.metrics.r2_score", "sklearn.model_selection.train_test_split", "numpy.mean" ] ]
Zhiquan-Wen/D-VQA
[ "688c4dcc811f49b431daea81406e628ec71a7247" ]
[ "data/utils.py" ]
[ "from __future__ import print_function\r\n\r\nimport errno\r\nimport os\r\nfrom PIL import Image\r\nimport torch\r\nimport torch.nn as nn\r\nimport re\r\n\r\nimport json\r\nimport pickle as cPickle\r\nimport numpy as np\r\nimport utils\r\nimport h5py\r\nimport operator\r\nimport functools\r\nfrom torch._six import string_classes\r\nimport torch.nn.functional as F\r\nimport collections\r\n\r\n#from pycocotools.coco import COCO\r\n# from scipy.sparse import coo_matrix\r\n# from sklearn.metrics.pairwise import cosine_similarity\r\nfrom torch.utils.data.dataloader import default_collate\r\n\r\n\r\nEPS = 1e-7\r\n\r\n\r\ndef assert_eq(real, expected):\r\n assert real == expected, '%s (true) vs %s (expected)' % (real, expected)\r\n\r\n\r\ndef assert_array_eq(real, expected):\r\n assert (np.abs(real-expected) < EPS).all(), \\\r\n '%s (true) vs %s (expected)' % (real, expected)\r\n\r\n\r\ndef load_folder(folder, suffix):\r\n imgs = []\r\n for f in sorted(os.listdir(folder)):\r\n if f.endswith(suffix):\r\n imgs.append(os.path.join(folder, f))\r\n return imgs\r\n\r\n\r\ndef load_imageid(folder):\r\n images = load_folder(folder, 'jpg')\r\n img_ids = set()\r\n for img in images:\r\n img_id = int(img.split('/')[-1].split('.')[0].split('_')[-1])\r\n img_ids.add(img_id)\r\n return img_ids\r\n\r\n\r\ndef pil_loader(path):\r\n with open(path, 'rb') as f:\r\n with Image.open(f) as img:\r\n return img.convert('RGB')\r\n\r\n\r\ndef weights_init(m):\r\n \"\"\"custom weights initialization.\"\"\"\r\n cname = m.__class__\r\n if cname == nn.Linear or cname == nn.Conv2d or cname == nn.ConvTranspose2d:\r\n m.weight.data.normal_(0.0, 0.02)\r\n elif cname == nn.BatchNorm2d:\r\n m.weight.data.normal_(1.0, 0.02)\r\n m.bias.data.fill_(0)\r\n else:\r\n print('%s is not initialized.' % cname)\r\n\r\n\r\ndef init_net(net, net_file):\r\n if net_file:\r\n net.load_state_dict(torch.load(net_file))\r\n else:\r\n net.apply(weights_init)\r\n\r\n\r\ndef create_dir(path):\r\n if not os.path.exists(path):\r\n try:\r\n os.makedirs(path)\r\n except OSError as exc:\r\n if exc.errno != errno.EEXIST:\r\n raise\r\n\r\n\r\nclass Logger(object):\r\n def __init__(self, output_name):\r\n dirname = os.path.dirname(output_name)\r\n if not os.path.exists(dirname):\r\n os.mkdir(dirname)\r\n\r\n self.log_file = open(output_name, 'w')\r\n self.infos = {}\r\n\r\n def append(self, key, val):\r\n vals = self.infos.setdefault(key, [])\r\n vals.append(val)\r\n\r\n def log(self, extra_msg=''):\r\n msgs = [extra_msg]\r\n for key, vals in self.infos.iteritems():\r\n msgs.append('%s %.6f' % (key, np.mean(vals)))\r\n msg = '\\n'.join(msgs)\r\n self.log_file.write(msg + '\\n')\r\n self.log_file.flush()\r\n self.infos = {}\r\n return msg\r\n\r\n def write(self, msg):\r\n self.log_file.write(msg + '\\n')\r\n self.log_file.flush()\r\n print(msg)\r\n\r\ndef print_model(model, logger):\r\n print(model)\r\n nParams = 0\r\n for w in model.parameters():\r\n nParams += functools.reduce(operator.mul, w.size(), 1)\r\n if logger:\r\n logger.write('nParams=\\t'+str(nParams))\r\n\r\n\r\ndef save_model(path, model, epoch, optimizer=None):\r\n model_dict = {\r\n 'epoch': epoch,\r\n 'model_state': model.state_dict()\r\n }\r\n if optimizer is not None:\r\n model_dict['optimizer_state'] = optimizer.state_dict()\r\n\r\n torch.save(model_dict, path)\r\n\r\ndef rho_select(pad, lengths):\r\n # Index of the last output for each sequence.\r\n idx_ = (lengths-1).view(-1,1).expand(pad.size(0), pad.size(2)).unsqueeze(1)\r\n extracted = pad.gather(1, idx_).squeeze(1)\r\n return extracted\r\n\r\ndef trim_collate(batch):\r\n \"Puts each data field into a tensor with outer dimension batch size\"\r\n _use_shared_memory = True\r\n error_msg = \"batch must contain tensors, numbers, dicts or lists; found {}\"\r\n elem_type = type(batch[0])\r\n if torch.is_tensor(batch[0]):\r\n out = None\r\n if 1 < batch[0].dim(): # image features\r\n max_num_boxes = max([x.size(0) for x in batch])\r\n if _use_shared_memory:\r\n # If we're in a background process, concatenate directly into a\r\n # shared memory tensor to avoid an extra copy\r\n numel = len(batch) * max_num_boxes * batch[0].size(-1)\r\n storage = batch[0].storage()._new_shared(numel)\r\n out = batch[0].new(storage)\r\n # warning: F.pad returns Variable!\r\n return torch.stack([F.pad(x, (0,0,0,max_num_boxes-x.size(0))).data for x in batch], 0, out=out)\r\n else:\r\n if _use_shared_memory:\r\n # If we're in a background process, concatenate directly into a\r\n # shared memory tensor to avoid an extra copy\r\n numel = sum([x.numel() for x in batch])\r\n storage = batch[0].storage()._new_shared(numel)\r\n out = batch[0].new(storage)\r\n return torch.stack(batch, 0, out=out)\r\n elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \\\r\n and elem_type.__name__ != 'string_':\r\n elem = batch[0]\r\n if elem_type.__name__ == 'ndarray':\r\n # array of string classes and object\r\n if re.search('[SaUO]', elem.dtype.str) is not None:\r\n raise TypeError(error_msg.format(elem.dtype))\r\n\r\n return torch.stack([torch.from_numpy(b) for b in batch], 0)\r\n if elem.shape == (): # scalars\r\n py_type = float if elem.dtype.name.startswith('float') else int\r\n return numpy_type_map[elem.dtype.name](list(map(py_type, batch)))\r\n elif isinstance(batch[0], int):\r\n return torch.LongTensor(batch)\r\n elif isinstance(batch[0], float):\r\n return torch.DoubleTensor(batch)\r\n elif isinstance(batch[0], string_classes):\r\n return batch\r\n elif isinstance(batch[0], collections.Mapping):\r\n return {key: default_collate([d[key] for d in batch]) for key in batch[0]}\r\n elif isinstance(batch[0], collections.Sequence):\r\n transposed = zip(*batch)\r\n return [trim_collate(samples) for samples in transposed]\r\n\r\n raise TypeError((error_msg.format(type(batch[0]))))\r\n\r\n\r\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\r\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\r\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\r\n indices = torch.from_numpy(\r\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\r\n values = torch.from_numpy(sparse_mx.data)\r\n shape = torch.Size(sparse_mx.shape)\r\n return torch.sparse.FloatTensor(indices, values, shape)\r\n\r\n\r\ndef mask_softmax(x, lengths): # , dim=1)\r\n mask = torch.zeros_like(x).to(device=x.device, non_blocking=True)\r\n t_lengths = lengths[:, :, None].expand_as(mask)\r\n arange_id = torch.arange(mask.size(1)).to(device=x.device, non_blocking=True)\r\n arange_id = arange_id[None, :, None].expand_as(mask)\r\n\r\n mask[arange_id < t_lengths] = 1\r\n # https://stackoverflow.com/questions/42599498/numercially-stable-softmax\r\n # https://stackoverflow.com/questions/34968722/how-to-implement-the-softmax-function-in-python\r\n # exp(x - max(x)) instead of exp(x) is a trick\r\n # to improve the numerical stability while giving\r\n # the same outputs\r\n x2 = torch.exp(x - torch.max(x))\r\n x3 = x2 * mask\r\n epsilon = 1e-5\r\n x3_sum = torch.sum(x3, dim=1, keepdim=True) + epsilon\r\n x4 = x3 / x3_sum.expand_as(x3)\r\n return x4\r\n\r\n\r\nclass GradReverseMask(torch.autograd.Function):\r\n \"\"\"\r\n This layer is used to create an adversarial loss.\r\n\r\n \"\"\"\r\n\r\n @staticmethod\r\n def forward(ctx, x, mask, weight):\r\n \"\"\"\r\n The mask should be composed of 0 or 1.\r\n The '1' will get their gradient reversed..\r\n \"\"\"\r\n ctx.save_for_backward(mask)\r\n ctx.weight = weight\r\n return x.view_as(x)\r\n\r\n @staticmethod\r\n def backward(ctx, grad_output):\r\n mask, = ctx.saved_tensors\r\n mask_c = mask.clone().detach().float()\r\n mask_c[mask == 0] = 1.0\r\n mask_c[mask == 1] = - float(ctx.weight)\r\n return grad_output * mask_c[:, None].float(), None, None\r\n\r\n\r\ndef grad_reverse_mask(x, mask, weight=1):\r\n return GradReverseMask.apply(x, mask, weight)\r\n\r\n\r\nclass GradReverse(torch.autograd.Function):\r\n \"\"\"\r\n This layer is used to create an adversarial loss.\r\n \"\"\"\r\n\r\n @staticmethod\r\n def forward(ctx, x):\r\n return x.view_as(x)\r\n\r\n @staticmethod\r\n def backward(ctx, grad_output):\r\n return grad_output.neg()\r\n\r\n\r\ndef grad_reverse(x):\r\n return GradReverse.apply(x)\r\n\r\n\r\nclass GradMulConst(torch.autograd.Function):\r\n \"\"\"\r\n This layer is used to create an adversarial loss.\r\n \"\"\"\r\n\r\n @staticmethod\r\n def forward(ctx, x, const):\r\n ctx.const = const\r\n return x.view_as(x)\r\n\r\n @staticmethod\r\n def backward(ctx, grad_output):\r\n return grad_output * ctx.const, None\r\n\r\n\r\ndef grad_mul_const(x, const):\r\n return GradMulConst.apply(x, const)\r\n" ]
[ [ "torch.sum", "numpy.vstack", "torch.utils.data.dataloader.default_collate", "torch.stack", "torch.Size", "torch.load", "torch.zeros_like", "torch.save", "numpy.abs", "torch.DoubleTensor", "torch.sparse.FloatTensor", "torch.is_tensor", "torch.from_numpy", "torch.max", "torch.LongTensor", "numpy.mean" ] ]
leo0519/TensorRT
[ "498dcb009fe4c2dedbe9c61044d3de4f3c04a41b", "498dcb009fe4c2dedbe9c61044d3de4f3c04a41b" ]
[ "samples/python/yolov3_onnx/yolov3_to_onnx.py", "demo/HuggingFace/T5/export.py" ]
[ "#!/usr/bin/env python3\n#\n# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import print_function\nfrom collections import OrderedDict\nimport sys\nimport os\n\nimport onnx\nfrom onnx import helper\nfrom onnx import TensorProto\nimport numpy as np\n\nsys.path.insert(1, os.path.join(sys.path[0], os.path.pardir))\nfrom downloader import getFilePath\n\n\nclass DarkNetParser(object):\n \"\"\"Definition of a parser for DarkNet-based YOLOv3-608 (only tested for this topology).\"\"\"\n\n def __init__(self, supported_layers):\n \"\"\"Initializes a DarkNetParser object.\n\n Keyword argument:\n supported_layers -- a string list of supported layers in DarkNet naming convention,\n parameters are only added to the class dictionary if a parsed layer is included.\n \"\"\"\n\n # A list of YOLOv3 layers containing dictionaries with all layer\n # parameters:\n self.layer_configs = OrderedDict()\n self.supported_layers = supported_layers\n self.layer_counter = 0\n\n def parse_cfg_file(self, cfg_file_path):\n \"\"\"Takes the yolov3.cfg file and parses it layer by layer,\n appending each layer's parameters as a dictionary to layer_configs.\n\n Keyword argument:\n cfg_file_path -- path to the yolov3.cfg file as string\n \"\"\"\n with open(cfg_file_path) as cfg_file:\n remainder = cfg_file.read()\n while remainder is not None:\n layer_dict, layer_name, remainder = self._next_layer(remainder)\n if layer_dict is not None:\n self.layer_configs[layer_name] = layer_dict\n return self.layer_configs\n\n def _next_layer(self, remainder):\n \"\"\"Takes in a string and segments it by looking for DarkNet delimiters.\n Returns the layer parameters and the remaining string after the last delimiter.\n Example for the first Conv layer in yolo.cfg ...\n\n [convolutional]\n batch_normalize=1\n filters=32\n size=3\n stride=1\n pad=1\n activation=leaky\n\n ... becomes the following layer_dict return value:\n {'activation': 'leaky', 'stride': 1, 'pad': 1, 'filters': 32,\n 'batch_normalize': 1, 'type': 'convolutional', 'size': 3}.\n\n '001_convolutional' is returned as layer_name, and all lines that follow in yolo.cfg\n are returned as the next remainder.\n\n Keyword argument:\n remainder -- a string with all raw text after the previously parsed layer\n \"\"\"\n remainder = remainder.split('[', 1)\n if len(remainder) == 2:\n remainder = remainder[1]\n else:\n return None, None, None\n remainder = remainder.split(']', 1)\n if len(remainder) == 2:\n layer_type, remainder = remainder\n else:\n return None, None, None\n if remainder.replace(' ', '')[0] == '#':\n remainder = remainder.split('\\n', 1)[1]\n\n layer_param_block, remainder = remainder.split('\\n\\n', 1)\n layer_param_lines = layer_param_block.split('\\n')[1:]\n layer_name = str(self.layer_counter).zfill(3) + '_' + layer_type\n layer_dict = dict(type=layer_type)\n if layer_type in self.supported_layers:\n for param_line in layer_param_lines:\n if param_line[0] == '#':\n continue\n param_type, param_value = self._parse_params(param_line)\n layer_dict[param_type] = param_value\n self.layer_counter += 1\n return layer_dict, layer_name, remainder\n\n def _parse_params(self, param_line):\n \"\"\"Identifies the parameters contained in one of the cfg file and returns\n them in the required format for each parameter type, e.g. as a list, an int or a float.\n\n Keyword argument:\n param_line -- one parsed line within a layer block\n \"\"\"\n param_line = param_line.replace(' ', '')\n param_type, param_value_raw = param_line.split('=')\n param_value = None\n if param_type == 'layers':\n layer_indexes = list()\n for index in param_value_raw.split(','):\n layer_indexes.append(int(index))\n param_value = layer_indexes\n elif isinstance(param_value_raw, str) and not param_value_raw.isalpha():\n condition_param_value_positive = param_value_raw.isdigit()\n condition_param_value_negative = param_value_raw[0] == '-' and \\\n param_value_raw[1:].isdigit()\n if condition_param_value_positive or condition_param_value_negative:\n param_value = int(param_value_raw)\n else:\n param_value = float(param_value_raw)\n else:\n param_value = str(param_value_raw)\n return param_type, param_value\n\n\nclass MajorNodeSpecs(object):\n \"\"\"Helper class used to store the names of ONNX output names,\n corresponding to the output of a DarkNet layer and its output channels.\n Some DarkNet layers are not created and there is no corresponding ONNX node,\n but we still need to track them in order to set up skip connections.\n \"\"\"\n\n def __init__(self, name, channels):\n \"\"\" Initialize a MajorNodeSpecs object.\n\n Keyword arguments:\n name -- name of the ONNX node\n channels -- number of output channels of this node\n \"\"\"\n self.name = name\n self.channels = channels\n self.created_onnx_node = False\n if name is not None and isinstance(channels, int) and channels > 0:\n self.created_onnx_node = True\n\n\nclass ConvParams(object):\n \"\"\"Helper class to store the hyper parameters of a Conv layer,\n including its prefix name in the ONNX graph and the expected dimensions\n of weights for convolution, bias, and batch normalization.\n\n Additionally acts as a wrapper for generating safe names for all\n weights, checking on feasible combinations.\n \"\"\"\n\n def __init__(self, node_name, batch_normalize, conv_weight_dims):\n \"\"\"Constructor based on the base node name (e.g. 101_convolutional), the batch\n normalization setting, and the convolutional weights shape.\n\n Keyword arguments:\n node_name -- base name of this YOLO convolutional layer\n batch_normalize -- bool value if batch normalization is used\n conv_weight_dims -- the dimensions of this layer's convolutional weights\n \"\"\"\n self.node_name = node_name\n self.batch_normalize = batch_normalize\n assert len(conv_weight_dims) == 4\n self.conv_weight_dims = conv_weight_dims\n\n def generate_param_name(self, param_category, suffix):\n \"\"\"Generates a name based on two string inputs,\n and checks if the combination is valid.\"\"\"\n assert suffix\n assert param_category in ['bn', 'conv']\n assert(suffix in ['scale', 'mean', 'var', 'weights', 'bias'])\n if param_category == 'bn':\n assert self.batch_normalize\n assert suffix in ['scale', 'bias', 'mean', 'var']\n elif param_category == 'conv':\n assert suffix in ['weights', 'bias']\n if suffix == 'bias':\n assert not self.batch_normalize\n param_name = self.node_name + '_' + param_category + '_' + suffix\n return param_name\n\nclass ResizeParams(object):\n #Helper class to store the scale parameter for an Resize node.\n\n def __init__(self, node_name, value):\n \"\"\"Constructor based on the base node name (e.g. 86_Resize),\n and the value of the scale input tensor.\n\n Keyword arguments:\n node_name -- base name of this YOLO Resize layer\n value -- the value of the scale input to the Resize layer as numpy array\n \"\"\"\n self.node_name = node_name\n self.value = value\n\n def generate_param_name(self):\n \"\"\"Generates the scale parameter name for the Resize node.\"\"\"\n param_name = self.node_name + '_' + \"scale\"\n return param_name\n\n def generate_roi_name(self):\n \"\"\"Generates the roi input name for the Resize node.\"\"\"\n param_name = self.node_name + '_' + \"roi\"\n return param_name\n\nclass WeightLoader(object):\n \"\"\"Helper class used for loading the serialized weights of a binary file stream\n and returning the initializers and the input tensors required for populating\n the ONNX graph with weights.\n \"\"\"\n\n def __init__(self, weights_file_path):\n \"\"\"Initialized with a path to the YOLOv3 .weights file.\n\n Keyword argument:\n weights_file_path -- path to the weights file.\n \"\"\"\n self.weights_file = self._open_weights_file(weights_file_path)\n\n def load_resize_scales(self, resize_params):\n \"\"\"Returns the initializers with the value of the scale input\n tensor given by resize_params.\n\n Keyword argument:\n resize_params -- a ResizeParams object\n \"\"\"\n initializer = list()\n inputs = list()\n name = resize_params.generate_param_name()\n shape = resize_params.value.shape\n data = resize_params.value\n scale_init = helper.make_tensor(\n name, TensorProto.FLOAT, shape, data)\n scale_input = helper.make_tensor_value_info(\n name, TensorProto.FLOAT, shape)\n initializer.append(scale_init)\n inputs.append(scale_input)\n\n # In opset 11 an additional input named roi is required. Create a dummy tensor to satisfy this.\n # It is a 1D tensor of size of the rank of the input (4)\n rank = 4\n roi_name = resize_params.generate_roi_name()\n roi_input = helper.make_tensor_value_info(roi_name, TensorProto.FLOAT, [rank])\n roi_init = helper.make_tensor(roi_name, TensorProto.FLOAT, [rank], [0,0,0,0])\n initializer.append(roi_init)\n inputs.append(roi_input)\n\n return initializer, inputs\n\n\n def load_conv_weights(self, conv_params):\n \"\"\"Returns the initializers with weights from the weights file and\n the input tensors of a convolutional layer for all corresponding ONNX nodes.\n\n Keyword argument:\n conv_params -- a ConvParams object\n \"\"\"\n initializer = list()\n inputs = list()\n if conv_params.batch_normalize:\n bias_init, bias_input = self._create_param_tensors(\n conv_params, 'bn', 'bias')\n bn_scale_init, bn_scale_input = self._create_param_tensors(\n conv_params, 'bn', 'scale')\n bn_mean_init, bn_mean_input = self._create_param_tensors(\n conv_params, 'bn', 'mean')\n bn_var_init, bn_var_input = self._create_param_tensors(\n conv_params, 'bn', 'var')\n initializer.extend(\n [bn_scale_init, bias_init, bn_mean_init, bn_var_init])\n inputs.extend([bn_scale_input, bias_input,\n bn_mean_input, bn_var_input])\n else:\n bias_init, bias_input = self._create_param_tensors(\n conv_params, 'conv', 'bias')\n initializer.append(bias_init)\n inputs.append(bias_input)\n conv_init, conv_input = self._create_param_tensors(\n conv_params, 'conv', 'weights')\n initializer.append(conv_init)\n inputs.append(conv_input)\n return initializer, inputs\n\n def _open_weights_file(self, weights_file_path):\n \"\"\"Opens a YOLOv3 DarkNet file stream and skips the header.\n\n Keyword argument:\n weights_file_path -- path to the weights file.\n \"\"\"\n weights_file = open(weights_file_path, 'rb')\n length_header = 5\n np.ndarray(\n shape=(length_header, ), dtype='int32', buffer=weights_file.read(\n length_header * 4))\n return weights_file\n\n def _create_param_tensors(self, conv_params, param_category, suffix):\n \"\"\"Creates the initializers with weights from the weights file together with\n the input tensors.\n\n Keyword arguments:\n conv_params -- a ConvParams object\n param_category -- the category of parameters to be created ('bn' or 'conv')\n suffix -- a string determining the sub-type of above param_category (e.g.,\n 'weights' or 'bias')\n \"\"\"\n param_name, param_data, param_data_shape = self._load_one_param_type(\n conv_params, param_category, suffix)\n\n initializer_tensor = helper.make_tensor(\n param_name, TensorProto.FLOAT, param_data_shape, param_data)\n input_tensor = helper.make_tensor_value_info(\n param_name, TensorProto.FLOAT, param_data_shape)\n return initializer_tensor, input_tensor\n\n def _load_one_param_type(self, conv_params, param_category, suffix):\n \"\"\"Deserializes the weights from a file stream in the DarkNet order.\n\n Keyword arguments:\n conv_params -- a ConvParams object\n param_category -- the category of parameters to be created ('bn' or 'conv')\n suffix -- a string determining the sub-type of above param_category (e.g.,\n 'weights' or 'bias')\n \"\"\"\n param_name = conv_params.generate_param_name(param_category, suffix)\n channels_out, channels_in, filter_h, filter_w = conv_params.conv_weight_dims\n if param_category == 'bn':\n param_shape = [channels_out]\n elif param_category == 'conv':\n if suffix == 'weights':\n param_shape = [channels_out, channels_in, filter_h, filter_w]\n elif suffix == 'bias':\n param_shape = [channels_out]\n param_size = np.product(np.array(param_shape))\n param_data = np.ndarray(\n shape=param_shape,\n dtype='float32',\n buffer=self.weights_file.read(param_size * 4))\n param_data = param_data.flatten().astype(float)\n return param_name, param_data, param_shape\n\n\nclass GraphBuilderONNX(object):\n \"\"\"Class for creating an ONNX graph from a previously generated list of layer dictionaries.\"\"\"\n\n def __init__(self, output_tensors):\n \"\"\"Initialize with all DarkNet default parameters used creating YOLOv3,\n and specify the output tensors as an OrderedDict for their output dimensions\n with their names as keys.\n\n Keyword argument:\n output_tensors -- the output tensors as an OrderedDict containing the keys'\n output dimensions\n \"\"\"\n self.output_tensors = output_tensors\n self._nodes = list()\n self.graph_def = None\n self.input_tensor = None\n self.epsilon_bn = 1e-5\n self.momentum_bn = 0.99\n self.alpha_lrelu = 0.1\n self.param_dict = OrderedDict()\n self.major_node_specs = list()\n self.batch_size = 1\n\n def build_onnx_graph(\n self,\n layer_configs,\n weights_file_path,\n verbose=True):\n \"\"\"Iterate over all layer configs (parsed from the DarkNet representation\n of YOLOv3-608), create an ONNX graph, populate it with weights from the weights\n file and return the graph definition.\n\n Keyword arguments:\n layer_configs -- an OrderedDict object with all parsed layers' configurations\n weights_file_path -- location of the weights file\n verbose -- toggles if the graph is printed after creation (default: True)\n \"\"\"\n for layer_name in layer_configs.keys():\n layer_dict = layer_configs[layer_name]\n major_node_specs = self._make_onnx_node(layer_name, layer_dict)\n if major_node_specs.name is not None:\n self.major_node_specs.append(major_node_specs)\n outputs = list()\n for tensor_name in self.output_tensors.keys():\n output_dims = [self.batch_size, ] + \\\n self.output_tensors[tensor_name]\n output_tensor = helper.make_tensor_value_info(\n tensor_name, TensorProto.FLOAT, output_dims)\n outputs.append(output_tensor)\n inputs = [self.input_tensor]\n weight_loader = WeightLoader(weights_file_path)\n initializer = list()\n # If a layer has parameters, add them to the initializer and input lists.\n for layer_name in self.param_dict.keys():\n _, layer_type = layer_name.split('_', 1)\n params = self.param_dict[layer_name]\n if layer_type == 'convolutional':\n initializer_layer, inputs_layer = weight_loader.load_conv_weights(\n params)\n initializer.extend(initializer_layer)\n inputs.extend(inputs_layer)\n elif layer_type == \"upsample\":\n initializer_layer, inputs_layer = weight_loader.load_resize_scales(\n params)\n initializer.extend(initializer_layer)\n inputs.extend(inputs_layer)\n del weight_loader\n self.graph_def = helper.make_graph(\n nodes=self._nodes,\n name='YOLOv3-608',\n inputs=inputs,\n outputs=outputs,\n initializer=initializer\n )\n if verbose:\n print(helper.printable_graph(self.graph_def))\n model_def = helper.make_model(self.graph_def,\n producer_name='NVIDIA TensorRT sample')\n return model_def\n\n def _make_onnx_node(self, layer_name, layer_dict):\n \"\"\"Take in a layer parameter dictionary, choose the correct function for\n creating an ONNX node and store the information important to graph creation\n as a MajorNodeSpec object.\n\n Keyword arguments:\n layer_name -- the layer's name (also the corresponding key in layer_configs)\n layer_dict -- a layer parameter dictionary (one element of layer_configs)\n \"\"\"\n layer_type = layer_dict['type']\n if self.input_tensor is None:\n if layer_type == 'net':\n major_node_output_name, major_node_output_channels = self._make_input_tensor(\n layer_name, layer_dict)\n major_node_specs = MajorNodeSpecs(major_node_output_name,\n major_node_output_channels)\n else:\n raise ValueError('The first node has to be of type \"net\".')\n else:\n node_creators = dict()\n node_creators['convolutional'] = self._make_conv_node\n node_creators['shortcut'] = self._make_shortcut_node\n node_creators['route'] = self._make_route_node\n node_creators['upsample'] = self._make_resize_node\n\n if layer_type in node_creators.keys():\n major_node_output_name, major_node_output_channels = \\\n node_creators[layer_type](layer_name, layer_dict)\n major_node_specs = MajorNodeSpecs(major_node_output_name,\n major_node_output_channels)\n else:\n print(\n 'Layer of type %s not supported, skipping ONNX node generation.' %\n layer_type)\n major_node_specs = MajorNodeSpecs(layer_name,\n None)\n return major_node_specs\n\n def _make_input_tensor(self, layer_name, layer_dict):\n \"\"\"Create an ONNX input tensor from a 'net' layer and store the batch size.\n\n Keyword arguments:\n layer_name -- the layer's name (also the corresponding key in layer_configs)\n layer_dict -- a layer parameter dictionary (one element of layer_configs)\n \"\"\"\n batch_size = layer_dict['batch']\n channels = layer_dict['channels']\n height = layer_dict['height']\n width = layer_dict['width']\n self.batch_size = batch_size\n input_tensor = helper.make_tensor_value_info(\n str(layer_name), TensorProto.FLOAT, [\n batch_size, channels, height, width])\n self.input_tensor = input_tensor\n return layer_name, channels\n\n def _get_previous_node_specs(self, target_index=-1):\n \"\"\"Get a previously generated ONNX node (skip those that were not generated).\n Target index can be passed for jumping to a specific index.\n\n Keyword arguments:\n target_index -- optional for jumping to a specific index (default: -1 for jumping\n to previous element)\n \"\"\"\n previous_node = None\n for node in self.major_node_specs[target_index::-1]:\n if node.created_onnx_node:\n previous_node = node\n break\n assert previous_node is not None\n return previous_node\n\n def _make_conv_node(self, layer_name, layer_dict):\n \"\"\"Create an ONNX Conv node with optional batch normalization and\n activation nodes.\n\n Keyword arguments:\n layer_name -- the layer's name (also the corresponding key in layer_configs)\n layer_dict -- a layer parameter dictionary (one element of layer_configs)\n \"\"\"\n previous_node_specs = self._get_previous_node_specs()\n inputs = [previous_node_specs.name]\n previous_channels = previous_node_specs.channels\n kernel_size = layer_dict['size']\n stride = layer_dict['stride']\n filters = layer_dict['filters']\n batch_normalize = False\n if 'batch_normalize' in layer_dict.keys(\n ) and layer_dict['batch_normalize'] == 1:\n batch_normalize = True\n\n kernel_shape = [kernel_size, kernel_size]\n weights_shape = [filters, previous_channels] + kernel_shape\n conv_params = ConvParams(layer_name, batch_normalize, weights_shape)\n\n strides = [stride, stride]\n dilations = [1, 1]\n weights_name = conv_params.generate_param_name('conv', 'weights')\n inputs.append(weights_name)\n if not batch_normalize:\n bias_name = conv_params.generate_param_name('conv', 'bias')\n inputs.append(bias_name)\n\n conv_node = helper.make_node(\n 'Conv',\n inputs=inputs,\n outputs=[layer_name],\n kernel_shape=kernel_shape,\n strides=strides,\n auto_pad='SAME_LOWER',\n dilations=dilations,\n name=layer_name\n )\n self._nodes.append(conv_node)\n inputs = [layer_name]\n layer_name_output = layer_name\n\n if batch_normalize:\n layer_name_bn = layer_name + '_bn'\n bn_param_suffixes = ['scale', 'bias', 'mean', 'var']\n for suffix in bn_param_suffixes:\n bn_param_name = conv_params.generate_param_name('bn', suffix)\n inputs.append(bn_param_name)\n batchnorm_node = helper.make_node(\n 'BatchNormalization',\n inputs=inputs,\n outputs=[layer_name_bn],\n epsilon=self.epsilon_bn,\n momentum=self.momentum_bn,\n name=layer_name_bn\n )\n self._nodes.append(batchnorm_node)\n inputs = [layer_name_bn]\n layer_name_output = layer_name_bn\n\n if layer_dict['activation'] == 'leaky':\n layer_name_lrelu = layer_name + '_lrelu'\n\n lrelu_node = helper.make_node(\n 'LeakyRelu',\n inputs=inputs,\n outputs=[layer_name_lrelu],\n name=layer_name_lrelu,\n alpha=self.alpha_lrelu\n )\n self._nodes.append(lrelu_node)\n inputs = [layer_name_lrelu]\n layer_name_output = layer_name_lrelu\n elif layer_dict['activation'] == 'linear':\n pass\n else:\n print('Activation not supported.')\n\n self.param_dict[layer_name] = conv_params\n return layer_name_output, filters\n\n def _make_shortcut_node(self, layer_name, layer_dict):\n \"\"\"Create an ONNX Add node with the shortcut properties from\n the DarkNet-based graph.\n\n Keyword arguments:\n layer_name -- the layer's name (also the corresponding key in layer_configs)\n layer_dict -- a layer parameter dictionary (one element of layer_configs)\n \"\"\"\n shortcut_index = layer_dict['from']\n activation = layer_dict['activation']\n assert activation == 'linear'\n\n first_node_specs = self._get_previous_node_specs()\n second_node_specs = self._get_previous_node_specs(\n target_index=shortcut_index)\n assert first_node_specs.channels == second_node_specs.channels\n channels = first_node_specs.channels\n inputs = [first_node_specs.name, second_node_specs.name]\n shortcut_node = helper.make_node(\n 'Add',\n inputs=inputs,\n outputs=[layer_name],\n name=layer_name,\n )\n self._nodes.append(shortcut_node)\n return layer_name, channels\n\n def _make_route_node(self, layer_name, layer_dict):\n \"\"\"If the 'layers' parameter from the DarkNet configuration is only one index, continue\n node creation at the indicated (negative) index. Otherwise, create an ONNX Concat node\n with the route properties from the DarkNet-based graph.\n\n Keyword arguments:\n layer_name -- the layer's name (also the corresponding key in layer_configs)\n layer_dict -- a layer parameter dictionary (one element of layer_configs)\n \"\"\"\n route_node_indexes = layer_dict['layers']\n if len(route_node_indexes) == 1:\n split_index = route_node_indexes[0]\n assert split_index < 0\n # Increment by one because we skipped the YOLO layer:\n split_index += 1\n self.major_node_specs = self.major_node_specs[:split_index]\n layer_name = None\n channels = None\n else:\n inputs = list()\n channels = 0\n for index in route_node_indexes:\n if index > 0:\n # Increment by one because we count the input as a node (DarkNet\n # does not)\n index += 1\n route_node_specs = self._get_previous_node_specs(\n target_index=index)\n inputs.append(route_node_specs.name)\n channels += route_node_specs.channels\n assert inputs\n assert channels > 0\n\n route_node = helper.make_node(\n 'Concat',\n axis=1,\n inputs=inputs,\n outputs=[layer_name],\n name=layer_name,\n )\n self._nodes.append(route_node)\n return layer_name, channels\n\n def _make_resize_node(self, layer_name, layer_dict):\n \"\"\"Create an ONNX Resize node with the properties from\n the DarkNet-based graph.\n\n Keyword arguments:\n layer_name -- the layer's name (also the corresponding key in layer_configs)\n layer_dict -- a layer parameter dictionary (one element of layer_configs)\n \"\"\"\n resize_scale_factors = float(layer_dict['stride'])\n # Create the scale factor array with node parameters\n scales=np.array([1.0, 1.0, resize_scale_factors, resize_scale_factors]).astype(np.float32)\n previous_node_specs = self._get_previous_node_specs()\n inputs = [previous_node_specs.name]\n\n channels = previous_node_specs.channels\n assert channels > 0\n resize_params = ResizeParams(layer_name, scales)\n\n # roi input is the second input, so append it before scales\n roi_name = resize_params.generate_roi_name()\n inputs.append(roi_name)\n\n scales_name = resize_params.generate_param_name()\n inputs.append(scales_name)\n\n resize_node = helper.make_node(\n 'Resize',\n coordinate_transformation_mode='asymmetric',\n mode='nearest',\n nearest_mode='floor',\n inputs=inputs,\n outputs=[layer_name],\n name=layer_name,\n )\n self._nodes.append(resize_node)\n self.param_dict[layer_name] = resize_params\n return layer_name, channels\n\n\ndef main():\n \"\"\"Run the DarkNet-to-ONNX conversion for YOLOv3-608.\"\"\"\n cfg_file_path = getFilePath('samples/python/yolov3_onnx/yolov3.cfg')\n # These are the only layers DarkNetParser will extract parameters from. The three layers of\n # type 'yolo' are not parsed in detail because they are included in the post-processing later:\n supported_layers = ['net', 'convolutional', 'shortcut',\n 'route', 'upsample']\n\n # Create a DarkNetParser object, and the use it to generate an OrderedDict with all\n # layer's configs from the cfg file:\n parser = DarkNetParser(supported_layers)\n layer_configs = parser.parse_cfg_file(cfg_file_path)\n # We do not need the parser anymore after we got layer_configs:\n del parser\n\n # In above layer_config, there are three outputs that we need to know the output\n # shape of (in CHW format):\n output_tensor_dims = OrderedDict()\n output_tensor_dims['082_convolutional'] = [255, 19, 19]\n output_tensor_dims['094_convolutional'] = [255, 38, 38]\n output_tensor_dims['106_convolutional'] = [255, 76, 76]\n\n # Create a GraphBuilderONNX object with the known output tensor dimensions:\n builder = GraphBuilderONNX(output_tensor_dims)\n\n weights_file_path = getFilePath('samples/python/yolov3_onnx/yolov3.weights')\n\n # Now generate an ONNX graph with weights from the previously parsed layer configurations\n # and the weights file:\n yolov3_model_def = builder.build_onnx_graph(\n layer_configs=layer_configs,\n weights_file_path=weights_file_path,\n verbose=True)\n # Once we have the model definition, we do not need the builder anymore:\n del builder\n\n # Perform a sanity check on the ONNX model definition:\n onnx.checker.check_model(yolov3_model_def)\n\n # Serialize the generated ONNX graph to this file:\n output_file_path = 'yolov3.onnx'\n onnx.save(yolov3_model_def, output_file_path)\n\nif __name__ == '__main__':\n main()\n", "#\n# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\nContains logic that captures T5 HuggingFace models into ONNX models.\nInspired by https://github.com/onnx/models/blob/master/text/machine_comprehension/t5/dependencies/T5-export.py\n\"\"\"\n\nfrom itertools import islice\n\n# tensorrt\nimport tensorrt as trt\n\n# polygraphy\nfrom polygraphy.backend.trt import Profile\n\n# torch\nimport torch\nfrom torch.nn import Module\n\n# huggingface\nfrom transformers.generation_utils import GenerationMixin\nfrom transformers.modeling_outputs import Seq2SeqLMOutput\n\n# TRT-HuggingFace\nfrom T5.T5ModelConfig import T5ModelTRTConfig\nfrom NNDF.tensorrt_utils import clamp_weights_onnx_to_fp16_bounds, move_t5_cast_op\nfrom NNDF.networks import NetworkMetadata, Precision\nfrom NNDF.logger import G_LOGGER\nfrom NNDF.models import (\n TRTEngineFile,\n TorchModelFile,\n ONNXModelFile,\n ModelFileConverter,\n)\n\ndef add_extra_fp32(network_definition):\n \"\"\"\n Force operations involved in layer norm to run in FP32 precision.\n \"\"\"\n pow_ops = {}\n for layer_index, layer in enumerate(network_definition[1]):\n if layer.type == trt.LayerType.IDENTITY:\n all_fp32 = all([layer.output_type_is_set(o) and layer.get_output_type(o) == trt.float32 for o in range(layer.num_outputs)])\n if all_fp32:\n if layer.get_input(0).dtype == trt.float32:\n layer.precision = trt.float32\n\n if layer.type == trt.LayerType.ELEMENTWISE:\n layer.__class__ = getattr(trt, \"IElementWiseLayer\")\n if layer.op == trt.ElementWiseOperation.POW:\n pow_ops[layer] = layer_index\n layer.precision = trt.float32\n layer.set_output_type(0, trt.float32)\n\n for _, index in pow_ops.items():\n # Iterate from few layers before pow to include residual add and cast op.\n # Iterate till 10 layers after pow op to include all operations included in layer norm.\n START_OFFSET = 4\n END_OFFSET = 12\n for i in range(index-START_OFFSET, index+END_OFFSET):\n l = network_definition[1].get_layer(i)\n if l.type == trt.LayerType.REDUCE:\n l.precision = trt.float32\n l.set_output_type(0, trt.float32)\n\n if l.type == trt.LayerType.ELEMENTWISE:\n l.__class__ = getattr(trt, \"IElementWiseLayer\")\n if l.op == trt.ElementWiseOperation.SUM:\n l.precision = trt.float32\n l.set_output_type(0, trt.float32)\n\n if l.type == trt.LayerType.UNARY:\n l.__class__ = getattr(trt, \"IUnaryLayer\")\n if l.op == trt.UnaryOperation.SQRT:\n l.precision = trt.float32\n l.set_output_type(0, trt.float32)\n\n if l.type == trt.LayerType.ELEMENTWISE:\n l.__class__ = getattr(trt, \"IElementWiseLayer\")\n if l.op == trt.ElementWiseOperation.DIV:\n l.precision = trt.float32\n l.set_output_type(0, trt.float32)\n\n if l.type == trt.LayerType.ELEMENTWISE:\n l.__class__ = getattr(trt, \"IElementWiseLayer\")\n if l.op == trt.ElementWiseOperation.PROD:\n l.precision = trt.float32\n l.set_output_type(0, trt.float32)\n\n return network_definition\n\n# Torch File Encoding #\nclass T5DecoderTorchFile(TorchModelFile):\n class TorchModule(Module, GenerationMixin):\n \"\"\"\n A simplied definition of T5 Decoder without support for loss.\n Decoder with lm-head attached.\n \"\"\"\n\n def __init__(self, decoder, lm_head, config):\n super().__init__()\n self.decoder = decoder\n self.lm_head = lm_head\n self.config = config\n\n def prepare_inputs_for_generation(self, input_ids, **kwargs):\n return {\n \"input_ids\": input_ids,\n \"encoder_hidden_states\": kwargs[\"encoder_hidden_states\"],\n }\n\n def forward(self, input_ids, encoder_hidden_states, **kwargs):\n decoder_outputs = self.decoder(\n input_ids=input_ids,\n encoder_hidden_states=encoder_hidden_states,\n **kwargs\n )\n\n # self.config.d_model ** -0.5 for rescaling output on vocab.\n # as seen in https://huggingface.co/transformers/_modules/transformers/models/t5/modeling_t5.html#T5ForConditionalGeneration\n sequence_output = decoder_outputs[0] * self.config.d_model ** -0.5\n logits = self.lm_head(sequence_output)\n if not kwargs.get(\"return_dict\", False):\n return (logits,) + decoder_outputs[1:]\n\n return Seq2SeqLMOutput(logits=logits)\n\n def __init__(self, model, network_metadata):\n super().__init__(model, T5DecoderConverter, network_metadata)\n\n\nclass T5EncoderTorchFile(TorchModelFile):\n \"\"\"Creation of a class to output only the last hidden state from the encoder.\"\"\"\n\n class TorchModule(Module, GenerationMixin):\n def __init__(self, encoder):\n super().__init__()\n self.encoder = encoder\n\n def forward(self, *input, **kwargs):\n return self.encoder(*input, **kwargs)[0]\n\n def __call__(self, *args, **kwargs):\n return self.forward(*args, **kwargs)\n\n def __init__(self, model, network_metadata):\n super().__init__(model, T5EncoderConverter, network_metadata)\n\n\n# ONNX File Encoding #\nclass T5EncoderONNXFile(ONNXModelFile):\n def __init__(self, model, network_metadata):\n super().__init__(model, T5EncoderConverter, network_metadata)\n\n\nclass T5DecoderONNXFile(ONNXModelFile):\n def __init__(self, model, network_metadata):\n super().__init__(model, T5DecoderConverter, network_metadata)\n\n\n# TRT Engine File Encoding #\nclass T5DecoderTRTEngine(TRTEngineFile):\n DEFAULT_TRT_WORKSPACE_MB = 3072\n\n def __init__(self, model, network_metadata, batch_size = 1):\n super().__init__(model, T5DecoderConverter, network_metadata, batch_size = batch_size)\n\n def get_network_definition(self, network_definition):\n return add_extra_fp32(network_definition)\n\n def get_dynamic_shape_profiles(self):\n max_sequence_length = T5ModelTRTConfig.MAX_SEQUENCE_LENGTH[\n self.network_metadata.variant\n ]\n profile = Profile()\n profile.add(\n \"input_ids\",\n min=(self.batch_size, 1),\n opt=(self.batch_size, max_sequence_length // 2),\n max=(self.batch_size, max_sequence_length),\n )\n profile.add(\n \"encoder_hidden_states\",\n min=(self.batch_size, 1, max_sequence_length),\n opt=(self.batch_size, max_sequence_length // 2, max_sequence_length),\n max=(self.batch_size, max_sequence_length, max_sequence_length),\n )\n return [profile]\n\n def use_obey_precision_constraints(self):\n return self.network_metadata.precision.fp16\n\n\nclass T5EncoderTRTEngine(TRTEngineFile):\n DEFAULT_TRT_WORKSPACE_MB = 2048\n\n def __init__(self, model, network_metadata, batch_size = 1):\n super().__init__(model, T5EncoderConverter, network_metadata, batch_size = batch_size)\n\n def get_network_definition(self, network_definition):\n return add_extra_fp32(network_definition)\n\n def get_dynamic_shape_profiles(self):\n max_sequence_length = T5ModelTRTConfig.MAX_SEQUENCE_LENGTH[\n self.network_metadata.variant\n ]\n\n return [\n Profile().add(\n \"input_ids\",\n min=(self.batch_size, 1),\n opt=(self.batch_size, max_sequence_length // 2),\n max=(self.batch_size, max_sequence_length),\n )\n ]\n\n def use_obey_precision_constraints(self):\n return self.network_metadata.precision.fp16\n\n# Converters #\nclass T5DecoderConverter(ModelFileConverter):\n def __init__(self):\n super().__init__(T5DecoderTorchFile, T5DecoderONNXFile, T5DecoderTRTEngine)\n\n def torch_to_onnx(\n self, output_fpath: str, model: Module, network_metadata: NetworkMetadata\n ):\n \"\"\"\n Exports a given huggingface T5 to decoder architecture only.\n Inspired by https://github.com/onnx/models/blob/master/text/machine_comprehension/t5/dependencies/T5-export.py\n\n Args:\n output_prefix (str): Path to the onnx file\n model (torch.Model): Model loaded torch class\n\n Returns:\n T5DecoderONNXFile: ONNX decoder object.\n \"\"\"\n\n input_ids = torch.tensor([[42] * 10])\n # Exporting the decoder requires a basic instance of the encoder\n # Create one temporarily\n simplified_encoder = T5EncoderTorchFile.TorchModule(model.encoder)\n # Exports to ONNX\n decoder_with_lm_head = T5DecoderTorchFile.TorchModule(\n model.decoder, model.lm_head, model.config\n )\n\n # This code allows for huggingface compatible torch class to use onnx exporter\n old_forward = decoder_with_lm_head.forward\n def _export_forward(*args, **kwargs):\n result = old_forward(*args, **kwargs)\n return result[0]\n\n decoder_with_lm_head.forward = _export_forward\n\n inputs = T5ModelTRTConfig.get_input_dims(network_metadata)[\"decoder\"]\n outputs = T5ModelTRTConfig.get_output_dims(network_metadata)[\"decoder\"]\n\n torch.onnx.export(\n decoder_with_lm_head,\n (input_ids, simplified_encoder(input_ids)),\n output_fpath,\n export_params=True,\n opset_version=12,\n input_names=inputs.get_names(),\n output_names=outputs.get_names(),\n dynamic_axes={\n **inputs.get_torch_dynamic_axis_encoding(),\n **outputs.get_torch_dynamic_axis_encoding(),\n },\n training=False,\n use_external_data_format=True\n )\n\n if network_metadata.precision.fp16:\n G_LOGGER.debug(\"Clamping FP16 weights for T5\")\n move_t5_cast_op(output_fpath, output_fpath)\n clamp_weights_onnx_to_fp16_bounds(output_fpath, output_fpath)\n\n return T5DecoderONNXFile(output_fpath, network_metadata)\n\n\nclass T5EncoderConverter(ModelFileConverter):\n def __init__(self):\n super().__init__(T5EncoderTorchFile, T5EncoderONNXFile, T5EncoderTRTEngine)\n\n def onnx_to_trt(\n self, output_fpath: str, input_fpath: str, network_metadata: NetworkMetadata, batch_size: int\n ):\n \"\"\"\n Override onnx_to_trt function from base.\n Workaround: T5-base and T5-large are too large and cause FP16 to overflow. Encoder should not use FP16 tactics even in FP16 mode.\n The perf decreases by less than 10% end-to-end. Usage with TRT is still substantial compared to frameworks.\n \"\"\"\n # Force encoder to FP32 only if variants are anything larger than small\n # because of overflow and underflow issues\n if network_metadata.precision.fp16 and network_metadata.variant != \"t5-small\":\n network_metadata_cp_dct = network_metadata._asdict()\n del network_metadata_cp_dct[\"precision\"]\n network_metadata = NetworkMetadata(**network_metadata_cp_dct, precision=Precision(fp16=False))\n\n return super().onnx_to_trt(output_fpath, input_fpath, network_metadata, batch_size)\n\n def torch_to_onnx(\n self, output_fpath: str, model: Module, network_metadata: NetworkMetadata\n ):\n \"\"\"\n Exports a given huggingface T5 to encoder architecture only.\n Inspired by https://github.com/onnx/models/blob/master/text/machine_comprehension/t5/dependencies/T5-export.py\n\n Args:\n output_prefix (str): Path to the onnx file\n model (torch.Model): Model loaded torch class\n\n Returns:\n Tuple[str]: Names of generated models\n \"\"\"\n input_ids = torch.tensor([[42] * 10])\n simplified_encoder = T5EncoderTorchFile.TorchModule(model.encoder)\n inputs = T5ModelTRTConfig.get_input_dims(network_metadata)[\"encoder\"]\n outputs = T5ModelTRTConfig.get_output_dims(network_metadata)[\"encoder\"]\n\n # Exports to ONNX\n torch.onnx._export(\n simplified_encoder,\n input_ids,\n output_fpath,\n export_params=True,\n opset_version=12,\n input_names=inputs.get_names(),\n output_names=outputs.get_names(),\n dynamic_axes={\n **inputs.get_torch_dynamic_axis_encoding(),\n **outputs.get_torch_dynamic_axis_encoding(),\n },\n training=False,\n use_external_data_format=True\n )\n\n if network_metadata.precision.fp16:\n G_LOGGER.debug(\"Clamping FP16 weights for T5\")\n move_t5_cast_op(output_fpath, output_fpath)\n clamp_weights_onnx_to_fp16_bounds(output_fpath, output_fpath)\n\n return T5EncoderONNXFile(output_fpath, network_metadata)\n" ]
[ [ "numpy.array" ], [ "torch.tensor" ] ]
DennisHgj/pyela
[ "bbdbf1a55b31cd2ae4dc1877d220ad32589ead4c", "bbdbf1a55b31cd2ae4dc1877d220ad32589ead4c" ]
[ "pyvista_sample/VisualizeDataProcess.py", "ela/spatial.py" ]
[ "import os\nimport pickle\nimport PVGeo\nimport pyvista as pv\nimport pandas as pd\nfrom ela.classification import GridInterpolation\n\nfrom ela.spatial import create_meshgrid_cartesian\nfrom ela.visual import *\n\n'''\n@author: Guanjie Huang\n@date: Aug 16th,2019\nThis class is used to process data before generating the 3D images\n'''\n\n\nclass VisualizeDataProcess:\n def __init__(self):\n # self.height_Adjustment_factor=height_Adjustment_factor\n self.scaled_from_height_colname = 'scaled_from_height'\n self.scaled_to_height_colname = 'scaled_to_height'\n self.dem_x_min = 0\n self.dem_x_max = 0\n self.dem_y_min = 0\n self.dem_y_max = 0\n self.ahd_max = 0\n self.ahd_min = 0\n self.grid_res = ''\n self.scalar_prop_name = \"litho_num\"\n\n def drill_file_read(self, file_path):\n\n \"\"\"Read drill data file\n Args:\n file_path (str): drill data file path\n\n Returns:\n df(pandas.core.frame.DataFrame)\n \"\"\"\n df = pd.read_pickle(file_path)\n return df\n\n def dem_file_read(self, file_path):\n \"\"\"Read dem data file\n Args:\n file_path (str): drill data file path\n Returns:\n dem_array_date(pandas.core.frame.DataFrame)\n \"\"\"\n with open(file_path, 'rb') as handle:\n dem_array_data = pickle.load(handle)\n handle.close()\n return dem_array_data\n\n def drill_data_initial(self, drill_data, depth_from_ahd=DEPTH_FROM_AHD_COL, depth_to_ahd=DEPTH_TO_AHD_COL):\n \"\"\"initial class variables and clean drilling data\n Args:\n drill_data (pandas.core.frame.DataFrame): original drilling data\n depth_from_ahd(str):set the column name of depth from AHD, default DEPTH_FROM_AHD_COL\n depth_to_ahd(str):set the column name of depth to AHD, default DEPTH_TO_AHD_COL\n\n Returns:\n drill_data(pandas.core.frame.DataFrame)\n \"\"\"\n self.ahd_max = drill_data[depth_from_ahd].max()\n self.ahd_min = drill_data[depth_to_ahd].min()\n # clean the invalid data\n return drill_data.dropna(subset=[depth_to_ahd, depth_from_ahd])\n\n def dem_data_initial(self, dem_array_data, dem_bounds='bounds', dem_grid_res='grid_res'):\n \"\"\"initial class variables and clean dem data\n Args:\n dem_array_data (pandas.core.frame.DataFrame): original dem data\n dem_bounds(str): set bounds column name according to dem files\n dem_grid_res(str): set grid_res column name according to dem files\n\n Returns:\n dem_array_data(pandas.core.frame.DataFrame)\n \"\"\"\n self.dem_x_min, self.dem_x_max, self.dem_y_min, self.dem_y_max = dem_array_data[dem_bounds]\n self.grid_res = dem_array_data[dem_grid_res]\n return dem_array_data\n\n def drill_data_process(self, drill_data, height_adjustment_factor=20, depth_from_ahd=DEPTH_FROM_AHD_COL,\n depth_to_ahd=DEPTH_TO_AHD_COL, drill_east='Easting', drill_north='Northing',\n boreID='BoreID', prime_lithology='Lithology_1_num', min_tube_radius=10):\n \"\"\"The whole data process from drill data to PolyData dictionary\n\n Args:\n drill_data(pandas.core.frame.DataFrame): original drilling data\n height_adjustment_factor (int): Height scaling factor, default 20.\n depth_from_ahd(str):set the column name of depth from AHD, default DEPTH_FROM_AHD_COL\n depth_to_ahd(str):set the column name of depth to AHD, default DEPTH_TO_AHD_COL\n drill_east(str):set the column name of point's x location in drilling data, default \"Easting\"\n drill_north(str):set the column name of point's y's location in drilling data, default \"Northing\"\n boreID(str):set the column name of bore hole ID,default \"BoreID\"\n prime_lithology(str):set the prime lithology column name\n min_tube_radius(int):set the min radius of borehole tube\n\n Returns:\n lines_dict(dict): PolyData dictionary.\n \"\"\"\n # data = self.drill_file_read(file_path, depth_from_ahd, depth_to_ahd)\n fixed_data = self.drill_data_initial(drill_data, depth_from_ahd, depth_to_ahd)\n data = self.add_scaled_height_column(fixed_data, height_adjustment_factor, depth_from_ahd, depth_to_ahd)\n well_dict = self.build_well_dict(data, boreID)\n # = self.add_missing_height_data(well_dict)\n point_dict = self.build_points_dict(well_dict, drill_east, drill_north)\n lines_dict = self.point_to_lines_dict(point_dict)\n lines_dict = self.add_lithology_based_scalar(well_dict, lines_dict, prime_lithology, min_tube_radius)\n return lines_dict\n\n def dem_data_process(self, dem_array_data, height_adjustment_factor, dem_mesh_xy='mesh_xy', dem_arrays='dem_array',\n dem_bounds='bounds', dem_grid_res='grid_res'):\n \"\"\"The whole data process from dem data to pv.StructuredGrid\n\n Args:\n dem_array_data (pandas.core.frame.DataFrame): original dem data\n height_adjustment_factor (int): Height scaling factor, default 20 .\n dem_mesh_xy(str): set mesh_xy column name according to dem files\n dem_arrays(str): set dem array column name according to dem files\n dem_bounds(str): set bounds column name according to dem files\n dem_grid_res(str): set grid_res column name according to dem files\n\n Returns:\n Grid(pyvista.core.pointset.StructuredGrid)\n\n \"\"\"\n dem_array_data = self.dem_data_initial(dem_array_data, dem_bounds, dem_grid_res)\n xx, yy = dem_array_data[dem_mesh_xy]\n dem_array = dem_array_data[dem_arrays]\n grid = pv.StructuredGrid(xx, yy, dem_array * height_adjustment_factor)\n return grid\n\n def lithology_layer_process(self, drill_data, dem_array_data, storage_file_name, height_adjustment_factor=20,\n layer_from=0, layer_to=0, dem_bounds='bounds', dem_grid_res='grid_res',\n dem_mesh_xy='mesh_xy', drill_east='Easting', drill_north='Northing',\n dem_arrays='dem_array', depth_from_ahd=DEPTH_FROM_AHD_COL,\n depth_to_ahd=DEPTH_TO_AHD_COL):\n \"\"\"add points lithology type, expands lines to tube based on lithology number\n Args:\n drill_data(pandas.core.frame.DataFrame): original drilling data\n dem_array_data (pandas.core.frame.DataFrame): original dem data\n storage_file_name(str): set the name of the save path for testing sample's\n lithology classification array\n height_adjustment_factor(int): height scala factor\n layer_from (float): set the begin number of layers\n layer_to (float): set the end number of layers\n dem_bounds(str): set bounds column name according to dem files\n dem_grid_res(str): set grid_res column name according to dem files\n dem_mesh_xy(str): set mesh_xy column name according to dem files\n drill_east(str):set the column name of point's x location in drilling data, default \"Easting\"\n drill_north(str):set the column name of point's y's location in drilling data, default \"Northing\"\n dem_arrays(str): set dem array column name according to dem files\n depth_from_ahd(str):set the column name of depth from AHD, default DEPTH_FROM_AHD_COL\n depth_to_ahd(str):set the column name of depth to AHD, default DEPTH_TO_AHD_COL\n\n\n Returns:\n layer_mesh(pyvista.core.pointset.UnstructuredGrid): layer mesh for display use\n \"\"\"\n\n # drill_data = self.drill_file_read(drill_file_path, depth_from_ahd, depth_to_ahd)\n # dem_array_data = self.dem_file_read(dem_file_path, dem_bounds, dem_grid_res)\n path = os.path.join(storage_file_name, \"lithology_3d_array.pkl\")\n try:\n with open(path, 'rb') as handle:\n lithology_3d_array = pickle.load(handle)\n handle.close()\n except:\n drill_data = self.drill_data_initial(drill_data, depth_from_ahd, depth_to_ahd)\n dem_array_data = self.dem_data_initial(dem_array_data, dem_bounds, dem_grid_res)\n lithology_3d_array = self.build_layer_data(drill_data, dem_array_data, dem_mesh_xy, drill_east, drill_north)\n lithology_3d_array = self.clean_over_bound_data(lithology_3d_array, dem_array_data, dem_arrays)\n # lithology_3d_array = self.vag_clean(lithology_3d_array, dem_array_data)\n folder = os.path.exists(path)\n if not folder:\n os.makedirs(storage_file_name)\n with open(path, \"wb\") as cf:\n pickle.dump(lithology_3d_array, cf)\n cf.close()\n\n layer_mesh = self.build_layer_mesh(lithology_3d_array, height_adjustment_factor, layer_from, layer_to)\n return layer_mesh\n\n def add_scaled_height_column(self, data, height_adjustment_factor, depth_from_ahd=DEPTH_FROM_AHD_COL,\n depth_to_ahd=DEPTH_TO_AHD_COL):\n \"\"\"Add scaled height columns to data frame\n Args:\n data (pandas.core.frame.DataFrame):original data\n height_adjustment_factor (int): Height scaling factor.\n depth_from_ahd(str):set the column name of depth from AHD, default DEPTH_FROM_AHD_COL\n depth_to_ahd(str):set the column name of depth to AHD, default DEPTH_TO_AHD_COL\n Returns:\n data(pandas.core.frame.DataFrame): modified data\n \"\"\"\n # scaled_from_height_colname = 'scaled_from_height'\n data.loc[:, self.scaled_from_height_colname] = data[depth_from_ahd].values * height_adjustment_factor\n # scaled_to_height_colname = 'scaled_to_height'\n data.loc[:, self.scaled_to_height_colname] = data[depth_to_ahd].values * height_adjustment_factor\n return data\n\n def build_well_dict(self, data, boreID='BoreID'):\n \"\"\"build dictionary according to BoreID\n Args:\n data (pandas.core.frame.DataFrame):original data\n boreID(str):set the column name of bore hole ID,default \"BoreID\"\n Returns:\n well_dict(dict()): wells dictionary\n \"\"\"\n data.loc[:, 'name'] = data.loc[:, boreID].values.astype(str)\n wells = data.name.unique()\n well_dict = {}\n for well in wells:\n well_dict[\"{0}\".format(well)] = data[data.name == well]\n return well_dict\n\n # def add_missing_height_data(self, well_dict):\n # \"\"\"Add the smallest height_to data to height_from data (len(well_dict[i])+1)\n # Args:\n # well_dict(dict()): original dictionary\n # Returns:\n # well_dict(dict()): modified dictionary\n # \"\"\"\n # bad_well = []\n # for well in well_dict.keys():\n # origin_well_df = well_dict.get(well)\n # after_well_df = origin_well_df.copy()\n # add_index = origin_well_df[self.scaled_to_height_colname].idxmin()\n # if np.isnan(add_index):\n # bad_well.append(well)\n # continue\n # line = origin_well_df.loc[add_index].copy()\n # line.scaled_from_height = line.scaled_to_height\n # line = line.to_frame()\n # temp = []\n # for value in line.values:\n # if value[0]:\n # temp.append(value[0])\n # else:\n # temp.append(0)\n # after_well_df.loc[\"new\"] = temp\n # well_dict[well] = after_well_df\n # for i in range(len(bad_well)):\n # well_dict.pop(bad_well[i])\n # return well_dict\n\n def build_points_dict(self, well_dict, drill_east=\"Easting\", drill_north=\"Northing\"):\n \"\"\"build points dictionary from wells dictionary\n Args:\n well_dict(dict()): wells dictionary\n drill_east(str):set the column name of point's x location in drilling data, default \"Easting\"\n drill_north(str):set the column name of point's y's location in drilling data, default \"Northing\"\n Returns:\n points_dict(dict()): zip points axis for points\n \"\"\"\n c = np.concatenate\n points_dict = {}\n for points in well_dict:\n e = well_dict[points][drill_east].values\n n = well_dict[points][drill_north].values\n points_dict[\"{0}\".format(points)] = np.array(\n list(\n zip(\n c((e, e)),\n c((n, n)),\n c((\n well_dict[points][self.scaled_from_height_colname].values,\n well_dict[points][self.scaled_to_height_colname].values + 1.0))\n )\n )\n )\n return points_dict\n\n def point_to_lines_dict(self, points_dict):\n \"\"\"build lines dictionary from points dictionary\n Args:\n points_dict(dict()): points dictionary\n Returns:\n lines_dict(dict()): build lines between same well points\n \"\"\"\n lines_dict = {}\n for bore_id in points_dict:\n poly = PVGeo.points_to_poly_data(points_dict[bore_id])\n lines_dict[\"{0}\".format(bore_id)] = PVGeo.filters.AddCellConnToPoints(nearest_nbr=True).apply(poly)\n # notice that the building of the lines need to follow the nearest neighbourhood search\n return lines_dict\n\n def add_lithology_based_scalar(self, well_dict, lines_dict, prime_lithology='Lithology_1_num', min_tube_radius=10):\n \"\"\"add points lithology type, expands lines to tube based on lithology number\n Args:\n well_dict(dict()): wells dictionary\n lines_dict(dict()):lines dictionary\n prime_lithology(str):set the prime lithology column name\n min_tube_radius(int): set the min radius of borehole tube\n Returns:\n lines_dict(dict()): with new attribute \"GR\" which represent lithology number, and expanded to tube.\n \"\"\"\n lines_dict_tmp = {}\n for bore_id in lines_dict:\n try:\n vals = well_dict[bore_id][prime_lithology].values\n bore_vis = lines_dict[bore_id]\n bore_vis[self.scalar_prop_name] = np.concatenate((vals, vals)) # tops then bottoms of cylinders.\n bore_vis.tube(radius=min_tube_radius, scalars=None, inplace=True)\n # lines_dict[bore_id].tube(radius=10, scalars=dp.scalar_prop_name, inplace=True)\n except Exception as e:\n raise Exception(\"Lithology attribute processed for visualisation failed for bore ID %s\" % (bore_id))\n if len(vals) > 0:\n lines_dict_tmp[bore_id] = lines_dict[bore_id]\n lines_dict = lines_dict_tmp\n return lines_dict\n\n def build_layer_data(self, drill_data, dem_array_data, dem_mesh_xy='mesh_xy', drill_east='Easting',\n drill_north='Northing'):\n \"\"\"get the layer data from the function contains in ela\n Args:\n drill_data (pandas.core.frame.DataFrame): drill data\n dem_array_data (pandas.core.frame.DataFrame): dem data\n dem_mesh_xy(str): set mesh_xy column name according to dem files\n drill_east(str):set the column name of point's x location in drilling data, default \"Easting\"\n drill_north(str):set the column name of point's y's location in drilling data, default \"Northing\"\n \"\"\"\n n_neighbours = 10\n xg, yg = dem_array_data[dem_mesh_xy]\n m = create_meshgrid_cartesian(self.dem_x_min, self.dem_x_max, self.dem_y_min, self.dem_y_max, self.grid_res)\n z_coords = np.arange(self.ahd_min, self.ahd_max, 1)\n dim_x, dim_y = xg.shape\n dim_z = len(z_coords)\n dims = (dim_x, dim_y, dim_z)\n lithology_3d_array = np.empty(dims)\n gi = GridInterpolation(easting_col=drill_east, northing_col=drill_north)\n gi.interpolate_volume(lithology_3d_array, drill_data, PRIMARY_LITHO_NUM_COL, z_coords, n_neighbours, m)\n return lithology_3d_array\n\n def clean_over_bound_data(self, lithology_3d_array, dem_array_data, dem_arrays='dem_array'):\n \"\"\"accurate process data that exceeds limits\n (we suppose that the lithology would not higher than the ground surface),\n accurate but slower\n Args:\n lithology_3d_array (np.array of dim 3): lithology numeric (lithology class) identifiers\n dem_array_data (pandas.core.frame.DataFrame): dem data\n dem_arrays(str): set dem array column name according to dem files\n \"\"\"\n dem_z = dem_array_data[dem_arrays]\n for i in range(lithology_3d_array.shape[0]):\n for j in range(lithology_3d_array.shape[1]):\n if np.isnan(dem_z[i][j]):\n lithology_3d_array[i][j] = None\n continue\n for k in range(lithology_3d_array.shape[2]):\n height = k * (self.ahd_max - self.ahd_min) / lithology_3d_array.shape[2] + self.ahd_min\n if height >= dem_z[i][j]:\n for tmp in range(k, lithology_3d_array.shape[2]):\n lithology_3d_array[i][j][tmp] = None\n break\n return lithology_3d_array\n\n def vag_clean(self, lithology_3d_array, dem_array_data, dem_arrays='dem_array'):\n \"\"\"Simply process data that exceeds limits(we suppose that the lithology would not higher than the ground surface),\n not accurate but faster\n\n Args:\n lithology_3d_array (np.array of dim 3): lithology numeric (lithology class) identifiers\n dem_array_data (pandas.core.frame.DataFrame: dem data\n dem_arrays(str): set dem array column name according to dem files\n \"\"\"\n dem_z = dem_array_data[dem_arrays]\n for i in range(1, lithology_3d_array.shape[0]):\n for j in range(1, lithology_3d_array.shape[1]):\n if np.isnan(dem_z[i][j]):\n k = 0\n else:\n k = int(dem_z[i][j] - self.ahd_min)\n for tep in range(k, lithology_3d_array.shape[2]):\n lithology_3d_array[i][j][tep] = None\n return lithology_3d_array\n\n def build_layer_mesh(self, lithology_3d_array, height_adjustment_factor, layer_from, layer_to):\n \"\"\"Build a 3D mesh of selected lithology class codes by binary bining cells. Use filter to select aim layers.\n\n Args:\n lithology_3d_array (np.array of dim 3): lithology numeric (lithology class) identifiers\n height_adjustment_factor (int): height scale factor\n layer_from (float): set the begin number of layers\n layer_to (float): set the end number of layers\n \"\"\"\n volume = pv.UniformGrid()\n volume.dimensions = np.array(lithology_3d_array.shape)\n volume.origin = (self.dem_x_min, self.dem_y_min, self.ahd_min * height_adjustment_factor)\n x_label = (self.dem_x_max - self.dem_x_min) / lithology_3d_array.shape[0]\n y_label = (self.dem_y_max - self.dem_y_min) / lithology_3d_array.shape[1]\n z_label = (self.ahd_max - self.ahd_min) * height_adjustment_factor / lithology_3d_array.shape[2]\n volume.spacing = (x_label, y_label, z_label)\n volume.point_arrays[\"Lithology\"] = lithology_3d_array.flatten('F')\n volume.set_active_scalar(\"Lithology\")\n threshed = volume.threshold([layer_from, layer_to])\n return threshed\n\n # def exist_3d_lithology(self):\n\n def extract_single_lithology_class_3d(self, lithology_3d_classes, class_value):\n \"\"\"Transform a 3D volume of lithology class codes by binary bining cells as being either of a class value or\n other. Preprocessing primarily for 3D visualisation for pyvista(not use in the sample ).\n\n Args:\n lithology_3d_classes (np.array of dim 3): lithology numeric (lithology class) identifiers\n class_value (float): class code of interest\n \"\"\"\n single_litho = np.copy(lithology_3d_classes)\n other_value = None\n single_litho[(single_litho != class_value)] = other_value\n # We burn the edges of the volume, as I suspect this is necessary to have a more intuitive viz (otherwise non\n # closed volumes)\n single_litho[0, :, :] = other_value\n single_litho[-1, :, :] = other_value\n single_litho[:, 0, :] = other_value\n single_litho[:, -1, :] = other_value\n single_litho[:, :, 0] = other_value\n single_litho[:, :, -1] = other_value\n return single_litho\n # burn_volume\n", "import numpy as np\nimport pandas as pd\n\nfrom ela.textproc import EASTING_COL, NORTHING_COL, DEPTH_FROM_AHD_COL, DEPTH_FROM_COL, DEPTH_TO_AHD_COL, DEPTH_TO_COL, BORE_ID_COL\n\nKNN_WEIGHTING = 'distance'\n\nfrom sklearn import neighbors\n\n\ndef read_raster_value(dem,band_1,easting,northing):\n \"\"\"Read a value in a raster grid given easting/northing\n\n Args:\n dem (rasterio dataset): dem\n band_1 (numpy array): the band 1 from the DEM\n easting (float): easting value\n northing (float): northing value\n\n Returns:\n (float): the value of the band at the specified point\n \"\"\"\n if (np.isnan(easting) or np.isnan(northing)):\n raise Exception(\"Easting and northing must not be NaN\")\n row, col = dem.index(easting,northing)\n # dem.index seems to return floats and this causes a but to index its numpy array.\n # something used to work (who knows which package version soup) and does not anymore. At runtime. Dynamic typing...\n row = int(row)\n col = int(col)\n if (row < 0 or row >= band_1.shape[0] or col < 0 or col >= band_1.shape[1]):\n return np.nan\n else:\n return band_1[row,col]\n\ndef get_coords_from_gpd_shape(shp, colname='geometry', out_colnames = None):\n \"\"\"Gets a dataframe of x/y geolocations out of a geopandas object\n\n Args:\n shp (GeoDataFrame): a geopandas GeoDataFrame\n colname (str): name of columns that has the geometry in the geopandas shapefile\n out_colnames (list of str): names of the added geolocation columns in the output data frame\n Returns:\n (DataFrame): a two column data frames, coordinates of all the points in the geodataframe\n\n Example:\n >>> from ela.doc.sampledata import *\n >>> from ela.spatial import get_coords_from_gpd_shape\n >>> dem ,bore_loc, litho_logs = sample_data()\n >>> df = litho_logs[[DEPTH_FROM_COL, DEPTH_TO_COL,TOP_ELEV_COL,BOTTOM_ELEV_COL,LITHO_DESC_COL,HYDRO_CODE_COL]]\n >>> geoloc = get_coords_from_gpd_shape(bore_loc, colname='geometry', out_colnames=[EASTING_COL, NORTHING_COL])\n >>> geoloc[HYDRO_CODE_COL] = bore_loc[HYDRO_CODE_COL]\n >>> geoloc.head()\n >>> # With this data frame we can perform two operations in one go: subsetting the lithology records to only the 640 bores of interest, and adding to the result the x/y geolocations to the data frame.\n >>> df = pd.merge(df, geoloc, how='inner', on=HYDRO_CODE_COL, sort=False, copy=True, indicator=False, validate=None)\n \"\"\"\n out_colnames = out_colnames or [\"x\",\"y\"]\n p = shp[[colname]]\n pts = p.values.flatten()\n c = [(pt.x, pt.y) for pt in pts]\n return pd.DataFrame(c, columns=out_colnames)\n\ndef get_unique_coordinates(easting, northing):\n \"\"\"Gets the unique set of geolocated points\n\n Args:\n easting (iterable of floats): easting values\n northing (iterable of floats): northing values\n Returns:\n (numpy array): two dimensional nparray\n \"\"\"\n grid_coords = np.empty( (len(easting), 2) )\n grid_coords[:,0] = easting\n grid_coords[:,1] = northing\n b = np.unique(grid_coords[:,0] + 1j * grid_coords[:,1])\n points = np.column_stack((b.real, b.imag))\n return points\n\nclass HeightDatumConverter:\n \"\"\"\n Attributes:\n dfcn (GeospatialDataFrameColumnNames): Adapter to a dataframe column names for depth/height information.\n dem_raster (rasterio dataset): DEM raster\n data_grid (??): band 1 data in the raster\n \"\"\"\n def __init__(self, dem_raster, easting_col=EASTING_COL, northing_col=NORTHING_COL, depth_from_ahd_col=DEPTH_FROM_AHD_COL, depth_to_ahd_col=DEPTH_TO_AHD_COL):\n \"\"\"Initialize this with a coordinate reference system object and an affine transform. See rasterio.\n\n Args:\n easting_col (str): name of the data frame column for easting\n northing_col (str): name of the data frame column for northing\n depth_from_ahd_col (str): name of the data frame column for the height of the top of the soil column (ahd stands for for australian height datum, but not restricted)\n depth_to_ahd_col (str): name of the data frame column for the height of the bottom of the soil column (ahd stands for for australian height datum, but not restricted)\n \"\"\"\n self.dfcn = GeospatialDataFrameColumnNames(easting_col, northing_col, depth_from_ahd_col, depth_to_ahd_col)\n self.dem_raster = dem_raster\n self.data_grid = self.dem_raster.read(1)\n\n def _raster_drill_df(self, df, easting_col, northing_col):\n x = df[easting_col].values\n y = df[northing_col].values\n v = np.empty_like(x, dtype=self.data_grid.dtype) # Try to fix https://github.com/jmp75/pyela/issues/2\n for i in range(len(x)):\n v[i] = read_raster_value(self.dem_raster, self.data_grid, x[i], y[i])\n return v\n\n def raster_drill_df(self, df):\n \"\"\"Gets the DEM values for the easting/northing in a data frame\n\n Args:\n df (pandas.DataFrame): data frame of records with easting/northing information in columns compatible with this object\n\n Returns:\n (1D numpy array): the datum height values at the specified points\n \"\"\"\n return self._raster_drill_df(df, self.dfcn.easting_col, self.dfcn.northing_col)\n\n def add_height(self, lithology_df,\n depth_from_col=DEPTH_FROM_COL, depth_to_col=DEPTH_TO_COL,\n depth_from_ahd_col=DEPTH_FROM_AHD_COL, depth_to_ahd_col=DEPTH_TO_AHD_COL,\n easting_col=EASTING_COL, northing_col=NORTHING_COL,\n drop_na=False):\n \"\"\"Helper class to round lithology record classes to the nearest metre of depth\n\n Args:\n lithology_df:\n depth_from_col (str): Column name storing \"from depth\" information\n depth_to_col (str): Column name storing \"to depth\" information\n depth_from_ahd_col (str): Column name datum height information\n depth_to_ahd_col (str): Column name datum height information\n easting_col (str): Column name storing easting information\n northing_col (str): Column name storing northing information\n drop_na (bool): If true, entries with nissing datum heights are dropped\n\n Returns:\n (pandas.DataFrame):\n \"\"\"\n df = lithology_df.copy(deep=True)\n nd = np.float32(self.dem_raster.nodata) # Try to fix https://github.com/jmp75/pyela/issues/2\n ahd = self._raster_drill_df(df, easting_col, northing_col)\n ahd[ahd==nd] = np.nan\n df[depth_from_ahd_col]=ahd-df[depth_from_col]\n df[depth_to_ahd_col]=ahd-df[depth_to_col]\n if drop_na:\n df = df[pd.notna(df[depth_to_ahd_col])]\n return df\n\n def raster_value_at(self, easting, northing):\n \"\"\"Raster value for a given easting/northing\n\n Args:\n easting (float): easting value\n northing (float): northing value\n\n Returns:\n (float): the value of the band at the specified point\n \"\"\"\n return read_raster_value(self.dem_raster, self.data_grid, easting, northing)\n\nclass DepthsRounding:\n \"\"\"Helper class to round lithology record classes to the nearest metre of depth\n\n Attributes:\n depth_from_col (str): Column name storing \"from depth\" information\n depth_to_col (str): Column name storing \"to depth\" information\n \"\"\"\n def __init__(self, depth_from_col=DEPTH_FROM_COL, depth_to_col=DEPTH_TO_COL):\n \"\"\"Helper class to round lithology record classes to the nearest metre of depth\n\n Args:\n depth_from_col (str): Column name storing \"from depth\" information\n depth_to_col (str): Column name storing \"to depth\" information\n \"\"\"\n self.depth_from_col = depth_from_col\n self.depth_to_col = depth_to_col\n\n def round_to_metre_depths(self, df, func=np.round, remove_collapsed=False):\n \"\"\"Round lithology record classes to the nearest metre of depth\n\n Args:\n df (pandas data frame): bore lithology data\n func (callable): rounding function callable with a signature similar to `np.round`\n remove_collapsed (bool): should entries where depths from and to are equal be removed from the result\n Returns:\n (pandas dataframe): a data frame of similar structure as the input but without entries less than a metre resolution.\n \"\"\"\n depth_from_rounded =df[self.depth_from_col].apply(func)\n depth_to_rounded =df[self.depth_to_col].apply(func)\n df_1 = df.copy(deep=True)\n df_1[self.depth_from_col] = depth_from_rounded\n df_1[self.depth_to_col] = depth_to_rounded\n collapsed = (df_1[self.depth_from_col] == df_1[self.depth_to_col])\n if remove_collapsed:\n df_1 = df_1[~collapsed]\n return df_1\n\n def assess_num_collapsed(self, df, func=np.round):\n \"\"\"How many records would be removed from the lithology records if rounding from/to depths\n\n Args:\n df (pandas data frame): bore lithology data\n func (callable): rounding function callable with a signature similar to `np.round`\n Returns:\n (int): the number of entries that would be collapsed from/to depths\n \"\"\"\n tmp = self.round_to_metre_depths(df, func)\n collapsed = (tmp[self.depth_from_col] == tmp[self.depth_to_col])\n return collapsed.sum()\n\n# Remove if indeed redundant/superseded\n# def slice_above(lithology_df, lower_bound_raster, drop_na=True):\n# df = lithology_df.copy(deep=True)\n# data_grid = lower_bound_raster.read(1)\n# lower_bound_values = raster_drill_df(df, lower_bound_raster, data_grid)\n# if drop_na:\n# df = df[pd.notna(lower_bound_values)]\n# lower_bound_values = lower_bound_values[pd.notna(lower_bound_values)]\n# df_slice=df.loc[(df[DEPTH_FROM_AHD_COL] >= lower_bound_values) & (df[DEPTH_TO_AHD_COL] >= lower_bound_values)]\n# return df_slice\n\ndef z_index_for_ahd_functor(a=1, b=50):\n \"\"\"Creates a linear univariate function for height to index conversions\n\n Args:\n a (float): slope - defaults to one\n b (float): height offset\n\n Returns:\n (callable): univariate linear function\n \"\"\"\n def z_index_for_ahd(ahd):\n return a * ahd + b\n return z_index_for_ahd\n\ndef average_slices(slices):\n \"\"\"Gets the average values over numeric slices\n\n Args:\n slices (list of 2D np arrays): slices to average\n\n \"\"\"\n\n # TODO there are ways to make this more efficient, e.g. if we get a volume instead of a list of slices\n # my_volume\n # my_sub_volume = my_volume[:,:,from:to:by] or something like that\n # the_average = np.average(my_sub_volume, axis=2).shape\n # for now:\n if len(slices) < 1:\n raise ZeroDivisionError(\"There must be at least one slice to average over\")\n summed = np.empty(slices[0].shape)\n summed = 0.0\n for i in range(len(slices)):\n summed = summed + slices[i]\n return summed / len(slices)\n\n\ndef burn_volume_func(func_below, func_above, volume, surface_raster, height_to_z, below=False, ignore_nan=False, inclusive=False):\n \"\"\"\n Reusable function, not for end user. Process parts of a xyz volume given a surface, below or above the intersection of the volume with the surface\n \"\"\"\n dim_x,dim_y,dim_z=volume.shape\n z_index_max = dim_z-1\n # TODO if surface_raster.shape[0] != dim_x or surface_raster.shape[1] != dim_y\n for x in np.arange(0,dim_x,1):\n for y in np.arange(0,dim_y,1):\n # From the original code I had retrieved something I cannot understand (why 30??)\n # erode_until=-(surface_raster.astype(int)-30)[x,y]\n dem_height = surface_raster[x,y]\n if np.isnan(dem_height):\n if not ignore_nan:\n volume[x,y,:]=np.nan\n else:\n z_height = height_to_z(dem_height)\n z_height = min(z_index_max, max(0.0, z_height))\n z_height = int(round(z_height))\n zh_nan = z_height\n if below:\n if inclusive:\n zh_nan = zh_nan + 1\n zh_nan = min(z_index_max, max(0.0, zh_nan))\n func_below(volume, x, y, zh_nan)\n else:\n if not inclusive:\n zh_nan = zh_nan + 1\n zh_nan = min(z_index_max, max(0.0, zh_nan))\n func_above(volume, x, y, zh_nan)\n\ndef volume_value_at(volume, slice_surface, height_to_z, x, y):\n \"\"\"read a volume value at an x/y/z location.\n\n Args:\n volume (3D ndarray): volume to drill\n slice_surface (2D numpy array): array of elevations\n height_to_z (callable): converter from datum height to z index\n x (float): easting index\n y (float): northing index\n\n Returns:\n (float): the value in the volume at the specified point\n \"\"\"\n dim_z=volume.shape[2]\n z_index_max = dim_z-1\n slice_height = slice_surface[x,y]\n def to_int(x): # may be custom later\n return int(np.floor(x))\n if np.isnan(slice_height):\n return np.nan\n else:\n z_height = to_int(height_to_z(slice_height))\n if z_height < 0:\n return np.nan\n elif z_height > z_index_max:\n return np.nan\n else:\n z = z_height\n return volume[x,y,z]\n\ndef slice_volume(volume, slice_surface, height_to_z):\n \"\"\"read values in a volume along a slicing surface\n\n Args:\n volume (3D ndarray): volume to drill\n slice_surface (2D numpy array): array of elevations\n height_to_z (callable): converter from datum height to z index\n\n Returns:\n (float): the value in the volume at the specified point\n \"\"\"\n dim_x,dim_y,_=volume.shape\n # TODO if surface_raster.shape[0] != dim_x or surface_raster.shape[1] != dim_y\n result = np.empty((dim_x,dim_y))\n for x in np.arange(0,dim_x,1):\n for y in np.arange(0,dim_y,1):\n result[x,y] = volume_value_at(volume, slice_surface, height_to_z, x, y)\n return result\n\nclass SliceOperation:\n \"\"\"Helper class to perform slicing operations on a 3D volume.\n\n Attributes:\n dem_array_zeroes_infill (2D array): An array, DEM for the grid at the same x/y resolution as the volume to be sliced.\n z_index_for_ahd (callable): bijection from a z index in the volume to its AHD height\n \"\"\"\n def __init__(self, dem_array_zeroes_infill, z_index_for_ahd):\n \"\"\"initialize a slice operator for a given grid size\n\n Args:\n dem_array_zeroes_infill (2D array): An array, DEM for the grid at the same x/y resolution as the volume to be sliced.\n z_index_for_ahd (callable): bijection from a z index in the volume to its AHD height\n \"\"\"\n self.dem_array_zeroes_infill = dem_array_zeroes_infill\n self.z_index_for_ahd = z_index_for_ahd\n\n @staticmethod\n def arithmetic_average(slices):\n k_average = np.empty(slices[0].shape)\n k_average = 0.0\n for i in range(len(slices)):\n k_average = k_average + slices[i]\n k_average = k_average / len(slices)\n return k_average\n\n @staticmethod\n def arithmetic_average_int(slices):\n return np.round(SliceOperation.arithmetic_average(slices))\n\n def reduce_slices_at_depths(self, volume, from_depth, to_depth, reduce_func):\n \"\"\"Slice a volume at every meter between two depths below ground level, and reduce the resulting 'vertical' values to a single statistic.\n\n Args:\n volume (3D array): volume of interest\n from_depth (numeric): top level depth below ground\n to_depth (numeric): bottom level depth below ground. `from_depth` is less than `to_depth`\n reduce_func (callable): A function that takes in a list of 2D grids and returns one 2D grid\n\n Returns:\n (2D Array): reduced values (e.g. averaged) for each grid geolocation between the two depths below ground.\n \"\"\"\n slices = [slice_volume(volume, self.dem_array_zeroes_infill - depth, self.z_index_for_ahd) for depth in range(from_depth, to_depth+1)]\n return reduce_func(slices)\n\n def from_ahd_to_depth_below_ground_level(self, volume, from_depth, to_depth):\n \"\"\"Slice a volume at every meter between two depths below ground level\n\n Args:\n volume (3D array): volume of interest\n from_depth (numeric): top level depth below ground\n to_depth (numeric): bottom level depth below ground. `from_depth` is less than `to_depth`\n Returns:\n (3D Array): volume values between the two depths below ground.\n \"\"\"\n # Note: may not be the most computationally efficient, but deal later.\n depths = range(from_depth, to_depth+1)\n slices = [slice_volume(volume, self.dem_array_zeroes_infill - depth, self.z_index_for_ahd) for depth in depths]\n nx, ny, _ = volume.shape\n nz = len(depths)\n result = np.empty([nx, ny, nz])\n for i in range(nz):\n ii = (nz-1) - i\n result[:,:,i] = slices[ii]\n return result\n\n\ndef burn_volume(volume, surface_raster, height_to_z, below=False, ignore_nan=False, inclusive=False):\n \"\"\"\n Burn out parts of a xyz volume given a surface, below or above the intersection of the volume with the surface\n\n :volume: volume to modify\n :type: 3D numpy\n\n :surface_raster: AHD coordinate at which to slice the data frame for lithology observations\n :type: 2D numpy\n\n :height_to_z: Number of neighbors to pass to KNeighborsClassifier\n :type: a function to convert the surface raster value (height for a DEM) to a corresponding z-index in the volume.\n\n :below: should the part below or above be burnt out\n :type: bool\n\n :ignore_nan: If the surface to burn from has NaNs, should it mask out the whole corresponding cells in the volume\n :type: bool\n\n :inclusive: is the cell in the volume cut by the surface included in the burning out (i.e. set to NaN) or its value kept?\n :type: bool\n \"\"\"\n def nan_below_z(volume, x, y, z):\n volume[x, y,0:z]=np.nan\n\n def nan_above_z(volume, x, y, z):\n volume[x, y,z:]=np.nan\n\n burn_volume_func(nan_below_z, nan_above_z, volume, surface_raster, height_to_z, below, ignore_nan, inclusive)\n\n\ndef set_at_surface_boundary(volume, surface_raster, height_to_z, value=0.0, ignore_nan=False):\n \"\"\"\n Burn out parts of a xyz volume given a surface, below or above the intersection of the volume with the surface\n\n :volume: volume to modify\n :type: 3D numpy\n\n :surface_raster: AHD coordinate at which to slice the data frame for lithology observations\n :type: 2D numpy\n\n :height_to_z: Number of neighbors to pass to KNeighborsClassifier\n :type: a function to convert the surface raster value (height for a DEM) to a corresponding z-index in the volume.\n\n :below: should the part below or above be burnt out\n :type: bool\n\n :ignore_nan: If the surface to burn from has NaNs, should it mask out the whole corresponding cells in the volume\n :type: bool\n\n :inclusive: is the cell in the volume cut by the surface included in the burning out (i.e. set to NaN) or its value kept?\n :type: bool\n \"\"\"\n def set_at_z(volume, x, y, z):\n volume[x, y,z]=value\n\n burn_volume_func(set_at_z, set_at_z, volume, surface_raster, height_to_z, below=False, ignore_nan=ignore_nan, inclusive=False)\n\n\ndef get_bbox(geo_pd):\n \"\"\"Gets the bounding box of a geopandas dataframe\n\n Args:\n geo_pd (geopandas): shape from which we can get the bounding box as a basis for the extend of the meshgrid\n\n Return:\n (tuple of floats): bbox (x_min, y_min, x_max, y_max)\n \"\"\"\n return (geo_pd.total_bounds[0], geo_pd.total_bounds[1], geo_pd.total_bounds[2], geo_pd.total_bounds[3])\n\ndef cookie_cut_gpd(gpd_df, x_min, x_max, y_min, y_max, fractions=None):\n \"\"\"Cookie cut a geopandas data frame, typically bore locations.\n\n Args:\n gpd_df (geopandas): geopandas data\n x_min (numeric): lower x coordinate\n x_max (numeric): upper x coordinate\n y_min (numeric): lower y coordinate\n y_max (numeric): upper y coordinate\n fractions (list of floats): lists of fractions from the original (x_min, x_max, y_min, y_max) box at which to clip the data. Defaults to the centered third of original width/height (i.e. 1/9th of the area)\n Return:\n (TBC): a geopandas data frame (or view thereof)\n \"\"\"\n if fractions is None:\n fractions = [0.33, 0.67, 0.33, 0.67]\n xmin = x_min + fractions[0] * (x_max-x_min)\n xmax = x_min + fractions[1] * (x_max-x_min)\n ymin = y_min + fractions[2] * (y_max-y_min)\n ymax = y_min + fractions[3] * (y_max-y_min)\n return gpd_df.cx[xmin:xmax, ymin:ymax]\n\n\ndef create_meshgrid_cartesian(x_min, x_max, y_min, y_max, grid_res):\n \"\"\"Create a 2D meshgrid to be used with numpy for vectorized operations and Mayavi visualisation.\n\n Args:\n x_min (numeric): lower x coordinate\n x_max (numeric): upper x coordinate\n y_min (numeric): lower y coordinate\n y_max (numeric): upper y coordinate\n grid_res (numeric): x and y resolution of the grid we create\n\n Return:\n (list of 2 2dim numpy.ndarray): 2-D coordinate arrays for vectorized evaluations of 2-D scalar/vector fields.\n The arrays are ordered such that the first dimension relates to the X coordinate and the second the Y coordinate. This is done such that\n the 2D coordinate arrays work as-is with visualisation with Mayavi without unnecessary transpose operations.\n \"\"\"\n # The use of indexing='ij' deserves an explanation, as it is counter intuitive. The nupmy doc states\n # https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html\n # In the 2D case with inputs of length M and N, the outputs are of shame N, M for 'xy' indexing and M, N for 'ij' indexing\n # We want an output that preserves the order of x then y coordinates, so we have to use indexing='ij' instead of indexing='xy' otherwise the dim order is swapped, and\n # later on for mayavi visualizations we need to swap them back, which leads to confusions.\n return np.meshgrid(np.arange(x_min, x_max, grid_res),np.arange(y_min, y_max, grid_res), indexing='ij')\n\ndef create_meshgrid(geo_pd, grid_res):\n \"\"\"Create a 2D meshgrid to be used with numpy for vectorized operations and Mayavi visualisation.\n\n Args:\n geo_pd (geopandas): shape from which we can get the bounding box as a basis for the extend of the meshgrid\n grid_res (numeric): x and y resolution of the grid we create\n\n Return:\n (list of 2 2dim numpy.ndarray): 2-D coordinate arrays for vectorized evaluations of 2-D scalar/vector fields.\n The arrays are ordered such that the first dimension relates to the X coordinate and the second the Y coordinate. This is done such that\n the 2D coordinate arrays work as-is with visualisation with Mayavi without unnecessary transpose operations.\n \"\"\"\n x_min, y_min, x_max, y_max = get_bbox(geo_pd)\n return create_meshgrid_cartesian(x_min, x_max, y_min, y_max, grid_res)\n\ndef intersecting_bounds(bounding_boxes):\n \"\"\"Gets the bounding box coordinates common to several spatial data sets\n\n Args:\n bounding_boxes (list): list of bounding boxes\n Returns:\n (tuple): x_min,x_max,y_min,y_max\n\n Example:\n >>> x_min,x_max,y_min,y_max = intersecting_bounds( get_bbox(bore_locations), dem.bounds )\n \"\"\"\n n_bb = len(bounding_boxes)\n # Given the order of the values in the bounding boxes, to get xmin,xmax,ymin,ymax we reorder\n x = [[bounding_boxes[i][j] for i in range(n_bb)] for j in [0, 2, 1, 3]]\n x_min = max(x[0])\n x_max = min(x[1])\n y_min = max(x[2])\n y_max = min(x[3])\n return x_min,x_max,y_min,y_max\n\n\ndef vstacked_points(xx, yy):\n g = (xx, yy)\n m = [np.ravel(pt) for pt in g]\n points = np.vstack(m)\n return points\n\ndef surface_array(raster, x_min, y_min, x_max, y_max, grid_res):\n \"\"\"Creates an isometric 2D grid from a raster, effectively resampling.\n\n This resampling is done to facilitate downstream operations on gridded interpolated volumes.\n\n Args:\n raster (rasterio dataset): raster to sample from, typically DEM elevations\n x_min (numeric): lower x coordinate\n x_max (numeric): upper x coordinate\n y_min (numeric): lower y coordinate\n y_max (numeric): upper y coordinate\n grid_res (numeric): x and y resolution of the grid we create\n\n Return:\n (2dim numpy.ndarray): grid of raster values, typically DEM elevations\n \"\"\"\n xx, yy = create_meshgrid_cartesian(x_min, x_max, y_min, y_max, grid_res)\n points = vstacked_points(xx, yy)\n num_points=points.shape[1]\n band_1 = raster.read(1)\n z = []\n nd = np.float32(raster.nodata)\n for point in np.arange(0,num_points):\n x=points[0,point]\n y=points[1,point]\n nrow, ncol = band_1.shape\n # return band_1.shape\n row, col = raster.index(x,y)\n # July 2018: Change of behavior with (package versions??). At runtime.\n # Python dynamic typing SNAFU...\n row = int(row)\n col = int(col)\n if (row < nrow and col < ncol and row >= 0 and col >= 0):\n result=band_1[row,col]\n if (result == nd):\n result = np.nan\n else:\n result = np.nan\n z=np.append(z,result)\n # z=z.clip(0) This was probably for the DEM assuming all is above sea level?\n #return (z.shape, xx.shape, num_points)\n dem_array=z.reshape(xx.shape)\n return dem_array\n\n\n\n# class_value = 3.0\n# color_name = 'yellow'\n# single_litho = extract_single_lithology_class_3d(test, class_value)\n# mlab.figure(size=(800, 800))\n# # s = np.flip(np.flip(test,axis=2), axis=0)\n# s = flip(flip(single_litho,axis=2), axis=0)\n# vol = mlab.contour3d(s, contours=[class_value-0.5], color=to_rgb(color_name))\n# dem_surf = mlab.surf(xx.T, yy.T, np.flipud(dem_array), warp_scale=10, colormap='terrain')\n# mlab.ylabel(EASTING_COL)\n# mlab.xlabel(NORTHING_COL)\n# mlab.zlabel('mAHD')\n\n# mlab.outline()\n# mlab.show()\n\ndef pad_training_set_functor(classes):\n \"\"\"Create a function that pads a training set so that all possible classes are present\"\"\"\n ### NEED TO APPEND DUMMY DATA TO MAKE SURE ALL CLASSES ARE PRESENT IN EACH SLICE ###\n # 0=sand\n # 1=sandstone\n # 2=clay\n # 3=limestone\n # 4=shale\n # 5=basalt\n # 6=coffee rock\n n = len(classes)\n def pad_training_set(X, y):\n dummy_EN=np.array([[0,0] for i in range(n)])\n dummy_targets=np.array(range(n))\n X=np.vstack((X,dummy_EN))\n y=np.append(y,dummy_targets)\n return (X, y)\n return pad_training_set\n\n\n\nclass GeospatialDataFrameColumnNames(object):\n \"\"\"Operations on data frames with 3D spatial information of lithology logs.\n The purpose of this class is to adapt 'pyela' operations\n to different data without requiring renaming columns.\n\n Attributes:\n easting_col (str): name of the data frame column for easting\n northing_col (str): name of the data frame column for northing\n depth_from_ahd_col (str): name of the data frame column for the height of the top of the soil column (ahd stands for for australian height datum, but not restricted)\n depth_to_ahd_col (str): name of the data frame column for the height of the bottom of the soil column (ahd stands for for australian height datum, but not restricted)\n \"\"\"\n\n def __init__(self, easting_col=EASTING_COL, northing_col=NORTHING_COL, depth_from_ahd_col=DEPTH_FROM_AHD_COL, depth_to_ahd_col=DEPTH_TO_AHD_COL):\n \"\"\"Constructor, operations on data frames with 3D spatial information of lithology logs\n\n Args:\n easting_col (str): name of the data frame column for easting\n northing_col (str): name of the data frame column for northing\n depth_from_ahd_col (str): name of the data frame column for the height of the top of the soil column (ahd stands for for australian height datum, but not restricted)\n depth_to_ahd_col (str): name of the data frame column for the height of the bottom of the soil column (ahd stands for for australian height datum, but not restricted)\n \"\"\"\n self.easting_col = easting_col\n self.northing_col = northing_col\n self.depth_from_ahd_col = depth_from_ahd_col\n self.depth_to_ahd_col = depth_to_ahd_col\n\n def lithologydata_slice_depth(self, df, slice_depth):\n \"\"\"\n Subset data frame with entries at a specified AHD coordinate\n\n Args:\n df (pandas data frame): bore lithology data\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n\n Returns:\n a (view of a) data frame, a subset of the input data frame,\n entries intersecting with the specified slice depth\n \"\"\"\n df_slice=df.loc[(df[self.depth_from_ahd_col] >= slice_depth) & (df[self.depth_to_ahd_col] <= slice_depth)]\n return df_slice\n\n # The following was spurred by trying to get more data in KNN cross-validation, but this may be a dubious method to increase the data pool. Park.\n # def get_lithology_observations_between(df, bottom_ahd, top_ahd, column_name ):\n # \"\"\"\n # Subset data frame with entries at a specified AHD coordinate, and with valid lithology information.\n\n # Args:\n # df (pandas data frame): bore lithology data\n # bottom_ahd (float): bottom AHD coordinate of the slice to subset\n # top_ahd (float): top AHD coordinate of the slice\n # column_name (str): name of the column with string information to use to strip entries with missing lithology information\n\n # Returns:\n # a (view of a) data frame; a subset of the input data frame,\n # entries intersecting with the specified slice depth\n # \"\"\"\n # depth_from_colname=DEPTH_FROM_AHD_COL\n # depth_to_colname=DEPTH_TO_AHD_COL\n # df_slice=df.loc[(df[depth_from_colname] >= top_ahd) & (df[depth_to_colname] <= slice_depth)] # CAREFUL HERE about order and criteria... trickier than 2D slicing.\n # df_1=df_slice[np.isnan(df_slice[column_name]) == False]\n # return df_1\n\n def get_lithology_observations_for_depth(self, df, slice_depth, column_name ):\n \"\"\"\n Subset data frame with entries at a specified AHD coordinate, and with valid lithology information.\n\n Args:\n df (pandas data frame): bore lithology data\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n column_name (str): name of the column with string information to use to strip entries with missing lithology information\n\n Returns:\n a (view of a) data frame; a subset of the input data frame,\n entries intersecting with the specified slice depth\n \"\"\"\n df_slice = self.lithologydata_slice_depth(df, slice_depth)\n df_1 = df_slice[np.isnan(df_slice[column_name]) == False]\n return df_1\n\n def extract_bore_class_num(self, bore_log_df, column_name):\n \"\"\"Gets the columns easting, northing, primary lithology class number, AHD depth 'from' and 'to' from a bore data log\n\n Args:\n bore_log_df (pandas data frame): bore lithology data\n column_name (str): name of the column of interest e.g. lithology descriptions or classes\n \"\"\"\n xx = bore_log_df[self.easting_col].values\n yy = bore_log_df[self.northing_col].values\n ss = bore_log_df[column_name].values\n zz_from = bore_log_df[self.depth_from_ahd_col].values\n zz_to = bore_log_df[self.depth_to_ahd_col].values\n return xx, yy, zz_from, zz_to, ss\n\n def make_training_set(self, observations, column_name):\n \"\"\"Create a training set suitable for machine learning by e.g. scikit-learn out of a georeferenced data frame.\n\n Args:\n observations (pandas data frame): bore lithology data\n column_name (str): name of the column of interest e.g. lithology descriptions or classes\n \"\"\"\n # X = observations.as_matrix(columns=[EASTING_COL, NORTHING_COL])\n X = observations[[self.easting_col, self.northing_col]].values\n y = np.array(observations[column_name])\n #NOTE: should I also do e.g.:\n #shuffle_index = np.random.permutation(len(y))\n #X, y = X[shuffle_index], y[shuffle_index]\n return (X, y)\n\n def get_knn_model(self, df, column_name, slice_depth, n_neighbours):\n \"\"\"Train a K-nearest neighbours model for a given plane\n\n Args:\n df (data frame):\n column_name (str):\n slice_depth (numeric):\n n_neighbours (int):\n\n Returns:\n KNeighborsClassifier: trained classifier.\n \"\"\"\n df_1 = self.get_lithology_observations_for_depth(df, slice_depth, column_name)\n X, y = self.make_training_set(df_1, column_name)\n if n_neighbours > len(df_1):\n return None\n else:\n knn = neighbors.KNeighborsClassifier(n_neighbours, weights = KNN_WEIGHTING).fit(X, y)\n return knn\n\n def class_probability_estimates_depth(self, df, column_name, slice_depth, n_neighbours, mesh_grid, func_training_set=None):\n \"\"\"Subset data frame with entries at a specified AHD coordinate\n\n Args:\n df (pandas data frame): bore lithology data\n column_name (str): name of the column with string information to use to strip entries with missing lithology information\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n n_neighbours (int): number of nearest neighbours\n mesh_grid (tuple): coordinate matrices to interpolate over (numpy.meshgrid)\n func_training_set (callable): a function to processing the training set (e.g. completing dummy with dummy classes, other not present in the trainining set)\n\n Returns:\n a list of numpy arrays, shaped like the meshgrid.\n \"\"\"\n df_1 = self.get_lithology_observations_for_depth(df, slice_depth, column_name)\n X, y = self.make_training_set(df_1, column_name)\n if not (func_training_set is None):\n X, y = func_training_set(X, y)\n knn = neighbors.KNeighborsClassifier(n_neighbours, weights = KNN_WEIGHTING).fit(X, y)\n xx, yy = mesh_grid\n class_prob = knn.predict_proba(np.c_[xx.ravel(), yy.ravel()])\n n_classes = class_prob.shape[1]\n probs = []\n for i in range(n_classes):\n p = class_prob[:,i].reshape(xx.shape)\n probs.append(p)\n return probs\n\n def class_probability_estimates_depth_bbox(self, df, column_name, slice_depth, n_neighbours, geo_pd, grid_res = 100, func_training_set=None):\n \"\"\"Interpolate over a volume the probability of each lithology class\n\n Args:\n df (pandas data frame): bore lithology data, spatially georeferenced\n column_name (str): name of the column with numeric codes for lithology classes\n z_ahd_coords (iterable of int): datum heights at which to interpolate. Must be equal to the length of the last dimension of the volume\n n_neighbours (int): number of nearest neighbours\n mesh_grid (tuple): coordinate matrices to interpolate over (numpy.meshgrid)\n\n Returns:\n numpy array, predicted values over the grid.\n \"\"\"\n mesh_grid = create_meshgrid(geo_pd, grid_res)\n return self.class_probability_estimates_depth(df, column_name, slice_depth, n_neighbours, mesh_grid, func_training_set)\n\n def get_lithology_classes_probabilities(self, lithologies, shape, df, column_name, z_ahd_coords, n_neighbours, mesh_grid):\n \"\"\"Interpolate over a volume the probability of each lithology class\n\n Args:\n shape (tuple of ints): shape of the output volumes to interpolate over\n df (pandas data frame): bore lithology data, spatially georeferenced\n column_name (str): name of the column with numeric codes for lithology classes\n z_ahd_coords (iterable of int): datum heights at which to interpolate. Must be equal to the length of the last dimension of the volume\n n_neighbours (int): number of nearest neighbours\n mesh_grid (tuple): coordinate matrices to interpolate over (numpy.meshgrid)\n\n Returns:\n numpy array, predicted values over the grid.\n \"\"\"\n dim_x,dim_y,dim_z = shape\n vol_template=np.empty((dim_x,dim_y,dim_z))\n classprob_3d_arrays=[vol_template.copy() for i in lithologies]\n n_classes = len(lithologies)\n pad_training_set = pad_training_set_functor(lithologies)\n # iterate over all slices\n for z_index,ahd_height in enumerate(z_ahd_coords):\n result=self.class_probability_estimates_depth(df, column_name, ahd_height, n_neighbours, mesh_grid, func_training_set = pad_training_set)\n for i in range(n_classes):\n classprob_3d_arrays[i][:,:,z_index]=result[i]\n return classprob_3d_arrays\n\n def interpolate_lithologydata_slice_depth(self, df, column_name, slice_depth, n_neighbours, mesh_grid):\n \"\"\"Interpolate lithology data\n\n Args:\n df (pandas data frame): bore lithology data\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n n_neighbours (int): number of nearest neighbours\n mesh_grid (tuple): coordinate matrices to interpolate over (numpy.meshgrid)\n\n Returns:\n numpy array, predicted values over the grid.\n \"\"\"\n knn = self.get_knn_model(df, column_name, slice_depth, n_neighbours)\n return interpolate_over_meshgrid(knn, mesh_grid)\n\n def interpolate_lithologydata_slice_depth_bbox(self, df, column_name, slice_depth, n_neighbours, geo_pd, grid_res = 100):\n \"\"\"Interpolate lithology data\n\n Args:\n df (pandas data frame): bore lithology data\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n n_neighbours (int): number of nearest neighbours\n geo_pd (geopandas df): vector of spatial data from which to get the bounds of interest (bounding box)\n grid_res (int): grid resolution in m for x and y.\n\n Returns:\n numpy array, predicted values over the grid.\n \"\"\"\n mesh_grid = create_meshgrid(geo_pd, grid_res)\n return self.interpolate_lithologydata_slice_depth(df, column_name, slice_depth, n_neighbours, mesh_grid)\n\n\ndef interpolate_over_meshgrid(predicting_algorithm, mesh_grid):\n \"\"\"Interpolate lithology data\n\n Args:\n predicting_algorithm (algorithm with a predict method.): trained algorithm such as the K Nearest Neighbours in scikit (KNN)\n mesh_grid (tuple): coordinate matrices to interpolate over (numpy.meshgrid)\n\n Returns:\n numpy array, predicted values over the grid.\n \"\"\"\n xx, yy = mesh_grid\n if predicting_algorithm is None:\n # the training set was too small and prediction cannot be made (odd that scikit would have let us train still)\n predicted = np.full(xx.shape, np.nan)\n else:\n predicted = predicting_algorithm.predict(np.c_[xx.ravel(), yy.ravel()])\n predicted = predicted.reshape(xx.shape)\n return predicted\n\nclass DepthCoverage:\n \"\"\"Helper class to round lithology record classes to the nearest metre of depth\n\n Attributes:\n df (data frame):\n depth_from_col (str): Column name storing \"from depth\" information\n depth_to_col (str): Column name storing \"to depth\" information\n group_col (str):\n \"\"\"\n def __init__(self, df, group_col = BORE_ID_COL, depth_from_col=DEPTH_FROM_AHD_COL, depth_to_col=DEPTH_TO_AHD_COL):\n \"\"\"Helper class to round lithology record classes to the nearest metre of depth\n\n Args:\n group_col (str):\n depth_from_col (str): Column name storing \"from depth\" information\n depth_to_col (str): Column name storing \"to depth\" information\n \"\"\"\n self.depth_from_col = depth_from_col\n self.depth_to_col = depth_to_col\n self.group_col = group_col\n x=df[np.isnan(df[depth_from_col]) == False]\n df_by_boreid = x.groupby(group_col)\n tops = df_by_boreid[depth_from_col].max()\n bottoms = df_by_boreid[depth_to_col].min()\n self.bore_ahd_depths = pd.concat([tops, bottoms], axis=1).reset_index()\n def bore_at_height(self, datum_height):\n return np.sum( np.logical_and((self.bore_ahd_depths[self.depth_from_col].values >= datum_height), (self.bore_ahd_depths[self.depth_to_col].values < datum_height)) )\n def highest_top(self):\n return self.bore_ahd_depths[self.depth_from_col].max()\n def lowest_bottom(self):\n return self.bore_ahd_depths[self.depth_to_col].min()\n def get_counts(self):\n r = np.array([ float(i) for i in range( int(np.floor(self.lowest_bottom())), int(np.floor(self.highest_top())) ) ])\n cc = np.array([ self.bore_at_height(i) for i in r ])\n return (r, cc)\n def get_range(self, cutoff):\n r, cc = self.get_counts()\n w = np.argwhere(cc > cutoff)\n lowest_ind = w[0][0]\n highest_ind = w[-1][0]\n return r[lowest_ind], r[highest_ind]\n\n\nclass GridInterpolation:\n \"\"\"Operations interpolating over a grid using a trained model\n The purpose of this class is to adapt 'pyela' operations\n to different data without requiring renaming columns.\n\n Attributes:\n dfcn (GeospatialDataFrameColumnNames):\n northing_col (str): name of the data frame column for northing\n depth_from_ahd_col (str): name of the data frame column for the height of the top of the soil column (ahd stands for for australian height datum, but not restricted)\n depth_to_ahd_col (str): name of the data frame column for the height of the bottom of the soil column (ahd stands for for australian height datum, but not restricted)\n \"\"\"\n\n def __init__(self, easting_col=EASTING_COL, northing_col=NORTHING_COL, depth_from_ahd_col=DEPTH_FROM_AHD_COL, depth_to_ahd_col=DEPTH_TO_AHD_COL):\n \"\"\"Constructor, operations interpolating over a grid using a trained model\n\n Args:\n easting_col (str): name of the data frame column for easting\n northing_col (str): name of the data frame column for northing\n depth_from_ahd_col (str): name of the data frame column for the height of the top of the soil column (ahd stands for for australian height datum, but not restricted)\n depth_to_ahd_col (str): name of the data frame column for the height of the bottom of the soil column (ahd stands for for australian height datum, but not restricted)\n \"\"\"\n self.dfcn = GeospatialDataFrameColumnNames(easting_col, northing_col, depth_from_ahd_col, depth_to_ahd_col)\n\n\n def interpolate_volume(self, volume, df, column_name, z_ahd_coords, n_neighbours, mesh_grid):\n \"\"\"Interpolate lithology data over a volume\n\n Args:\n volume (ndarray): 3d volume to fill with interpolated lithologies\n df (pandas data frame): bore lithology data\n column_name (str): name of the column with numeric codes for lithology classes\n z_ahd_coords (iterable of int): datum heights at which to interpolate. Must be equal to the length of the last dimension of the volume\n n_neighbours (int): number of nearest neighbours\n mesh_grid (tuple): coordinate matrices to interpolate over (numpy.meshgrid)\n\n Returns:\n numpy array, predicted values over the grid.\n \"\"\"\n dim_x,dim_y = mesh_grid[0].shape\n dim_z = len(z_ahd_coords)\n if volume.shape[0] != dim_x or volume.shape[1] != dim_y or volume.shape[2] != dim_z:\n raise Error(\"Incompatible dimensions in arguments\")\n for index,ahd_height in enumerate(z_ahd_coords):\n surface = self.interpolate_lithologydata_slice_depth(df, column_name, ahd_height, n_neighbours, mesh_grid)\n volume[:,:,index]=surface\n\n def interpolate_lithologydata_slice_depth(self, df, column_name, slice_depth, n_neighbours, mesh_grid):\n \"\"\"Interpolate lithology data\n\n Args:\n df (pandas data frame): bore lithology data\n column_name (str): name of the column with string information to use to strip entries with missing lithology information\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n n_neighbours (int): number of nearest neighbours\n mesh_grid (tuple): coordinate matrices to interpolate over (numpy.meshgrid)\n\n Returns:\n numpy array, predicted values over the grid.\n \"\"\"\n knn = self.get_knn_model(df, column_name, slice_depth, n_neighbours)\n return interpolate_over_meshgrid(knn, mesh_grid)\n\n def get_knn_model(self, df, column_name, slice_depth, n_neighbours):\n \"\"\"Train a K-nearest neighbours model for a given plane\n\n Args:\n df (pandas data frame): bore lithology data\n column_name (str): name of the column with string information to use to strip entries with missing lithology information\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n n_neighbours (int): number of nearest neighbours\n\n Returns:\n KNeighborsClassifier: trained classifier.\n \"\"\"\n df_1 = self.get_lithology_observations_for_depth(df, slice_depth, column_name)\n X, y = self.make_training_set(df_1, column_name)\n if n_neighbours > len(df_1):\n return None\n else:\n knn = neighbors.KNeighborsClassifier(n_neighbours, weights = KNN_WEIGHTING).fit(X, y)\n return knn\n\n def get_lithology_observations_for_depth(self, df, slice_depth, column_name ):\n \"\"\"\n Subset data frame with entries at a specified AHD coordinate, and with valid lithology information.\n\n Args:\n df (pandas data frame): bore lithology data\n slice_depth (float): AHD coordinate at which to slice the data frame for lithology observations\n column_name (str): name of the column with string information to use to strip entries with missing lithology information\n\n Returns:\n a (view of a) data frame; a subset of the input data frame,\n entries intersecting with the specified slice depth\n \"\"\"\n df_slice=self.dfcn.lithologydata_slice_depth(df, slice_depth)\n df_1=df_slice[np.isnan(df_slice[column_name]) == False]\n return df_1\n\n def make_training_set(self, observations, column_name):\n \"\"\"Create a training set from a set of geolocated observations\n\n Args:\n observations (pandas data frame): bore lithology data with geocoordinates\n column_name (str): name of the column with string information to use to strip entries with missing lithology information\n\n Returns:\n (tuple): observations and predictors (geolocation).\n \"\"\"\n X = observations[[self.dfcn.easting_col, self.dfcn.northing_col]].values\n y = np.array(observations[column_name])\n #NOTE: should I also do e.g.:\n #shuffle_index = np.random.permutation(len(y))\n #X, y = X[shuffle_index], y[shuffle_index]\n return (X, y)\n\n" ]
[ [ "pandas.read_pickle" ], [ "numpy.argwhere", "numpy.vstack", "numpy.append", "numpy.logical_and", "numpy.empty_like", "numpy.isnan", "numpy.unique", "numpy.float32", "numpy.column_stack", "numpy.arange", "pandas.concat", "sklearn.neighbors.KNeighborsClassifier", "pandas.notna", "numpy.empty", "pandas.DataFrame", "numpy.floor", "numpy.ravel", "numpy.array", "numpy.full" ] ]
ashblib/protocell
[ "037c3aa6ab2250eae09889729d512c243518e282" ]
[ "model/protonet.py" ]
[ "import torch.nn as nn\nimport torch\n\nclass ProtoNetBig(nn.Module):\n def __init__(self, x_dim=23433, hid_dim=[2000, 1000, 500, 250], z_dim=100):\n super(ProtoNetBig, self).__init__()\n self.linear0 = nn.Linear(x_dim, hid_dim[0])\n self.bn1 = nn.BatchNorm1d(hid_dim[0])\n self.linear1 = nn.Linear(hid_dim[0], hid_dim[1])\n self.bn2 = nn.BatchNorm1d(hid_dim[1])\n self.linear2 = nn.Linear(hid_dim[1] + hid_dim[0], hid_dim[2])\n self.bn3 = nn.BatchNorm1d(hid_dim[2])\n self.linear3 = nn.Linear(hid_dim[1] + hid_dim[0] + hid_dim[2], hid_dim[3])\n self.bn4 = nn.BatchNorm1d(hid_dim[3])\n self.linear4 = nn.Linear(hid_dim[1] + hid_dim[0] + hid_dim[2] + hid_dim[3], z_dim)\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(inplace=True)\n def forward(self, x):\n out = self.dropout(self.bn1(self.relu(self.linear0(x))))\n out1 = self.dropout(self.bn2(self.relu(self.linear1(out))))\n out2 = torch.cat([out, out1], 1)\n out3 = self.dropout(self.bn3(self.relu(self.linear2(out2))))\n out4 = torch.cat([out, out1, out3], 1)\n out5 = self.dropout(self.bn4(self.relu(self.linear3(out4))))\n out6 = torch.cat([out, out1, out3, out5], 1)\n out7 = self.linear4(out6)\n return out7" ]
[ [ "torch.nn.Linear", "torch.nn.BatchNorm1d", "torch.cat", "torch.nn.ReLU", "torch.nn.Dropout" ] ]
XiaoJake/SOLD2
[ "ddd36788c112136be2975ee29b096df979571bb2" ]
[ "sold2/model/model_util.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.init as init\n\nfrom .nets.backbone import HourglassBackbone, SuperpointBackbone\nfrom .nets.junction_decoder import SuperpointDecoder\nfrom .nets.heatmap_decoder import PixelShuffleDecoder\nfrom .nets.descriptor_decoder import SuperpointDescriptor\n\n\ndef get_model(model_cfg=None, loss_weights=None, mode=\"train\"):\n \"\"\" Get model based on the model configuration. \"\"\"\n # Check dataset config is given\n if model_cfg is None:\n raise ValueError(\"[Error] The model config is required!\")\n\n # List the supported options here\n print(\"\\n\\n\\t--------Initializing model----------\")\n supported_arch = [\"simple\"]\n if not model_cfg[\"model_architecture\"] in supported_arch:\n raise ValueError(\n \"[Error] The model architecture is not in supported arch!\")\n\n if model_cfg[\"model_architecture\"] == \"simple\":\n model = SOLD2Net(model_cfg)\n else:\n raise ValueError(\n \"[Error] The model architecture is not in supported arch!\")\n\n # Optionally register loss weights to the model\n if mode == \"train\":\n if loss_weights is not None:\n for param_name, param in loss_weights.items():\n if isinstance(param, nn.Parameter):\n print(\"\\t [Debug] Adding %s with value %f to model\"\n % (param_name, param.item()))\n model.register_parameter(param_name, param)\n else:\n raise ValueError(\n \"[Error] the loss weights can not be None in dynamic weighting mode during training.\")\n\n # Display some summary info.\n print(\"\\tModel architecture: %s\" % model_cfg[\"model_architecture\"])\n print(\"\\tBackbone: %s\" % model_cfg[\"backbone\"])\n print(\"\\tJunction decoder: %s\" % model_cfg[\"junction_decoder\"])\n print(\"\\tHeatmap decoder: %s\" % model_cfg[\"heatmap_decoder\"])\n print(\"\\t-------------------------------------\")\n\n return model\n\n\nclass SOLD2Net(nn.Module):\n \"\"\" Full network for SOLD². \"\"\"\n def __init__(self, model_cfg):\n super(SOLD2Net, self).__init__()\n self.name = model_cfg[\"model_name\"]\n self.cfg = model_cfg\n\n # List supported network options\n self.supported_backbone = [\"lcnn\", \"superpoint\"]\n self.backbone_net, self.feat_channel = self.get_backbone()\n\n # List supported junction decoder options\n self.supported_junction_decoder = [\"superpoint_decoder\"]\n self.junction_decoder = self.get_junction_decoder()\n\n # List supported heatmap decoder options\n self.supported_heatmap_decoder = [\"pixel_shuffle\",\n \"pixel_shuffle_single\"]\n self.heatmap_decoder = self.get_heatmap_decoder()\n\n # List supported descriptor decoder options\n if \"descriptor_decoder\" in self.cfg:\n self.supported_descriptor_decoder = [\"superpoint_descriptor\"]\n self.descriptor_decoder = self.get_descriptor_decoder()\n\n # Initialize the model weights\n self.apply(weight_init)\n\n def forward(self, input_images):\n # The backbone\n features = self.backbone_net(input_images)\n\n # junction decoder\n junctions = self.junction_decoder(features)\n\n # heatmap decoder\n heatmaps = self.heatmap_decoder(features)\n\n outputs = {\"junctions\": junctions, \"heatmap\": heatmaps}\n\n # Descriptor decoder\n if \"descriptor_decoder\" in self.cfg:\n outputs[\"descriptors\"] = self.descriptor_decoder(features)\n\n return outputs\n\n def get_backbone(self):\n \"\"\" Retrieve the backbone encoder network. \"\"\"\n if not self.cfg[\"backbone\"] in self.supported_backbone:\n raise ValueError(\n \"[Error] The backbone selection is not supported.\")\n\n # lcnn backbone (stacked hourglass)\n if self.cfg[\"backbone\"] == \"lcnn\":\n backbone_cfg = self.cfg[\"backbone_cfg\"]\n backbone = HourglassBackbone(**backbone_cfg)\n feat_channel = 256\n\n elif self.cfg[\"backbone\"] == \"superpoint\":\n backbone_cfg = self.cfg[\"backbone_cfg\"]\n backbone = SuperpointBackbone()\n feat_channel = 128\n\n else:\n raise ValueError(\n \"[Error] The backbone selection is not supported.\")\n\n return backbone, feat_channel\n\n def get_junction_decoder(self):\n \"\"\" Get the junction decoder. \"\"\"\n if (not self.cfg[\"junction_decoder\"]\n in self.supported_junction_decoder):\n raise ValueError(\n \"[Error] The junction decoder selection is not supported.\")\n\n # superpoint decoder\n if self.cfg[\"junction_decoder\"] == \"superpoint_decoder\":\n decoder = SuperpointDecoder(self.feat_channel,\n self.cfg[\"backbone\"])\n else:\n raise ValueError(\n \"[Error] The junction decoder selection is not supported.\")\n\n return decoder\n\n def get_heatmap_decoder(self):\n \"\"\" Get the heatmap decoder. \"\"\"\n if not self.cfg[\"heatmap_decoder\"] in self.supported_heatmap_decoder:\n raise ValueError(\n \"[Error] The heatmap decoder selection is not supported.\")\n\n # Pixel_shuffle decoder\n if self.cfg[\"heatmap_decoder\"] == \"pixel_shuffle\":\n if self.cfg[\"backbone\"] == \"lcnn\":\n decoder = PixelShuffleDecoder(self.feat_channel,\n num_upsample=2)\n elif self.cfg[\"backbone\"] == \"superpoint\":\n decoder = PixelShuffleDecoder(self.feat_channel,\n num_upsample=3)\n else:\n raise ValueError(\"[Error] Unknown backbone option.\")\n # Pixel_shuffle decoder with single channel output\n elif self.cfg[\"heatmap_decoder\"] == \"pixel_shuffle_single\":\n if self.cfg[\"backbone\"] == \"lcnn\":\n decoder = PixelShuffleDecoder(\n self.feat_channel, num_upsample=2, output_channel=1)\n elif self.cfg[\"backbone\"] == \"superpoint\":\n decoder = PixelShuffleDecoder(\n self.feat_channel, num_upsample=3, output_channel=1)\n else:\n raise ValueError(\"[Error] Unknown backbone option.\")\n else:\n raise ValueError(\n \"[Error] The heatmap decoder selection is not supported.\")\n\n return decoder\n\n def get_descriptor_decoder(self):\n \"\"\" Get the descriptor decoder. \"\"\"\n if (not self.cfg[\"descriptor_decoder\"]\n in self.supported_descriptor_decoder):\n raise ValueError(\n \"[Error] The descriptor decoder selection is not supported.\")\n\n # SuperPoint descriptor\n if self.cfg[\"descriptor_decoder\"] == \"superpoint_descriptor\":\n decoder = SuperpointDescriptor(self.feat_channel)\n else:\n raise ValueError(\n \"[Error] The descriptor decoder selection is not supported.\")\n\n return decoder\n\n\ndef weight_init(m):\n \"\"\" Weight initialization function. \"\"\"\n # Conv2D\n if isinstance(m, nn.Conv2d):\n init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n init.normal_(m.bias.data)\n # Batchnorm\n elif isinstance(m, nn.BatchNorm2d):\n init.normal_(m.weight.data, mean=1, std=0.02)\n init.constant_(m.bias.data, 0)\n # Linear\n elif isinstance(m, nn.Linear):\n init.xavier_normal_(m.weight.data)\n init.normal_(m.bias.data)\n else:\n pass\n" ]
[ [ "torch.nn.init.normal_", "torch.nn.init.constant_", "torch.nn.init.xavier_normal_" ] ]
JohnGriffiths/dipy
[ "5fb38e9b77547cdaf5eb140730444535733ae01d" ]
[ "dipy/reconst/tests/test_peakdf.py" ]
[ "import numpy as np\nimport numpy.testing as npt\n\nfrom dipy.reconst.peaks import default_sphere, peaks_from_model\n\n\ndef test_PeaksAndMetricsDirectionGetter():\n\n class SillyModel(object):\n def fit(self, data, mask=None):\n return SillyFit(self)\n\n class SillyFit(object):\n\n def __init__(self, model):\n self.model = model\n\n def odf(self, sphere):\n odf = np.zeros(sphere.theta.shape)\n r = np.random.randint(0, len(odf))\n odf[r] = 1\n return odf\n\n def get_direction(dg, point, dir):\n newdir = dir.copy()\n state = dg.get_direction(point, newdir)\n return (state, np.array(newdir))\n\n data = np.random.random((3, 4, 5, 2))\n peaks = peaks_from_model(SillyModel(), data, default_sphere,\n relative_peak_threshold=.5,\n min_separation_angle=25)\n peaks._initialize()\n\n up = np.zeros(3)\n up[2] = 1.\n down = -up\n\n for i in range(3-1):\n for j in range(4-1):\n for k in range(5-1):\n point = np.array([i, j, k], dtype=float)\n\n # Test that the angle threshold rejects points\n peaks.ang_thr = 0.\n state, nd = get_direction(peaks, point, up)\n npt.assert_equal(state, 1)\n\n # Here we leverage the fact that we know Hemispheres project\n # all their vertices into the z >= 0 half of the sphere.\n peaks.ang_thr = 90.\n state, nd = get_direction(peaks, point, up)\n npt.assert_equal(state, 0)\n expected_dir = peaks.peak_dirs[i, j, k, 0]\n npt.assert_array_almost_equal(nd, expected_dir)\n state, nd = get_direction(peaks, point, down)\n npt.assert_array_almost_equal(nd, -expected_dir)\n\n # Check that we can get directions at non-integer points\n point += np.random.random(3)\n state, nd = get_direction(peaks, point, up)\n npt.assert_equal(state, 0)\n\n # Check that points are rounded to get initial direction\n point -= .5\n id = peaks.initial_direction(point)\n # id should be a (1, 3) array\n npt.assert_array_almost_equal(id, [expected_dir])\n\n\nif __name__ == \"__main__\":\n npt.run_module_suite()\n\n" ]
[ [ "numpy.zeros", "numpy.testing.assert_equal", "numpy.testing.run_module_suite", "numpy.random.random", "numpy.testing.assert_array_almost_equal", "numpy.array" ] ]
reactivetype/cs234-reinforcement-learning
[ "693a90854d6548157ac8ec1c70a90b08810aec1b" ]
[ "assignment/assignment2/q3_nature.py" ]
[ "import tensorflow as tf\r\nimport tensorflow.contrib.layers as layers\r\n\r\nfrom utils.general import get_logger\r\nfrom utils.test_env import EnvTest\r\nfrom q1_schedule import LinearExploration, LinearSchedule\r\nfrom q2_linear import Linear\r\n\r\n\r\nfrom configs.q3_nature import config\r\n\r\n\r\nclass NatureQN(Linear):\r\n \"\"\"\r\n Implementing DeepMind's Nature paper. Here are the relevant urls.\r\n https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf\r\n https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf\r\n \"\"\"\r\n def get_q_values_op(self, state, scope, reuse=False):\r\n \"\"\"\r\n Returns Q values for all actions\r\n\r\n Args:\r\n state: (tf tensor) \r\n shape = (batch_size, img height, img width, nchannels)\r\n scope: (string) scope name, that specifies if target network or not\r\n reuse: (bool) reuse of variables in the scope\r\n\r\n Returns:\r\n out: (tf tensor) of shape = (batch_size, num_actions)\r\n \"\"\"\r\n # this information might be useful\r\n num_actions = self.env.action_space.n\r\n ##############################################################\r\n \"\"\"\r\n TODO: implement the computation of Q values like in the paper\r\n https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf\r\n\r\n you may find the section \"model architecture\" of the appendix of the \r\n nature paper particulary useful.\r\n\r\n store your result in out of shape = (batch_size, num_actions)\r\n\r\n HINT: you may find tensorflow.contrib.layers useful (imported)\r\n make sure to understand the use of the scope param\r\n make sure to flatten() the tensor before connecting it to fully connected layers \r\n\r\n you can use any other methods from tensorflow\r\n you are not allowed to import extra packages (like keras,\r\n lasagne, cafe, etc.)\r\n\r\n \"\"\"\r\n ##############################################################\r\n ################ YOUR CODE HERE - 10-15 lines ################ \r\n with tf.variable_scope(scope, reuse):\r\n conv1 = layers.conv2d(inputs = state, num_outputs = 32,\r\n kernel_size = [8, 8], stride = 4,\r\n activation_fn = tf.nn.relu,\r\n reuse = reuse, scope = \"Conv1\")\r\n conv2 = layers.conv2d(inputs = conv1, num_outputs = 64,\r\n kernel_size = [4, 4], stride = 2,\r\n activation_fn = tf.nn.relu,\r\n reuse=reuse, scope = \"Conv2\")\r\n conv3 = layers.conv2d(inputs=conv2, num_outputs=64,\r\n kernel_size=[3, 3], stride=1,\r\n activation_fn=tf.nn.relu,\r\n reuse=reuse, scope=\"Conv3\")\r\n flattened = layers.flatten(conv3, scope = \"flattened\")\r\n hidden_fc = layers.fully_connected(inputs = flattened,\r\n num_outputs = 512,\r\n activation_fn = tf.nn.relu,\r\n reuse=reuse, scope = \"hidden-fc\")\r\n out = layers.fully_connected(inputs = hidden_fc,\r\n num_outputs = num_actions,\r\n activation_fn = None,\r\n reuse=reuse, scope = \"output-Q\")\r\n\r\n ##############################################################\r\n ######################## END YOUR CODE #######################\r\n return out\r\n\r\n\r\n\"\"\"\r\nUse deep Q network for test environment.\r\n\"\"\"\r\nif __name__ == '__main__':\r\n env = EnvTest((80, 80, 1))\r\n\r\n # exploration strategy\r\n exp_schedule = LinearExploration(env, config.eps_begin, \r\n config.eps_end, config.eps_nsteps)\r\n\r\n # learning rate schedule\r\n lr_schedule = LinearSchedule(config.lr_begin, config.lr_end,\r\n config.lr_nsteps)\r\n\r\n # train model\r\n model = NatureQN(env, config)\r\n model.run(exp_schedule, lr_schedule)\r\n" ]
[ [ "tensorflow.contrib.layers.flatten", "tensorflow.contrib.layers.fully_connected", "tensorflow.contrib.layers.conv2d", "tensorflow.variable_scope" ] ]
onodip/OpenMDAO
[ "96a99806fb3a547b881d2ad3da2733bca9978567" ]
[ "openmdao/approximation_schemes/complex_step.py" ]
[ "\"\"\"Complex Step derivative approximations.\"\"\"\nfrom __future__ import division, print_function\n\nfrom itertools import groupby\nfrom six.moves import range\n\nimport numpy as np\n\nfrom openmdao.approximation_schemes.approximation_scheme import ApproximationScheme\nfrom openmdao.utils.name_maps import abs_key2rel_key\n\n\nDEFAULT_CS_OPTIONS = {\n 'step': 1e-15,\n 'form': 'forward',\n}\n\n\nclass ComplexStep(ApproximationScheme):\n r\"\"\"\n Approximation scheme using complex step to calculate derivatives.\n\n For example, using a step size of 'h' will approximate the derivative in\n the following way:\n\n .. math::\n\n f'(x) = \\Im{\\frac{f(x+ih)}{h}}.\n\n Attributes\n ----------\n _exec_list : list\n A list of which derivatives (in execution order) to compute.\n The entries are of the form (of, wrt, options), where of and wrt are absolute names\n and options is a dictionary.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize the ApproximationScheme.\n \"\"\"\n super(ComplexStep, self).__init__()\n self._exec_list = []\n\n def add_approximation(self, abs_key, kwargs):\n \"\"\"\n Use this approximation scheme to approximate the derivative d(of)/d(wrt).\n\n Parameters\n ----------\n abs_key : tuple(str,str)\n Absolute name pairing of (of, wrt) for the derivative.\n kwargs : dict\n Additional keyword arguments, to be interpreted by sub-classes.\n \"\"\"\n of, wrt = abs_key\n options = DEFAULT_CS_OPTIONS.copy()\n options.update(kwargs)\n self._exec_list.append((of, wrt, options))\n\n @staticmethod\n def _key_fun(approx_tuple):\n \"\"\"\n Compute the sorting key for an approximation tuple.\n\n Parameters\n ----------\n approx_tuple : tuple(str, str, dict)\n A given approximated derivative (of, wrt, options)\n\n Returns\n -------\n tuple(str, str, float)\n Sorting key (wrt, form, step_size)\n\n \"\"\"\n options = approx_tuple[2]\n return (approx_tuple[1], options['form'], options['step'])\n\n def _init_approximations(self):\n \"\"\"\n Prepare for later approximations.\n \"\"\"\n # itertools.groupby works like `uniq` rather than the SQL query, meaning that it will only\n # group adjacent items with identical keys.\n self._exec_list.sort(key=self._key_fun)\n\n # TODO: Automatic sparse FD by constructing a graph of variable dependence?\n\n def compute_approximations(self, system, jac=None, deriv_type='partial'):\n \"\"\"\n Execute the system to compute the approximate sub-Jacobians.\n\n Parameters\n ----------\n system : System\n System on which the execution is run.\n jac : None or dict-like\n If None, update system with the approximated sub-Jacobians. Otherwise, store the\n approximations in the given dict-like object.\n deriv_type : str\n One of 'total' or 'partial', indicating if total or partial derivatives are\n being approximated.\n \"\"\"\n if jac is None:\n jac = system._jacobian\n\n if deriv_type == 'total':\n current_vec = system._outputs\n elif deriv_type == 'partial':\n current_vec = system._residuals\n else:\n raise ValueError('deriv_type must be one of \"total\" or \"partial\"')\n\n # Turn on complex step.\n system._inputs._vector_info._under_complex_step = True\n\n # create a scratch array\n out_tmp = system._outputs.get_data()\n results_clone = current_vec._clone(True)\n\n # To support driver src_indices, we need to override some checks in Jacobian, but do it\n # selectively.\n uses_src_indices = (system._owns_approx_of_idx or system._owns_approx_wrt_idx) and \\\n not isinstance(jac, dict)\n\n for key, approximations in groupby(self._exec_list, self._key_fun):\n # groupby (along with this key function) will group all 'of's that have the same wrt and\n # step size.\n wrt, form, delta = key\n if form == 'reverse':\n delta *= -1.0\n fact = 1.0 / delta\n\n if wrt in system._owns_approx_wrt_idx:\n in_idx = system._owns_approx_wrt_idx[wrt]\n in_size = len(in_idx)\n else:\n if wrt in system._var_abs2meta:\n in_size = system._var_abs2meta[wrt]['size']\n\n in_idx = range(in_size)\n\n outputs = []\n\n # Note: If access to `approximations` is required again in the future, we will need to\n # throw it in a list first. The groupby iterator only works once.\n for approx_tuple in approximations:\n of = approx_tuple[0]\n # TODO: Sparse derivatives\n if of in system._owns_approx_of_idx:\n out_idx = system._owns_approx_of_idx[of]\n out_size = len(out_idx)\n else:\n out_size = system._var_abs2meta[of]['size']\n\n outputs.append((of, np.zeros((out_size, in_size))))\n\n for i_count, idx in enumerate(in_idx):\n # Run the Finite Difference\n input_delta = [(wrt, idx, delta)]\n result = self._run_point_complex(system, input_delta, out_tmp, results_clone,\n deriv_type)\n\n for of, subjac in outputs:\n if of in system._owns_approx_of_idx:\n out_idx = system._owns_approx_of_idx[of]\n subjac[:, i_count] = result._imag_views_flat[of][out_idx] * fact\n else:\n subjac[:, i_count] = result._imag_views_flat[of] * fact\n\n for of, subjac in outputs:\n rel_key = abs_key2rel_key(system, (of, wrt))\n if uses_src_indices:\n jac._override_checks = True\n jac[rel_key] = subjac\n if uses_src_indices:\n jac._override_checks = False\n\n # Turn off complex step.\n system._inputs._vector_info._under_complex_step = False\n\n def _run_point_complex(self, system, input_deltas, out_tmp, result_clone, deriv_type='partial'):\n \"\"\"\n Perturb the system inputs with a complex step, runs, and returns the results.\n\n Parameters\n ----------\n system : System\n The system having its derivs approximated.\n input_deltas : list\n List of (input name, indices, delta) tuples, where input name is an absolute name.\n out_tmp : ndarray\n An array the same size as the system outputs that is used for temporary storage.\n result_clone : Vector\n A vector cloned from the outputs vector. Used to store the results.\n deriv_type : str\n One of 'total' or 'partial', indicating if total or partial derivatives are being\n approximated.\n\n Returns\n -------\n Vector\n Copy of the results from running the perturbed system.\n \"\"\"\n # TODO: MPI\n\n inputs = system._inputs\n outputs = system._outputs\n\n if deriv_type == 'total':\n run_model = system.run_solve_nonlinear\n results_vec = outputs\n elif deriv_type == 'partial':\n run_model = system.run_apply_nonlinear\n results_vec = system._residuals\n else:\n raise ValueError('deriv_type must be one of \"total\" or \"partial\"')\n\n for in_name, idxs, delta in input_deltas:\n if in_name in outputs._imag_views_flat:\n outputs._imag_views_flat[in_name][idxs] += delta\n else:\n inputs._imag_views_flat[in_name][idxs] += delta\n\n results_vec.get_data(out_tmp)\n run_model()\n\n # TODO: Grab only results of interest\n result_clone.set_vec(results_vec)\n results_vec.set_data(out_tmp)\n\n for in_name, idxs, delta in input_deltas:\n if in_name in outputs._imag_views_flat:\n outputs._imag_views_flat[in_name][idxs] -= delta\n else:\n inputs._imag_views_flat[in_name][idxs] -= delta\n\n return result_clone\n" ]
[ [ "numpy.zeros" ] ]
yarikoptic/NiPy-OLD
[ "8759b598ac72d3b9df7414642c7a662ad9c55ece", "8759b598ac72d3b9df7414642c7a662ad9c55ece", "8759b598ac72d3b9df7414642c7a662ad9c55ece" ]
[ "nipy/neurospin/register/__init__.py", "nipy/neurospin/register/tests/test_iconic_matcher.py", "examples/neurospin/hierarchical_rois.py" ]
[ "from iconic_matcher import IconicMatcher\n#from realign4d import TimeSeries, realign4d, resample4d\nimport transform\n\nfrom numpy.testing import Tester\n\ntest = Tester().test\nbench = Tester().bench \n\n", "#!/usr/bin/env python\n\nfrom nipy.testing import assert_equal, assert_almost_equal, assert_raises\nimport numpy as np\n\nfrom nipy.neurospin.register.iconic_matcher import IconicMatcher\n\n\nclass Image(object):\n \"\"\" \n Empty object to easily create image objects independently from any I/O package.\n \"\"\"\n def __init__(self, array, toworld=None, voxsize=[1, 1, 1]):\n self.array = array\n self.voxsize = np.asarray(voxsize)\n if toworld == None: \n toworld = np.diag(np.concatenate((self.voxsize, [1])))\n self.toworld = toworld\n\n\n\ndef make_data_uint8(dx=100, dy=100, dz=50):\n return (256*(np.random.rand(dx, dy, dz) - np.random.rand())).astype('uint8')\n\ndef make_data_int16(dx=100, dy=100, dz=50):\n return (256*(np.random.rand(dx, dy, dz) - np.random.rand())).astype('int16')\n\ndef make_data_float64(dx=100, dy=100, dz=50):\n return (256*(np.random.rand(dx, dy, dz) - np.random.rand())).astype('float64')\n\ndef _test_clamping(I, thI=0.0, clI=256):\n IM = IconicMatcher(I.array, I.array, I.toworld, I.toworld, thI, thI, source_bins=clI, target_bins=clI)\n Ic = IM.source_clamped\n Ic2 = IM.target_clamped[1:I.array.shape[0]+1,1:I.array.shape[1]+1,1:I.array.shape[2]+1].squeeze()\n assert_equal(Ic, Ic2)\n dyn = Ic.max() + 1\n assert_equal(dyn, IM.joint_hist.shape[0])\n assert_equal(dyn, IM.joint_hist.shape[1])\n assert_equal(dyn, IM.source_hist.shape[0])\n assert_equal(dyn, IM.target_hist.shape[0])\n\ndef test_clamping_uint8(): \n I = Image(make_data_uint8())\n _test_clamping(I)\n\ndef test_clamping_uint8_nonstd():\n I = Image(make_data_uint8())\n _test_clamping(I, 10, 165)\n\ndef test_clamping_int16(): \n I = Image(make_data_int16())\n _test_clamping(I)\n\ndef test_clamping_int16_nonstd(): \n I = Image(make_data_int16())\n _test_clamping(I, 10, 165)\n\ndef test_clamping_float64(): \n I = Image(make_data_float64())\n _test_clamping(I)\n\ndef test_clamping_float64_nonstd():\n I = Image(make_data_float64())\n _test_clamping(I, 10, 165)\n \ndef _test_similarity_measure(simi, val):\n I = Image(make_data_int16())\n J = Image(I.array.copy())\n IM = IconicMatcher(I.array, J.array, I.toworld, J.toworld)\n IM.set_field_of_view(subsampling=[2,1,3])\n IM.set_similarity(simi)\n assert_almost_equal(IM.eval(np.eye(4)), val)\n\ndef test_correlation_coefficient():\n _test_similarity_measure('cc', 1.0) \n\ndef test_correlation_ratio():\n _test_similarity_measure('cr', 1.0) \n\ndef test_normalized_mutual_information():\n _test_similarity_measure('nmi', 1.0) \n\ndef test_explore(): \n I = Image(make_data_int16())\n J = Image(make_data_int16())\n IM = IconicMatcher(I.array, J.array, I.toworld, J.toworld)\n T = np.eye(4)\n T[0:3,3] = np.random.rand(3)\n simi, params = IM.explore(ux=[-1,0,1],uy=[-1,0,1])\n\ndef test_iconic():\n \"\"\" Test the iconic class.\n \"\"\"\n I = Image(make_data_int16())\n J = Image(I.array.copy())\n IM = IconicMatcher(I.array, J.array, I.toworld, J.toworld)\n assert_raises(ValueError, IM.set_field_of_view, subsampling=[0,1,3])\n\nif __name__ == \"__main__\":\n import nose\n nose.run(argv=['', __file__])\n", "\"\"\"\nExample of a script that crates a 'hierarchical roi' structure\nfrom the blob model of an image\n\nfixme : redo it\nUsed mainly for debugging at the moment (before unittests are created)\n\nThis example is based on a (simplistic) simulated image.\n# Author : Bertrand Thirion, 2008-2009\n\"\"\"\n\nimport numpy as np\n\n\nimport nipy.neurospin.spatial_models.hroi as hroi\nimport nipy.neurospin.utils.simul_2d_multisubject_fmri_dataset as simul\nimport nipy.neurospin.graph.field as ff\n\n##############################################################################\n# simulate the data\ndimx = 60\ndimy = 60\npos = 2*np.array([[6,7],[10,10],[15,10]])\nampli = np.array([3,4,4])\n\ndataset = simul.make_surrogate_array(nbsubj=1, dimx=dimx, dimy=dimy, pos=pos,\n ampli=ampli, width=10.0).squeeze()\n\ndataset = np.reshape(dataset, (dimx, dimy,1))\nref_dim = (dimx,dimy,1)\nxyz = np.array(np.where(dataset)).T\nnbvox = np.size(xyz, 0)\naffine = np.eye(4)\nshape = (dimx,dimy,1)\n\n# create the field strcture that encodes image topology\nFbeta = ff.Field(nbvox)\nFbeta.from_3d_grid(xyz.astype(np.int), 18)\nbeta = np.reshape(dataset,(nbvox,1))\nFbeta.set_field(beta)\nnroi = hroi.NROI_from_field(Fbeta, affine, shape, xyz, th=2.0, smin = 10)\nif nroi != None:\n n1 = nroi.copy()\n n2 = nroi.reduce_to_leaves()\n\ntd = n1.depth_from_leaves()\na = np.argmax(td)\nlv = n1.rooted_subtree(a)\nu = nroi.cc()\nu = np.nonzero(u == u[0])[0]\n\nnroi.set_discrete_feature_from_index('activation',beta)\nnroi.discrete_to_roi_features('activation')\n\n\nlabel = -np.ones((dimx,dimy))\nfor k in range(nroi.k):\n label[nroi.xyz[k][:,0],nroi.xyz[k][:,1]]=k\nimport matplotlib.pylab as mp\nmp.figure()\nmp.imshow(label,interpolation='Nearest')\nmp.show()\n" ]
[ [ "numpy.testing.Tester" ], [ "numpy.concatenate", "numpy.eye", "numpy.asarray", "numpy.random.rand" ], [ "numpy.eye", "numpy.ones", "numpy.reshape", "matplotlib.pylab.figure", "numpy.argmax", "numpy.size", "matplotlib.pylab.show", "numpy.array", "matplotlib.pylab.imshow", "numpy.where", "numpy.nonzero" ] ]
bdshieh/cnl-dyna
[ "9013fa11cabb6ad51aaa385b44ef99cc43bf6a2b" ]
[ "cnld/util.py" ]
[ "'''\nUtility functions.\n'''\nimport argparse\nimport functools\nimport itertools\nimport os\nimport sqlite3 as sql\nfrom contextlib import closing\nfrom copy import deepcopy\nfrom itertools import repeat\n\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nimport scipy.fftpack\nimport scipy.signal\nfrom cnld import abstract\nfrom scipy.spatial.distance import cdist\n''' GEOMETRY-RELATED FUNCTIONS '''\n\n\ndef meshview(v1, v2, v3, mode='cartesian', as_list=True):\n '''\n '''\n if mode.lower() in ('cart', 'cartesian'):\n x, y, z = np.meshgrid(v1, v2, v3, indexing='ij')\n\n elif mode.lower() in ('sph', 'spherical'):\n r, theta, phi = np.meshgrid(v1, np.deg2rad(v2), np.deg2rad(v3), indexing='ij')\n x, y, z = sph2cart(r, theta, phi)\n\n elif mode.lower() in ('sec', 'sector'):\n r, alpha, beta = np.meshgrid(v1, np.deg2rad(v2), np.deg2rad(v3), indexing='ij')\n x, y, z = sec2cart(r, alpha, beta)\n\n elif mode.lower() in ('dp', 'dpolar'):\n r, alpha, beta = np.meshgrid(v1, np.deg2rad(v2), np.deg2rad(v3), indexing='ij')\n x, y, z = dp2cart(r, alpha, beta)\n\n if as_list:\n return np.c_[x.ravel('F'), y.ravel('F'), z.ravel('F')]\n else:\n return x, y, z\n\n\ndef sec2cart(r, alpha, beta):\n '''\n '''\n z = r / np.sqrt(np.tan(alpha)**2 + np.tan(beta)**2 + 1)\n x = z * np.tan(alpha)\n y = z * np.tan(beta)\n\n # alpha_p = np.arctan(np.tan(alpha) * np.cos(beta))\n # x = np.sin(alpha_p) * r\n # y = -np.sin(beta) * r * np.cos(alpha_p)\n # z = np.sqrt(r**2 - x**2 - y**2)\n\n # px = -px\n # pyp = np.arctan(np.cos(px) * np.sin(py) / np.cos(py))\n # x = r * np.sin(pyp)\n # y = -r * np.cos(pyp) * np.sin(px)\n # z = r * np.cos(px) * np.cos(pyp)\n\n return x, y, z\n\n\ndef cart2sec(x, y, z):\n '''\n '''\n r = np.sqrt(x**2 + y**2 + z**2)\n alpha = np.arccos(z / (np.sqrt(x**2 + z**2))) * np.sign(x)\n beta = np.arccos(z / (np.sqrt(y**2 + z**2))) * np.sign(y)\n\n # r = np.sqrt(x**2 + y**2 + z**2)\n # alpha_p = np.arcsin(x / r)\n # beta = -np.arcsin(-y / r / np.cos(alpha_p))\n # alpha = np.arctan(np.tan(alpha_p) / np.cos(beta))\n\n return r, alpha, beta\n\n\ndef sph2cart(r, theta, phi):\n '''\n '''\n x = r * np.cos(theta) * np.sin(phi)\n y = r * np.sin(theta) * np.sin(phi)\n z = r * np.cos(phi)\n\n return x, y, z\n\n\ndef cart2sph(x, y, z):\n '''\n '''\n r = np.sqrt(x**2 + y**2 + z**2)\n theta = np.arctan(y / x)\n phi = np.arccos(z / r)\n\n return r, theta, phi\n\n\ndef cart2dp(x, y, z):\n '''\n '''\n r = np.sqrt(x**2 + y**2 + z**2)\n alpha = np.arccos((np.sqrt(y**2 + z**2) / r))\n beta = np.arccos((np.sqrt(x**2 + z**2) / r))\n\n return r, alpha, beta\n\n\ndef dp2cart(r, alpha, beta):\n '''\n '''\n z = r * (1 - np.sin(alpha)**2 - np.sin(beta)**2)\n x = r * np.sin(alpha)\n y = r * np.sin(beta)\n\n return x, y, z\n\n\ndef rotation_matrix(vec, angle):\n '''\n '''\n if isinstance(vec, str):\n string = vec.lower()\n if string == 'x':\n vec = [1, 0, 0]\n elif string == '-x':\n vec = [-1, 0, 0]\n elif string == 'y':\n vec = [0, 1, 0]\n elif string == '-y':\n vec = [0, -1, 0]\n elif string == 'z':\n vec = [0, 0, 1]\n elif string == '-x':\n vec = [0, 0, -1]\n\n x, y, z = vec\n a = angle\n\n r = np.zeros((3, 3))\n r[0, 0] = np.cos(a) + x**2 * (1 - np.cos(a))\n r[0, 1] = x * y * (1 - np.cos(a)) - z * np.sin(a)\n r[0, 2] = x * z * (1 - np.cos(a)) + y * np.sin(a)\n r[1, 0] = y * x * (1 - np.cos(a)) + z * np.sin(a)\n r[1, 1] = np.cos(a) + y**2 * (1 - np.cos(a))\n r[1, 2] = y * z * (1 - np.cos(a)) - x * np.sin(a)\n r[2, 0] = z * x * (1 - np.cos(a)) - z * np.sin(a)\n r[2, 1] = z * y * (1 - np.cos(a)) + x * np.sin(a)\n r[2, 2] = np.cos(a) + z**2 * (1 - np.cos(a))\n\n return r\n\n\ndef rotate_nodes(nodes, vec, angle):\n '''\n '''\n rmatrix = rotation_matrix(vec, angle)\n return rmatrix.dot(nodes.T).T\n\n\ndef distance(*args):\n '''\n '''\n return cdist(*np.atleast_2d(*args))\n\n\n''' SIGNAL PROCESSING AND RF DATA FUNCTIONS '''\n\n\ndef gausspulse(fc, fbw, fs):\n '''\n '''\n cutoff = scipy.signal.gausspulse('cutoff', fc=fc, bw=fbw, tpr=-100, bwr=-3)\n adj_cutoff = np.ceil(cutoff * fs) / fs\n\n t = np.arange(-adj_cutoff, adj_cutoff + 1 / fs, 1 / fs)\n pulse, _ = sp.signal.gausspulse(t, fc=fc, bw=fbw, retquad=True, bwr=-3)\n\n return pulse, t\n\n\ndef nextpow2(n):\n '''\n '''\n return 2**int(np.ceil(np.log2(n)))\n\n\ndef envelope(rf_data, N=None, axis=-1):\n '''\n '''\n return np.abs(scipy.signal.hilbert(np.atleast_2d(rf_data), N, axis=axis))\n\n\ndef qbutter(x, fn, fs=1, btype='lowpass', n=4, plot=False, axis=-1):\n '''\n '''\n wn = fn / (fs / 2.)\n b, a = sp.signal.butter(n, wn, btype)\n\n fx = sp.signal.lfilter(b, a, x, axis=axis)\n\n return fx\n\n\ndef qfirwin(x,\n fn,\n fs=1,\n btype='lowpass',\n ntaps=80,\n plot=False,\n axis=-1,\n window='hamming'):\n '''\n '''\n if btype.lower() in ('lowpass', 'low'):\n pass_zero = 1\n elif btype.lower() in ('bandpass', 'band'):\n pass_zero = 0\n elif btype.lower() in ('highpass', 'high'):\n pass_zero = 0\n\n wn = fn / (fs / 2.)\n b = sp.signal.firwin(ntaps, wn, pass_zero=pass_zero, window=window)\n\n fx = np.apply_along_axis(lambda x: np.convolve(x, b), axis, x)\n\n return fx\n\n\ndef qfft(s, nfft=None, fs=1, dr=100, fig=None, **kwargs):\n '''\n Quick FFT plot. Returns frequency bins and FFT in dB.\n '''\n s = np.atleast_2d(s)\n\n nsig, nsample = s.shape\n\n if nfft is None:\n nfft = nsample\n\n # if fig is None:\n # fig = plt.figure(tight_layout=1)\n # ax = fig.add_subplot(111)\n # else:\n # ax = fig.get_axes()[0]\n\n if nfft > nsample:\n s = np.pad(s, ((0, 0), (0, nfft - nsample)), mode='constant')\n elif nfft < nsample:\n s = s[:, :nfft]\n\n ft = sp.fftpack.fft(s, axis=1)\n freqs = sp.fftpack.fftfreq(nfft, 1 / fs)\n\n ftdb = 20 * np.log10(np.abs(ft) / (np.max(np.abs(ft), axis=1)[..., None]))\n ftdb[ftdb < -dr] = -dr\n\n cutoff = (nfft + 1) // 2\n\n # ax.plot(freqs[:cutoff], ftdb[:, :cutoff].T, **kwargs)\n # ax.set_xlabel('Frequency (Hz)')\n # ax.set_ylabel('Magnitude (dB re max)')\n # fig.show()\n\n return freqs[:cutoff], ftdb[:, :cutoff]\n\n\n''' JOB-RELATED FUNCTIONS '''\n\n\ndef chunks(iterable, n):\n\n res = []\n for el in iterable:\n res.append(el)\n if len(res) == n:\n yield res\n res = []\n if res:\n yield res\n\n\ndef create_jobs(*args, mode='zip', is_complete=None):\n '''\n Convenience function for creating jobs (sets of input arguments) for\n multiprocessing Pool. Supports zip and product combinations, and automatic chunking\n of iterables.\n '''\n static_args = list()\n static_idx = list()\n iterable_args = list()\n iterable_idx = list()\n\n for arg_no, arg in enumerate(args):\n if isinstance(arg, (tuple, list)):\n iterable, chunksize = arg\n if chunksize == 1:\n iterable_args.append(iterable)\n else:\n iterable_args.append(chunks(iterable, chunksize))\n iterable_idx.append(arg_no)\n else:\n static_args.append(itertools.repeat(arg))\n static_idx.append(arg_no)\n\n if not iterable_args and not static_args:\n return\n\n if not iterable_args:\n yield 1, tuple(args[i] for i in static_idx)\n\n if not static_args:\n repeats = itertools.repeat(())\n else:\n repeats = zip(*static_args)\n\n if mode.lower() == 'product':\n combos = itertools.product(*iterable_args)\n elif mode.lower() == 'zip':\n combos = zip(*iterable_args)\n elif mode.lower() == 'zip_longest':\n combos = itertools.zip_longest(*iterable_args)\n\n for job_id, (r, p) in enumerate(zip(repeats, combos)):\n # skip jobs that have been completed\n if is_complete is not None and is_complete[job_id]:\n continue\n\n res = r + p\n # reorder vals according to input order\n yield job_id + 1, tuple(res[i] for i in np.argsort(static_idx + iterable_idx))\n\n\n''' DATABASE FUNCTIONS '''\n\n\ndef open_db(f):\n def decorator(firstarg, *args, **kwargs):\n if isinstance(firstarg, sql.Connection):\n return f(firstarg, *args, **kwargs)\n else:\n # if os.path.isfile(firstarg):\n with closing(sql.connect(firstarg)) as con:\n return f(con, *args, **kwargs)\n # else:\n # raise IOError\n\n return decorator\n\n\ndef read_db(f):\n def decorator(firstarg, *args, **kwargs):\n if isinstance(firstarg, sql.Connection):\n return f(firstarg, *args, **kwargs)\n else:\n if os.path.isfile(firstarg):\n with closing(sql.connect(firstarg)) as con:\n return f(con, *args, **kwargs)\n else:\n raise IOError('File does not exist')\n\n return decorator\n\n\n@open_db\ndef table_exists(con, name):\n\n query = '''SELECT count(*) FROM sqlite_master WHERE type='table' and name=?'''\n return con.execute(query, (name, )).fetchone()[0] != 0\n\n\n@open_db\ndef create_metadata_table(con, **kwargs):\n\n table = [[str(v) for v in list(kwargs.values())]]\n columns = list(kwargs.keys())\n pd.DataFrame(table, columns=columns, dtype=str).to_sql('metadata',\n con,\n if_exists='replace',\n index=False)\n\n\n@open_db\ndef create_progress_table(con, njobs):\n\n with con:\n # create table\n con.execute(\n 'CREATE TABLE progress (job_id INTEGER PRIMARY KEY, is_complete boolean)')\n # insert values\n con.executemany('INSERT INTO progress (is_complete) VALUES (?)',\n repeat((False, ), njobs))\n\n\n@open_db\ndef get_progress(con):\n\n table = pd.read_sql('SELECT is_complete FROM progress ORDER BY job_id', con)\n\n is_complete = np.array(table).squeeze()\n ijob = sum(is_complete) + 1\n\n return is_complete, ijob\n\n\n@open_db\ndef update_progress(con, job_id):\n\n with con:\n con.execute('UPDATE progress SET is_complete=1 WHERE job_id=?', [\n job_id,\n ])\n\n\n''' SCRIPTING FUNCTIONS '''\n\n\ndef script_parser(main, config_def):\n '''\n General script command-line interface with 'config' and 'run' subcommands.\n '''\n if isinstance(config_def, dict):\n # create config abstract type based on supplied dict\n Config = abstract.register_type('Config', config_def)\n else:\n # config abstract type already defined\n Config = config_def\n\n # config subcommand generates a default configuration template\n def config(args):\n if args.file:\n abstract.dump(Config(), args.file)\n else:\n print(Config())\n\n # run subcommand will load the config file and pass to main\n def run(args):\n if args.config:\n cfg = Config(**abstract.load(args.config))\n else:\n cfg = Config()\n return main(cfg, args)\n\n # create argument parser\n parser = argparse.ArgumentParser()\n # define config subparser\n subparsers = parser.add_subparsers(help='sub-command help')\n config_parser = subparsers.add_parser('config', help='config_help')\n config_parser.add_argument('-f', '--file', nargs='?')\n config_parser.set_defaults(func=config)\n # define run subparser\n run_parser = subparsers.add_parser('run', help='run_help')\n run_parser.add_argument('config', nargs='?')\n run_parser.add_argument('-f', '--file', nargs='?')\n run_parser.add_argument('-t', '--threads', nargs='?', type=int)\n run_parser.add_argument('-w', '--write-over', action='store_true')\n run_parser.set_defaults(func=run)\n\n return parser, run_parser\n\n\ndef script_parser2(main, config_def):\n '''\n General script command-line interface with 'config' and 'run' subcommands.\n '''\n if isinstance(config_def, dict):\n # create config abstract type based on supplied dict\n Config = abstract.register_type('Config', config_def)\n else:\n # config abstract type already defined\n Config = config_def\n\n # run\n def run(args):\n\n if args.show_config:\n print(Config())\n return\n\n if args.generate_config:\n abstract.dump(Config(), args.generate_config)\n return\n\n if args.file:\n if args.config:\n cfg = Config(**abstract.load(args.config))\n else:\n cfg = Config()\n\n return main(cfg, args)\n\n # create argument parser\n parser = argparse.ArgumentParser()\n parser.add_argument('-g', '--generate-config')\n parser.add_argument('-s', '--show-config', action='store_true')\n parser.add_argument('file', nargs='?')\n parser.add_argument('-c', '--config')\n parser.add_argument('-t', '--threads', type=int)\n parser.add_argument('-w', '--write-over', action='store_true')\n parser.set_defaults(func=run)\n\n return parser\n\n\n''' MISC FUNCTIONS '''\n\n\ndef memoize_old(func):\n '''\n Simple memoizer to cache repeated function calls.\n '''\n def ishashable(obj):\n try:\n hash(obj)\n except TypeError:\n return False\n return True\n\n def make_hashable(obj):\n if not ishashable(obj):\n # use tostring on ndarray since str returns truncated output\n if isinstance(obj, np.ndarray):\n return obj.tostring()\n return str(obj)\n # round float arguments to avoid round-off error affecting cache\n if isinstance(obj, float):\n return round(obj, 18)\n return obj\n\n memo = {}\n\n @functools.wraps(func)\n def decorator(*args, **kwargs):\n # key = tuple(make_hashable(a) for a in args)\n key = (tuple(make_hashable(a) for a in args),\n tuple((k, make_hashable(v)) for k, v in sorted(kwargs.items())))\n if key not in memo:\n memo[key] = func(*args, **kwargs)\n # return a deep copy to avoid issues with mutable return objects\n return deepcopy(memo[key])\n\n return decorator\n\n\ndef memoize(func, maxsize=20):\n '''\n Simple memoizer to cache repeated function calls.\n '''\n def ishashable(obj):\n try:\n hash(obj)\n except TypeError:\n return False\n return True\n\n def make_hashable(obj):\n if hasattr(obj, '_memoize'):\n return obj._memoize()\n if not ishashable(obj):\n # use tostring on ndarray since str returns truncated output\n if isinstance(obj, np.ndarray):\n return obj.tostring()\n return str(obj)\n # round float arguments to avoid round-off error affecting cache\n if isinstance(obj, float):\n return round(obj, 18)\n return obj\n\n func.memo = {}\n\n @functools.wraps(func)\n def decorator(*args, **kwargs):\n # key = tuple(make_hashable(a) for a in args)\n key = (tuple(make_hashable(a) for a in args),\n tuple((k, make_hashable(v)) for k, v in sorted(kwargs.items())))\n if key not in func.memo:\n if len(func.memo) > maxsize:\n return func(*args, **kwargs)\n else:\n func.memo[key] = func(*args, **kwargs)\n # return a deep copy to avoid issues with mutable return objects\n return deepcopy(func.memo[key])\n\n return decorator\n\n\nclass Counter:\n def __init__(self):\n self.count = 0\n\n def increment(self, *args, **kwargs):\n self.count += 1\n\n def decrement(self, *args, **kwargs):\n self.count -= 1\n" ]
[ [ "numpy.argsort", "numpy.meshgrid", "scipy.signal.gausspulse", "scipy.signal.butter", "numpy.arccos", "numpy.cos", "numpy.abs", "numpy.deg2rad", "numpy.atleast_2d", "numpy.ceil", "numpy.zeros", "numpy.arange", "numpy.tan", "numpy.pad", "numpy.array", "numpy.log2", "pandas.read_sql", "numpy.sign", "scipy.signal.firwin", "scipy.fftpack.fft", "numpy.arctan", "pandas.DataFrame", "scipy.signal.lfilter", "scipy.fftpack.fftfreq", "numpy.sqrt", "numpy.sin", "numpy.convolve" ] ]
datanonymous/TFandroid
[ "6aa83398ab03bfae822f36772757097bcb98b6ed", "6aa83398ab03bfae822f36772757097bcb98b6ed" ]
[ "tensorflow/python/kernel_tests/linalg/linear_operator_adjoint_test.py", "tensorflow/python/ops/string_ops.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops.linalg import linalg as linalg_lib\nfrom tensorflow.python.ops.linalg import linear_operator_adjoint\nfrom tensorflow.python.ops.linalg import linear_operator_test_util\nfrom tensorflow.python.platform import test\n\nlinalg = linalg_lib\n\nLinearOperatorAdjoint = linear_operator_adjoint.LinearOperatorAdjoint # pylint: disable=invalid-name\n\n\nclass LinearOperatorAdjointTest(\n linear_operator_test_util.SquareLinearOperatorDerivedClassTest):\n \"\"\"Most tests done in the base class LinearOperatorDerivedClassTest.\"\"\"\n\n def setUp(self):\n self._atol[dtypes.complex64] = 1e-5\n self._rtol[dtypes.complex64] = 1e-5\n\n def _operator_and_matrix(self,\n build_info,\n dtype,\n use_placeholder,\n ensure_self_adjoint_and_pd=False):\n shape = list(build_info.shape)\n\n if ensure_self_adjoint_and_pd:\n matrix = linear_operator_test_util.random_positive_definite_matrix(\n shape, dtype, force_well_conditioned=True)\n else:\n matrix = linear_operator_test_util.random_tril_matrix(\n shape, dtype, force_well_conditioned=True, remove_upper=True)\n\n lin_op_matrix = matrix\n\n if use_placeholder:\n lin_op_matrix = array_ops.placeholder_with_default(matrix, shape=None)\n\n if ensure_self_adjoint_and_pd:\n operator = LinearOperatorAdjoint(\n linalg.LinearOperatorFullMatrix(\n lin_op_matrix, is_positive_definite=True, is_self_adjoint=True))\n else:\n operator = LinearOperatorAdjoint(\n linalg.LinearOperatorLowerTriangular(lin_op_matrix))\n\n return operator, linalg.adjoint(matrix)\n\n def test_base_operator_hint_used(self):\n # The matrix values do not effect auto-setting of the flags.\n matrix = [[1., 0.], [1., 1.]]\n operator = linalg.LinearOperatorFullMatrix(\n matrix,\n is_positive_definite=True,\n is_non_singular=True,\n is_self_adjoint=False)\n operator_adjoint = LinearOperatorAdjoint(operator)\n self.assertTrue(operator_adjoint.is_positive_definite)\n self.assertTrue(operator_adjoint.is_non_singular)\n self.assertFalse(operator_adjoint.is_self_adjoint)\n\n def test_supplied_hint_used(self):\n # The matrix values do not effect auto-setting of the flags.\n matrix = [[1., 0.], [1., 1.]]\n operator = linalg.LinearOperatorFullMatrix(matrix)\n operator_adjoint = LinearOperatorAdjoint(\n operator,\n is_positive_definite=True,\n is_non_singular=True,\n is_self_adjoint=False)\n self.assertTrue(operator_adjoint.is_positive_definite)\n self.assertTrue(operator_adjoint.is_non_singular)\n self.assertFalse(operator_adjoint.is_self_adjoint)\n\n def test_contradicting_hints_raise(self):\n # The matrix values do not effect auto-setting of the flags.\n matrix = [[1., 0.], [1., 1.]]\n operator = linalg.LinearOperatorFullMatrix(\n matrix, is_positive_definite=False)\n with self.assertRaisesRegexp(ValueError, \"positive-definite\"):\n LinearOperatorAdjoint(operator, is_positive_definite=True)\n\n operator = linalg.LinearOperatorFullMatrix(matrix, is_self_adjoint=False)\n with self.assertRaisesRegexp(ValueError, \"self-adjoint\"):\n LinearOperatorAdjoint(operator, is_self_adjoint=True)\n\n def test_name(self):\n matrix = [[11., 0.], [1., 8.]]\n operator = linalg.LinearOperatorFullMatrix(\n matrix, name=\"my_operator\", is_non_singular=True)\n\n operator = LinearOperatorAdjoint(operator)\n\n self.assertEqual(\"my_operator_adjoint\", operator.name)\n\n\nclass LinearOperatorAdjointNonSquareTest(\n linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest):\n \"\"\"Tests done in the base class NonSquareLinearOperatorDerivedClassTest.\"\"\"\n\n def _operator_and_matrix(self, build_info, dtype, use_placeholder):\n shape_before_adjoint = list(build_info.shape)\n # We need to swap the last two dimensions because we are taking the adjoint\n # of this operator\n shape_before_adjoint[-1], shape_before_adjoint[-2] = (\n shape_before_adjoint[-2], shape_before_adjoint[-1])\n matrix = linear_operator_test_util.random_normal(\n shape_before_adjoint, dtype=dtype)\n\n lin_op_matrix = matrix\n\n if use_placeholder:\n lin_op_matrix = array_ops.placeholder_with_default(matrix, shape=None)\n\n operator = LinearOperatorAdjoint(\n linalg.LinearOperatorFullMatrix(lin_op_matrix))\n\n return operator, linalg.adjoint(matrix)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Operations for working with string Tensors.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_parsing_ops\nfrom tensorflow.python.ops import gen_string_ops\nfrom tensorflow.python.ops import math_ops\n\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\n# pylint: disable=g-bad-import-order\nfrom tensorflow.python.ops.gen_string_ops import *\nfrom tensorflow.python.util import compat as util_compat\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import dispatch\nfrom tensorflow.python.util.tf_export import tf_export\n# pylint: enable=g-bad-import-order\n# pylint: enable=wildcard-import\n\n\n# pylint: disable=redefined-builtin\n@tf_export(\"strings.regex_full_match\")\[email protected]_dispatch_support\ndef regex_full_match(input, pattern, name=None):\n r\"\"\"Match elements of `input` with regex `pattern`.\n\n Args:\n input: string `Tensor`, the source strings to process.\n pattern: string or scalar string `Tensor`, regular expression to use,\n see more details at https://github.com/google/re2/wiki/Syntax\n name: Name of the op.\n\n Returns:\n bool `Tensor` of the same shape as `input` with match results.\n \"\"\"\n # TODO(b/112455102): Remove compat.forward_compatible once past the horizon.\n if not compat.forward_compatible(2018, 11, 10):\n return gen_string_ops.regex_full_match(\n input=input, pattern=pattern, name=name)\n if isinstance(pattern, util_compat.bytes_or_text_types):\n # When `pattern` is static through the life of the op we can\n # use a version which performs the expensive regex compilation once at\n # creation time.\n return gen_string_ops.static_regex_full_match(\n input=input, pattern=pattern, name=name)\n return gen_string_ops.regex_full_match(\n input=input, pattern=pattern, name=name)\n\nregex_full_match.__doc__ = gen_string_ops.regex_full_match.__doc__\n\n\n@tf_export(\n \"strings.regex_replace\", v1=[\"strings.regex_replace\", \"regex_replace\"])\[email protected]_endpoints(\"regex_replace\")\[email protected]_dispatch_support\ndef regex_replace(input, pattern, rewrite, replace_global=True, name=None):\n r\"\"\"Replace elements of `input` matching regex `pattern` with `rewrite`.\n\n Args:\n input: string `Tensor`, the source strings to process.\n pattern: string or scalar string `Tensor`, regular expression to use,\n see more details at https://github.com/google/re2/wiki/Syntax\n rewrite: string or scalar string `Tensor`, value to use in match\n replacement, supports backslash-escaped digits (\\1 to \\9) can be to insert\n text matching corresponding parenthesized group.\n replace_global: `bool`, if `True` replace all non-overlapping matches,\n else replace only the first match.\n name: A name for the operation (optional).\n\n Returns:\n string `Tensor` of the same shape as `input` with specified replacements.\n \"\"\"\n if (isinstance(pattern, util_compat.bytes_or_text_types) and\n isinstance(rewrite, util_compat.bytes_or_text_types)):\n # When `pattern` and `rewrite` are static through the life of the op we can\n # use a version which performs the expensive regex compilation once at\n # creation time.\n return gen_string_ops.static_regex_replace(\n input=input, pattern=pattern,\n rewrite=rewrite, replace_global=replace_global,\n name=name)\n return gen_string_ops.regex_replace(\n input=input, pattern=pattern,\n rewrite=rewrite, replace_global=replace_global,\n name=name)\n\n\n@tf_export(\"strings.format\")\ndef string_format(template, inputs, placeholder=\"{}\", summarize=3, name=None):\n r\"\"\"Formats a string template using a list of tensors.\n\n Formats a string template using a list of tensors, abbreviating tensors by\n only printing the first and last `summarize` elements of each dimension\n (recursively). If formatting only one tensor into a template, the tensor does\n not have to be wrapped in a list.\n\n Example:\n Formatting a single-tensor template:\n ```python\n sess = tf.Session()\n with sess.as_default():\n tensor = tf.range(10)\n formatted = tf.strings.format(\"tensor: {}, suffix\", tensor)\n out = sess.run(formatted)\n expected = \"tensor: [0 1 2 ... 7 8 9], suffix\"\n\n assert(out.decode() == expected)\n ```\n\n Formatting a multi-tensor template:\n ```python\n sess = tf.Session()\n with sess.as_default():\n tensor_one = tf.reshape(tf.range(100), [10, 10])\n tensor_two = tf.range(10)\n formatted = tf.strings.format(\"first: {}, second: {}, suffix\",\n (tensor_one, tensor_two))\n\n out = sess.run(formatted)\n expected = (\"first: [[0 1 2 ... 7 8 9]\\n\"\n \" [10 11 12 ... 17 18 19]\\n\"\n \" [20 21 22 ... 27 28 29]\\n\"\n \" ...\\n\"\n \" [70 71 72 ... 77 78 79]\\n\"\n \" [80 81 82 ... 87 88 89]\\n\"\n \" [90 91 92 ... 97 98 99]], second: [0 1 2 ... 7 8 9], suffix\")\n\n assert(out.decode() == expected)\n ```\n\n Args:\n template: A string template to format tensor values into.\n inputs: A list of `Tensor` objects, or a single Tensor.\n The list of tensors to format into the template string. If a solitary\n tensor is passed in, the input tensor will automatically be wrapped as a\n list.\n placeholder: An optional `string`. Defaults to `{}`.\n At each placeholder occurring in the template, a subsequent tensor\n will be inserted.\n summarize: An optional `int`. Defaults to `3`.\n When formatting the tensors, show the first and last `summarize`\n entries of each tensor dimension (recursively). If set to -1, all\n elements of the tensor will be shown.\n name: A name for the operation (optional).\n\n Returns:\n A scalar `Tensor` of type `string`.\n\n Raises:\n ValueError: if the number of placeholders does not match the number of\n inputs.\n \"\"\"\n # If there is only one tensor to format, we will automatically wrap it in a\n # list to simplify the user experience\n if tensor_util.is_tensor(inputs):\n inputs = [inputs]\n if template.count(placeholder) != len(inputs):\n raise ValueError(\"%s placeholder(s) in template does not match %s tensor(s)\"\n \" provided as input\" % (template.count(placeholder),\n len(inputs)))\n\n return gen_string_ops.string_format(inputs,\n template=template,\n placeholder=placeholder,\n summarize=summarize,\n name=name)\n\n\n@tf_export(\"string_split\")\ndef string_split(source, delimiter=\" \", skip_empty=True): # pylint: disable=invalid-name\n \"\"\"Split elements of `source` based on `delimiter` into a `SparseTensor`.\n\n Let N be the size of source (typically N will be the batch size). Split each\n element of `source` based on `delimiter` and return a `SparseTensor`\n containing the split tokens. Empty tokens are ignored.\n\n If `delimiter` is an empty string, each element of the `source` is split\n into individual strings, each containing one byte. (This includes splitting\n multibyte sequences of UTF-8.) If delimiter contains multiple bytes, it is\n treated as a set of delimiters with each considered a potential split point.\n\n For example:\n N = 2, source[0] is 'hello world' and source[1] is 'a b c', then the output\n will be\n\n st.indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\n st.shape = [2, 3]\n st.values = ['hello', 'world', 'a', 'b', 'c']\n\n Args:\n source: `1-D` string `Tensor`, the strings to split.\n delimiter: `0-D` string `Tensor`, the delimiter character, the string should\n be length 0 or 1.\n skip_empty: A `bool`. If `True`, skip the empty strings from the result.\n\n Raises:\n ValueError: If delimiter is not a string.\n\n Returns:\n A `SparseTensor` of rank `2`, the strings split according to the delimiter.\n The first column of the indices corresponds to the row in `source` and the\n second column corresponds to the index of the split component in this row.\n \"\"\"\n delimiter = ops.convert_to_tensor(delimiter, dtype=dtypes.string)\n source = ops.convert_to_tensor(source, dtype=dtypes.string)\n\n indices, values, shape = gen_string_ops.string_split(\n source, delimiter=delimiter, skip_empty=skip_empty)\n indices.set_shape([None, 2])\n values.set_shape([None])\n shape.set_shape([2])\n return sparse_tensor.SparseTensor(indices, values, shape)\n\n\n@tf_export(\"strings.split\")\ndef string_split_v2(source, sep=None, maxsplit=-1):\n \"\"\"Split elements of `source` based on `sep` into a `SparseTensor`.\n\n Let N be the size of source (typically N will be the batch size). Split each\n element of `source` based on `sep` and return a `SparseTensor`\n containing the split tokens. Empty tokens are ignored.\n\n For example, N = 2, source[0] is 'hello world' and source[1] is 'a b c',\n then the output will be\n\n st.indices = [0, 0;\n 0, 1;\n 1, 0;\n 1, 1;\n 1, 2]\n st.shape = [2, 3]\n st.values = ['hello', 'world', 'a', 'b', 'c']\n\n If `sep` is given, consecutive delimiters are not grouped together and are\n deemed to delimit empty strings. For example, source of `\"1<>2<><>3\"` and\n sep of `\"<>\"` returns `[\"1\", \"2\", \"\", \"3\"]`. If `sep` is None or an empty\n string, consecutive whitespace are regarded as a single separator, and the\n result will contain no empty strings at the startor end if the string has\n leading or trailing whitespace.\n\n Note that the above mentioned behavior matches python's str.split.\n\n Args:\n source: `1-D` string `Tensor`, the strings to split.\n sep: `0-D` string `Tensor`, the delimiter character.\n maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result.\n\n Raises:\n ValueError: If sep is not a string.\n\n Returns:\n A `SparseTensor` of rank `2`, the strings split according to the delimiter.\n The first column of the indices corresponds to the row in `source` and the\n second column corresponds to the index of the split component in this row.\n \"\"\"\n if sep is None:\n sep = \"\"\n sep = ops.convert_to_tensor(sep, dtype=dtypes.string)\n source = ops.convert_to_tensor(source, dtype=dtypes.string)\n\n indices, values, shape = gen_string_ops.string_split_v2(\n source, sep=sep, maxsplit=maxsplit)\n indices.set_shape([None, 2])\n values.set_shape([None])\n shape.set_shape([2])\n return sparse_tensor.SparseTensor(indices, values, shape)\n\n\ndef _reduce_join_reduction_dims(x, axis, reduction_indices):\n \"\"\"Returns range(rank(x) - 1, 0, -1) if reduction_indices is None.\"\"\"\n # TODO(aselle): Remove this after deprecation\n if reduction_indices is not None:\n if axis is not None:\n raise ValueError(\"Can't specify both 'axis' and 'reduction_indices'.\")\n axis = reduction_indices\n if axis is not None:\n return axis\n else:\n # Fast path: avoid creating Rank and Range ops if ndims is known.\n if x.get_shape().ndims is not None:\n return constant_op.constant(\n np.arange(x.get_shape().ndims - 1, -1, -1), dtype=dtypes.int32)\n\n # Otherwise, we rely on Range and Rank to do the right thing at run-time.\n return math_ops.range(array_ops.rank(x) - 1, -1, -1)\n\n\n@tf_export(v1=[\"strings.reduce_join\", \"reduce_join\"])\[email protected]_endpoints(\"reduce_join\")\ndef reduce_join(inputs, axis=None, # pylint: disable=missing-docstring\n keep_dims=False,\n separator=\"\",\n name=None,\n reduction_indices=None,\n keepdims=None):\n keep_dims = deprecation.deprecated_argument_lookup(\n \"keepdims\", keepdims, \"keep_dims\", keep_dims)\n inputs_t = ops.convert_to_tensor(inputs)\n reduction_indices = _reduce_join_reduction_dims(\n inputs_t, axis, reduction_indices)\n return gen_string_ops.reduce_join(\n inputs=inputs_t,\n reduction_indices=reduction_indices,\n keep_dims=keep_dims,\n separator=separator,\n name=name)\n\n\n@tf_export(\"strings.reduce_join\", v1=[])\ndef reduce_join_v2( # pylint: disable=missing-docstring\n inputs,\n axis=None,\n keepdims=False,\n separator=\"\",\n name=None):\n return reduce_join(\n inputs, axis, keep_dims=keepdims, separator=separator, name=name)\n\n\nreduce_join.__doc__ = deprecation.rewrite_argument_docstring(\n gen_string_ops.reduce_join.__doc__, \"reduction_indices\", \"axis\")\nreduce_join.__doc__ = reduce_join.__doc__.replace(\"tf.reduce_join(\",\n \"tf.strings.reduce_join(\")\n\n\n# This wrapper provides backwards compatibility for code that predates the\n# unit argument and that passed 'name' as a positional argument.\n@tf_export(v1=[\"strings.length\"])\[email protected]_dispatch_support\ndef string_length(input, name=None, unit=\"BYTE\"):\n return gen_string_ops.string_length(input, unit=unit, name=name)\n\n\n@tf_export(\"strings.length\", v1=[])\[email protected]_dispatch_support\ndef string_length_v2(input, unit=\"BYTE\", name=None):\n return string_length(input, name, unit)\n\n\nstring_length.__doc__ = gen_string_ops.string_length.__doc__\n\n\n@tf_export(v1=[\"substr\"])\[email protected](None, \"Use `tf.strings.substr` instead of `tf.substr`.\")\ndef substr_deprecated(input, pos, len, name=None, unit=\"BYTE\"):\n return substr(input, pos, len, name=name, unit=unit)\n\nsubstr_deprecated.__doc__ = gen_string_ops.substr.__doc__\n\n\n@tf_export(v1=[\"strings.substr\"])\[email protected]_dispatch_support\ndef substr(input, pos, len, name=None, unit=\"BYTE\"):\n return gen_string_ops.substr(input, pos, len, unit=unit, name=name)\n\nsubstr.__doc__ = gen_string_ops.substr.__doc__\n\n\n@tf_export(\"strings.substr\", v1=[])\[email protected]_dispatch_support\ndef substr_v2(input, pos, len, unit=\"BYTE\", name=None):\n return gen_string_ops.substr(input, pos, len, unit=unit, name=name)\n\nsubstr_v2.__doc__ = gen_string_ops.substr.__doc__\n\n\nops.NotDifferentiable(\"RegexReplace\")\nops.NotDifferentiable(\"StringToHashBucket\")\nops.NotDifferentiable(\"StringToHashBucketFast\")\nops.NotDifferentiable(\"StringToHashBucketStrong\")\nops.NotDifferentiable(\"ReduceJoin\")\nops.NotDifferentiable(\"StringJoin\")\nops.NotDifferentiable(\"StringSplit\")\nops.NotDifferentiable(\"AsString\")\nops.NotDifferentiable(\"EncodeBase64\")\nops.NotDifferentiable(\"DecodeBase64\")\n\n\n@tf_export(\"strings.to_number\", v1=[])\[email protected]_dispatch_support\ndef string_to_number(input, out_type=dtypes.float32, name=None):\n r\"\"\"Converts each string in the input Tensor to the specified numeric type.\n\n (Note that int32 overflow results in an error while float overflow\n results in a rounded value.)\n\n Args:\n input: A `Tensor` of type `string`.\n out_type: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32,\n tf.int64`. Defaults to `tf.float32`.\n The numeric type to interpret each string in `string_tensor` as.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `out_type`.\n \"\"\"\n return gen_parsing_ops.string_to_number(input, out_type, name)\n\n\n@tf_export(v1=[\"strings.to_number\", \"string_to_number\"])\ndef string_to_number_v1(\n string_tensor=None,\n out_type=dtypes.float32,\n name=None,\n input=None):\n string_tensor = deprecation.deprecated_argument_lookup(\n \"input\", input, \"string_tensor\", string_tensor)\n return gen_parsing_ops.string_to_number(string_tensor, out_type, name)\n\nstring_to_number_v1.__doc__ = gen_parsing_ops.string_to_number.__doc__\n\n\n@tf_export(\"strings.to_hash_bucket\", v1=[])\[email protected]_dispatch_support\ndef string_to_hash_bucket(input, num_buckets, name=None):\n # pylint: disable=line-too-long\n r\"\"\"Converts each string in the input Tensor to its hash mod by a number of buckets.\n\n The hash function is deterministic on the content of the string within the\n process.\n\n Note that the hash function may change from time to time.\n This functionality will be deprecated and it's recommended to use\n `tf.string_to_hash_bucket_fast()` or `tf.string_to_hash_bucket_strong()`.\n\n Args:\n input: A `Tensor` of type `string`.\n num_buckets: An `int` that is `>= 1`. The number of buckets.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `int64`.\n \"\"\"\n # pylint: enable=line-too-long\n return gen_string_ops.string_to_hash_bucket(input, num_buckets, name)\n\n\n@tf_export(v1=[\"strings.to_hash_bucket\", \"string_to_hash_bucket\"])\ndef string_to_hash_bucket_v1(\n string_tensor=None,\n num_buckets=None,\n name=None,\n input=None):\n string_tensor = deprecation.deprecated_argument_lookup(\n \"input\", input, \"string_tensor\", string_tensor)\n return gen_string_ops.string_to_hash_bucket(string_tensor, num_buckets, name)\n\nstring_to_hash_bucket_v1.__doc__ = gen_string_ops.string_to_hash_bucket.__doc__\n" ]
[ [ "tensorflow.python.ops.linalg.linear_operator_test_util.random_normal", "tensorflow.python.ops.linalg.linear_operator_test_util.random_positive_definite_matrix", "tensorflow.python.ops.array_ops.placeholder_with_default", "tensorflow.python.platform.test.main", "tensorflow.python.ops.linalg.linear_operator_test_util.random_tril_matrix" ], [ "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.util.deprecation.deprecated_argument_lookup", "tensorflow.python.util.deprecation.deprecated_endpoints", "tensorflow.python.ops.gen_string_ops.regex_replace", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.gen_string_ops.regex_full_match", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.gen_parsing_ops.string_to_number", "tensorflow.python.ops.gen_string_ops.static_regex_full_match", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.compat.compat.forward_compatible", "tensorflow.python.ops.gen_string_ops.string_length", "tensorflow.python.ops.gen_string_ops.reduce_join", "tensorflow.python.ops.gen_string_ops.string_format", "tensorflow.python.ops.gen_string_ops.string_split", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.gen_string_ops.string_split_v2", "tensorflow.python.ops.gen_string_ops.substr", "tensorflow.python.ops.gen_string_ops.string_to_hash_bucket", "tensorflow.python.util.deprecation.rewrite_argument_docstring", "tensorflow.python.framework.ops.NotDifferentiable", "tensorflow.python.ops.gen_string_ops.static_regex_replace", "tensorflow.python.framework.tensor_util.is_tensor" ] ]
DanielOrtega94/pytorch-lightning
[ "34e11fab167a7beb78fbe6991ff8721dc9208793" ]
[ "pytorch_lightning/callbacks/model_checkpoint.py" ]
[ "\"\"\"\nModel Checkpointing\n===================\n\nAutomatically save model checkpoints during training.\n\n\"\"\"\n\nimport os\nimport re\n\nimport numpy as np\nfrom typing import Optional\n\nimport torch\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.callbacks.base import Callback\nfrom pytorch_lightning.utilities import rank_zero_warn, rank_zero_only\n\n\nclass ModelCheckpoint(Callback):\n r\"\"\"\n Save the model after every epoch if it improves.\n\n After training finishes, use :attr:`best_model_path` to retrieve the path to the\n best checkpoint file and :attr:`best_model_score` to retrieve its score.\n\n Args:\n filepath: path to save the model file.\n Can contain named formatting options to be auto-filled.\n\n Example::\n\n # custom path\n # saves a file like: my/path/epoch_0.ckpt\n >>> checkpoint_callback = ModelCheckpoint('my/path/')\n\n # save any arbitrary metrics like `val_loss`, etc. in name\n # saves a file like: my/path/epoch=2-val_loss=0.2_other_metric=0.3.ckpt\n >>> checkpoint_callback = ModelCheckpoint(\n ... filepath='my/path/{epoch}-{val_loss:.2f}-{other_metric:.2f}'\n ... )\n\n Can also be set to `None`, then it will be set to default location\n during trainer construction.\n\n monitor: quantity to monitor.\n verbose: verbosity mode. Default: ``False``.\n save_last: always saves the model at the end of the epoch. Default: ``False``.\n save_top_k: if `save_top_k == k`,\n the best k models according to\n the quantity monitored will be saved.\n if ``save_top_k == 0``, no models are saved.\n if ``save_top_k == -1``, all models are saved.\n Please note that the monitors are checked every `period` epochs.\n if ``save_top_k >= 2`` and the callback is called multiple\n times inside an epoch, the name of the saved file will be\n appended with a version count starting with `v0`.\n mode: one of {auto, min, max}.\n If ``save_top_k != 0``, the decision\n to overwrite the current save file is made\n based on either the maximization or the\n minimization of the monitored quantity. For `val_acc`,\n this should be `max`, for `val_loss` this should\n be `min`, etc. In `auto` mode, the direction is\n automatically inferred from the name of the monitored quantity.\n save_weights_only: if ``True``, then only the model's weights will be\n saved (``model.save_weights(filepath)``), else the full model\n is saved (``model.save(filepath)``).\n period: Interval (number of epochs) between checkpoints.\n\n Example::\n\n >>> from pytorch_lightning import Trainer\n >>> from pytorch_lightning.callbacks import ModelCheckpoint\n\n # saves checkpoints to 'my/path/' whenever 'val_loss' has a new min\n >>> checkpoint_callback = ModelCheckpoint(filepath='my/path/')\n >>> trainer = Trainer(checkpoint_callback=checkpoint_callback)\n\n # save epoch and val_loss in name\n # saves a file like: my/path/sample-mnist_epoch=02_val_loss=0.32.ckpt\n >>> checkpoint_callback = ModelCheckpoint(\n ... filepath='my/path/sample-mnist_{epoch:02d}-{val_loss:.2f}'\n ... )\n\n # retrieve the best checkpoint after training\n checkpoint_callback = ModelCheckpoint(filepath='my/path/')\n trainer = Trainer(checkpoint_callback=checkpoint_callback)\n model = ...\n trainer.fit(model)\n checkpoint_callback.best_model_path\n\n \"\"\"\n\n def __init__(self, filepath: Optional[str] = None, monitor: str = 'val_loss', verbose: bool = False,\n save_last: bool = False, save_top_k: int = 1, save_weights_only: bool = False,\n mode: str = 'auto', period: int = 1, prefix: str = ''):\n super().__init__()\n if save_top_k > 0 and filepath is not None and os.path.isdir(filepath) and len(os.listdir(filepath)) > 0:\n rank_zero_warn(\n f\"Checkpoint directory {filepath} exists and is not empty with save_top_k != 0.\"\n \"All files in this directory will be deleted when a checkpoint is saved!\"\n )\n self._rank = 0\n\n self.monitor = monitor\n self.verbose = verbose\n if filepath is None: # will be determined by trainer at runtime\n self.dirpath, self.filename = None, None\n else:\n if os.path.isdir(filepath):\n self.dirpath, self.filename = filepath, '{epoch}'\n else:\n filepath = os.path.realpath(filepath)\n self.dirpath, self.filename = os.path.split(filepath)\n os.makedirs(self.dirpath, exist_ok=True)\n self.save_last = save_last\n self.save_top_k = save_top_k\n self.save_weights_only = save_weights_only\n self.period = period\n self.epoch_last_check = None\n self.prefix = prefix\n self.best_k_models = {}\n # {filename: monitor}\n self.kth_best_model_path = ''\n self.best_model_score = 0\n self.best_model_path = ''\n self.save_function = None\n\n torch_inf = torch.tensor(np.Inf)\n mode_dict = {\n 'min': (torch_inf, 'min'),\n 'max': (-torch_inf, 'max'),\n 'auto': (-torch_inf, 'max') if 'acc' in self.monitor or self.monitor.startswith('fmeasure')\n else (torch_inf, 'min'),\n }\n\n if mode not in mode_dict:\n rank_zero_warn(f'ModelCheckpoint mode {mode} is unknown, '\n f'fallback to auto mode.', RuntimeWarning)\n mode = 'auto'\n\n self.kth_value, self.mode = mode_dict[mode]\n\n @property\n def best(self):\n rank_zero_warn(\"Attribute `best` has been renamed to `best_model_score` since v0.8.0\"\n \" and will be removed in v0.10.0\", DeprecationWarning)\n return self.best_model_score\n\n @property\n def kth_best_model(self):\n rank_zero_warn(\"Attribute `kth_best_model` has been renamed to `kth_best_model_path` since v0.8.0\"\n \" and will be removed in v0.10.0\", DeprecationWarning)\n return self.kth_best_model_path\n\n def _del_model(self, filepath):\n if os.path.isfile(filepath):\n os.remove(filepath)\n\n def _save_model(self, filepath):\n # make paths\n os.makedirs(os.path.dirname(filepath), exist_ok=True)\n\n # delegate the saving to the model\n if self.save_function is not None:\n self.save_function(filepath, self.save_weights_only)\n else:\n raise ValueError(\".save_function() not set\")\n\n def check_monitor_top_k(self, current):\n less_than_k_models = len(self.best_k_models) < self.save_top_k\n if less_than_k_models:\n return True\n\n if not isinstance(current, torch.Tensor):\n rank_zero_warn(\n f'{current} is supposed to be a `torch.Tensor`. Saving checkpoint may not work correctly.'\n f' HINT: check the value of {self.monitor} in your validation loop', RuntimeWarning\n )\n current = torch.tensor(current)\n\n monitor_op = {\n \"min\": torch.lt,\n \"max\": torch.gt,\n }[self.mode]\n\n return monitor_op(current, self.best_k_models[self.kth_best_model_path])\n\n def format_checkpoint_name(self, epoch, metrics, ver=None):\n \"\"\"Generate a filename according to the defined template.\n\n Example::\n\n >>> tmpdir = os.path.dirname(__file__)\n >>> ckpt = ModelCheckpoint(os.path.join(tmpdir, '{epoch}'))\n >>> os.path.basename(ckpt.format_checkpoint_name(0, {}))\n 'epoch=0.ckpt'\n >>> ckpt = ModelCheckpoint(os.path.join(tmpdir, '{epoch:03d}'))\n >>> os.path.basename(ckpt.format_checkpoint_name(5, {}))\n 'epoch=005.ckpt'\n >>> ckpt = ModelCheckpoint(os.path.join(tmpdir, '{epoch}-{val_loss:.2f}'))\n >>> os.path.basename(ckpt.format_checkpoint_name(2, dict(val_loss=0.123456)))\n 'epoch=2-val_loss=0.12.ckpt'\n >>> ckpt = ModelCheckpoint(os.path.join(tmpdir, '{missing:d}'))\n >>> os.path.basename(ckpt.format_checkpoint_name(0, {}))\n 'missing=0.ckpt'\n \"\"\"\n # check if user passed in keys to the string\n groups = re.findall(r'(\\{.*?)[:\\}]', self.filename)\n\n if len(groups) == 0:\n # default name\n filename = f'{self.prefix}_ckpt_epoch_{epoch}'\n else:\n metrics['epoch'] = epoch\n filename = self.filename\n for tmp in groups:\n name = tmp[1:]\n filename = filename.replace(tmp, name + '={' + name)\n if name not in metrics:\n metrics[name] = 0\n filename = filename.format(**metrics)\n str_ver = f'_v{ver}' if ver is not None else ''\n filepath = os.path.join(self.dirpath, self.prefix + filename + str_ver + '.ckpt')\n return filepath\n\n @rank_zero_only\n def on_train_start(self, trainer, pl_module):\n \"\"\"\n Determine model checkpoint save directory at runtime. References attributes from the\n Trainer's logger to determine where to save checkpoints.\n \"\"\"\n if self.dirpath is not None:\n return # short circuit\n\n self.filename = '{epoch}'\n\n if trainer.logger is not None:\n # weights_save_path overrides anything\n save_dir = (getattr(trainer, 'weights_save_path', None)\n or getattr(trainer.logger, 'save_dir', None)\n or trainer.default_root_dir)\n\n version = trainer.logger.version if isinstance(\n trainer.logger.version, str) else f'version_{trainer.logger.version}'\n ckpt_path = os.path.join(\n save_dir,\n trainer.logger.name,\n version,\n \"checkpoints\"\n )\n else:\n ckpt_path = os.path.join(trainer.default_root_dir, \"checkpoints\")\n\n self.dirpath = ckpt_path\n\n assert trainer.global_rank == 0, 'tried to make a checkpoint from non global_rank=0'\n\n os.makedirs(self.dirpath, exist_ok=True)\n trainer.ckpt_path = ckpt_path\n trainer.weights_save_path = ckpt_path\n\n @rank_zero_only\n def on_validation_end(self, trainer, pl_module):\n # only run on main process\n if trainer.global_rank != 0:\n return\n\n metrics = trainer.callback_metrics\n epoch = trainer.current_epoch\n if self.save_top_k == 0:\n # no models are saved\n return\n if self.epoch_last_check is not None and (epoch - self.epoch_last_check) < self.period:\n # skipping in this term\n return\n\n self.epoch_last_check = epoch\n\n if self.save_last:\n filepath = os.path.join(self.dirpath, self.prefix + 'last.ckpt')\n self._save_model(filepath)\n\n filepath = self.format_checkpoint_name(epoch, metrics)\n version_cnt = 0\n while os.path.isfile(filepath):\n filepath = self.format_checkpoint_name(epoch, metrics, ver=version_cnt)\n # this epoch called before\n version_cnt += 1\n\n if self.save_top_k != -1:\n current = metrics.get(self.monitor)\n\n if not isinstance(current, torch.Tensor):\n rank_zero_warn(\n f'The metric you returned {current} must be a `torch.Tensor` instance, checkpoint not saved'\n f' HINT: what is the value of {self.monitor} in validation_epoch_end()?', RuntimeWarning\n )\n if current is not None:\n current = torch.tensor(current)\n\n if current is None:\n rank_zero_warn(\n f'Can save best model only with {self.monitor} available, skipping.', RuntimeWarning\n )\n elif self.check_monitor_top_k(current):\n self._do_check_save(filepath, current, epoch)\n elif self.verbose > 0:\n log.info(f'\\nEpoch {epoch:05d}: {self.monitor} was not in top {self.save_top_k}')\n\n else:\n if self.verbose > 0:\n log.info(f'\\nEpoch {epoch:05d}: saving model to {filepath}')\n\n assert trainer.global_rank == 0, 'tried to make a checkpoint from non global_rank=0'\n self._save_model(filepath)\n\n def _do_check_save(self, filepath, current, epoch):\n # remove kth\n\n del_list = []\n if len(self.best_k_models) == self.save_top_k and self.save_top_k > 0:\n delpath = self.kth_best_model_path\n self.best_k_models.pop(self.kth_best_model_path)\n del_list.append(delpath)\n\n self.best_k_models[filepath] = current\n if len(self.best_k_models) == self.save_top_k:\n # monitor dict has reached k elements\n _op = max if self.mode == 'min' else min\n self.kth_best_model_path = _op(self.best_k_models,\n key=self.best_k_models.get)\n self.kth_value = self.best_k_models[self.kth_best_model_path]\n\n _op = min if self.mode == 'min' else max\n self.best_model_path = _op(self.best_k_models, key=self.best_k_models.get)\n self.best_model_score = self.best_k_models[self.best_model_path]\n\n if self.verbose > 0:\n log.info(\n f'\\nEpoch {epoch:05d}: {self.monitor} reached'\n f' {current:0.5f} (best {self.best_model_score:0.5f}), saving model to'\n f' {filepath} as top {self.save_top_k}')\n self._save_model(filepath)\n\n for cur_path in del_list:\n if cur_path != filepath:\n self._del_model(cur_path)\n" ]
[ [ "torch.tensor" ] ]
sitek/subcortical-auditory-atlas
[ "8218140c457ab97a6d897eb26aae4d6240596033" ]
[ "code/invivo/diffusion/02_analysis/dipy_atlas_target.py" ]
[ "'''\nAfter creating tractography streamlines with dipy_csd.py,\nthis workflow takes an atlas file and finds connections\nbetween each region in the atlas\nKRS 2018.05.04\n'''\nfrom nipype import config\nconfig.set('execution', 'remove_unnecessary_outputs', 'false')\nconfig.set('execution', 'crashfile_format', 'txt')\n\nfrom nipype import Node, Function, Workflow, IdentityInterface, MapNode\nfrom nipype.interfaces.io import SelectFiles, DataSink\n\nimport os\nfrom glob import glob\n\n# which data sampling? also used for naming\nout_prefix = 'dipy_csd'\natlas_type = 'func-atlas_shift_vox-4_ax-1'\n\nproj_dir = os.path.abspath('/om2/user/ksitek/maastricht/diffusion_faruk/')\ndata_dir = os.path.join(proj_dir, 'data/01_diff_preprocessed')\nout_base = os.path.join(proj_dir, 'analysis/')\nout_dir = os.path.join(out_base, '%s_%s/'%(out_prefix, atlas_type))\nif not os.path.exists(out_dir):\n os.mkdir(out_dir)\n\nwork_dir = os.path.abspath('/om2/scratch/ksitek/%s_%s_0114/'%(out_prefix, atlas_type))\n\n#sids = ['S02']\nsids = ['S%02d' %s for s in range(1,12)]\n\nroi_names = ['LH_CN', 'LH_SOC', 'LH_IC', 'LH_MGB',\n 'RH_CN', 'RH_SOC', 'RH_IC', 'RH_MGB']\nrois = list(range(len(roi_names)))\n\n'''\nroi_dir = os.path.join(proj_dir, 'analysis/roi_diff/')\nsubj_rois = {}\nfor subj in sids:\n subj_rois[subj] = sorted(glob('%s/%s/%s_roi*_2diff.nii.gz'%(roi_dir, subj, subj)))\nprint(subj_rois)\n'''\n\nroi_dir = os.path.join(proj_dir, 'analysis/roi_diff_shift/')\nsubj_rois = {}\nfor subj in sids:\n subj_rois[subj] = sorted(glob('%s/%s/%s_roi*_2diff_shift_vox-4_ax-1.nii.gz'%(roi_dir, subj, subj)))\nprint(subj_rois)\n\n# create the nipype workflow\nwf = Workflow(name='connectivity')\nwf.config['execution']['crashfile_format'] = 'txt'\n\n# define inputs to the workflow\ninfosource = Node(IdentityInterface(fields=['subject_id', 'roi']), name='infosource')\ninfosource.iterables = [('subject_id', list(subj_rois.keys())),\n ('roi', rois)]\n\n# grab data\n#templates = {'trk': 'analysis/mrtrix/{subject_id}/tracks.trk'}\ntemplates = {'trk': 'analysis/fathresh-0.5/{subject_id}/recon/{subject_id}_csd_streamline.trk'}\ngrabber = Node(SelectFiles(templates), name='grabber')\ngrabber.inputs.base_directory = proj_dir\ngrabber.inputs.sort_filelist = True\n\nwf.connect(infosource, 'subject_id', grabber, 'subject_id')\n\n''' define ROI mask files '''\n\n# get subject-specific list of ROI filenames:\ndef rois_fetcher(subj_rois, subj):\n return subj_rois[subj], subj\nfetch_rois = Node(Function(input_names=['subj_rois', 'subj'],\n output_names=['target_roi_filenames', 'subj'],\n function=rois_fetcher),\n name='fetch_rois')\nfetch_rois.inputs.subj_rois = subj_rois\nwf.connect(infosource, 'subject_id', fetch_rois, 'subj')\n\n# get single ROI filename for a specific subject:\ndef roi_fetcher(subj_rois, subj, roi_idx):\n return subj_rois[subj][roi_idx], roi_idx\nfetch_roi = Node(Function(input_names=['subj_rois', 'subj', 'roi_idx'],\n output_names=['seed_roi', 'roi_idx'],\n function=roi_fetcher),\n name='fetch_roi')\nfetch_roi.inputs.subj_rois = subj_rois\nwf.connect(fetch_rois, 'subj', fetch_roi, 'subj')\nwf.connect(infosource, 'roi', fetch_roi, 'roi_idx')\n\n\n''' streamline filtering '''\n# filter streamlines by seed region of interest\ndef sl_filter(streamlines, target_mask):\n from dipy.tracking.utils import target\n #from nilearn.image import resample_img\n import numpy as np\n import os\n import nibabel as nib\n\n trk_file = nib.streamlines.load(streamlines)\n streams = trk_file.streamlines\n hdr = trk_file.header\n\n # resample mask to resolution of input data & get data\n #target_resamp = resample_img(target_mask, affine)\n target_mask_img = nib.load(target_mask)\n affine = target_mask_img.affine\n\n target_mask_bool = np.zeros(target_mask_img.get_data().shape)\n target_mask_bool[target_mask_img.get_data().round()>0]=1 # rounding is key!\n\n target_sl_generator = target(streams, target_mask_bool, affine, include=True)\n target_streams = list(target_sl_generator)\n\n # create new filtered streamlines .trk file\n tractogram = nib.streamlines.Tractogram(target_streams)\n tractogram.affine_to_rasmm = np.eye(4)\n trk_file = nib.streamlines.TrkFile(tractogram, header=hdr)\n\n # get the filename\n import re\n label = re.search(r'(?<=Fix_)\\w+',target_mask).group(0)[:-6]\n\n # save streamlines to filename\n target_streamlines = os.path.abspath('target_streamlines_region_%s.trk'%label)\n nib.streamlines.save(trk_file, target_streamlines)\n\n return target_streamlines, target_mask, affine, label\n\nfilter_streamlines = Node(Function(input_names = ['streamlines', 'target_mask'],\n output_names = ['target_streamlines', 'target_mask',\n 'affine', 'seed_label'],\n function = sl_filter),\n name = 'filter_streamlines')\nfilter_streamlines.inputs.roi_names = roi_names\nwf.connect(grabber, 'trk', filter_streamlines, 'streamlines')\nwf.connect(fetch_roi, 'seed_roi', filter_streamlines, 'target_mask')\n\n# filter streamlines by target ROI (for each seed ROI)\ndef sl_filter_target(streamlines, target_mask, affine, seed_label):\n from dipy.tracking.utils import target\n from nilearn.image import resample_img\n import numpy as np\n import os\n\n import nibabel as nib\n trk_file = nib.streamlines.load(streamlines)\n streams = trk_file.streamlines\n hdr = trk_file.header\n\n # resample mask to resolution of input data & get data\n #target_resamp = resample_img(target_mask, affine)\n target_mask_img = nib.load(target_mask)\n affine = target_mask_img.affine\n\n target_mask_bool = np.zeros(target_mask_img.get_data().shape)\n target_mask_bool[target_mask_img.get_data().round()>0]=1 # rounding is key!\n\n target_sl_generator = target(streams, target_mask_bool, affine, include=True)\n target_streams = list(target_sl_generator)\n\n # create new filtered streamlines .trk file\n tractogram = nib.streamlines.Tractogram(target_streams)\n tractogram.affine_to_rasmm = np.eye(4)\n trk_file = nib.streamlines.TrkFile(tractogram, header=hdr)\n\n # get the filename\n import re\n label = re.search(r'(?<=Fix_)\\w+',target_mask).group(0)[:-6]\n\n # save streamlines to filename\n target_streamlines = os.path.abspath('target_streamlines_seed-%s_target-%s.trk'%(seed_label, label))\n nib.streamlines.save(trk_file, target_streamlines)\n\n return target_streamlines\n\nfilter_streamlines_target = MapNode(Function(input_names = ['streamlines', 'target_mask',\n 'affine', 'seed_label'],\n output_names = ['target_streamlines'],\n function = sl_filter_target),\n iterfield = ['target_mask'],\n name = 'filter_streamlines_target')\nwf.connect(fetch_rois, 'target_roi_filenames', filter_streamlines_target, 'target_mask')\nwf.connect(filter_streamlines, 'target_streamlines', filter_streamlines_target, 'streamlines')\nwf.connect(filter_streamlines, 'affine', filter_streamlines_target, 'affine')\nwf.connect(filter_streamlines, 'seed_label', filter_streamlines_target, 'seed_label')\n\n''' workflow '''\n# create the output data sink\nds = Node(DataSink(parameterization=False), name='sinker')\nds.inputs.base_directory = out_dir\nds.plugin_args = {'overwrite': True}\n\nwf.connect(infosource, 'subject_id', ds, 'container')\n\nwf.connect(filter_streamlines_target, 'target_streamlines', ds, 'target_streamlines')\n\n# definte the working directory and run the workflow\nwf.base_dir = work_dir\nwf.run(plugin='MultiProc')\n" ]
[ [ "numpy.eye" ] ]
HaojieYuan/cleverhans
[ "02a5ac27870ad8318c1e6ef3b210467e3500fdd9" ]
[ "cleverhans/future/tf2/attacks/fast_gradient_method.py" ]
[ "\"\"\"The Fast Gradient Method attack.\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef fast_gradient_method(model_fn, x, eps, ord, clip_min=None, clip_max=None, y=None,\n targeted=False, sanity_checks=False):\n \"\"\"\n Tensorflow 2.0 implementation of the Fast Gradient Method.\n :param model_fn: a callable that takes an input tensor and returns the model logits.\n :param x: input tensor.\n :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.\n :param ord: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2.\n :param clip_min: (optional) float. Minimum float value for adversarial example components.\n :param clip_max: (optional) float. Maximum float value for adversarial example components.\n :param y: (optional) Tensor with true labels. If targeted is true, then provide the\n target label. Otherwise, only provide this parameter if you'd like to use true\n labels when crafting adversarial samples. Otherwise, model predictions are used\n as labels to avoid the \"label leaking\" effect (explained in this paper:\n https://arxiv.org/abs/1611.01236). Default is None.\n :param targeted: (optional) bool. Is the attack targeted or untargeted?\n Untargeted, the default, will try to make the label incorrect.\n Targeted will instead try to move in the direction of being more like y.\n :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime /\n memory or for unit tests that intentionally pass strange input)\n :return: a tensor for the adversarial example\n \"\"\"\n if ord not in [np.inf, 1, 2]:\n raise ValueError(\"Norm order must be either np.inf, 1, or 2.\")\n\n asserts = []\n\n # If a data range was specified, check that the input was in that range\n if clip_min is not None:\n asserts.append(tf.math.greater_equal(x, clip_min))\n\n if clip_max is not None:\n asserts.append(tf.math.less_equal(x, clip_max))\n\n if y is None:\n # Using model predictions as ground truth to avoid label leaking\n y = tf.argmax(model_fn(x), 1)\n\n grad = compute_gradient(model_fn, x, y, targeted)\n\n optimal_perturbation = optimize_linear(grad, eps, ord)\n # Add perturbation to original example to obtain adversarial example\n adv_x = x + optimal_perturbation\n\n # If clipping is needed, reset all values outside of [clip_min, clip_max]\n if (clip_min is not None) or (clip_max is not None):\n # We don't currently support one-sided clipping\n assert clip_min is not None and clip_max is not None\n adv_x = tf.clip_by_value(adv_x, clip_min, clip_max)\n\n if sanity_checks:\n assert np.all(asserts)\n return adv_x\n\n\n# Due to performance reasons, this function is wrapped inside of tf.function decorator.\n# Not using the decorator here, or letting the user wrap the attack in tf.function is way\n# slower on Tensorflow 2.0.0-alpha0.\[email protected]\ndef compute_gradient(model_fn, x, y, targeted):\n \"\"\"\n Computes the gradient of the loss with respect to the input tensor.\n :param model_fn: a callable that takes an input tensor and returns the model logits.\n :param x: input tensor\n :param y: Tensor with true labels. If targeted is true, then provide the target label.\n :param targeted: bool. Is the attack targeted or untargeted? Untargeted, the default, will\n try to make the label incorrect. Targeted will instead try to move in the\n direction of being more like y.\n :return: A tensor containing the gradient of the loss with respect to the input tensor.\n \"\"\"\n loss_fn = tf.nn.sparse_softmax_cross_entropy_with_logits\n with tf.GradientTape() as g:\n g.watch(x)\n # Compute loss\n loss = loss_fn(labels=y, logits=model_fn(x))\n if targeted: # attack is targeted, minimize loss of target label rather than maximize loss of correct label\n loss = -loss\n\n # Define gradient of loss wrt input\n grad = g.gradient(loss, x)\n return grad\n\n\ndef optimize_linear(grad, eps, ord=np.inf):\n \"\"\"\n Solves for the optimal input to a linear function under a norm constraint.\n\n Optimal_perturbation = argmax_{eta, ||eta||_{ord} < eps} dot(eta, grad)\n\n :param grad: tf tensor containing a batch of gradients\n :param eps: float scalar specifying size of constraint region\n :param ord: int specifying order of norm\n :returns:\n tf tensor containing optimal perturbation\n \"\"\"\n\n # Convert the iterator returned by `range` into a list.\n axis = list(range(1, len(grad.get_shape())))\n avoid_zero_div = 1e-12\n if ord == np.inf:\n # Take sign of gradient\n optimal_perturbation = tf.sign(grad)\n # The following line should not change the numerical results. It applies only because\n # `optimal_perturbation` is the output of a `sign` op, which has zero derivative anyway.\n # It should not be applied for the other norms, where the perturbation has a non-zero derivative.\n optimal_perturbation = tf.stop_gradient(optimal_perturbation)\n elif ord == 1:\n abs_grad = tf.abs(grad)\n sign = tf.sign(grad)\n max_abs_grad = tf.reduce_max(abs_grad, axis, keepdims=True)\n tied_for_max = tf.dtypes.cast(tf.equal(abs_grad, max_abs_grad), dtype=tf.float32)\n num_ties = tf.reduce_sum(tied_for_max, axis, keepdims=True)\n optimal_perturbation = sign * tied_for_max / num_ties\n elif ord == 2:\n square = tf.maximum(avoid_zero_div, tf.reduce_sum(tf.square(grad), axis, keepdims=True))\n optimal_perturbation = grad / tf.sqrt(square)\n else:\n raise NotImplementedError(\"Only L-inf, L1 and L2 norms are currently implemented.\")\n\n # Scale perturbation to be the solution for the norm=eps rather than norm=1 problem\n scaled_perturbation = tf.multiply(eps, optimal_perturbation)\n return scaled_perturbation\n" ]
[ [ "tensorflow.math.greater_equal", "tensorflow.equal", "tensorflow.math.less_equal", "tensorflow.reduce_max", "tensorflow.sign", "tensorflow.multiply", "tensorflow.sqrt", "tensorflow.stop_gradient", "tensorflow.GradientTape", "numpy.all", "tensorflow.abs", "tensorflow.clip_by_value", "tensorflow.square", "tensorflow.reduce_sum" ] ]
data301-2021-winter1/project-group25-project
[ "203421ca91c95786de4a2fff5412693493b9371f" ]
[ "notebooks/project_functions.py" ]
[ "import pandas as pd\nimport numpy as np\n\ndef load_and_process_data(path):\n rawData = pd.read_csv(path, sep=\";\")\n rawData = rawData[rawData.columns[:-2]].dropna().rename(columns={\"RH\": \"Relative Humidity\", \"AH\": \"Absolute Humdity\", \"T\": \"Temp\"})\n \n for col in rawData.columns:\n #covert strings into floats\n if rawData[col].dtypes == object:\n try:\n rawData[col] = rawData[col].str.replace(\",\", \".\")\n rawData[col] = rawData[col].astype(float)\n except ValueError:\n pass\n #remove row with values of less than 0\n if rawData[col].dtypes==np.float64:\n rawData = rawData[rawData[col]>=0]\n return rawData\ndef getAverageConcentration(df, column):\n '''\n takes in dataFrame and a string column name\n returns an array of 24 integers representing the average values of the column for every hour of the day\n '''\n average=0\n averages = np.zeros(24)\n print(type(df[column][0]))\n for hour in range(24):\n time = \"%s.00.00\"%hour\n validColumns = df[df[\"Time\"]==time]\n average = float(validColumns.sum()[column]) / int(df.shape[0])\n averages[hour]= average\n return averages\n pass" ]
[ [ "pandas.read_csv", "numpy.zeros" ] ]
hietalajulius/clothmanip
[ "ec2ee1177d5cf31ee2367c2576c34b9cf3691501" ]
[ "experiments/produce_images.py" ]
[ "from clothmanip.utils.utils import get_variant, argsparser, get_randomized_env, dump_commit_hashes, get_keys_and_dims, dump_goal\nfrom clothmanip.envs.cloth import ClothEnvPickled as ClothEnv\nimport numpy as np\nfrom rlkit.torch.sac.policies import TanhGaussianPolicy, MakeDeterministic, TanhScriptPolicy, CustomScriptPolicy, CustomTanhScriptPolicy, ScriptPolicy\nimport cv2\nimport os\nfrom rlkit.envs.wrappers import NormalizedBoxEnv\n\n\ndef main(variant):\n\n variant['save_folder'] = \"/home/julius/robotics/clothmanip/experiments/paper_images\"\n env = ClothEnv(**variant['env_kwargs'], has_viewer=True, save_folder=variant['save_folder'])\n env = NormalizedBoxEnv(env)\n env = get_randomized_env(env, variant)\n\n keys, dims = get_keys_and_dims(variant, env)\n\n demo_path = variant['demo_paths'][0]\n predefined_actions = np.genfromtxt(demo_path, delimiter=',')\n\n iter_folder = os.path.join(variant['save_folder'], \"close_no_corners\", \"0\")\n\n os.makedirs(os.path.join(iter_folder, \"corners_images\"), exist_ok=True)\n #os.makedirs(os.path.join(iter_folder, \"env_images\"), exist_ok=True)\n #os.makedirs(os.path.join(iter_folder, \"cnn_images\"), exist_ok=True)\n #os.makedirs(os.path.join(iter_folder, \"cnn_color_images\"), exist_ok=True)\n #os.makedirs(os.path.join(iter_folder, \"cnn_color_full_images\"), exist_ok=True)\n\n policy = TanhScriptPolicy(\n output_size=dims['action_dim'],\n added_fc_input_size=dims['added_fc_input_size'],\n aux_output_size=9,\n **variant['policy_kwargs'],\n )\n\n eval_policy = MakeDeterministic(policy)\n\n\n for step_number, delta in enumerate(predefined_actions):\n print(step_number)\n a = delta/env.output_max\n a = np.clip(a, -1, 1)\n\n corner_image, eval_image, cnn_color_image_full, cnn_color_image, cnn_image = env.capture_images(None, mask_type=None)\n cv2.imwrite(f'{iter_folder}/corners_images/{str(step_number).zfill(3)}.png', corner_image)\n #cv2.imwrite(f'{iter_folder}/env_images/{str(step_number).zfill(3)}.png', eval_image)\n #cv2.imwrite(f'{iter_folder}/cnn_images/{str(step_number).zfill(3)}.png', corner_image)\n #cv2.imwrite(f'{iter_folder}/cnn_color_images/{str(step_number).zfill(3)}.png', cnn_color_image)\n #cv2.imwrite(f'{iter_folder}/cnn_color_full_images/{str(step_number).zfill(3)}.png', cnn_color_image_full)\n\n o, r, d, env_info = env.step(a)\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n args = argsparser()\n variant, arg_str = get_variant(args)\n main(variant)" ]
[ [ "numpy.genfromtxt", "numpy.clip" ] ]
stevenkfirth/OBLib
[ "12ab46ca2c24d28d8ed5b14be0978fb5dacae394" ]
[ "OBLib/Model.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport pandas as pd\n\n\n\nclass Model():\n \"\"\"Abstract model class.\n This is the top-level class and should not be used directly.\n Instead this class is inherited by other more specialised model classes.\n \n \"\"\"\n \n def __init__(self):\n \"\"\n self._inputs=Inputs()\n \n \n def run(self):\n \"\"\"Runs the model.\n \n This is an abstract method and should be overloaded by subclasses.\n \n :returns: The model outputs.\n :rtype: Outputs\n \n \"\"\"\n outputs=Outputs()\n \n # timestamps passed from inputs to outputs\n outputs._timestamps=self._inputs._timestamps\n \n # CALCULATIONS HERE\n \n return outputs\n \n \n @property\n def inputs(self):\n \"\"\"The model inputs. Access this object to change the model inputs. \n \n Read-only property.\n \n :rtype: Inputs\n \n \"\"\"\n return self._inputs\n \n \n \nclass Inputs():\n \"\"\"Abstract model inputs class.\n This is the top-level class and should not be used directly.\n Instead this class is inherited by other more specialised model inputs classes.\n \n \"\"\"\n \n def __init__(self):\n \"\"\n \n self._timestamps=None\n \n \n def set_timestamps(self,\n start=None,\n end=None,\n *args,\n **kwargs):\n \"\"\"Convenience method to set the `timestamps` property.\n \n :param start: The start timestamp (optional)\n :type start: tuple\n :param end: The end timestamp (optional)\n :type end: tuple\n \n The remaining input arguments here are passed to the `pandas.date_range` method. \n See the pandas documentation for details.\n \n Typcial inputs might be:\n \n * start=(2021,1,1,0,0) (i.e. 1st January 2021)\n * freq='H' (for hourly intervals)\n * periods=24 (to generate 1 day of hourly intervals) \n \n :rtype: pandas.DatetimeIndex\n \n \"\"\"\n if not start is None:\n start=pd.Timestamp(*start)\n if not end is None:\n end=pd.Timestamp(*end)\n \n \n self._timestamps=pd.date_range(start=start,\n end=end,\n *args,\n **kwargs)\n return self._timestamps\n \n \n @property\n def timestamps(self):\n \"\"\"The input timestamps. \n Model predictions will be made for each timestamp.\n \n Read / write property.\n \n :rtype: pandas.DatetimeIndex\n \n \"\"\"\n return self._timestamps\n \n \n @timestamps.setter\n def timestamps(self,value):\n \"\"\n self._timestamps=value\n \n \n \nclass Outputs():\n \"\"\"Abstract model outputs class.\n This is the top-level class and should not be used directly.\n Instead this class is inherited by other more specialised model outputs classes.\n \n \"\"\"\n \n def __init__(self):\n \"\"\"\n \"\"\"\n self._timestamps=None # ->pd.DatetimeIndex\n self._data={} # key -> data name; value-> np.array etc.\n \n \n def __repr__(self):\n \"\"\n return (\"%s\" % self.__class__.__name__\n + \"(\"\n + \"timestamps=%s\" % self.timestamps\n + \", \"\n + \"data=%s\" % self.data\n + \")\"\n )\n \n \n @property\n def timestamps(self):\n \"\"\"The outputs timestamps. \n \n Read-only property.\n \n :rtype: pandas.DatetimeIndex\n \n \"\"\"\n return self._timestamps\n \n \n @property\n def data(self):\n \"\"\"The model predictions.\n \n Read-only property.\n \n :returns: A dictionary of the model results.\n Key-value pairs are: keys -> the name of the quantity or variable; \n values -> a list of the model predictions (this list aligns with the \n output timestamps).\n \n :rtype: dict\n \n \"\"\"\n return self._data\n \n \n @property\n def df(self):\n \"\"\"A Pandas dataframe of the timestamps and data.\n \n Read-only property.\n \n :returns: A dataframe with: index -> timestamps; \n columns -> 'data' keys; values -> `data` values.\n \n :rtype: pandas.DataFrame\n \n \"\"\"\n return pd.DataFrame(index=self.timestamps,\n data=self.data)\n \n \n\n\n" ]
[ [ "pandas.DataFrame", "pandas.Timestamp", "pandas.date_range" ] ]
ZoneTsuyoshi/pyassim
[ "1b40ce914a7b1e4ec6e240a6d67a19a22e431137" ]
[ "sample/sample_advection.py" ]
[ "\"\"\"\nsample code for LLOCK, SLOCK, LSLOCK\napplication the method to advection model (periodic boundary condition)\n\"\"\"\n\nimport os, sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsys.path.append(\"..\")\nfrom pyassim import KalmanFilter, LocalLOCK, SpatiallyUniformLOCK, LSLOCK,\\\n PeriodicAdvection, EulerScheme\n\n\ndef main():\n result_dir = \"figures/advection\"\n if not os.path.exists(result_dir):\n os.mkdir(result_dir)\n seed = 121\n np.random.seed(seed)\n\n # parameters\n N = 20\n x0 = np.exp(-(np.arange(N)-N//2)**2/20)\n dt = 0.01\n dx = 1\n c = 1\n sys_sd = 0.001\n obs_sd = 0.1\n timestep = 10000\n ds = 100\n\n # generate data\n model = PeriodicAdvection(dx, c, dt, scheme=\"LW\")\n scheme = EulerScheme(dt, timestep, model, seed=seed)\n true, obs = scheme.noise_added_simulation(x0, sys_sd, obs_sd)\n\n # setup matrices\n # adjacency matrix\n A = np.eye(N)\n A[np.arange(N-1), np.arange(1,N)] = 2\n A[np.arange(1,N), np.arange(N-1)] = 3\n A[0,-1] = 3\n A[-1,0] = 2\n # A[np.arange(N-2), np.arange(2,N)] = True\n # A[np.arange(2,N), np.arange(N-2)] = True\n # A[0,-2] = A[-2,0] = A[1,-1] = A[-1,1] = True\n\n # initial transition matrix\n F = np.eye(N)\n H = np.eye(N)\n\n # covariance\n Q = obs_sd**2 * np.eye(N)\n R = obs_sd**2 * np.eye(N)\n V0 = obs_sd**2 * np.eye(N)\n\n # execution\n kf = KalmanFilter(obs[::ds], x0, V0, F, H, Q, R, em_vars=[\"transition_matrices\"])\n kf.em(n_iter=10)\n kf.forward()\n\n llock = LocalLOCK(obs[::ds], x0, V0, F, H, Q, R, A.astype(bool), method=\"elementwise\",\n estimation_length=20, estimation_interval=5, eta=1.0,\n cutoff=10, estimation_mode=\"forward\")\n llock.forward()\n\n slock = SpatiallyUniformLOCK(obs[::ds], x0, V0, F, H, Q, R, np.zeros(N), A, \n estimation_length=1, estimation_interval=1, eta=1.,\n cutoff=10., estimation_mode=\"forward\")\n slock.forward()\n\n lslock = LSLOCK(obs[::ds], x0, V0, F, H, Q, R, A, method=\"gridwise\", \n estimation_length=10, estimation_interval=5, eta=1.,\n cutoff=10., estimation_mode=\"forward\")\n lslock.forward()\n\n # draw results\n dim=0\n plt.figure(figsize=(8,5))\n plt.scatter(np.arange(timestep//ds), obs[::ds,dim], label=\"obs\", c=\"k\")\n plt.plot(true[::ds,dim], label=\"true\", c=\"cyan\", ls=\"--\")\n plt.plot(kf.get_filtered_value(dim), label=\"kf w/ EM\")\n plt.plot(llock.get_filtered_value(dim), label=\"llock\")\n plt.plot(slock.get_filtered_value(dim), label=\"slock\")\n plt.plot(lslock.get_filtered_value(dim), label=\"lslock\")\n plt.legend()\n plt.savefig(os.path.join(result_dir, \"dim{}_estimated.pdf\".format(dim)), bbox_inches=\"tight\")\n\n fig, ax = plt.subplots(2,2,figsize=(10,10))\n vmin, vmax = obs.min(), obs.max()\n sns.heatmap(true[::ds], cmap=\"Blues\", vmin=vmin, vmax=vmax, ax=ax[0,0])\n sns.heatmap(llock.get_filtered_value(), cmap=\"Blues\", vmin=vmin, vmax=vmax, ax=ax[0,1])\n sns.heatmap(slock.get_filtered_value(), cmap=\"Blues\", vmin=vmin, vmax=vmax, ax=ax[1,0])\n sns.heatmap(lslock.get_filtered_value(), cmap=\"Blues\", vmin=vmin, vmax=vmax, ax=ax[1,1])\n\n ax[0,0].set_title(\"True\")\n ax[0,1].set_title(\"LLOCK\")\n ax[1,0].set_title(\"SLOCK\")\n ax[1,1].set_title(\"LSLOCK\")\n\n for i in range(2):\n for j in range(2):\n ax[i,j].set_xlabel(\"space\")\n ax[i,j].set_ylabel(\"timestep\")\n fig.savefig(os.path.join(result_dir, \"estimated.pdf\"))\n\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "numpy.eye", "matplotlib.pyplot.legend", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.random.seed", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.plot" ] ]
jihunchoi/probability
[ "685c5012eba03a23d1b849d35f5e8efe7fdc402d" ]
[ "tensorflow_probability/python/distributions/mixture.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\"\"\"The Mixture distribution class.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_probability.python.distributions import categorical\nfrom tensorflow_probability.python.distributions import distribution\nfrom tensorflow_probability.python.distributions import seed_stream\nfrom tensorflow_probability.python.internal import distribution_util\nfrom tensorflow_probability.python.internal import reparameterization\nfrom tensorflow.python.framework import tensor_util\n\n\nclass Mixture(distribution.Distribution):\n \"\"\"Mixture distribution.\n\n The `Mixture` object implements batched mixture distributions.\n The mixture model is defined by a `Categorical` distribution (the mixture)\n and a python list of `Distribution` objects.\n\n Methods supported include `log_prob`, `prob`, `mean`, `sample`, and\n `entropy_lower_bound`.\n\n\n #### Examples\n\n ```python\n # Create a mixture of two Gaussians:\n tfd = tfp.distributions\n mix = 0.3\n bimix_gauss = tfd.Mixture(\n cat=tfd.Categorical(probs=[mix, 1.-mix]),\n components=[\n tfd.Normal(loc=-1., scale=0.1),\n tfd.Normal(loc=+1., scale=0.5),\n ])\n\n # Plot the PDF.\n import matplotlib.pyplot as plt\n x = tf.linspace(-2., 3., int(1e4)).eval()\n plt.plot(x, bimix_gauss.prob(x).eval());\n ```\n\n \"\"\"\n\n def __init__(self,\n cat,\n components,\n validate_args=False,\n allow_nan_stats=True,\n use_static_graph=False,\n name=\"Mixture\"):\n \"\"\"Initialize a Mixture distribution.\n\n A `Mixture` is defined by a `Categorical` (`cat`, representing the\n mixture probabilities) and a list of `Distribution` objects\n all having matching dtype, batch shape, event shape, and continuity\n properties (the components).\n\n The `num_classes` of `cat` must be possible to infer at graph construction\n time and match `len(components)`.\n\n Args:\n cat: A `Categorical` distribution instance, representing the probabilities\n of `distributions`.\n components: A list or tuple of `Distribution` instances.\n Each instance must have the same type, be defined on the same domain,\n and have matching `event_shape` and `batch_shape`.\n validate_args: Python `bool`, default `False`. If `True`, raise a runtime\n error if batch or event ranks are inconsistent between cat and any of\n the distributions. This is only checked if the ranks cannot be\n determined statically at graph construction time.\n allow_nan_stats: Boolean, default `True`. If `False`, raise an\n exception if a statistic (e.g. mean/mode/etc...) is undefined for any\n batch member. If `True`, batch members with valid parameters leading to\n undefined statistics will return NaN for this statistic.\n use_static_graph: Calls to `sample` will not rely on dynamic tensor\n indexing, allowing for some static graph compilation optimizations, but\n at the expense of sampling all underlying distributions in the mixture.\n (Possibly useful when running on TPUs).\n Default value: `False` (i.e., use dynamic indexing).\n name: A name for this distribution (optional).\n\n Raises:\n TypeError: If cat is not a `Categorical`, or `components` is not\n a list or tuple, or the elements of `components` are not\n instances of `Distribution`, or do not have matching `dtype`.\n ValueError: If `components` is an empty list or tuple, or its\n elements do not have a statically known event rank.\n If `cat.num_classes` cannot be inferred at graph creation time,\n or the constant value of `cat.num_classes` is not equal to\n `len(components)`, or all `components` and `cat` do not have\n matching static batch shapes, or all components do not\n have matching static event shapes.\n \"\"\"\n parameters = dict(locals())\n # TODO(b/117098119): Remove tf.distribution references once they're gone.\n if not isinstance(cat, categorical.Categorical) and not isinstance(\n cat, tf.distributions.Categorical):\n raise TypeError(\"cat must be a Categorical distribution, but saw: %s\" %\n cat)\n if not components:\n raise ValueError(\"components must be a non-empty list or tuple\")\n if not isinstance(components, (list, tuple)):\n raise TypeError(\"components must be a list or tuple, but saw: %s\" %\n components)\n # TODO(b/117098119): Remove tf.distribution references once they're gone.\n if not all(\n isinstance(c, distribution.Distribution) or\n isinstance(cat, tf.distributions.Distribution) for c in components):\n raise TypeError(\n \"all entries in components must be Distribution instances\"\n \" but saw: %s\" % components)\n\n dtype = components[0].dtype\n if not all(d.dtype == dtype for d in components):\n raise TypeError(\"All components must have the same dtype, but saw \"\n \"dtypes: %s\" % [(d.name, d.dtype) for d in components])\n static_event_shape = components[0].event_shape\n static_batch_shape = cat.batch_shape\n for d in components:\n static_event_shape = static_event_shape.merge_with(d.event_shape)\n static_batch_shape = static_batch_shape.merge_with(d.batch_shape)\n if static_event_shape.ndims is None:\n raise ValueError(\n \"Expected to know rank(event_shape) from components, but \"\n \"none of the components provide a static number of ndims\")\n\n # Ensure that all batch and event ndims are consistent.\n with tf.name_scope(name, values=[cat.logits]) as name:\n num_components = cat.event_size\n static_num_components = tensor_util.constant_value(num_components)\n if static_num_components is None:\n raise ValueError(\n \"Could not infer number of classes from cat and unable \"\n \"to compare this value to the number of components passed in.\")\n # Possibly convert from numpy 0-D array.\n static_num_components = int(static_num_components)\n if static_num_components != len(components):\n raise ValueError(\"cat.num_classes != len(components): %d vs. %d\" %\n (static_num_components, len(components)))\n\n cat_batch_shape = cat.batch_shape_tensor()\n cat_batch_rank = tf.size(cat_batch_shape)\n if validate_args:\n batch_shapes = [d.batch_shape_tensor() for d in components]\n batch_ranks = [tf.size(bs) for bs in batch_shapes]\n check_message = (\"components[%d] batch shape must match cat \"\n \"batch shape\")\n self._assertions = [\n tf.assert_equal(\n cat_batch_rank, batch_ranks[di], message=check_message % di)\n for di in range(len(components))\n ]\n self._assertions += [\n tf.assert_equal(\n cat_batch_shape, batch_shapes[di], message=check_message % di)\n for di in range(len(components))\n ]\n else:\n self._assertions = []\n\n self._cat = cat\n self._components = list(components)\n self._num_components = static_num_components\n self._static_event_shape = static_event_shape\n self._static_batch_shape = static_batch_shape\n\n self._use_static_graph = use_static_graph\n if use_static_graph and static_num_components is None:\n raise ValueError(\"Number of categories must be known statically when \"\n \"`static_sample=True`.\")\n # We let the Mixture distribution access _graph_parents since its arguably\n # more like a baseclass.\n graph_parents = self._cat._graph_parents # pylint: disable=protected-access\n for c in self._components:\n graph_parents += c._graph_parents # pylint: disable=protected-access\n\n super(Mixture, self).__init__(\n dtype=dtype,\n reparameterization_type=reparameterization.NOT_REPARAMETERIZED,\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n parameters=parameters,\n graph_parents=graph_parents,\n name=name)\n\n @property\n def cat(self):\n return self._cat\n\n @property\n def components(self):\n return self._components\n\n @property\n def num_components(self):\n return self._num_components\n\n def _batch_shape_tensor(self):\n return self._cat.batch_shape_tensor()\n\n def _batch_shape(self):\n return self._static_batch_shape\n\n def _event_shape_tensor(self):\n return self._components[0].event_shape_tensor()\n\n def _event_shape(self):\n return self._static_event_shape\n\n def _expand_to_event_rank(self, x):\n \"\"\"Expand the rank of x up to static_event_rank times for broadcasting.\n\n The static event rank was checked to not be None at construction time.\n\n Args:\n x: A tensor to expand.\n Returns:\n The expanded tensor.\n \"\"\"\n expanded_x = x\n for _ in range(self.event_shape.ndims):\n expanded_x = tf.expand_dims(expanded_x, -1)\n return expanded_x\n\n def _mean(self):\n with tf.control_dependencies(self._assertions):\n distribution_means = [d.mean() for d in self.components]\n cat_probs = self._cat_probs(log_probs=False)\n cat_probs = [self._expand_to_event_rank(c_p) for c_p in cat_probs]\n partial_means = [\n c_p * m for (c_p, m) in zip(cat_probs, distribution_means)\n ]\n # These should all be the same shape by virtue of matching\n # batch_shape and event_shape.\n return tf.add_n(partial_means)\n\n def _stddev(self):\n with tf.control_dependencies(self._assertions):\n distribution_means = [d.mean() for d in self.components]\n distribution_devs = [d.stddev() for d in self.components]\n cat_probs = self._cat_probs(log_probs=False)\n\n stacked_means = tf.stack(distribution_means, axis=-1)\n stacked_devs = tf.stack(distribution_devs, axis=-1)\n cat_probs = [self._expand_to_event_rank(c_p) for c_p in cat_probs]\n broadcasted_cat_probs = (\n tf.stack(cat_probs, axis=-1) * tf.ones_like(stacked_means))\n\n batched_dev = distribution_util.mixture_stddev(\n tf.reshape(broadcasted_cat_probs, [-1, len(self.components)]),\n tf.reshape(stacked_means, [-1, len(self.components)]),\n tf.reshape(stacked_devs, [-1, len(self.components)]))\n\n # I.e. re-shape to list(batch_shape) + list(event_shape).\n return tf.reshape(batched_dev, tf.shape(broadcasted_cat_probs)[:-1])\n\n def _log_prob(self, x):\n with tf.control_dependencies(self._assertions):\n x = tf.convert_to_tensor(x, name=\"x\")\n distribution_log_probs = [d.log_prob(x) for d in self.components]\n cat_log_probs = self._cat_probs(log_probs=True)\n final_log_probs = [\n cat_lp + d_lp\n for (cat_lp, d_lp) in zip(cat_log_probs, distribution_log_probs)\n ]\n concat_log_probs = tf.stack(final_log_probs, 0)\n log_sum_exp = tf.reduce_logsumexp(concat_log_probs, [0])\n return log_sum_exp\n\n def _log_cdf(self, x):\n with tf.control_dependencies(self._assertions):\n x = tf.convert_to_tensor(x, name=\"x\")\n distribution_log_cdfs = [d.log_cdf(x) for d in self.components]\n cat_log_probs = self._cat_probs(log_probs=True)\n final_log_cdfs = [\n cat_lp + d_lcdf\n for (cat_lp, d_lcdf) in zip(cat_log_probs, distribution_log_cdfs)\n ]\n concatted_log_cdfs = tf.stack(final_log_cdfs, axis=0)\n mixture_log_cdf = tf.reduce_logsumexp(concatted_log_cdfs, [0])\n return mixture_log_cdf\n\n def _sample_n(self, n, seed=None):\n if self._use_static_graph:\n # This sampling approach is almost the same as the approach used by\n # `MixtureSameFamily`. The differences are due to having a list of\n # `Distribution` objects rather than a single object, and maintaining\n # random seed management that is consistent with the non-static code path.\n samples = []\n cat_samples = self.cat.sample(n, seed=seed)\n stream = seed_stream.SeedStream(seed, salt=\"Mixture\")\n\n for c in range(self.num_components):\n samples.append(self.components[c].sample(n, seed=stream()))\n x = tf.stack(samples, -self._static_event_shape.ndims - 1) # [n, B, k, E]\n npdt = x.dtype.as_numpy_dtype\n mask = tf.one_hot(\n indices=cat_samples, # [n, B]\n depth=self._num_components, # == k\n on_value=np.ones([], dtype=npdt),\n off_value=np.zeros([], dtype=npdt)) # [n, B, k]\n mask = distribution_util.pad_mixture_dimensions(\n mask, self, self._cat,\n self._static_event_shape.ndims) # [n, B, k, [1]*e]\n return tf.reduce_sum(\n x * mask, axis=-1 - self._static_event_shape.ndims) # [n, B, E]\n\n with tf.control_dependencies(self._assertions):\n n = tf.convert_to_tensor(n, name=\"n\")\n static_n = tensor_util.constant_value(n)\n n = int(static_n) if static_n is not None else n\n cat_samples = self.cat.sample(n, seed=seed)\n\n static_samples_shape = cat_samples.shape\n if static_samples_shape.is_fully_defined():\n samples_shape = static_samples_shape.as_list()\n samples_size = static_samples_shape.num_elements()\n else:\n samples_shape = tf.shape(cat_samples)\n samples_size = tf.size(cat_samples)\n static_batch_shape = self.batch_shape\n if static_batch_shape.is_fully_defined():\n batch_shape = static_batch_shape.as_list()\n batch_size = static_batch_shape.num_elements()\n else:\n batch_shape = self.batch_shape_tensor()\n batch_size = tf.reduce_prod(batch_shape)\n static_event_shape = self.event_shape\n if static_event_shape.is_fully_defined():\n event_shape = np.array(static_event_shape.as_list(), dtype=np.int32)\n else:\n event_shape = self.event_shape_tensor()\n\n # Get indices into the raw cat sampling tensor. We will\n # need these to stitch sample values back out after sampling\n # within the component partitions.\n samples_raw_indices = tf.reshape(tf.range(0, samples_size), samples_shape)\n\n # Partition the raw indices so that we can use\n # dynamic_stitch later to reconstruct the samples from the\n # known partitions.\n partitioned_samples_indices = tf.dynamic_partition(\n data=samples_raw_indices,\n partitions=cat_samples,\n num_partitions=self.num_components)\n\n # Copy the batch indices n times, as we will need to know\n # these to pull out the appropriate rows within the\n # component partitions.\n batch_raw_indices = tf.reshape(\n tf.tile(tf.range(0, batch_size), [n]), samples_shape)\n\n # Explanation of the dynamic partitioning below:\n # batch indices are i.e., [0, 1, 0, 1, 0, 1]\n # Suppose partitions are:\n # [1 1 0 0 1 1]\n # After partitioning, batch indices are cut as:\n # [batch_indices[x] for x in 2, 3]\n # [batch_indices[x] for x in 0, 1, 4, 5]\n # i.e.\n # [1 1] and [0 0 0 0]\n # Now we sample n=2 from part 0 and n=4 from part 1.\n # For part 0 we want samples from batch entries 1, 1 (samples 0, 1),\n # and for part 1 we want samples from batch entries 0, 0, 0, 0\n # (samples 0, 1, 2, 3).\n partitioned_batch_indices = tf.dynamic_partition(\n data=batch_raw_indices,\n partitions=cat_samples,\n num_partitions=self.num_components)\n samples_class = [None for _ in range(self.num_components)]\n\n stream = seed_stream.SeedStream(seed, salt=\"Mixture\")\n\n for c in range(self.num_components):\n n_class = tf.size(partitioned_samples_indices[c])\n samples_class_c = self.components[c].sample(\n n_class, seed=stream())\n\n # Pull out the correct batch entries from each index.\n # To do this, we may have to flatten the batch shape.\n\n # For sample s, batch element b of component c, we get the\n # partitioned batch indices from\n # partitioned_batch_indices[c]; and shift each element by\n # the sample index. The final lookup can be thought of as\n # a matrix gather along locations (s, b) in\n # samples_class_c where the n_class rows correspond to\n # samples within this component and the batch_size columns\n # correspond to batch elements within the component.\n #\n # Thus the lookup index is\n # lookup[c, i] = batch_size * s[i] + b[c, i]\n # for i = 0 ... n_class[c] - 1.\n lookup_partitioned_batch_indices = (\n batch_size * tf.range(n_class) + partitioned_batch_indices[c])\n samples_class_c = tf.reshape(\n samples_class_c, tf.concat([[n_class * batch_size], event_shape],\n 0))\n samples_class_c = tf.gather(\n samples_class_c,\n lookup_partitioned_batch_indices,\n name=\"samples_class_c_gather\")\n samples_class[c] = samples_class_c\n\n # Stitch back together the samples across the components.\n lhs_flat_ret = tf.dynamic_stitch(\n indices=partitioned_samples_indices, data=samples_class)\n # Reshape back to proper sample, batch, and event shape.\n ret = tf.reshape(\n lhs_flat_ret, tf.concat(\n [samples_shape, self.event_shape_tensor()], 0))\n ret.set_shape(\n tf.TensorShape(static_samples_shape).concatenate(self.event_shape))\n return ret\n\n def entropy_lower_bound(self, name=\"entropy_lower_bound\"):\n r\"\"\"A lower bound on the entropy of this mixture model.\n\n The bound below is not always very tight, and its usefulness depends\n on the mixture probabilities and the components in use.\n\n A lower bound is useful for ELBO when the `Mixture` is the variational\n distribution:\n\n \\\\(\n \\log p(x) >= ELBO = \\int q(z) \\log p(x, z) dz + H[q]\n \\\\)\n\n where \\\\( p \\\\) is the prior distribution, \\\\( q \\\\) is the variational,\n and \\\\( H[q] \\\\) is the entropy of \\\\( q \\\\). If there is a lower bound\n \\\\( G[q] \\\\) such that \\\\( H[q] \\geq G[q] \\\\) then it can be used in\n place of \\\\( H[q] \\\\).\n\n For a mixture of distributions \\\\( q(Z) = \\sum_i c_i q_i(Z) \\\\) with\n \\\\( \\sum_i c_i = 1 \\\\), by the concavity of \\\\( f(x) = -x \\log x \\\\), a\n simple lower bound is:\n\n \\\\(\n \\begin{align}\n H[q] & = - \\int q(z) \\log q(z) dz \\\\\\\n & = - \\int (\\sum_i c_i q_i(z)) \\log(\\sum_i c_i q_i(z)) dz \\\\\\\n & \\geq - \\sum_i c_i \\int q_i(z) \\log q_i(z) dz \\\\\\\n & = \\sum_i c_i H[q_i]\n \\end{align}\n \\\\)\n\n This is the term we calculate below for \\\\( G[q] \\\\).\n\n Args:\n name: A name for this operation (optional).\n\n Returns:\n A lower bound on the Mixture's entropy.\n \"\"\"\n with self._name_scope(name, values=[self.cat.logits]):\n with tf.control_dependencies(self._assertions):\n distribution_entropies = [d.entropy() for d in self.components]\n cat_probs = self._cat_probs(log_probs=False)\n partial_entropies = [\n c_p * m for (c_p, m) in zip(cat_probs, distribution_entropies)\n ]\n # These are all the same shape by virtue of matching batch_shape\n return tf.add_n(partial_entropies)\n\n def _cat_probs(self, log_probs):\n \"\"\"Get a list of num_components batchwise probabilities.\"\"\"\n which_softmax = tf.nn.log_softmax if log_probs else tf.nn.softmax\n cat_probs = which_softmax(self.cat.logits)\n cat_probs = tf.unstack(cat_probs, num=self.num_components, axis=-1)\n return cat_probs\n" ]
[ [ "tensorflow.reduce_logsumexp", "numpy.ones", "tensorflow.unstack", "tensorflow.name_scope", "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.reduce_sum", "tensorflow.reduce_prod", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.stack", "tensorflow.add_n", "tensorflow.shape", "tensorflow.assert_equal", "tensorflow.ones_like", "numpy.zeros", "tensorflow.expand_dims", "tensorflow.dynamic_partition", "tensorflow.TensorShape", "tensorflow.dynamic_stitch", "tensorflow.control_dependencies", "tensorflow.size", "tensorflow.range", "tensorflow.gather" ] ]
jbampton/dash-table
[ "1e25a1296ccbe0f061cc791e259a3f37ed3fbed9" ]
[ "tests/selenium/test_scrolling.py" ]
[ "import dash\nimport dash.testing.wait as wait\nfrom dash_table import DataTable\n\nimport pandas as pd\nimport pytest\nfrom selenium.webdriver.common.keys import Keys\n\ndf = pd.read_csv(\"https://raw.githubusercontent.com/plotly/datasets/master/solar.csv\")\n\nbase_props = dict(\n id=\"table\",\n columns=[{\"name\": i, \"id\": i} for i in df.columns],\n row_selectable=\"single\",\n row_deletable=True,\n data=df.to_dict(\"records\"),\n editable=True,\n fixed_rows={\"headers\": True, \"data\": 1},\n style_cell=dict(width=150),\n style_table=dict(width=500),\n)\n\n\ndef get_margin(test):\n return test.driver.execute_script(\n \"return parseFloat(getComputedStyle(document.querySelector('#table .cell-0-1')).marginLeft);\"\n )\n\n\ndef get_scroll(test):\n return test.driver.execute_script(\n \"return document.querySelector('#table .dt-table-container__row-1').scrollLeft;\"\n )\n\n\ndef scroll_by(test, value):\n test.driver.execute_script(\n \"document.querySelector('#table .dt-table-container__row-1').scrollBy({}, 0);\".format(\n value\n )\n )\n\n\[email protected](\n \"fixed_rows\",\n [dict(fixed_rows=dict(headers=True)), dict(fixed_rows=dict(headers=True, data=1))],\n)\[email protected](\n \"fixed_columns\",\n [\n dict(),\n dict(fixed_columns=dict(headers=True)),\n dict(fixed_columns=dict(headers=True, data=1)),\n ],\n)\[email protected](\n \"ops\", [dict(), dict(row_selectable=\"single\", row_deletable=True)]\n)\ndef test_scrol001_fixed_alignment(test, fixed_rows, fixed_columns, ops):\n props = {**base_props, **fixed_rows, **fixed_columns, **ops}\n\n app = dash.Dash(__name__)\n app.layout = DataTable(**props)\n\n test.start_server(app)\n\n target = test.table(\"table\")\n assert target.is_ready()\n\n fixed_width = test.driver.execute_script(\n \"return parseFloat(getComputedStyle(document.querySelector('#table .cell-0-0')).width) || 0;\"\n )\n\n assert -get_margin(test) == fixed_width\n\n scroll_by(test, 200)\n\n wait.until(\n lambda: -get_margin(test) == fixed_width + 200, 3,\n )\n\n scroll_by(test, -200)\n\n wait.until(\n lambda: -get_margin(test) == fixed_width, 3,\n )\n assert test.get_log_errors() == []\n\n\[email protected](\n \"fixed_rows\",\n [dict(fixed_rows=dict(headers=True)), dict(fixed_rows=dict(headers=True, data=1))],\n)\[email protected](\n \"fixed_columns\",\n [\n dict(),\n dict(fixed_columns=dict(headers=True)),\n dict(fixed_columns=dict(headers=True, data=1)),\n ],\n)\[email protected](\n \"ops\", [dict(), dict(row_selectable=\"single\", row_deletable=True)]\n)\ndef test_scrol002_edit_navigate(test, fixed_rows, fixed_columns, ops):\n props = {**base_props, **fixed_rows, **fixed_columns, **ops}\n\n app = dash.Dash(__name__)\n app.layout = DataTable(**props)\n\n test.start_server(app)\n\n target = test.table(\"table\")\n assert target.is_ready()\n\n fixed_width = test.driver.execute_script(\n \"return parseFloat(getComputedStyle(document.querySelector('#table .cell-0-0')).width) || 0;\"\n )\n\n scroll_by(test, 200)\n\n # alignment is ok after editing a cell\n target.cell(0, 3).click()\n test.send_keys(\"abc\" + Keys.ENTER)\n\n wait.until(lambda: target.cell(1, 3).is_selected(), 3)\n wait.until(lambda: -get_margin(test) == fixed_width + get_scroll(test), 3)\n\n # alignment is ok after navigating\n test.send_keys(Keys.ARROW_DOWN)\n test.send_keys(Keys.ARROW_RIGHT)\n\n wait.until(lambda: target.cell(2, 4).is_selected(), 3)\n wait.until(\n lambda: -get_margin(test) == fixed_width + get_scroll(test), 3,\n )\n assert test.get_log_errors() == []\n" ]
[ [ "pandas.read_csv" ] ]
connorkerry/RobinhoodBot
[ "6a1e1733d900abfc00a8e6fff1cf48184af4edc3" ]
[ "robinhoodbot/main.py" ]
[ "import robin_stocks as r\nimport pandas as pd\nimport numpy as np\nimport ta as ta\nfrom pandas.plotting import register_matplotlib_converters\nfrom ta import *\nfrom misc import *\nfrom tradingstats import *\n\n#Log in to Robinhood\nlogin = r.login('YOUR_EMAIL','YOUR_PASSWORD')\n\n#Safe divide by zero division function\ndef safe_division(n, d):\n return n / d if d else 0\n\ndef get_watchlist_symbols():\n \"\"\"\n Returns: the symbol for each stock in your watchlist as a list of strings\n \"\"\"\n my_list_names = []\n symbols = []\n for name in r.get_all_watchlists(info='name'):\n my_list_names.append(name)\n for name in my_list_names:\n list = r.get_watchlist_by_name(name)\n for item in list:\n instrument_data = r.get_instrument_by_url(item.get('instrument'))\n symbol = instrument_data['symbol']\n symbols.append(symbol)\n return symbols\n\ndef get_portfolio_symbols():\n \"\"\"\n Returns: the symbol for each stock in your portfolio as a list of strings\n \"\"\"\n symbols = []\n holdings_data = r.get_open_stock_positions()\n for item in holdings_data:\n if not item:\n continue\n instrument_data = r.get_instrument_by_url(item.get('instrument'))\n symbol = instrument_data['symbol']\n symbols.append(symbol)\n return symbols\n\ndef get_position_creation_date(symbol, holdings_data):\n \"\"\"Returns the time at which we bought a certain stock in our portfolio\n\n Args:\n symbol(str): Symbol of the stock that we are trying to figure out when it was bought\n holdings_data(dict): dict returned by r.get_open_stock_positions()\n\n Returns:\n A string containing the date and time the stock was bought, or \"Not found\" otherwise\n \"\"\"\n instrument = r.get_instruments_by_symbols(symbol)\n url = instrument[0].get('url')\n for dict in holdings_data:\n if(dict.get('instrument') == url):\n return dict.get('created_at')\n return \"Not found\"\n\ndef get_modified_holdings():\n \"\"\" Retrieves the same dictionary as r.build_holdings, but includes data about\n when the stock was purchased, which is useful for the read_trade_history() method\n in tradingstats.py\n\n Returns:\n the same dict from r.build_holdings, but with an extra key-value pair for each\n position you have, which is 'bought_at': (the time the stock was purchased)\n \"\"\"\n holdings = r.build_holdings()\n holdings_data = r.get_open_stock_positions()\n for symbol, dict in holdings.items():\n bought_at = get_position_creation_date(symbol, holdings_data)\n bought_at = str(pd.to_datetime(bought_at))\n holdings[symbol].update({'bought_at': bought_at})\n return holdings\n\ndef get_last_crossing(df, days, symbol=\"\", direction=\"\"):\n \"\"\"Searches for a crossing between two indicators for a given stock\n\n Args:\n df(pandas.core.frame.DataFrame): Pandas dataframe with columns containing the stock's prices, both indicators, and the dates\n days(int): Specifies the maximum number of days that the cross can occur by\n symbol(str): Symbol of the stock we're querying. Optional, used for printing purposes\n direction(str): \"above\" if we are searching for an upwards cross, \"below\" if we are searching for a downwaords cross. Optional, used for printing purposes\n\n Returns:\n 1 if the short-term indicator crosses above the long-term one\n 0 if there is no cross between the indicators\n -1 if the short-term indicator crosses below the long-term one\n \"\"\"\n prices = df.loc[:,\"Price\"]\n shortTerm = df.loc[:,\"Indicator1\"]\n LongTerm = df.loc[:,\"Indicator2\"]\n dates = df.loc[:,\"Dates\"]\n lastIndex = prices.size - 1\n index = lastIndex\n found = index\n recentDiff = (shortTerm.at[index] - LongTerm.at[index]) >= 0\n if((direction == \"above\" and not recentDiff) or (direction == \"below\" and recentDiff)):\n return 0\n index -= 1\n while(index >= 0 and found == lastIndex and not np.isnan(shortTerm.at[index]) and not np.isnan(LongTerm.at[index]) \\\n and ((pd.Timestamp(\"now\", tz='UTC') - dates.at[index]) <= pd.Timedelta(str(days) + \" days\"))):\n if(recentDiff):\n if((shortTerm.at[index] - LongTerm.at[index]) < 0):\n found = index\n else:\n if((shortTerm.at[index] - LongTerm.at[index]) > 0):\n found = index\n index -= 1\n if(found != lastIndex):\n if((direction == \"above\" and recentDiff) or (direction == \"below\" and not recentDiff)):\n print(symbol + \": Short SMA crossed\" + (\" ABOVE \" if recentDiff else \" BELOW \") + \"Long SMA at \" + str(dates.at[found]) \\\n +\", which was \" + str(pd.Timestamp(\"now\", tz='UTC') - dates.at[found]) + \" ago\", \", price at cross: \" + str(prices.at[found]) \\\n + \", current price: \" + str(prices.at[lastIndex]))\n return (1 if recentDiff else -1)\n else:\n return 0\n\ndef five_year_check(stockTicker):\n \"\"\"Figure out if a stock has risen or been created within the last five years.\n\n Args:\n stockTicker(str): Symbol of the stock we're querying\n\n Returns:\n True if the stock's current price is higher than it was five years ago, or the stock IPO'd within the last five years\n False otherwise\n \"\"\"\n instrument = r.get_instruments_by_symbols(stockTicker)\n list_date = instrument[0].get(\"list_date\")\n if ((pd.Timestamp(\"now\") - pd.to_datetime(list_date)) < pd.Timedelta(\"5 Y\")):\n return True\n fiveyear = r.get_historicals(stockTicker,span='5year',bounds='regular')\n closingPrices = []\n for item in fiveyear:\n closingPrices.append(float(item['close_price']))\n recent_price = closingPrices[len(closingPrices) - 1]\n oldest_price = closingPrices[0]\n return (recent_price > oldest_price)\n\ndef golden_cross(stockTicker, n1, n2, days, direction=\"\"):\n \"\"\"Determine if a golden/death cross has occured for a specified stock in the last X trading days\n\n Args:\n stockTicker(str): Symbol of the stock we're querying\n n1(int): Specifies the short-term indicator as an X-day moving average.\n n2(int): Specifies the long-term indicator as an X-day moving average.\n (n1 should be smaller than n2 to produce meaningful results, e.g n1=50, n2=200)\n days(int): Specifies the maximum number of days that the cross can occur by\n direction(str): \"above\" if we are searching for an upwards cross, \"below\" if we are searching for a downwaords cross. Optional, used for printing purposes\n\n Returns:\n 1 if the short-term indicator crosses above the long-term one\n 0 if there is no cross between the indicators\n -1 if the short-term indicator crosses below the long-term one\n False if direction == \"above\" and five_year_check(stockTicker) returns False, meaning that we're considering whether to\n buy the stock but it hasn't risen overall in the last five years, suggesting it contains fundamental issues\n \"\"\"\n if(direction == \"above\" and not five_year_check(stockTicker)):\n return False\n history = r.get_historicals(stockTicker,span='year',bounds='regular')\n closingPrices = []\n dates = []\n for item in history:\n closingPrices.append(float(item['close_price']))\n dates.append(item['begins_at'])\n price = pd.Series(closingPrices)\n dates = pd.Series(dates)\n dates = pd.to_datetime(dates)\n sma1 = ta.volatility.bollinger_mavg(price, n=int(n1), fillna=False)\n sma2 = ta.volatility.bollinger_mavg(price, n=int(n2), fillna=False)\n series = [price.rename(\"Price\"), sma1.rename(\"Indicator1\"), sma2.rename(\"Indicator2\"), dates.rename(\"Dates\")]\n df = pd.concat(series, axis=1)\n cross = get_last_crossing(df, days, symbol=stockTicker, direction=direction)\n # if(cross):\n # show_plot(price, sma1, sma2, dates, symbol=stockTicker, label1=str(n1)+\" day SMA\", label2=str(n2)+\" day SMA\")\n return cross\n\ndef sell_holdings(symbol, holdings_data):\n \"\"\" Place an order to sell all holdings of a stock.\n\n Args:\n symbol(str): Symbol of the stock we want to sell\n holdings_data(dict): dict obtained from get_modified_holdings() method\n \"\"\"\n shares_owned = int(float(holdings_data[symbol].get(\"quantity\")))\n r.order_sell_market(symbol, shares_owned)\n print(\"####### Selling \" + str(shares_owned) + \" shares of \" + symbol + \" #######\")\n\ndef buy_holdings(potential_buys, profile_data, holdings_data):\n \"\"\" Places orders to buy holdings of stocks. This method will try to order\n an appropriate amount of shares such that your holdings of the stock will\n roughly match the average for the rest of your portfoilio. If the share\n price is too high considering the rest of your holdings and the amount of\n buying power in your account, it will not order any shares.\n\n Args:\n potential_buys(list): List of strings, the strings are the symbols of stocks we want to buy\n symbol(str): Symbol of the stock we want to sell\n holdings_data(dict): dict obtained from r.build_holdings() or get_modified_holdings() method\n \"\"\"\n cash = float(profile_data.get('cash'))\n portfolio_value = float(profile_data.get('equity')) - cash\n ideal_position_size = (safe_division(portfolio_value, len(holdings_data))+cash/len(potential_buys))/(2 * len(potential_buys))\n prices = r.get_latest_price(potential_buys)\n for i in range(0, len(potential_buys)):\n stock_price = float(prices[i])\n if(ideal_position_size < stock_price < ideal_position_size*1.5):\n num_shares = int(ideal_position_size*1.5/stock_price)\n elif (stock_price < ideal_position_size):\n num_shares = int(ideal_position_size/stock_price)\n else:\n print(\"####### Tried buying shares of \" + potential_buys[i] + \", but not enough buying power to do so#######\")\n break\n print(\"####### Buying \" + str(num_shares) + \" shares of \" + potential_buys[i] + \" #######\")\n r.order_buy_market(potential_buys[i], num_shares)\n\ndef scan_stocks():\n \"\"\" The main method. Sells stocks in your portfolio if their 50 day moving average crosses\n below the 200 day, and buys stocks in your watchlist if the opposite happens.\n\n ###############################################################################################\n WARNING: Comment out the sell_holdings and buy_holdings lines if you don't actually want to execute the trade.\n ###############################################################################################\n\n If you sell a stock, this updates tradehistory.txt with information about the position,\n how much you've earned/lost, etc.\n \"\"\"\n print(\"----- Starting scan... -----\\n\")\n register_matplotlib_converters()\n watchlist_symbols = get_watchlist_symbols()\n portfolio_symbols = get_portfolio_symbols()\n holdings_data = get_modified_holdings()\n potential_buys = []\n sells = []\n print(\"Current Portfolio: \" + str(portfolio_symbols) + \"\\n\")\n print(\"Current Watchlist: \" + str(watchlist_symbols) + \"\\n\")\n print(\"----- Scanning portfolio for stocks to sell -----\\n\")\n for symbol in portfolio_symbols:\n cross = golden_cross(symbol, n1=50, n2=200, days=30, direction=\"below\")\n if(cross == -1):\n sell_holdings(symbol, holdings_data)\n sells.append(symbol)\n profile_data = r.build_user_profile()\n print(\"\\n----- Scanning watchlist for stocks to buy -----\\n\")\n for symbol in watchlist_symbols:\n if(symbol not in portfolio_symbols):\n cross = golden_cross(symbol, n1=50, n2=200, days=10, direction=\"above\")\n if(cross == 1):\n potential_buys.append(symbol)\n if(len(potential_buys) > 0):\n buy_holdings(potential_buys, profile_data, holdings_data)\n if(len(sells) > 0):\n update_trade_history(sells, holdings_data, \"tradehistory.txt\")\n print(\"----- Scan over -----\\n\")\n\n#execute the scan\nscan_stocks()\n" ]
[ [ "pandas.Series", "pandas.Timedelta", "pandas.plotting.register_matplotlib_converters", "pandas.to_datetime", "pandas.concat", "numpy.isnan", "pandas.Timestamp" ] ]
TheGlobalExpert/protein-stability
[ "b5cc6efaaa6a2f7784729420b746a7ec07bd0d97" ]
[ "old/ROC_foldx.py" ]
[ "import pandas as pd\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n\ndata = pd.read_csv(\"../results/master.csv\")\ndata = pd.read_csv(\"../data/FoldX_predictions.csv\")\n\nx = list(data[\"ddG\"])\ny = list(data[\"FoldX_dGG\"])\n\n\n#clean # XXX:\n\n\n\n\nimport itertools\n\n#lists = sorted(zip(*[x, y]))\n#x, y = list(zip(*lists))\n#x = x[:10]\n#y = y[:10]\n\nfor i in range(len(x)):\n x[i] = float(x[i])\n\nprint(y)\nprint(x)\nx = np.array(x)\ny = np.array(y)\n\ndata = {\"x\":x,\"y\":y}\nplt.scatter(\"x\",\"y\", data=data, label=None)\n\nplt.plot(x,y,\"o\")\n\nplt.ylabel(\"Predicted ddG\")\nplt.xlabel(\"Experimental ddG\")\nx = np.array(x)\n#plt.xticks(np.arange(x.min(), x.max(), 0.5))\ncorr = np.corrcoef(x, y)[0,1]\nplt.text(-2.5, 7, 'Spearman correlation \\ncoefficent: '+str(round(corr,3)))\nprint(corr)\n\nm, b = np.polyfit(x, y, 1)\nplt.plot(x, m*x + b, label=\"Best Fit\")\nplt.text(3.3, -1.3, 'slope = '+str(round(m,2)))\nplt.text(3.3, -1.7, 'y-intercept = '+str(round(b,2)))\n\nx_hori = list(np.arange(-10,10, 0.5))\ny_hori = list(np.arange(-10,10, 0.5))\n\n\nplt.plot(x_hori, y_hori, linestyle=\"dashed\", label=\"Ideal\")\nplt.ylim(-3,8)\nplt.xlim(-3,6)\nplt.legend(loc=\"upper right\")\nplt.title(\"New dataset (ProTherm+HotMusic)\")\n\nplt.show()\n\n\n\nprint(x)\nprint(y)\n\ndef check_accuracy(threshold):\n\n true_positive = 0\n false_positive = 0\n true_negative = 0\n false_negative = 0\n\n for i in range(data.shape[0]):\n if data.loc[i, \"ddG\"] >= threshold: #Positve\n if data.loc[i, \"FoldX_predictions\"] >= threshold:\n true_positive = true_positive + 1\n elif data.loc[i, \"FoldX_predictions\"] <= threshold:\n false_positive = false_positive + 1\n else:\n exit()\n else: #negative\n if data.loc[i, \"FoldX_predictions\"] <= threshold:\n true_negative = true_negative + 1\n elif data.loc[i, \"FoldX_predictions\"] >= threshold:\n false_negative = false_negative + 1\n else:\n exit()\n\n return [true_positive, false_positive, true_negative, false_negative]\n\ndef check_accuracy(threshold, x, y):\n\n true_positive = 0\n false_positive = 0\n true_negative = 0\n false_negative = 0\n\n for i in range(len(x)):\n if float(x[i]) >= threshold: #Positve\n if y[i] >= threshold:\n true_positive = true_positive + 1\n elif y[i] <= threshold:\n false_positive = false_positive + 1\n else:\n exit()\n else: #negative\n if y[i] <= threshold:\n true_negative = true_negative + 1\n elif y[i] >= threshold:\n false_negative = false_negative + 1\n else:\n exit()\n\n return [true_positive, false_positive, true_negative, false_negative]\n\n\nresults = []\n\nthresholds = list(np.arange(-10,10, 0.1))\n\n\nprint(thresholds)\n\nfor threshold in thresholds:\n results.append(check_accuracy(threshold, x, y))\n print(threshold)\n pass\n\nprint(results)\n\nx = []\ny = []\n\nfor i, result in enumerate(results):\n print(result)\n try:\n x.append(result[1] / (result[1] + result[2]))\n y.append(result[0] / (result[0] + result[3]))\n except:\n x.append(np.nan)\n y.append(np.nan)\n\nprint(x)\n\n\nfor i in range(len(x)):\n print(i, \"----\")\n print(x[i])\n print(results[i])\n\nx_hori = list(np.arange(0,1.1, 0.1))\ny_hori = list(np.arange(0,1.1, 0.1))\n\nTOI = [100,103, 105, 107, 110, 112, 118, 120]\nplt.figure(figsize = (6,6))\nfor threshold in TOI:\n plt.text(x[threshold] - 0.06, y[threshold] + 0.01, str(round(thresholds[threshold],3)))\n #print(thresholds[threshold], threshold)\n\n\n\nplt.plot(x,y)\nplt.plot(x_hori, y_hori, linestyle=\"dashed\")\nplt.xlabel(\"False Positive Rate\")\nplt.ylabel(\"True Postive Rate\")\nplt.xlim(0,1)\nplt.ylim(0,1)\nplt.title(\"ROC curve of FoldX predictions of ddG with relation\\nto varying ddG threshold (HotMusic dataset)\")\n\nfor threshold in TOI:\n plt.scatter(x[threshold], y[threshold], c=\"b\")\n\nplt.show()\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.figure", "matplotlib.pyplot.xlim", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.polyfit", "matplotlib.pyplot.ylim", "numpy.array", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.scatter", "numpy.corrcoef" ] ]
d3ft0uch/Tacotron-2
[ "a508bb842053599697a7c0a20d2b8cbb32e28632" ]
[ "hparams.py" ]
[ "# -*- coding: utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\n\n# Default hyperparameters\nhparams = tf.contrib.training.HParams(\n # Comma-separated list of cleaners to run on text prior to training and eval. For non-English\n # text, you may want to use \"basic_cleaners\" or \"transliteration_cleaners\".\n cleaners='transliteration_cleaners',\n\n # If you only have 1 GPU or want to use only one GPU, please set num_gpus=0 and specify the GPU idx on run. example:\n # expample 1 GPU of index 2 (train on \"/gpu2\" only): CUDA_VISIBLE_DEVICES=2 python train.py --model='Tacotron' --hparams='tacotron_gpu_start_idx=2'\n # If you want to train on multiple GPUs, simply specify the number of GPUs available, and the idx of the first GPU to use. example:\n # example 4 GPUs starting from index 0 (train on \"/gpu0\"->\"/gpu3\"): python train.py --model='Tacotron' --hparams='tacotron_num_gpus=4, tacotron_gpu_start_idx=0'\n # The hparams arguments can be directly modified on this hparams.py file instead of being specified on run if preferred!\n\n # If one wants to train both Tacotron and WaveNet in parallel (provided WaveNet will be trained on True mel spectrograms), one needs to specify different GPU idxes.\n # example Tacotron+WaveNet on a machine with 4 or more GPUs. Two GPUs for each model:\n # CUDA_VISIBLE_DEVICES=0,1 python train.py --model='Tacotron' --hparams='tacotron_num_gpus=2'\n # Cuda_VISIBLE_DEVICES=2,3 python train.py --model='WaveNet' --hparams='wavenet_num_gpus=2'\n\n # IMPORTANT NOTES: The Multi-GPU performance highly depends on your hardware and optimal parameters change between rigs. Default are optimized for servers.\n # If using N GPUs, please multiply the tacotron_batch_size by N below in the hparams! (tacotron_batch_size = 32 * N)\n # Never use lower batch size than 32 on a single GPU!\n # Same applies for Wavenet: wavenet_batch_size = 8 * N (wavenet_batch_size can be smaller than 8 if GPU is having OOM, minimum 2)\n # Please also apply the synthesis batch size modification likewise. (if N GPUs are used for synthesis, minimal batch size must be N, minimum of 1 sample per GPU)\n # We did not add an automatic multi-GPU batch size computation to avoid confusion in the user's mind and to provide more control to the user for\n # resources related decisions.\n\n # Acknowledgement:\n #\tMany thanks to @MlWoo for his awesome work on multi-GPU Tacotron which showed to work a little faster than the original\n #\tpipeline for a single GPU as well. Great work!\n\n # Hardware setup: Default supposes user has only one GPU: \"/gpu:0\" (Both Tacotron and WaveNet can be trained on multi-GPU: data parallelization)\n # Synthesis also uses the following hardware parameters for multi-GPU parallel synthesis.\n tacotron_num_gpus=1, # Determines the number of gpus in use for Tacotron training.\n wavenet_num_gpus=1, # Determines the number of gpus in use for WaveNet training.\n split_on_cpu=False,\n # Determines whether to split data on CPU or on first GPU. This is automatically True when more than 1 GPU is used.\n # (Recommend: False on slow CPUs/Disks, True otherwise for small speed boost)\n ###########################################################################################################################################\n\n # Audio\n # Audio parameters are the most important parameters to tune when using this work on your personal data. Below are the beginner steps to adapt\n # this work to your personal data:\n #\t1- Determine my data sample rate: First you need to determine your audio sample_rate (how many samples are in a second of audio). This can be done using sox: \"sox --i <filename>\"\n #\t\t(For this small tuto, I will consider 24kHz (24000 Hz), and defaults are 22050Hz, so there are plenty of examples to refer to)\n #\t2- set sample_rate parameter to your data correct sample rate\n #\t3- Fix win_size and and hop_size accordingly: (Supposing you will follow our advice: 50ms window_size, and 12.5ms frame_shift(hop_size))\n #\t\ta- win_size = 0.05 * sample_rate. In the tuto example, 0.05 * 24000 = 1200\n #\t\tb- hop_size = 0.25 * win_size. Also equal to 0.0125 * sample_rate. In the tuto example, 0.25 * 1200 = 0.0125 * 24000 = 300 (Can set frame_shift_ms=12.5 instead)\n #\t4- Fix n_fft, num_freq and upsample_scales parameters accordingly.\n #\t\ta- n_fft can be either equal to win_size or the first power of 2 that comes after win_size. I usually recommend using the latter\n #\t\t\tto be more consistent with signal processing friends. No big difference to be seen however. For the tuto example: n_fft = 2048 = 2**11\n #\t\tb- num_freq = (n_fft / 2) + 1. For the tuto example: num_freq = 2048 / 2 + 1 = 1024 + 1 = 1025.\n #\t\tc- For WaveNet, upsample_scales products must be equal to hop_size. For the tuto example: upsample_scales=[15, 20] where 15 * 20 = 300\n #\t\t\tit is also possible to use upsample_scales=[3, 4, 5, 5] instead. One must only keep in mind that upsample_kernel_size[0] = 2*upsample_scales[0]\n #\t\t\tso the training segments should be long enough (2.8~3x upsample_scales[0] * hop_size or longer) so that the first kernel size can see the middle\n #\t\t\tof the samples efficiently. The length of WaveNet training segments is under the parameter \"max_time_steps\".\n #\t5- Finally comes the silence trimming. This very much data dependent, so I suggest trying preprocessing (or part of it, ctrl-C to stop), then use the\n #\t\t.ipynb provided in the repo to listen to some inverted mel/linear spectrograms. That will first give you some idea about your above parameters, and\n #\t\tit will also give you an idea about trimming. If silences persist, try reducing trim_top_db slowly. If samples are trimmed mid words, try increasing it.\n #\t6- If audio quality is too metallic or fragmented (or if linear spectrogram plots are showing black silent regions on top), then restart from step 2.\n num_mels=80, # Number of mel-spectrogram channels and local conditioning dimensionality\n num_freq=1025, # (= n_fft / 2 + 1) only used when adding linear spectrograms post processing network\n rescale=True, # Whether to rescale audio prior to preprocessing\n rescaling_max=0.999, # Rescaling value\n\n # train samples of lengths between 3sec and 14sec are more than enough to make a model capable of generating consistent speech.\n clip_mels_length=True,\n # For cases of OOM (Not really recommended, only use if facing unsolvable OOM errors, also consider clipping your samples to smaller chunks)\n max_mel_frames=800,\n # Only relevant when clip_mels_length = True, please only use after trying output_per_steps=3 and still getting OOM errors.\n output_per_steps=3,\n # Use LWS (https://github.com/Jonathan-LeRoux/lws) for STFT and phase reconstruction\n # It's preferred to set True to use with https://github.com/r9y9/wavenet_vocoder\n # Does not work if n_ffit is not multiple of hop_size!!\n use_lws=False,\n # Only used to set as True if using WaveNet, no difference in performance is observed in either cases.\n silence_threshold=2, # silence threshold used for sound trimming for wavenet preprocessing\n\n # Mel spectrogram\n n_fft=2048, # Extra window size is filled with 0 paddings to match this parameter\n hop_size=275, # For 22050Hz, 275 ~= 12.5 ms (0.0125 * sample_rate)\n win_size=1100, # For 22050Hz, 1100 ~= 50 ms (If None, win_size = n_fft) (0.05 * sample_rate)\n sample_rate=22050, # 22050 Hz (corresponding to ljspeech dataset) (sox --i <filename>)\n frame_shift_ms=None, # Can replace hop_size parameter. (Recommended: 12.5)\n magnitude_power=2., # The power of the spectrogram magnitude (1. for energy, 2. for power)\n\n # M-AILABS (and other datasets) trim params (there parameters are usually correct for any data, but definitely must be tuned for specific speakers)\n trim_silence=True, # Whether to clip silence in Audio (at beginning and end of audio only, not the middle)\n trim_fft_size=2048, # Trimming window size\n trim_hop_size=512, # Trimmin hop length\n trim_top_db=40, # Trimming db difference from reference db (smaller==harder trim.)\n\n # Mel and Linear spectrograms normalization/scaling and clipping\n signal_normalization=True,\n # Whether to normalize mel spectrograms to some predefined range (following below parameters)\n allow_clipping_in_normalization=True, # Only relevant if mel_normalization = True\n symmetric_mels=True,\n # Whether to scale the data to be symmetric around 0. (Also multiplies the output range by 2, faster and cleaner convergence)\n max_abs_value=4.,\n # max absolute value of data. If symmetric, data will be [-max, max] else [0, max] (Must not be too big to avoid gradient explosion,\n # not too small for fast convergence)\n normalize_for_wavenet=True, # whether to rescale to [0, 1] for wavenet. (better audio quality)\n clip_for_wavenet=True,\n # whether to clip [-max, max] before training/synthesizing with wavenet (better audio quality)\n wavenet_pad_sides=1, # Can be 1 or 2. 1 for pad right only, 2 for both sides padding.\n\n # Contribution by @begeekmyfriend\n # Spectrogram Pre-Emphasis (Lfilter: Reduce spectrogram noise and helps model certitude levels. Also allows for better G&L phase reconstruction)\n preemphasize=True, # whether to apply filter\n preemphasis=0.97, # filter coefficient.\n\n # Limits\n min_level_db=-100,\n ref_level_db=20,\n fmin=55,\n # Set this to 55 if your speaker is male! if female, 95 should help taking off noise. (To test depending on dataset. Pitch info: male~[65, 260], female~[100, 525])\n fmax=7600, # To be increased/reduced depending on data.\n\n # Griffin Lim\n power=1.5, # Only used in G&L inversion, usually values between 1.2 and 1.5 are a good choice.\n griffin_lim_iters=60, # Number of G&L iterations, typically 30 is enough but we use 60 to ensure convergence.\n GL_on_GPU=True,\n # Whether to use G&L GPU version as part of tensorflow graph. (Usually much faster than CPU but slightly worse quality too).\n ###########################################################################################################################################\n\n # Tacotron\n # Model general type\n outputs_per_step=3,\n # number of frames to generate at each decoding step (increase to speed up computation and allows for higher batch size, decreases G&L audio quality)\n stop_at_any=True,\n # Determines whether the decoder should stop when predicting <stop> to any frame or to all of them (True works pretty well)\n batch_norm_position='after',\n # Can be in ('before', 'after'). Determines whether we use batch norm before or after the activation function (relu). Matter for debate.\n clip_outputs=True,\n # Whether to clip spectrograms to T2_output_range (even in loss computation). ie: Don't penalize model for exceeding output range and bring back to borders.\n lower_bound_decay=0.1,\n # Small regularizer for noise synthesis by adding small range of penalty for silence regions. Set to 0 to clip in Tacotron range.\n\n # Input parameters\n embedding_dim=512, # dimension of embedding space\n\n # Encoder parameters\n enc_conv_num_layers=3, # number of encoder convolutional layers\n enc_conv_kernel_size=(5,), # size of encoder convolution filters for each layer\n enc_conv_channels=512, # number of encoder convolutions filters for each layer\n encoder_lstm_units=256, # number of lstm units for each direction (forward and backward)\n\n # Attention mechanism\n smoothing=False, # Whether to smooth the attention normalization function\n attention_dim=128, # dimension of attention space\n attention_filters=32, # number of attention convolution filters\n attention_kernel=(31,), # kernel size of attention convolution\n cumulative_weights=True,\n # Whether to cumulate (sum) all previous attention weights or simply feed previous weights (Recommended: True)\n\n # Attention synthesis constraints\n # \"Monotonic\" constraint forces the model to only look at the forwards attention_win_size steps.\n # \"Window\" allows the model to look at attention_win_size neighbors, both forward and backward steps.\n synthesis_constraint=False,\n # Whether to use attention windows constraints in synthesis only (Useful for long utterances synthesis)\n synthesis_constraint_type='window', # can be in ('window', 'monotonic').\n attention_win_size=7,\n # Side of the window. Current step does not count. If mode is window and attention_win_size is not pair, the 1 extra is provided to backward part of the window.\n\n # Decoder\n prenet_layers=[256, 256], # number of layers and number of units of prenet\n decoder_layers=2, # number of decoder lstm layers\n decoder_lstm_units=1024, # number of decoder lstm units on each layer\n max_iters=10000, # Max decoder steps during inference (Just for safety from infinite loop cases)\n\n # Residual postnet\n postnet_num_layers=5, # number of postnet convolutional layers\n postnet_kernel_size=(5,), # size of postnet convolution filters for each layer\n postnet_channels=512, # number of postnet convolution filters for each layer\n\n # CBHG mel->linear postnet\n cbhg_kernels=8,\n # All kernel sizes from 1 to cbhg_kernels will be used in the convolution bank of CBHG to act as \"K-grams\"\n cbhg_conv_channels=128, # Channels of the convolution bank\n cbhg_pool_size=2, # pooling size of the CBHG\n cbhg_projection=256, # projection channels of the CBHG (1st projection, 2nd is automatically set to num_mels)\n cbhg_projection_kernel_size=3, # kernel_size of the CBHG projections\n cbhg_highwaynet_layers=4, # Number of HighwayNet layers\n cbhg_highway_units=128, # Number of units used in HighwayNet fully connected layers\n cbhg_rnn_units=128,\n # Number of GRU units used in bidirectional RNN of CBHG block. CBHG output is 2x rnn_units in shape\n\n # Loss params\n mask_encoder=True,\n # whether to mask encoder padding while computing attention. Set to True for better prosody but slower convergence.\n mask_decoder=False,\n # Whether to use loss mask for padded sequences (if False, <stop_token> loss function will not be weighted, else recommended pos_weight = 20)\n cross_entropy_pos_weight=1,\n # Use class weights to reduce the stop token classes imbalance (by adding more penalty on False Negatives (FN)) (1 = disabled)\n predict_linear=True,\n # Whether to add a post-processing network to the Tacotron to predict linear spectrograms (True mode Not tested!!)\n ###########################################################################################################################################\n\n # Wavenet\n # Input type:\n # 1. raw [-1, 1]\n # 2. mulaw [-1, 1]\n # 3. mulaw-quantize [0, mu]\n # If input_type is raw or mulaw, network assumes scalar input and\n # discretized mixture of logistic distributions output, otherwise one-hot\n # input and softmax output are assumed.\n # Model general type\n input_type=\"raw\",\n # Raw has better quality but harder to train. mulaw-quantize is easier to train but has lower quality.\n quantize_channels=2 ** 16,\n # 65536 (16-bit) (raw) or 256 (8-bit) (mulaw or mulaw-quantize) // number of classes = 256 <=> mu = 255\n use_bias=True, # Whether to use bias in convolutional layers of the Wavenet\n legacy=True,\n # Whether to use legacy mode: Multiply all skip outputs but the first one with sqrt(0.5) (True for more early training stability, especially for large models)\n residual_legacy=True,\n # Whether to scale residual blocks outputs by a factor of sqrt(0.5) (True for input variance preservation early in training and better overall stability)\n\n # Model Losses parmeters\n # Minimal scales ranges for MoL and Gaussian modeling\n log_scale_min=float(np.log(1e-14)), # Mixture of logistic distributions minimal log scale\n log_scale_min_gauss=float(np.log(1e-7)), # Gaussian distribution minimal allowed log scale\n # Loss type\n cdf_loss=False,\n # Whether to use CDF loss in Gaussian modeling. Advantages: non-negative loss term and more training stability. (Automatically True for MoL)\n\n # model parameters\n # To use Gaussian distribution as output distribution instead of mixture of logistics, set \"out_channels = 2\" instead of \"out_channels = 10 * 3\". (UNDER TEST)\n out_channels=2,\n # This should be equal to quantize channels when input type is 'mulaw-quantize' else: num_distributions * 3 (prob, mean, log_scale).\n layers=20, # Number of dilated convolutions (Default: Simplified Wavenet of Tacotron-2 paper)\n stacks=2, # Number of dilated convolution stacks (Default: Simplified Wavenet of Tacotron-2 paper)\n residual_channels=128, # Number of residual block input/output channels.\n gate_channels=256, # split in 2 in gated convolutions\n skip_out_channels=128, # Number of residual block skip convolution channels.\n kernel_size=3, # The number of inputs to consider in dilated convolutions.\n\n # Upsampling parameters (local conditioning)\n cin_channels=80, # Set this to -1 to disable local conditioning, else it must be equal to num_mels!!\n # Upsample types: ('1D', '2D', 'Resize', 'SubPixel', 'NearestNeighbor')\n # All upsampling initialization/kernel_size are chosen to omit checkerboard artifacts as much as possible. (Resize is designed to omit that by nature).\n # To be specific, all initial upsample weights/biases (when NN_init=True) ensure that the upsampling layers act as a \"Nearest neighbor upsample\" of size \"hop_size\" (checkerboard free).\n # 1D spans all frequency bands for each frame (channel-wise) while 2D spans \"freq_axis_kernel_size\" bands at a time. Both are vanilla transpose convolutions.\n # Resize is a 2D convolution that follows a Nearest Neighbor (NN) resize. For reference, this is: \"NN resize->convolution\".\n # SubPixel (2D) is the ICNR version (initialized to be equivalent to \"convolution->NN resize\") of Sub-Pixel convolutions. also called \"checkered artifact free sub-pixel conv\".\n # Finally, NearestNeighbor is a non-trainable upsampling layer that just expands each frame (or \"pixel\") to the equivalent hop size. Ignores all upsampling parameters.\n upsample_type='SubPixel',\n # Type of the upsampling deconvolution. Can be ('1D' or '2D', 'Resize', 'SubPixel' or simple 'NearestNeighbor').\n upsample_activation='Relu', # Activation function used during upsampling. Can be ('LeakyRelu', 'Relu' or None)\n upsample_scales=[11, 25], # prod(upsample_scales) should be equal to hop_size\n freq_axis_kernel_size=3,\n # Only used for 2D upsampling types. This is the number of requency bands that are spanned at a time for each frame.\n leaky_alpha=0.4, # slope of the negative portion of LeakyRelu (LeakyRelu: y=x if x>0 else y=alpha * x)\n NN_init=True,\n # Determines whether we want to initialize upsampling kernels/biases in a way to ensure upsample is initialize to Nearest neighbor upsampling. (Mostly for debug)\n NN_scaler=0.3,\n # Determines the initial Nearest Neighbor upsample values scale. i.e: upscaled_input_values = input_values * NN_scaler (1. to disable)\n\n # global conditioning\n gin_channels=-1,\n # Set this to -1 to disable global conditioning, Only used for multi speaker dataset. It defines the depth of the embeddings (Recommended: 16)\n use_speaker_embedding=True, # whether to make a speaker embedding\n n_speakers=5, # number of speakers (rows of the embedding)\n speakers_path=None,\n # Defines path to speakers metadata. Can be either in \"speaker\\tglobal_id\" (with header) tsv format, or a single column tsv with speaker names. If None, use \"speakers\".\n speakers=['speaker0', 'speaker1',\n # List of speakers used for embeddings visualization. (Consult \"wavenet_vocoder/train.py\" if you want to modify the speaker names source).\n 'speaker2', 'speaker3', 'speaker4'],\n # Must be consistent with speaker ids specified for global conditioning for correct visualization.\n ###########################################################################################################################################\n\n # Tacotron Training\n # Reproduction seeds\n tacotron_random_seed=5339,\n # Determines initial graph and operations (i.e: model) random state for reproducibility\n tacotron_data_random_state=1234, # random state for train test split repeatability\n\n # performance parameters\n tacotron_swap_with_cpu=False,\n # Whether to use cpu as support to gpu for decoder computation (Not recommended: may cause major slowdowns! Only use when critical!)\n\n # train/test split ratios, mini-batches sizes\n tacotron_batch_size=32, # number of training samples on each training steps\n # Tacotron Batch synthesis supports ~16x the training batch size (no gradients during testing).\n # Training Tacotron with unmasked paddings makes it aware of them, which makes synthesis times different from training. We thus recommend masking the encoder.\n tacotron_synthesis_batch_size=1,\n # DO NOT MAKE THIS BIGGER THAN 1 IF YOU DIDN'T TRAIN TACOTRON WITH \"mask_encoder=True\"!!\n tacotron_test_size=0.05,\n # % of data to keep as test data, if None, tacotron_test_batches must be not None. (5% is enough to have a good idea about overfit)\n tacotron_test_batches=None, # number of test batches.\n\n # Learning rate schedule\n tacotron_decay_learning_rate=True, # boolean, determines if the learning rate will follow an exponential decay\n tacotron_start_decay=40000, # Step at which learning decay starts\n tacotron_decay_steps=18000, # Determines the learning rate decay slope (UNDER TEST)\n tacotron_decay_rate=0.5, # learning rate decay rate (UNDER TEST)\n tacotron_initial_learning_rate=1e-3, # starting learning rate\n tacotron_final_learning_rate=1e-4, # minimal learning rate\n\n # Optimization parameters\n tacotron_adam_beta1=0.9, # AdamOptimizer beta1 parameter\n tacotron_adam_beta2=0.999, # AdamOptimizer beta2 parameter\n tacotron_adam_epsilon=1e-6, # AdamOptimizer Epsilon parameter\n\n # Regularization parameters\n tacotron_reg_weight=1e-6, # regularization weight (for L2 regularization)\n tacotron_scale_regularization=False,\n # Whether to rescale regularization weight to adapt for outputs range (used when reg_weight is high and biasing the model)\n tacotron_zoneout_rate=0.1, # zoneout rate for all LSTM cells in the network\n tacotron_dropout_rate=0.5, # dropout rate for all convolutional layers + prenet\n tacotron_clip_gradients=True, # whether to clip gradients\n\n # Evaluation parameters\n tacotron_natural_eval=False,\n # Whether to use 100% natural eval (to evaluate Curriculum Learning performance) or with same teacher-forcing ratio as in training (just for overfit)\n\n # Decoder RNN learning can take be done in one of two ways:\n #\tTeacher Forcing: vanilla teacher forcing (usually with ratio = 1). mode='constant'\n #\tScheduled Sampling Scheme: From Teacher-Forcing to sampling from previous outputs is function of global step. (teacher forcing ratio decay) mode='scheduled'\n # The second approach is inspired by:\n # Bengio et al. 2015: Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks.\n # Can be found under: https://arxiv.org/pdf/1506.03099.pdf\n tacotron_teacher_forcing_mode='constant',\n # Can be ('constant' or 'scheduled'). 'scheduled' mode applies a cosine teacher forcing ratio decay. (Preference: scheduled)\n tacotron_teacher_forcing_ratio=1.,\n # Value from [0., 1.], 0.=0%, 1.=100%, determines the % of times we force next decoder inputs, Only relevant if mode='constant'\n tacotron_teacher_forcing_init_ratio=1., # initial teacher forcing ratio. Relevant if mode='scheduled'\n tacotron_teacher_forcing_final_ratio=0.,\n # final teacher forcing ratio. (Set None to use alpha instead) Relevant if mode='scheduled'\n tacotron_teacher_forcing_start_decay=10000,\n # starting point of teacher forcing ratio decay. Relevant if mode='scheduled'\n tacotron_teacher_forcing_decay_steps=40000,\n # Determines the teacher forcing ratio decay slope. Relevant if mode='scheduled'\n tacotron_teacher_forcing_decay_alpha=None,\n # teacher forcing ratio decay rate. Defines the final tfr as a ratio of initial tfr. Relevant if mode='scheduled'\n\n # Speaker adaptation parameters\n tacotron_fine_tuning=False,\n # Set to True to freeze encoder and only keep training pretrained decoder. Used for speaker adaptation with small data.\n ###########################################################################################################################################\n\n # Wavenet Training\n wavenet_random_seed=5339, # S=5, E=3, D=9 :)\n wavenet_data_random_state=1234, # random state for train test split repeatability\n\n # performance parameters\n wavenet_swap_with_cpu=False,\n # Whether to use cpu as support to gpu for synthesis computation (while loop).(Not recommended: may cause major slowdowns! Only use when critical!)\n\n # train/test split ratios, mini-batches sizes\n wavenet_batch_size=8, # batch size used to train wavenet.\n # During synthesis, there is no max_time_steps limitation so the model can sample much longer audio than 8k(or 13k) steps. (Audio can go up to 500k steps, equivalent to ~21sec on 24kHz)\n # Usually your GPU can handle ~2x wavenet_batch_size during synthesis for the same memory amount during training (because no gradients to keep and ops to register for backprop)\n wavenet_synthesis_batch_size=10 * 2,\n # This ensure that wavenet synthesis goes up to 4x~8x faster when synthesizing multiple sentences. Watch out for OOM with long audios.\n wavenet_test_size=None, # % of data to keep as test data, if None, wavenet_test_batches must be not None\n wavenet_test_batches=1, # number of test batches.\n\n # Learning rate schedule\n wavenet_lr_schedule='exponential', # learning rate schedule. Can be ('exponential', 'noam')\n wavenet_learning_rate=1e-3, # wavenet initial learning rate\n wavenet_warmup=float(4000), # Only used with 'noam' scheme. Defines the number of ascending learning rate steps.\n wavenet_decay_rate=0.5, # Only used with 'exponential' scheme. Defines the decay rate.\n wavenet_decay_steps=200000, # Only used with 'exponential' scheme. Defines the decay steps.\n\n # Optimization parameters\n wavenet_adam_beta1=0.9, # Adam beta1\n wavenet_adam_beta2=0.999, # Adam beta2\n wavenet_adam_epsilon=1e-6, # Adam Epsilon\n\n # Regularization parameters\n wavenet_clip_gradients=True, # Whether the clip the gradients during wavenet training.\n wavenet_ema_decay=0.9999, # decay rate of exponential moving average\n wavenet_weight_normalization=False,\n # Whether to Apply Saliman & Kingma Weight Normalization (reparametrization) technique. (Used in DeepVoice3, not critical here)\n wavenet_init_scale=1.,\n # Only relevent if weight_normalization=True. Defines the initial scale in data dependent initialization of parameters.\n wavenet_dropout=0.05, # drop rate of wavenet layers\n wavenet_gradient_max_norm=100.0, # Norm used to clip wavenet gradients\n wavenet_gradient_max_value=5.0, # Value used to clip wavenet gradients\n\n # training samples length\n max_time_sec=None, # Max time of audio for training. If None, we use max_time_steps.\n max_time_steps=11000,\n # Max time steps in audio used to train wavenet (decrease to save memory) (Recommend: 8000 on modest GPUs, 13000 on stronger ones)\n\n # Evaluation parameters\n wavenet_natural_eval=False,\n # Whether to use 100% natural eval (to evaluate autoregressivity performance) or with teacher forcing to evaluate overfit and model consistency.\n\n # Tacotron-2 integration parameters\n train_with_GTA=True, # Whether to use GTA mels to train WaveNet instead of ground truth mels.\n ###########################################################################################################################################\n\n # Eval/Debug parameters\n # Eval sentences (if no eval text file was specified during synthesis, these sentences are used for eval)\n sentences=[\n 'Handballer setzen mit Training aus',\n 'Weil die Einsicht bei den Verantwortlichen spät kam',\n 'Die geforderte Kehrtwende war am Ende unausweichlich',\n 'Wir haben uns am Nachmittag dazu entschieden',\n 'Er plädierte zugleich für eine Absage der Ende März geplanten',\n 'Für die prestigeträchtigen Spiele hat Japan aus der Staatskasse Milliarden investiert und laut Aussagen',\n 'Mit einem eindringlichen Appell an Kunden und Politik',\n 'Knapp eine halbe Million Nutzerinnen und Nutzer sahen binnen'\n ],\n\n # Wavenet Debug\n wavenet_synth_debug=False, # Set True to use target as debug in WaveNet synthesis.\n wavenet_debug_wavs=['training_data/audio/audio-alter_afrikaner_01_f000008.npy'],\n # Path to debug audios. Must be multiple of wavenet_num_gpus.\n wavenet_debug_mels=['training_data/mels/mel-alter_afrikaner_01_f000008.npy'],\n # Path to corresponding mels. Must be of same length and order as wavenet_debug_wavs.\n)\n\n\ndef hparams_debug_string():\n values = hparams.values()\n hp = [' %s: %s' % (name, values[name]) for name in sorted(values) if name != 'sentences']\n return 'Hyperparameters:\\n' + '\\n'.join(hp)\n" ]
[ [ "numpy.log" ] ]
Slavkata/Forecast-Report
[ "3cfeac5ab6b60ad32e1b9433b3281b5336373c30" ]
[ "PastYearFeatures/setup.py" ]
[ "import pandas as p\nimport numpy as np\nfrom file_setup_helper import FileSetupHelper as fsh\nfrom preprocess_data import PreprocessData as pd\nfrom model_export import ModelExport as me\nimport sys\nfrom sklearn.linear_model import Ridge\n\ndef main():\n #call for file download with given date\n file_name = fsh(sys.argv[1], 1460, 0).download_csv()\n\n #aquire features and target data filenames\n features_file_name, target_file_name = pd(file_name).preprocess(True, None)\n\n #init model, and open the features and target file\n #(drop column added by pandas and bypass 29.02 potential error)\n model = Ridge(alpha=1, fit_intercept=True)\n X_train = p.read_csv(features_file_name).drop(['Unnamed: 0', 'Date_29.02'], axis=1)\n y_train = p.read_csv(target_file_name).drop(['Unnamed: 0'], axis=1)\n\n #export model with the given datasets and model\n me(model, X_train, y_train).fit_and_export(sys.argv[2])\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.read_csv", "sklearn.linear_model.Ridge" ] ]
Elscha/MetricsML
[ "2ecbc42ad7bd2465f4f75658f44452ea5c552c3b" ]
[ "metricsML/Normalizator.py" ]
[ "from metricsML.NormalizationType import NormalizationType\nimport numpy as np\nimport math\n\ndef normalization(normalization, train_data, test_data, validation_data=None):\n if not isinstance(normalization, NormalizationType):\n print(\"Unknown normalization specified, use \" + str(NormalizationType.PERCENTAGE) + \" for normalizing data\")\n normalization = NormalizationType.PERCENTAGE;\n \n if (normalization is NormalizationType.NO_NORMALIZATION):\n print(\"No normalization selected\")\n elif (normalization is NormalizationType.PERCENTAGE):\n __percentageNormalization(train_data, test_data, validation_data)\n elif (normalization is NormalizationType.LOGARITHM):\n __logarithmNormalization(train_data, test_data, validation_data)\n else:\n raise TypeError(\"Unhandled normalization selected\")\n\n\ndef __percentageNormalization(train_data, test_data, validation_data=None):\n nColumns = train_data.shape[1] if len(train_data.shape) == 2 else 0;\n train_max = np.amax(train_data, axis=0)\n test_max = np.amax(test_data, axis=0)\n if (validation_data is not None):\n validation_max = np.amax(validation_data, axis=0)\n else:\n validation_max = np.zeros(nColumns)\n \n max_vector = np.amax([train_max, test_max, validation_max], axis=0)\n \n train_data = train_data/max_vector\n test_data = test_data/max_vector\n \n if (validation_data is not None):\n validation_data = validation_data/max_vector\n \ndef __logarithmNormalization(train_data, test_data, validation_data=None):\n nColumns = train_data.shape[1] if len(train_data.shape) == 2 else 0;\n train_max = np.amax(train_data, axis=0)\n test_max = np.amax(test_data, axis=0)\n if (validation_data is not None):\n validation_max = np.amax(validation_data, axis=0)\n else:\n validation_max = np.zeros(nColumns)\n \n max_vector = np.amax([train_max, test_max, validation_max], axis=0)\n \n for column in range(0, nColumns):\n max_value = max_vector[column]\n if (max_value > 1):\n train_data[:, column] = [__positiveLogarithm(x) for x in train_data[:, column]]\n test_data[:, column] = [__positiveLogarithm(x) for x in test_data[:, column]]\n if (validation_data is not None):\n validation_data[:, column] = [__positiveLogarithm(x) for x in validation_data[:, column]]\n\ndef __positiveLogarithm(number, base):\n if (number > 1):\n return math.log(number, base)\n else:\n return 0" ]
[ [ "numpy.amax", "numpy.zeros" ] ]
int-brain-lab/ONE
[ "8766cd27308ddc2c247acb56685be3b2ce204390" ]
[ "one/tests/util.py" ]
[ "\"\"\"Utilities functions for setting up test fixtures.\"\"\"\nimport tempfile\nfrom pathlib import Path\nimport shutil\nimport json\nfrom uuid import uuid4\n\nimport pandas as pd\nimport numpy as np\nfrom iblutil.io.parquet import uuid2np, np2str\n\nimport one.params\n\n\ndef set_up_env(use_temp_cache=True) -> tempfile.TemporaryDirectory:\n \"\"\"\n Create a temporary directory and copy cache fixtures over.\n\n Parameters\n ----------\n use_temp_cache : bool\n If True, copies REST cache fixtures to the temporary directory, otherwise they are copied\n to the directory returned by one.params.get_params_dir\n\n Returns\n -------\n tempfile.TemporaryDirectory\n The temporary directory containing the test ONE caches\n\n \"\"\"\n fixture = Path(__file__).parent.joinpath('fixtures')\n tempdir = tempfile.TemporaryDirectory()\n # Copy cache files to temporary directory\n for cache_file in ('sessions', 'datasets'):\n filename = shutil.copy(fixture / f'{cache_file}.pqt', tempdir.name)\n assert Path(filename).exists()\n\n # Copy cached rest responses\n rest_cache_location = Path(tempdir.name) / '.one' if use_temp_cache else None\n setup_rest_cache(rest_cache_location)\n\n return tempdir\n\n\ndef setup_rest_cache(param_dir=None):\n \"\"\"Copy REST cache fixtures to the .one parameter directory.\n\n Parameters\n ----------\n param_dir : str, pathlib.Path\n The location of the ONE params directory (e.g. ~/.one)\n\n \"\"\"\n fixture = Path(__file__).parent.joinpath('fixtures')\n path_parts = ('.rest', 'test.alyx.internationalbrainlab.org', 'https')\n rest_cache_dir = Path(param_dir or one.params.get_params_dir()).joinpath(*path_parts)\n\n # Ensure empty\n shutil.rmtree(rest_cache_dir, ignore_errors=True)\n rest_cache_dir.mkdir(parents=True, exist_ok=True)\n # Copy over fixtures\n for file in fixture.joinpath('rest_responses').glob('*'):\n filename = shutil.copy(file, rest_cache_dir)\n assert Path(filename).exists()\n\n\ndef create_file_tree(one):\n \"\"\"Touch all the files in the datasets table.\n\n Parameters\n ----------\n one : one.api.One\n An instance of One containing cache tables to use.\n\n \"\"\"\n # Create dset files from cache\n for session_path, rel_path in one._cache.datasets[['session_path', 'rel_path']].values:\n filepath = Path(one.cache_dir).joinpath(session_path, rel_path)\n filepath.parent.mkdir(exist_ok=True, parents=True)\n filepath.touch()\n\n\ndef setup_test_params(token=False, cache_dir=None):\n \"\"\"\n Copies cache parameter fixture to .one directory.\n\n Parameters\n ----------\n token : bool\n If true, save a token file so that client doesn't hit auth endpoint\n cache_dir : str, pathlib.Path\n The cache_dir to save\n\n \"\"\"\n params_dir = Path(one.params.get_params_dir())\n fixture = Path(__file__).parent.joinpath('fixtures')\n test_pars = '.test.alyx.internationalbrainlab.org'\n if not list(params_dir.glob(test_pars)):\n filename = shutil.copy(fixture / 'params' / test_pars, params_dir)\n assert Path(filename).exists()\n\n # Add to cache map\n map_file = params_dir / '.caches'\n if not map_file.exists():\n shutil.copy(fixture / 'params' / '.caches', map_file)\n assert Path(filename).exists()\n with open(map_file, 'r+') as f:\n data = json.load(f)\n data['CLIENT_MAP'][test_pars[1:]] = str(cache_dir or '')\n f.seek(0)\n json.dump(data, f)\n f.truncate()\n\n # Add token to file so db not hit\n if token:\n pars = one.params.get(client=test_pars[1:])\n if not getattr(pars, 'TOKEN', False):\n one.params.save(pars.set('TOKEN', {'token': 'T0k3N'}), test_pars[1:])\n\n\ndef revisions_datasets_table(collections=('', 'alf/probe00', 'alf/probe01'),\n revisions=('', '2020-01-08', '2021-07-06'),\n object='spikes',\n attributes=('times', 'waveforems')):\n \"\"\"Returns a datasets cache DataFrame containing datasets with revision folders.\n\n As there are no revised datasets on the test databases, this function acts as a fixture for\n testing the filtering of datasets by a revision.\n\n Parameters\n ----------\n collections : tuple\n A list of collections\n revisions : tuple\n A list of revisions\n object : str\n An ALF object\n attributes : tuple\n A list of ALF attributes\n\n Returns\n -------\n pd.DataFrame\n A datasets cache table containing datasets made from the input names\n\n \"\"\"\n rel_path = []\n for attr in attributes:\n for collec in collections:\n for rev in (f'#{x}#' if x else '' for x in revisions):\n rel_path.append('/'.join(x for x in (collec, rev, f'{object}.{attr}.npy') if x))\n ids = uuid2np([uuid4() for _ in range(len(rel_path))])\n eid_0, eid_1 = uuid2np([uuid4()])[0]\n\n return pd.DataFrame(data={\n 'rel_path': rel_path,\n 'session_path': 'subject/1900-01-01/001',\n 'file_size': None,\n 'hash': None,\n 'eid_0': eid_0,\n 'eid_1': eid_1\n }, index=[ids[:, 0], ids[:, 1]])\n\n\ndef create_schema_cache(param_dir=None):\n \"\"\"Save REST cache file for docs/ endpoint.\n\n Ensures the database isn't hit when the rest_schemas property is accessed.\n\n Parameters\n ----------\n param_dir : str, pathlib.Path\n The location of the parameter directory. If None, the default one is used.\n\n \"\"\"\n actions = dict.fromkeys(['list', 'read', 'create', 'update', 'partial_update', 'delete'])\n endpoints = ['cache', 'dataset-types', 'datasets', 'downloads', 'insertions', 'sessions']\n path_parts = ('.rest', 'test.alyx.internationalbrainlab.org', 'https')\n rest_cache_dir = Path(param_dir or one.params.get_params_dir()).joinpath(*path_parts)\n with open(rest_cache_dir / '1baff95c2d0e31059720a3716ad5b5a34b61a207', 'r') as f:\n json.dump({k: actions for k in endpoints}, f)\n\n\ndef get_file(root: str, str_id: str) -> str:\n \"\"\"\n A stub function for iblutil.io.params.getfile. Allows the injection of a different param dir.\n\n Parameters\n ----------\n root : str, pathlib.Path\n The root directory of the new parameters\n str_id : str\n The parameter string identifier\n\n Returns\n -------\n str\n The parameter file path\n\n \"\"\"\n parts = ['.' + p if not p.startswith('.') else p for p in Path(str_id).parts]\n pfile = Path(root, *parts).as_posix()\n return pfile\n\n\ndef caches_int2str(caches):\n \"\"\"Convert int ids to str ids for cache tables.\n\n Parameters\n ----------\n caches : Bunch\n A bunch of cache tables (from One._cache)\n\n \"\"\"\n for table in ('sessions', 'datasets'):\n # Set integer uuids to NaN\n cache = caches[table].reset_index()\n int_cols = cache.filter(regex=r'_\\d{1}$').columns\n for i in range(0, len(int_cols), 2):\n name = int_cols.values[i].rsplit('_', 1)[0]\n cache[name] = np2str(cache[int_cols[i:i + 2]])\n cache[int_cols] = np.nan\n caches[table] = cache.set_index('id')\n" ]
[ [ "pandas.DataFrame" ] ]
mduranmustafa/keras
[ "c458024d5c379ef990f72b6f6b738301e1895cff" ]
[ "tests/keras/layers/recurrent_test.py" ]
[ "import pytest\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nimport keras\nfrom keras.utils.test_utils import layer_test\nfrom keras.utils.test_utils import keras_test\nfrom keras.layers import recurrent\nfrom keras.layers import embeddings\nfrom keras.models import Sequential\nfrom keras.models import Model\nfrom keras.engine.topology import Input\nfrom keras.layers.core import Masking\nfrom keras import regularizers\nfrom keras import backend as K\n\nnum_samples, timesteps, embedding_dim, units = 2, 5, 4, 3\nembedding_num = 12\n\n\n@keras_test\ndef rnn_test(f):\n \"\"\"\n All the recurrent layers share the same interface,\n so we can run through them with a single function.\n \"\"\"\n f = keras_test(f)\n return pytest.mark.parametrize('layer_class', [\n recurrent.SimpleRNN,\n recurrent.GRU,\n recurrent.LSTM\n ])(f)\n\n\n@rnn_test\ndef test_return_sequences(layer_class):\n layer_test(layer_class,\n kwargs={'units': units,\n 'return_sequences': True},\n input_shape=(num_samples, timesteps, embedding_dim))\n\n\n@rnn_test\ndef test_dynamic_behavior(layer_class):\n layer = layer_class(units, input_shape=(None, embedding_dim))\n model = Sequential()\n model.add(layer)\n model.compile('sgd', 'mse')\n x = np.random.random((num_samples, timesteps, embedding_dim))\n y = np.random.random((num_samples, units))\n model.train_on_batch(x, y)\n\n\n@rnn_test\ndef test_stateful_invalid_use(layer_class):\n layer = layer_class(units,\n stateful=True,\n batch_input_shape=(num_samples,\n timesteps,\n embedding_dim))\n model = Sequential()\n model.add(layer)\n model.compile('sgd', 'mse')\n x = np.random.random((num_samples * 2, timesteps, embedding_dim))\n y = np.random.random((num_samples * 2, units))\n with pytest.raises(ValueError):\n model.fit(x, y)\n with pytest.raises(ValueError):\n model.predict(x, batch_size=num_samples + 1)\n\n\n@rnn_test\[email protected]((K.backend() == 'cntk'),\n reason='Not yet supported.')\ndef test_dropout(layer_class):\n for unroll in [True, False]:\n layer_test(layer_class,\n kwargs={'units': units,\n 'dropout': 0.1,\n 'recurrent_dropout': 0.1,\n 'unroll': unroll},\n input_shape=(num_samples, timesteps, embedding_dim))\n\n # Test that dropout is applied during training\n x = K.ones((num_samples, timesteps, embedding_dim))\n layer = layer_class(units, dropout=0.5, recurrent_dropout=0.5,\n input_shape=(timesteps, embedding_dim))\n y = layer(x)\n assert y._uses_learning_phase\n\n y = layer(x, training=True)\n assert not getattr(y, '_uses_learning_phase')\n\n # Test that dropout is not applied during testing\n x = np.random.random((num_samples, timesteps, embedding_dim))\n layer = layer_class(units, dropout=0.5, recurrent_dropout=0.5,\n unroll=unroll,\n input_shape=(timesteps, embedding_dim))\n model = Sequential([layer])\n assert model.uses_learning_phase\n y1 = model.predict(x)\n y2 = model.predict(x)\n assert_allclose(y1, y2)\n\n\n@rnn_test\ndef test_statefulness(layer_class):\n model = Sequential()\n model.add(embeddings.Embedding(embedding_num, embedding_dim,\n mask_zero=True,\n input_length=timesteps,\n batch_input_shape=(num_samples, timesteps)))\n layer = layer_class(units, return_sequences=False,\n stateful=True,\n weights=None)\n model.add(layer)\n model.compile(optimizer='sgd', loss='mse')\n out1 = model.predict(np.ones((num_samples, timesteps)))\n assert(out1.shape == (num_samples, units))\n\n # train once so that the states change\n model.train_on_batch(np.ones((num_samples, timesteps)),\n np.ones((num_samples, units)))\n out2 = model.predict(np.ones((num_samples, timesteps)))\n\n # if the state is not reset, output should be different\n assert(out1.max() != out2.max())\n\n # check that output changes after states are reset\n # (even though the model itself didn't change)\n layer.reset_states()\n out3 = model.predict(np.ones((num_samples, timesteps)))\n assert(out2.max() != out3.max())\n\n # check that container-level reset_states() works\n model.reset_states()\n out4 = model.predict(np.ones((num_samples, timesteps)))\n assert_allclose(out3, out4, atol=1e-5)\n\n # check that the call to `predict` updated the states\n out5 = model.predict(np.ones((num_samples, timesteps)))\n assert(out4.max() != out5.max())\n\n\n@rnn_test\ndef test_masking_correctness(layer_class):\n # Check masking: output with left padding and right padding\n # should be the same.\n model = Sequential()\n model.add(embeddings.Embedding(embedding_num, embedding_dim,\n mask_zero=True,\n input_length=timesteps,\n batch_input_shape=(num_samples, timesteps)))\n layer = layer_class(units, return_sequences=False)\n model.add(layer)\n model.compile(optimizer='sgd', loss='mse')\n\n left_padded_input = np.ones((num_samples, timesteps))\n left_padded_input[0, :1] = 0\n left_padded_input[1, :2] = 0\n out6 = model.predict(left_padded_input)\n\n right_padded_input = np.ones((num_samples, timesteps))\n right_padded_input[0, -1:] = 0\n right_padded_input[1, -2:] = 0\n out7 = model.predict(right_padded_input)\n\n assert_allclose(out7, out6, atol=1e-5)\n\n\n@rnn_test\ndef test_implementation_mode(layer_class):\n for mode in [1, 2]:\n # Without dropout\n layer_test(layer_class,\n kwargs={'units': units,\n 'implementation': mode},\n input_shape=(num_samples, timesteps, embedding_dim))\n # With dropout\n layer_test(layer_class,\n kwargs={'units': units,\n 'implementation': mode,\n 'dropout': 0.1,\n 'recurrent_dropout': 0.1},\n input_shape=(num_samples, timesteps, embedding_dim))\n # Without bias\n layer_test(layer_class,\n kwargs={'units': units,\n 'implementation': mode,\n 'use_bias': False},\n input_shape=(num_samples, timesteps, embedding_dim))\n\n\n@rnn_test\ndef test_regularizer(layer_class):\n layer = layer_class(units, return_sequences=False, weights=None,\n input_shape=(timesteps, embedding_dim),\n kernel_regularizer=regularizers.l1(0.01),\n recurrent_regularizer=regularizers.l1(0.01),\n bias_regularizer='l2')\n layer.build((None, None, embedding_dim))\n assert len(layer.losses) == 3\n assert len(layer.cell.losses) == 3\n\n layer = layer_class(units, return_sequences=False, weights=None,\n input_shape=(timesteps, embedding_dim),\n activity_regularizer='l2')\n assert layer.activity_regularizer\n x = K.variable(np.ones((num_samples, timesteps, embedding_dim)))\n layer(x)\n assert len(layer.cell.get_losses_for(x)) == 0\n assert len(layer.get_losses_for(x)) == 1\n\n\n@rnn_test\ndef test_trainability(layer_class):\n layer = layer_class(units)\n layer.build((None, None, embedding_dim))\n assert len(layer.weights) == 3\n assert len(layer.trainable_weights) == 3\n assert len(layer.non_trainable_weights) == 0\n layer.trainable = False\n assert len(layer.weights) == 3\n assert len(layer.trainable_weights) == 0\n assert len(layer.non_trainable_weights) == 3\n layer.trainable = True\n assert len(layer.weights) == 3\n assert len(layer.trainable_weights) == 3\n assert len(layer.non_trainable_weights) == 0\n\n\n@keras_test\ndef test_masking_layer():\n ''' This test based on a previously failing issue here:\n https://github.com/fchollet/keras/issues/1567\n '''\n inputs = np.random.random((6, 3, 4))\n targets = np.abs(np.random.random((6, 3, 5)))\n targets /= targets.sum(axis=-1, keepdims=True)\n\n model = Sequential()\n model.add(Masking(input_shape=(3, 4)))\n model.add(recurrent.SimpleRNN(units=5, return_sequences=True, unroll=False))\n model.compile(loss='categorical_crossentropy', optimizer='adam')\n model.fit(inputs, targets, epochs=1, batch_size=100, verbose=1)\n\n model = Sequential()\n model.add(Masking(input_shape=(3, 4)))\n model.add(recurrent.SimpleRNN(units=5, return_sequences=True, unroll=True))\n model.compile(loss='categorical_crossentropy', optimizer='adam')\n model.fit(inputs, targets, epochs=1, batch_size=100, verbose=1)\n\n\n@rnn_test\ndef test_from_config(layer_class):\n stateful_flags = (False, True)\n for stateful in stateful_flags:\n l1 = layer_class(units=1, stateful=stateful)\n l2 = layer_class.from_config(l1.get_config())\n assert l1.get_config() == l2.get_config()\n\n\n@rnn_test\ndef test_specify_initial_state_keras_tensor(layer_class):\n num_states = 2 if layer_class is recurrent.LSTM else 1\n\n # Test with Keras tensor\n inputs = Input((timesteps, embedding_dim))\n initial_state = [Input((units,)) for _ in range(num_states)]\n layer = layer_class(units)\n if len(initial_state) == 1:\n output = layer(inputs, initial_state=initial_state[0])\n else:\n output = layer(inputs, initial_state=initial_state)\n assert initial_state[0] in layer.inbound_nodes[0].input_tensors\n\n model = Model([inputs] + initial_state, output)\n model.compile(loss='categorical_crossentropy', optimizer='adam')\n\n inputs = np.random.random((num_samples, timesteps, embedding_dim))\n initial_state = [np.random.random((num_samples, units))\n for _ in range(num_states)]\n targets = np.random.random((num_samples, units))\n model.fit([inputs] + initial_state, targets)\n\n\n@rnn_test\ndef test_specify_initial_state_non_keras_tensor(layer_class):\n num_states = 2 if layer_class is recurrent.LSTM else 1\n\n # Test with non-Keras tensor\n inputs = Input((timesteps, embedding_dim))\n initial_state = [K.random_normal_variable((num_samples, units), 0, 1)\n for _ in range(num_states)]\n layer = layer_class(units)\n output = layer(inputs, initial_state=initial_state)\n\n model = Model(inputs, output)\n model.compile(loss='categorical_crossentropy', optimizer='adam')\n\n inputs = np.random.random((num_samples, timesteps, embedding_dim))\n targets = np.random.random((num_samples, units))\n model.fit(inputs, targets)\n\n\n@rnn_test\ndef test_reset_states_with_values(layer_class):\n num_states = 2 if layer_class is recurrent.LSTM else 1\n\n layer = layer_class(units, stateful=True)\n layer.build((num_samples, timesteps, embedding_dim))\n layer.reset_states()\n assert len(layer.states) == num_states\n assert layer.states[0] is not None\n np.testing.assert_allclose(K.eval(layer.states[0]),\n np.zeros(K.int_shape(layer.states[0])),\n atol=1e-4)\n state_shapes = [K.int_shape(state) for state in layer.states]\n values = [np.ones(shape) for shape in state_shapes]\n if len(values) == 1:\n values = values[0]\n layer.reset_states(values)\n np.testing.assert_allclose(K.eval(layer.states[0]),\n np.ones(K.int_shape(layer.states[0])),\n atol=1e-4)\n\n # Test fit with invalid data\n with pytest.raises(ValueError):\n layer.reset_states([1] * (len(layer.states) + 1))\n\n\n@rnn_test\ndef test_initial_states_as_other_inputs(layer_class):\n num_states = 2 if layer_class is recurrent.LSTM else 1\n\n # Test with Keras tensor\n main_inputs = Input((timesteps, embedding_dim))\n initial_state = [Input((units,)) for _ in range(num_states)]\n inputs = [main_inputs] + initial_state\n\n layer = layer_class(units)\n output = layer(inputs)\n assert initial_state[0] in layer.inbound_nodes[0].input_tensors\n\n model = Model(inputs, output)\n model.compile(loss='categorical_crossentropy', optimizer='adam')\n\n main_inputs = np.random.random((num_samples, timesteps, embedding_dim))\n initial_state = [np.random.random((num_samples, units))\n for _ in range(num_states)]\n targets = np.random.random((num_samples, units))\n model.train_on_batch([main_inputs] + initial_state, targets)\n\n\n@rnn_test\ndef test_specify_state_with_masking(layer_class):\n ''' This test based on a previously failing issue here:\n https://github.com/fchollet/keras/issues/1567\n '''\n num_states = 2 if layer_class is recurrent.LSTM else 1\n\n inputs = Input((timesteps, embedding_dim))\n _ = Masking()(inputs)\n initial_state = [Input((units,)) for _ in range(num_states)]\n output = layer_class(units)(inputs, initial_state=initial_state)\n\n model = Model([inputs] + initial_state, output)\n model.compile(loss='categorical_crossentropy', optimizer='adam')\n\n inputs = np.random.random((num_samples, timesteps, embedding_dim))\n initial_state = [np.random.random((num_samples, units))\n for _ in range(num_states)]\n targets = np.random.random((num_samples, units))\n model.fit([inputs] + initial_state, targets)\n\n\n@rnn_test\ndef test_return_state(layer_class):\n num_states = 2 if layer_class is recurrent.LSTM else 1\n\n inputs = Input(batch_shape=(num_samples, timesteps, embedding_dim))\n layer = layer_class(units, return_state=True, stateful=True)\n outputs = layer(inputs)\n output, state = outputs[0], outputs[1:]\n assert len(state) == num_states\n model = Model(inputs, state[0])\n\n inputs = np.random.random((num_samples, timesteps, embedding_dim))\n state = model.predict(inputs)\n np.testing.assert_allclose(K.eval(layer.states[0]), state, atol=1e-4)\n\n\n@rnn_test\ndef test_state_reuse(layer_class):\n inputs = Input(batch_shape=(num_samples, timesteps, embedding_dim))\n layer = layer_class(units, return_state=True, return_sequences=True)\n outputs = layer(inputs)\n output, state = outputs[0], outputs[1:]\n output = layer_class(units)(output, initial_state=state)\n model = Model(inputs, output)\n\n inputs = np.random.random((num_samples, timesteps, embedding_dim))\n outputs = model.predict(inputs)\n\n\n@keras_test\ndef test_minimal_rnn_cell_non_layer():\n\n class MinimalRNNCell(object):\n\n def __init__(self, units, input_dim):\n self.units = units\n self.state_size = units\n self.kernel = keras.backend.variable(\n np.random.random((input_dim, units)))\n\n def call(self, inputs, states):\n prev_output = states[0]\n output = keras.backend.dot(inputs, self.kernel) + prev_output\n return output, [output]\n\n # Basic test case.\n cell = MinimalRNNCell(32, 5)\n x = keras.Input((None, 5))\n layer = recurrent.RNN(cell)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32)))\n\n # Test stacking.\n cells = [MinimalRNNCell(8, 5),\n MinimalRNNCell(32, 8),\n MinimalRNNCell(32, 32)]\n layer = recurrent.RNN(cells)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32)))\n\n\n@keras_test\ndef test_minimal_rnn_cell_non_layer_multiple_states():\n\n class MinimalRNNCell(object):\n\n def __init__(self, units, input_dim):\n self.units = units\n self.state_size = (units, units)\n self.kernel = keras.backend.variable(\n np.random.random((input_dim, units)))\n\n def call(self, inputs, states):\n prev_output_1 = states[0]\n prev_output_2 = states[1]\n output = keras.backend.dot(inputs, self.kernel)\n output += prev_output_1\n output -= prev_output_2\n return output, [output * 2, output * 3]\n\n # Basic test case.\n cell = MinimalRNNCell(32, 5)\n x = keras.Input((None, 5))\n layer = recurrent.RNN(cell)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32)))\n\n # Test stacking.\n cells = [MinimalRNNCell(8, 5),\n MinimalRNNCell(16, 8),\n MinimalRNNCell(32, 16)]\n layer = recurrent.RNN(cells)\n assert layer.cell.state_size == (32, 32, 16, 16, 8, 8)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32)))\n\n\n@keras_test\ndef test_minimal_rnn_cell_layer():\n\n class MinimalRNNCell(keras.layers.Layer):\n\n def __init__(self, units, **kwargs):\n self.units = units\n self.state_size = units\n super(MinimalRNNCell, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(shape=(input_shape[-1], self.units),\n initializer='uniform',\n name='kernel')\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units),\n initializer='uniform',\n name='recurrent_kernel')\n self.built = True\n\n def call(self, inputs, states):\n prev_output = states[0]\n h = keras.backend.dot(inputs, self.kernel)\n output = h + keras.backend.dot(prev_output, self.recurrent_kernel)\n return output, [output]\n\n def get_config(self):\n config = {'units': self.units}\n base_config = super(MinimalRNNCell, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n # Test basic case.\n x = keras.Input((None, 5))\n cell = MinimalRNNCell(32)\n layer = recurrent.RNN(cell)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32)))\n\n # Test basic case serialization.\n x_np = np.random.random((6, 5, 5))\n y_np = model.predict(x_np)\n weights = model.get_weights()\n config = layer.get_config()\n with keras.utils.CustomObjectScope({'MinimalRNNCell': MinimalRNNCell}):\n layer = recurrent.RNN.from_config(config)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.set_weights(weights)\n y_np_2 = model.predict(x_np)\n assert_allclose(y_np, y_np_2, atol=1e-4)\n\n # Test stacking.\n cells = [MinimalRNNCell(8),\n MinimalRNNCell(12),\n MinimalRNNCell(32)]\n layer = recurrent.RNN(cells)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(np.zeros((6, 5, 5)), np.zeros((6, 32)))\n\n # Test stacked RNN serialization.\n x_np = np.random.random((6, 5, 5))\n y_np = model.predict(x_np)\n weights = model.get_weights()\n config = layer.get_config()\n with keras.utils.CustomObjectScope({'MinimalRNNCell': MinimalRNNCell}):\n layer = recurrent.RNN.from_config(config)\n y = layer(x)\n model = keras.models.Model(x, y)\n model.set_weights(weights)\n y_np_2 = model.predict(x_np)\n assert_allclose(y_np, y_np_2, atol=1e-4)\n\n\n@keras_test\ndef test_stacked_rnn_attributes():\n cells = [recurrent.LSTMCell(3),\n recurrent.LSTMCell(3, kernel_regularizer='l2')]\n layer = recurrent.RNN(cells)\n layer.build((None, None, 5))\n\n # Test regularization losses\n assert len(layer.losses) == 1\n\n # Test weights\n assert len(layer.trainable_weights) == 6\n cells[0].trainable = False\n assert len(layer.trainable_weights) == 3\n assert len(layer.non_trainable_weights) == 3\n\n # Test `get_losses_for`\n x = keras.Input((None, 5))\n y = K.sum(x)\n cells[0].add_loss(y, inputs=x)\n assert layer.get_losses_for(x) == [y]\n\n\n@rnn_test\ndef test_batch_size_equal_one(layer_class):\n inputs = Input(batch_shape=(1, timesteps, embedding_dim))\n layer = layer_class(units)\n outputs = layer(inputs)\n model = Model(inputs, outputs)\n model.compile('sgd', 'mse')\n x = np.random.random((1, timesteps, embedding_dim))\n y = np.random.random((1, units))\n model.train_on_batch(x, y)\n\n\ndef test_rnn_cell_with_constants_layer():\n\n class RNNCellWithConstants(keras.layers.Layer):\n\n def __init__(self, units, **kwargs):\n self.units = units\n self.state_size = units\n super(RNNCellWithConstants, self).__init__(**kwargs)\n\n def build(self, input_shape):\n if not isinstance(input_shape, list):\n raise TypeError('expects constants shape')\n [input_shape, constant_shape] = input_shape\n # will (and should) raise if more than one constant passed\n\n self.input_kernel = self.add_weight(\n shape=(input_shape[-1], self.units),\n initializer='uniform',\n name='kernel')\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units),\n initializer='uniform',\n name='recurrent_kernel')\n self.constant_kernel = self.add_weight(\n shape=(constant_shape[-1], self.units),\n initializer='uniform',\n name='constant_kernel')\n self.built = True\n\n def call(self, inputs, states, constants):\n [prev_output] = states\n [constant] = constants\n h_input = keras.backend.dot(inputs, self.input_kernel)\n h_state = keras.backend.dot(prev_output, self.recurrent_kernel)\n h_const = keras.backend.dot(constant, self.constant_kernel)\n output = h_input + h_state + h_const\n return output, [output]\n\n def get_config(self):\n config = {'units': self.units}\n base_config = super(RNNCellWithConstants, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n # Test basic case.\n x = keras.Input((None, 5))\n c = keras.Input((3,))\n cell = RNNCellWithConstants(32)\n layer = recurrent.RNN(cell)\n y = layer(x, constants=c)\n model = keras.models.Model([x, c], y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(\n [np.zeros((6, 5, 5)), np.zeros((6, 3))],\n np.zeros((6, 32))\n )\n\n # Test basic case serialization.\n x_np = np.random.random((6, 5, 5))\n c_np = np.random.random((6, 3))\n y_np = model.predict([x_np, c_np])\n weights = model.get_weights()\n config = layer.get_config()\n custom_objects = {'RNNCellWithConstants': RNNCellWithConstants}\n with keras.utils.CustomObjectScope(custom_objects):\n layer = recurrent.RNN.from_config(config.copy())\n y = layer(x, constants=c)\n model = keras.models.Model([x, c], y)\n model.set_weights(weights)\n y_np_2 = model.predict([x_np, c_np])\n assert_allclose(y_np, y_np_2, atol=1e-4)\n\n # test flat list inputs\n with keras.utils.CustomObjectScope(custom_objects):\n layer = recurrent.RNN.from_config(config.copy())\n y = layer([x, c])\n model = keras.models.Model([x, c], y)\n model.set_weights(weights)\n y_np_3 = model.predict([x_np, c_np])\n assert_allclose(y_np, y_np_3, atol=1e-4)\n\n\ndef test_rnn_cell_with_constants_layer_passing_initial_state():\n\n class RNNCellWithConstants(keras.layers.Layer):\n\n def __init__(self, units, **kwargs):\n self.units = units\n self.state_size = units\n super(RNNCellWithConstants, self).__init__(**kwargs)\n\n def build(self, input_shape):\n if not isinstance(input_shape, list):\n raise TypeError('expects constants shape')\n [input_shape, constant_shape] = input_shape\n # will (and should) raise if more than one constant passed\n\n self.input_kernel = self.add_weight(\n shape=(input_shape[-1], self.units),\n initializer='uniform',\n name='kernel')\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units),\n initializer='uniform',\n name='recurrent_kernel')\n self.constant_kernel = self.add_weight(\n shape=(constant_shape[-1], self.units),\n initializer='uniform',\n name='constant_kernel')\n self.built = True\n\n def call(self, inputs, states, constants):\n [prev_output] = states\n [constant] = constants\n h_input = keras.backend.dot(inputs, self.input_kernel)\n h_state = keras.backend.dot(prev_output, self.recurrent_kernel)\n h_const = keras.backend.dot(constant, self.constant_kernel)\n output = h_input + h_state + h_const\n return output, [output]\n\n def get_config(self):\n config = {'units': self.units}\n base_config = super(RNNCellWithConstants, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n # Test basic case.\n x = keras.Input((None, 5))\n c = keras.Input((3,))\n s = keras.Input((32,))\n cell = RNNCellWithConstants(32)\n layer = recurrent.RNN(cell)\n y = layer(x, initial_state=s, constants=c)\n model = keras.models.Model([x, s, c], y)\n model.compile(optimizer='rmsprop', loss='mse')\n model.train_on_batch(\n [np.zeros((6, 5, 5)), np.zeros((6, 32)), np.zeros((6, 3))],\n np.zeros((6, 32))\n )\n\n # Test basic case serialization.\n x_np = np.random.random((6, 5, 5))\n s_np = np.random.random((6, 32))\n c_np = np.random.random((6, 3))\n y_np = model.predict([x_np, s_np, c_np])\n weights = model.get_weights()\n config = layer.get_config()\n custom_objects = {'RNNCellWithConstants': RNNCellWithConstants}\n with keras.utils.CustomObjectScope(custom_objects):\n layer = recurrent.RNN.from_config(config.copy())\n y = layer(x, initial_state=s, constants=c)\n model = keras.models.Model([x, s, c], y)\n model.set_weights(weights)\n y_np_2 = model.predict([x_np, s_np, c_np])\n assert_allclose(y_np, y_np_2, atol=1e-4)\n\n # verify that state is used\n y_np_2_different_s = model.predict([x_np, s_np + 10., c_np])\n with pytest.raises(AssertionError):\n assert_allclose(y_np, y_np_2_different_s, atol=1e-4)\n\n # test flat list inputs\n with keras.utils.CustomObjectScope(custom_objects):\n layer = recurrent.RNN.from_config(config.copy())\n y = layer([x, s, c])\n model = keras.models.Model([x, s, c], y)\n model.set_weights(weights)\n y_np_3 = model.predict([x_np, s_np, c_np])\n assert_allclose(y_np, y_np_3, atol=1e-4)\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n" ]
[ [ "numpy.random.random", "numpy.ones", "numpy.zeros", "numpy.testing.assert_allclose" ] ]
pwalczysko/ilastik
[ "e4fa2c3c1ba1f83d3dcc392ccdd29e4391b8dbcf" ]
[ "scripts/pixel_classification_zarr.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#\n# Copyright (c) 2020 University of Dundee.\n#\n# Redistribution and use in source and binary forms, with or without modification, \n# are permitted provided that the following conditions are met:\n# \n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# Redistributions in binary form must reproduce the above copyright notice, \n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\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 WARRANTIES\n# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \n# INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND 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 SOFTWARE, EVEN IF ADVISED\n# OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# Version: 1.0\n#\n\nimport time\nimport tempfile\nimport tarfile\nimport numpy\nimport os\nimport zarr\nimport dask.array as da\n\nimport omero.clients\nfrom omero.gateway import BlitzGateway\nfrom getpass import getpass\n\n\nfrom ilastik import app\nfrom ilastik.applets.dataSelection.opDataSelection import PreloadedArrayDatasetInfo # noqa\nimport vigra\n\n\n# Connect to the server\ndef connect(hostname, username, password):\n conn = BlitzGateway(username, password,\n host=hostname, secure=True)\n conn.connect()\n return conn\n\n\n# Load-images\ndef load_images(conn, dataset_id):\n return conn.getObjects('Image', opts={'dataset': dataset_id})\n\n\n# Create-dataset\ndef create_dataset(conn, dataset_id):\n dataset = omero.model.DatasetI()\n v = \"ilastik_probabilities_from_dataset_%s\" % dataset_id\n dataset.setName(omero.rtypes.rstring(v))\n v = \"ilatisk results probabilities from Dataset:%s\" % dataset_id\n dataset.setDescription(omero.rtypes.rstring(v))\n return conn.getUpdateService().saveAndReturnObject(dataset)\n\n\n# Load-data\ndef load_numpy_array(image, path, extension=\".tar\", resolution=0):\n # load annotation linked to the image. Download in a tmp dir\n for ann in image.listAnnotations():\n if isinstance(ann, omero.gateway.FileAnnotationWrapper):\n name = ann.getFile().getName()\n ns = ann.getNs()\n if (name.endswith(\".zip\") or name.endswith(\".tar\")) and ns is None:\n file_path = os.path.join(path, name)\n f_path = os.path.join(path, name.strip(extension))\n with open(str(file_path), 'wb') as f:\n for chunk in ann.getFileInChunks():\n f.write(chunk)\n # extract the file\n if extension == \".tar\":\n tf = tarfile.open(file_path)\n tf.extractall(path)\n tf.close()\n data = zarr.open(f_path)\n values = data[resolution][:]\n # from tczyx to tzyxc\n values = values.swapaxes(1, 2).swapaxes(2, 3)\n values = values.swapaxes(3, 4)\n return values\n else:\n data = zarr.open(file_path)\n return data[:]\n return None\n\n\ndef load_from_s3(image, resolution='0'):\n id = image.getId()\n endpoint_url = 'https://minio-dev.openmicroscopy.org/'\n root = 'idr/outreach/%s.zarr/' % id\n # data.shape is (t, c, z, y, x) by convention\n data = da.from_zarr(endpoint_url + root)\n values = data[:]\n values = values.swapaxes(1, 2).swapaxes(2, 3).swapaxes(3, 4)\n return numpy.asarray(values)\n\n\n# Analyze-data\ndef analyze(conn, images, model, new_dataset, extension=\".tar\", resolution=0):\n # Prepare ilastik\n # temporary directory where to download files\n path = tempfile.mkdtemp()\n if not os.path.exists(path):\n os.makedirs(path)\n\n os.environ[\"LAZYFLOW_THREADS\"] = \"2\"\n os.environ[\"LAZYFLOW_TOTAL_RAM_MB\"] = \"2000\"\n args = app.parse_args([])\n args.headless = True\n args.project = model\n args.readonly = True\n shell = app.main(args)\n\n start = time.time()\n for image in images:\n input_data = load_from_s3(image, path)\n # run ilastik headless\n print('running ilastik using %s and %s' % (model, image.getName()))\n data = [ {\"Raw Data\": PreloadedArrayDatasetInfo(preloaded_array=input_data, axistags=vigra.defaultAxistags(\"tzyxc\"))}] # noqa\n shell.workflow.batchProcessingApplet.run_export(data, export_to_array=True) # noqa\n elapsed = time.time() - start\n print(elapsed)\n\n\n# Save-results\ndef save_results(conn, image, data, dataset, path):\n filename, file_extension = os.path.splitext(image.getName())\n # Save the probabilities file as an image\n print(\"Saving Probabilities as zarr file attached to the original Image\")\n name = filename + \"_Probabilities_zarr.zip\"\n desc = \"ilastik probabilities from Image:%s\" % image.getId()\n # Re-organise array from tzyxc to zctyx order expected by OMERO\n # data = data.swapaxes(0, 1).swapaxes(3, 4).swapaxes(2, 3).swapaxes(1, 2)\n namespace = \"ilastik.zarr.demo\"\n fp = os.path.join(path, name)\n with zarr.ZipStore(fp, mode='w') as store:\n zarr.array(data, store=store, dtype='int16',\n compressor=zarr.Blosc(cname='zstd'))\n ann = conn.createFileAnnfromLocalFile(fp, mimetype=\"application/zip\",\n ns=namespace, desc=desc)\n image.linkAnnotation(ann)\n\n\n# Disconnect\ndef disconnect(conn):\n conn.close()\n\n\n# main\ndef main():\n # Collect user credentials\n try:\n host = input(\"Host [wss://outreach.openmicroscopy.org/omero-ws]: \") or 'wss://outreach.openmicroscopy.org/omero-ws' # noqa\n username = input(\"Username [trainer-1]: \") or 'trainer-1'\n password = getpass(\"Password: \")\n dataset_id = input(\"Dataset ID [6161]: \") or '6161'\n # Connect to the server\n conn = connect(host, username, password)\n conn.c.enableKeepAlive(60)\n\n # path to the ilastik project\n ilastik_project = \"../notebooks/pipelines/pixel-class-133.ilp\"\n\n # Load the images in the dataset\n images = load_images(conn, dataset_id)\n\n new_dataset = create_dataset(conn, dataset_id)\n\n analyze(conn, images, ilastik_project, new_dataset)\n finally:\n disconnect(conn)\n\n print(\"done\")\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.asarray" ] ]
ryancoe/WDRT
[ "039d53b13b8d6ee98bbbab69d6433af4f709e6c0" ]
[ "examples/example_shortTermExtreme_2.py" ]
[ "\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport WDRT.shortTermExtreme as ecm\nimport WDRT.fatigue as fatigue\n\nmethod = 1\n\t# 1 - All peaks Weibull\n\t# 2 - Weibull tail fit\n\t# 3 - Peaks over threshold\n\t# 4 - Block maxima GEV\n\t# 5 - Block maxima Gumbel\n\n# load global peaks\nt_peaks = np.loadtxt(r'C:\\full\\filepath\\to\\WDRT\\examples\\data\\t.dat')\npeaks = np.loadtxt(r'C:\\full\\filepath\\to\\WDRT_py3\\WDRT\\examples\\data\\peaks.dat')/1000.\n\n# get the 1-hour extreme distribution using the method selected above\nx_e = np.linspace(0, 2 * np.max(peaks), 10000)\nt_x = (t_peaks[-1]-t_peaks[0]) + ((t_peaks[-1]-t_peaks[0])/(1.*len(peaks)))\nt_st = 1. * 60. * 60.\nif method==1:\n\tstextreme_dist, peaks_dist, _ = ecm.extremeDistribution_Weibull(x=peaks, x_e=x_e, t_x=t_x, t_st=t_st)\nelif method==2:\n\tstextreme_dist, peaks_dist, _, _, _ = ecm.extremeDistribution_WeibullTailFit(x=peaks, x_e=x_e, t_x=t_x, t_st=t_st)\nelif method==3:\n\tthresh = np.mean(peaks) + 1.4*np.std(peaks)\n\tthresh_x = np.min(x_e[x_e>thresh])\n\tstextreme_dist, peaks_dist, pot_dist, _ = ecm.extremeDistribution_peaksOverThreshold(x=peaks, x_e=x_e, t_x=t_x, t_st=t_st, u=thresh)\nelif method==4:\n\tstextreme_dist,_,bm = ecm.extremeDistribution_blockMaximaGEV(x=peaks, t=t_peaks, t_st=t_st)\nelif method == 5:\n\tstextreme_dist,_,bm = ecm.extremeDistribution_blockMaximaGumb(x=peaks, t=t_peaks, t_st=t_st)\n\n# goodness of fit plots\nif method==1 or method==2:\n\tbm = ecm.blockMaxima(x=peaks, t=t_peaks, t_st=t_st)\n\t_ = ecm.goodnessOfFitPlots(data=peaks, prob_func=peaks_dist, np_return=1000001, x_pdf=x_e, bins_pdf=20, response_name='PTO Force', response_name_2='Peaks',response_units='kN')\nif not method==3:\n\tfig_gof = ecm.goodnessOfFitPlots(data=bm, prob_func=stextreme_dist, np_return=10001, x_pdf=x_e, bins_pdf=20, response_name='PTO Force', response_name_2='1-hr Extreme',response_units='kN')\nif method==3:\n\tbm = ecm.blockMaxima(x=peaks, t=t_peaks, t_st=t_st)\n\t_ = ecm.goodnessOfFitPlots(data=peaks[peaks>thresh_x], prob_func=peaks_dist, np_return=100001, x_pdf=x_e[x_e>thresh_x], bins_pdf=20,m_prob=1.*len(peaks[peaks<thresh_x]), response_name='PTO Force', response_name_2='Peaks',response_units='kN')\n\t_ = ecm.goodnessOfFitPlots(data=peaks[peaks>thresh]-thresh, prob_func=pot_dist, np_return=100001, x_pdf=x_e[x_e>thresh]-thresh, bins_pdf=20, response_name='PTO Force', response_name_2='Peaks Over Threshold',response_units='kN')\n\tfig_gof = ecm.goodnessOfFitPlots(data=bm, prob_func=stextreme_dist, np_return=10001, x_pdf=x_e[x_e>thresh_x], bins_pdf=20, response_name='PTO Force', response_name_2='1-hr Extreme',response_units='kN')\n\n# plot\nplt.figure()\nif method==3:\n\tplt.plot(t_peaks[peaks<thresh], peaks[peaks<thresh], 'ko', alpha=0.2)\n\tplt.plot(t_peaks[peaks>thresh], peaks[peaks>thresh], 'go')\n\tplt.plot([0, t_peaks[-1]], [thresh, thresh], 'r--')\nelse:\n\tplt.plot(t_peaks, peaks, 'go')\nplt.plot([0, t_peaks[-1]], [0, 0], 'k--')\nplt.xlabel('Time, $t$ [s]')\nplt.ylabel('Response, $x$')\nplt.xlim([0,3600*2])\nplt.grid(True)\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\n\nplt.figure()\nax = plt.subplot(2, 1, 1)\nif method==1 or method==2:\n\tplt.plot(x_e, peaks_dist.pdf(x_e), 'g-', label='Peak distribution')\nif not method==3:\n\tplt.plot(x_e, stextreme_dist.pdf(x_e), 'r-', label='Extreme distribution')\nif method==3:\n\tplt.plot(x_e[x_e>thresh_x], peaks_dist.pdf(x_e[x_e>thresh_x]), 'g-', label='Peak distribution')\n\tplt.plot(x_e[x_e>thresh_x], stextreme_dist.pdf(x_e[x_e>thresh_x]), 'r-', label='Extreme distribution')\nxlim = ax.get_xlim()\nylim = ax.get_ylim()\nif method==3:\n\tplt.plot([thresh, thresh], [0, ylim[1]], 'k--')\nplt.ylim([0,ylim[1]])\nplt.xlim([0,xlim[1]])\nplt.xlabel('Response, $x$')\nplt.ylabel('$PDF(x)$')\nplt.grid(True)\nplt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\nplt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))\nplt.legend()\n\nax = plt.subplot(2, 1, 2)\nif method==1 or method==2:\n\tplt.plot(x_e, peaks_dist.cdf(x_e), 'g-')\nif not method==3:\n\tplt.plot(x_e, stextreme_dist.cdf(x_e), 'r-')\nif method==3:\n\tplt.plot(x_e[x_e>thresh_x], peaks_dist.cdf(x_e[x_e>thresh_x]), 'g-')\n\tplt.plot(x_e[x_e>thresh_x], stextreme_dist.cdf(x_e[x_e>thresh_x]), 'r-')\nxlim = ax.get_xlim()\nylim = ax.get_ylim()\nif method==3:\n\tplt.plot([thresh, thresh], [0, ylim[1]], 'k--')\nplt.ylim([0,ylim[1]])\nplt.xlim([0,xlim[1]])\nplt.xlabel('Response, $x$')\nplt.ylabel('$CDF(x)$')\nplt.grid(True)\nplt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n\nplt.show()\n" ]
[ [ "matplotlib.pyplot.ticklabel_format", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "matplotlib.pyplot.grid", "numpy.std", "matplotlib.pyplot.xlim", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.max", "matplotlib.pyplot.ylim", "numpy.min", "numpy.mean", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "numpy.loadtxt" ] ]
MaayanLab/maayanlab-bioinformatics
[ "f84bda02a8841a65d4c72e491129cdc339fb73b3" ]
[ "maayanlab_bioinformatics/plotting/upset.py" ]
[ "import itertools\nimport pandas as pd\nfrom typing import Dict, Set, Hashable\n\ndef upset_from_dict_of_sets(inputs: Dict[Hashable, Set[Hashable]]):\n ''' Given a dictionary of sets, produce input ready for `upsetplot` python package\n\n We produce this input by computing set intersections of all relevant combinations\n of sets interacting with one another.\n\n Example:\n ```python\n import upsetplot\n from maayanlab_bioinformatics.plotting import upset_from_dict_of_sets\n upsetplot.plot(upset_from_dict_of_sets({\n 'A': {'a', 'b', 'c'},\n 'B': {'b', 'c', 'd'},\n 'C': {'d', 'e', 'f'},\n }))\n ```\n :param inputs: (Dict[Hashable, Set[Hashable]]) Several named sets\n :return: (pd.DataFrame) in a form ready for `upsetplot.plot`\n '''\n sets = []\n for n in range(1, len(inputs)+1):\n if n == 1:\n it = [[k] for k in inputs.keys()]\n else:\n it = map(list, itertools.combinations(inputs.keys(), n))\n for V in it:\n size = len(inputs[V[0]] if n == 1 else set.intersection(*[inputs[v] for v in V]))\n if size > 0:\n sets.append(dict({vv: vv in V for vv in inputs.keys()}, size=size))\n return pd.DataFrame(sets).groupby(list(inputs.keys()))['size'].sum()\n" ]
[ [ "pandas.DataFrame" ] ]
ludwigjer/visualsudoku
[ "a5ed257edfda45123ef3779b8181d5f27412ea50" ]
[ "src/OCR_CNN_Trainning.py" ]
[ "import numpy as np\nimport cv2\nimport os\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras.layers import Dropout,Flatten\nfrom keras.layers.convolutional import Conv2D,MaxPooling2D\nimport pickle\nfrom tensorflow.keras.layers import Activation, Dense, Conv2D, Dropout, Flatten, MaxPooling2D\n\n# PARAMETERS \npath = 'numbers/train2'\ntestRatio = 0.2\nvalRatio = 0.2\nimageDimensions= (28,28,3)\nbatchSizeVal= 6\nepochsVal = 10\nstepsPerEpochVal = 2000\n\n\n# IMPORTING DATA/IMAGES FROM FOLDERS \ncount = 0\nimages = [] # LIST CONTAINING ALL THE IMAGES \nclassNo = [] # LIST CONTAINING ALL THE CORRESPONDING CLASS ID OF IMAGES \nmyList = os.listdir(path)\nprint(\"Total Classes Detected:\",len(myList))\nnoOfClasses = len(myList)\nprint(\"Importing Classes .......\")\nfor x in range (0,noOfClasses):\n myPicList = os.listdir(path+\"/\"+str(x))\n for y in myPicList:\n curImg = cv2.imread(path+\"/\"+str(x)+\"/\"+y)\n curImg = cv2.resize(curImg,(28,28))\n images.append(curImg)\n classNo.append(x)\n print(x,end= \" \")\nprint(\" \")\nprint(\"Total Images in Images List = \",len(images))\nprint(\"Total IDS in classNo List= \",len(classNo))\n\n# CONVERT TO NUMPY ARRAY \nimages = np.array(images)\nclassNo = np.array(classNo)\nprint(images.shape)\nprint(classNo.shape)\n\n# SPLITTING THE DATA\nX_train,X_test,y_train,y_test = train_test_split(images,classNo,test_size=testRatio)\nX_train,X_validation,y_train,y_validation = train_test_split(X_train,y_train,test_size=valRatio)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(X_validation.shape)\n\n# PLOT BAR CHART FOR DISTRIBUTION OF IMAGES\nnumOfSamples= []\nfor x in range(0,noOfClasses):\n #print(len(np.where(y_train==x)[0]))\n numOfSamples.append(len(np.where(y_train==x)[0]))\nprint(numOfSamples)\n\nplt.figure(figsize=(10,5))\nplt.bar(range(0,noOfClasses),numOfSamples)\nplt.title(\"No of Images for each Class\")\nplt.xlabel(\"Class ID\")\nplt.ylabel(\"Number of Images\")\nplt.show()\n\n# PREPOSSESSING FUNCTION FOR IMAGES FOR TRAINING \ndef preProcessing(img):\n img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n img = cv2.equalizeHist(img)\n img = img/255\n return img\n#img = preProcessing(X_train[30])\n#img = cv2.resize(img,(300,300))\n#cv2.imshow(\"PreProcesssed\",img)\n#cv2.waitKey(0)\n\nX_train= np.array(list(map(preProcessing,X_train)))\nX_test= np.array(list(map(preProcessing,X_test)))\nX_validation= np.array(list(map(preProcessing,X_validation)))\n\n\n# RESHAPE IMAGES \nX_train = X_train.reshape(X_train.shape[0],X_train.shape[1],X_train.shape[2],1)\nX_test = X_test.reshape(X_test.shape[0],X_test.shape[1],X_test.shape[2],1)\nX_validation = X_validation.reshape(X_validation.shape[0],X_validation.shape[1],X_validation.shape[2],1)\n\n# IMAGE AUGMENTATION \ndataGen = ImageDataGenerator(width_shift_range=0.1,\n height_shift_range=0.1,\n zoom_range=0.2,\n shear_range=0.1,\n rotation_range=10)\ndataGen.fit(X_train)\n\n# ONE HOT ENCODING OF MATRICES\ny_train = to_categorical(y_train,noOfClasses)\ny_test = to_categorical(y_test,noOfClasses)\ny_validation = to_categorical(y_validation,noOfClasses)\n\n# CREATING THE MODEL \ndef myModel():\n\n model = Sequential()\n model.add(Conv2D(64, kernel_size=(3,3), input_shape= (28, 28, 1)))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n \n model.add(Conv2D(64, kernel_size=(3,3)))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n \n model.add(Conv2D(64, kernel_size=(3,3)))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n \n model.add(Flatten())\n model.add(Dense(64))\n model.add(Activation(\"relu\"))\n \n model.add(Dense(32))\n model.add(Activation(\"relu\"))\n \n model.add(Dense(10))\n model.add(Activation(\"softmax\"))\n\n model.compile(Adam(lr=0.001),loss='categorical_crossentropy',metrics=['accuracy'])\n return model\n\nmodel = myModel()\nprint(model.summary())\n\n#### STARTING THE TRAINING PROCESS\nhistory = model.fit_generator(dataGen.flow(X_train,y_train,\n batch_size=batchSizeVal),\n steps_per_epoch=stepsPerEpochVal,\n epochs=epochsVal,\n validation_data=(X_validation,y_validation),\n shuffle=1)\n\n\n\n# PLOT THE RESULTS \nplt.figure(1)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['training','validation'])\nplt.title('Loss')\nplt.xlabel('epoch')\nplt.figure(2)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.legend(['training','validation'])\nplt.title('Accuracy')\nplt.xlabel('epoch')\nplt.show()\n\n# EVALUATE USING TEST IMAGES\nscore = model.evaluate(X_test,y_test,verbose=0)\nprint('Test Score = ',score[0])\nprint('Test Accuracy =', score[1])\n\n# SAVE THE TRAINED MODEL \nmodel.save('model11.h5')\n" ]
[ [ "tensorflow.keras.layers.Flatten", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Activation", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.ylabel", "tensorflow.keras.layers.Dense", "numpy.array", "matplotlib.pyplot.plot", "numpy.where", "matplotlib.pyplot.xlabel" ] ]
mihaid-b/CyberSakura
[ "f60e6b6bfd6898c69b84424b080090ae98f8076c" ]
[ "Gathered CTF writeups/ctf-7867/2020/pbctf/queensarah2/graphic.py" ]
[ "from string import ascii_lowercase\nfrom itertools import product\nimport gizeh\nimport numpy as np\nimport random\n\nrandom.seed(1234)\n\nalphabet = ascii_lowercase + \"_\"\nbigrams = [''.join(bigram) for bigram in product(alphabet, repeat=2)]\nrandom.shuffle(bigrams)\n\nscale = 2\nwidth = 512 * scale\nheight = 512 * scale\n\n\ndef draw(bs, name, theta_offset=0):\n surface = gizeh.Surface(width=width, height=height)\n\n r = width / 2 * 3/4\n offset = [width / 2, height / 2]\n theta_step = (2 * np.pi) / (len(bs))\n\n i = 0\n for theta in np.linspace(0, 2 * np.pi, len(bs) + 1)[:-1]:\n t = theta + (theta_offset * theta_step / 2)\n xy = [r * np.sin(t) + offset[0], r * np.cos(t) + offset[1]]\n text = gizeh.text(\n bs[i],\n fontfamily=\"monospace\",\n fontsize=20 * scale,\n fill=(0, 0, 0),\n xy=xy,\n angle=0\n )\n text.draw(surface)\n i += 1\n\n surface.write_to_png(\"gen/\" + name + \".png\")\n\n\neven = bigrams[:16]\neven0 = [x for i, x in enumerate(even) if i % 2 == 0]\neven1 = [x for i, x in enumerate(even) if i % 2 == 1]\nbigrams = bigrams[16:]\n\ndraw(even, \"even\")\ndraw(even0, \"even0\")\ndraw(even1, \"even1\", theta_offset=1)\n\nodd = bigrams[:15]\nbigrams = bigrams[15:]\n\ndraw(odd, \"odd\")\n" ]
[ [ "numpy.sin", "numpy.cos" ] ]
tarepan/mutated_DVC
[ "7fbbf4754285944387ec5d5108ed5f3d473d4f81" ]
[ "nets/block.py" ]
[ "import math\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nimport numpy as np\nfrom .sn_convolution_2d import SNConvolution2D, SNDeconvolution2D\nfrom .sn_linear import SNLinear\n\ndef _upsample(x):\n h, w = x.shape[2:]\n return F.unpooling_2d(x, 2, outsize=(h * 2, w * 2))\n\ndef _downsample(x):\n return F.average_pooling_2d(x, 2)\n\ndef upsample_conv(x, conv):\n return conv(_upsample(x))\n\ndef _upsample_frq(x):\n h, w = x.shape[2:]\n return F.unpooling_2d(x, (1,2), outsize=(h, w * 2))\n\ndef _downsample_frq(x):\n return F.average_pooling_2d(x, (1,2))\n\ndef upsample_conv_frq(x, conv):\n return conv(_upsample_frq(x))\n\nclass ResBlock(chainer.Chain):\n def __init__(self, in_channels, out_channels, ksize=3, pad=1, activation=F.leaky_relu, mode='none', bn=False, dr=None):\n super(ResBlock, self).__init__()\n initializer = chainer.initializers.GlorotUniform()\n initializer_sc = chainer.initializers.GlorotUniform()\n self.activation = activation\n self.mode = _downsample if mode == 'down' else _upsample if mode == 'up' else None\n self.learnable_sc = in_channels != out_channels\n self.dr = dr\n self.bn = bn\n with self.init_scope():\n self.c1 = L.Convolution2D(in_channels, out_channels, ksize=ksize, pad=pad, initialW=initializer, nobias=bn)\n self.c2 = L.Convolution2D(out_channels, out_channels, ksize=ksize, pad=pad, initialW=initializer, nobias=bn)\n if bn:\n self.b1 = L.BatchNormalization(out_channels)\n self.b2 = L.BatchNormalization(out_channels)\n if self.learnable_sc:\n self.c_sc = L.Convolution2D(in_channels, out_channels, ksize=1, pad=0, initialW=initializer_sc)\n\n def residual(self, x):\n h = x\n h = self.c1(h)\n if self.bn:\n h = self.b1(h)\n if self.activation:\n h = self.activation(h)\n if self.mode:\n h = self.mode(h)\n if self.dr:\n with chainer.using_config('train', True):\n h = F.dropout(h, self.dr)\n h = self.c2(h)\n if self.bn:\n h = self.b2(h)\n if self.activation:\n h = self.activation(h)\n return h\n\n def shortcut(self, x):\n if self.mode:\n x = self.mode(x)\n if self.learnable_sc:\n x = self.c_sc(x)\n return x\n\n def __call__(self, x):\n return self.residual(x) + self.shortcut(x)\n\nclass ConvBlock(chainer.Chain):\n def __init__(self, in_channels, out_channels, mode='none', activation=F.leaky_relu, bn=False, dr=None):\n super(ConvBlock, self).__init__()\n # initializer = chainer.initializers.GlorotUniform()\n initializer = chainer.initializers.HeUniform()\n self.activation = activation\n self.bn = bn\n self.dr = dr\n with self.init_scope():\n if mode == 'none':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=3, stride=1, pad=1, initialW=initializer, nobias=bn)\n elif mode == 'none-7':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=(7,7), stride=1, pad=(3,3), initialW=initializer, nobias=bn)\n elif mode == 'down':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=4, stride=2, pad=1, initialW=initializer, nobias=bn)\n elif mode == 'up':\n self.c = L.Deconvolution2D(in_channels, out_channels, ksize=4, stride=2, pad=1, initialW=initializer, nobias=bn)\n elif mode == 'full-down':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=4, stride=1, pad=0, initialW=initializer, nobias=bn)\n elif mode == 'frq':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=(1,9), stride=1, pad=(0,4), initialW=initializer, nobias=bn)\n elif mode == 'frq-down':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=(1,9), stride=1, pad=(0,4), initialW=initializer, nobias=bn)\n self.activation = lambda x: activation(_downsample(x))\n elif mode == 'frq-up':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=(1,9), stride=1, pad=(0,4), initialW=initializer, nobias=bn)\n self.activation = lambda x: activation(_upsample(x))\n elif mode == 'pad':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=3, stride=1, pad=2, initialW=initializer, nobias=bn)\n elif mode == 'trim':\n self.c = L.Convolution2D(in_channels, out_channels, ksize=3, stride=1, pad=0, initialW=initializer, nobias=bn)\n else:\n raise Exception('mode is missing')\n if bn:\n self.b = L.BatchNormalization(out_channels)\n\n def __call__(self, h):\n if self.dr:\n with chainer.using_config('train', True):\n h = F.dropout(h, self.dr)\n h = self.c(h)\n if self.bn:\n h = self.b(h)\n if self.activation:\n h = self.activation(h)\n return h\n \nclass CoPSBlock(chainer.Chain):\n def __init__(self, in_channels, out_channels, activation=F.leaky_relu, bn=True):\n super(CoPSBlock, self).__init__()\n initializer = chainer.initializers.GlorotUniform()\n self.activation = activation\n self.bn = bn\n with self.init_scope():\n self.ps = L.Convolution2D(in_channels, in_channels*4, ksize=1, stride=1, initialW=initializer)\n self.c = L.Convolution2D(in_channels, out_channels, ksize=3, stride=1, pad=1, initialW=initializer)\n if bn:\n self.b = L.BatchNormalization(out_channels)\n\n def pixel_shuffle(self, x):\n out = self.ps(x)\n b = out.shape[0]\n c = out.shape[1]\n h = out.shape[2]\n w = out.shape[3]\n out = F.reshape(out, (b, 2, 2, c//4, h, w))\n out = F.transpose(out, (0, 3, 4, 1, 5, 2))\n out = F.reshape(out, (b, c//4, h*2, w*2))\n return out\n\n def __call__(self, h):\n h = self.pixel_shuffle(h)\n h = self.c(h)\n if self.bn:\n h = self.b(h)\n if self.activation:\n h = self.activation(h)\n return h\n \nclass SNResBlock(chainer.Chain):\n def __init__(self, in_channels, out_channels, activation=F.leaky_relu, sample='none', dr=None):\n super(SNResBlock, self).__init__()\n initializer = chainer.initializers.GlorotUniform()\n initializer_sc = chainer.initializers.GlorotUniform()\n self.activation = activation\n self.dr = dr\n self.sample = _downsample if sample == 'down' else _upsample if sample == 'up' else None\n self.learnable_sc = in_channels != out_channels or sample == 'down' or sample == 'up'\n with self.init_scope():\n self.c1 = SNConvolution2D(in_channels, out_channels, ksize=3, pad=1, initialW=initializer)\n self.c2 = SNConvolution2D(out_channels, out_channels, ksize=3, pad=1, initialW=initializer)\n if self.learnable_sc:\n self.c_sc = SNConvolution2D(in_channels, out_channels, ksize=1, pad=0, initialW=initializer_sc)\n\n def residual(self, x):\n h = x\n h = self.activation(h)\n h = self.c1(h)\n if self.sample:\n h = self.sample(h)\n if self.dr:\n with chainer.using_config('train', True):\n h = F.dropout(h, self.dr)\n h = self.activation(h)\n h = self.c2(h)\n return h\n\n def shortcut(self, x):\n if self.learnable_sc:\n x = self.c_sc(x)\n if self.sample:\n return self.sample(x)\n else:\n return x\n else:\n return x\n\n def __call__(self, x):\n return self.residual(x) + self.shortcut(x)\n\nclass SNConvBlock(chainer.Chain):\n def __init__(self, in_channels, out_channels, mode='none', activation=F.leaky_relu, bn=False, dr=None):\n super(SNConvBlock, self).__init__()\n # initializer = chainer.initializers.GlorotUniform()\n initializer = chainer.initializers.HeUniform()\n self.activation = activation\n self.bn = bn\n self.dr = dr\n with self.init_scope():\n if mode == 'none':\n self.c = SNConvolution2D(in_channels, out_channels, ksize=3, stride=1, pad=1, initialW=initializer, nobias=bn)\n elif mode == 'none-7':\n self.c = SNConvolution2D(in_channels, out_channels, ksize=(7,7), stride=1, pad=(3,3), initialW=initializer, nobias=bn)\n elif mode == 'down':\n self.c = SNConvolution2D(in_channels, out_channels, ksize=4, stride=2, pad=1, initialW=initializer, nobias=bn)\n elif mode == 'up':\n self.c = SNDeconvolution2D(in_channels, out_channels, ksize=4, stride=2, pad=1, initialW=initializer, nobias=bn)\n elif mode == 'full-down':\n self.c = SNConvolution2D(in_channels, out_channels, ksize=4, stride=1, pad=0, initialW=initializer, nobias=bn)\n elif mode == 'frq':\n self.c = SNConvolution2D(in_channels, out_channels, ksize=(1,9), stride=1, pad=(0,4), initialW=initializer, nobias=bn)\n elif mode == 'frq-down':\n self.c = SNConvolution2D(in_channels, out_channels, ksize=(1,9), stride=1, pad=(0,4), initialW=initializer, nobias=bn)\n self.activation = lambda x: activation(_downsample(x))\n elif mode == 'frq-up':\n self.c = SNConvolution2D(in_channels, out_channels, ksize=(1,9), stride=1, pad=(0,4), initialW=initializer, nobias=bn)\n self.activation = lambda x: activation(_upsample(x))\n else:\n raise Exception('mode is missing')\n if bn:\n self.b = L.BatchNormalization(out_channels)\n\n def __call__(self, h):\n if self.dr:\n with chainer.using_config('train', True):\n h = F.dropout(h, self.dr)\n h = self.c(h)\n if self.bn:\n h = self.b(h)\n if self.activation:\n h = self.activation(h)\n return h\n \nclass SNLinearBlock(chainer.Chain):\n def __init__(self, in_channels, out_channels, activation=F.leaky_relu, dr=None):\n super(SNLinearBlock, self).__init__()\n initializer = chainer.initializers.GlorotUniform()\n self.activation = activation\n self.dr = dr\n if type(out_channels) is tuple:\n self.out_shape = (-1,)+out_channels\n else:\n self.out_shape = None\n with self.init_scope():\n self.l = SNLinear(in_channels, np.prod(out_channels), initialW=initializer)\n\n def __call__(self, x):\n if self.dr:\n x = F.dropout(x, self.dr)\n x = self.l(x)\n x = self.activation(x)\n if self.out_shape:\n x = F.reshape(x, self.out_shape)\n return x\n\nclass SNMDBlock(chainer.Chain):\n def __init__(self, in_channels, in_size=4, B=100, C=5, gap=True, dr=None):\n super(SNMDBlock, self).__init__()\n # initializer = chainer.initializers.GlorotUniform()\n initializer = chainer.initializers.HeUniform()\n self.B = B\n self.C = C\n self.dr = dr\n self.gap = gap\n if gap:\n in_size = 1\n if type(in_size) is int:\n in_size = (in_size, in_size)\n with self.init_scope():\n self.l = SNLinear(in_size[0] * in_size[1] * in_channels + B, 1, initialW=initializer)\n self.md = SNLinear(in_size[0] * in_size[1] * in_channels, B * C, initialW=initializer)\n\n def __call__(self, x):\n if self.dr:\n with chainer.using_config('train', True):\n x = F.dropout(x, self.dr)\n if self.gap:\n x = F.sum(x, axis=(2,3))\n N = x.shape[0]\n #Below code copyed from https://github.com/pfnet-research/chainer-gan-lib/blob/master/minibatch_discrimination/net.py\n feature = F.reshape(F.leaky_relu(x), (N, -1))\n m = F.reshape(self.md(feature), (N, self.B * self.C, 1))\n m0 = F.broadcast_to(m, (N, self.B * self.C, N))\n m1 = F.transpose(m0, (2, 1, 0))\n d = F.absolute(F.reshape(m0 - m1, (N, self.B, self.C, N)))\n d = F.sum(F.exp(-F.sum(d, axis=2)), axis=2) - 1\n h = F.concat([feature, d])\n\n h = self.l(h)\n return h\n\nclass SNL1DBlock(chainer.Chain):\n def __init__(self, in_ch, out_ch, width, activation=F.leaky_relu, dr=None):\n super(SNL1DBlock, self).__init__()\n initializer = chainer.initializers.GlorotUniform()\n self.activation = activation\n self.dr = dr\n self.out_ch = out_ch\n with self.init_scope():\n self.l = SNLinear(in_ch*width, out_ch*width, initialW=initializer)\n\n def __call__(self, x):\n if self.dr:\n x = F.dropout(x, self.dr)\n x = F.transpose(x, (0, 2, 1, 3))\n out_shape = list(x.shape)\n x = F.reshape(x, (-1, x.shape[2]*x.shape[3]))\n x = self.l(x)\n x = self.activation(x)\n out_shape[2] = self.out_ch\n x = F.reshape(x, out_shape)\n x = F.transpose(x, (0, 2, 1, 3))\n return x\n\nclass L1DBlock(chainer.Chain):\n def __init__(self, in_ch, out_ch, width, activation=F.leaky_relu, dr=None):\n super(L1DBlock, self).__init__()\n # initializer = chainer.initializers.GlorotUniform()\n initializer = chainer.initializers.HeUniform()\n self.activation = activation\n self.dr = dr\n self.out_ch = out_ch\n with self.init_scope():\n self.l = L.Linear(in_ch*width, out_ch*width, initialW=initializer)\n\n def __call__(self, x):\n if self.dr:\n x = F.dropout(x, self.dr)\n x = F.transpose(x, (0, 2, 1, 3))\n out_shape = list(x.shape)\n x = F.reshape(x, (-1, x.shape[2]*x.shape[3]))\n x = self.l(x)\n x = self.activation(x)\n out_shape[2] = self.out_ch\n x = F.reshape(x, out_shape)\n x = F.transpose(x, (0, 2, 1, 3))\n return x\n\nclass CLBlock(chainer.Chain):\n def __init__(self, in_ch, out_ch, width, activation=F.leaky_relu, liner_out_ch=1, dr=None):\n super(CLBlock, self).__init__()\n self.dr = dr\n if out_ch - liner_out_ch <= 0:\n raise Exception('out_ch <= liner_out_ch!')\n with self.init_scope():\n self.c = ConvBlock(in_ch, out_ch-liner_out_ch, activation=activation)\n self.l = L1DBlock(in_ch, liner_out_ch, width, activation)\n\n def __call__(self, x):\n h = x\n if self.dr:\n h = F.dropout(h, self.dr)\n h1 = self.c(h)\n h2 = self.l(h)\n h = F.concat([h1,h2])\n return h\n\nclass SNCLBlock(chainer.Chain):\n def __init__(self, in_ch, out_ch, width, activation=F.leaky_relu, dr=None):\n super(SNCLBlock, self).__init__()\n self.dr = dr\n with self.init_scope():\n self.c = SNConvBlock(in_ch, out_ch-1, activation=activation)\n self.l = SNL1DBlock(in_ch, 1, width, activation)\n\n def __call__(self, x):\n h = x\n if self.dr:\n h = F.dropout(h, self.dr)\n h1 = self.c(h)\n h2 = self.l(h)\n h = F.concat([h1,h2])\n return h\n\n" ]
[ [ "numpy.prod" ] ]
autonomousvision/handheld_svbrdf_geometry
[ "41218b0546e7386229b87c94d528cd193127acff" ]
[ "code/main.py" ]
[ "\"\"\"\nCopyright (c) 2020 Autonomous Vision Group (AVG), Max Planck Institute for Intelligent Systems, Tuebingen, Germany\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport json\nimport os\nfrom tqdm import tqdm\nimport cv2\nimport torch\nimport itertools\n\nfrom data import DataAdapterFactory\nfrom experiment_state import ExperimentState\nfrom experiment_settings import ExperimentSettings, recursive_dict_update\nfrom optimization import optimize\nfrom higo import higo_baseline\nimport general_settings\nfrom evaluation import evaluate_state\n\nfrom utils.logging import error\n\nsettings_dict_base = {\n 'data_settings': {\n 'data_type': \"XIMEA\",\n 'center_view': None,\n 'nr_neighbours': 40, \n 'base_input_path': \"<input_data_base_folder>/\",\n 'object_name': None,\n 'base_output_path': \"<output_base_folder>/\",\n 'gt_scan_folder': \"<gt_scan_folder>/\",\n 'calibration_path_geometric': \"<calibration_base_folder>/geometric/\",\n 'vignetting_file': '<calibration_base_folder>/photometric/vignetting.npz',\n 'depth_folder': 'tsdf-fusion-depth_oldCV_40_views',\n 'center_stride': 2,\n 'depth_scale': 1e-3,\n 'light_scale': 1e0,\n 'lazy_image_loading': False,\n 'input_reup_sample': 1.,\n 'input_down_sample': 1.,\n 'manual_center_view_crop': None,\n },\n 'parametrization_settings': {\n 'locations': 'depth map',\n 'normals': 'per point',\n 'materials': 'base specular materials',\n 'brdf': 'cook torrance F1',\n 'observation_poses': 'quaternion',\n 'lights': 'point light',\n },\n 'initialization_settings': {\n 'normals': 'from_closed_form',\n 'diffuse': 'from_closed_form',\n 'specular': 'hardcoded',\n 'lights': 'precalibrated',\n 'light_calibration_files': {\n \"positions\": \"<calibration_base_folder>/photometric/lights_array.pkl\",\n \"intensities\": \"<calibration_base_folder>/photometric/LED_light_intensities.npy\",\n \"attenuations\": \"<calibration_base_folder>/photometric/LED_angular_dependency.npy\",\n }\n },\n 'default_optimization_settings': {\n 'parameters': [\n 'locations',\n 'poses',\n 'normals',\n 'vignetting',\n 'diffuse_materials',\n 'specular_weights',\n 'specular_materials',\n 'light_positions',\n 'light_intensities',\n 'light_attenuations',\n ],\n 'losses': {\n \"photoconsistency L1\": 1e-4,\n \"geometric consistency\": 1e1,\n \"depth compatibility\": 1e10,\n \"normal smoothness\": 1e-1,\n \"material sparsity\": 1e-1,\n \"material smoothness\": 1e0,\n },\n \"iterations\": 1000,\n 'visualize_initial': False,\n 'visualize_results': True,\n 'target_set': \"training\",\n },\n 'optimization_steps': [],\n}\n\nsettings_dict_higo = recursive_dict_update(\n settings_dict_base,\n {\n 'data_settings': {\n 'output_path_suffix': 'higo',\n },\n 'higo_baseline': {\n 'step_size': 0.001, #1 mm\n 'step_radius': 25,\n 'eta': 10,\n 'lambda_n': 7.5,\n 'lambda_s': 3.0,\n 'lambda_1': 0.1,\n 'lambda_2': 0.5,\n },\n }\n)\n\ndisjoint_iteration = [\n {\n 'parameters': ['specular_weights'],\n \"iterations\": 40,\n },\n {\n 'parameters': ['diffuse_materials', 'specular_materials'],\n \"iterations\": 40,\n },\n {\n 'parameters': ['normals'],\n \"iterations\": 60,\n },\n {\n 'parameters': ['locations', 'observation_poses'],\n \"iterations\": 60,\n },\n]\nsettings_dict_disjoint = recursive_dict_update(\n settings_dict_base,\n {\n 'data_settings': {\n 'output_path_suffix': 'disjoint',\n },\n 'default_optimization_settings': {\n },\n 'optimization_steps': [\n *(disjoint_iteration * 5),\n # {\n # 'iterations': 1000,\n # 'parameters': [\n # 'observation_poses',\n # ],\n # 'visualize_initial': True,\n # 'target_set': \"testing\",\n # },\n ]\n }\n)\n\nsettings_dict_proposed = recursive_dict_update(\n settings_dict_base,\n {\n 'data_settings': {\n 'output_path_suffix': 'proposed',\n },\n 'optimization_steps': [\n {\n 'parameters': [\n 'diffuse_materials',\n 'specular_weights',\n 'specular_materials',\n 'normals',\n 'observation_poses',\n 'locations',\n ],\n 'visualize_initial': True,\n },\n # {\n # 'parameters': [\n # 'observation_poses',\n # ],\n # 'visualize_initial': True,\n # 'target_set': \"testing\",\n # },\n ]\n }\n)\n\n\ndef run_experiment(settings_dict):\n experiment_settings = ExperimentSettings(settings_dict)\n # localize to the current computer as required\n experiment_settings.localize()\n\n # create an empty experiment object, with the correct parametrizations\n experiment_settings.check_stored(\"parametrization_settings\")\n experiment_state = ExperimentState.create(experiment_settings.get('parametrization_settings'))\n experiment_settings.save(\"parametrization_settings\")\n\n # create the data adapter\n experiment_settings.check_stored(\"data_settings\")\n data_adapter = DataAdapterFactory(\n experiment_settings.get('data_settings')['data_type']\n )(\n experiment_settings.get('local_data_settings')\n )\n\n if not experiment_settings.get('data_settings')['lazy_image_loading']:\n device = torch.device(general_settings.device_name)\n image_tensors = [\n observation.get_image()\n for observation in tqdm(data_adapter.images, desc=\"Preloading training images\")\n ]\n # now compact all observations into a few big tensors and remove the old tensors\n # this makes for much faster access/operations\n data_adapter.compound_image_tensors = {}\n data_adapter.compound_image_tensor_sizes = {}\n training_indices_batches, _ = data_adapter.get_training_info()\n testing_indices_batches, _ = data_adapter.get_testing_info()\n for batch in itertools.chain(training_indices_batches, testing_indices_batches):\n compound_H = max([image_tensors[i].shape[-2] for i in batch])\n compound_W = max([image_tensors[i].shape[-1] for i in batch])\n C = len(batch)\n compound_images = torch.zeros(C, 3, compound_H, compound_W, dtype=torch.float, device=device)\n compound_sizes = torch.zeros(C, 2, dtype=torch.long, device=device)\n for idx, image_idx in enumerate(batch):\n src_tensor = image_tensors[image_idx]\n compound_images[idx,:,:src_tensor.shape[-2], :src_tensor.shape[-1]] = src_tensor\n compound_sizes[idx,0] = src_tensor.shape[-1]\n compound_sizes[idx,1] = src_tensor.shape[-2]\n del data_adapter.images[image_idx]._image\n data_adapter.compound_image_tensors[batch] = compound_images\n data_adapter.compound_image_tensor_sizes[batch] = compound_sizes\n del image_tensors\n\n experiment_settings.save(\"data_settings\")\n\n # initialize the parametrizations with the requested values, if the initialization is not available on disk\n initialization_state_folder = experiment_settings.get_state_folder(\"initialization\")\n if experiment_settings.check_stored(\"initialization_settings\"):\n experiment_state.load(initialization_state_folder)\n else:\n experiment_state.initialize(data_adapter, experiment_settings.get('local_initialization_settings'))\n experiment_state.save(initialization_state_folder)\n experiment_settings.save(\"initialization_settings\")\n\n # evaluate_state(\"initialization\",\n # experiment_settings.get('data_settings')['object_name'],\n # experiment_settings.get('local_data_settings')['gt_scan_folder'],\n # experiment_state)\n experiment_state.visualize_statics(\n experiment_settings.get_output_path(),\n data_adapter\n )\n\n if experiment_settings.get(\"higo_baseline\") is not None:\n higo_state_folder = experiment_settings.get_state_folder(\"higo\")\n if not experiment_settings.check_stored(\"higo_baseline\"):\n higo_experiment_state = higo_baseline(\n experiment_state,\n data_adapter,\n higo_state_folder,\n experiment_settings.get('higo_baseline')\n )\n higo_experiment_state.visualize(\n experiment_settings.get_output_path(),\n \"higo_baseline\",\n data_adapter,\n losses = [],\n shadows_occlusions=False\n )\n higo_experiment_state.save(higo_state_folder)\n experiment_settings.save(\"higo_baseline\")\n else:\n higo_experiment_state = ExperimentState.copy(experiment_state)\n higo_experiment_state.load(higo_state_folder)\n evaluate_state(\"higo baseline\",\n experiment_settings.get('data_settings')['object_name'],\n experiment_settings.get('local_data_settings')['gt_scan_folder'],\n higo_experiment_state)\n\n optimization_step_settings = experiment_settings.get('default_optimization_settings')\n experiment_settings.check_stored(\"default_optimization_settings\")\n experiment_settings.save(\"default_optimization_settings\")\n\n for step_index in range(len(experiment_settings.get('optimization_steps'))):\n step_state_folder = experiment_settings.get_state_folder(\"optimization_steps\", step_index)\n\n optimization_settings = experiment_settings.get(\"optimization_steps\", step_index)\n\n shorthand = experiment_settings.get_shorthand(\"optimization_steps\", step_index)\n set_name = \"%02d_%s\" % (step_index, shorthand)\n\n if optimization_settings['visualize_initial']:\n experiment_state.visualize(\n experiment_settings.get_output_path(),\n \"%02d__initial\" % step_index,\n data_adapter,\n optimization_settings['losses']\n )\n\n if experiment_settings.check_stored(\"optimization_steps\", step_index):\n experiment_state.load(step_state_folder)\n else:\n optimize(\n experiment_state,\n data_adapter,\n optimization_settings,\n output_path_structure=os.path.join(\n experiment_settings.get_output_path(),\n \"evolution_%%s_%s.png\" % set_name\n )\n )\n experiment_state.save(step_state_folder)\n experiment_settings.save(\"optimization_steps\", step_index)\n\n if optimization_settings['visualize_results']:\n experiment_state.visualize(\n experiment_settings.get_output_path(),\n set_name,\n data_adapter,\n optimization_settings['losses']\n )\n\n evaluate_state(experiment_settings.get('data_settings').get('output_path_suffix', 'proposed'),\n experiment_settings.get('data_settings')['object_name'],\n experiment_settings.get('local_data_settings')['gt_scan_folder'],\n experiment_state)\n\nif __name__ == \"__main__\":\n for object_name, center_view in [\n # (\"peter\", 1171),\n # (\"peter\", 566),\n # (\"teapot\", 451),\n # (\"teapot\", 999),\n # (\"gnome\", 308),\n # (\"gnome\", 488),\n # (\"girl\", 882),\n # (\"girl\", 1059),\n (\"duck\", 826),\n # (\"duck\", 49),\n # (\"fire_hydrant\", 582),\n # (\"fire_hydrant\", 704),\n # (\"pineapple\", 401),\n # (\"pineapple\", 536),\n # (\"bunny\", 670),\n # (\"bunny\", 180),\n ]:\n for settings_dict in [settings_dict_proposed, settings_dict_higo, settings_dict_disjoint]:\n settings_dict['data_settings']['object_name'] = object_name\n settings_dict['data_settings']['center_view'] = center_view\n run_experiment(settings_dict)\n\n" ]
[ [ "torch.zeros", "torch.device" ] ]
KMarkert/RHEAS
[ "453f24ef635ca5a6338d3e2b19f215835dd1f10d" ]
[ "src/datasets/decorators.py" ]
[ "\"\"\" Definition for RHEAS Datasets decorators.\n\n.. module:: datasets.decorators\n :synopsis: Definition of the Datasets decorators\n\n.. moduleauthor:: Kostas Andreadis <[email protected]>\n\n\"\"\"\n\nfrom functools import wraps\nimport tempfile\nimport shutil\nimport urllib\nfrom datetime import datetime\nfrom ftplib import FTP\nimport re\nfrom pydap.client import open_url\nimport netCDF4 as netcdf4\nimport numpy as np\nfrom osgeo import gdal\nimport datasets\n\n\ndef resetDatetime(dt):\n \"\"\"Set time to 00:00 to align with daily data.\"\"\"\n return datetime(dt.year, dt.month, dt.day, 0, 0)\n\n\ndef path(fetch):\n \"\"\"Decorator for getting files from local path.\"\"\"\n @wraps(fetch)\n def wrapper(*args, **kwargs):\n url, bbox, dt = fetch(*args, **kwargs)\n outpath = tempfile.mkdtemp()\n filename = url.format(dt.year, dt.month, dt.day)\n try:\n shutil.copy(filename, outpath)\n lfilename = filename.split(\"/\")[-1]\n except:\n lfilename = None\n return outpath, lfilename, bbox, dt\n return wrapper\n\n\ndef http(fetch):\n \"\"\"Decorator for downloading files from HTTP sites.\"\"\"\n @wraps(fetch)\n def wrapper(*args, **kwargs):\n url, bbox, dt = fetch(*args, **kwargs)\n outpath = tempfile.mkdtemp()\n filename = url.format(dt.year, dt.month, dt.day)\n try:\n lfilename = filename.split(\"/\")[-1]\n urllib.urlcleanup()\n urllib.urlretrieve(filename, \"{0}/{1}\".format(outpath, lfilename))\n except:\n lfilename = None\n return outpath, lfilename, bbox, dt\n return wrapper\n\n\ndef ftp(fetch):\n \"\"\"Decorator for downloading files from FTP sites.\"\"\"\n @wraps(fetch)\n def wrapper(*args, **kwargs):\n url, bbox, dt = fetch(*args, **kwargs)\n ftpurl = url.split(\"/\")[2]\n outpath = tempfile.mkdtemp()\n try:\n conn = FTP(ftpurl)\n conn.login()\n conn.cwd(\"/\".join(url.split(\"/\")[3:-1]).format(dt.year, dt.month, dt.day))\n name = url.split(\"/\")[-1].format(dt.year, dt.month, dt.day)\n filenames = [f for f in conn.nlst() if re.match(r\".*{0}.*\".format(name), f) is not None]\n if len(filenames) > 0:\n filename = filenames[0]\n with open(\"{0}/{1}\".format(outpath, filename), 'wb') as f:\n conn.retrbinary(\"RETR {0}\".format(filename), f.write)\n filenames.append(\"{0}/{1}\".format(outpath, filename))\n else:\n filename = None\n except:\n filename = None\n return outpath, filename, bbox, dt\n return wrapper\n\n\ndef opendap(fetch):\n \"\"\"Decorator for fetching data from Opendap servers.\"\"\"\n @wraps(fetch)\n def wrapper(*args, **kwargs):\n url, varname, bbox, dt = fetch(*args, **kwargs)\n ds = open_url(url)\n for var in ds.keys():\n if var.lower().startswith(\"lon\") or var.lower() == \"x\":\n lonvar = var\n if var.lower().startswith(\"lat\") or var.lower() == \"y\":\n latvar = var\n if var.lower().startswith(\"time\") or var.lower() == \"t\":\n timevar = var\n lat = ds[latvar][:].data\n lon = ds[lonvar][:].data\n lon[lon > 180] -= 360\n res = abs(lat[0]-lat[1]) # assume rectangular grid\n i1, i2, j1, j2 = datasets.spatialSubset(np.sort(lat)[::-1], np.sort(lon), res, bbox)\n t = ds[timevar]\n tt = netcdf4.num2date(t[:].data, units=t.units)\n ti = [tj for tj in range(len(tt)) if resetDatetime(tt[tj]) >= dt[0] and resetDatetime(tt[tj]) <= dt[1]]\n if len(ti) > 0:\n lati = np.argsort(lat)[::-1][i1:i2]\n loni = np.argsort(lon)[j1:j2]\n if len(ds[varname].data[0].shape) > 3:\n data = ds[varname].data[0][ti[0]:ti[-1]+1, 0, lati[0]:lati[-1]+1, loni[0]:loni[-1]+1]\n else:\n data = ds[varname].data[0][ti[0]:ti[-1]+1, 0, lati[0]:lati[-1]+1, loni[0]:loni[-1]+1]\n dt = tt[ti]\n else:\n data = None\n dt = None\n lat = np.sort(lat)[::-1][i1:i2]\n lon = np.sort(lon)[j1:j2]\n return data, lat, lon, dt\n return wrapper\n \n \n \ndef netcdf(fetch):\n \"\"\"Decorator for fetching NetCDF files (local or from Opendap servers).\"\"\"\n @wraps(fetch)\n def wrapper(*args, **kwargs):\n url, varname, bbox, dt = fetch(*args, **kwargs)\n ds = netcdf4.Dataset(url)\n for var in ds.variables:\n if var.lower().startswith(\"lon\") or var.lower() == \"x\":\n lonvar = var\n if var.lower().startswith(\"lat\") or var.lower() == \"y\":\n latvar = var\n if var.lower().startswith(\"time\") or var.lower() == \"t\":\n timevar = var\n lat = ds.variables[latvar][:]\n lon = ds.variables[lonvar][:]\n lon[lon > 180] -= 360\n res = abs(lat[0]-lat[1]) # assume rectangular grid\n i1, i2, j1, j2 = datasets.spatialSubset(np.sort(lat)[::-1], np.sort(lon), res, bbox)\n t = ds.variables[timevar]\n tt = netcdf4.num2date(t[:], units=t.units)\n ti = [tj for tj in range(len(tt)) if resetDatetime(tt[tj]) >= dt[0] and resetDatetime(tt[tj]) <= dt[1]]\n if len(ti) > 0:\n lati = np.argsort(lat)[::-1][i1:i2]\n loni = np.argsort(lon)[j1:j2]\n if len(ds.variables[varname].shape) > 3:\n data = ds.variables[varname][ti, 0, lati, loni]\n else:\n data = ds.variables[varname][ti, lati, loni]\n dt = tt[ti]\n else:\n data = None\n dt = None\n lat = np.sort(lat)[::-1][i1:i2]\n lon = np.sort(lon)[j1:j2]\n return data, lat, lon, dt\n return wrapper\n\n\ndef geotiff(fetch):\n \"\"\"Decorator for reading data from raster files.\"\"\"\n @wraps(fetch)\n def wrapper(*args, **kwargs):\n outpath, filename, bbox, dt = fetch(*args, **kwargs)\n if filename is not None:\n lfilename = datasets.uncompress(filename, outpath)\n f = gdal.Open(\"{0}/{1}\".format(outpath, lfilename))\n xul, xres, _, yul, _, yres = f.GetGeoTransform()\n data = f.ReadAsArray()\n nr, nc = data.shape\n lat = np.arange(yul + yres/2.0, yul + yres * nr, yres)\n lon = np.arange(xul + xres/2.0, xul + xres * nc, xres)\n i1, i2, j1, j2 = datasets.spatialSubset(lat, lon, xres, bbox)\n data = data[i1:i2, j1:j2]\n lat = lat[i1:i2]\n lon = lon[j1:j2]\n shutil.rmtree(outpath)\n else:\n data = lat = lon = None\n return data, lat, lon, dt\n return wrapper\n" ]
[ [ "numpy.sort", "numpy.arange", "numpy.argsort" ] ]
vidurj/allennlp
[ "5b513d4f7c7365ac33b3cbc557506b46a9b50450" ]
[ "tests/training/trainer_test.py" ]
[ "# pylint: disable=invalid-name\nimport glob\nimport os\nimport re\nimport time\n\nimport torch\nimport pytest\n\nfrom allennlp.common.testing import AllenNlpTestCase\nfrom allennlp.training.trainer import Trainer, sparse_clip_norm, is_sparse\nfrom allennlp.data import Vocabulary\nfrom allennlp.common.params import Params\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.models.simple_tagger import SimpleTagger\nfrom allennlp.data.iterators import BasicIterator\nfrom allennlp.data.dataset_readers import SequenceTaggingDatasetReader\n\n\nclass TestTrainer(AllenNlpTestCase):\n def setUp(self):\n super(TestTrainer, self).setUp()\n self.instances = SequenceTaggingDatasetReader().read('tests/fixtures/data/sequence_tagging.tsv')\n vocab = Vocabulary.from_instances(self.instances)\n self.vocab = vocab\n self.model_params = Params({\n \"text_field_embedder\": {\n \"tokens\": {\n \"type\": \"embedding\",\n \"embedding_dim\": 5\n }\n },\n \"encoder\": {\n \"type\": \"lstm\",\n \"input_size\": 5,\n \"hidden_size\": 7,\n \"num_layers\": 2\n }\n })\n self.model = SimpleTagger.from_params(self.vocab, self.model_params)\n self.optimizer = torch.optim.SGD(self.model.parameters(), 0.01)\n self.iterator = BasicIterator(batch_size=2)\n self.iterator.index_with(vocab)\n\n def test_trainer_can_run(self):\n trainer = Trainer(model=self.model,\n optimizer=self.optimizer,\n iterator=self.iterator,\n train_dataset=self.instances,\n validation_dataset=self.instances,\n num_epochs=2)\n metrics = trainer.train()\n assert 'best_validation_loss' in metrics\n assert isinstance(metrics['best_validation_loss'], float)\n assert 'best_epoch' in metrics\n assert isinstance(metrics['best_epoch'], int)\n\n # Making sure that both increasing and decreasing validation metrics work.\n trainer = Trainer(model=self.model,\n optimizer=self.optimizer,\n iterator=self.iterator,\n train_dataset=self.instances,\n validation_dataset=self.instances,\n validation_metric='+loss',\n num_epochs=2)\n metrics = trainer.train()\n assert 'best_validation_loss' in metrics\n assert isinstance(metrics['best_validation_loss'], float)\n assert 'best_epoch' in metrics\n assert isinstance(metrics['best_epoch'], int)\n\n @pytest.mark.skipif(not torch.cuda.is_available(), reason=\"No CUDA device registered.\")\n def test_trainer_can_run_cuda(self):\n trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances, num_epochs=2,\n cuda_device=0)\n trainer.train()\n\n @pytest.mark.skipif(torch.cuda.device_count() < 2,\n reason=\"Need multiple GPUs.\")\n def test_trainer_can_run_multiple_gpu(self):\n multigpu_iterator = BasicIterator(batch_size=4)\n multigpu_iterator.index_with(self.vocab)\n trainer = Trainer(self.model, self.optimizer,\n multigpu_iterator, self.instances, num_epochs=2,\n cuda_device=[0, 1])\n trainer.train()\n\n def test_trainer_can_resume_training(self):\n trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances,\n validation_dataset=self.instances,\n num_epochs=1, serialization_dir=self.TEST_DIR)\n trainer.train()\n new_trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances,\n validation_dataset=self.instances,\n num_epochs=3, serialization_dir=self.TEST_DIR)\n\n epoch, val_metrics_per_epoch = new_trainer._restore_checkpoint() # pylint: disable=protected-access\n assert epoch == 1\n assert len(val_metrics_per_epoch) == 1\n assert isinstance(val_metrics_per_epoch[0], float)\n assert val_metrics_per_epoch[0] != 0.\n new_trainer.train()\n\n def test_should_stop_early_with_increasing_metric(self):\n new_trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances,\n validation_dataset=self.instances,\n num_epochs=3, serialization_dir=self.TEST_DIR,\n patience=5, validation_metric=\"+test\")\n assert new_trainer._should_stop_early([.5, .3, .2, .1, .4, .4]) # pylint: disable=protected-access\n assert not new_trainer._should_stop_early([.3, .3, .3, .2, .5, .1]) # pylint: disable=protected-access\n\n def test_should_stop_early_with_decreasing_metric(self):\n new_trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances,\n validation_dataset=self.instances,\n num_epochs=3, serialization_dir=self.TEST_DIR,\n patience=5, validation_metric=\"-test\")\n assert new_trainer._should_stop_early([.02, .3, .2, .1, .4, .4]) # pylint: disable=protected-access\n assert not new_trainer._should_stop_early([.3, .3, .2, .1, .4, .5]) # pylint: disable=protected-access\n\n def test_train_driver_raises_on_model_with_no_loss_key(self):\n\n class FakeModel(torch.nn.Module):\n def forward(self, **kwargs): # pylint: disable=arguments-differ,unused-argument\n return {}\n with pytest.raises(ConfigurationError):\n trainer = Trainer(FakeModel(), self.optimizer,\n self.iterator, self.instances,\n num_epochs=2, serialization_dir=self.TEST_DIR)\n trainer.train()\n\n def test_trainer_can_log_histograms(self):\n # enable activation logging\n for module in self.model.modules():\n module.should_log_activations = True\n\n trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances, num_epochs=3,\n serialization_dir=self.TEST_DIR,\n histogram_interval=2)\n trainer.train()\n\n def test_trainer_respects_num_serialized_models_to_keep(self):\n trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances, num_epochs=5,\n serialization_dir=self.TEST_DIR,\n num_serialized_models_to_keep=3)\n trainer.train()\n\n # Now check the serialized files\n for prefix in ['model_state_epoch_*', 'training_state_epoch_*']:\n file_names = glob.glob(os.path.join(self.TEST_DIR, prefix))\n epochs = [int(re.search(r\"_([0-9])\\.th\", fname).group(1))\n for fname in file_names]\n assert sorted(epochs) == [2, 3, 4]\n\n def test_trainer_respects_keep_serialized_model_every_num_seconds(self):\n # To test:\n # Create an iterator that sleeps for 0.5 second per epoch, so the total training\n # time for one epoch is slightly greater then 0.5 seconds.\n # Run for 6 epochs, keeping the last 2 models, models also kept every 1 second.\n # Check the resulting checkpoints. Should then have models at epochs\n # 2, 4, plus the last two at 5 and 6.\n class WaitingIterator(BasicIterator):\n # pylint: disable=arguments-differ\n def _create_batches(self, *args, **kwargs):\n time.sleep(0.5)\n return super(WaitingIterator, self)._create_batches(*args, **kwargs)\n\n iterator = WaitingIterator(batch_size=2)\n iterator.index_with(self.vocab)\n\n trainer = Trainer(self.model, self.optimizer,\n iterator, self.instances, num_epochs=6,\n serialization_dir=self.TEST_DIR,\n num_serialized_models_to_keep=2,\n keep_serialized_model_every_num_seconds=1)\n trainer.train()\n\n # Now check the serialized files\n for prefix in ['model_state_epoch_*', 'training_state_epoch_*']:\n file_names = glob.glob(os.path.join(self.TEST_DIR, prefix))\n epochs = [int(re.search(r\"_([0-9])\\.th\", fname).group(1))\n for fname in file_names]\n # epoch N has N-1 in file name\n assert sorted(epochs) == [1, 3, 4, 5]\n\n def test_trainer_saves_models_at_specified_interval(self):\n iterator = BasicIterator(batch_size=4)\n iterator.index_with(self.vocab)\n\n trainer = Trainer(self.model, self.optimizer,\n iterator, self.instances, num_epochs=2,\n serialization_dir=self.TEST_DIR,\n model_save_interval=0.0001)\n\n trainer.train()\n\n # Now check the serialized files for models saved during the epoch.\n prefix = 'model_state_epoch_*'\n file_names = sorted(glob.glob(os.path.join(self.TEST_DIR, prefix)))\n epochs = [re.search(r\"_([0-9\\.\\-]+)\\.th\", fname).group(1)\n for fname in file_names]\n # We should have checkpoints at the end of each epoch and during each, e.g.\n # [0.timestamp, 0, 1.timestamp, 1]\n assert len(epochs) == 4\n assert epochs[3] == '1'\n assert '.' in epochs[0]\n\n # Now make certain we can restore from timestamped checkpoint.\n # To do so, remove the checkpoint from the end of epoch 1&2, so\n # that we are forced to restore from the timestamped checkpoints.\n for k in range(2):\n os.remove(os.path.join(self.TEST_DIR, 'model_state_epoch_{}.th'.format(k)))\n os.remove(os.path.join(self.TEST_DIR, 'training_state_epoch_{}.th'.format(k)))\n os.remove(os.path.join(self.TEST_DIR, 'best.th'))\n\n restore_trainer = Trainer(self.model, self.optimizer,\n self.iterator, self.instances, num_epochs=2,\n serialization_dir=self.TEST_DIR,\n model_save_interval=0.0001)\n epoch, _ = restore_trainer._restore_checkpoint() # pylint: disable=protected-access\n assert epoch == 2\n # One batch per epoch.\n assert restore_trainer._batch_num_total == 2 # pylint: disable=protected-access\n\n\nclass TestSparseClipGrad(AllenNlpTestCase):\n def test_sparse_clip_grad(self):\n # create a sparse embedding layer, then take gradient\n embedding = torch.nn.Embedding(100, 16, sparse=True)\n embedding.zero_grad()\n ids = torch.autograd.Variable((torch.rand(17) * 100).long())\n # Set some of the ids to the same value so that the sparse gradient\n # has repeated indices. This tests some additional logic.\n ids[:5] = 5\n loss = embedding(ids).sum()\n loss.backward()\n assert is_sparse(embedding.weight.grad)\n\n # Now try to clip the gradients.\n _ = sparse_clip_norm([embedding.weight], 1.5)\n # Final norm should be 1.5\n grad = embedding.weight.grad.data.coalesce()\n self.assertAlmostEqual(grad._values().norm(2.0), 1.5, places=5) # pylint: disable=protected-access\n" ]
[ [ "torch.rand", "torch.cuda.is_available", "torch.nn.Embedding", "torch.cuda.device_count" ] ]
speakupai/ml_deployment
[ "f80735049de8111b2415608046bb2b0af57fcdd3" ]
[ "inference.py" ]
[ "import os\n\nimport librosa\nimport numpy as np\nimport soundfile as sf\nimport torch\nfrom tqdm import tqdm\n\nfrom utils import data, spectrogram, spectrogram_clean\nfrom models.hifi_gan import Generator\nfrom models.wavenet import WaveNet\n\nfrom utils.hparams import hparams as hp\n\ndef inference(audio_clip):\n original_file = audio_clip\n save_dir = './uploads'\n checkpoint_path = './saved_model/latest_checkpoint.pt'\n #default_inf_device = 'cpu',\n\n # Load checkpoint\n checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))\n\n # Initializing model, optimizer, criterion and scaler\n model = Generator(wavenet=WaveNet())\n model.to('cpu')\n model.load_state_dict(checkpoint['generator_state_dict'])\n model.eval()\n\n inference_files = [original_file]\n\n with torch.no_grad():\n for file in inference_files:\n filename = os.path.splitext(os.path.split(file)[1])[0]\n x, _ = librosa.load(file, sr=16000, mono=True)\n target_length = len(x)\n x = torch.tensor(x).to('cpu')\n x = data.preprocess_inference_data(x,\n hp.inference.batched,\n hp.inference.batch_size,\n hp.inference.sequence_length,\n 16000)\n\n # run inference and create spectrograms\n y = []\n for x_batch in tqdm(x):\n spect_orig = np.array(x_batch[0])\n spectrogram.create_spectrogram(spect_orig)\n clean_temp = model.inference(x_batch)\n y.append(clean_temp)\n spectrogram_clean.create_spectrogram(np.array(clean_temp))\n y = data.postprocess_inference_data(y, hp.inference.batched,\n 16000)\n y = y[:target_length].detach().cpu().numpy()\n sf.write(os.path.join(save_dir, f'{filename}_denoised.wav'),\n y.astype(np.float32), samplerate=hp.dsp.sample_rate)\n" ]
[ [ "numpy.array", "torch.no_grad", "torch.device", "torch.tensor" ] ]
SvipRepetitionCounting/AlphaPose
[ "0cc38e4c1d6f08ea9c34c720ae188506d3de6eb6" ]
[ "trackers/tracking/utils/io.py" ]
[ "import os\nfrom typing import Dict\nimport numpy as np\n\nfrom utils.log import logger\n\n\ndef write_results(filename, results_dict: Dict, data_type: str):\n if not filename:\n return\n path = os.path.dirname(filename)\n if not os.path.exists(path):\n os.makedirs(path)\n\n if data_type in ('mot', 'mcmot', 'lab'):\n save_format = '{frame},{id},{x1},{y1},{w},{h},1,-1,-1,-1\\n'\n elif data_type == 'kitti':\n save_format = '{frame} {id} pedestrian -1 -1 -10 {x1} {y1} {x2} {y2} -1 -1 -1 -1000 -1000 -1000 -10 {score}\\n'\n else:\n raise ValueError(data_type)\n\n with open(filename, 'w') as f:\n for frame_id, frame_data in results_dict.items():\n if data_type == 'kitti':\n frame_id -= 1\n for tlwh, track_id in frame_data:\n if track_id < 0:\n continue\n x1, y1, w, h = tlwh\n x2, y2 = x1 + w, y1 + h\n line = save_format.format(frame=frame_id, id=track_id, x1=x1, y1=y1, x2=x2, y2=y2, w=w, h=h, score=1.0)\n f.write(line)\n logger.info('Save results to {}'.format(filename))\n\n\ndef read_results(filename, data_type: str, is_gt=False, is_ignore=False):\n if data_type in ('mot', 'lab'):\n read_fun = read_mot_results\n else:\n raise ValueError('Unknown data type: {}'.format(data_type))\n\n return read_fun(filename, is_gt, is_ignore)\n\n\n\"\"\"\nlabels={'ped', ...\t\t\t% 1\n'person_on_vhcl', ...\t% 2\n'car', ...\t\t\t\t% 3\n'bicycle', ...\t\t\t% 4\n'mbike', ...\t\t\t% 5\n'non_mot_vhcl', ...\t\t% 6\n'static_person', ...\t% 7\n'distractor', ...\t\t% 8\n'occluder', ...\t\t\t% 9\n'occluder_on_grnd', ...\t\t%10\n'occluder_full', ...\t\t% 11\n'reflection', ...\t\t% 12\n'crowd' ...\t\t\t% 13\n};\n\"\"\"\n\n\ndef read_mot_results(filename, is_gt, is_ignore):\n valid_labels = {1}\n ignore_labels = {2, 7, 8, 12}\n results_dict = dict()\n if os.path.isfile(filename):\n with open(filename, 'r') as f:\n for line in f.readlines():\n linelist = line.split(',')\n if len(linelist) < 7:\n continue\n fid = int(linelist[0])\n if fid < 1:\n continue\n results_dict.setdefault(fid, list())\n\n if is_gt:\n if 'MOT16-' in filename or 'MOT17-' in filename:\n label = int(float(linelist[7]))\n mark = int(float(linelist[6]))\n if mark == 0 or label not in valid_labels:\n continue\n score = 1\n elif is_ignore:\n if 'MOT16-' in filename or 'MOT17-' in filename:\n label = int(float(linelist[7]))\n vis_ratio = float(linelist[8])\n if label not in ignore_labels and vis_ratio >= 0:\n continue\n else:\n continue\n score = 1\n else:\n score = float(linelist[6])\n\n tlwh = tuple(map(float, linelist[2:6]))\n target_id = int(linelist[1])\n\n results_dict[fid].append((tlwh, target_id, score))\n\n return results_dict\n\n\ndef unzip_objs(objs):\n if len(objs) > 0:\n tlwhs, ids, scores = zip(*objs)\n else:\n tlwhs, ids, scores = [], [], []\n tlwhs = np.asarray(tlwhs, dtype=float).reshape(-1, 4)\n\n return tlwhs, ids, scores" ]
[ [ "numpy.asarray" ] ]
rturrisige/POT
[ "c5039bcafde999114283f7e59fb03e176027d740" ]
[ "test/test_bregman.py" ]
[ "\"\"\"Tests for module bregman on OT with bregman projections \"\"\"\n\n# Author: Remi Flamary <[email protected]>\n# Kilian Fatras <[email protected]>\n#\n# License: MIT License\n\nimport numpy as np\nimport ot\nimport pytest\n\n\ndef test_sinkhorn():\n # test sinkhorn\n n = 100\n rng = np.random.RandomState(0)\n\n x = rng.randn(n, 2)\n u = ot.utils.unif(n)\n\n M = ot.dist(x, x)\n\n G = ot.sinkhorn(u, u, M, 1, stopThr=1e-10)\n\n # check constratints\n np.testing.assert_allclose(\n u, G.sum(1), atol=1e-05) # cf convergence sinkhorn\n np.testing.assert_allclose(\n u, G.sum(0), atol=1e-05) # cf convergence sinkhorn\n\n\ndef test_sinkhorn_empty():\n # test sinkhorn\n n = 100\n rng = np.random.RandomState(0)\n\n x = rng.randn(n, 2)\n u = ot.utils.unif(n)\n\n M = ot.dist(x, x)\n\n G, log = ot.sinkhorn([], [], M, 1, stopThr=1e-10, verbose=True, log=True)\n # check constratints\n np.testing.assert_allclose(u, G.sum(1), atol=1e-05)\n np.testing.assert_allclose(u, G.sum(0), atol=1e-05)\n\n G, log = ot.sinkhorn([], [], M, 1, stopThr=1e-10,\n method='sinkhorn_stabilized', verbose=True, log=True)\n # check constratints\n np.testing.assert_allclose(u, G.sum(1), atol=1e-05)\n np.testing.assert_allclose(u, G.sum(0), atol=1e-05)\n\n G, log = ot.sinkhorn(\n [], [], M, 1, stopThr=1e-10, method='sinkhorn_epsilon_scaling',\n verbose=True, log=True)\n # check constratints\n np.testing.assert_allclose(u, G.sum(1), atol=1e-05)\n np.testing.assert_allclose(u, G.sum(0), atol=1e-05)\n\n\ndef test_sinkhorn_variants():\n # test sinkhorn\n n = 100\n rng = np.random.RandomState(0)\n\n x = rng.randn(n, 2)\n u = ot.utils.unif(n)\n\n M = ot.dist(x, x)\n\n G0 = ot.sinkhorn(u, u, M, 1, method='sinkhorn', stopThr=1e-10)\n Gs = ot.sinkhorn(u, u, M, 1, method='sinkhorn_stabilized', stopThr=1e-10)\n Ges = ot.sinkhorn(\n u, u, M, 1, method='sinkhorn_epsilon_scaling', stopThr=1e-10)\n G_green = ot.sinkhorn(u, u, M, 1, method='greenkhorn', stopThr=1e-10)\n\n # check values\n np.testing.assert_allclose(G0, Gs, atol=1e-05)\n np.testing.assert_allclose(G0, Ges, atol=1e-05)\n np.testing.assert_allclose(G0, G_green, atol=1e-5)\n print(G0, G_green)\n\n\ndef test_sinkhorn_variants_log():\n # test sinkhorn\n n = 100\n rng = np.random.RandomState(0)\n\n x = rng.randn(n, 2)\n u = ot.utils.unif(n)\n\n M = ot.dist(x, x)\n\n G0, log0 = ot.sinkhorn(u, u, M, 1, method='sinkhorn', stopThr=1e-10, log=True)\n Gs, logs = ot.sinkhorn(u, u, M, 1, method='sinkhorn_stabilized', stopThr=1e-10, log=True)\n Ges, loges = ot.sinkhorn(\n u, u, M, 1, method='sinkhorn_epsilon_scaling', stopThr=1e-10, log=True)\n G_green, loggreen = ot.sinkhorn(u, u, M, 1, method='greenkhorn', stopThr=1e-10, log=True)\n\n # check values\n np.testing.assert_allclose(G0, Gs, atol=1e-05)\n np.testing.assert_allclose(G0, Ges, atol=1e-05)\n np.testing.assert_allclose(G0, G_green, atol=1e-5)\n print(G0, G_green)\n\n\[email protected](\"method\", [\"sinkhorn\", \"sinkhorn_stabilized\"])\ndef test_barycenter(method):\n\n n_bins = 100 # nb bins\n\n # Gaussian distributions\n a1 = ot.datasets.make_1D_gauss(n_bins, m=30, s=10) # m= mean, s= std\n a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)\n\n # creating matrix A containing all distributions\n A = np.vstack((a1, a2)).T\n\n # loss matrix + normalization\n M = ot.utils.dist0(n_bins)\n M /= M.max()\n\n alpha = 0.5 # 0<=alpha<=1\n weights = np.array([1 - alpha, alpha])\n\n # wasserstein\n reg = 1e-2\n bary_wass = ot.bregman.barycenter(A, M, reg, weights, method=method)\n\n np.testing.assert_allclose(1, np.sum(bary_wass))\n\n ot.bregman.barycenter(A, M, reg, log=True, verbose=True)\n\n\ndef test_barycenter_stabilization():\n\n n_bins = 100 # nb bins\n\n # Gaussian distributions\n a1 = ot.datasets.make_1D_gauss(n_bins, m=30, s=10) # m= mean, s= std\n a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)\n\n # creating matrix A containing all distributions\n A = np.vstack((a1, a2)).T\n\n # loss matrix + normalization\n M = ot.utils.dist0(n_bins)\n M /= M.max()\n\n alpha = 0.5 # 0<=alpha<=1\n weights = np.array([1 - alpha, alpha])\n\n # wasserstein\n reg = 1e-2\n bar_stable = ot.bregman.barycenter(A, M, reg, weights,\n method=\"sinkhorn_stabilized\",\n stopThr=1e-8)\n bar = ot.bregman.barycenter(A, M, reg, weights, method=\"sinkhorn\",\n stopThr=1e-8)\n np.testing.assert_allclose(bar, bar_stable)\n\n\ndef test_wasserstein_bary_2d():\n\n size = 100 # size of a square image\n a1 = np.random.randn(size, size)\n a1 += a1.min()\n a1 = a1 / np.sum(a1)\n a2 = np.random.randn(size, size)\n a2 += a2.min()\n a2 = a2 / np.sum(a2)\n # creating matrix A containing all distributions\n A = np.zeros((2, size, size))\n A[0, :, :] = a1\n A[1, :, :] = a2\n\n # wasserstein\n reg = 1e-2\n bary_wass = ot.bregman.convolutional_barycenter2d(A, reg)\n\n np.testing.assert_allclose(1, np.sum(bary_wass))\n\n # help in checking if log and verbose do not bug the function\n ot.bregman.convolutional_barycenter2d(A, reg, log=True, verbose=True)\n\n\ndef test_unmix():\n\n n_bins = 50 # nb bins\n\n # Gaussian distributions\n a1 = ot.datasets.make_1D_gauss(n_bins, m=20, s=10) # m= mean, s= std\n a2 = ot.datasets.make_1D_gauss(n_bins, m=40, s=10)\n\n a = ot.datasets.make_1D_gauss(n_bins, m=30, s=10)\n\n # creating matrix A containing all distributions\n D = np.vstack((a1, a2)).T\n\n # loss matrix + normalization\n M = ot.utils.dist0(n_bins)\n M /= M.max()\n\n M0 = ot.utils.dist0(2)\n M0 /= M0.max()\n h0 = ot.unif(2)\n\n # wasserstein\n reg = 1e-3\n um = ot.bregman.unmix(a, D, M, M0, h0, reg, 1, alpha=0.01,)\n\n np.testing.assert_allclose(1, np.sum(um), rtol=1e-03, atol=1e-03)\n np.testing.assert_allclose([0.5, 0.5], um, rtol=1e-03, atol=1e-03)\n\n ot.bregman.unmix(a, D, M, M0, h0, reg,\n 1, alpha=0.01, log=True, verbose=True)\n\n\ndef test_empirical_sinkhorn():\n # test sinkhorn\n n = 100\n a = ot.unif(n)\n b = ot.unif(n)\n\n X_s = np.reshape(np.arange(n), (n, 1))\n X_t = np.reshape(np.arange(0, n), (n, 1))\n M = ot.dist(X_s, X_t)\n M_m = ot.dist(X_s, X_t, metric='minkowski')\n\n G_sqe = ot.bregman.empirical_sinkhorn(X_s, X_t, 1)\n sinkhorn_sqe = ot.sinkhorn(a, b, M, 1)\n\n G_log, log_es = ot.bregman.empirical_sinkhorn(X_s, X_t, 0.1, log=True)\n sinkhorn_log, log_s = ot.sinkhorn(a, b, M, 0.1, log=True)\n\n G_m = ot.bregman.empirical_sinkhorn(X_s, X_t, 1, metric='minkowski')\n sinkhorn_m = ot.sinkhorn(a, b, M_m, 1)\n\n loss_emp_sinkhorn = ot.bregman.empirical_sinkhorn2(X_s, X_t, 1)\n loss_sinkhorn = ot.sinkhorn2(a, b, M, 1)\n\n # check constratints\n np.testing.assert_allclose(\n sinkhorn_sqe.sum(1), G_sqe.sum(1), atol=1e-05) # metric sqeuclidian\n np.testing.assert_allclose(\n sinkhorn_sqe.sum(0), G_sqe.sum(0), atol=1e-05) # metric sqeuclidian\n np.testing.assert_allclose(\n sinkhorn_log.sum(1), G_log.sum(1), atol=1e-05) # log\n np.testing.assert_allclose(\n sinkhorn_log.sum(0), G_log.sum(0), atol=1e-05) # log\n np.testing.assert_allclose(\n sinkhorn_m.sum(1), G_m.sum(1), atol=1e-05) # metric euclidian\n np.testing.assert_allclose(\n sinkhorn_m.sum(0), G_m.sum(0), atol=1e-05) # metric euclidian\n np.testing.assert_allclose(loss_emp_sinkhorn, loss_sinkhorn, atol=1e-05)\n\n\ndef test_empirical_sinkhorn_divergence():\n #Test sinkhorn divergence\n n = 10\n a = ot.unif(n)\n b = ot.unif(n)\n X_s = np.reshape(np.arange(n), (n, 1))\n X_t = np.reshape(np.arange(0, n * 2, 2), (n, 1))\n M = ot.dist(X_s, X_t)\n M_s = ot.dist(X_s, X_s)\n M_t = ot.dist(X_t, X_t)\n\n emp_sinkhorn_div = ot.bregman.empirical_sinkhorn_divergence(X_s, X_t, 1)\n sinkhorn_div = (ot.sinkhorn2(a, b, M, 1) - 1 / 2 * ot.sinkhorn2(a, a, M_s, 1) - 1 / 2 * ot.sinkhorn2(b, b, M_t, 1))\n\n emp_sinkhorn_div_log, log_es = ot.bregman.empirical_sinkhorn_divergence(X_s, X_t, 1, log=True)\n sink_div_log_ab, log_s_ab = ot.sinkhorn2(a, b, M, 1, log=True)\n sink_div_log_a, log_s_a = ot.sinkhorn2(a, a, M_s, 1, log=True)\n sink_div_log_b, log_s_b = ot.sinkhorn2(b, b, M_t, 1, log=True)\n sink_div_log = sink_div_log_ab - 1 / 2 * (sink_div_log_a + sink_div_log_b)\n\n # check constratints\n np.testing.assert_allclose(\n emp_sinkhorn_div, sinkhorn_div, atol=1e-05) # cf conv emp sinkhorn\n np.testing.assert_allclose(\n emp_sinkhorn_div_log, sink_div_log, atol=1e-05) # cf conv emp sinkhorn\n\n\ndef test_stabilized_vs_sinkhorn_multidim():\n # test if stable version matches sinkhorn\n # for multidimensional inputs\n n = 100\n\n # Gaussian distributions\n a = ot.datasets.make_1D_gauss(n, m=20, s=5) # m= mean, s= std\n b1 = ot.datasets.make_1D_gauss(n, m=60, s=8)\n b2 = ot.datasets.make_1D_gauss(n, m=30, s=4)\n\n # creating matrix A containing all distributions\n b = np.vstack((b1, b2)).T\n\n M = ot.utils.dist0(n)\n M /= np.median(M)\n epsilon = 0.1\n G, log = ot.bregman.sinkhorn(a, b, M, reg=epsilon,\n method=\"sinkhorn_stabilized\",\n log=True)\n G2, log2 = ot.bregman.sinkhorn(a, b, M, epsilon,\n method=\"sinkhorn\", log=True)\n\n np.testing.assert_allclose(G, G2)\n\n\ndef test_implemented_methods():\n IMPLEMENTED_METHODS = ['sinkhorn', 'sinkhorn_stabilized']\n ONLY_1D_methods = ['greenkhorn', 'sinkhorn_epsilon_scaling']\n NOT_VALID_TOKENS = ['foo']\n # test generalized sinkhorn for unbalanced OT barycenter\n n = 3\n rng = np.random.RandomState(42)\n\n x = rng.randn(n, 2)\n a = ot.utils.unif(n)\n\n # make dists unbalanced\n b = ot.utils.unif(n)\n A = rng.rand(n, 2)\n M = ot.dist(x, x)\n epsilon = 1.\n\n for method in IMPLEMENTED_METHODS:\n ot.bregman.sinkhorn(a, b, M, epsilon, method=method)\n ot.bregman.sinkhorn2(a, b, M, epsilon, method=method)\n ot.bregman.barycenter(A, M, reg=epsilon, method=method)\n with pytest.raises(ValueError):\n for method in set(NOT_VALID_TOKENS):\n ot.bregman.sinkhorn(a, b, M, epsilon, method=method)\n ot.bregman.sinkhorn2(a, b, M, epsilon, method=method)\n ot.bregman.barycenter(A, M, reg=epsilon, method=method)\n for method in ONLY_1D_methods:\n ot.bregman.sinkhorn(a, b, M, epsilon, method=method)\n with pytest.raises(ValueError):\n ot.bregman.sinkhorn2(a, b, M, epsilon, method=method)\n" ]
[ [ "numpy.vstack", "numpy.sum", "numpy.zeros", "numpy.random.randn", "numpy.median", "numpy.random.RandomState", "numpy.arange", "numpy.testing.assert_allclose", "numpy.array" ] ]
linus87/drl_shape_optimization
[ "39e6b66bd5b70dfce07e145aafe815071bc1b6fe" ]
[ "src/tensorforce/tensorforce/core/optimizers/optimizer.py" ]
[ "# Copyright 2018 Tensorforce Team. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nimport tensorflow as tf\n\nfrom tensorforce import TensorforceError, util\nfrom tensorforce.core import Module\n\n\nclass Optimizer(Module):\n \"\"\"\n Base class for optimizers which minimize a not yet further specified expression, usually some\n kind of loss function. More generally, an optimizer can be considered as some method of\n updating a set of variables.\n \"\"\"\n\n def __init__(self, name, summary_labels=None):\n super().__init__(name=name, l2_regularization=0.0, summary_labels=summary_labels)\n\n def tf_step(self, variables, **kwargs):\n \"\"\"\n Creates the TensorFlow operations for performing an optimization step on the given \n variables, including actually changing the values of the variables.\n\n Args:\n variables: List of variables to optimize.\n **kwargs: Additional arguments depending on the specific optimizer implementation. \n For instance, often includes `fn_loss` if a loss function is optimized.\n\n Returns:\n List of delta tensors corresponding to the updates for each optimized variable.\n \"\"\"\n raise NotImplementedError\n\n def tf_apply_step(self, variables, deltas):\n \"\"\"\n Applies the given (and already calculated) step deltas to the variable values.\n\n Args:\n variables: List of variables.\n deltas: List of deltas of same length.\n\n Returns:\n The step-applied operation. A tf.group of tf.assign_add ops.\n \"\"\"\n if len(variables) != len(deltas):\n raise TensorforceError(\"Invalid variables and deltas lists.\")\n\n assignments = list()\n for variable, delta in zip(variables, deltas):\n assignments.append(tf.assign_add(ref=variable, value=delta))\n\n with tf.control_dependencies(control_inputs=assignments):\n return util.no_operation()\n\n def tf_minimize(self, variables, **kwargs):\n \"\"\"\n Performs an optimization step.\n\n Args:\n variables: List of variables to optimize.\n **kwargs: Additional optimizer-specific arguments. The following arguments are used\n by some optimizers:\n - arguments: Dict of arguments for callables, like fn_loss.\n - fn_loss: A callable returning the loss of the current model.\n - fn_reference: A callable returning the reference values, in case of a comparative \n loss.\n - fn_kl_divergence: A callable returning the KL-divergence relative to the\n current model.\n - sampled_loss: A sampled loss (integer).\n - return_estimated_improvement: Returns the estimated improvement resulting from\n the natural gradient calculation if true.\n - source_variables: List of source variables to synchronize with.\n - global_variables: List of global variables to apply the proposed optimization\n step to.\n\n\n Returns:\n The optimization operation.\n \"\"\"\n deltas = self.step(variables=variables, **kwargs)\n\n for n in range(len(variables)):\n name = variables[n].name\n if name[-2:] != ':0':\n raise TensorforceError.unexpected()\n deltas[n] = self.add_summary(\n label=('updates', 'updates-full'), name=(name[:-2] + '-update'), tensor=deltas[n],\n mean_variance=True\n )\n deltas[n] = self.add_summary(\n label='updates-full', name=(name[:-2] + '-update'), tensor=deltas[n]\n )\n\n with tf.control_dependencies(control_inputs=deltas):\n return util.no_operation()\n\n def add_variable(self, name, dtype, shape, is_trainable=False, initializer='zeros'):\n if is_trainable:\n raise TensorforceError(\"Invalid trainable variable.\")\n\n return super().add_variable(\n name=name, dtype=dtype, shape=shape, is_trainable=is_trainable, initializer=initializer\n )\n" ]
[ [ "tensorflow.assign_add", "tensorflow.control_dependencies" ] ]
SaronZhou/python
[ "40d73b49b9b17542c73a3c09d28e479d2fefcde3" ]
[ "sjfxjc/foundations-for-analytics-with-python-master/csv/pandas_value_meets_condition.py" ]
[ "#!/usr/bin/env python3\nimport pandas as pd\nimport sys\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\n\ndata_frame = pd.read_csv(input_file)\n\ndata_frame['Cost'] = data_frame['Cost'].str.strip('$').astype(float)\ndata_frame_value_meets_condition = data_frame.loc[(data_frame['Supplier Name']\\\n.str.contains('Z')) | (data_frame['Cost'] > 600.0), :]\n\ndata_frame_value_meets_condition.to_csv(output_file, index=False)" ]
[ [ "pandas.read_csv" ] ]
yohasebe/spaCy
[ "3dcb747980303457c662d668d5a0735c9efc9b72" ]
[ "spacy/tests/pipeline/test_spancat.py" ]
[ "from numpy.testing import assert_equal\nfrom spacy.language import Language\nfrom spacy.training import Example\nfrom spacy.util import fix_random_seed, registry\n\n\nSPAN_KEY = \"labeled_spans\"\n\nTRAIN_DATA = [\n (\"Who is Shaka Khan?\", {\"spans\": {SPAN_KEY: [(7, 17, \"PERSON\")]}}),\n (\n \"I like London and Berlin.\",\n {\"spans\": {SPAN_KEY: [(7, 13, \"LOC\"), (18, 24, \"LOC\")]}},\n ),\n]\n\n\ndef make_get_examples(nlp):\n train_examples = []\n for t in TRAIN_DATA:\n eg = Example.from_dict(nlp.make_doc(t[0]), t[1])\n train_examples.append(eg)\n\n def get_examples():\n return train_examples\n\n return get_examples\n\n\ndef test_simple_train():\n fix_random_seed(0)\n nlp = Language()\n spancat = nlp.add_pipe(\"spancat\", config={\"spans_key\": SPAN_KEY})\n get_examples = make_get_examples(nlp)\n nlp.initialize(get_examples)\n sgd = nlp.create_optimizer()\n assert len(spancat.labels) != 0\n for i in range(40):\n losses = {}\n nlp.update(list(get_examples()), losses=losses, drop=0.1, sgd=sgd)\n doc = nlp(\"I like London and Berlin.\")\n assert doc.spans[spancat.key] == doc.spans[SPAN_KEY]\n assert len(doc.spans[spancat.key]) == 2\n assert doc.spans[spancat.key][0].text == \"London\"\n scores = nlp.evaluate(get_examples())\n assert f\"spans_{SPAN_KEY}_f\" in scores\n assert scores[f\"spans_{SPAN_KEY}_f\"] == 1.0\n\n\ndef test_ngram_suggester(en_tokenizer):\n # test different n-gram lengths\n for size in [1, 2, 3]:\n ngram_suggester = registry.misc.get(\"ngram_suggester.v1\")(sizes=[size])\n docs = [\n en_tokenizer(text)\n for text in [\n \"a\",\n \"a b\",\n \"a b c\",\n \"a b c d\",\n \"a b c d e\",\n \"a \" * 100,\n ]\n ]\n ngrams = ngram_suggester(docs)\n # span sizes are correct\n for s in ngrams.data:\n assert s[1] - s[0] == size\n # spans are within docs\n offset = 0\n for i, doc in enumerate(docs):\n spans = ngrams.dataXd[offset : offset + ngrams.lengths[i]]\n spans_set = set()\n for span in spans:\n assert 0 <= span[0] < len(doc)\n assert 0 < span[1] <= len(doc)\n spans_set.add((span[0], span[1]))\n # spans are unique\n assert spans.shape[0] == len(spans_set)\n offset += ngrams.lengths[i]\n # the number of spans is correct\n assert_equal(ngrams.lengths, [max(0, len(doc) - (size - 1)) for doc in docs])\n\n # test 1-3-gram suggestions\n ngram_suggester = registry.misc.get(\"ngram_suggester.v1\")(sizes=[1, 2, 3])\n docs = [\n en_tokenizer(text) for text in [\"a\", \"a b\", \"a b c\", \"a b c d\", \"a b c d e\"]\n ]\n ngrams = ngram_suggester(docs)\n assert_equal(ngrams.lengths, [1, 3, 6, 9, 12])\n assert_equal(\n ngrams.data,\n [\n # doc 0\n [0, 1],\n # doc 1\n [0, 1],\n [1, 2],\n [0, 2],\n # doc 2\n [0, 1],\n [1, 2],\n [2, 3],\n [0, 2],\n [1, 3],\n [0, 3],\n # doc 3\n [0, 1],\n [1, 2],\n [2, 3],\n [3, 4],\n [0, 2],\n [1, 3],\n [2, 4],\n [0, 3],\n [1, 4],\n # doc 4\n [0, 1],\n [1, 2],\n [2, 3],\n [3, 4],\n [4, 5],\n [0, 2],\n [1, 3],\n [2, 4],\n [3, 5],\n [0, 3],\n [1, 4],\n [2, 5],\n ],\n )\n\n # test some empty docs\n ngram_suggester = registry.misc.get(\"ngram_suggester.v1\")(sizes=[1])\n docs = [en_tokenizer(text) for text in [\"\", \"a\", \"\"]]\n ngrams = ngram_suggester(docs)\n assert_equal(ngrams.lengths, [len(doc) for doc in docs])\n\n # test all empty docs\n ngram_suggester = registry.misc.get(\"ngram_suggester.v1\")(sizes=[1])\n docs = [en_tokenizer(text) for text in [\"\", \"\", \"\"]]\n ngrams = ngram_suggester(docs)\n assert_equal(ngrams.lengths, [len(doc) for doc in docs])\n" ]
[ [ "numpy.testing.assert_equal" ] ]