repo_name
stringlengths
8
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
dependencyInversion/UdemyML
[ "9e1a0a01688a82c61ef006a592a58c12fb186552" ]
[ "Chapter2_Python/NumpyIntro.py" ]
[ "import numpy as np\n\nlist1 = np.array([-2, 1, 2, -10, 22, -10])\nlist2 = np.array([-20, 123, 112, -10, 22, -120])\n\nprint(\n f\"values: {list1}\",\n f\"min: {np.min(list1)}\",\n f\"max: {np.max(list1)}\",\n f\"mean: {np.mean(list1)}\",\n f\"median: {np.median(list2)}\",\n sep=\"\\n\",\n end=\"\\n\\n\"\n)\n\nprint(\n f\"values: {list2}\",\n f\"min: {np.min(list2)}\",\n f\"max: {np.max(list2)}\",\n f\"mean: {np.mean(list2)}\",\n f\"median: {np.median(list2)}\",\n sep=\"\\n\",\n end=\"\\n\\n\"\n)\n" ]
[ [ "numpy.median", "numpy.max", "numpy.min", "numpy.array", "numpy.mean" ] ]
RobZelluf/RL_pong
[ "55c8feeb9c43c1c11d6fd8924660e8038138cf7e" ]
[ "DQN_SAA/DQN_SAA.py" ]
[ "from wimblepong import Wimblepong\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport numpy as np\nfrom utils import Transition, ReplayMemory\n\n\nclass Q_CNN(nn.Module):\n def __init__(self, state_space, action_space, size, fc1_size=64):\n super(Q_CNN, self).__init__()\n self.state_space = state_space\n self.action_space = action_space\n self.linear_size = 13 * 13 * 32\n\n self.conv1 = nn.Conv2d(1, 8, 4, 4)\n self.conv2 = nn.Conv2d(8, 16, 3, 2)\n self.conv3 = nn.Conv2d(16, 32, 2, 1)\n self.fc1 = torch.nn.Linear(self.linear_size, fc1_size)\n self.fc2 = torch.nn.Linear(fc1_size, action_space)\n\n def forward(self, x):\n # Computes the activation of the first convolution\n # Size changes from (3, 32, 32) to (18, 32, 32)\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n print(x.shape)\n\n # Reshape data to input to the input layer of the neural net\n # Size changes from (18, 16, 16) to (1, 4608)\n # Recall that the -1 infers this dimension from the other given dimension\n x = x.view(-1, self.fc1.in_features)\n\n # Computes the activation of the first fully connected layer\n # Size changes from (1, 4608) to (1, 64)\n x = F.relu(self.fc1(x))\n\n # Computes the second fully connected layer (activation applied later)\n # Size changes from (1, 64) to (1, 10)\n x = self.fc2(x)\n return x\n\n\nclass DQN_SAA(object):\n def __init__(self, env, player_id=1, size=200, model_info=None, fc1_size=64):\n if type(env) is not Wimblepong:\n raise TypeError(\"I'm not a very smart AI. All I can play is Wimblepong.\")\n\n self.env = env\n self.player_id = player_id\n self.name = \"SAA\"\n self.gamma = 0.98\n self.size = size\n self.fc1_size = fc1_size\n\n if torch.cuda.is_available():\n print(\"Using GPU!\")\n torch.cuda.set_device(0)\n\n self.state_space = env.observation_space\n self.action_space = env.action_space.n\n self.memory = ReplayMemory()\n self.batch_size = 256 * 2\n self.chosen_actions = np.zeros(self.action_space)\n\n if model_info is not None:\n self.policy_net = torch.load(\"DQN_SAA/\" + model_info[\"model_name\"] + \"/policy_net.pth\")\n self.size = model_info[\"size\"]\n print(\"Policy loaded!\")\n else:\n self.policy_net = Q_CNN(self.state_space, self.action_space, size, fc1_size=fc1_size)\n\n self.target_net = self.policy_net\n self.optimizer = optim.Adam(self.policy_net.parameters(), lr=1e-4)\n\n def update_network(self, updates=1):\n for _ in range(updates):\n self._do_network_update()\n\n def _do_network_update(self):\n if len(self.memory) < self.batch_size:\n return\n\n transitions = self.memory.sample(self.batch_size)\n # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n # detailed explanation). This converts batch-array of Transitions\n # to Transition of batch-arrays.\n batch = Transition(*zip(*transitions))\n\n # Compute a mask of non-final states and concatenate the batch elements\n # (a final state would've been the one after which simulation ended)\n non_final_mask = 1 - torch.tensor(batch.done, dtype=torch.uint8)\n non_final_next_states = [s for nonfinal, s in zip(non_final_mask,\n batch.next_state) if nonfinal > 0]\n non_final_next_states = torch.stack(non_final_next_states)\n state_batch = torch.stack(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n\n state_action_values = self.policy_net(state_batch).gather(1, action_batch)\n\n next_state_values = torch.zeros(self.batch_size)\n next_state_values[non_final_mask] = self.target_net(non_final_next_states).max(1)[0].detach()\n\n expected_state_action_values = reward_batch + self.gamma * next_state_values\n\n loss = F.mse_loss(state_action_values.squeeze(),\n expected_state_action_values)\n\n # Optimize the model\n self.optimizer.zero_grad()\n loss.backward()\n for param in self.policy_net.parameters():\n param.grad.data.clamp_(-1e-1, 1e-1)\n self.optimizer.step()\n\n def get_name(self):\n return self.name\n\n def get_action(self, state, epsilon=0.05):\n sample = random.random()\n if sample > epsilon:\n with torch.no_grad():\n state = state.reshape(1, 1, self.size, self.size)\n state = torch.from_numpy(state).float()\n q_values = self.policy_net(state)\n action = torch.argmax(q_values).item()\n self.chosen_actions[action] += 1\n\n return action\n else:\n return random.randrange(self.action_space)\n\n def update_target_network(self):\n self.target_net.load_state_dict(self.policy_net.state_dict())\n\n def store_transition(self, state, action, next_state, reward, done):\n action = torch.Tensor([[action]]).long()\n reward = torch.tensor([reward], dtype=torch.float32)\n next_state = torch.from_numpy(next_state).float()\n state = torch.from_numpy(state).float()\n self.memory.push(state, action, next_state, reward, done)" ]
[ [ "torch.stack", "torch.nn.Linear", "torch.load", "numpy.zeros", "torch.argmax", "torch.no_grad", "torch.tensor", "torch.cuda.is_available", "torch.nn.Conv2d", "torch.from_numpy", "torch.zeros", "torch.cat", "torch.Tensor", "torch.cuda.set_device" ] ]
adellanno/MetaXcan
[ "cfc9e369bbf5630e0c9488993cd877f231c5d02e" ]
[ "software/metax/misc/KeyedDataSource.py" ]
[ "import gzip\nimport io\nimport pandas\n\nfrom .. import Utilities\n\ndef try_parse(string, fail=None):\n try:\n return float(string)\n except Exception:\n return fail;\n\ndef skip_na(key, value):\n skip = (not value or value == \"NA\")\n return skip\n\ndef skip_non_rsid_value(key, value):\n return not \"rs\" in value\n\ndef dot_to_na(value):\n return \"NA\" if value == \".\" else value\n\ndef load_data(path, key_name, value_name, white_list=None, value_white_list=None, numeric=False, should_skip=None, value_conversion=None, key_filter=None):\n data = {}\n c_key=None\n c_value=None\n for i, line in enumerate(Utilities.generate_from_any_plain_file(path)):\n if i==0:\n header = line.strip().split()\n c_key = header.index(key_name)\n c_value = header.index(value_name)\n continue\n\n comps = line.strip().split()\n key = comps[c_key]\n if white_list and not key in white_list:\n continue\n if key_filter and key_filter(key):\n continue\n\n value = comps[c_value]\n if value_white_list and not value in value_white_list:\n continue\n\n if should_skip and should_skip(key, value):\n continue\n\n if value_conversion:\n value = value_conversion(value)\n elif numeric:\n value = try_parse(value)\n\n if value:\n data[key] = value\n\n return data\n\ndef load_data_column(path, column_name):\n def _ogz(p):\n return io.TextIOWrapper(gzip.open(p, \"r\"), newline=\"\")\n _o = _ogz if \".gz\" in path else open\n data = []\n c_key=None\n with _o(path) as file:\n for i, line in enumerate(file):\n if i==0:\n header = line.strip().split()\n c_key = header.index(column_name)\n continue\n\n comps = line.strip().split()\n value = comps[c_key]\n data.append(value)\n return data\n\ndef to_data_frame(data, keys, key_column, value_column, to_numeric=None):\n ids = [x for x in keys if x in data]\n data = [(x, data[x]) for x in ids]\n if len(data) == 0:\n return pandas.DataFrame({key_column: [], value_column: []})\n data = Utilities.to_dataframe(data, [key_column, value_column], to_numeric)\n return data" ]
[ [ "pandas.DataFrame" ] ]
simonfqy/DTI_prediction
[ "e01c592cc06c4de04b3ed6db35da5af5ff7f863f" ]
[ "davis_data/preprocess.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport os\nimport sys\nimport pdb\nimport csv\n\n\ndef generate_data(input_csv, binarize=False, head_only=False, head_row_num=15000, \n limit_rows=False, limit_row_num=2400, prefix=\"davis_\", input_prot=True, output_csv=None):\n df = pd.read_csv(input_csv, header = 2, index_col=0, usecols=range(3, 76))\n if head_only:\n df = df.head(head_row_num)\n molList = list(df)\n #print(len(molList))\n protList = list(df.index)\n interactions = [] \n for row in df.itertuples():\n intxn = list(row)[1:]\n interactions.append(intxn) \n #print(interactions)\n interactions = np.array(interactions)\n interactions[np.isnan(interactions)] = 10000\n interactions = 9 - np.log10(interactions)\n if binarize:\n interaction_bin = (interactions >= 7.0) * 1\n if limit_rows:\n counter = 0\n with open(output_csv, 'w', newline='') as csvfile:\n fieldnames = ['smiles']\n if input_prot:\n fieldnames = ['davis'] + fieldnames + ['proteinName', 'protein_dataset']\n if binarize:\n fieldnames = ['davis_bin'] + fieldnames\n else:\n tasks = [prefix + prot for prot in protList]\n fieldnames = tasks + fieldnames\n writer = csv.DictWriter(csvfile, fieldnames = fieldnames)\n writer.writeheader()\n\n if input_prot:\n for i, protein in enumerate(protList): \n output_dict = {'proteinName': protein, 'protein_dataset': 'davis'}\n for j, compound in enumerate(molList):\n # will start writing rows.\n intxn_value = interactions[i][j]\n output_dict.update({'davis': intxn_value, 'smiles': compound})\n if binarize:\n intxn_bin = interaction_bin[i][j]\n output_dict['davis_bin'] = intxn_bin \n writer.writerow(output_dict)\n if not limit_rows:\n continue\n counter += 1\n if (counter > limit_row_num):\n break\n if not limit_rows:\n continue\n if (counter > limit_row_num):\n break\n else:\n for j, compound in enumerate(molList):\n output_dict = {'smiles': compound}\n for i, _ in enumerate(protList):\n task_name = fieldnames[i]\n output_dict[task_name] = interactions[i][j]\n writer.writerow(output_dict)\n\nif __name__ == '__main__':\n generate_data('Bio_results.csv', input_prot=True, limit_rows=True, limit_row_num=2400, \n output_csv='restructured_toy.csv')\n \n" ]
[ [ "numpy.array", "numpy.log10", "numpy.isnan" ] ]
zjjszj/PS_DM_mydetector_faster_rcnn_pytorch
[ "f1d3ad0711ca6b606f05dfee3ed223edd0ea699f" ]
[ "faster_rcnn/datasets/imdb.py" ]
[ "# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\nimport os\nimport os.path as osp\nimport PIL\nimport numpy as np\nimport scipy.sparse\n\nfrom ..utils.cython_bbox import bbox_overlaps\nfrom PIL import Image\n\n# TODO: make fast_rcnn irrelevant\n# >>>> obsolete, because it depends on sth outside of this project\nfrom ..fast_rcnn.config import cfg\n\n# <<<< obsolete\n\nROOT_DIR = osp.join(osp.dirname(__file__), '..', '..')\nMATLAB = 'matlab_r2013b'\n\n\nclass imdb(object):\n \"\"\"Image database.\"\"\"\n\n def __init__(self, name):\n self._name = name\n self._num_classes = 0\n self._classes = []\n self._image_index = []\n self._obj_proposer = 'selective_search'\n self._roidb = None\n print (self.default_roidb)\n self._roidb_handler = self.default_roidb\n # Use this dict for storing dataset specific config options\n self.config = {}\n\n @property\n def name(self):\n return self._name\n\n @property\n def num_classes(self):\n return len(self._classes)\n\n @property\n def classes(self):\n return self._classes\n\n @property\n def image_index(self):\n return self._image_index\n\n @property\n def roidb_handler(self):\n return self._roidb_handler\n\n @roidb_handler.setter\n def roidb_handler(self, val):\n self._roidb_handler = val\n\n def set_proposal_method(self, method):\n method = eval('self.' + method + '_roidb')\n self.roidb_handler = method\n\n @property\n def roidb(self):\n # A roidb is a list of dictionaries, each with the following keys:\n # boxes\n # gt_overlaps\n # gt_classes\n # flipped\n if self._roidb is not None:\n return self._roidb\n self._roidb = self.roidb_handler()\n return self._roidb\n\n @property\n def cache_path(self):\n cache_path = osp.abspath(osp.join(cfg.DATA_DIR, 'cache'))\n if not os.path.exists(cache_path):\n os.makedirs(cache_path)\n return cache_path\n\n @property\n def num_images(self):\n return len(self.image_index)\n\n def image_path_at(self, i):\n raise NotImplementedError\n\n def default_roidb(self):\n raise NotImplementedError\n\n def evaluate_detections(self, all_boxes, output_dir=None):\n \"\"\"\n all_boxes is a list of length number-of-classes.\n Each list element is a list of length number-of-images.\n Each of those list elements is either an empty list []\n or a numpy array of detection.\n\n all_boxes[class][image] = [] or np.array of shape #dets x 5\n \"\"\"\n raise NotImplementedError\n\n def _get_widths(self):\n return [PIL.Image.open(self.image_path_at(i)).size[0]\n for i in range(self.num_images)]\n\n def append_flipped_images(self):\n num_images = self.num_images\n widths = self._get_widths()\n for i in range(num_images):\n boxes = self.roidb[i]['boxes'].copy()\n oldx1 = boxes[:, 0].copy()\n oldx2 = boxes[:, 2].copy()\n boxes[:, 0] = widths[i] - oldx2 - 1\n boxes[:, 2] = widths[i] - oldx1 - 1\n assert (boxes[:, 2] >= boxes[:, 0]).all()\n entry = {'boxes': boxes,\n 'gt_overlaps': self.roidb[i]['gt_overlaps'],\n 'gt_classes': self.roidb[i]['gt_classes'],\n 'flipped': True}\n\n if 'gt_ishard' in self.roidb[i] and 'dontcare_areas' in self.roidb[i]:\n entry['gt_ishard'] = self.roidb[i]['gt_ishard'].copy()\n dontcare_areas = self.roidb[i]['dontcare_areas'].copy()\n oldx1 = dontcare_areas[:, 0].copy()\n oldx2 = dontcare_areas[:, 2].copy()\n dontcare_areas[:, 0] = widths[i] - oldx2 - 1\n dontcare_areas[:, 2] = widths[i] - oldx1 - 1\n entry['dontcare_areas'] = dontcare_areas\n\n self.roidb.append(entry)\n\n self._image_index = self._image_index * 2\n\n def evaluate_recall(self, candidate_boxes=None, thresholds=None,\n area='all', limit=None):\n \"\"\"Evaluate detection proposal recall metrics.\n\n Returns:\n results: dictionary of results with keys\n 'ar': average recall\n 'recalls': vector recalls at each IoU overlap threshold\n 'thresholds': vector of IoU overlap thresholds\n 'gt_overlaps': vector of all ground-truth overlaps\n \"\"\"\n # Record max overlap value for each gt box\n # Return vector of overlap values\n areas = {'all': 0, 'small': 1, 'medium': 2, 'large': 3,\n '96-128': 4, '128-256': 5, '256-512': 6, '512-inf': 7}\n area_ranges = [[0 ** 2, 1e5 ** 2], # all\n [0 ** 2, 32 ** 2], # small\n [32 ** 2, 96 ** 2], # medium\n [96 ** 2, 1e5 ** 2], # large\n [96 ** 2, 128 ** 2], # 96-128\n [128 ** 2, 256 ** 2], # 128-256\n [256 ** 2, 512 ** 2], # 256-512\n [512 ** 2, 1e5 ** 2], # 512-inf\n ]\n assert areas.has_key(area), 'unknown area range: {}'.format(area)\n area_range = area_ranges[areas[area]]\n gt_overlaps = np.zeros(0)\n num_pos = 0\n for i in range(self.num_images):\n # Checking for max_overlaps == 1 avoids including crowd annotations\n # (...pretty hacking :/)\n max_gt_overlaps = self.roidb[i]['gt_overlaps'].toarray().max(axis=1)\n gt_inds = np.where((self.roidb[i]['gt_classes'] > 0) &\n (max_gt_overlaps == 1))[0]\n gt_boxes = self.roidb[i]['boxes'][gt_inds, :]\n gt_areas = self.roidb[i]['seg_areas'][gt_inds]\n valid_gt_inds = np.where((gt_areas >= area_range[0]) &\n (gt_areas <= area_range[1]))[0]\n gt_boxes = gt_boxes[valid_gt_inds, :]\n num_pos += len(valid_gt_inds)\n\n if candidate_boxes is None:\n # If candidate_boxes is not supplied, the default is to use the\n # non-ground-truth boxes from this roidb\n non_gt_inds = np.where(self.roidb[i]['gt_classes'] == 0)[0]\n boxes = self.roidb[i]['boxes'][non_gt_inds, :]\n else:\n boxes = candidate_boxes[i]\n if boxes.shape[0] == 0:\n continue\n if limit is not None and boxes.shape[0] > limit:\n boxes = boxes[:limit, :]\n\n overlaps = bbox_overlaps(boxes.astype(np.float),\n gt_boxes.astype(np.float))\n\n _gt_overlaps = np.zeros((gt_boxes.shape[0]))\n for j in range(gt_boxes.shape[0]):\n # find which proposal box maximally covers each gt box\n argmax_overlaps = overlaps.argmax(axis=0)\n # and get the iou amount of coverage for each gt box\n max_overlaps = overlaps.max(axis=0)\n # find which gt box is 'best' covered (i.e. 'best' = most iou)\n gt_ind = max_overlaps.argmax()\n gt_ovr = max_overlaps.max()\n assert (gt_ovr >= 0)\n # find the proposal box that covers the best covered gt box\n box_ind = argmax_overlaps[gt_ind]\n # record the iou coverage of this gt box\n _gt_overlaps[j] = overlaps[box_ind, gt_ind]\n assert (_gt_overlaps[j] == gt_ovr)\n # mark the proposal box and the gt box as used\n overlaps[box_ind, :] = -1\n overlaps[:, gt_ind] = -1\n # append recorded iou coverage level\n gt_overlaps = np.hstack((gt_overlaps, _gt_overlaps))\n\n gt_overlaps = np.sort(gt_overlaps)\n if thresholds is None:\n step = 0.05\n thresholds = np.arange(0.5, 0.95 + 1e-5, step)\n recalls = np.zeros_like(thresholds)\n # compute recall for each iou threshold\n for i, t in enumerate(thresholds):\n recalls[i] = (gt_overlaps >= t).sum() / float(num_pos)\n # ar = 2 * np.trapz(recalls, thresholds)\n ar = recalls.mean()\n return {'ar': ar, 'recalls': recalls, 'thresholds': thresholds,\n 'gt_overlaps': gt_overlaps}\n\n def create_roidb_from_box_list(self, box_list, gt_roidb):\n assert len(box_list) == self.num_images, \\\n 'Number of boxes must match number of ground-truth images'\n roidb = []\n for i in range(self.num_images):\n boxes = box_list[i]\n num_boxes = boxes.shape[0]\n overlaps = np.zeros((num_boxes, self.num_classes), dtype=np.float32)\n\n if gt_roidb is not None and gt_roidb[i]['boxes'].size > 0:\n gt_boxes = gt_roidb[i]['boxes']\n gt_classes = gt_roidb[i]['gt_classes']\n gt_overlaps = bbox_overlaps(boxes.astype(np.float),\n gt_boxes.astype(np.float))\n argmaxes = gt_overlaps.argmax(axis=1)\n maxes = gt_overlaps.max(axis=1)\n I = np.where(maxes > 0)[0]\n overlaps[I, gt_classes[argmaxes[I]]] = maxes[I]\n\n overlaps = scipy.sparse.csr_matrix(overlaps)\n roidb.append({\n 'boxes': boxes,\n 'gt_classes': np.zeros((num_boxes,), dtype=np.int32),\n 'gt_overlaps': overlaps,\n 'flipped': False,\n 'seg_areas': np.zeros((num_boxes,), dtype=np.float32),\n })\n return roidb\n\n @staticmethod\n def merge_roidbs(a, b):\n assert len(a) == len(b)\n for i in range(len(a)):\n a[i]['boxes'] = np.vstack((a[i]['boxes'], b[i]['boxes']))\n a[i]['gt_classes'] = np.hstack((a[i]['gt_classes'],\n b[i]['gt_classes']))\n a[i]['gt_overlaps'] = scipy.sparse.vstack([a[i]['gt_overlaps'],\n b[i]['gt_overlaps']])\n a[i]['seg_areas'] = np.hstack((a[i]['seg_areas'],\n b[i]['seg_areas']))\n return a\n\n def competition_mode(self, on):\n \"\"\"Turn competition mode on or off.\"\"\"\n pass\n" ]
[ [ "numpy.vstack", "numpy.zeros_like", "numpy.zeros", "numpy.arange", "numpy.hstack", "numpy.sort", "numpy.where" ] ]
vberthiaume/vblandr
[ "dbd139e7b6172b9dbc97707ff4874bc398de7aaa" ]
[ "mnist/mainMnist.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Trains and Evaluates the MNIST network using a feed dictionary.\"\"\"\n# pylint: disable=missing-docstring\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport math\nfrom six.moves import urllib\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets\n\nimport gzip\nimport os\nimport tempfile\n\nimport numpy\n\n# Basic model parameters as external flags.\nflags = tf.app.flags\nFLAGS = flags.FLAGS\nflags.DEFINE_float ('learning_rate', 0.01, 'Initial learning rate.')\nflags.DEFINE_integer('max_steps', 2000, 'Number of steps to run trainer.')\nflags.DEFINE_integer('hidden1', 128, 'Number of units in hidden layer 1.')\nflags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')\nflags.DEFINE_integer('batch_size', 100, 'Batch size. Must divide evenly into the dataset sizes.')\nflags.DEFINE_string ('train_dir', 'data', 'Directory to put the training data.')\nflags.DEFINE_boolean('fake_data', False, 'If true, uses fake data for unit testing.')\n\n# The MNIST dataset has 10 classes, representing the digits 0 through 9.\nNUM_CLASSES = 10\n\n# The MNIST images are always 28x28 pixels.\nIMAGE_SIZE = 28\nIMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE\n\n\ndef run_training():\n \"\"\"Train MNIST for a number of steps.\"\"\"\n # Get the sets of images and labels for training, validation, and\n # test on MNIST.\n data_sets = read_data_sets(FLAGS.train_dir, FLAGS.fake_data)\n\n # Tell TensorFlow that the model will be built into the default Graph.\n with tf.Graph().as_default():\n # Generate placeholders for the images and labels.\n images_placeholder, labels_placeholder = placeholder_inputs(FLAGS.batch_size)\n # Build a Graph that computes predictions from the inference model.\n logits = inference(images_placeholder, FLAGS.hidden1, FLAGS.hidden2)\n # Add to the Graph the Ops for loss calculation.\n loss = loss_funct(logits, labels_placeholder)\n # Add to the Graph the Ops that calculate and apply gradients.\n train_op = training(loss, FLAGS.learning_rate)\n # Add the Op to compare the logits to the labels during evaluation.\n eval_correct = evaluation(logits, labels_placeholder)\n # Build the summary operation based on the TF collection of Summaries.\n summary_op = tf.merge_all_summaries()\n # Add the variable initializer Op.\n init = tf.initialize_all_variables()\n # Create a saver for writing training checkpoints.\n saver = tf.train.Saver()\n # Create a session for running Ops on the Graph.\n sess = tf.Session()\n # Instantiate a SummaryWriter to output summaries and the Graph.\n summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph)\n # Run the Op to initialize the variables.\n sess.run(init)\n # training loop.\n for step in xrange(FLAGS.max_steps):\n start_time = time.time()\n # Fill a feed dictionary with the actual set of images and labels\n # for this particular training step.\n feed_dict = fill_feed_dict(data_sets.train, images_placeholder, labels_placeholder)\n # Run one step of the model. The return values are the activations\n # from the `train_op` (which is discarded) and the `loss` Op. To\n # inspect the values of your Ops or variables, you may include them\n # in the list passed to sess.run() and the value tensors will be\n # returned in the tuple from the call.\n _, loss_value = sess.run([train_op, loss], feed_dict=feed_dict)\n duration = time.time() - start_time\n # Write the summaries and print an overview fairly often.\n if step % 100 == 0:\n # Print status to stdout.\n print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration))\n # Update the events file.\n summary_str = sess.run(summary_op, feed_dict=feed_dict)\n summary_writer.add_summary(summary_str, step)\n summary_writer.flush()\n\n # Save a checkpoint and evaluate the model periodically.\n if (step + 1) % 1000 == 0 or (step + 1) == FLAGS.max_steps:\n saver.save(sess, FLAGS.train_dir, global_step=step)\n # Evaluate against the training set.\n print('Training Data Eval:')\n do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.train)\n # Evaluate against the validation set.\n print('Validation Data Eval:')\n do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.validation)\n # Evaluate against the test set.\n print('Test Data Eval:')\n do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_sets.test)\n\ndef placeholder_inputs(batch_size):\n \"\"\"Generate placeholder variables to represent the input tensors.\n\n These placeholders are used as inputs by the rest of the model building\n code and will be fed from the downloaded data in the .run() loop, below.\n\n Args:\n batch_size: The batch size will be baked into both placeholders.\n\n Returns:\n images_placeholder: Images placeholder.\n labels_placeholder: Labels placeholder.\n \"\"\"\n # Note that the shapes of the placeholders match the shapes of the full\n # image and label tensors, except the first dimension is now batch_size\n # rather than the full size of the train or test data sets.\n images_placeholder = tf.placeholder(tf.float32, shape=(batch_size, IMAGE_PIXELS))\n labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size))\n return images_placeholder, labels_placeholder\n\ndef inference(images, hidden1_units, hidden2_units):\n #Build the MNIST model up to where it may be used for inference.\n\n # Hidden 1\n with tf.name_scope('hidden1'):\n weights = tf.Variable(tf.truncated_normal([IMAGE_PIXELS, hidden1_units], stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))), name='weights')\n biases = tf.Variable(tf.zeros([hidden1_units]), name='biases')\n hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)\n # Hidden 2\n with tf.name_scope('hidden2'):\n weights = tf.Variable(tf.truncated_normal([hidden1_units, hidden2_units], stddev=1.0 / math.sqrt(float(hidden1_units))), name='weights')\n biases = tf.Variable(tf.zeros([hidden2_units]), name='biases')\n hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)\n # Linear\n with tf.name_scope('softmax_linear'):\n weights = tf.Variable(tf.truncated_normal([hidden2_units, NUM_CLASSES], stddev=1.0 / math.sqrt(float(hidden2_units))), name='weights')\n biases = tf.Variable(tf.zeros([NUM_CLASSES]), name='biases')\n logits = tf.matmul(hidden2, weights) + biases\n return logits\n\ndef loss_funct(logits, labels):\n labels = tf.to_int64(labels)\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( logits, labels, name='xentropy')\n loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')\n return loss\n\ndef fill_feed_dict(data_set, images_pl, labels_pl):\n \"\"\"Fills the feed_dict for training the given step.\n\n A feed_dict takes the form of:\n feed_dict = {\n <placeholder>: <tensor of values to be passed for placeholder>,\n ....\n }\n\n Args:\n data_set: The set of images and labels, from input_data.read_data_sets()\n images_pl: The images placeholder, from placeholder_inputs().\n labels_pl: The labels placeholder, from placeholder_inputs().\n\n Returns:\n feed_dict: The feed dictionary mapping from placeholders to values.\n \"\"\"\n # Create the feed_dict for the placeholders filled with the next `batch size ` examples.\n images_feed, labels_feed = data_set.next_batch(FLAGS.batch_size, FLAGS.fake_data)\n feed_dict = { images_pl: images_feed, labels_pl: labels_feed}\n return feed_dict\n\ndef do_eval(sess, eval_correct, images_placeholder, labels_placeholder, data_set):\n \"\"\"Runs one evaluation against the full epoch of data.\n\n Args:\n sess: The session in which the model has been trained.\n eval_correct: The Tensor that returns the number of correct predictions.\n images_placeholder: The images placeholder.\n labels_placeholder: The labels placeholder.\n data_set: The set of images and labels to evaluate, from\n input_data.read_data_sets().\n \"\"\"\n # And run one epoch of eval.\n true_count = 0 # Counts the number of correct predictions.\n steps_per_epoch = data_set.num_examples // FLAGS.batch_size\n num_examples = steps_per_epoch * FLAGS.batch_size\n for step in xrange(steps_per_epoch):\n feed_dict = fill_feed_dict(data_set, images_placeholder, labels_placeholder)\n true_count += sess.run(eval_correct, feed_dict=feed_dict)\n precision = true_count / num_examples\n print(' Num examples: %d Num correct: %d Precision @ 1: %0.04f' % (num_examples, true_count, precision))\n\ndef training(loss, learning_rate):\n \"\"\"Sets up the training Ops. Creates a summarizer to track the loss over time in TensorBoard. Creates an optimizer and applies the gradients \n to all trainable variables. The Op returned by this function is what must be passed to the`sess.run()` call to cause the model to train.\n Args:\n loss: Loss tensor, from loss().\n learning_rate: The learning rate to use for gradient descent.\n Returns:\n train_op: The Op for training.\n \"\"\"\n # Add a scalar summary for the snapshot loss.\n tf.scalar_summary(loss.op.name, loss)\n # Create the gradient descent optimizer with the given learning rate.\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n # Create a variable to track the global step.\n global_step = tf.Variable(0, name='global_step', trainable=False)\n # Use the optimizer to apply the gradients that minimize the loss\n # (and also increment the global step counter) as a single training step.\n train_op = optimizer.minimize(loss, global_step=global_step)\n return train_op\n\ndef evaluation(logits, labels):\n \"\"\"Evaluate the quality of the logits at predicting the label.\n Args:\n logits: Logits tensor, float - [batch_size, NUM_CLASSES].\n labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES).\n Returns:\n A scalar int32 tensor with the number of examples (out of batch_size)\n that were predicted correctly.\n \"\"\"\n # For a classifier model, we can use the in_top_k Op. It returns a bool tensor with shape [batch_size] that is true for\n # the examples where the label is in the top k (here k=1) of all logits for that example.\n correct = tf.nn.in_top_k(logits, labels, 1)\n # Return the number of true entries.\n return tf.reduce_sum(tf.cast(correct, tf.int32))\n\ndef main(_):\n run_training()\n\nif __name__ == '__main__':\n tf.app.run()\n" ]
[ [ "tensorflow.contrib.learn.python.learn.datasets.mnist.read_data_sets", "tensorflow.initialize_all_variables", "tensorflow.matmul", "tensorflow.name_scope", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.Variable", "tensorflow.nn.in_top_k", "tensorflow.train.SummaryWriter", "tensorflow.Graph", "tensorflow.scalar_summary", "tensorflow.app.run", "tensorflow.cast", "tensorflow.train.Saver", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.zeros", "tensorflow.to_int64", "tensorflow.reduce_mean", "tensorflow.train.GradientDescentOptimizer", "tensorflow.merge_all_summaries" ] ]
mawanda-jun/NoLabels
[ "6861867ad5ab49fc7ae6f562977f60195f9ff216" ]
[ "Dataset/generate_hamming_set.py" ]
[ "\"\"\"\nThis file generates a set of most distant permutations from each other. This is only a support dataset: this will be useful\nwhen we will crop each image and reorder them in those distances.\nThis is a kind of mathematical distribution, no data are loaded here.\n\"\"\"\n\nimport numpy as np\nimport itertools\nimport os\nfrom scipy.spatial.distance import cdist\nimport h5py\nfrom config import conf\n\nNUM_CROPS = conf.numCrops\nNUM_PERMUTATIONS = conf.hammingSetSize\nSELECTION = conf.selectionMethod\nFILENAME = conf.hammingFileName\nFOLDER = conf.resources\n\n\ndef hamming_set(num_crops=NUM_CROPS, num_permutations=NUM_PERMUTATIONS, selection=SELECTION, filename=FILENAME):\n \"\"\"\n generate and save the hamming set\n :param num_crops: number of tiles from each image\n :param num_permutations: Number of permutations to select (i.e. number of classes for the pretext task)\n :param selection: Sample selected per iteration based on hamming distance: [max] highest; [mean] average\n :param filename: name of file\n :return a list of different permutations: [[perm1], [perm2], ...]. Each permutation is in form (10_elements)\n \"\"\"\n # create different permutation for num_crops (i.e: num_crops=9, P_hat[0]=(0, 1, 2, 4, 5, 3, 7, 8, 6, 9)\n P_hat = np.array(list(itertools.permutations(list(range(num_crops)), num_crops)))\n n = P_hat.shape[0] # number of total permutations (i.e num_crops=9 -> shape[0]=3628800\n\n j = np.random.randint(n)\n P = np.array(P_hat[j]).reshape((1, -1)) # reshape j array into [[1, 2, ...]]\n\n for _ in range(num_permutations)[1:]:\n # select the <num_permutations> max distant from each other of permutations\n P = np.concatenate([P, P_hat[j].reshape([1, -1])], axis=0) # concatenate as [[el1], [el2], [...]]\n P_hat = np.delete(P_hat, j, axis=0)\n # Takes the distance between the combination that are already present in P and those who are in P_hat.\n # Note that in P_hat there are no combinations of P.\n D = cdist(P, P_hat, metric='hamming').mean(axis=0).flatten()\n\n if selection == 'max':\n # select max distances between\n j = D.argmax()\n elif selection == 'mean':\n m = int(D.shape[0] / 2)\n S = D.argsort()\n j = S[np.random.randint(m - 10, m + 10)]\n\n os.makedirs(FOLDER, exist_ok=True)\n\n with h5py.File(os.path.join(os.getcwd(), FOLDER, filename + str(NUM_PERMUTATIONS) + '.h5'), 'w') as h5f:\n h5f.create_dataset('max_hamming_set', data=P)\n\n print('file created --> ' + FOLDER + filename + str(NUM_PERMUTATIONS) + '.h5')\n\n\nif __name__ == \"__main__\":\n hamming_set()\n\n" ]
[ [ "numpy.array", "numpy.random.randint", "scipy.spatial.distance.cdist", "numpy.delete" ] ]
Gnupur/scikit-learn
[ "513695f1e4f7613f988159333bfccc59358879dd" ]
[ "sklearn/ensemble/_voting.py" ]
[ "\"\"\"\nSoft Voting/Majority Rule classifier and Voting regressor.\n\nThis module contains:\n - A Soft Voting/Majority Rule classifier for classification estimators.\n - A Voting regressor for regression estimators.\n\"\"\"\n\n# Authors: Sebastian Raschka <[email protected]>,\n# Gilles Louppe <[email protected]>,\n# Ramil Nugmanov <[email protected]>\n# Mohamed Ali Jamaoui <[email protected]>\n#\n# License: BSD 3 clause\n\nfrom abc import abstractmethod\n\nimport numpy as np\n\nfrom joblib import Parallel\n\nfrom ..base import ClassifierMixin\nfrom ..base import RegressorMixin\nfrom ..base import TransformerMixin\nfrom ..base import clone\nfrom ._base import _fit_single_estimator\nfrom ._base import _BaseHeterogeneousEnsemble\nfrom ..preprocessing import LabelEncoder\nfrom ..utils import Bunch\nfrom ..utils.validation import check_is_fitted\nfrom ..utils.multiclass import check_classification_targets\nfrom ..utils.validation import column_or_1d\nfrom ..exceptions import NotFittedError\nfrom ..utils._estimator_html_repr import _VisualBlock\nfrom ..utils.fixes import delayed\n\n\nclass _BaseVoting(TransformerMixin, _BaseHeterogeneousEnsemble):\n \"\"\"Base class for voting.\n\n Warning: This class should not be used directly. Use derived classes\n instead.\n \"\"\"\n\n def _log_message(self, name, idx, total):\n if not self.verbose:\n return None\n return \"(%d of %d) Processing %s\" % (idx, total, name)\n\n @property\n def _weights_not_none(self):\n \"\"\"Get the weights of not `None` estimators.\"\"\"\n if self.weights is None:\n return None\n return [w for est, w in zip(self.estimators, self.weights) if est[1] != \"drop\"]\n\n def _predict(self, X):\n \"\"\"Collect results from clf.predict calls.\"\"\"\n return np.asarray([est.predict(X) for est in self.estimators_]).T\n\n @abstractmethod\n def fit(self, X, y, sample_weight=None):\n \"\"\"Get common fit operations.\"\"\"\n names, clfs = self._validate_estimators()\n\n if self.weights is not None and len(self.weights) != len(self.estimators):\n raise ValueError(\n \"Number of `estimators` and weights must be equal\"\n \"; got %d weights, %d estimators\"\n % (len(self.weights), len(self.estimators))\n )\n\n self.estimators_ = Parallel(n_jobs=self.n_jobs)(\n delayed(_fit_single_estimator)(\n clone(clf),\n X,\n y,\n sample_weight=sample_weight,\n message_clsname=\"Voting\",\n message=self._log_message(names[idx], idx + 1, len(clfs)),\n )\n for idx, clf in enumerate(clfs)\n if clf != \"drop\"\n )\n\n self.named_estimators_ = Bunch()\n\n # Uses 'drop' as placeholder for dropped estimators\n est_iter = iter(self.estimators_)\n for name, est in self.estimators:\n current_est = est if est == \"drop\" else next(est_iter)\n self.named_estimators_[name] = current_est\n\n return self\n\n def fit_transform(self, X, y=None, **fit_params):\n \"\"\"Return class labels or probabilities for each estimator.\n\n Return predictions for X for each estimator.\n\n Parameters\n ----------\n X : {array-like, sparse matrix, dataframe} of shape \\\n (n_samples, n_features)\n Input samples.\n\n y : ndarray of shape (n_samples,), default=None\n Target values (None for unsupervised transformations).\n\n **fit_params : dict\n Additional fit parameters.\n\n Returns\n -------\n X_new : ndarray array of shape (n_samples, n_features_new)\n Transformed array.\n \"\"\"\n return super().fit_transform(X, y, **fit_params)\n\n @property\n def n_features_in_(self):\n \"\"\"Number of features seen during :term:`fit`.\"\"\"\n # For consistency with other estimators we raise a AttributeError so\n # that hasattr() fails if the estimator isn't fitted.\n try:\n check_is_fitted(self)\n except NotFittedError as nfe:\n raise AttributeError(\n \"{} object has no n_features_in_ attribute.\".format(\n self.__class__.__name__\n )\n ) from nfe\n\n return self.estimators_[0].n_features_in_\n\n def _sk_visual_block_(self):\n names, estimators = zip(*self.estimators)\n return _VisualBlock(\"parallel\", estimators, names=names)\n\n def _more_tags(self):\n return {\"preserves_dtype\": []}\n\n\nclass VotingClassifier(ClassifierMixin, _BaseVoting):\n \"\"\"Soft Voting/Majority Rule classifier for unfitted estimators.\n\n Read more in the :ref:`User Guide <voting_classifier>`.\n\n .. versionadded:: 0.17\n\n Parameters\n ----------\n estimators : list of (str, estimator) tuples\n Invoking the ``fit`` method on the ``VotingClassifier`` will fit clones\n of those original estimators that will be stored in the class attribute\n ``self.estimators_``. An estimator can be set to ``'drop'``\n using ``set_params``.\n\n .. versionchanged:: 0.21\n ``'drop'`` is accepted. Using None was deprecated in 0.22 and\n support was removed in 0.24.\n\n voting : {'hard', 'soft'}, default='hard'\n If 'hard', uses predicted class labels for majority rule voting.\n Else if 'soft', predicts the class label based on the argmax of\n the sums of the predicted probabilities, which is recommended for\n an ensemble of well-calibrated classifiers.\n\n weights : array-like of shape (n_classifiers,), default=None\n Sequence of weights (`float` or `int`) to weight the occurrences of\n predicted class labels (`hard` voting) or class probabilities\n before averaging (`soft` voting). Uses uniform weights if `None`.\n\n n_jobs : int, default=None\n The number of jobs to run in parallel for ``fit``.\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 .. versionadded:: 0.18\n\n flatten_transform : bool, default=True\n Affects shape of transform output only when voting='soft'\n If voting='soft' and flatten_transform=True, transform method returns\n matrix with shape (n_samples, n_classifiers * n_classes). If\n flatten_transform=False, it returns\n (n_classifiers, n_samples, n_classes).\n\n verbose : bool, default=False\n If True, the time elapsed while fitting will be printed as it\n is completed.\n\n .. versionadded:: 0.23\n\n Attributes\n ----------\n estimators_ : list of classifiers\n The collection of fitted sub-estimators as defined in ``estimators``\n that are not 'drop'.\n\n named_estimators_ : :class:`~sklearn.utils.Bunch`\n Attribute to access any fitted sub-estimators by name.\n\n .. versionadded:: 0.20\n\n le_ : :class:`~sklearn.preprocessing.LabelEncoder`\n Transformer used to encode the labels during fit and decode during\n prediction.\n\n classes_ : ndarray of shape (n_classes,)\n The classes labels.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`. Only defined if the\n underlying classifier exposes such an attribute when fit.\n\n .. versionadded:: 0.24\n\n See Also\n --------\n VotingRegressor : Prediction voting regressor.\n\n Examples\n --------\n >>> import numpy as np\n >>> from sklearn.linear_model import LogisticRegression\n >>> from sklearn.naive_bayes import GaussianNB\n >>> from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n >>> clf1 = LogisticRegression(multi_class='multinomial', random_state=1)\n >>> clf2 = RandomForestClassifier(n_estimators=50, random_state=1)\n >>> clf3 = GaussianNB()\n >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])\n >>> y = np.array([1, 1, 1, 2, 2, 2])\n >>> eclf1 = VotingClassifier(estimators=[\n ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)], voting='hard')\n >>> eclf1 = eclf1.fit(X, y)\n >>> print(eclf1.predict(X))\n [1 1 1 2 2 2]\n >>> np.array_equal(eclf1.named_estimators_.lr.predict(X),\n ... eclf1.named_estimators_['lr'].predict(X))\n True\n >>> eclf2 = VotingClassifier(estimators=[\n ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)],\n ... voting='soft')\n >>> eclf2 = eclf2.fit(X, y)\n >>> print(eclf2.predict(X))\n [1 1 1 2 2 2]\n >>> eclf3 = VotingClassifier(estimators=[\n ... ('lr', clf1), ('rf', clf2), ('gnb', clf3)],\n ... voting='soft', weights=[2,1,1],\n ... flatten_transform=True)\n >>> eclf3 = eclf3.fit(X, y)\n >>> print(eclf3.predict(X))\n [1 1 1 2 2 2]\n >>> print(eclf3.transform(X).shape)\n (6, 6)\n \"\"\"\n\n def __init__(\n self,\n estimators,\n *,\n voting=\"hard\",\n weights=None,\n n_jobs=None,\n flatten_transform=True,\n verbose=False,\n ):\n super().__init__(estimators=estimators)\n self.voting = voting\n self.weights = weights\n self.n_jobs = n_jobs\n self.flatten_transform = flatten_transform\n self.verbose = verbose\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit the estimators.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training vectors, 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 values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights. If None, then samples are equally weighted.\n Note that this is supported only if all underlying estimators\n support sample weights.\n\n .. versionadded:: 0.18\n\n Returns\n -------\n self : object\n Returns the instance itself.\n\n \"\"\"\n check_classification_targets(y)\n if isinstance(y, np.ndarray) and len(y.shape) > 1 and y.shape[1] > 1:\n raise NotImplementedError(\n \"Multilabel and multi-output classification is not supported.\"\n )\n\n if self.voting not in (\"soft\", \"hard\"):\n raise ValueError(\n \"Voting must be 'soft' or 'hard'; got (voting=%r)\" % self.voting\n )\n\n self.le_ = LabelEncoder().fit(y)\n self.classes_ = self.le_.classes_\n transformed_y = self.le_.transform(y)\n\n return super().fit(X, transformed_y, sample_weight)\n\n def predict(self, X):\n \"\"\"Predict class labels for X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n\n Returns\n -------\n maj : array-like of shape (n_samples,)\n Predicted class labels.\n \"\"\"\n check_is_fitted(self)\n if self.voting == \"soft\":\n maj = np.argmax(self.predict_proba(X), axis=1)\n\n else: # 'hard' voting\n predictions = self._predict(X)\n maj = np.apply_along_axis(\n lambda x: np.argmax(np.bincount(x, weights=self._weights_not_none)),\n axis=1,\n arr=predictions,\n )\n\n maj = self.le_.inverse_transform(maj)\n\n return maj\n\n def _collect_probas(self, X):\n \"\"\"Collect results from clf.predict calls.\"\"\"\n return np.asarray([clf.predict_proba(X) for clf in self.estimators_])\n\n def _predict_proba(self, X):\n \"\"\"Predict class probabilities for X in 'soft' voting.\"\"\"\n check_is_fitted(self)\n avg = np.average(\n self._collect_probas(X), axis=0, weights=self._weights_not_none\n )\n return avg\n\n @property\n def predict_proba(self):\n \"\"\"Compute probabilities of possible outcomes for samples in X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n\n Returns\n -------\n avg : array-like of shape (n_samples, n_classes)\n Weighted average probability for each class per sample.\n \"\"\"\n if self.voting == \"hard\":\n raise AttributeError(\n \"predict_proba is not available when voting=%r\" % self.voting\n )\n return self._predict_proba\n\n def transform(self, X):\n \"\"\"Return class labels or probabilities for X for each estimator.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training vectors, where n_samples is the number of samples and\n n_features is the number of features.\n\n Returns\n -------\n probabilities_or_labels\n If `voting='soft'` and `flatten_transform=True`:\n returns ndarray of shape (n_classifiers, n_samples *\n n_classes), being class probabilities calculated by each\n classifier.\n If `voting='soft' and `flatten_transform=False`:\n ndarray of shape (n_classifiers, n_samples, n_classes)\n If `voting='hard'`:\n ndarray of shape (n_samples, n_classifiers), being\n class labels predicted by each classifier.\n \"\"\"\n check_is_fitted(self)\n\n if self.voting == \"soft\":\n probas = self._collect_probas(X)\n if not self.flatten_transform:\n return probas\n return np.hstack(probas)\n\n else:\n return self._predict(X)\n\n\nclass VotingRegressor(RegressorMixin, _BaseVoting):\n \"\"\"Prediction voting regressor for unfitted estimators.\n\n A voting regressor is an ensemble meta-estimator that fits several base\n regressors, each on the whole dataset. Then it averages the individual\n predictions to form a final prediction.\n\n Read more in the :ref:`User Guide <voting_regressor>`.\n\n .. versionadded:: 0.21\n\n Parameters\n ----------\n estimators : list of (str, estimator) tuples\n Invoking the ``fit`` method on the ``VotingRegressor`` will fit clones\n of those original estimators that will be stored in the class attribute\n ``self.estimators_``. An estimator can be set to ``'drop'`` using\n ``set_params``.\n\n .. versionchanged:: 0.21\n ``'drop'`` is accepted. Using None was deprecated in 0.22 and\n support was removed in 0.24.\n\n weights : array-like of shape (n_regressors,), default=None\n Sequence of weights (`float` or `int`) to weight the occurrences of\n predicted values before averaging. Uses uniform weights if `None`.\n\n n_jobs : int, default=None\n The number of jobs to run in parallel for ``fit``.\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 : bool, default=False\n If True, the time elapsed while fitting will be printed as it\n is completed.\n\n .. versionadded:: 0.23\n\n Attributes\n ----------\n estimators_ : list of regressors\n The collection of fitted sub-estimators as defined in ``estimators``\n that are not 'drop'.\n\n named_estimators_ : :class:`~sklearn.utils.Bunch`\n Attribute to access any fitted sub-estimators by name.\n\n .. versionadded:: 0.20\n\n n_features_in_ : int\n Number of features seen during :term:`fit`. Only defined if the\n underlying regressor exposes such an attribute when fit.\n\n .. versionadded:: 0.24\n\n See Also\n --------\n VotingClassifier : Soft Voting/Majority Rule classifier.\n\n Examples\n --------\n >>> import numpy as np\n >>> from sklearn.linear_model import LinearRegression\n >>> from sklearn.ensemble import RandomForestRegressor\n >>> from sklearn.ensemble import VotingRegressor\n >>> r1 = LinearRegression()\n >>> r2 = RandomForestRegressor(n_estimators=10, random_state=1)\n >>> X = np.array([[1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36]])\n >>> y = np.array([2, 6, 12, 20, 30, 42])\n >>> er = VotingRegressor([('lr', r1), ('rf', r2)])\n >>> print(er.fit(X, y).predict(X))\n [ 3.3 5.7 11.8 19.7 28. 40.3]\n \"\"\"\n\n def __init__(self, estimators, *, weights=None, n_jobs=None, verbose=False):\n super().__init__(estimators=estimators)\n self.weights = weights\n self.n_jobs = n_jobs\n self.verbose = verbose\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit the estimators.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training vectors, 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 values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights. If None, then samples are equally weighted.\n Note that this is supported only if all underlying estimators\n support sample weights.\n\n Returns\n -------\n self : object\n Fitted estimator.\n \"\"\"\n y = column_or_1d(y, warn=True)\n return super().fit(X, y, sample_weight)\n\n def predict(self, X):\n \"\"\"Predict regression target for X.\n\n The predicted regression target of an input sample is computed as the\n mean predicted regression targets of the estimators in the ensemble.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n\n Returns\n -------\n y : ndarray of shape (n_samples,)\n The predicted values.\n \"\"\"\n check_is_fitted(self)\n return np.average(self._predict(X), axis=1, weights=self._weights_not_none)\n\n def transform(self, X):\n \"\"\"Return predictions for X for each estimator.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n The input samples.\n\n Returns\n -------\n predictions : ndarray of shape (n_samples, n_classifiers)\n Values predicted by each regressor.\n \"\"\"\n check_is_fitted(self)\n return self._predict(X)\n" ]
[ [ "numpy.hstack", "numpy.bincount" ] ]
andreasala98/pykeen
[ "205af6c2604b3882bf0adf275610bceb6ac53c0c" ]
[ "src/pykeen/triples/triples_numeric_literals_factory.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"Implementation of factory that create instances containing of triples and numeric literals.tsv.\"\"\"\n\nimport logging\nimport pathlib\nfrom typing import Any, Dict, Optional, TextIO, Tuple, Union\n\nimport numpy as np\nimport torch\n\nfrom .triples_factory import TriplesFactory\nfrom .utils import load_triples\nfrom ..typing import EntityMapping, LabeledTriples, MappedTriples\n\n__all__ = [\n \"TriplesNumericLiteralsFactory\",\n]\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_matrix_of_literals(\n numeric_triples: np.array,\n entity_to_id: EntityMapping,\n) -> Tuple[np.ndarray, Dict[str, int]]:\n \"\"\"Create matrix of literals where each row corresponds to an entity and each column to a literal.\"\"\"\n data_relations = np.unique(np.ndarray.flatten(numeric_triples[:, 1:2]))\n data_rel_to_id: Dict[str, int] = {value: key for key, value in enumerate(data_relations)}\n # Prepare literal matrix, set every literal to zero, and afterwards fill in the corresponding value if available\n num_literals = np.zeros([len(entity_to_id), len(data_rel_to_id)], dtype=np.float32)\n\n # TODO vectorize code\n for h, r, lit in numeric_triples:\n try:\n # row define entity, and column the literal. Set the corresponding literal for the entity\n num_literals[entity_to_id[h], data_rel_to_id[r]] = lit\n except KeyError:\n logger.info(\"Either entity or relation to literal doesn't exist.\")\n continue\n\n return num_literals, data_rel_to_id\n\n\nclass TriplesNumericLiteralsFactory(TriplesFactory):\n \"\"\"Create multi-modal instances given the path to triples.\"\"\"\n\n def __init__(\n self,\n *,\n path: Union[None, str, pathlib.Path, TextIO] = None,\n triples: Optional[LabeledTriples] = None,\n path_to_numeric_triples: Union[None, str, pathlib.Path, TextIO] = None,\n numeric_triples: Optional[np.ndarray] = None,\n **kwargs,\n ) -> None:\n \"\"\"Initialize the multi-modal triples factory.\n\n :param path: The path to a 3-column TSV file with triples in it. If not specified,\n you should specify ``triples``.\n :param triples: A 3-column numpy array with triples in it. If not specified,\n you should specify ``path``\n :param path_to_numeric_triples: The path to a 3-column TSV file with triples and\n numeric. If not specified, you should specify ``numeric_triples``.\n :param numeric_triples: A 3-column numpy array with numeric triples in it. If not\n specified, you should specify ``path_to_numeric_triples``.\n \"\"\"\n if path is not None:\n base = TriplesFactory.from_path(path=path, **kwargs)\n elif triples is None:\n base = TriplesFactory(**kwargs)\n else:\n base = TriplesFactory.from_labeled_triples(triples=triples, **kwargs)\n super().__init__(\n entity_to_id=base.entity_to_id,\n relation_to_id=base.relation_to_id,\n mapped_triples=base.mapped_triples,\n create_inverse_triples=base.create_inverse_triples,\n )\n\n if path_to_numeric_triples is None and numeric_triples is None:\n raise ValueError(\"Must specify one of path_to_numeric_triples or numeric_triples\")\n elif path_to_numeric_triples is not None and numeric_triples is not None:\n raise ValueError(\"Must not specify both path_to_numeric_triples and numeric_triples\")\n elif path_to_numeric_triples is not None:\n self.numeric_triples = load_triples(path_to_numeric_triples)\n else:\n self.numeric_triples = numeric_triples\n\n assert self.entity_to_id is not None\n self.numeric_literals, self.literals_to_id = create_matrix_of_literals(\n numeric_triples=self.numeric_triples,\n entity_to_id=self.entity_to_id,\n )\n\n def get_numeric_literals_tensor(self) -> torch.FloatTensor:\n \"\"\"Return the numeric literals as a tensor.\"\"\"\n return torch.as_tensor(self.numeric_literals, dtype=torch.float32)\n\n def extra_repr(self) -> str: # noqa: D102\n return super().extra_repr() + (f\"num_literals={len(self.literals_to_id)}\")\n\n def clone_and_exchange_triples(\n self,\n mapped_triples: MappedTriples,\n extra_metadata: Optional[Dict[str, Any]] = None,\n keep_metadata: bool = True,\n create_inverse_triples: Optional[bool] = None,\n ) -> \"TriplesNumericLiteralsFactory\": # noqa: D102\n if create_inverse_triples is None:\n create_inverse_triples = self.create_inverse_triples\n return TriplesNumericLiteralsFactory(\n numeric_triples=self.numeric_triples,\n mapped_triples=mapped_triples,\n entity_to_id=self.entity_to_id,\n relation_to_id=self.relation_to_id,\n create_inverse_triples=create_inverse_triples,\n metadata={\n **(extra_metadata or {}),\n **(self.metadata if keep_metadata else {}), # type: ignore\n },\n )\n" ]
[ [ "torch.as_tensor", "numpy.ndarray.flatten" ] ]
Fanping/ai.example
[ "452a8c00e58a6c3a27ab78a2b4a30bdd054ef165" ]
[ "10.Face-Generated-With-GAN/face_generated_gan_model.py" ]
[ "import tensorflow as tf\n\n\nclass FaceGANModel(object):\n def __init__(self, batch_size=64, learning_rate=1e-3):\n # 1. Define input.\n self.input_image = tf.placeholder(tf.float32, [batch_size, 40 * 55],\n name=\"input_image\")\n self.input_prior = tf.placeholder(tf.float32, [batch_size, 100],\n name=\"input_prior\")\n self.keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n\n # 2. Define generator.\n generator_w1 = tf.Variable(tf.truncated_normal([100, 150], stddev=0.1),\n name=\"g_w1\", dtype=tf.float32)\n generator_b1 = tf.Variable(tf.zeros([150]), name=\"g_b1\",\n dtype=tf.float32)\n generator_layer1 = tf.nn.relu(\n tf.matmul(self.input_prior, generator_w1) + generator_b1)\n generator_w2 = tf.Variable(tf.truncated_normal([150, 300], stddev=0.1),\n name=\"g_w2\", dtype=tf.float32)\n generator_b2 = tf.Variable(tf.zeros([300]), name=\"g_b2\",\n dtype=tf.float32)\n generator_layer2 = tf.nn.relu(\n tf.matmul(generator_layer1, generator_w2) + generator_b2)\n generator_w3 = tf.Variable(\n tf.truncated_normal([300, 40 * 55], stddev=0.1),\n name=\"g_w3\", dtype=tf.float32)\n generator_b3 = tf.Variable(tf.zeros([40 * 55]), name=\"g_b3\",\n dtype=tf.float32)\n generator_layer3 = tf.matmul(generator_layer2,\n generator_w3) + generator_b3\n self.generator = tf.nn.tanh(generator_layer3)\n\n # 3. Define discriminator.\n x_in = tf.concat([self.input_image, self.generator], 0)\n discriminator_w1 = tf.Variable(\n tf.truncated_normal([40 * 55, 300], stddev=0.1),\n name=\"d_w1\", dtype=tf.float32)\n discriminator_b1 = tf.Variable(tf.zeros([300]), name=\"d_b1\",\n dtype=tf.float32)\n discriminator_layer1 = tf.nn.dropout(\n tf.nn.relu(tf.matmul(x_in, discriminator_w1) + discriminator_b1),\n self.keep_prob)\n discriminator_w2 = tf.Variable(\n tf.truncated_normal([300, 150], stddev=0.1),\n name=\"d_w2\", dtype=tf.float32)\n discriminator_b2 = tf.Variable(tf.zeros([150]), name=\"d_b2\",\n dtype=tf.float32)\n discriminator_layer2 = tf.nn.dropout(tf.nn.relu(\n tf.matmul(discriminator_layer1,\n discriminator_w2) + discriminator_b2), self.keep_prob)\n discriminator_w3 = tf.Variable(\n tf.truncated_normal([150, 1], stddev=0.1),\n name=\"d_w3\",\n dtype=tf.float32)\n discriminator_b3 = tf.Variable(tf.zeros([1]), name=\"d_b3\",\n dtype=tf.float32)\n discriminator_h3 = tf.matmul(discriminator_layer2,\n discriminator_w3) + discriminator_b3\n y_data = tf.nn.sigmoid(\n tf.slice(discriminator_h3, [0, 0], [batch_size, -1]))\n self.discriminator = tf.nn.sigmoid(\n tf.slice(discriminator_h3, [batch_size, 0], [-1, -1]))\n\n # 4.Define loss\n discriminator_loss = - (tf.log(y_data) + tf.log(1 - self.discriminator))\n generator_loss = - tf.log(self.discriminator)\n self.optimizer = tf.train.AdamOptimizer(learning_rate)\n self.discriminator_trainer = self.optimizer.minimize(discriminator_loss,\n var_list=[\n discriminator_w1,\n discriminator_b1,\n discriminator_w2,\n discriminator_b2,\n discriminator_w3,\n discriminator_b3])\n self.generator_trainer = self.optimizer.minimize(generator_loss,\n var_list=[generator_w1,\n generator_b1,\n generator_w2,\n generator_b2,\n generator_w3,\n generator_b3])\n" ]
[ [ "tensorflow.placeholder", "tensorflow.nn.tanh", "tensorflow.zeros", "tensorflow.truncated_normal", "tensorflow.train.AdamOptimizer", "tensorflow.matmul", "tensorflow.concat", "tensorflow.slice", "tensorflow.log" ] ]
Fngg/contact_tracing
[ "0df5d859fe7b89ac6539d409af8e6cec86f32137" ]
[ "src/service.py" ]
[ "'''\n流调查询\n'''\nfrom settings_class import settings_obj\nimport pandas as pd\nfrom util.logger import logger\nfrom sqlalchemy import desc\nfrom datetime import datetime,timedelta\n\n\ndef get_forward_backward_time(current_time, minutes):\n # 获取向前和向后的时间\n if isinstance(current_time,str):\n current = datetime.strptime(current_time, \"%Y-%m-%d %H:%M:%S\")\n else:\n current =current_time\n backward_time = current + timedelta(minutes=minutes)\n forward_time = current - timedelta(minutes=minutes)\n return forward_time, backward_time\n\n\ndef get_forward_contact(forward_time, current_time, location_condition_str, user_id, conn,table_obj,close_contact_record_num):\n '''\n 先向前查询,逻辑为 查询在向前时间到当前时间范围内,在该校区和该地点内的,并以时间倒序排序查询的限制close_contact_record_num\n :return:\n '''\n # 查(在限制的时间范围内)close_contact_record_num 条记录\n s = f\"conn.session.query({settings_obj.result_filed_names_str}).filter(table_obj.c[settings_obj.user_id_field_name]!=user_id, table_obj.c[settings_obj.time_field_name]>=forward_time, table_obj.c[settings_obj.time_field_name]<=current_time, {location_condition_str}).order_by(desc(table_obj.c[settings_obj.time_field_name])).limit(close_contact_record_num).all()\"\n records = eval(s)\n forward_results = [list(result) for result in records]\n return forward_results\n\n\ndef get_backward_contact(backward_time,current_time,location_condition_str,user_id,conn,table_obj,close_contact_record_num):\n '''\n 再向后查询,逻辑为 查询在当前时间到向后时间范围内,在该校区和该地点内的,并以时间正序排序查询的限制close_contact_record_num 条消费记录\n :param close_contact_record_num:\n :param backward_time:\n :param current_time:\n :param location_condition_str:\n :param user_id:\n :param conn:\n :return:\n '''\n # 先查(在限制的时间范围内))close_contact_record_num 条记录\n s =f\"conn.session.query({settings_obj.result_filed_names_str}).filter(table_obj.c[settings_obj.user_id_field_name]!=user_id, table_obj.c[settings_obj.time_field_name]>=current_time, table_obj.c[settings_obj.time_field_name]<=backward_time, {location_condition_str}).order_by(table_obj.c[settings_obj.time_field_name]).limit(close_contact_record_num).all()\"\n records = eval(s)\n backward_results = [list(result) for result in records]\n return backward_results\n\n\ndef get_backward_contacts(backward_time, current_time, location_condition_str, user_id, conn,table_obj, close_contact_record_num=settings_obj.close_contact_people_num, backward_result_df=None):\n if backward_result_df is None:\n backward_result_df = pd.DataFrame(columns=settings_obj.result_filed_names)\n backward_results = get_backward_contact(backward_time, current_time, location_condition_str, user_id, conn,table_obj, close_contact_record_num)\n if len(backward_results)>0:\n tem_df = pd.DataFrame(backward_results,columns=backward_result_df.columns)\n backward_result_df = pd.concat([backward_result_df, tem_df], ignore_index=True)\n backward_result_df.sort_values(by=settings_obj.time_field_name, inplace=True, ascending=True) # 升序\n if len(backward_results)>=close_contact_record_num:\n close_contact_record_num = settings_obj.close_contact_people_num - backward_result_df[settings_obj.user_id_field_name].nunique()\n if close_contact_record_num>0 and len(backward_result_df)>0:\n current_time = backward_result_df.loc[len(backward_result_df)-1,settings_obj.time_field_name]\n user_id = backward_result_df.loc[len(backward_result_df)-1,settings_obj.user_id_field_name]\n backward_result_df = get_backward_contacts(backward_time,current_time, location_condition_str, user_id, conn,table_obj,close_contact_record_num=close_contact_record_num,backward_result_df=backward_result_df)\n return backward_result_df\n\n\ndef get_forward_contacts(forward_time, current_time, location_condition_str, user_id, conn, table_obj, close_contact_record_num=settings_obj.close_contact_people_num, forward_result_df=None):\n '''\n 递归查询\n :param table_obj:\n :param forward_time:\n :param current_time:\n :param location_condition_str:\n :param user_id:\n :param conn:\n :param close_contact_record_num:\n :param forward_result_df:\n :return: 返回dataframe格式\n '''\n if forward_result_df is None:\n forward_result_df = pd.DataFrame(columns=settings_obj.result_filed_names)\n forward_results = get_forward_contact(forward_time, current_time, location_condition_str, user_id, conn,table_obj,close_contact_record_num)\n if len(forward_results)>0:\n tem_df = pd.DataFrame(forward_results, columns=forward_result_df.columns)\n forward_result_df = pd.concat([forward_result_df, tem_df], ignore_index=True)\n forward_result_df.sort_values(by=settings_obj.time_field_name, inplace=True, ascending=True) # 升序\n if len(forward_results)>=close_contact_record_num:\n # 这时候在forward_time, current_time时间范围内所有记录都已经被查询出\n close_contact_record_num = settings_obj.close_contact_people_num - forward_result_df[settings_obj.user_id_field_name].nunique()\n if close_contact_record_num>0 and len(forward_result_df)>0:\n current_time = forward_result_df.loc[0,settings_obj.time_field_name]\n user_id = forward_result_df.loc[0,settings_obj.user_id_field_name]\n forward_result_df = get_forward_contacts(forward_time,current_time, location_condition_str, user_id, conn, table_obj,close_contact_record_num=close_contact_record_num,forward_result_df=forward_result_df)\n return forward_result_df\n\n\ndef change_time_type(time,table_obj):\n '''\n 转换str_time的类型\n :param time: 字符串或者datetime两种类型\n :param table_obj:\n :return:\n '''\n if isinstance(time,datetime) or isinstance(time,str):\n if table_obj.c[settings_obj.time_field_name].type.python_type==datetime:\n if isinstance(time,str):\n return datetime.strptime(time,'%Y-%m-%d %H:%M:%S')\n else:\n if isinstance(time,datetime):\n return str(time)\n return time\n\n\ndef change_userid_type(user_id,table_obj):\n if table_obj.c[settings_obj.user_id_field_name].type.python_type==int:\n return int(user_id)\n return str(user_id)\n\n\ndef get_contact(user_id, conn, table_obj):\n # 针对user_id进行密接查询\n # 首先查询user_id在flow_tone_start_time和flow_tone_end_time时间内的消费记录\n # 因为user_id对应的消费记录也需要输出,所以查询时要查出包括location_filed_names、time_field_name、result_filed_names中的所有字段\n flow_tone_start_time = change_time_type(settings_obj.flow_tone_start_time, table_obj)\n flow_tone_end_time = change_time_type(settings_obj.flow_tone_end_time, table_obj)\n user_id = change_userid_type(user_id,table_obj)\n s = f\"conn.session.query({settings_obj.filed_names_str}).filter(table_obj.c[settings_obj.user_id_field_name]== user_id, table_obj.c[settings_obj.time_field_name]>=flow_tone_start_time, table_obj.c[settings_obj.time_field_name]<=flow_tone_end_time).order_by(table_obj.c[settings_obj.time_field_name]).all()\"\n records = eval(s)\n result_df = pd.DataFrame(columns=settings_obj.result_filed_names)\n for record in records:\n # 针对每一条消费记录,分别查询在该时间前后close_contact_time分钟内在该地点消费的相关记录,不超过多少人\n current_time = record[settings_obj.time_field_name]\n forward_time, backward_time = get_forward_backward_time(current_time, settings_obj.close_contact_time)\n forward_time = change_time_type(forward_time, table_obj)\n backward_time = change_time_type(backward_time, table_obj)\n current_time = change_time_type(current_time, table_obj)\n location_condition_list = []\n for location_filed_name in settings_obj.location_filed_names:\n location_condition = f\"table_obj.c['{location_filed_name}']=='{record[location_filed_name]}'\"\n location_condition_list.append(location_condition)\n location_condition_str = \", \".join(location_condition_list)\n # 先向前查询\n forward_results = get_forward_contacts(forward_time,current_time,location_condition_str,user_id,conn,table_obj)\n forward_results.drop_duplicates(subset=[settings_obj.user_id_field_name], keep ='last', inplace = True) # 去重\n # 先向后查询\n backward_results = get_backward_contacts(backward_time,current_time,location_condition_str,user_id,conn,table_obj)\n backward_results.drop_duplicates(subset=[settings_obj.user_id_field_name], keep ='first', inplace = True)\n # 放在一起\n result_df = pd.concat([result_df, forward_results], ignore_index=True)\n userid_result = [record[i] for i in settings_obj.result_filed_names]\n result_df.loc[len(result_df)] = userid_result # 记录user_id对应的消费记录\n result_df = pd.concat([result_df, backward_results], ignore_index=True)\n result_df[\"contact_\" + settings_obj.user_id_field_name] = user_id\n return result_df\n\n\ndef change_settings_obj():\n '''\n 将settings_obj 中的列表参数转为字符串\n :return:\n '''\n tmp_result_filed_names2 = settings_obj.result_filed_names.copy()\n tmp_result_filed_names2.append(settings_obj.time_field_name)\n tmp_result_filed_names2.extend(settings_obj.location_filed_names)\n tmp_result_filed_names2= [\"table_obj.c['\"+i+\"']\" for i in set(tmp_result_filed_names2)]\n filed_names_str = \", \".join(tmp_result_filed_names2)\n settings_obj.filed_names_str = filed_names_str\n tmp_result_filed_names3= [\"table_obj.c['\"+i+\"']\" for i in settings_obj.result_filed_names]\n result_filed_names_str = \", \".join(tmp_result_filed_names3)\n settings_obj.result_filed_names_str = result_filed_names_str\n\n\ndef flow_tone(user_ids, conn):\n # 定义输出的df\n tmp_result_filed_names = settings_obj.result_filed_names.copy()\n result_columns = tmp_result_filed_names.append(\"contact_\" + settings_obj.user_id_field_name)\n result_df = pd.DataFrame(columns=result_columns)\n change_settings_obj()\n # 获取数据库表的对象\n table_obj = conn.get_table_obj(settings_obj.table_name,settings_obj)\n for user_id in user_ids:\n # 针对每一条 user_id 进行密接查询\n logger.info(f\"针对 {settings_obj.user_id_field_name} 为 {user_id} 的人员进行密接查询\")\n sub_result_df = get_contact(user_id, conn, table_obj)\n result_df = pd.concat([result_df, sub_result_df], ignore_index=True)\n return result_df\n" ]
[ [ "pandas.DataFrame", "pandas.concat" ] ]
HsiuWen/FairMOT
[ "67c4fe4b5ce11f960251bd8d0cdfd37622194e29" ]
[ "src/lib/datasets/dataset/jde.py" ]
[ "import glob\nimport math\nimport os\nimport os.path as osp\nimport random\nimport time\nfrom collections import OrderedDict\n\nimport cv2\nimport json\nimport numpy as np\nimport torch\nimport copy\n\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms import transforms as T\nfrom cython_bbox import bbox_overlaps as bbox_ious\nfrom opts import opts\nfrom utils.image import gaussian_radius, draw_umich_gaussian, draw_msra_gaussian\nfrom utils.utils import xyxy2xywh, generate_anchors, xywh2xyxy, encode_delta\n\n\nclass LoadImages: # for inference\n def __init__(self, path, img_size=(1088, 608)):\n if os.path.isdir(path):\n image_format = ['.jpg', '.jpeg', '.png', '.tif']\n self.files = sorted(glob.glob('%s/*.*' % path))\n self.files = list(filter(lambda x: os.path.splitext(x)[1].lower() in image_format, self.files))\n elif os.path.isfile(path):\n self.files = [path]\n\n self.nF = len(self.files) # number of image files\n self.width = img_size[0]\n self.height = img_size[1]\n self.count = 0\n\n assert self.nF > 0, 'No images found in ' + path\n\n def __iter__(self):\n self.count = -1\n return self\n\n def __next__(self):\n self.count += 1\n if self.count == self.nF:\n raise StopIteration\n img_path = self.files[self.count]\n\n # Read image\n img0 = cv2.imread(img_path) # BGR\n assert img0 is not None, 'Failed to load ' + img_path\n\n # Padded resize\n img, _, _, _ = letterbox(img0, height=self.height, width=self.width)\n\n # Normalize RGB\n img = img[:, :, ::-1].transpose(2, 0, 1)\n img = np.ascontiguousarray(img, dtype=np.float32)\n img /= 255.0\n\n # cv2.imwrite(img_path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image\n return img_path, img, img0\n\n def __getitem__(self, idx):\n idx = idx % self.nF\n img_path = self.files[idx]\n\n # Read image\n img0 = cv2.imread(img_path) # BGR\n assert img0 is not None, 'Failed to load ' + img_path\n\n # Padded resize\n img, _, _, _ = letterbox(img0, height=self.height, width=self.width)\n\n # Normalize RGB\n img = img[:, :, ::-1].transpose(2, 0, 1)\n img = np.ascontiguousarray(img, dtype=np.float32)\n img /= 255.0\n\n return img_path, img, img0\n\n def __len__(self):\n return self.nF # number of files\n\n\nclass LoadVideo: # for inference\n def __init__(self, path, img_size=(1088, 608)):\n self.cap = cv2.VideoCapture(path)\n self.frame_rate = int(round(self.cap.get(cv2.CAP_PROP_FPS)))\n self.vw = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n self.vh = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n self.vn = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n self.width = img_size[0]\n self.height = img_size[1]\n self.count = 0\n\n self.w, self.h = 1920, 1080\n print('Lenth of the video: {:d} frames'.format(self.vn))\n\n def get_size(self, vw, vh, dw, dh):\n wa, ha = float(dw) / vw, float(dh) / vh\n a = min(wa, ha)\n return int(vw * a), int(vh * a)\n\n def __iter__(self):\n self.count = -1\n return self\n\n def __next__(self):\n self.count += 1\n if self.count == len(self):\n raise StopIteration\n # Read image\n res, img0 = self.cap.read() # BGR\n assert img0 is not None, 'Failed to load frame {:d}'.format(self.count)\n img0 = cv2.resize(img0, (self.w, self.h))\n\n # Padded resize\n img, _, _, _ = letterbox(img0, height=self.height, width=self.width)\n\n # Normalize RGB\n img = img[:, :, ::-1].transpose(2, 0, 1)\n img = np.ascontiguousarray(img, dtype=np.float32)\n img /= 255.0\n\n # cv2.imwrite(img_path + '.letterbox.jpg', 255 * img.transpose((1, 2, 0))[:, :, ::-1]) # save letterbox image\n return self.count, img, img0\n\n def __len__(self):\n return self.vn # number of files\n\n\nclass LoadImagesAndLabels: # for training\n def __init__(self, path, img_size=(1088, 608), augment=False, transforms=None):\n with open(path, 'r') as file:\n self.img_files = file.readlines()\n self.img_files = [x.replace('\\n', '') for x in self.img_files]\n self.img_files = list(filter(lambda x: len(x) > 0, self.img_files))\n\n self.label_files = [x.replace('images', 'labels_with_ids').replace('.png', '.txt').replace('.jpg', '.txt')\n for x in self.img_files]\n\n self.nF = len(self.img_files) # number of image files\n self.width = img_size[0]\n self.height = img_size[1]\n self.augment = augment\n self.transforms = transforms\n\n def __getitem__(self, files_index):\n img_path = self.img_files[files_index]\n label_path = self.label_files[files_index]\n return self.get_data(img_path, label_path)\n\n def get_data(self, img_path, label_path):\n height = self.height\n width = self.width\n img = cv2.imread(img_path) # BGR\n if img is None:\n raise ValueError('File corrupt {}'.format(img_path))\n augment_hsv = True\n if self.augment and augment_hsv:\n # SV augmentation by 50%\n fraction = 0.50\n img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n S = img_hsv[:, :, 1].astype(np.float32)\n V = img_hsv[:, :, 2].astype(np.float32)\n\n a = (random.random() * 2 - 1) * fraction + 1\n S *= a\n if a > 1:\n np.clip(S, a_min=0, a_max=255, out=S)\n\n a = (random.random() * 2 - 1) * fraction + 1\n V *= a\n if a > 1:\n np.clip(V, a_min=0, a_max=255, out=V)\n\n img_hsv[:, :, 1] = S.astype(np.uint8)\n img_hsv[:, :, 2] = V.astype(np.uint8)\n cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img)\n\n h, w, _ = img.shape\n img, ratio, padw, padh = letterbox(img, height=height, width=width)\n\n # Load labels\n if os.path.isfile(label_path):\n labels0 = np.loadtxt(label_path, dtype=np.float32).reshape(-1, 6)\n\n # Normalized xywh to pixel xyxy format\n labels = labels0.copy()\n labels[:, 2] = ratio * w * (labels0[:, 2] - labels0[:, 4] / 2) + padw\n labels[:, 3] = ratio * h * (labels0[:, 3] - labels0[:, 5] / 2) + padh\n labels[:, 4] = ratio * w * (labels0[:, 2] + labels0[:, 4] / 2) + padw\n labels[:, 5] = ratio * h * (labels0[:, 3] + labels0[:, 5] / 2) + padh\n else:\n labels = np.array([])\n\n # Augment image and labels\n if self.augment:\n img, labels, M = random_affine(img, labels, degrees=(-5, 5), translate=(0.10, 0.10), scale=(0.50, 1.20))\n\n plotFlag = False\n if plotFlag:\n import matplotlib\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n plt.figure(figsize=(50, 50))\n plt.imshow(img[:, :, ::-1])\n plt.plot(labels[:, [1, 3, 3, 1, 1]].T, labels[:, [2, 2, 4, 4, 2]].T, '.-')\n plt.axis('off')\n plt.savefig('test.jpg')\n time.sleep(10)\n\n nL = len(labels)\n if nL > 0:\n # convert xyxy to xywh\n labels[:, 2:6] = xyxy2xywh(labels[:, 2:6].copy()) # / height\n labels[:, 2] /= width\n labels[:, 3] /= height\n labels[:, 4] /= width\n labels[:, 5] /= height\n if self.augment:\n # random left-right flip\n lr_flip = True\n if lr_flip & (random.random() > 0.5):\n img = np.fliplr(img)\n if nL > 0:\n labels[:, 2] = 1 - labels[:, 2]\n\n img = np.ascontiguousarray(img[:, :, ::-1]) # BGR to RGB\n\n if self.transforms is not None:\n img = self.transforms(img)\n\n return img, labels, img_path, (h, w)\n\n def __len__(self):\n return self.nF # number of batches\n\n\ndef letterbox(img, height=608, width=1088,\n color=(127.5, 127.5, 127.5)): # resize a rectangular image to a padded rectangular\n shape = img.shape[:2] # shape = [height, width]\n ratio = min(float(height) / shape[0], float(width) / shape[1])\n new_shape = (round(shape[1] * ratio), round(shape[0] * ratio)) # new_shape = [width, height]\n dw = (width - new_shape[0]) / 2 # width padding\n dh = (height - new_shape[1]) / 2 # height padding\n top, bottom = round(dh - 0.1), round(dh + 0.1)\n left, right = round(dw - 0.1), round(dw + 0.1)\n img = cv2.resize(img, new_shape, interpolation=cv2.INTER_AREA) # resized, no border\n img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # padded rectangular\n return img, ratio, dw, dh\n\n\ndef random_affine(img, targets=None, degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-2, 2),\n borderValue=(127.5, 127.5, 127.5)):\n # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))\n # https://medium.com/uruvideo/dataset-augmentation-with-random-homographies-a8f4b44830d4\n\n border = 0 # width of added border (optional)\n height = img.shape[0]\n width = img.shape[1]\n\n # Rotation and Scale\n R = np.eye(3)\n a = random.random() * (degrees[1] - degrees[0]) + degrees[0]\n # a += random.choice([-180, -90, 0, 90]) # 90deg rotations added to small rotations\n s = random.random() * (scale[1] - scale[0]) + scale[0]\n R[:2] = cv2.getRotationMatrix2D(angle=a, center=(img.shape[1] / 2, img.shape[0] / 2), scale=s)\n\n # Translation\n T = np.eye(3)\n T[0, 2] = (random.random() * 2 - 1) * translate[0] * img.shape[0] + border # x translation (pixels)\n T[1, 2] = (random.random() * 2 - 1) * translate[1] * img.shape[1] + border # y translation (pixels)\n\n # Shear\n S = np.eye(3)\n S[0, 1] = math.tan((random.random() * (shear[1] - shear[0]) + shear[0]) * math.pi / 180) # x shear (deg)\n S[1, 0] = math.tan((random.random() * (shear[1] - shear[0]) + shear[0]) * math.pi / 180) # y shear (deg)\n\n M = S @ T @ R # Combined rotation matrix. ORDER IS IMPORTANT HERE!!\n imw = cv2.warpPerspective(img, M, dsize=(width, height), flags=cv2.INTER_LINEAR,\n borderValue=borderValue) # BGR order borderValue\n\n # Return warped points also\n if targets is not None:\n if len(targets) > 0:\n n = targets.shape[0]\n points = targets[:, 2:6].copy()\n area0 = (points[:, 2] - points[:, 0]) * (points[:, 3] - points[:, 1])\n\n # warp points\n xy = np.ones((n * 4, 3))\n xy[:, :2] = points[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1\n xy = (xy @ M.T)[:, :2].reshape(n, 8)\n\n # create new boxes\n x = xy[:, [0, 2, 4, 6]]\n y = xy[:, [1, 3, 5, 7]]\n xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n # apply angle-based reduction\n radians = a * math.pi / 180\n reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5\n x = (xy[:, 2] + xy[:, 0]) / 2\n y = (xy[:, 3] + xy[:, 1]) / 2\n w = (xy[:, 2] - xy[:, 0]) * reduction\n h = (xy[:, 3] - xy[:, 1]) * reduction\n xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T\n\n # reject warped points outside of image\n #np.clip(xy[:, 0], 0, width, out=xy[:, 0])\n #np.clip(xy[:, 2], 0, width, out=xy[:, 2])\n #np.clip(xy[:, 1], 0, height, out=xy[:, 1])\n #np.clip(xy[:, 3], 0, height, out=xy[:, 3])\n w = xy[:, 2] - xy[:, 0]\n h = xy[:, 3] - xy[:, 1]\n area = w * h\n ar = np.maximum(w / (h + 1e-16), h / (w + 1e-16))\n i = (w > 4) & (h > 4) & (area / (area0 + 1e-16) > 0.1) & (ar < 10)\n\n targets = targets[i]\n targets[:, 2:6] = xy[i]\n\n return imw, targets, M\n else:\n return imw\n\n\ndef collate_fn(batch):\n imgs, labels, paths, sizes = zip(*batch)\n batch_size = len(labels)\n imgs = torch.stack(imgs, 0)\n max_box_len = max([l.shape[0] for l in labels])\n labels = [torch.from_numpy(l) for l in labels]\n filled_labels = torch.zeros(batch_size, max_box_len, 6)\n labels_len = torch.zeros(batch_size)\n\n for i in range(batch_size):\n isize = labels[i].shape[0]\n if len(labels[i]) > 0:\n filled_labels[i, :isize, :] = labels[i]\n labels_len[i] = isize\n\n return imgs, filled_labels, paths, sizes, labels_len.unsqueeze(1)\n\n\nclass JointDataset(LoadImagesAndLabels): # for training\n default_resolution = [1088, 608]\n mean = None\n std = None\n num_classes = 1\n\n def __init__(self, opt, root, paths, img_size=(1088, 608), augment=False, transforms=None):\n self.opt = opt\n dataset_names = paths.keys()\n self.img_files = OrderedDict()\n self.label_files = OrderedDict()\n self.tid_num = OrderedDict()\n self.tid_start_index = OrderedDict()\n self.num_classes = 1 #TODO JointDataset limit the tracking to one class type only\n\n for ds, path in paths.items():\n with open(path, 'r') as file:\n self.img_files[ds] = file.readlines()\n self.img_files[ds] = [osp.join(root, x.strip()) for x in self.img_files[ds]]\n self.img_files[ds] = list(filter(lambda x: len(x) > 0, self.img_files[ds]))\n\n self.label_files[ds] = [\n x.replace('images', 'labels_with_ids').replace('.png', '.txt').replace('.jpg', '.txt')\n for x in self.img_files[ds]]\n\n for ds, label_paths in self.label_files.items():\n max_index = -1\n print('Processing labels files ({}), please be patiend.'.format(len(label_paths)))\n every_10_percent = int(len(label_paths)/10)\n count = 0\n for lp in label_paths:\n count +=1\n if count % every_10_percent == 0:\n print('Finished {}0%'.format(int(count/every_10_percent)))\n lb = np.loadtxt(lp)\n if len(lb) < 1:\n continue\n if len(lb.shape) < 2:\n img_max = lb[1]\n else:\n img_max = np.max(lb[:, 1])\n if img_max > max_index:\n max_index = img_max\n self.tid_num[ds] = max_index + 1\n # For fast debugging of UA-DETRAC\n # self.tid_num[ds] = 342\n \n last_index = 0\n for i, (k, v) in enumerate(self.tid_num.items()):\n self.tid_start_index[k] = last_index\n last_index += v\n\n self.nID = int(last_index + 1)\n self.nds = [len(x) for x in self.img_files.values()]\n self.cds = [sum(self.nds[:i]) for i in range(len(self.nds))]\n self.nF = sum(self.nds)\n self.width = img_size[0]\n self.height = img_size[1]\n self.max_objs = opt.K\n self.augment = augment\n self.transforms = transforms\n\n print('=' * 80)\n print('dataset summary')\n print(self.tid_num)\n print('total # identities:', self.nID)\n print('start index')\n print(self.tid_start_index)\n print('=' * 80)\n\n def __getitem__(self, files_index):\n\n for i, c in enumerate(self.cds):\n if files_index >= c:\n ds = list(self.label_files.keys())[i]\n start_index = c\n\n img_path = self.img_files[ds][files_index - start_index]\n label_path = self.label_files[ds][files_index - start_index]\n\n imgs, labels, img_path, (input_h, input_w) = self.get_data(img_path, label_path)\n for i, _ in enumerate(labels):\n if labels[i, 1] > -1:\n labels[i, 1] += self.tid_start_index[ds]\n\n output_h = imgs.shape[1] // self.opt.down_ratio\n output_w = imgs.shape[2] // self.opt.down_ratio\n num_classes = self.num_classes\n num_objs = labels.shape[0]\n hm = np.zeros((num_classes, output_h, output_w), dtype=np.float32)\n if self.opt.ltrb:\n wh = np.zeros((self.max_objs, 4), dtype=np.float32)\n else:\n wh = np.zeros((self.max_objs, 2), dtype=np.float32)\n reg = np.zeros((self.max_objs, 2), dtype=np.float32)\n ind = np.zeros((self.max_objs, ), dtype=np.int64)\n reg_mask = np.zeros((self.max_objs, ), dtype=np.uint8)\n ids = np.zeros((self.max_objs, ), dtype=np.int64)\n bbox_xys = np.zeros((self.max_objs, 4), dtype=np.float32)\n\n draw_gaussian = draw_msra_gaussian if self.opt.mse_loss else draw_umich_gaussian\n for k in range(num_objs):\n label = labels[k]\n bbox = label[2:]\n cls_id = int(label[0])\n bbox[[0, 2]] = bbox[[0, 2]] * output_w\n bbox[[1, 3]] = bbox[[1, 3]] * output_h\n bbox_amodal = copy.deepcopy(bbox)\n bbox_amodal[0] = bbox_amodal[0] - bbox_amodal[2] / 2.\n bbox_amodal[1] = bbox_amodal[1] - bbox_amodal[3] / 2.\n bbox_amodal[2] = bbox_amodal[0] + bbox_amodal[2]\n bbox_amodal[3] = bbox_amodal[1] + bbox_amodal[3]\n bbox[0] = np.clip(bbox[0], 0, output_w - 1)\n bbox[1] = np.clip(bbox[1], 0, output_h - 1)\n h = bbox[3]\n w = bbox[2]\n\n bbox_xy = copy.deepcopy(bbox)\n bbox_xy[0] = bbox_xy[0] - bbox_xy[2] / 2\n bbox_xy[1] = bbox_xy[1] - bbox_xy[3] / 2\n bbox_xy[2] = bbox_xy[0] + bbox_xy[2]\n bbox_xy[3] = bbox_xy[1] + bbox_xy[3]\n\n if h > 0 and w > 0:\n radius = gaussian_radius((math.ceil(h), math.ceil(w)))\n radius = max(0, int(radius))\n radius = 6 if self.opt.mse_loss else radius\n #radius = max(1, int(radius)) if self.opt.mse_loss else radius\n ct = np.array(\n [bbox[0], bbox[1]], dtype=np.float32)\n ct_int = ct.astype(np.int32)\n draw_gaussian(hm[cls_id], ct_int, radius)\n if self.opt.ltrb:\n wh[k] = ct[0] - bbox_amodal[0], ct[1] - bbox_amodal[1], \\\n bbox_amodal[2] - ct[0], bbox_amodal[3] - ct[1]\n else:\n wh[k] = 1. * w, 1. * h\n ind[k] = ct_int[1] * output_w + ct_int[0]\n reg[k] = ct - ct_int\n reg_mask[k] = 1\n ids[k] = label[1]\n bbox_xys[k] = bbox_xy\n\n ret = {'input': imgs, 'hm': hm, 'reg_mask': reg_mask, 'ind': ind, 'wh': wh, 'reg': reg, 'ids': ids, 'bbox': bbox_xys}\n return ret\n\n\nclass DetDataset(LoadImagesAndLabels): # for training\n def __init__(self, root, paths, img_size=(1088, 608), augment=False, transforms=None):\n\n dataset_names = paths.keys()\n self.img_files = OrderedDict()\n self.label_files = OrderedDict()\n self.tid_num = OrderedDict()\n self.tid_start_index = OrderedDict()\n for ds, path in paths.items():\n with open(path, 'r') as file:\n self.img_files[ds] = file.readlines()\n self.img_files[ds] = [osp.join(root, x.strip()) for x in self.img_files[ds]]\n self.img_files[ds] = list(filter(lambda x: len(x) > 0, self.img_files[ds]))\n\n self.label_files[ds] = [\n x.replace('images', 'labels_with_ids').replace('.png', '.txt').replace('.jpg', '.txt')\n for x in self.img_files[ds]]\n\n for ds, label_paths in self.label_files.items():\n max_index = -1\n for lp in label_paths:\n lb = np.loadtxt(lp)\n if len(lb) < 1:\n continue\n if len(lb.shape) < 2:\n img_max = lb[1]\n else:\n img_max = np.max(lb[:, 1])\n if img_max > max_index:\n max_index = img_max\n self.tid_num[ds] = max_index + 1\n\n last_index = 0\n for i, (k, v) in enumerate(self.tid_num.items()):\n self.tid_start_index[k] = last_index\n last_index += v\n\n self.nID = int(last_index + 1)\n self.nds = [len(x) for x in self.img_files.values()]\n self.cds = [sum(self.nds[:i]) for i in range(len(self.nds))]\n self.nF = sum(self.nds)\n self.width = img_size[0]\n self.height = img_size[1]\n self.augment = augment\n self.transforms = transforms\n\n print('=' * 80)\n print('dataset summary')\n print(self.tid_num)\n print('total # identities:', self.nID)\n print('start index')\n print(self.tid_start_index)\n print('=' * 80)\n\n def __getitem__(self, files_index):\n\n for i, c in enumerate(self.cds):\n if files_index >= c:\n ds = list(self.label_files.keys())[i]\n start_index = c\n\n img_path = self.img_files[ds][files_index - start_index]\n label_path = self.label_files[ds][files_index - start_index]\n if os.path.isfile(label_path):\n labels0 = np.loadtxt(label_path, dtype=np.float32).reshape(-1, 6)\n\n imgs, labels, img_path, (h, w) = self.get_data(img_path, label_path)\n for i, _ in enumerate(labels):\n if labels[i, 1] > -1:\n labels[i, 1] += self.tid_start_index[ds]\n\n return imgs, labels0, img_path, (h, w)\n\n\n" ]
[ [ "numpy.ones", "torch.stack", "matplotlib.pyplot.imshow", "matplotlib.pyplot.plot", "numpy.ascontiguousarray", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "numpy.fliplr", "torch.from_numpy", "matplotlib.use", "numpy.eye", "numpy.zeros", "matplotlib.pyplot.axis", "numpy.max", "numpy.maximum", "numpy.array", "numpy.clip", "torch.zeros", "numpy.concatenate", "numpy.loadtxt" ] ]
llichengtong/yx1
[ "6619532e43799fea739a21fb14b999f7d1898fe9" ]
[ "h_RNN/Mnist.py" ]
[ "import time\r\nimport tflearn\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nfrom h_RNN.RNN import RNNWrapper, Generator\r\nfrom h_RNN.SpRNN import SparseRNN\r\nfrom Util.Util import DataUtil\r\n\r\n\r\nclass MnistGenerator(Generator):\r\n def __init__(self, im=None, om=None, one_hot=True):\r\n super(MnistGenerator, self).__init__(im, om)\r\n self._x, self._y = DataUtil.get_dataset(\"mnist\", \"../_Data/mnist.txt\", quantized=True, one_hot=one_hot)\r\n self._x = self._x.reshape(-1, 28, 28)\r\n self._x_train, self._x_test = self._x[:1800], self._x[1800:]\r\n self._y_train, self._y_test = self._y[:1800], self._y[1800:]\r\n\r\n def gen(self, batch, test=False, **kwargs):\r\n if batch == 0:\r\n if test:\r\n return self._x_test, self._y_test\r\n return self._x_train, self._y_train\r\n batch = np.random.choice(len(self._x_train), batch)\r\n return self._x_train[batch], self._y_train[batch]\r\n\r\nif __name__ == '__main__':\r\n n_history = 3\r\n print(\"=\" * 60, \"\\n\" + \"Normal LSTM\", \"\\n\" + \"-\" * 60)\r\n generator = MnistGenerator()\r\n t = time.time()\r\n tf.reset_default_graph()\r\n rnn = RNNWrapper()\r\n rnn.fit(28, 10, generator, n_history=n_history, epoch=10, squeeze=True)\r\n print(\"Time Cost: {}\".format(time.time() - t))\r\n rnn.draw_err_logs()\r\n\r\n print(\"=\" * 60, \"\\n\" + \"Sparse LSTM\" + \"\\n\" + \"-\" * 60)\r\n generator = MnistGenerator(one_hot=False)\r\n t = time.time()\r\n tf.reset_default_graph()\r\n rnn = SparseRNN()\r\n rnn.fit(28, 10, generator, n_history=n_history, epoch=10)\r\n print(\"Time Cost: {}\".format(time.time() - t))\r\n rnn.draw_err_logs()\r\n\r\n print(\"=\" * 60, \"\\n\" + \"Tflearn\", \"\\n\" + \"-\" * 60)\r\n generator = MnistGenerator()\r\n t = time.time()\r\n tf.reset_default_graph()\r\n net = tflearn.input_data(shape=[None, 28, 28])\r\n net = tf.concat(tflearn.lstm(net, 128, return_seq=True)[-n_history:], axis=1)\r\n net = tflearn.fully_connected(net, 10, activation='softmax')\r\n net = tflearn.regression(net, optimizer='adam', batch_size=64,\r\n loss='categorical_crossentropy')\r\n model = tflearn.DNN(net, tensorboard_verbose=0)\r\n model.fit(*generator.gen(0), n_epoch=10, validation_set=generator.gen(0, True), show_metric=True)\r\n print(\"Time Cost: {}\".format(time.time() - t))\r\n" ]
[ [ "tensorflow.reset_default_graph" ] ]
vamsigp/EVA5
[ "e03603cbf41f8d18d2e0ac149ddc5718371a360e" ]
[ "trainer/trainer.py" ]
[ "from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom tqdm import tqdm\n\n\nclass Trainer():\n\n def __init__(self, model, device, train_loader, test_loader, optimizer, loss_func, lr_scheduler):\n self.is_last_epoch = False\n# self.train_losses = [] # detailed training loss\n self.test_losses = []\n# self.train_acc = [] # detailed training accuracy\n self.train_acc_total = [] # per epoch training accuracy\n self.train_loss_total = [] # per epoch train loss\n self.test_acc = []\n self.model = model\n self.device = device\n self.train_loader = train_loader\n self.test_loader = test_loader\n self.optimizer = optimizer\n self.loss_func = loss_func\n self.lr_scheduler = lr_scheduler\n\n def train_model(self, lambda_l1, epochs=5):\n for epoch in range(epochs):\n print(\"\\nCurrent EPOCH:\", epoch)\n\n if self.lr_scheduler is not None:\n if not isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):\n print(\"Current EPOCH:\", epoch, \"last LR=\", self.lr_scheduler.get_last_lr(), \"LR = \", self.lr_scheduler.get_lr())\n else:\n print(\"Learning Rate(ReduceLROnPlateau) = \", self.optimizer.param_groups[0]['lr'])\n # https://discuss.pytorch.org/t/how-to-retrieve-learning-rate-from-reducelronplateau-scheduler/54234\n\n self.train(epoch, lambda_l1)\n self.is_last_epoch = epoch == epochs\n tst_metric = self.test()\n\n if self.lr_scheduler is not None:\n if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau):\n val_loss = tst_metric # test_losses[-1]\n print(\"ReduceLROnPlateau, ReduceLROnPlateau::step(), val_loss\", val_loss)\n self.lr_scheduler.step(val_loss)\n\n if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.StepLR):\n self.lr_scheduler.step()\n\n\n return (self.train_loss_total, self.train_acc_total, self.test_losses, self.test_acc)\n\n# def get_detailed_train_stats(self):\n# return (self.train_losses, self.train_acc)\n\n def train(self, epoch, lambda_l1):\n self.model.train()\n pbar = tqdm(self.train_loader)\n correct = 0\n processed = 0\n loss = 0\n for batch_idx, (data, target) in enumerate(pbar):\n # get samples\n data, target = data.to(self.device), target.to(self.device)\n\n # Init\n self.optimizer.zero_grad()\n # In PyTorch, we need to set the gradients to zero before starting to do backpropragation because PyTorch accumulates the gradients on subsequent backward passes.\n # Because of this, when you start your training loop, ideally you should zero out the gradients so that you do the parameter update correctly.\n\n # Predict\n y_pred = self.model(data)\n\n # Calculate loss\n loss = self.loss_func(y_pred, target)\n\n # L2 loss\n\n # L1 loss\n loss_l1 = 0\n # lambda_l1 = 0.05\n if lambda_l1 > 0:\n for p in self.model.parameters():\n loss_l1 = loss_l1 + p.abs().sum()\n loss = loss + lambda_l1 * loss_l1\n\n# self.train_losses.append(loss)\n\n # Backpropagation\n loss.backward()\n self.optimizer.step()\n\n pred = y_pred.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n processed += len(data)\n\n pbar.set_description(\n desc=f'Train set: Loss={loss.item()} Batch_id={batch_idx} Accuracy={100 * correct / processed:0.2f}')\n# self.train_acc.append(100 * correct / processed)\n\n if isinstance(self.lr_scheduler, torch.optim.lr_scheduler.OneCycleLR):\n self.lr_scheduler.step()\n\n\n training_accuracy_perepoch = 100 * correct / processed\n self.train_acc_total.append(training_accuracy_perepoch)\n self.train_loss_total.append(loss)\n\n def test(self):\n self.model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in self.test_loader:\n data, target = data.to(self.device), target.to(self.device)\n output = self.model(data)\n test_loss += self.loss_func(output, target).item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n is_correct = pred.eq(target.view_as(pred))\n correct += is_correct.sum().item()\n\n test_loss /= len(self.test_loader.dataset)\n self.test_losses.append(test_loss)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(self.test_loader.dataset),\n 100. * correct / len(self.test_loader.dataset)))\n\n self.test_acc.append(100. * correct / len(self.test_loader.dataset))\n return test_loss\n\n def getValues(self):\n return (self.train_loss_total, self.train_acc_total, self.test_losses, self.test_acc)\n\n def get_misclassified(self):\n self.model.eval()\n misclassified_imgs = []\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in self.test_loader:\n data, target = data.to(self.device), target.to(self.device)\n output = self.model(data)\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n is_correct = pred.eq(target.view_as(pred))\n if True:\n misclassified_inds = (is_correct == 0).nonzero()[:, 0]\n for mis_ind in misclassified_inds:\n if len(misclassified_imgs) == 25:\n break\n misclassified_imgs.append({\n \"target\": target[mis_ind].cpu().numpy(),\n \"pred\": pred[mis_ind][0].cpu().numpy(),\n \"img\": data[mis_ind].cpu().numpy()\n })\n correct += is_correct.sum().item()\n\n return misclassified_imgs\n\n def classwise_acc(self, classes):\n class_correct = list(0. for i in range(10))\n class_total = list(0. for i in range(10))\n with torch.no_grad():\n for images, labels in self.test_loader:\n images, labels = images.to(self.device), labels.to(self.device)\n outputs = self.model(images)\n _, predicted = torch.max(outputs, 1)\n c = (predicted == labels).squeeze()\n for i in range(4):\n label = labels[i]\n class_correct[label] += c[i].item()\n class_total[label] += 1\n\n # print class-wise test accuracies\n print()\n for i in range(10):\n print('Accuracy of %5s : %2d %%' % (\n classes[i], 100 * class_correct[i] / class_total[i]))\n print()\n" ]
[ [ "torch.no_grad", "torch.max" ] ]
AlantheBenign/Minecraft-Stronghold-Finder
[ "05d3eb89eaccd3620fa25cd4c828c907aecf2178" ]
[ "finder.py" ]
[ "import numpy as np\n\n#hitCircle calculates where the first stronghold generation ring starts, where the player would \"hit\" it, moving directly forward\n#and calculates the position to the second ender eye throw\ndef hitCircle(pX,pZ,angle):\n xHit = None\n yHit = None\n cos = np.cos(angle*np.pi/180)\n #if the stronghold is at the +X\n if cos >= 0:\n x = np.linspace(pX-10, 2700,2700)\n a = np.tan(angle*np.pi/180)\n b = pZ - pX * a\n y = a*x + b\n for i in range(len(x)):\n if x[i]*x[i] + y[i]*y[i] >= 1408*1408:\n xHit = x[i]\n yHit = y[i]\n break\n pos1 = (xHit,yHit)\n x2 = np.linspace(xHit, xHit+100,500)\n a2 = -1/np.tan(angle*np.pi/180)\n b2 = yHit - xHit * a2\n y2 = a2*x2 + b2\n for i in range(len(x2)):\n if abs(x2[i] - xHit)**2 + abs(y2[i] - yHit)**2 >= 42*42:\n xST = x2[i]\n yST = y2[i]\n pos2 = (xST,yST)\n #if the stronghold is at the -X\n else:\n x = np.linspace(pX+10, -2700,2700)\n a = np.tan(angle*np.pi/180)\n b = pZ - pX * a\n y = a*x + b\n for i in range(len(x)):\n if x[i]*x[i] + y[i]*y[i] >= 1408*1408:\n xHit = x[i]\n yHit = y[i]\n break\n pos1 = (xHit,yHit)\n x2 = np.linspace(xHit, xHit+100,500)\n a2 = -1/np.tan(angle*np.pi/180)\n b2 = yHit - xHit * a2\n y2 = a2*x2 + b2\n for i in range(len(x2)):\n if abs(x2[i] - xHit)**2 + abs(y2[i] - yHit)**2 >= 42*42:\n xST = x2[i]\n yST = y2[i]\n pos2 = (xST,yST)\n \n return (pos1,pos2)\n \ndef StrongholdCoords():\n #stabilishing the variables\n f3c0 = input()\n f3c0 = f3c0[42:]\n f3c0 = f3c0.split()\n px0 = float(f3c0[0]) \n pz0 = float(f3c0[2])\n angle0 = float(f3c0[3])%360\n\n #translating minecraft angles to daily life cartesian angles\n if angle0 >= 0:\n angle0 = (angle0+90)%360\n else:\n angle0 = (angle0-270)%360\n \n #distance from origin\n distOrigin = np.sqrt(px0*px0 + pz0*pz0)\n #print(\"You're this far from the Origin: \", distOrigin)\n \n if distOrigin >= 1400:\n print(\"Move 27 blocks perpendicularly to the Ender Eye flight direction and throw the second one. (27 blocks = 4 seconds sprinting)\")\n \n else:\n circlePoint, secThrowPoint = hitCircle(px0,pz0,angle0)\n print(\"Go to: \", secThrowPoint, \"\\nCircle starts at: \", circlePoint)\n \n #stabilishing the variables\n f3c1 = input()\n f3c1 = f3c1[42:]\n f3c1 = f3c1.split()\n px1 = float(f3c1[0])\n pz1 = float(f3c1[2])\n angle1 = float(f3c1[3])%360\n \n #translating minecraft angles to daily life cartesian angles \n if angle1 >= 0:\n angle1 = (angle1+90)%360\n else:\n angle1 = (angle1-270)%360\n \n #calculating stronghold position\n a0 = np.tan(angle0*np.pi/180)\n a1 = np.tan(angle1*np.pi/180)\n b0 = pz0 - px0 * a0\n b1 = pz1 - px1 * a1\n pxS = (b1 - b0)/(a0 - a1)\n pzS = pxS * a0 + b0\n \n #printing\n print(\"Stronghold is at: \", (pxS, pzS), \" GOOD LUCK :D\")\n" ]
[ [ "numpy.sqrt", "numpy.tan", "numpy.linspace", "numpy.cos" ] ]
OliverScherf/mlir-emitc
[ "af6a34bee5563bf71a218a93139da0e25cd9b2a5" ]
[ "scripts/optimize_tf_dialect.py" ]
[ "# 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# Forked from https://github.com/google/iree\n\nimport argparse\n\nfrom tensorflow.python import pywrap_mlir # pylint: disable=no-name-in-module\n\n\ndef optimize(model_path: str, output_path: str):\n pass_pipeline = \",\".join([\n \"symbol-dce\", \"tf-standard-pipeline\",\n \"func(tf-device-index-selector)\", \"inline\", \"canonicalize\",\n \"func(tf-device-decompose-resource-ops)\",\n \"func(tf-functional-control-flow-to-cfg)\", \"inline\", \"symbol-dce\",\n \"canonicalize\", \"tf-saved-model-optimize-global-tensors\",\n \"tf-saved-model-freeze-global-tensors\"\n ])\n with open(model_path) as file:\n mlir = file.read()\n\n with open(output_path, \"w\") as file:\n file.write(\n pywrap_mlir.experimental_run_pass_pipeline(mlir, pass_pipeline,\n True))\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Optimize model in tf dialect\")\n parser.add_argument(\"model_path\",\n metavar=\"model-path\",\n help=\"Path to tf mlir model\")\n parser.add_argument(\"output_path\",\n metavar=\"output-path\",\n help=\"Output path\")\n args = parser.parse_args()\n\n optimize(args.model_path, args.output_path)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "tensorflow.python.pywrap_mlir.experimental_run_pass_pipeline" ] ]
V4I2021/V4IBack
[ "88c6215d65eccae42cde18515d1da84d94c45ba6" ]
[ "dataService/dataService.py" ]
[ "import datetime\nimport os\nimport pandas as pd\nfrom flask_caching import Cache\nimport seaborn as sns\nfrom scipy.stats import pearsonr\n\nimport numpy as np\nimport math\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import StandardScaler\n\ncache = Cache()\n\nFILE_ABS_PATH = os.path.dirname(__file__)\nROOT_PATH = os.path.join(FILE_ABS_PATH, '../')\nEDGE_FOLDER = os.path.join(ROOT_PATH, 'data/edge')\nINSIGHT_FOLDER = os.path.join(ROOT_PATH, 'data/insight')\nRECORD_FOLDER = os.path.join(ROOT_PATH, 'data/record')\nSID_CID_FOLDER = os.path.join(ROOT_PATH, 'data/sid_cid')\nSUBSPACE_FOLDER = os.path.join(ROOT_PATH, 'data/subspace')\n\nsns_counter = 0\n\n\nclass DataService():\n def __init__(self):\n pass\n\n def read_data_names(self):\n return [p.split('.')[0].split('_')[-1] for p in os.listdir(INSIGHT_FOLDER)]\n\n @cache.memoize(timeout=50)\n def __get_edge_by_name(self, name):\n edges_path = os.path.join(EDGE_FOLDER, 'edge_{}.csv'.format(name))\n df = pd.read_csv(edges_path)\n return df\n\n @cache.memoize(timeout=50)\n def __get_insight_by_name(self, name):\n insight_path = os.path.join(INSIGHT_FOLDER, 'insight_{}.csv'.format(name))\n df = pd.read_csv(insight_path)\n return df, df['insight'].unique().tolist(), df['insight_type'].unique().tolist()\n\n @cache.memoize(timeout=50)\n def __get_record_by_name(self, name):\n record_path = os.path.join(RECORD_FOLDER, 'record_{}.csv'.format(name))\n df = pd.read_csv(record_path)\n return df\n\n @cache.memoize(timeout=50)\n def __get_sid_cid_by_name(self, name):\n sid_cid_path = os.path.join(SID_CID_FOLDER, 'sid_cid_{}.csv'.format(name))\n df = pd.read_csv(sid_cid_path)\n return df\n\n @cache.memoize(timeout=50)\n def __get_subspace_by_name(self, name):\n subspace_path = os.path.join(SUBSPACE_FOLDER, 'subspace_{}.csv'.format(name))\n df = pd.read_csv(subspace_path)\n return df, df.columns.values.tolist()[0:-1]\n\n def __get_record_by_subspace(self, name, sid):\n sid_cid_data = self.__get_sid_cid_by_name(name)\n record_data = self.__get_record_by_name(name)\n\n df = pd.merge(sid_cid_data, record_data, on=['cid'])\n df = df.loc[df['sid'] == sid]\n df = df.drop(['sid', 'cid'], axis=1)\n return df\n\n def __get_subspace_str(self, subspace_col, row):\n style_before = '<span style=\"color:#f7cd59; display:inline;\">'\n style_after = '</span>'\n\n subspace = ''\n for i in range(len(subspace_col)):\n col = subspace_col[i]\n if row[col].tolist()[0] != '*':\n subspace += col + ' is ' + style_before + row[col].tolist()[0] + style_after + ', '\n if subspace[-2:] == ', ':\n subspace = subspace[0:-2]\n return subspace\n\n def get_data_by_name(self, name):\n edge_data = self.__get_edge_by_name(name)\n insight_data, insight_name, insight_type = self.__get_insight_by_name(name)\n measure_col = insight_data['measure'].unique()\n measures = []\n for measure in measure_col:\n if ';' not in measure:\n measures.append(measure)\n if len(measures) > 1:\n measures = ['All Measures'] + measures\n # record_data = self.__get_record_by_name(name)\n subspace_data, feature_data = self.__get_subspace_by_name(name)\n insight_cnt = insight_data['insight'].value_counts().to_dict()\n return {\n # 'record': record_data.to_dict('records'),\n 'insight': insight_data.to_dict('records'),\n 'edge': edge_data.to_dict('records'),\n 'feature': feature_data,\n 'insight_name': insight_name,\n 'insight_count': [insight_cnt[x] for x in insight_name],\n 'insight_type': insight_type,\n 'subspace': subspace_data.to_dict('index'),\n 'measures': measures\n }\n\n def get_insight_count_for_record_by_name(self, name):\n sid_cid_df = self.__get_sid_cid_by_name(name)\n insight_data, _, _ = self.__get_insight_by_name(name)\n iids_df = pd.merge(insight_data, sid_cid_df, on='sid', how='inner')\n iids_df = iids_df.groupby('cid')['iid'].apply(list).reset_index(name='iids')\n iids_df['iid_count'] = [len(id_list) for id_list in iids_df['iids']]\n iids_df.sort_values(by='iid_count', inplace=True, ascending=False)\n iids_df.reset_index(inplace=True, drop=True)\n res = iids_df.to_dict('index')\n return res\n\n def get_insight_by_iid(self, iid, name):\n insight_data, insight_name, insight_type = self.__get_insight_by_name(name)\n subspace_data, feature_data = self.__get_subspace_by_name(name)\n insight = insight_data.loc[insight_data['iid'] == iid]\n insight = pd.merge(insight, subspace_data, on='sid', how='inner')\n record = self.__get_record_by_subspace(name, insight['sid'].iloc[0])\n\n insight_name = insight['insight'].iloc[0]\n breakdown = insight['breakdown'].iloc[0]\n breakdown_value = insight['breakdown_value'].iloc[0]\n if breakdown_value.isdigit():\n breakdown_value = int(breakdown_value)\n measure = insight['measure'].iloc[0]\n subspace = self.__get_subspace_str(feature_data, insight)\n\n if insight_name == 'Top1':\n record = record.groupby(breakdown, as_index=False).agg({measure: 'sum'})\n record = record.sort_values(by=measure, ascending=False).iloc[0:10]\n measure_value = record[measure].tolist()\n sentence = '<span style=\"display:inline;\">The highest {} among {} is {} with {} ' \\\n 'equals <span style=\"color:#f7cd59; display:inline;\">{}</span> {}.</span>' \\\n .format(measure, breakdown, round(measure_value[0], 2),\n breakdown, breakdown_value,\n 'when ' + subspace if subspace != '' else '')\n return {\n 'insight_name': insight_name,\n 'breakdown': breakdown,\n 'breakdown_value': record[breakdown].tolist(),\n 'measure': measure,\n 'measure_value': measure_value,\n 'sentence': sentence\n }\n elif insight_name == 'Trend':\n record = record.groupby(breakdown, as_index=False).agg(\n {breakdown: 'first', measure: 'sum'})\n\n breakdown_value = record[breakdown]\n\n if breakdown == 'date' or breakdown == 'Date':\n record[breakdown] = pd.to_datetime(record[breakdown])\n try:\n x = record[breakdown].map(datetime.datetime.toordinal).values\n except:\n x = record[breakdown].values\n\n x = np.array(x).reshape(-1, 1)\n y = np.array(record[measure]).reshape(-1, 1)\n reg = LinearRegression().fit(x, y)\n slope = reg.coef_[0][0]\n sentence = '<span style=\"display:inline;\">The sum of {} over {} is ' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> {}.</span>' \\\n .format(measure, breakdown,\n ('increasing' if slope >= 0 else 'decreasing'),\n ('when ' + ' and '.join(subspace.rsplit(', ', 1)) if subspace != '' else ''), )\n # sentence = 'The trend of the {} {} over {}s' \\\n # '{}{} is {}.' \\\n # .format('total', measure, breakdown,\n # (' when ' if subspace != '' else ' in all data'),\n # ' and '.join(subspace.rsplit(', ', 1)),\n # ('increasing' if slope >= 0 else 'decreasing'))\n return {\n 'insight_name': insight_name,\n 'breakdown': breakdown,\n 'measure': measure,\n 'breakdown_value': breakdown_value.tolist(),\n 'measure_value': record[measure].tolist(),\n 'sentence': sentence\n }\n elif insight_name == 'Correlation':\n time_col = \"\"\n if name == 'carSales1':\n time_col = 'Year'\n elif name == 'Emission':\n time_col = 'Year'\n elif name == 'Census':\n time_col = 'Birthday'\n elif name == 'NBA':\n time_col = 'year'\n\n breakdown_value = insight['breakdown_value'].values[0].split(';')\n _, col_list = self.__get_subspace_by_name(name)\n record = self.__get_record_by_name(name)\n record.drop(['cid'], axis=1, inplace=True)\n\n for i in range(len(col_list)):\n value = insight[col_list[i]].values[0]\n if value != '*':\n record = record.loc[record[col_list[i]] == value]\n if breakdown_value[1] != '*':\n corr_record = record.loc[record[insight['breakdown'].values[0]] == breakdown_value[1]]\n else:\n corr_record = record.copy()\n if breakdown_value[0] != '*':\n record = record.loc[record[insight['breakdown'].values[0]] == breakdown_value[0]]\n\n corr_record = corr_record.groupby(time_col, as_index=False).agg(\n {breakdown: 'first', measure: 'sum'})\n record = record.groupby(time_col, as_index=False).agg(\n {breakdown: 'first', measure: 'sum'})\n y1 = record[measure].values\n y2 = corr_record[measure].values\n corr, _ = pearsonr(y1, y2)\n\n sentence = '<span style=\"display:inline;\">The {} of ' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> and ' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> are correlated {}.</span>' \\\n .format(measure, breakdown_value[0],\n (breakdown_value[1] if breakdown_value[1] != '*' else 'all data'),\n ('in the dataset' if subspace == '' else 'when ' + subspace))\n\n y1 = y1.tolist()\n y2 = y2.tolist()\n\n return {\n 'insight_name': insight_name,\n 'time_col': time_col,\n 'time_col_value': record[time_col].tolist(),\n 'measure': measure,\n 'measure_value': [y1, y2],\n 'max_min': [max(max(y1), max(y2)), min(min(y1), min(y2))],\n 'sentence': sentence\n }\n elif insight_name == 'Change Point' or insight_name == 'Outlier':\n record = record.groupby(breakdown, as_index=False).agg(\n {breakdown: 'first', measure: 'sum'})\n # todo: int value might be read as string\n y = record.loc[record[breakdown] == breakdown_value][measure].iloc[0]\n\n if insight_name == 'Change Point':\n sentence = '<span style=\"display:inline;\">Among {}s{}{}, ' \\\n 'change occurs in <span style=\"color:#f7cd59; display:inline;\">{}</span> ' \\\n 'and its {} {} is {}.</span>' \\\n .format(breakdown, (' when ' if subspace != '' else ' in all data'),\n ' and '.join(subspace.rsplit(', ', 1)),\n breakdown_value, 'total', measure, round(y, 2))\n\n else:\n sentence = '<span style=\"display:inline;\">Among {}s{}{}, ' \\\n 'the {} {} of {} in ' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> is an anomaly.</span>' \\\n .format(breakdown, (' when ' if subspace != '' else ' in all data'),\n ' and '.join(subspace.rsplit(', ', 1)),\n 'total', measure, round(y, 2), breakdown_value)\n\n return {\n 'insight_name': insight_name,\n 'breakdown': breakdown,\n 'measure': measure,\n 'breakdown_value': record[breakdown].tolist(),\n 'measure_value': record[measure].tolist(),\n 'x': str(breakdown_value),\n 'y': str(y),\n 'sentence': sentence\n }\n elif insight_name == 'Attribution':\n record = record.groupby(breakdown, as_index=False).agg(\n {breakdown: 'first', measure: 'sum'})\n record = record.sort_values(by=measure, ascending=False)\n\n breakdown_value = record[breakdown].tolist()\n percentage = (record[measure] / record[measure].sum()).tolist()\n\n breakdown_value_list = ''\n percentage_list = ''\n for i in range(len(breakdown_value)):\n percentage[i] = round(percentage[i], 2)\n if i == 0:\n breakdown_value_list += '<span style=\"color:#f7cd59; display:inline;\">' \\\n + breakdown_value[i] + '</span>, '\n percentage_list += '<span style=\"color:#f7cd59; display:inline;\">' \\\n + str(percentage[i]) + '</span>, '\n else:\n breakdown_value_list += breakdown_value[i] + ', '\n percentage_list += str(percentage[i]) + ', '\n if breakdown_value_list[-2:] == ', ':\n breakdown_value_list = breakdown_value_list[0:-2]\n percentage_list = percentage_list[0:-2]\n sentence = '<span style=\"display:inline;\">{} makes up {} ' \\\n 'of the {} {}{}{}{}.</span>' \\\n .format(' and '.join(breakdown_value_list.rsplit(', ', 1)),\n ' and '.join(percentage_list.rsplit(', ', 1)),\n 'total', measure,\n ' respectively ' if len(percentage) > 1 else '',\n (' when ' if subspace != '' else ' in all data'),\n ' and '.join(subspace.rsplit(', ', 1)))\n\n return {\n 'insight_name': insight_name,\n 'breakdown_value': breakdown_value,\n 'measure_value': record[measure].tolist(),\n 'sentence': sentence,\n 'percentage': percentage\n }\n elif insight_name == 'Cross Measure Correlation':\n measures = measure.split(';')\n record = record.groupby(breakdown, as_index=False).agg(\n {breakdown: 'first', measures[0]: 'sum', measures[1]: 'sum'})\n record = record.sort_values(by=measures[0])\n\n x_value = record[measures[0]].values\n y_value = record[measures[1]].values\n reg = LinearRegression().fit(x_value.reshape(-1, 1), y_value.reshape(-1, 1))\n\n sentence = '<span style=\"display:inline;\">' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> and ' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> are linear correlated' \\\n '{}{}{}being grouped by {}.</span>' \\\n .format(measures[0], measures[1],\n (' when ' if subspace != '' else ' in all data'),\n ' and '.join(subspace.rsplit(', ', 1)),\n (' and ' if subspace != '' else ' when '),\n breakdown)\n\n return {\n 'insight_name': insight_name,\n 'x_value': x_value.tolist(),\n 'y_value': y_value.tolist(),\n 'line_y_value': [reg.predict(x_value[0].reshape(-1, 1))[0][0],\n reg.predict(x_value[-1].reshape(-1, 1))[0][0]],\n 'sentence': sentence\n }\n elif insight_name == 'Clustering':\n measures = measure.split(';')\n record = record.groupby(breakdown, as_index=False).agg(\n {breakdown: 'first', measures[0]: 'sum', measures[1]: 'sum'})\n record = record.sort_values(by=measures[0])\n\n x_value = record[measures[0]].values\n y_value = record[measures[1]].values\n X = np.vstack((x_value, y_value)).T\n X_scale = StandardScaler().fit_transform(X)\n db = DBSCAN(eps=0.3, min_samples=5).fit(X_scale)\n core_samples_mask = np.zeros_like(db.labels_, dtype=bool)\n core_samples_mask[db.core_sample_indices_] = True\n labels = db.labels_\n\n noise = ''\n if -1 in labels:\n breakdown_value = record[breakdown].values\n cnt = 2\n for i, label in enumerate(labels):\n if label == -1 and cnt > 0:\n noise += str(breakdown_value[i]) + ', '\n cnt -= 1\n noise += 'etc'\n\n sentence = '<span style=\"display:inline;\">' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> and ' \\\n '<span style=\"color:#f7cd59; display:inline;\">{}</span> form clusters' \\\n '{}{}{}being grouped by {}{}{}.</span>' \\\n .format(measures[0], measures[1],\n (' when ' if subspace != '' else ' in all data'),\n ' and '.join(subspace.rsplit(', ', 1)),\n (' and ' if subspace != '' else ' when '),\n breakdown,\n (', except for ' if noise != '' else ''),\n noise)\n\n return {\n 'insight_name': insight_name,\n 'x_value': x_value.tolist(),\n 'y_value': y_value.tolist(),\n 'label': labels.tolist(),\n 'sentence': sentence\n }\n else:\n return 0\n\n def get_insight_count_for_subspace_by_name(self, name):\n insight_data, _, _ = self.__get_insight_by_name(name)\n iid_sid_df = insight_data[['iid', 'sid']].groupby('sid')['iid'].apply(list).reset_index(name='iids')\n iid_sid_df['iid_count'] = [len(id_list) for id_list in iid_sid_df['iids']]\n subspace_data, _ = self.__get_subspace_by_name(name)\n iid_sid_df = pd.merge(iid_sid_df, subspace_data, on='sid', how='inner')\n iid_sid_df.sort_values(by=['iid_count'], inplace=True, ascending=False)\n iid_sid_df.reset_index(inplace=True, drop=True)\n res = iid_sid_df.to_dict('index')\n return res\n\n def get_subspace_count_for_record_by_name(self, name):\n sid_cid_df = self.__get_sid_cid_by_name(name)\n record_data = self.__get_record_by_name(name)\n df = pd.merge(record_data, sid_cid_df, on='cid', how='inner')\n df = df.groupby('cid')['sid'].apply(list).reset_index(name='sid')\n df['sid_count'] = [len(id_list) for id_list in df['sid']]\n df.sort_values(by='sid_count', inplace=True, ascending=False)\n df.reset_index(inplace=True, drop=True)\n res = df.to_dict('index')\n return res\n\n @cache.memoize(timeout=50)\n def get_data_info_by_name(self, name):\n global sns_counter\n record_data = self.__get_record_by_name(name)\n insight_data, _, _ = self.__get_insight_by_name(name)\n record_data = record_data.drop(columns=['cid'])\n\n data_info = {\n 'dataName': name,\n 'dataDescription': '',\n 'rowCnt': record_data.shape[0],\n 'colCnt': record_data.shape[1],\n 'colName': [],\n 'colType': [],\n 'colValueType': [],\n 'colValue': []\n }\n\n for value_type in record_data.dtypes.tolist():\n value_type = str(value_type)\n if value_type != 'int64' and value_type != 'float64':\n data_info['colValueType'].append('categorical')\n else:\n data_info['colValueType'].append(value_type.rstrip('64'))\n\n if name == 'carSales1':\n data_info['dataDescription'] = 'Describe vehicle sales.'\n elif name == 'Census':\n data_info['dataDescription'] = 'Describe demographic information.'\n elif name == 'COVID-19':\n data_info['dataDescription'] = 'Describe COVID-19 cases and deaths.'\n elif name == 'Emission':\n data_info['dataDescription'] = 'Describe emissions of harmful gases in the process of energy production.'\n elif name == 'NBA':\n data_info['dataDescription'] = 'Describe NBA players\\' stats since 1947.'\n\n data_info['colName'] = record_data.columns.values.tolist()\n measure_list = insight_data['measure'].unique().tolist()\n for measure in measure_list:\n if ';' in measure:\n measure = measure.split(';')\n measure_list.append(measure[0])\n measure_list.append(measure[1])\n\n for i in range(len(data_info['colName'])):\n col = data_info['colName'][i]\n if col in measure_list:\n data_info['colType'].append('measure')\n else:\n data_info['colType'].append('dimension')\n\n if data_info['colValueType'][i] == 'int' \\\n or data_info['colValueType'][i] == 'float':\n p = sns.kdeplot(record_data[col].values)\n lines = [obj for obj in p.findobj() if str(type(obj)) == \"<class 'matplotlib.lines.Line2D'>\"]\n x, y = lines[sns_counter].get_data()[0].tolist(), lines[sns_counter].get_data()[1].tolist()\n data_info['colValue'].append([x, y,\n round(min(x), 2), round(max(x), 2),\n min(y), max(y)])\n sns_counter += 1\n else:\n cnt_dict = record_data[col].value_counts().to_dict()\n value_list = list(cnt_dict.values())\n upper_bound = value_list[0]\n while upper_bound % 5 != 0 or upper_bound % 2 != 0:\n upper_bound += 1\n data_info['colValue'].append([list(cnt_dict), value_list, upper_bound])\n\n return data_info\n\n def get_data_attr_map_by_name(self, name):\n record_data = self.__get_record_by_name(name)\n _, feature_data = self.__get_subspace_by_name(name)\n attr_map = dict()\n for feature in feature_data:\n feature_list = record_data[feature].unique().tolist()\n attr_map[feature] = dict((k, i) for (i, k) in enumerate(feature_list))\n # {'Year': {2007: 0, 2008: 1, 2009: 2, 2010: 3, 2011: 4},\n return attr_map\n\n def get_subspace_range_by_name(self, name):\n insight, _, _ = self.__get_insight_by_name(name)\n sid_list = np.unique(insight['sid'].tolist())\n subspace, feature_data = self.__get_subspace_by_name(name)\n subspace = subspace.loc[subspace['sid'].isin(sid_list)]\n subspace_range = dict()\n for feature in feature_data:\n feature_list = subspace[feature].unique().tolist()\n subspace_range[feature] = feature_list\n return subspace_range\n\n def get_data_feature_attribution_by_name(self, name):\n record_data = self.__get_record_by_name(name)\n # result = {'feature_name': {'value_name' : [start_angle, end_angle]}}\n _, feature_data = self.__get_subspace_by_name(name)\n result = {}\n for feature in feature_data:\n value_count = record_data[feature].value_counts().sort_values(ascending=False)\n value_angle = (value_count / value_count.sum() * 2 * math.pi).tolist()\n start_angle = np.concatenate(([0.0], np.cumsum(value_angle)))\n end_angle = np.cumsum(value_angle)\n feature_res = {str(val): [start_angle[idx], end_angle[idx]] for (idx, val) in enumerate(value_count.keys())}\n result[feature] = feature_res\n # feature_cid_count = {feature: record_data[feature].value_counts().to_dict() for feature in feature_data}\n return result\n\n def get_similar_insight(self, feature, sid, name, breakdown, breakdown_value):\n insight_data, insight_name, insight_type = self.__get_insight_by_name(name)\n subspace_data, feature_data = self.__get_subspace_by_name(name)\n subspace_data = pd.merge(subspace_data, insight_data, on='sid', how='inner')\n\n subspace = subspace_data.loc[subspace_data['sid'] == sid]\n feature_value = subspace[feature].tolist()[0]\n if feature_value == '*':\n if breakdown == feature:\n feature_value = breakdown_value\n else:\n return {\n 'similar_iid': [],\n 'similar_sid': [],\n 'similar_insight_name': []\n }\n\n if ';' in feature_value:\n feature_value = breakdown_value.split(';')\n else:\n feature_value = [feature_value]\n\n similar_iid = []\n similar_sid = []\n similar_insight_name = []\n for value in feature_value:\n if value == '*':\n continue\n similar_subspace = subspace_data.loc[subspace_data[feature] == value]\n similar_iid.extend(similar_subspace['iid'].tolist())\n similar_sid.extend(similar_subspace['sid'].tolist())\n similar_insight_name.extend(similar_subspace['insight'].tolist())\n\n similar_subspace = subspace_data.loc[subspace_data['breakdown_value'] == value]\n similar_iid.extend(similar_subspace['iid'].tolist())\n similar_sid.extend(similar_subspace['sid'].tolist())\n similar_insight_name.extend(similar_subspace['insight'].tolist())\n\n return {\n 'similar_iid': similar_iid,\n 'similar_sid': similar_sid,\n 'similar_insight_name': similar_insight_name\n }\n" ]
[ [ "numpy.vstack", "numpy.zeros_like", "numpy.cumsum", "scipy.stats.pearsonr", "pandas.read_csv", "sklearn.cluster.DBSCAN", "sklearn.linear_model.LinearRegression", "pandas.to_datetime", "pandas.merge", "sklearn.preprocessing.StandardScaler", "numpy.array" ] ]
tfederico/human_dynamics
[ "ab7ab6aefce5ec33c208091710a37624a1a6ef4a" ]
[ "src/discriminators.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\n\nclass PoseDiscriminator(object):\n def __init__(self, weight_decay):\n self.vars = []\n self.reuse = False\n self.wd = weight_decay\n\n def get_output(self, poses):\n \"\"\"\n Gets discriminator's predictions for each pose and all poses.\n\n Args:\n poses (Nx23x1x9).\n\n Returns:\n Predictions (Nx[23+1]).\n \"\"\"\n data_format = 'NHWC'\n with tf.variable_scope('D_pose', reuse=self.reuse) as scope:\n with slim.arg_scope(\n [slim.conv2d, slim.fully_connected],\n weights_regularizer=slim.l2_regularizer(self.wd)):\n with slim.arg_scope([slim.conv2d], data_format=data_format):\n poses = slim.conv2d(\n inputs=poses,\n num_outputs=32,\n kernel_size=[1, 1],\n reuse=self.reuse,\n scope='D_conv1')\n poses = slim.conv2d(\n inputs=poses,\n num_outputs=32,\n kernel_size=[1, 1],\n reuse=self.reuse,\n scope='D_conv2')\n theta_out = []\n for i in range(0, 23):\n theta_out.append(\n slim.fully_connected(\n inputs=poses[:, i, :, :],\n num_outputs=1,\n activation_fn=None,\n reuse=self.reuse,\n scope='pose_out_j{}'.format(i)))\n theta_out_all = tf.squeeze(tf.stack(theta_out, axis=1))\n\n # Compute joint correlation prior!\n nz_feat = 1024\n poses_all = slim.flatten(poses, scope='vectorize')\n poses_all = slim.fully_connected(\n inputs=poses_all,\n num_outputs=nz_feat,\n reuse=self.reuse,\n scope='D_alljoints_fc1')\n poses_all = slim.fully_connected(\n inputs=poses_all,\n num_outputs=nz_feat,\n reuse=self.reuse,\n scope='D_alljoints_fc2')\n poses_all_out = slim.fully_connected(\n inputs=poses_all,\n num_outputs=1,\n activation_fn=None,\n reuse=self.reuse,\n scope='D_alljoints_out')\n out = tf.concat([theta_out_all, poses_all_out], 1)\n\n if not self.reuse:\n self.update(tf.contrib.framework.get_variables(scope))\n\n return out\n\n def get_vars(self):\n return self.vars\n\n def update(self, vars):\n self.reuse = True\n self.vars.extend(vars)\n" ]
[ [ "tensorflow.stack", "tensorflow.contrib.slim.conv2d", "tensorflow.contrib.slim.fully_connected", "tensorflow.contrib.slim.l2_regularizer", "tensorflow.contrib.slim.flatten", "tensorflow.contrib.framework.get_variables", "tensorflow.variable_scope", "tensorflow.contrib.slim.arg_scope", "tensorflow.concat" ] ]
mohanadhammad/dlnd-sagemaker-deployment
[ "ad1da6fc928e351f6782d1a9c180e0910b67b702" ]
[ "Project/train/train.py" ]
[ "import argparse\nimport json\nimport os\nimport pickle\nimport sys\nimport sagemaker_containers\nimport pandas as pd\nimport torch\nimport torch.optim as optim\nimport torch.utils.data\n\nfrom model import LSTMClassifier\n\ndef model_fn(model_dir):\n \"\"\"Load the PyTorch model from the `model_dir` directory.\"\"\"\n print(\"Loading model.\")\n\n # First, load the parameters used to create the model.\n model_info = {}\n model_info_path = os.path.join(model_dir, 'model_info.pth')\n with open(model_info_path, 'rb') as f:\n model_info = torch.load(f)\n\n print(\"model_info: {}\".format(model_info))\n\n # Determine the device and construct the model.\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = LSTMClassifier(model_info['embedding_dim'], model_info['hidden_dim'], model_info['vocab_size'])\n\n # Load the stored model parameters.\n model_path = os.path.join(model_dir, 'model.pth')\n with open(model_path, 'rb') as f:\n model.load_state_dict(torch.load(f))\n\n # Load the saved word_dict.\n word_dict_path = os.path.join(model_dir, 'word_dict.pkl')\n with open(word_dict_path, 'rb') as f:\n model.word_dict = pickle.load(f)\n\n model.to(device).eval()\n\n print(\"Done loading model.\")\n return model\n\ndef _get_train_data_loader(batch_size, training_dir):\n print(\"Get train data loader.\")\n\n train_data = pd.read_csv(os.path.join(training_dir, \"train.csv\"), header=None, names=None)\n\n train_y = torch.from_numpy(train_data[[0]].values).float().squeeze()\n train_X = torch.from_numpy(train_data.drop([0], axis=1).values).long()\n\n train_ds = torch.utils.data.TensorDataset(train_X, train_y)\n\n return torch.utils.data.DataLoader(train_ds, batch_size=batch_size)\n\n\ndef train(model, train_loader, epochs, optimizer, loss_fn, device):\n \"\"\"\n This is the training method that is called by the PyTorch training script. The parameters\n passed are as follows:\n model - The PyTorch model that we wish to train.\n train_loader - The PyTorch DataLoader that should be used during training.\n epochs - The total number of epochs to train for.\n optimizer - The optimizer to use during training.\n loss_fn - The loss function used for training.\n device - Where the model and data should be loaded (gpu or cpu).\n \"\"\"\n \n for epoch in range(1, epochs + 1):\n model.train()\n total_loss = 0\n for batch in train_loader: \n batch_X, batch_y = batch\n \n batch_X = batch_X.to(device)\n batch_y = batch_y.to(device)\n \n # TODO: Complete this train method to train the model provided.\n optimizer.zero_grad()\n prediction = model(batch_X)\n loss = loss_fn(prediction, batch_y)\n loss.backward()\n optimizer.step()\n \n total_loss += loss.data.item()\n print(\"Epoch: {}, BCELoss: {}\".format(epoch, total_loss / len(train_loader)))\n\n\nif __name__ == '__main__':\n # All of the model parameters and training parameters are sent as arguments when the script\n # is executed. Here we set up an argument parser to easily access the parameters.\n\n parser = argparse.ArgumentParser()\n\n # Training Parameters\n parser.add_argument('--batch-size', type=int, default=512, metavar='N',\n help='input batch size for training (default: 512)')\n parser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n\n # Model Parameters\n parser.add_argument('--embedding_dim', type=int, default=32, metavar='N',\n help='size of the word embeddings (default: 32)')\n parser.add_argument('--hidden_dim', type=int, default=100, metavar='N',\n help='size of the hidden dimension (default: 100)')\n parser.add_argument('--vocab_size', type=int, default=5000, metavar='N',\n help='size of the vocabulary (default: 5000)')\n\n # SageMaker Parameters\n parser.add_argument('--hosts', type=list, default=json.loads(os.environ['SM_HOSTS']))\n parser.add_argument('--current-host', type=str, default=os.environ['SM_CURRENT_HOST'])\n parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])\n parser.add_argument('--data-dir', type=str, default=os.environ['SM_CHANNEL_TRAINING'])\n parser.add_argument('--num-gpus', type=int, default=os.environ['SM_NUM_GPUS'])\n\n args = parser.parse_args()\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(\"Using device {}.\".format(device))\n\n torch.manual_seed(args.seed)\n\n # Load the training data.\n train_loader = _get_train_data_loader(args.batch_size, args.data_dir)\n\n # Build the model.\n model = LSTMClassifier(args.embedding_dim, args.hidden_dim, args.vocab_size).to(device)\n\n with open(os.path.join(args.data_dir, \"word_dict.pkl\"), \"rb\") as f:\n model.word_dict = pickle.load(f)\n\n print(\"Model loaded with embedding_dim {}, hidden_dim {}, vocab_size {}.\".format(\n args.embedding_dim, args.hidden_dim, args.vocab_size\n ))\n\n # Train the model.\n optimizer = optim.Adam(model.parameters())\n loss_fn = torch.nn.BCELoss()\n\n train(model, train_loader, args.epochs, optimizer, loss_fn, device)\n\n # Save the parameters used to construct the model\n model_info_path = os.path.join(args.model_dir, 'model_info.pth')\n with open(model_info_path, 'wb') as f:\n model_info = {\n 'embedding_dim': args.embedding_dim,\n 'hidden_dim': args.hidden_dim,\n 'vocab_size': args.vocab_size,\n }\n torch.save(model_info, f)\n\n\t# Save the word_dict\n word_dict_path = os.path.join(args.model_dir, 'word_dict.pkl')\n with open(word_dict_path, 'wb') as f:\n pickle.dump(model.word_dict, f)\n\n\t# Save the model parameters\n model_path = os.path.join(args.model_dir, 'model.pth')\n with open(model_path, 'wb') as f:\n torch.save(model.cpu().state_dict(), f)\n" ]
[ [ "torch.utils.data.DataLoader", "torch.load", "torch.manual_seed", "torch.save", "torch.cuda.is_available", "torch.from_numpy", "torch.nn.BCELoss", "torch.utils.data.TensorDataset" ] ]
yuhongsun96/PySyft
[ "36f624ec47336d58fb73504c0817aa988a678626" ]
[ "packages/syft/src/syft/core/node/common/client.py" ]
[ "# stdlib\nimport sys\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Iterator\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\n# third party\nfrom google.protobuf.reflection import GeneratedProtocolMessageType\nfrom nacl.signing import SigningKey\nfrom nacl.signing import VerifyKey\nimport pandas as pd\n\n# syft absolute\nimport syft as sy\n\n# relative\nfrom ....logger import critical\nfrom ....logger import debug\nfrom ....logger import error\nfrom ....logger import info\nfrom ....logger import traceback_and_raise\nfrom ....proto.core.node.common.client_pb2 import Client as Client_PB\nfrom ....proto.core.node.common.metadata_pb2 import Metadata as Metadata_PB\nfrom ....util import get_fully_qualified_name\nfrom ...common.message import EventualSyftMessageWithoutReply\nfrom ...common.message import ImmediateSyftMessageWithReply\nfrom ...common.message import ImmediateSyftMessageWithoutReply\nfrom ...common.message import SignedEventualSyftMessageWithoutReply\nfrom ...common.message import SignedImmediateSyftMessageWithReply\nfrom ...common.message import SignedImmediateSyftMessageWithoutReply\nfrom ...common.message import SyftMessage\nfrom ...common.serde.serializable import serializable\nfrom ...common.uid import UID\nfrom ...io.location import Location\nfrom ...io.location import SpecificLocation\nfrom ...io.route import Route\nfrom ...pointer.garbage_collection import GarbageCollection\nfrom ...pointer.garbage_collection import gc_get_default_strategy\nfrom ...pointer.pointer import Pointer\nfrom ..abstract.node import AbstractNodeClient\nfrom .action.exception_action import ExceptionMessage\nfrom .node_service.object_search.obj_search_service import ObjectSearchMessage\n\n\n@serializable()\nclass Client(AbstractNodeClient):\n \"\"\"Client is an incredibly powerful abstraction in Syft. We assume that,\n no matter where a client is, it can figure out how to communicate with\n the Node it is supposed to point to. If I send you a client I have\n with all of the metadata in it, you should have all the information\n you need to know to interact with a node (although you might not\n have permissions - clients should not store private keys).\"\"\"\n\n def __init__(\n self,\n name: Optional[str],\n routes: List[Route],\n network: Optional[Location] = None,\n domain: Optional[Location] = None,\n device: Optional[Location] = None,\n vm: Optional[Location] = None,\n signing_key: Optional[SigningKey] = None,\n verify_key: Optional[VerifyKey] = None,\n ):\n name = f\"{name}\" if name is not None else None\n super().__init__(\n name=name, network=network, domain=domain, device=device, vm=vm\n )\n\n self.routes = routes\n self.default_route_index = 0\n\n gc_strategy_name = gc_get_default_strategy()\n self.gc = GarbageCollection(gc_strategy_name)\n\n # create a signing key if one isn't provided\n if signing_key is None:\n self.signing_key = SigningKey.generate()\n else:\n self.signing_key = signing_key\n\n # if verify key isn't provided, get verify key from signing key\n if verify_key is None:\n self.verify_key = self.signing_key.verify_key\n else:\n self.verify_key = verify_key\n\n self.install_supported_frameworks()\n\n self.store = StoreClient(client=self)\n\n def obj_exists(self, obj_id: UID) -> bool:\n raise NotImplementedError\n\n @property\n def icon(self) -> str:\n icon = \"📡\"\n sub = []\n if self.vm is not None:\n sub.append(\"🍰\")\n if self.device is not None:\n sub.append(\"📱\")\n if self.domain is not None:\n sub.append(\"🏰\")\n if self.network is not None:\n sub.append(\"🔗\")\n\n if len(sub) > 0:\n icon = f\"{icon} [\"\n for s in sub:\n icon += s\n icon += \"]\"\n return icon\n\n @staticmethod\n def deserialize_client_metadata_from_node(\n metadata: Metadata_PB,\n ) -> Tuple[SpecificLocation, str, UID]:\n # string of bytes\n meta = sy.deserialize(blob=metadata)\n return meta.node, meta.name, meta.id\n\n def install_supported_frameworks(self) -> None:\n self.lib_ast = sy.lib.create_lib_ast(client=self)\n\n # first time we want to register for future updates\n self.lib_ast.register_updates(self)\n\n if self.lib_ast is not None:\n for attr_name, attr in self.lib_ast.attrs.items():\n setattr(self, attr_name, attr)\n\n # shortcut syft.lib.python to just python\n if hasattr(self.lib_ast, \"syft\"):\n try:\n lib_attr = getattr(self.lib_ast.syft, \"lib\", None)\n\n if lib_attr is not None:\n python_attr = getattr(lib_attr, \"python\", None)\n setattr(self, \"python\", python_attr)\n python_attr = getattr(lib_attr, \"adp\", None)\n setattr(self, \"adp\", python_attr)\n\n except Exception as e:\n critical(f\"Failed to set python attribute on client. {e}\")\n\n def configure(self, **kwargs: Any) -> Any:\n # relative\n from .node_service.node_setup.node_setup_messages import UpdateSetupMessage\n\n if \"daa_document\" in kwargs.keys():\n kwargs[\"daa_document\"] = open(kwargs[\"daa_document\"], \"rb\").read()\n else:\n kwargs[\"daa_document\"] = b\"\"\n response = self._perform_grid_request( # type: ignore\n grid_msg=UpdateSetupMessage, content=kwargs\n ).content\n info(response)\n\n @property\n def settings(self, **kwargs: Any) -> Dict[Any, Any]: # type: ignore\n # relative\n from .node_service.node_setup.node_setup_messages import GetSetUpMessage\n\n return self._perform_grid_request( # type: ignore\n grid_msg=GetSetUpMessage, content=kwargs\n ).content # type : ignore\n\n def join_network(\n self,\n client: Optional[AbstractNodeClient] = None,\n host_or_ip: Optional[str] = None,\n ) -> None:\n # this asks for a VPN key so it must be on a public interface hence the\n # client or a public host_or_ip\n try:\n if client is None and host_or_ip is None:\n raise ValueError(\n \"join_network requires a Client object or host_or_ip string\"\n )\n if client is not None:\n # connection.host has a http protocol\n connection_host = client.routes[0].connection.host # type: ignore\n parts = connection_host.split(\"://\")\n host_or_ip = parts[1]\n # if we are using localhost to connect we need to change to docker-host\n # so that the domain container can connect to the host not itself\n host_or_ip = str(host_or_ip).replace(\"localhost\", \"docker-host\")\n return self.vpn.join_network(host_or_ip=str(host_or_ip)) # type: ignore\n except Exception as e:\n print(f\"Failed to join network with {host_or_ip}. {e}\")\n\n @property\n def id(self) -> UID:\n \"\"\"This client points to an node, this returns the id of that node.\"\"\"\n traceback_and_raise(NotImplementedError)\n\n # TODO fix the msg type but currently tensor needs SyftMessage\n\n def send_immediate_msg_with_reply(\n self,\n msg: Union[\n SignedImmediateSyftMessageWithReply,\n ImmediateSyftMessageWithReply,\n Any, # TEMPORARY until we switch everything to NodeRunnableMessage types.\n ],\n route_index: int = 0,\n ) -> SyftMessage:\n\n # relative\n from .node_service.simple.simple_messages import NodeRunnableMessageWithReply\n\n # TEMPORARY: if message is instance of NodeRunnableMessageWithReply then we need to wrap it in a SimpleMessage\n if isinstance(msg, NodeRunnableMessageWithReply):\n msg = msg.prepare(address=self.address, reply_to=self.address)\n\n route_index = route_index or self.default_route_index\n\n if isinstance(msg, ImmediateSyftMessageWithReply):\n output = (\n f\"> {self.pprint} Signing {msg.pprint} with \"\n + f\"{self.key_emoji(key=self.signing_key.verify_key)}\"\n )\n debug(output)\n msg = msg.sign(signing_key=self.signing_key)\n\n response = self.routes[route_index].send_immediate_msg_with_reply(msg=msg)\n if response.is_valid:\n # check if we have an ExceptionMessage to trigger a local exception\n # from a remote exception that we caused\n if isinstance(response.message, ExceptionMessage):\n exception_msg = response.message\n exception = exception_msg.exception_type(exception_msg.exception_msg)\n error(str(exception))\n traceback_and_raise(exception)\n else:\n return response.message\n\n traceback_and_raise(\n Exception(\"Response was signed by a fake key or was corrupted in transit.\")\n )\n\n # TODO fix the msg type but currently tensor needs SyftMessage\n\n def send_immediate_msg_without_reply(\n self,\n msg: Union[\n SignedImmediateSyftMessageWithoutReply, ImmediateSyftMessageWithoutReply\n ],\n route_index: int = 0,\n ) -> None:\n route_index = route_index or self.default_route_index\n\n if isinstance(msg, ImmediateSyftMessageWithoutReply):\n output = (\n f\"> {self.pprint} Signing {msg.pprint} with \"\n + f\"{self.key_emoji(key=self.signing_key.verify_key)}\"\n )\n debug(output)\n msg = msg.sign(signing_key=self.signing_key)\n debug(f\"> Sending {msg.pprint} {self.pprint} ➡️ {msg.address.pprint}\")\n self.routes[route_index].send_immediate_msg_without_reply(msg=msg)\n\n def send_eventual_msg_without_reply(\n self, msg: EventualSyftMessageWithoutReply, route_index: int = 0\n ) -> None:\n route_index = route_index or self.default_route_index\n output = (\n f\"> {self.pprint} Signing {msg.pprint} with \"\n + f\"{self.key_emoji(key=self.signing_key.verify_key)}\"\n )\n debug(output)\n signed_msg: SignedEventualSyftMessageWithoutReply = msg.sign(\n signing_key=self.signing_key\n )\n\n self.routes[route_index].send_eventual_msg_without_reply(msg=signed_msg)\n\n def __repr__(self) -> str:\n return f\"<Client pointing to node with id:{self.id}>\"\n\n def register_route(self, route: Route) -> None:\n self.routes.append(route)\n\n def set_default_route(self, route_index: int) -> None:\n self.default_route = route_index\n\n def _object2proto(self) -> Client_PB:\n client_pb = Client_PB(\n obj_type=get_fully_qualified_name(obj=self),\n id=sy.serialize(self.id),\n name=self.name,\n routes=[sy.serialize(route) for route in self.routes],\n network=self.network._object2proto() if self.network else None,\n domain=self.domain._object2proto() if self.domain else None,\n device=self.device._object2proto() if self.device else None,\n vm=self.vm._object2proto() if self.vm else None,\n )\n return client_pb\n\n @staticmethod\n def _proto2object(proto: Client_PB) -> \"Client\":\n module_parts = proto.obj_type.split(\".\")\n klass = module_parts.pop()\n obj_type = getattr(sys.modules[\".\".join(module_parts)], klass)\n\n obj = obj_type(\n name=proto.name,\n routes=[sy.deserialize(route) for route in proto.routes],\n network=sy.deserialize(proto.network)\n if proto.HasField(\"network\")\n else None,\n domain=sy.deserialize(proto.domain) if proto.HasField(\"domain\") else None,\n device=sy.deserialize(proto.device) if proto.HasField(\"device\") else None,\n vm=sy.deserialize(proto.vm) if proto.HasField(\"vm\") else None,\n )\n\n if type(obj) != obj_type:\n traceback_and_raise(\n TypeError(\n f\"Deserializing Client. Expected type {obj_type}. Got {type(obj)}\"\n )\n )\n\n return obj\n\n @staticmethod\n def get_protobuf_schema() -> GeneratedProtocolMessageType:\n return Client_PB\n\n @property\n def keys(self) -> str:\n verify = (\n self.key_emoji(key=self.signing_key.verify_key)\n if self.signing_key is not None\n else \"🚫\"\n )\n keys = f\"🔑 {verify}\"\n\n return keys\n\n def __hash__(self) -> Any:\n return hash(self.id)\n\n\nclass StoreClient:\n def __init__(self, client: Client) -> None:\n self.client = client\n\n @property\n def store(self) -> List[Pointer]:\n msg = ObjectSearchMessage(\n address=self.client.address, reply_to=self.client.address\n )\n\n results = getattr(\n self.client.send_immediate_msg_with_reply(msg=msg), \"results\", None\n )\n if results is None:\n traceback_and_raise(ValueError(\"TODO\"))\n\n # This is because of a current limitation in Pointer where we cannot\n # serialize a client object. TODO: Fix limitation in Pointer so that we don't need this.\n for result in results:\n result.gc_enabled = False\n result.client = self.client\n\n return results\n\n def __len__(self) -> int:\n \"\"\"Return the number of items in the object store we're allowed to know about\"\"\"\n return len(self.store)\n\n def __iter__(self) -> Iterator[Any]:\n return self.store.__iter__()\n\n def __getitem__(self, key: Union[str, int]) -> Pointer:\n if isinstance(key, str):\n matches = 0\n match_obj: Optional[Pointer] = None\n\n for obj in self.store:\n if key in obj.tags:\n matches += 1\n match_obj = obj\n if matches == 1 and match_obj is not None:\n return match_obj\n elif matches > 1:\n traceback_and_raise(KeyError(\"More than one item with tag:\" + str(key)))\n else:\n # If key does not math with any tags, we then try to match it with id string.\n # But we only do this if len(key)>=5, because if key is too short, for example\n # if key=\"a\", there are chances of mismatch it with id string, and I don't\n # think the user pass a key such short as part of id string.\n if len(key) >= 5:\n for obj in self.store:\n if key in str(obj.id_at_location.value).replace(\"-\", \"\"):\n return obj\n else:\n traceback_and_raise(\n KeyError(\n f\"No such item found for tag: {key}, and we \"\n + \"don't consider it as part of id string because its too short.\"\n )\n )\n\n traceback_and_raise(KeyError(\"No such item found for id:\" + str(key)))\n if isinstance(key, int):\n return self.store[key]\n else:\n traceback_and_raise(KeyError(\"Please pass in a string or int key\"))\n\n def __repr__(self) -> str:\n return repr(self.store)\n\n @property\n def pandas(self) -> pd.DataFrame:\n obj_lines: List[Dict[str, Any]] = list()\n for obj in self.store:\n obj_lines.append(\n {\n \"ID\": obj.id_at_location,\n \"Tags\": obj.tags,\n \"Description\": obj.description,\n \"object_type\": obj.object_type,\n }\n )\n return pd.DataFrame(obj_lines)\n\n def _repr_html_(self) -> str:\n return self.pandas._repr_html_()\n" ]
[ [ "pandas.DataFrame" ] ]
ibivu/protein-glue
[ "47f68b4789c6750dfb9bf6d6ae382a9061514bfd" ]
[ "dataset/ss3.py" ]
[ "from numpy import float32\nimport tensorflow as tf\nimport constants as c\n\ndef _parse_example(example_proto):\n features = {\n \"sequence\": tf.io.FixedLenFeature((), tf.string, default_value=\"\"),\n \"ss3\": tf.io.VarLenFeature(tf.int64),\n \"ss8\": tf.io.VarLenFeature(tf.int64)\n }\n parsed_features = tf.io.parse_single_example(example_proto, features)\n\n input_seq = tf.io.decode_raw(parsed_features[\"sequence\"], tf.dtypes.uint8)\n # We get raw ASCII bytes from the tensorflow file format, shift their values so 'A' maps to index 3,\n # because we reserve 0 for padding / masked values, 1 for the start of sequence marker, and 2 for\n # the end of sequence marker\n input_seq = input_seq - 65 + c.NUM_SPECIAL_SYMBOLS\n input_seq = tf.cast(input_seq, tf.int32)\n\n segment_label = tf.ones_like(input_seq, dtype=tf.float32)\n\n target_seq = tf.sparse.to_dense(parsed_features['ss3'],\n default_value=0)\n target_seq = target_seq + 1\n target_seq = tf.cast(target_seq, tf.int32)\n\n return (input_seq, target_seq, segment_label)\n\ndef create_dataset_ss3(filenames, batch_size=16, max_length=128):\n dataset = tf.data.TFRecordDataset(filenames)\n dataset = dataset.map(_parse_example)\n if max_length:\n dataset = dataset.filter(lambda x, y, z: tf.shape(x)[0] <= max_length)\n dataset = dataset.padded_batch(batch_size, padded_shapes=([None], [None], [None])).prefetch(tf.data.experimental.AUTOTUNE)\n\n return dataset\n" ]
[ [ "tensorflow.data.TFRecordDataset", "tensorflow.io.parse_single_example", "tensorflow.sparse.to_dense", "tensorflow.shape", "tensorflow.ones_like", "tensorflow.io.decode_raw", "tensorflow.cast", "tensorflow.io.FixedLenFeature", "tensorflow.io.VarLenFeature" ] ]
gabrieldemarmiesse/tracks_separation
[ "81b0b1cb0bce269a76403ad5e16c3e0469160f40" ]
[ "converter.py" ]
[ "from glob import glob\nfrom tqdm import tqdm as tq\nfrom scipy.io.wavfile import read, write\nfrom resampy import resample\nnew_rate = 16000\npath = \"./data/DSD100_16kHz/Sources/*/*/*.wav\"\n\nfor file in tq(glob(path)):\n rate, array = read(file)\n new_array = resample(array,rate, new_rate, axis=0)\n write(file, new_rate, new_array)\n" ]
[ [ "scipy.io.wavfile.write", "scipy.io.wavfile.read" ] ]
Yu-AnChen/tabbi
[ "bf4655905d0f3fc5b7dd49a1cd12c69cb83e5bb5" ]
[ "tabbi/gmm.py" ]
[ "import sklearn.mixture\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib import ticker\r\nimport matplotlib.patheffects as mpatheffects\r\n\r\n\r\ndef get_gmm_and_pos_label(\r\n array, n_components=2, n_steps=5000\r\n):\r\n gmm = sklearn.mixture.GaussianMixture(\r\n n_components=n_components, covariance_type='spherical', random_state=0\r\n )\r\n gmm.fit(array.reshape(-1, 1))\r\n label = np.argmax(gmm.means_)\r\n\r\n # low = array.min()\r\n # high = array.max()\r\n\r\n low = gmm.means_.min() - 2*np.sqrt(gmm.covariances_[np.argmin(gmm.means_)])\r\n high = gmm.means_.max() + 2*np.sqrt(gmm.covariances_[np.argmax(gmm.means_)])\r\n\r\n ref_space = np.linspace(low, high, n_steps)\r\n result = gmm.predict(ref_space.reshape(-1, 1))\r\n\r\n idx = np.where(np.ediff1d(result) != 0)\r\n cutoffs = ref_space[idx]\r\n\r\n return gmm, label, cutoffs\r\n\r\n\r\ndef _get_gmm_and_pos_label(array, n_components=2):\r\n gmm = sklearn.mixture.GaussianMixture(\r\n n_components=n_components, covariance_type='spherical', random_state=0\r\n )\r\n gmm.fit(array.reshape(-1, 1))\r\n label = np.argmax(gmm.means_)\r\n\r\n low = np.expm1(array.min())\r\n high = np.expm1(array.max())\r\n ref_space = np.arange(low, high)\r\n ref_space = np.log1p(ref_space)\r\n result = gmm.predict(ref_space.reshape(-1, 1))\r\n\r\n idx = np.where(np.ediff1d(result) != 0)\r\n _cutoffs = ref_space[idx]\r\n\r\n diff_mean = np.absolute(_cutoffs - np.mean(array))\r\n diff_high = np.absolute(_cutoffs - np.log1p(high))\r\n\r\n cutoffs = _cutoffs[diff_mean < diff_high]\r\n cutoff = np.expm1(cutoffs.max())\r\n\r\n # cutoff = cutoffs[np.argmin(diff_mean < diff_high)]\r\n # return gmm, label, cutoff\r\n return gmm, label, _cutoffs\r\n\r\n diff_mean = np.absolute(_cutoffs - np.mean(np.expm1(array)))\r\n diff_high = np.absolute(_cutoffs - high)\r\n diff_low = np.absolute(_cutoffs - low)\r\n\r\n between = (diff_mean < diff_high) & (diff_mean < diff_low)\r\n cutoffs = _cutoffs[between]\r\n\r\n cutoff = cutoffs[np.argmax(between)]\r\n return gmm, label, cutoff\r\n\r\n\r\ndef plot_gmm_fitting(array, gmm, ax):\r\n plt.sca(ax)\r\n _ = plt.hist(array.flatten(), color='lightgray', bins=200, density=True)\r\n x = np.linspace(array.min(), array.max(), 200)\r\n\r\n log_prob = gmm.score_samples(x.reshape(-1, 1))\r\n responsibilities = gmm.predict_proba(x.reshape(-1, 1))\r\n pdf = np.exp(log_prob)\r\n pdf_individual = responsibilities * pdf[:, np.newaxis]\r\n\r\n mean_index = np.argmax(pdf_individual, axis=0)\r\n rank_map = mean_index.argsort().argsort()\r\n\r\n ax.set_prop_cycle(\r\n color=plt.get_cmap('Dark2')(rank_map)\r\n )\r\n ax.plot(x, pdf_individual)\r\n ax.plot(x, pdf, '--k')\r\n return ax\r\n\r\n\r\ndef auto_gate_func(array, n_components=3, n_stds=3, log_transform=True):\r\n gmm = sklearn.mixture.GaussianMixture(\r\n n_components=n_components, covariance_type='spherical', random_state=0\r\n )\r\n if log_transform:\r\n gmm.fit(np.log1p(array).reshape(-1, 1))\r\n else:\r\n gmm.fit(array.reshape(-1, 1))\r\n means = gmm.means_\r\n stds = np.sqrt(gmm.covariances_)\r\n idx = np.argmax(means)\r\n lower_bound = means[idx] - n_stds * stds[idx]\r\n if log_transform:\r\n return np.expm1(lower_bound)\r\n else:\r\n return lower_bound\r\n\r\n\r\ndef plot_cumulative(array, ax, hist_kwargs={}):\r\n formatter = ticker.ScalarFormatter(useMathText=True)\r\n formatter.set_scientific(True) \r\n formatter.set_powerlimits((-1,1))\r\n ax.yaxis.set_major_formatter(formatter) \r\n _ = ax.hist(array, histtype='step', bins=300, cumulative=1, **hist_kwargs)\r\n \r\n return ax\r\n\r\n\r\ndef gmm_label_map_by_mean(gmm):\r\n return {\r\n o:n \r\n for o, n in zip(\r\n range(len(gmm.means_)),\r\n sorted(range(len(gmm.means_)), key=lambda x: gmm.means_[x][0])\r\n )\r\n }\r\n\r\n\r\ndef sort_predict_label(gmm, labels):\r\n mapping = gmm_label_map_by_mean(gmm)\r\n sorted_labels = labels.copy()\r\n for k, v in mapping.iteritems():\r\n sorted_labels[labels==k] = v\r\n return sorted_labels\r\n\r\n\r\ndef plot_hist_gmm(\r\n df,\r\n markers,\r\n n_components=2,\r\n subplot_grid_shape=None,\r\n transform_log=True,\r\n xlim_percentiles=(0, 100),\r\n cum_density=False,\r\n hide_yaxis_left=True\r\n): \r\n if transform_log:\r\n df = df.transform(np.log1p)\r\n revert_func = np.expm1\r\n else:\r\n revert_func = np.array\r\n if subplot_grid_shape is None:\r\n subplot_grid_shape = (1, len(markers))\r\n n_rows, n_cols = subplot_grid_shape\r\n fig, axes = plt.subplots(n_rows, n_cols, sharex=True)\r\n axes = np.array(axes)\r\n\r\n for m, ax in zip(markers, axes.ravel()):\r\n gmm, _, cutoffs = get_gmm_and_pos_label(\r\n df[m].values, n_components=n_components\r\n )\r\n plot_gmm_fitting(df[m].values, gmm, ax)\r\n ax.title.set_text(m)\r\n if hide_yaxis_left:\r\n ax.yaxis.set_visible(False)\r\n\r\n p1, p2 = np.array(xlim_percentiles) / 100\r\n axis_min = df.loc[:, markers].quantile(p1).min()\r\n axis_max = df.loc[:, markers].quantile(p2).max()\r\n\r\n color_cum = 'gray'\r\n\r\n pax = ax.twinx()\r\n pax = plot_cumulative(\r\n df[m].values, pax, \r\n hist_kwargs=dict(color=color_cum, density=cum_density)\r\n )\r\n pax.tick_params(axis='y', labelsize=8, colors=color_cum)\r\n\r\n print(cutoffs)\r\n\r\n cutoff_range = np.ptp(cutoffs)\r\n if cutoff_range == 0: cutoff_range = 1\r\n cutoff_colors = plt.get_cmap('plasma')(\r\n (cutoffs - np.min(cutoffs)) / cutoff_range\r\n )\r\n\r\n for co, cc in zip(cutoffs, cutoff_colors):\r\n ax.axvline(x=co, c=cc, alpha=0.2)\r\n ax.annotate(\r\n '',\r\n xy=(co, 0), xytext=(co, -0.05),\r\n xycoords=('data', 'axes fraction'),\r\n arrowprops=dict(arrowstyle='wedge, tail_width=0.7, shrink_factor=0.5', color=cc)\r\n )\r\n ax.set_xlim(axis_min, axis_max)\r\n # cutoff_string = np.round(revert_func(cutoffs)).astype(int)\r\n\r\n for i, (co, cc) in enumerate(\r\n zip(revert_func(cutoffs)[::-1], cutoff_colors[::-1])\r\n ):\r\n text = ax.text(\r\n ax.get_xlim()[0] + 0.02*np.diff(ax.get_xlim()), \r\n ax.get_ylim()[1] - 0.05*(i+1)*np.diff(ax.get_ylim()), \r\n f'{np.round(co).astype(int)}', \r\n fontsize=10, c=cc\r\n )\r\n text_outline = mpatheffects.Stroke(linewidth=1, foreground='#000')\r\n text.set_path_effects(\r\n [text_outline, mpatheffects.Normal()]\r\n )\r\n plt.tight_layout()\r\n for aax in fig.axes:\r\n aax.spines['right'].set_color(color_cum)\r\n power_label = aax.yaxis.get_offset_text()\r\n power_label.set_visible(False)\r\n aax.annotate(\r\n power_label.get_text(), xy=(1.02, 1.01),\r\n xycoords='axes fraction', fontsize=10,\r\n color=color_cum\r\n )\r\n plt.sca(ax)\r\n" ]
[ [ "matplotlib.pyplot.tight_layout", "numpy.log1p", "numpy.ediff1d", "numpy.argmin", "matplotlib.pyplot.get_cmap", "numpy.absolute", "numpy.expm1", "numpy.linspace", "numpy.round", "numpy.mean", "numpy.sqrt", "matplotlib.ticker.ScalarFormatter", "numpy.argmax", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.patheffects.Stroke", "numpy.min", "matplotlib.patheffects.Normal", "numpy.ptp", "numpy.exp", "matplotlib.pyplot.sca", "numpy.array" ] ]
Dtananaev/tf_lstm_depth
[ "94f83e8671e8928eba24eac6936a02cd9d123686" ]
[ "layers/conv.py" ]
[ "#\n# Author: Denis Tananaev\n# File: conv.py\n# Date: 9.02.2017\n# Description: convolution functions for neural networks\n#\n\n#include libs\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n#import os\nfrom six.moves import xrange\n#import os\n#import re\n#import sys\n#import tarfile\n#import math \nimport tensorflow as tf\nimport layers.summary as sm\n\ndef _variable_on_cpu(name, shape, initializer, FLOAT16=False):\n \"\"\"Helper to create a Variable stored on CPU memory.\n\n Args:\n name: name of the variable\n shape: list of ints\n initializer: initializer for Variable\n\n Returns:\n Variable Tensor\n \"\"\"\n with tf.device('/cpu:0'):\n if(FLOAT16==True):\n dtype = tf.float16 \n else:\n dtype = tf.float32\n var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype)\n return var\n\n\ndef _variable_with_weight_decay(name, shape, stddev, wd,FLOAT16=False):\n \"\"\"Helper to create an initialized Variable with weight decay.\n \n Note that the Variable is initialized with a truncated normal distribution.\n A weight decay is added only if one is specified.\n\n Args:\n name: name of the variable\n shape: list of ints\n stddev: standard deviation of a truncated Gaussian\n wd: add L2Loss weight decay multiplied by this float. If None, weight\n decay is not added for this Variable.\n\n Returns:\n Variable Tensor\n \"\"\"\n if(FLOAT16==True):\n dtype = tf.float16 \n else:\n dtype = tf.float32\n var = _variable_on_cpu(\n name,\n shape,\n tf.truncated_normal_initializer(stddev=stddev, dtype=dtype))\n if wd is not None:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\ndef _const_variable_with_weight_decay(name, shape, stddev, wd,FLOAT16=False):\n if(FLOAT16==True):\n dtype = tf.float16 \n else:\n dtype = tf.float32\n var = _variable_on_cpu(\n name,\n shape,\n tf.constant_initializer(1.0))\n if wd is not None:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\ndef conv(data,scope,shape,stride=[1, 1, 1, 1],padding='SAME',wd=0.0,FLOAT16=False,reuse=None):\n with tf.variable_scope(scope, 'Conv', [data], reuse=reuse):\n STDdev=1/tf.sqrt(shape[0]*shape[1]*shape[2]/2) #Xavier/2 initialization \n kernel = _variable_with_weight_decay('weights',\n shape=shape,\n stddev=STDdev,\n wd=wd,FLOAT16=FLOAT16)\n conv = tf.nn.conv2d(data, kernel, stride, padding=padding)\n biases = _variable_on_cpu('biases', [shape[3]], tf.constant_initializer(0.0001))#positive biases\n pre_activation = tf.nn.bias_add(conv, biases)\n sm._activation_summary(pre_activation)\n return pre_activation \n\ndef dilated_conv(data,scope,shape,rate=1,padding='SAME',wd=0.0,FLOAT16=False,reuse=None):\n with tf.variable_scope(scope, 'Dilated_Conv', [data], reuse=reuse):\n STDdev=1/tf.sqrt(shape[0]*shape[1]*shape[2]/2) #Xavier/2 initialization \n kernel = _variable_with_weight_decay('weights',\n shape=shape,\n stddev=STDdev,\n wd=wd,FLOAT16=FLOAT16)\n conv = tf.nn.atrous_conv2d(data, kernel, rate, padding=padding)\n biases = _variable_on_cpu('biases', [shape[3]], tf.constant_initializer(0.0001))#positive biases\n pre_activation = tf.nn.bias_add(conv, biases)\n sm._activation_summary(pre_activation)\n return pre_activation \n\ndef fclayer(data,batch_size,hidden,scope,wd=0.0,FLOAT16=False,reuse=None):\n with tf.variable_scope(scope, 'fc',[data],reuse=reuse):\n # Move everything into depth so we can perform a single matrix multiply.\n reshape = tf.reshape(data, [batch_size,-1])\n dim = reshape.get_shape()[1].value\n weights = _variable_with_weight_decay('weights', shape=[dim, hidden],\n stddev=0.04, wd=wd,FLOAT16=FLOAT16)\n biases = _variable_on_cpu('biases', [hidden], tf.constant_initializer(0.00001))\n pre_activation = tf.matmul(reshape, weights) + biases\n sm._activation_summary(pre_activation)\n return pre_activation \n\n\n\n\n\n\n" ]
[ [ "tensorflow.constant_initializer", "tensorflow.add_to_collection", "tensorflow.truncated_normal_initializer", "tensorflow.nn.bias_add", "tensorflow.nn.atrous_conv2d", "tensorflow.device", "tensorflow.reshape", "tensorflow.sqrt", "tensorflow.variable_scope", "tensorflow.nn.l2_loss", "tensorflow.nn.conv2d", "tensorflow.matmul", "tensorflow.get_variable" ] ]
ravi-0841/spect-pitch-gan
[ "ea4b9ea8396df753e25e0b2cb210288f683d3903" ]
[ "utils/convert.py" ]
[ "import argparse\nimport os\nimport numpy as np\nimport librosa\nimport scipy.io.wavfile as scwav\nimport scipy.signal as scisig\nimport pylab\nimport numpy.matlib as npmat\n\nimport utils.preprocess as preproc\nfrom utils.helper import smooth, generate_interpolation\n#from nn_models.model_embedding_wasserstein import VariationalCycleGAN as VCGAN_embedding\nfrom nn_models.model_pitch_mfc_discriminate_wasserstein import VariationalCycleGAN as VCGAN_embedding\nfrom nn_models.model_separate_discriminate_id import VariationalCycleGAN as VCGAN\nfrom encoder_decoder import AE\n#from model_pair_lvi import CycleGAN as CycleGAN_f0s\n\n\nnum_mfcc = 23\nnum_pitch = 1\nsampling_rate = 16000\nframe_period = 5.0\n\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\n\ndef conversion(model_dir=None, model_name=None, audio_file=None, \n data_dir=None, conversion_direction=None, \n output_dir=None, embedding=True, only_energy=False):\n \n if embedding:\n ae_model = AE(dim_mfc=num_mfcc)\n ae_model.load(filename='./model/AE_cmu_pre_trained_noise_std_1.ckpt')\n model = VCGAN_embedding(dim_mfc=1, dim_pitch=1, mode='test')\n model.load(filepath=os.path.join(model_dir, model_name))\n else:\n model = VCGAN(dim_mfc=23, dim_pitch=1, mode='test')\n model.load(filepath=os.path.join(model_dir, model_name))\n \n if audio_file is not None:\n wav, sr = librosa.load(audio_file, sr=sampling_rate, mono=True)\n assert (sr==sampling_rate)\n wav = preproc.wav_padding(wav=wav, sr=sampling_rate, \\\n frame_period=frame_period, multiple=4)\n f0, sp, ap = preproc.world_decompose(wav=wav, \\\n fs=sampling_rate, frame_period=frame_period)\n coded_sp = preproc.world_encode_spectral_envelope(sp=sp, \\\n fs=sampling_rate, dim=num_mfcc)\n \n coded_sp = np.expand_dims(coded_sp, axis=0)\n coded_sp = np.transpose(coded_sp, (0,2,1))\n \n if embedding:\n sp_embedding = ae_model.get_embedding(mfc_features=coded_sp)\n coded_sp = sp_embedding\n \n f0 = scisig.medfilt(f0, kernel_size=3)\n z_idx = np.where(f0<10.0)[0]\n f0 = generate_interpolation(f0)\n f0 = smooth(f0, window_len=13)\n f0 = np.reshape(f0, (1,1,-1))\n\n f0_converted, coded_sp_converted = model.test(input_pitch=f0, \n input_mfc=coded_sp, \n direction=conversion_direction)\n \n\n if embedding:\n coded_sp_converted = ae_model.get_mfcc(embeddings=coded_sp_converted)\n\n coded_sp_converted = np.asarray(np.transpose(coded_sp_converted[0]), np.float64)\n coded_sp_converted = np.ascontiguousarray(coded_sp_converted)\n f0_converted = np.asarray(np.reshape(f0_converted[0], (-1,)), np.float64)\n f0_converted = np.ascontiguousarray(f0_converted)\n f0_converted[z_idx] = 0\n \n decoded_sp_converted = preproc.world_decode_spectral_envelope(coded_sp=coded_sp_converted, \n fs=sampling_rate)\n # Normalization of converted features\n decoded_sp_converted = decoded_sp_converted / np.max(decoded_sp_converted)\n wav_transformed = preproc.world_speech_synthesis(f0=f0_converted, \n decoded_sp=decoded_sp_converted, \n ap=ap, fs=sampling_rate, \n frame_period=frame_period)\n scwav.write(os.path.join('/home/ravi/Desktop', \n os.path.basename(audio_file)), \n sampling_rate, wav_transformed)\n print('Processed: ' + audio_file)\n \n else:\n os.makedirs(output_dir, exist_ok=True)\n \n for file in os.listdir(data_dir):\n \n filepath = os.path.join(data_dir, file)\n \n wav, sr = librosa.load(filepath, sr=sampling_rate, mono=True)\n wav = (wav - np.min(wav)) / (np.max(wav) - np.min(wav))\n \n assert (sr==sampling_rate)\n wav = preproc.wav_padding(wav=wav, sr=sampling_rate, \\\n frame_period=frame_period, multiple=4)\n f0, sp, ap = preproc.world_decompose(wav=wav, \\\n fs=sampling_rate, frame_period=frame_period)\n coded_sp = preproc.world_encode_spectral_envelope(sp=sp, \\\n fs=sampling_rate, dim=num_mfcc)\n \n coded_sp = np.expand_dims(coded_sp, axis=0)\n coded_sp = np.transpose(coded_sp, (0,2,1))\n \n if embedding:\n sp_embedding = ae_model.get_embedding(mfc_features=coded_sp)\n else:\n sp_embedding = coded_sp\n \n f0 = scisig.medfilt(f0, kernel_size=3)\n z_idx = np.where(f0<10.0)[0]\n f0 = generate_interpolation(f0)\n f0 = smooth(f0, window_len=13)\n f0 = np.reshape(f0, (1,1,-1))\n \n f0_converted, coded_sp_converted = model.test(input_pitch=f0, \n input_mfc=sp_embedding, \n direction=conversion_direction)\n \n# f0_converted = cgan_f0.test(input_pitch=f0, input_mfc=coded_sp, \n# direction='A2B')\n \n if embedding:\n coded_sp_converted = ae_model.get_mfcc(embeddings=coded_sp_converted)\n\n coded_sp_converted = np.asarray(np.transpose(np.squeeze(coded_sp_converted)), np.float64)\n coded_sp_converted = np.ascontiguousarray(coded_sp_converted)\n f0_converted = np.asarray(np.reshape(f0_converted[0], (-1,)), np.float64)\n f0_converted = np.ascontiguousarray(f0_converted)\n f0_converted[z_idx] = 0\n \n # Mixing the mfcc features\n print(np.min(coded_sp_converted), np.min(coded_sp))\n \n if embedding and not only_energy:\n coded_sp_converted = 0.6*coded_sp_converted + 0.4*np.transpose(np.squeeze(coded_sp))\n elif embedding and only_energy:\n energy_contour_converted = np.sum(coded_sp_converted**2, axis=1, keepdims=True)\n energy_contour = np.sum(np.squeeze(coded_sp).T**2, axis=1, keepdims=True)\n factor = (energy_contour_converted / energy_contour)**(0.5)\n coded_sp_converted = np.squeeze(coded_sp).T * (npmat.repmat(factor, 1,coded_sp.shape[1]))\n \n # Pyworld decoding\n decoded_sp_converted = preproc.world_decode_spectral_envelope(coded_sp=coded_sp_converted, \n fs=sampling_rate)\n \n # Normalization of converted features\n# decoded_sp_converted = decoded_sp_converted / np.max(decoded_sp_converted)\n wav_transformed = preproc.world_speech_synthesis(f0=f0_converted, \n decoded_sp=decoded_sp_converted, \n ap=ap, fs=sampling_rate, \n frame_period=frame_period)\n \n wav_transformed = (wav_transformed - np.min(wav_transformed)) \\\n / (np.max(wav_transformed) - np.min(wav_transformed))\n wav_transformed = wav_transformed - np.mean(wav_transformed)\n \n scwav.write(os.path.join(output_dir, os.path.basename(file)), \n 16000, wav_transformed)\n print('Processed: ' + file)\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description = 'Convert Emotion using pre-trained VariationalCycleGAN model.')\n\n model_dir_default = './model/neu-ang/lp_1e-05_lm_0.1_lmo_1e-06_lrg_2e-06_lrd_1e-07_li_0.05_pre_trained_pitch_mfc_discriminate_wasserstein_all_spk'\n model_name_default = 'neu-ang_450.ckpt'\n data_dir_default = 'data/evaluation/neu-ang/test/neutral'\n conversion_direction_default = 'A2B'\n output_dir_default = '/home/ravi/Desktop/AE_wasserstein_energy'\n audio_file_default = None\n\n parser.add_argument('--model_dir', type = str, help='Directory for the pre-trained model.', default=model_dir_default)\n parser.add_argument('--model_name', type = str, help='Filename for the pre-trained model.', default=model_name_default)\n parser.add_argument('--data_dir', type=str, help='Directory for the voices for conversion.', default=data_dir_default)\n parser.add_argument('--conversion_direction', type=str, help='Conversion direction for VCGAN, A2B or B2A', default=conversion_direction_default)\n parser.add_argument('--output_dir', type=str, help='Directory for the converted voices.', default=output_dir_default)\n parser.add_argument('--audio_file', type=str, help='convert a single audio file', default=audio_file_default)\n\n argv = parser.parse_args()\n\n model_dir = argv.model_dir\n model_name = argv.model_name\n data_dir = argv.data_dir\n conversion_direction = argv.conversion_direction\n output_dir = argv.output_dir\n audio_file = argv.audio_file\n \n conversion(model_dir=model_dir, model_name=model_name, audio_file=audio_file, \n data_dir=data_dir, conversion_direction=conversion_direction, \n output_dir=output_dir, embedding=True, only_energy=True)\n\n\n" ]
[ [ "numpy.sum", "numpy.transpose", "scipy.signal.medfilt", "numpy.squeeze", "numpy.reshape", "numpy.matlib.repmat", "numpy.where", "numpy.expand_dims", "numpy.max", "numpy.min", "numpy.ascontiguousarray", "numpy.mean" ] ]
fabibo3/pytorch3d
[ "36b7656753ae759aed2eb7ffb432b6eca4d42fe2" ]
[ "pytorch3d/io/experimental_gltf_io.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n\"\"\"\nThis module implements loading meshes from glTF 2 assets stored in a\nGLB container file or a glTF JSON file with embedded binary data.\nIt is experimental.\n\nThe module provides a MeshFormatInterpreter called\nMeshGlbFormat which must be used explicitly.\ne.g.\n\n.. code-block:: python\n\n from pytorch3d.io import IO\n from pytorch3d.io.experimental_gltf_io import MeshGlbFormat\n\n io = IO()\n io.register_meshes_format(MeshGlbFormat())\n io.load_mesh(...)\n\nThis implementation is quite restricted in what it supports.\n\n - It does not try to validate the input against the standard.\n - It loads the default scene only.\n - Only triangulated geometry is supported.\n - The geometry of all meshes of the entire scene is aggregated into a single mesh.\n Use `load_meshes()` instead to get un-aggregated (but transformed) ones.\n - All material properties are ignored except for either vertex color, baseColorTexture\n or baseColorFactor. If available, one of these (in this order) is exclusively\n used which does not match the semantics of the standard.\n\"\"\"\n\nimport json\nimport struct\nimport warnings\nfrom base64 import b64decode\nfrom collections import deque\nfrom enum import IntEnum\nfrom io import BytesIO\nfrom typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union, cast\n\nimport numpy as np\nimport torch\nfrom iopath.common.file_io import PathManager\nfrom PIL import Image\nfrom pytorch3d.io.utils import PathOrStr, _open_file\nfrom pytorch3d.renderer.mesh import TexturesBase, TexturesUV, TexturesVertex\nfrom pytorch3d.structures import Meshes, join_meshes_as_scene\nfrom pytorch3d.transforms import Transform3d, quaternion_to_matrix\n\nfrom .pluggable_formats import MeshFormatInterpreter, endswith\n\n\n_GLTF_MAGIC = 0x46546C67\n_JSON_CHUNK_TYPE = 0x4E4F534A\n_BINARY_CHUNK_TYPE = 0x004E4942\n_DATA_URI_PREFIX = \"data:application/octet-stream;base64,\"\n\n\nclass _PrimitiveMode(IntEnum):\n POINTS = 0\n LINES = 1\n LINE_LOOP = 2\n LINE_STRIP = 3\n TRIANGLES = 4\n TRIANGLE_STRIP = 5\n TRIANGLE_FAN = 6\n\n\nclass _ComponentType(IntEnum):\n BYTE = 5120\n UNSIGNED_BYTE = 5121\n SHORT = 5122\n UNSIGNED_SHORT = 5123\n UNSIGNED_INT = 5125\n FLOAT = 5126\n\n\n_ITEM_TYPES: Dict[int, Any] = {\n 5120: np.int8,\n 5121: np.uint8,\n 5122: np.int16,\n 5123: np.uint16,\n 5125: np.uint32,\n 5126: np.float32,\n}\n\n\n_ElementShape = Union[Tuple[int], Tuple[int, int]]\n_ELEMENT_SHAPES: Dict[str, _ElementShape] = {\n \"SCALAR\": (1,),\n \"VEC2\": (2,),\n \"VEC3\": (3,),\n \"VEC4\": (4,),\n \"MAT2\": (2, 2),\n \"MAT3\": (3, 3),\n \"MAT4\": (4, 4),\n}\n\n\ndef _read_header(stream: BinaryIO) -> Optional[Tuple[int, int]]:\n header = stream.read(12)\n magic, version, length = struct.unpack(\"<III\", header)\n\n if magic != _GLTF_MAGIC:\n return None\n\n return version, length\n\n\ndef _read_chunks(\n stream: BinaryIO, length: int\n) -> Optional[Tuple[Dict[str, Any], np.ndarray]]:\n \"\"\"\n Get the json header and the binary data from a\n GLB file.\n \"\"\"\n json_data = None\n binary_data = None\n\n while stream.tell() < length:\n chunk_header = stream.read(8)\n chunk_length, chunk_type = struct.unpack(\"<II\", chunk_header)\n chunk_data = stream.read(chunk_length)\n if chunk_type == _JSON_CHUNK_TYPE:\n json_data = json.loads(chunk_data)\n elif chunk_type == _BINARY_CHUNK_TYPE:\n binary_data = chunk_data\n else:\n warnings.warn(\"Unsupported chunk type\")\n return None\n\n if json_data is None:\n raise ValueError(\"Missing json header\")\n\n if binary_data is not None:\n binary_data = np.frombuffer(binary_data, dtype=np.uint8)\n\n return json_data, binary_data\n\n\ndef _make_node_transform(node: Dict[str, Any]) -> Transform3d:\n \"\"\"\n Convert a transform from the json data in to a PyTorch3D\n Transform3d format.\n \"\"\"\n array = node.get(\"matrix\")\n if array is not None: # Stored in column-major order\n M = np.array(array, dtype=np.float32).reshape(4, 4, order=\"F\")\n return Transform3d(matrix=torch.from_numpy(M))\n\n out = Transform3d()\n\n # Given some of (scale/rotation/translation), we do them in that order to\n # get points in to the world space.\n # See https://github.com/KhronosGroup/glTF/issues/743 .\n\n array = node.get(\"scale\", None)\n if array is not None:\n scale_vector = torch.FloatTensor(array)\n out = out.scale(scale_vector[None])\n\n # Rotation quaternion (x, y, z, w) where w is the scalar\n array = node.get(\"rotation\", None)\n if array is not None:\n x, y, z, w = array\n # We negate w. This is equivalent to inverting the rotation.\n # This is needed as quaternion_to_matrix makes a matrix which\n # operates on column vectors, whereas Transform3d wants a\n # matrix which operates on row vectors.\n rotation_quaternion = torch.FloatTensor([-w, x, y, z])\n rotation_matrix = quaternion_to_matrix(rotation_quaternion)\n out = out.rotate(R=rotation_matrix)\n\n array = node.get(\"translation\", None)\n if array is not None:\n translation_vector = torch.FloatTensor(array)\n out = out.translate(x=translation_vector[None])\n\n return out\n\n\nclass _GLTFLoader:\n def __init__(self, stream: BinaryIO) -> None:\n self._json_data = None\n # Map from buffer index to (decoded) binary data\n self._binary_data = {}\n\n version_and_length = _read_header(stream)\n if version_and_length is None: # GLTF\n stream.seek(0)\n json_data = json.load(stream)\n else: # GLB\n version, length = version_and_length\n if version != 2:\n warnings.warn(\"Unsupported version\")\n return\n json_and_binary_data = _read_chunks(stream, length)\n if json_and_binary_data is None:\n raise ValueError(\"Data not found\")\n json_data, binary_data = json_and_binary_data\n self._binary_data[0] = binary_data\n\n self._json_data = json_data\n self._accessors = json_data.get(\"accessors\", [])\n self._buffer_views = json_data.get(\"bufferViews\", [])\n self._buffers = json_data.get(\"buffers\", [])\n self._texture_map_images = {}\n\n def _access_image(self, image_index: int) -> np.ndarray:\n \"\"\"\n Get the data for an image from the file. This is only called\n by _get_texture_map_image which caches it.\n \"\"\"\n\n image_json = self._json_data[\"images\"][image_index]\n buffer_view = self._buffer_views[image_json[\"bufferView\"]]\n if \"byteStride\" in buffer_view:\n raise NotImplementedError(\"strided buffer views\")\n\n length = buffer_view[\"byteLength\"]\n offset = buffer_view.get(\"byteOffset\", 0)\n\n binary_data = self.get_binary_data(buffer_view[\"buffer\"])\n\n bytesio = BytesIO(binary_data[offset : offset + length].tobytes())\n # pyre-fixme[16]: `Image.Image` has no attribute `__enter__`.\n with Image.open(bytesio) as f:\n array = np.array(f)\n if array.dtype == np.uint8:\n return array.astype(np.float32) / 255.0\n else:\n return array\n\n def _get_texture_map_image(self, image_index: int) -> torch.Tensor:\n \"\"\"\n Return a texture map image as a torch tensor.\n Calling this function repeatedly with the same arguments returns\n the very same tensor, this allows a memory optimization to happen\n later in TexturesUV.join_scene.\n Any alpha channel is ignored.\n \"\"\"\n im = self._texture_map_images.get(image_index)\n if im is not None:\n return im\n\n im = torch.from_numpy(self._access_image(image_index))[:, :, :3]\n self._texture_map_images[image_index] = im\n return im\n\n def _access_data(self, accessor_index: int) -> np.ndarray:\n \"\"\"\n Get the raw data from an accessor as a numpy array.\n \"\"\"\n accessor = self._accessors[accessor_index]\n\n buffer_view_index = accessor.get(\"bufferView\")\n # Undefined buffer view (all zeros) are not (yet) supported\n if buffer_view_index is None:\n raise NotImplementedError(\"Undefined buffer view\")\n\n accessor_byte_offset = accessor.get(\"byteOffset\", 0)\n component_type = accessor[\"componentType\"]\n element_count = accessor[\"count\"]\n element_type = accessor[\"type\"]\n\n # Sparse accessors are not (yet) supported\n if accessor.get(\"sparse\") is not None:\n raise NotImplementedError(\"Sparse Accessors\")\n\n buffer_view = self._buffer_views[buffer_view_index]\n buffer_index = buffer_view[\"buffer\"]\n buffer_byte_length = buffer_view[\"byteLength\"]\n element_byte_offset = buffer_view.get(\"byteOffset\", 0)\n element_byte_stride = buffer_view.get(\"byteStride\", 0)\n if element_byte_stride != 0 and element_byte_stride < 4:\n raise ValueError(\"Stride is too small.\")\n if element_byte_stride > 252:\n raise ValueError(\"Stride is too big.\")\n\n element_shape = _ELEMENT_SHAPES[element_type]\n item_type = _ITEM_TYPES[component_type]\n item_dtype = np.dtype(item_type)\n item_count = np.prod(element_shape)\n item_size = item_dtype.itemsize\n size = element_count * item_count * item_size\n if size > buffer_byte_length:\n raise ValueError(\"Buffer did not have enough data for the accessor\")\n\n buffer_ = self._buffers[buffer_index]\n binary_data = self.get_binary_data(buffer_index)\n if len(binary_data) < buffer_[\"byteLength\"]:\n raise ValueError(\"Not enough binary data for the buffer\")\n\n if element_byte_stride == 0:\n element_byte_stride = item_size * item_count\n # The same buffer can store interleaved elements\n if element_byte_stride < item_size * item_count:\n raise ValueError(\"Items should not overlap\")\n\n dtype = np.dtype(\n {\n \"names\": [\"element\"],\n \"formats\": [str(element_shape) + item_dtype.str],\n \"offsets\": [0],\n \"itemsize\": element_byte_stride,\n }\n )\n\n byte_offset = accessor_byte_offset + element_byte_offset\n if byte_offset % item_size != 0:\n raise ValueError(\"Misaligned data\")\n byte_length = element_count * element_byte_stride\n buffer_view = binary_data[byte_offset : byte_offset + byte_length].view(dtype)[\n \"element\"\n ]\n\n # Convert matrix data from column-major (OpenGL) to row-major order\n if element_type in (\"MAT2\", \"MAT3\", \"MAT4\"):\n buffer_view = np.transpose(buffer_view, (0, 2, 1))\n\n return buffer_view\n\n def _get_primitive_attribute(\n self, primitive_attributes: Dict[str, Any], key: str, dtype\n ) -> Optional[np.ndarray]:\n accessor_index = primitive_attributes.get(key)\n if accessor_index is None:\n return None\n primitive_attribute = self._access_data(accessor_index)\n if key == \"JOINTS_0\":\n pass\n elif dtype == np.uint8:\n primitive_attribute /= 255.0\n elif dtype == np.uint16:\n primitive_attribute /= 65535.0\n else:\n if dtype != np.float32:\n raise ValueError(\"Unexpected data type\")\n primitive_attribute = primitive_attribute.astype(dtype)\n return primitive_attribute\n\n def get_binary_data(self, buffer_index: int):\n \"\"\"\n Get the binary data from a buffer as a 1D numpy array of bytes.\n This is implemented for explicit uri data buffers or the main GLB data\n segment.\n \"\"\"\n buffer_ = self._buffers[buffer_index]\n binary_data = self._binary_data.get(buffer_index)\n if binary_data is None: # Lazily decode binary data\n uri = buffer_.get(\"uri\")\n if not uri.startswith(_DATA_URI_PREFIX):\n raise NotImplementedError(\"Unexpected URI type\")\n binary_data = b64decode(uri[len(_DATA_URI_PREFIX) :])\n binary_data = np.frombuffer(binary_data, dtype=np.uint8)\n self._binary_data[buffer_index] = binary_data\n return binary_data\n\n def get_texture_for_mesh(\n self, primitive: Dict[str, Any], indices: torch.Tensor\n ) -> Optional[TexturesBase]:\n \"\"\"\n Get the texture object representing the given mesh primitive.\n\n Args:\n primitive: the mesh primitive being loaded.\n indices: the face indices of the mesh\n \"\"\"\n attributes = primitive[\"attributes\"]\n vertex_colors = self._get_primitive_attribute(attributes, \"COLOR_0\", np.float32)\n if vertex_colors is not None:\n return TexturesVertex(torch.from_numpy(vertex_colors))\n\n vertex_texcoords_0 = self._get_primitive_attribute(\n attributes, \"TEXCOORD_0\", np.float32\n )\n if vertex_texcoords_0 is not None:\n verts_uvs = torch.from_numpy(vertex_texcoords_0)\n verts_uvs[:, 1] = 1 - verts_uvs[:, -1]\n faces_uvs = indices\n material_index = primitive.get(\"material\", 0)\n material = self._json_data[\"materials\"][material_index]\n material_roughness = material[\"pbrMetallicRoughness\"]\n if \"baseColorTexture\" in material_roughness:\n texture_index = material_roughness[\"baseColorTexture\"][\"index\"]\n texture_json = self._json_data[\"textures\"][texture_index]\n # Todo - include baseColorFactor when also given\n # Todo - look at the sampler\n image_index = texture_json[\"source\"]\n map = self._get_texture_map_image(image_index)\n elif \"baseColorFactor\" in material_roughness:\n # Constant color?\n map = torch.FloatTensor(material_roughness[\"baseColorFactor\"])[\n None, None, :3\n ]\n texture = TexturesUV(\n # pyre-fixme[61]: `map` may not be initialized here.\n maps=[map], # alpha channel ignored\n faces_uvs=[faces_uvs],\n verts_uvs=[verts_uvs],\n )\n return texture\n\n return None\n\n def load(self, include_textures: bool) -> List[Tuple[Optional[str], Meshes]]:\n \"\"\"\n Attempt to load all the meshes making up the default scene from\n the file as a list of possibly-named Meshes objects.\n\n Args:\n include_textures: Whether to try loading textures.\n\n Returns:\n Meshes object containing one mesh.\n \"\"\"\n if self._json_data is None:\n raise ValueError(\"Initialization problem\")\n\n # This loads the default scene from the file.\n # This is usually the only one.\n # It is possible to have multiple scenes, in which case\n # you could choose another here instead of taking the default.\n scene_index = self._json_data.get(\"scene\")\n\n if scene_index is None:\n raise ValueError(\"Default scene is not specified.\")\n\n scene = self._json_data[\"scenes\"][scene_index]\n nodes = self._json_data.get(\"nodes\", [])\n meshes = self._json_data.get(\"meshes\", [])\n root_node_indices = scene[\"nodes\"]\n\n mesh_transform = Transform3d()\n names_meshes_list: List[Tuple[Optional[str], Meshes]] = []\n\n # Keep track and apply the transform of the scene node to mesh vertices\n Q = deque([(Transform3d(), node_index) for node_index in root_node_indices])\n\n while Q:\n parent_transform, current_node_index = Q.popleft()\n\n current_node = nodes[current_node_index]\n\n transform = _make_node_transform(current_node)\n current_transform = transform.compose(parent_transform)\n\n if \"mesh\" in current_node:\n mesh_index = current_node[\"mesh\"]\n mesh = meshes[mesh_index]\n mesh_name = mesh.get(\"name\", None)\n mesh_transform = current_transform\n\n for primitive in mesh[\"primitives\"]:\n attributes = primitive[\"attributes\"]\n accessor_index = attributes[\"POSITION\"]\n positions = torch.from_numpy(\n self._access_data(accessor_index).copy()\n )\n positions = mesh_transform.transform_points(positions)\n\n mode = primitive.get(\"mode\", _PrimitiveMode.TRIANGLES)\n if mode != _PrimitiveMode.TRIANGLES:\n raise NotImplementedError(\"Non triangular meshes\")\n\n if \"indices\" in primitive:\n accessor_index = primitive[\"indices\"]\n indices = self._access_data(accessor_index).astype(np.int64)\n else:\n indices = np.arange(0, len(positions), dtype=np.int64)\n indices = torch.from_numpy(indices.reshape(-1, 3))\n\n texture = None\n if include_textures:\n texture = self.get_texture_for_mesh(primitive, indices)\n\n mesh_obj = Meshes(\n verts=[positions], faces=[indices], textures=texture\n )\n names_meshes_list.append((mesh_name, mesh_obj))\n\n if \"children\" in current_node:\n children_node_indices = current_node[\"children\"]\n Q.extend(\n [\n (current_transform, node_index)\n for node_index in children_node_indices\n ]\n )\n\n return names_meshes_list\n\n\ndef load_meshes(\n path: PathOrStr,\n path_manager: PathManager,\n include_textures: bool = True,\n) -> List[Tuple[Optional[str], Meshes]]:\n \"\"\"\n Loads all the meshes from the default scene in the given GLB file.\n and returns them separately.\n\n Args:\n path: path to read from\n path_manager: PathManager object for interpreting the path\n include_textures: whether to load textures\n\n Returns:\n List of (name, mesh) pairs, where the name is the optional name property\n from the GLB file, or None if it is absent, and the mesh is a Meshes\n object containing one mesh.\n \"\"\"\n with _open_file(path, path_manager, \"rb\") as f:\n loader = _GLTFLoader(cast(BinaryIO, f))\n names_meshes_list = loader.load(include_textures=include_textures)\n return names_meshes_list\n\n\nclass MeshGlbFormat(MeshFormatInterpreter):\n \"\"\"\n Implements loading meshes from glTF 2 assets stored in a\n GLB container file or a glTF JSON file with embedded binary data.\n\n This implementation is quite restricted in what it supports.\n\n - It does not try to validate the input against the standard.\n - It loads the default scene only.\n - Only triangulated geometry is supported.\n - The geometry of all meshes of the entire scene is aggregated into a single mesh.\n Use `load_meshes()` instead to get un-aggregated (but transformed) ones.\n - All material properties are ignored except for either vertex color, baseColorTexture\n or baseColorFactor. If available, one of these (in this order) is exclusively\n used which does not match the semantics of the standard.\n \"\"\"\n\n def __init__(self) -> None:\n self.known_suffixes = (\".glb\",)\n\n def read(\n self,\n path: PathOrStr,\n include_textures: bool,\n device,\n path_manager: PathManager,\n **kwargs,\n ) -> Optional[Meshes]:\n if not endswith(path, self.known_suffixes):\n return None\n\n names_meshes_list = load_meshes(\n path=path,\n path_manager=path_manager,\n include_textures=include_textures,\n )\n\n meshes_list = [mesh for name, mesh in names_meshes_list]\n mesh = join_meshes_as_scene(meshes_list)\n return mesh.to(device)\n\n def save(\n self,\n data: Meshes,\n path: PathOrStr,\n path_manager: PathManager,\n binary: Optional[bool],\n **kwargs,\n ) -> bool:\n return False\n" ]
[ [ "torch.FloatTensor", "numpy.transpose", "numpy.dtype", "torch.from_numpy", "numpy.prod", "numpy.array", "numpy.frombuffer" ] ]
dmnlk/namedivider-python
[ "d87a488d4696bc26d2f6444ed399d83a6a1911a7" ]
[ "namedivider/name_divider.py" ]
[ "import numpy as np\nimport pandas as pd\nimport regex\nfrom namedivider.divided_name import DividedName\nfrom namedivider.kanji_statistics import KanjiStatistics\nfrom pathlib import Path\nfrom typing import Optional\nCURRENT_DIR = Path(__file__).resolve().parent\n\n\nclass NameDivider:\n def __init__(self, path_csv: str = f\"{CURRENT_DIR}/assets/kanji.csv\", separator: str = \" \"):\n \"\"\"\n Class for dividing an undivided name\n (\"undivided name\" means names with no space between the family name and given name.)\n :param path_csv: Path of the file containing the kanji information\n :param separator: Characters to separate first and last names\n \"\"\"\n kanji_records = pd.read_csv(path_csv).to_numpy()\n kanjis = kanji_records[:, 0]\n orders = kanji_records[:, 1:7]\n lengths = kanji_records[:, 7:]\n\n self.kanji_dict = {}\n for _kanji, _order, _length in zip(kanjis, orders, lengths):\n self.kanji_dict[_kanji] = KanjiStatistics(kanji=_kanji, order_counts=_order, length_counts=_length)\n\n self.default_kanji = KanjiStatistics.default()\n self.separator = separator\n self.compiled_regex_kanji = regex.compile(r'\\p{Script=Han}+')\n\n def _create_divided_name(self, family: str, given: str, score: float = 1., algorithm: str = \"\") -> DividedName:\n \"\"\"\n Generates DividedName.\n :param family: Family name\n :param given: Given name\n :param score: Confidence level, from 0 to 1\n :param algorithm: The name of dividing algorithm\n :return: Divided name\n :rtype: DividedName\n \"\"\"\n return DividedName(family, given, separator=self.separator, score=score, algorithm=algorithm)\n\n @staticmethod\n def _create_order_mask(full_name_length: int, char_idx: int) -> np.ndarray:\n \"\"\"\n Create order mask.\n Order mask is one-hot mask for calculate order score.\n :param full_name_length: Length of full name.\n :param char_idx: The order of the character in full name\n :return: Order mask\n :rtype: np.ndarray\n \"\"\"\n if char_idx == 0 or char_idx == full_name_length - 1:\n raise ValueError(\"First character and last character must not be created order mask.\")\n\n if full_name_length == 3:\n return np.array([0, 0, 1, 1, 0, 0])\n\n if char_idx == 1:\n return np.array([0, 1, 1, 1, 0, 0])\n\n if char_idx == full_name_length - 2:\n return np.array([0, 0, 1, 1, 1, 0])\n\n return np.array([0, 1, 1, 1, 1, 0])\n\n @staticmethod\n def _create_length_mask(full_name_length, char_idx) -> np.ndarray:\n \"\"\"\n Create length mask.\n Length mask is one-hot mask for calculate length score.\n :param full_name_length: Length of full name.\n :param char_idx: The order of the character in full name\n :return: Length mask\n :rtype: np.ndarray\n \"\"\"\n min_family = char_idx + 1\n max_family = full_name_length - 1\n max_family = 4 if max_family > 4 else max_family\n min_given = full_name_length - char_idx\n max_given = full_name_length - 1\n max_given = 4 if max_given > 4 else max_given\n lc_family = np.array([0, 0, 0, 0])\n if min_family <= max_family:\n lc_family[min_family - 1: max_family] = 1\n lc_given = np.array([0, 0, 0, 0])\n if min_given <= max_given:\n lc_given[min_given - 1: max_given] = 1\n return np.concatenate([lc_family, lc_given])\n\n @staticmethod\n def _calc_current_order_status(piece_of_divided_name: str,\n idx_in_piece_of_divided_name: int,\n is_family: bool) -> int:\n \"\"\"\n Determine which index of order_counts the kanji corresponds to.\n :param piece_of_divided_name: Family name or given name\n :param idx_in_piece_of_divided_name: Index in family or given name\n :param is_family: True if piece_of_divided_name is family name\n :return: The index of order_counts\n :rtype: int\n \"\"\"\n if idx_in_piece_of_divided_name == 0:\n return 0 if is_family else 3\n if idx_in_piece_of_divided_name == len(piece_of_divided_name) - 1:\n return 2 if is_family else 5\n else:\n return 1 if is_family else 4\n\n @staticmethod\n def _calc_current_length_status(piece_of_divided_name: str, is_family: bool) -> int:\n \"\"\"\n Determine which index of length_counts the kanji corresponds to.\n :param piece_of_divided_name: Family name or given name\n :param is_family: True if piece_of_divided_name is family name\n :return: The index of length_counts\n :rtype: int\n \"\"\"\n piece_of_divided_name_length = len(piece_of_divided_name) if len(piece_of_divided_name) <= 4 else 4\n return piece_of_divided_name_length - 1 if is_family else piece_of_divided_name_length - 1 + 4\n\n def _calc_order_score(self, piece_of_divided_name: str, full_name_length: int, start_index: int = 0) -> float:\n \"\"\"\n Calculates order score.\n Order score is a feature, which is a kind of frequency, calculated from where each kanji in full name is used.\n See this link if you need more explanation: https://rskmoi.hatenablog.com/entry/2017/01/15/190837\n :param piece_of_divided_name: Family name or given name\n :param full_name_length: Length of fullname\n :param start_index: The order of the first charactar of piece_of_divided_name in full name\n :return: Order score\n :rtype: float\n\n example:\n -----------------------------------------------------\n >>> namedivider = NameDivider()\n >>> # Full name: 新海誠\n >>> namedivider._calc_order_score(piece_of_divided_name='新海', full_name_length=3, start_index=0)\n 0.8305084745762712\n >>> namedivider._calc_order_score(piece_of_divided_name='誠', full_name_length=3, start_index=2)\n 0\n >>> # Full name: 清武弘嗣\n >>> namedivider._calc_order_score(piece_of_divided_name='清武', full_name_length=4, start_index=0)\n 0.2222222222222222\n >>> namedivider._calc_order_score(piece_of_divided_name='弘嗣', full_name_length=4, start_index=2)\n 0.9919571045576407\n -----------------------------------------------------\n \"\"\"\n is_family = True if start_index == 0 else False\n scores = 0\n for idx_in_piece_of_divided_name, _kanji in enumerate(piece_of_divided_name):\n current_idx = start_index + idx_in_piece_of_divided_name\n if current_idx == 0:\n continue\n if current_idx == full_name_length - 1:\n continue\n mask = self._create_order_mask(full_name_length, current_idx)\n current_order_status_idx = self._calc_current_order_status(piece_of_divided_name,\n idx_in_piece_of_divided_name,\n is_family)\n masked_order = self.kanji_dict.get(_kanji, self.default_kanji).order_counts * mask\n if np.sum(masked_order) == 0:\n continue\n scores += masked_order[current_order_status_idx] / np.sum(masked_order)\n return scores\n\n def _calc_length_score(self, piece_of_divided_name, full_name_length, start_index=0) -> float:\n \"\"\"\n Calculates length score.\n Length score is a feature, which is a kind of frequency,\n calculated from how long is family/given name containing the kanji.\n See this link if you need more explanation: https://rskmoi.hatenablog.com/entry/2017/01/15/190837\n :param piece_of_divided_name: Family name or given name\n :param full_name_length: Length of fullname\n :param start_index: The order of the first charactar of piece_of_divided_name in full name\n :return: Length score\n :rtype: float\n\n example:\n -----------------------------------------------------\n >>> namedivider = NameDivider()\n >>> # Full name: 新海誠\n >>> namedivider._calc_length_score(piece_of_divided_name='新海', full_name_length=3, start_index=0)\n 1.6721919841662545\n >>> namedivider._calc_length_score(piece_of_divided_name='誠', full_name_length=3, start_index=2)\n 0.5414201183431953\n >>> # Full name: 清武弘嗣\n >>> namedivider._calc_length_score(piece_of_divided_name='清武', full_name_length=4, start_index=0)\n 1.9431977559607292\n >>> namedivider._calc_length_score(piece_of_divided_name='弘嗣', full_name_length=4, start_index=2)\n 1.982873228774868\n -----------------------------------------------------\n \"\"\"\n is_family = True if start_index == 0 else False\n scores = 0\n for i, _kanji in enumerate(piece_of_divided_name):\n current_idx = start_index + i\n mask = self._create_length_mask(full_name_length, current_idx)\n current_length_status_idx = self._calc_current_length_status(piece_of_divided_name, is_family)\n masked_length_scores = self.kanji_dict.get(_kanji, self.default_kanji).length_counts * mask\n if np.sum(masked_length_scores) == 0:\n continue\n scores += masked_length_scores[current_length_status_idx] / np.sum(masked_length_scores)\n return scores\n\n def calc_score(self, family: str, given: str) -> float:\n \"\"\"\n Calculates the score for correct division.\n :param family: Family name\n :param given: Given name\n :return: Score for correct division\n :rtype: float\n \"\"\"\n name = family + given\n order_score_family = self._calc_order_score(family, len(name), 0)\n order_score_given = self._calc_order_score(given, len(name), len(family))\n order_score = (order_score_family + order_score_given) / (len(name) - 2)\n\n # If full name consists of 4 chars, the accuracy is better when using only order score.\n if len(name) == 4:\n return order_score\n\n length_score_family = self._calc_length_score(family, len(name), 0)\n length_score_given = self._calc_length_score(given, len(name), len(family))\n length_score = (length_score_family + length_score_given) / len(name)\n\n return (order_score + length_score) / 2\n\n @staticmethod\n def _validate(undivided_name: str):\n \"\"\"\n Determines if it is an assumed input.\n :param undivided_name: Names with no space between the first and last name\n \"\"\"\n if len(undivided_name) < 2:\n raise ValueError(\"Name length needs at least 2 chars\")\n\n def _divide_by_rule_base(self, undivided_name: str) -> Optional[DividedName]:\n \"\"\"\n Divides undivided name without using kanji statistics.\n :param undivided_name: Names with no space between the family name and given name\n :return:\n if fits the rules: Divided name\n else: None\n :rtype:\n if fits the rules: DividedName\n else: None\n \"\"\"\n # If the undivided name consists of 2 characters,\n # the first characters is family name, and the last characters is given name.\n if len(undivided_name) == 2:\n return self._create_divided_name(family=undivided_name[0],\n given=undivided_name[-1],\n algorithm=\"rule\")\n\n # If the undivided name consists of kanji and other types of characters (hiragana, katakana, etc...),\n # the undivided name will be divided where the kanji and other character types are switched.\n # The criterion for determining switched is whether \"two\" consecutive characters are having\n # different type of characters from first character type.\n # The reason of \"two\" is some family names consist of some kanji and one katakana.\n # (ex: \"井ノ原\", \"三ツ又\", \"関ヶ原\" contains \"ノ\", \"ツ\", \"ヶ\". They are all katakana.)\n is_kanji_list = []\n for i, _char in enumerate(undivided_name):\n is_kanji = True if self.compiled_regex_kanji.fullmatch(_char) else False\n is_kanji_list.append(is_kanji)\n if i >= 2:\n if is_kanji_list[0] != is_kanji and is_kanji_list[-2] == is_kanji:\n return self._create_divided_name(family=undivided_name[:i - 1],\n given=undivided_name[i - 1:],\n algorithm=\"rule\")\n\n @staticmethod\n def _softmax(x) -> np.ndarray:\n \"\"\"\n Calculates softmax score\n :param x: array_like\n :return: Softmax scores\n :rtype: np.ndarray\n \"\"\"\n u = np.sum(np.exp(x))\n return np.exp(x) / u\n\n def _divide_by_statistics(self, undivided_name: str) -> DividedName:\n \"\"\"\n Divides undivided name using kanji statistics.\n :param undivided_name: Names with no space between the family name and given name\n :return: Divided name\n :rtype: DividedName\n \"\"\"\n total_scores = []\n for i in range(1, len(undivided_name)):\n family = undivided_name[:i]\n given = undivided_name[i:]\n score = self.calc_score(family, given)\n total_scores.append(score)\n\n total_scores = self._softmax(total_scores)\n max_idx = np.argmax(np.array(total_scores)) + 1\n return self._create_divided_name(family=undivided_name[:max_idx],\n given=undivided_name[max_idx:],\n score=total_scores[max_idx - 1],\n algorithm=\"kanji_feature\")\n\n def divide_name(self, undivided_name: str) -> DividedName:\n \"\"\"\n Divides undivided name.\n :param undivided_name: Names with no space between the family name and given name\n :return: Divided name\n :rtype: DividedName\n\n example:\n -----------------------------------------------------\n >>> namedivider = NameDivider()\n >>> divided_name = namedivider.divide_name(\"菅義偉\")\n >>> print(divided_name)\n \"菅 義偉\"\n >>> print(divided_name.to_dict())\n {'family': '菅', 'given': '義偉', 'separator': ' ', 'score': 0.6328842762252201, 'algorithm': 'kanji_feature'}\n -----------------------------------------------------\n \"\"\"\n self._validate(undivided_name)\n divided_name_by_rule_base = self._divide_by_rule_base(undivided_name)\n if divided_name_by_rule_base:\n return divided_name_by_rule_base\n return self._divide_by_statistics(undivided_name)\n" ]
[ [ "numpy.sum", "pandas.read_csv", "numpy.exp", "numpy.array", "numpy.concatenate" ] ]
siril-pivotchain/ETAG-OCR
[ "216c27e8ab63acc5b3686da2948a6881da70350e" ]
[ "keras_ocr/recognition.py" ]
[ "# pylint: disable=invalid-name,too-many-locals,too-many-arguments\nimport typing\nimport string\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport cv2\n\nfrom . import tools\n\nDEFAULT_BUILD_PARAMS = {\n 'height': 31,\n 'width': 200,\n 'color': False,\n 'filters': (64, 128, 256, 256, 512, 512, 512),\n 'rnn_units': (128, 128),\n 'dropout': 0.25,\n 'rnn_steps_to_discard': 2,\n 'pool_size': 2,\n 'stn': True,\n}\n\nDEFAULT_ALPHABET = string.digits + string.ascii_lowercase\n\nPRETRAINED_WEIGHTS = {\n 'kurapan': {\n 'alphabet': DEFAULT_ALPHABET,\n 'build_params': DEFAULT_BUILD_PARAMS,\n 'weights': {\n 'notop': {\n 'url': 'https://www.mediafire.com/file/n9yfn5wueu82rgf/crnn_kurapan_notop.h5/file',\n 'filename': 'crnn_kurapan_notop.h5',\n 'sha256': '027fd2cced3cbea0c4f5894bb8e9e85bac04f11daf96b8fdcf1e4ee95dcf51b9'\n },\n 'top': {\n 'url': 'https://www.mediafire.com/file/pkj2p29b1f6fpil/crnn_kurapan.h5/file',\n 'filename': 'crnn_kurapan.h5',\n 'sha256': 'a7d8086ac8f5c3d6a0a828f7d6fbabcaf815415dd125c32533013f85603be46d'\n }\n }\n },\n 'captcha': {\n 'alphabet': DEFAULT_ALPHABET,\n 'build_params': DEFAULT_BUILD_PARAMS,\n 'weights': {\n 'notop': {\n 'url': 'https://drive.google.com/uc?export=download&id=1drJ9rlIb6WtnW8ysoWU9kTp3TBAS-q6v',\n 'filename': 'captcha.hdf5',\n 'sha256': '701e0947beab802624ba562200da7b7684b87fd516a7d720c6a7453d0e3db805'\n },\n 'top': {\n 'url': 'https://drive.google.com/uc?export=download&id=1drJ9rlIb6WtnW8ysoWU9kTp3TBAS-q6v',\n 'filename': 'captcha.hdf5',\n 'sha256': '701e0947beab802624ba562200da7b7684b87fd516a7d720c6a7453d0e3db805'\n }\n }\n },\n 'etag': {\n 'alphabet': DEFAULT_ALPHABET,\n 'build_params': DEFAULT_BUILD_PARAMS,\n 'weights': {\n 'notop': {\n 'url': 'https://drive.google.com/uc?export=download&id=15rVYQCiMz1wLQUQFFbaJ3DbC3FBHPHX8',\n 'filename': 'recognizer_etag.h5',\n 'sha256': '00178a3ed1e5d1585bdf26252d35a4c03716963c9b2f868b733fe41b718c350e'\n },\n 'top': {\n 'url': 'https://drive.google.com/uc?export=download&id=15rVYQCiMz1wLQUQFFbaJ3DbC3FBHPHX8',\n 'filename': 'recognizer_etag.h5',\n 'sha256': '00178a3ed1e5d1585bdf26252d35a4c03716963c9b2f868b733fe41b718c350e'\n }\n }\n },\n 'etag_2': {\n 'alphabet': DEFAULT_ALPHABET,\n 'build_params': DEFAULT_BUILD_PARAMS,\n 'weights': {\n 'notop': {\n 'url': 'https://drive.google.com/uc?export=download&id=1mqYCyUD1cJzsCbYLzBUYYZ3-1VoPopOZ',\n 'filename': 'recognizer_etag_detect.h5',\n 'sha256': 'fc9f8acfdfe5a3a5dd4880a2bb4a3d0ce353c1469dda507a41faaf52d4dc3afc'\n },\n 'top': {\n 'url': 'https://drive.google.com/uc?export=download&id=1mqYCyUD1cJzsCbYLzBUYYZ3-1VoPopOZ',\n 'filename': 'recognizer_etag_detect.h5',\n 'sha256': 'fc9f8acfdfe5a3a5dd4880a2bb4a3d0ce353c1469dda507a41faaf52d4dc3afc'\n }\n }\n },\n 'etag_3': {\n 'alphabet': DEFAULT_ALPHABET,\n 'build_params': DEFAULT_BUILD_PARAMS,\n 'weights': {\n 'notop': {\n 'url': 'https://drive.google.com/uc?export=download&id=1-1NK1D4AHT5zxQPdNraNT2pNVdgi5qvI',\n 'filename': 'recognizer_etag_detect_aug.h5',\n 'sha256': '84a8d8e56576d99d6ca9c7d792ef6b9b4fc42c16c316fbbb2e26c66bdbb46286'\n },\n 'top': {\n 'url': 'https://drive.google.com/uc?export=download&id=1-1NK1D4AHT5zxQPdNraNT2pNVdgi5qvI',\n 'filename': 'recognizer_etag_detect_aug.h5',\n 'sha256': '84a8d8e56576d99d6ca9c7d792ef6b9b4fc42c16c316fbbb2e26c66bdbb46286'\n }\n }\n }\n}\n\n\ndef swish(x, beta=1):\n return x * keras.backend.sigmoid(beta * x)\n\n\nkeras.utils.get_custom_objects().update({'swish': keras.layers.Activation(swish)})\n\n\ndef _repeat(x, num_repeats):\n ones = tf.ones((1, num_repeats), dtype='int32')\n x = tf.reshape(x, shape=(-1, 1))\n x = tf.matmul(x, ones)\n return tf.reshape(x, [-1])\n\n\ndef _meshgrid(height, width):\n x_linspace = tf.linspace(-1., 1., width)\n y_linspace = tf.linspace(-1., 1., height)\n x_coordinates, y_coordinates = tf.meshgrid(x_linspace, y_linspace)\n x_coordinates = tf.reshape(x_coordinates, shape=(1, -1))\n y_coordinates = tf.reshape(y_coordinates, shape=(1, -1))\n ones = tf.ones_like(x_coordinates)\n indices_grid = tf.concat([x_coordinates, y_coordinates, ones], 0)\n return indices_grid\n\n\n# pylint: disable=too-many-statements\ndef _transform(inputs):\n locnet_x, locnet_y = inputs\n output_size = locnet_x.shape[1:]\n batch_size = tf.shape(locnet_x)[0]\n height = tf.shape(locnet_x)[1]\n width = tf.shape(locnet_x)[2]\n num_channels = tf.shape(locnet_x)[3]\n\n locnet_y = tf.reshape(locnet_y, shape=(batch_size, 2, 3))\n\n locnet_y = tf.reshape(locnet_y, (-1, 2, 3))\n locnet_y = tf.cast(locnet_y, 'float32')\n\n output_height = output_size[0]\n output_width = output_size[1]\n indices_grid = _meshgrid(output_height, output_width)\n indices_grid = tf.expand_dims(indices_grid, 0)\n indices_grid = tf.reshape(indices_grid, [-1]) # flatten?\n indices_grid = tf.tile(indices_grid, tf.stack([batch_size]))\n indices_grid = tf.reshape(indices_grid, tf.stack([batch_size, 3, -1]))\n\n transformed_grid = tf.matmul(locnet_y, indices_grid)\n x_s = tf.slice(transformed_grid, [0, 0, 0], [-1, 1, -1])\n y_s = tf.slice(transformed_grid, [0, 1, 0], [-1, 1, -1])\n x = tf.reshape(x_s, [-1])\n y = tf.reshape(y_s, [-1])\n\n # Interpolate\n height_float = tf.cast(height, dtype='float32')\n width_float = tf.cast(width, dtype='float32')\n\n output_height = output_size[0]\n output_width = output_size[1]\n\n x = tf.cast(x, dtype='float32')\n y = tf.cast(y, dtype='float32')\n x = .5 * (x + 1.0) * width_float\n y = .5 * (y + 1.0) * height_float\n\n x0 = tf.cast(tf.floor(x), 'int32')\n x1 = x0 + 1\n y0 = tf.cast(tf.floor(y), 'int32')\n y1 = y0 + 1\n\n max_y = tf.cast(height - 1, dtype='int32')\n max_x = tf.cast(width - 1, dtype='int32')\n zero = tf.zeros([], dtype='int32')\n\n x0 = tf.clip_by_value(x0, zero, max_x)\n x1 = tf.clip_by_value(x1, zero, max_x)\n y0 = tf.clip_by_value(y0, zero, max_y)\n y1 = tf.clip_by_value(y1, zero, max_y)\n\n flat_image_dimensions = width * height\n pixels_batch = tf.range(batch_size) * flat_image_dimensions\n flat_output_dimensions = output_height * output_width\n base = _repeat(pixels_batch, flat_output_dimensions)\n base_y0 = base + y0 * width\n base_y1 = base + y1 * width\n indices_a = base_y0 + x0\n indices_b = base_y1 + x0\n indices_c = base_y0 + x1\n indices_d = base_y1 + x1\n\n flat_image = tf.reshape(locnet_x, shape=(-1, num_channels))\n flat_image = tf.cast(flat_image, dtype='float32')\n pixel_values_a = tf.gather(flat_image, indices_a)\n pixel_values_b = tf.gather(flat_image, indices_b)\n pixel_values_c = tf.gather(flat_image, indices_c)\n pixel_values_d = tf.gather(flat_image, indices_d)\n\n x0 = tf.cast(x0, 'float32')\n x1 = tf.cast(x1, 'float32')\n y0 = tf.cast(y0, 'float32')\n y1 = tf.cast(y1, 'float32')\n\n area_a = tf.expand_dims(((x1 - x) * (y1 - y)), 1)\n area_b = tf.expand_dims(((x1 - x) * (y - y0)), 1)\n area_c = tf.expand_dims(((x - x0) * (y1 - y)), 1)\n area_d = tf.expand_dims(((x - x0) * (y - y0)), 1)\n transformed_image = tf.add_n([\n area_a * pixel_values_a, area_b * pixel_values_b, area_c * pixel_values_c,\n area_d * pixel_values_d\n ])\n # Finished interpolation\n\n transformed_image = tf.reshape(transformed_image,\n shape=(batch_size, output_height, output_width, num_channels))\n return transformed_image\n\n\ndef CTCDecoder():\n def decoder(y_pred):\n input_shape = tf.keras.backend.shape(y_pred)\n input_length = tf.ones(shape=input_shape[0]) * tf.keras.backend.cast(\n input_shape[1], 'float32')\n unpadded = tf.keras.backend.ctc_decode(y_pred, input_length)[0][0]\n unpadded_shape = tf.keras.backend.shape(unpadded)\n padded = tf.pad(unpadded,\n paddings=[[0, 0], [0, input_shape[1] - unpadded_shape[1]]],\n constant_values=-1)\n return padded\n\n return tf.keras.layers.Lambda(decoder, name='decode')\n\n\ndef build_model(alphabet,\n height,\n width,\n color,\n filters,\n rnn_units,\n dropout,\n rnn_steps_to_discard,\n pool_size,\n stn=True):\n \"\"\"Build a Keras CRNN model for character recognition.\n\n Args:\n height: The height of cropped images\n width: The width of cropped images\n color: Whether the inputs should be in color (RGB)\n filters: The number of filters to use for each of the 7 convolutional layers\n rnn_units: The number of units for each of the RNN layers\n dropout: The dropout to use for the final layer\n rnn_steps_to_discard: The number of initial RNN steps to discard\n pool_size: The size of the pooling steps\n stn: Whether to add a Spatial Transformer layer\n \"\"\"\n assert len(filters) == 7, '7 CNN filters must be provided.'\n assert len(rnn_units) == 2, '2 RNN filters must be provided.'\n inputs = keras.layers.Input((height, width, 3 if color else 1))\n x = keras.layers.Permute((2, 1, 3))(inputs)\n x = keras.layers.Lambda(lambda x: x[:, :, ::-1])(x)\n x = keras.layers.Conv2D(filters[0], (3, 3), activation='relu', padding='same', name='conv_1')(x)\n x = keras.layers.Conv2D(filters[1], (3, 3), activation='relu', padding='same', name='conv_2')(x)\n x = keras.layers.Conv2D(filters[2], (3, 3), activation='relu', padding='same', name='conv_3')(x)\n x = keras.layers.BatchNormalization(name='bn_3')(x)\n x = keras.layers.MaxPooling2D(pool_size=(pool_size, pool_size), name='maxpool_3')(x)\n x = keras.layers.Conv2D(filters[3], (3, 3), activation='relu', padding='same', name='conv_4')(x)\n x = keras.layers.Conv2D(filters[4], (3, 3), activation='relu', padding='same', name='conv_5')(x)\n x = keras.layers.BatchNormalization(name='bn_5')(x)\n x = keras.layers.MaxPooling2D(pool_size=(pool_size, pool_size), name='maxpool_5')(x)\n x = keras.layers.Conv2D(filters[5], (3, 3), activation='relu', padding='same', name='conv_6')(x)\n x = keras.layers.Conv2D(filters[6], (3, 3), activation='relu', padding='same', name='conv_7')(x)\n x = keras.layers.BatchNormalization(name='bn_7')(x)\n if stn:\n # pylint: disable=pointless-string-statement\n \"\"\"Spatial Transformer Layer\n Implements a spatial transformer layer as described in [1]_.\n Borrowed from [2]_:\n downsample_fator : float\n A value of 1 will keep the orignal size of the image.\n Values larger than 1 will down sample the image. Values below 1 will\n upsample the image.\n example image: height= 100, width = 200\n downsample_factor = 2\n output image will then be 50, 100\n References\n ----------\n .. [1] Spatial Transformer Networks\n Max Jaderberg, Karen Simonyan, Andrew Zisserman, Koray Kavukcuoglu\n Submitted on 5 Jun 2015\n .. [2] https://github.com/skaae/transformer_network/blob/master/transformerlayer.py\n .. [3] https://github.com/EderSantana/seya/blob/keras1/seya/layers/attention.py\n \"\"\"\n stn_input_output_shape = (width // pool_size**2, height // pool_size**2, filters[6])\n stn_input_layer = keras.layers.Input(shape=stn_input_output_shape)\n locnet_y = keras.layers.Conv2D(16, (5, 5), padding='same',\n activation='relu')(stn_input_layer)\n locnet_y = keras.layers.Conv2D(32, (5, 5), padding='same', activation='relu')(locnet_y)\n locnet_y = keras.layers.Flatten()(locnet_y)\n locnet_y = keras.layers.Dense(64, activation='relu')(locnet_y)\n locnet_y = keras.layers.Dense(6,\n weights=[\n np.zeros((64, 6), dtype='float32'),\n np.float32([[1, 0, 0], [0, 1, 0]]).flatten()\n ])(locnet_y)\n localization_net = keras.models.Model(inputs=stn_input_layer, outputs=locnet_y)\n x = keras.layers.Lambda(_transform,\n output_shape=stn_input_output_shape)([x, localization_net(x)])\n x = keras.layers.Reshape(target_shape=(width // pool_size**2,\n (height // pool_size**2) * filters[-1]),\n name='reshape')(x)\n\n x = keras.layers.Dense(rnn_units[0], activation='relu', name='fc_9')(x)\n\n rnn_1_forward = keras.layers.LSTM(rnn_units[0],\n kernel_initializer=\"he_normal\",\n return_sequences=True,\n name='lstm_10')(x)\n rnn_1_back = keras.layers.LSTM(rnn_units[0],\n kernel_initializer=\"he_normal\",\n go_backwards=True,\n return_sequences=True,\n name='lstm_10_back')(x)\n rnn_1_add = keras.layers.Add()([rnn_1_forward, rnn_1_back])\n rnn_2_forward = keras.layers.LSTM(rnn_units[1],\n kernel_initializer=\"he_normal\",\n return_sequences=True,\n name='lstm_11')(rnn_1_add)\n rnn_2_back = keras.layers.LSTM(rnn_units[1],\n kernel_initializer=\"he_normal\",\n go_backwards=True,\n return_sequences=True,\n name='lstm_11_back')(rnn_1_add)\n x = keras.layers.Concatenate()([rnn_2_forward, rnn_2_back])\n backbone = keras.models.Model(inputs=inputs, outputs=x)\n x = keras.layers.Dropout(dropout, name='dropout')(x)\n x = keras.layers.Dense(len(alphabet) + 1,\n kernel_initializer='he_normal',\n activation='softmax',\n name='fc_12')(x)\n x = keras.layers.Lambda(lambda x: x[:, rnn_steps_to_discard:])(x)\n model = keras.models.Model(inputs=inputs, outputs=x)\n\n prediction_model = keras.models.Model(inputs=inputs, outputs=CTCDecoder()(model.output))\n labels = keras.layers.Input(name='labels', shape=[model.output_shape[1]], dtype='float32')\n label_length = keras.layers.Input(shape=[1])\n input_length = keras.layers.Input(shape=[1])\n loss = keras.layers.Lambda(lambda inputs: keras.backend.ctc_batch_cost(\n y_true=inputs[0], y_pred=inputs[1], input_length=inputs[2], label_length=inputs[3]))(\n [labels, model.output, input_length, label_length])\n training_model = keras.models.Model(inputs=[model.input, labels, input_length, label_length],\n outputs=loss)\n return backbone, model, training_model, prediction_model\n\n\nclass Recognizer:\n \"\"\"A text detector using the CRNN architecture.\n\n Args:\n alphabet: The alphabet the model should recognize.\n build_params: A dictionary of build parameters for the model.\n See `keras_ocr.recognition.build_model` for details.\n weights: The starting weight configuration for the model.\n include_top: Whether to include the final classification layer in the model (set\n to False to use a custom alphabet).\n \"\"\"\n def __init__(self, alphabet=None, weights='kurapan', build_params=None):\n assert alphabet or weights, 'At least one of alphabet or weights must be provided.'\n if weights is not None:\n build_params = build_params or PRETRAINED_WEIGHTS[weights]['build_params']\n alphabet = alphabet or PRETRAINED_WEIGHTS[weights]['alphabet']\n build_params = build_params or DEFAULT_BUILD_PARAMS\n if alphabet is None:\n alphabet = DEFAULT_ALPHABET\n self.alphabet = alphabet\n self.blank_label_idx = len(alphabet)\n self.backbone, self.model, self.training_model, self.prediction_model = build_model(\n alphabet=alphabet, **build_params)\n if weights is not None:\n weights_dict = PRETRAINED_WEIGHTS[weights]\n if alphabet == weights_dict['alphabet']:\n self.model.load_weights(\n tools.download_and_verify(url=weights_dict['weights']['top']['url'],\n filename=weights_dict['weights']['top']['filename'],\n sha256=weights_dict['weights']['top']['sha256']))\n else:\n print('Provided alphabet does not match pretrained alphabet. '\n 'Using backbone weights only.')\n self.backbone.load_weights(\n tools.download_and_verify(url=weights_dict['weights']['notop']['url'],\n filename=weights_dict['weights']['notop']['filename'],\n sha256=weights_dict['weights']['notop']['sha256']))\n\n def get_batch_generator(self, image_generator, batch_size=8, lowercase=False):\n \"\"\"\n Generate batches of training data from an image generator. The generator\n should yield tuples of (image, sentence) where image contains a single\n line of text and sentence is a string representing the contents of\n the image. If a sample weight is desired, it can be provided as a third\n entry in the tuple, making each tuple an (image, sentence, weight) tuple.\n\n Args:\n image_generator: An image / sentence tuple generator. The images should\n be in color even if the OCR is setup to handle grayscale as they\n will be converted here.\n batch_size: How many images to generate at a time.\n lowercase: Whether to convert all characters to lowercase before\n encoding.\n \"\"\"\n y = np.zeros((batch_size, 1))\n if self.training_model is None:\n raise Exception('You must first call create_training_model().')\n max_string_length = self.training_model.input_shape[1][1]\n while True:\n batch = [sample for sample, _ in zip(image_generator, range(batch_size))]\n if not self.model.input_shape[-1] == 3:\n images = [\n cv2.cvtColor(sample[0], cv2.COLOR_RGB2GRAY)[..., np.newaxis] for sample in batch\n ]\n else:\n images = [sample[0] for sample in batch]\n images = np.array([image.astype('float32') / 255 for image in images])\n sentences = [sample[1].strip() for sample in batch]\n if lowercase:\n sentences = [sentence.lower() for sentence in sentences]\n assert all(c in self.alphabet\n for c in ''.join(sentences)), 'Found illegal characters in sentence.'\n assert all(sentences), 'Found a zero length sentence.'\n assert all(\n len(sentence) <= max_string_length\n for sentence in sentences), 'A sentence is longer than this model can predict.'\n assert all(\" \" not in sentence for sentence in sentences), (\n 'Strings with multiple sequential spaces are not permitted. '\n 'See https://github.com/faustomorales/keras-ocr/issues/54')\n label_length = np.array([len(sentence) for sentence in sentences])[:, np.newaxis]\n labels = np.array([[self.alphabet.index(c)\n for c in sentence] + [-1] * (max_string_length - len(sentence))\n for sentence in sentences])\n input_length = np.ones((batch_size, 1)) * max_string_length\n if len(batch[0]) == 3:\n sample_weights = np.array([sample[2] for sample in batch])\n yield (images, labels, input_length, label_length), y, sample_weights\n else:\n yield (images, labels, input_length, label_length), y\n\n def recognize(self, image):\n \"\"\"Recognize text from a single image.\n\n Args:\n image: A pre-cropped image containing characters\n \"\"\"\n image = tools.read_and_fit(filepath_or_array=image,\n width=self.prediction_model.input_shape[2],\n height=self.prediction_model.input_shape[1],\n cval=0)\n if self.prediction_model.input_shape[-1] == 1 and image.shape[-1] == 3:\n # Convert color to grayscale\n image = cv2.cvtColor(image, code=cv2.COLOR_RGB2GRAY)[..., np.newaxis]\n image = image.astype('float32') / 255\n return ''.join([\n self.alphabet[idx] for idx in self.prediction_model.predict(image[np.newaxis])[0]\n if idx not in [self.blank_label_idx, -1]\n ])\n\n def recognize_from_boxes(self, images, box_groups, **kwargs) -> typing.List[str]:\n \"\"\"Recognize text from images using lists of bounding boxes.\n\n Args:\n images: A list of input images, supplied as numpy arrays with shape\n (H, W, 3).\n boxes: A list of groups of boxes, one for each image\n \"\"\"\n assert len(box_groups) == len(images), \\\n 'You must provide the same number of box groups as images.'\n crops = []\n start_end = []\n for image, boxes in zip(images, box_groups):\n image = tools.read(image)\n if self.prediction_model.input_shape[-1] == 1 and image.shape[-1] == 3:\n # Convert color to grayscale\n image = cv2.cvtColor(image, code=cv2.COLOR_RGB2GRAY)\n for box in boxes:\n crops.append(\n tools.warpBox(image=image,\n box=box,\n target_height=self.model.input_shape[1],\n target_width=self.model.input_shape[2]))\n start = 0 if not start_end else start_end[-1][1]\n start_end.append((start, start + len(boxes)))\n if not crops:\n return [[] for image in images]\n X = np.float32(crops) / 255\n if len(X.shape) == 3:\n X = X[..., np.newaxis]\n predictions = [\n ''.join([self.alphabet[idx] for idx in row if idx not in [self.blank_label_idx, -1]])\n for row in self.prediction_model.predict(X, **kwargs)\n ]\n return [predictions[start:end] for start, end in start_end]\n\n def compile(self, *args, **kwargs):\n \"\"\"Compile the training model.\"\"\"\n if 'optimizer' not in kwargs:\n kwargs['optimizer'] = 'RMSprop'\n if 'loss' not in kwargs:\n kwargs['loss'] = lambda _, y_pred: y_pred\n self.training_model.compile(*args, **kwargs)\n" ]
[ [ "numpy.ones", "tensorflow.keras.layers.Flatten", "tensorflow.keras.layers.Concatenate", "tensorflow.reshape", "tensorflow.ones", "tensorflow.keras.layers.Lambda", "tensorflow.matmul", "tensorflow.linspace", "tensorflow.keras.models.Model", "tensorflow.keras.backend.cast", "tensorflow.keras.layers.Add", "tensorflow.concat", "tensorflow.slice", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.Permute", "tensorflow.meshgrid", "tensorflow.keras.backend.ctc_decode", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.BatchNormalization", "tensorflow.clip_by_value", "tensorflow.keras.layers.Dense", "tensorflow.stack", "tensorflow.add_n", "tensorflow.keras.utils.get_custom_objects", "tensorflow.shape", "tensorflow.ones_like", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Dropout", "numpy.zeros", "tensorflow.expand_dims", "numpy.float32", "tensorflow.keras.backend.ctc_batch_cost", "tensorflow.cast", "tensorflow.keras.backend.shape", "tensorflow.floor", "tensorflow.pad", "tensorflow.zeros", "tensorflow.range", "tensorflow.keras.backend.sigmoid", "tensorflow.keras.layers.LSTM", "numpy.array", "tensorflow.gather", "tensorflow.keras.layers.Reshape", "tensorflow.keras.layers.Input" ] ]
tomoino/GagRocket
[ "1f0bbef1a48cc12774d11bc380f0b72b9ffaf9f1" ]
[ "src/humorcalc.py" ]
[ "import numpy as np\nfrom keras.models import load_model\nimport MeCab\nimport re\n\ndef calc_humor_score(text, model, word_index):\n (words, reading) = morph(text)\n if not is_dajare(reading):\n return 0\n \n return predict(words, model, word_index)\n \ndef morph(text):\n words = [] # 単語の原形\n reading = \"\" # 単語の読み(発音)\n\n # 発音に関係のない不要な文字を削除\n char_to_trim = [\" \",\" \", \"、\", \"。\", \"!\", \"?\", \"!\", \"?\", \"「\", \"」\", \"『\", \"』\", \"(\", \")\", \"(\", \")\", \"・\", \"~\", \"\\\"\", \"\\'\"];\n for c in char_to_trim:\n text = text.replace(c, \"\")\n\n res = MeCab.Tagger().parse(text)\n\n lines = res.split('\\n')\n items = (re.split('[\\t]',line) for line in lines)\n for item in items:\n if len(item) == 1:\n continue\n\n info = re.split('[,]', item[1])\n words.append(info[6])\n\n if len(info) == 9:\n reading += info[8] if info[8] != \"ヲ\" else \"オ\"\n else:\n reading += item[0] # 登録されていない語やカタカナ語への対応\n\n return (words, reading)\n\ndef is_dajare(reading):\n reading = reading.replace(\"ッ\", \"\").replace(\"ー\", \"\") # 音韻変化を考慮してトリム\n reading_len = len(reading)\n\n for i in range(2, int(reading_len / 2) + 1): # i文字の繰り返しを検出する\n parts = [reading[j:j + i] for j in range(0, reading_len - i + 1)] # 1文字ずつずらしながら検出\n if len(parts) != len(set(parts)):\n return True\n\n return False\n\ndef predict(words, model, word_index):\n max_length = 32 # 含まれる単語の最大の数\n words = [word_index[word] for word in words if word in word_index]\n words = words + [0]*(max_length - len(words))\n ret = model.predict(np.array([words]))\n \n return ret[0][0]" ]
[ [ "numpy.array" ] ]
LukasDegitz/kge
[ "0ff3d2623d520e0634374e81d4184d525c189a25" ]
[ "kge/model/hmcn_model.py" ]
[ "import torch\nfrom torch import Tensor\nfrom kge import Config, Dataset\nfrom kge.model.kge_model import KgeModel\nimport json\nimport os\nimport numpy as np\nimport time\n\nclass hmcn_model(KgeModel):\n\n \"\"\"\n Implements hierarchical Multi-Label classification Network as defined in Wehrmann et al. (2018)\n Codes are adapted from:\n https://github.com/Tencent/NeuralNLP-NeuralClassifier/blob/master/model/classification/hmcn.py\n\n \"\"\"\n\n def __init__(\n self,\n config: Config,\n dataset: Dataset,\n configuration_key=None,\n init_for_load_only=False,\n ):\n self._init_configuration(config, configuration_key)\n\n # Initialize embedding model\n embedding_model = KgeModel.create(\n config=config,\n dataset=dataset,\n configuration_key=self.configuration_key + \".embedding_model\",\n init_for_load_only=init_for_load_only,\n )\n\n # Initialize this model\n super().__init__(\n config=config,\n dataset=dataset,\n scorer=embedding_model.get_scorer(),\n create_embedders=False,\n init_for_load_only=init_for_load_only,\n )\n self._embedding_model = embedding_model\n\n\n types_path = self.config.get('hmcn_model.types_path')\n y, idx, pos_weights, hier_tuple_ids, hier, hierarchical_depth, global2local, hierarchy_classes\\\n = self.load_types(types_dataset_path=types_path, num_entities=dataset.num_entities())\n self.types = y\n self.type_ids = idx\n self.hier_tuple_ids = hier_tuple_ids\n self.hier = hier\n self.pos_weights = pos_weights\n\n #HMCN setup\n self.hierarchical_depth = hierarchical_depth\n self.hierarchical_class = hierarchy_classes\n self.global2local = global2local\n hidden_dimension = self._embedding_model.get_s_embedder().dim\n\n #predictions\n self.beta = self.config.get(\"hmcn_model.beta\")\n self.p = self.config.get(\"hmcn_model.hiddenlayer_dropout\")\n self.lamb = torch.Tensor([self.config.get(\"hmcn_model.lambda\")])\n\n # Setup HMCN model according to Wehrmann et al. (2018)\n # Code adapted from\n # https://github.com/Tencent/NeuralNLP-NeuralClassifier/blob/master/model/classification/hmcn.py\n self.local_layers = torch.nn.ModuleList()\n self.global_layers = torch.nn.ModuleList()\n for i in range(1, len(self.hierarchical_depth)):\n self.global_layers.append(\n torch.nn.Sequential(\n torch.nn.Linear(hidden_dimension + self.hierarchical_depth[i - 1], self.hierarchical_depth[i]),\n torch.nn.ReLU(),\n torch.nn.BatchNorm1d(self.hierarchical_depth[i]),\n torch.nn.Dropout(p=0.5)\n ))\n self.local_layers.append(\n torch.nn.Sequential(\n torch.nn.Linear(self.hierarchical_depth[i], self.global2local[i]),\n torch.nn.ReLU(),\n torch.nn.BatchNorm1d(self.global2local[i]),\n torch.nn.Linear(self.global2local[i], self.hierarchical_class[i])\n ))\n\n self.global_layers.apply(self._init_weight)\n self.local_layers.apply(self._init_weight)\n self.linear = torch.nn.Linear(self.hierarchical_depth[-1], len(hier_tuple_ids))\n self.linear.apply(self._init_weight)\n self.dropout = torch.nn.Dropout(p=self.p)\n\n def prepare_job(self, job, **kwargs):\n self._embedding_model.prepare_job(job, **kwargs)\n\n def penalty(self, **kwargs):\n ''' penalty calculated in training as it depends on confidence estimates '''\n penalties = self._embedding_model.penalty(**kwargs)\n return penalties\n\n def get_lambda(self):\n return self.lamb\n\n def get_tuple_ids(self):\n return self.hier_tuple_ids\n\n def get_train_mask(self, idx):\n return self.train_mask[idx]\n\n # pass embedding methods down to wrapped embedder\n def get_s_embedder(self):\n return self._embedding_model.get_s_embedder()\n\n def get_o_embedder(self):\n return self._embedding_model.get_o_embedder()\n\n def get_p_embedder(self):\n return self._embedding_model.get_p_embedder()\n\n def get_scorer(self):\n return self._embedding_model.get_scorer()\n\n def score_spo(self, s, p, o, direction=None):\n return self._embedding_model.score_spo(s, p, o, direction)\n\n def score_po(self, p, o, s=None):\n return self._embedding_model.score_po(p, o, s)\n\n def score_so(self, s, o, p=None):\n return self._embedding_model.score_so(s, o, p)\n\n def score_sp_po(self, s, p, o, entity_subset=None):\n return self._embedding_model.score_sp_po(s, p, o, entity_subset)\n\n # mimics forward\n def predict_all(self, idx, device):\n\n entity_embeddings = self._embedding_model.get_s_embedder().to(device).embed(indexes=idx)\n local_layer_outputs = []\n global_layer_activation = entity_embeddings\n #batch_size = len(idx)\n for i, (local_layer, global_layer) in enumerate(zip(self.local_layers, self.global_layers)):\n local_layer_activation = global_layer(global_layer_activation)\n local_layer_outputs.append(local_layer(local_layer_activation))\n if i < len(self.global_layers) - 1:\n global_layer_activation = torch.cat((local_layer_activation, entity_embeddings), 1)\n else:\n global_layer_activation = local_layer_activation\n\n global_layer_output = self.linear(global_layer_activation)\n local_layer_output = torch.cat(local_layer_outputs, 1)\n probits = self.beta * torch.sigmoid(local_layer_output) + (1 - self.beta) * torch.sigmoid(global_layer_output)\n return global_layer_output, local_layer_output, probits\n\n # function to zero all child class predictions, that dont have the relative parent type assigned\n # type = 'proba' used for violation calculation by lagging parent confidence to child\n # type = 'binbary' used to ensure hierarchy consistent prediction\n def build_mask(self, y, type='binary', device=None):\n\n mask = []\n y_parent = {}\n # Assume root type is predicted for all instances\n for root_type in self.hier[1].keys():\n if type == 'binary':\n y_parent[(1, root_type)] = torch.ones(len(y), dtype=torch.int).to(device)\n else:\n y_parent[(1, root_type)] = torch.ones(len(y), dtype=torch.float).to(device)\n\n for hier_tuple, tuple_id in self.hier_tuple_ids.items():\n mask.append(y_parent[hier_tuple])\n type_level, type_id = hier_tuple\n for child in self.hier[type_level][type_id]:\n child_tuple = (type_level + 1, child)\n if child_tuple not in y_parent:\n y_parent[child_tuple] = y[:, tuple_id]\n # DAG!\n else:\n if type == 'binary':\n # Tie handling when both parent cast predictions: logical or\n y_parent[child_tuple] = torch.logical_or(y_parent[child_tuple], y[:, tuple_id]).int()\n else:\n # Tie Handling use maximum confidence of parent predictions\n y_parent[child_tuple] = torch.max(y_parent[child_tuple], y[:, tuple_id]).float()\n\n return torch.stack(mask).transpose(0, 1).float()\n\n def load_types(self, types_dataset_path, num_entities):\n \"\"\"\n @param types_dataset_path: Path to type dataset. Requires hier.json, train.del, valid.del and test.del.\n @param num_entities: Number of unique entities in the KG.\n @return:\n y: Binary map of types with shape (num_entities, num_types-1). Root type not considered.\n idx: dict with keys ['train', 'valid', 'test'] containing respective entity ids.\n pos_weights: positive weights of class computed from training split for weighted bce_with_logits_loss.\n hier_tuple_ids: dict with keys [(level, type_id)] for mapping y to type id\n hierarchical_depth: number of ReLU neurons per hierarchy level: 384.\n global2local: local ReLU neurons. same as hierarchy_classes.\n hierarchy_classes: Number of classes per hierarchy level. root class excluded.\n \"\"\"\n # load the hierarchy to receive type information\n hier_path = os.path.join(types_dataset_path, 'hier.json')\n with open(hier_path, 'r') as json_file:\n hier = json.load(json_file)\n\n # reshape hierarchy and build binary type map (usefull to map predictions to type_ids)\n # build required shapes for HMCN\n # ReLU neurons set to 384 per level see Wehrmann et al (2018)\n hier_t, train_freq, hier_tuple_ids = {}, [], {}\n for hier_level, parents in hier.items():\n hier_t[int(hier_level)] = {}\n if int(hier_level) == 0:\n #no prediction for level 0\n hierarchical_depth = [0] # Global ReLU neurons\n global2local = [0] # Local transfer neurons\n hierarchy_classes = [0] #number of classes per level\n continue\n else:\n hierarchical_depth.append(384) # Global ReLU neurons\n global2local.append(len(parents)) # Local transfer neurons\n hierarchy_classes.append(len(parents)) # number of classes per level\n for level_type in parents:\n hier_t[int(hier_level)][int(level_type)] = hier[hier_level][level_type].copy()\n if (int(hier_level), int(level_type)) not in hier_tuple_ids:\n hier_tuple_ids[(int(hier_level), int(level_type))] = len(hier_tuple_ids)\n train_freq.append(0)\n hier = hier_t\n\n # build type maps keeping track of ids of respective split\n type_idx = {}\n y = np.zeros((num_entities, len(hier_tuple_ids)))\n # load types\n for split in ['train', 'valid', 'test']:\n idx = []\n types_path = os.path.join(types_dataset_path, split + '.del')\n with open(types_path, 'r') as file:\n for line in file:\n entity_id, type_list = line.split(\"\\t\", maxsplit=1)\n type_list = type_list.rstrip(\"\\n\")\n # iterate through hierarchical type structure\n for level, level_types in enumerate(json.loads(type_list)):\n if level == 0:\n continue\n for type_id in level_types:\n bin_type_id = hier_tuple_ids[(level, int(type_id))]\n y[int(entity_id), bin_type_id] = 1\n if split == 'train':\n train_freq[bin_type_id] += 1\n idx.append(int(entity_id))\n type_idx[split] = idx.copy()\n\n # compute weights for loss function\n pos_weights = []\n for class_count in train_freq:\n if class_count == 0:\n pos_weight = len(type_idx['train'])\n else:\n neg_count = len(type_idx['train']) - class_count\n pos_weight = neg_count / class_count\n pos_weights.append(pos_weight)\n\n # create output numpy arrays and tensors\n y = torch.from_numpy(y)\n pos_weights = torch.from_numpy(np.array(pos_weights))\n idx = {split: torch.from_numpy(np.array(entity_ids)) for split, entity_ids in type_idx.items()}\n return y, idx, pos_weights, hier_tuple_ids, hier, hierarchical_depth, global2local, hierarchy_classes\n\n\n def _init_weight(self, m):\n if isinstance(m, torch.nn.Linear):\n torch.nn.init.normal_(m.weight, std=0.1)" ]
[ [ "torch.stack", "torch.nn.Linear", "torch.logical_or", "torch.nn.BatchNorm1d", "torch.nn.init.normal_", "torch.nn.ReLU", "torch.from_numpy", "torch.nn.ModuleList", "torch.max", "numpy.array", "torch.sigmoid", "torch.cat", "torch.nn.Dropout" ] ]
EricPWilliamson/bhattacharyya-distance
[ "d67498d58bed342151c9d820a520254a503abdc8" ]
[ "bhatta_dist.py" ]
[ "\"\"\"\r\nThe function bhatta_dist() calculates the Bhattacharyya distance between two classes on a single feature.\r\n The distance is positively correlated to the class separation of this feature. Four different methods are\r\n provided for calculating the Bhattacharyya coefficient.\r\n\r\nCreated on 4/14/2018\r\nAuthor: Eric Williamson ([email protected])\r\n\"\"\"\r\nimport numpy as np\r\nfrom math import sqrt\r\nfrom scipy.stats import gaussian_kde\r\n\r\ndef bhatta_dist(X1, X2, method='continuous'):\r\n #Calculate the Bhattacharyya distance between X1 and X2. X1 and X2 should be 1D numpy arrays representing the same\r\n # feature in two separate classes. \r\n\r\n def get_density(x, cov_factor=0.1):\r\n #Produces a continuous density function for the data in 'x'. Some benefit may be gained from adjusting the cov_factor.\r\n density = gaussian_kde(x)\r\n density.covariance_factor = lambda:cov_factor\r\n density._compute_covariance()\r\n return density\r\n\r\n #Combine X1 and X2, we'll use it later:\r\n cX = np.concatenate((X1,X2))\r\n\r\n if method == 'noiseless':\r\n ###This method works well when the feature is qualitative (rather than quantitative). Each unique value is\r\n ### treated as an individual bin.\r\n uX = np.unique(cX)\r\n A1 = len(X1) * (max(cX)-min(cX)) / len(uX)\r\n A2 = len(X2) * (max(cX)-min(cX)) / len(uX)\r\n bht = 0\r\n for x in uX:\r\n p1 = (X1==x).sum() / A1\r\n p2 = (X2==x).sum() / A2\r\n bht += sqrt(p1*p2) * (max(cX)-min(cX))/len(uX)\r\n\r\n elif method == 'hist':\r\n ###Bin the values into a hardcoded number of bins (This is sensitive to N_BINS)\r\n N_BINS = 10\r\n #Bin the values:\r\n h1 = np.histogram(X1,bins=N_BINS,range=(min(cX),max(cX)), density=True)[0]\r\n h2 = np.histogram(X2,bins=N_BINS,range=(min(cX),max(cX)), density=True)[0]\r\n #Calc coeff from bin densities:\r\n bht = 0\r\n for i in range(N_BINS):\r\n p1 = h1[i]\r\n p2 = h2[i]\r\n bht += sqrt(p1*p2) * (max(cX)-min(cX))/N_BINS\r\n\r\n elif method == 'autohist':\r\n ###Bin the values into bins automatically set by np.histogram:\r\n #Create bins from the combined sets:\r\n # bins = np.histogram(cX, bins='fd')[1]\r\n bins = np.histogram(cX, bins='doane')[1] #Seems to work best\r\n # bins = np.histogram(cX, bins='auto')[1]\r\n\r\n h1 = np.histogram(X1,bins=bins, density=True)[0]\r\n h2 = np.histogram(X2,bins=bins, density=True)[0]\r\n\r\n #Calc coeff from bin densities:\r\n bht = 0\r\n for i in range(len(h1)):\r\n p1 = h1[i]\r\n p2 = h2[i]\r\n bht += sqrt(p1*p2) * (max(cX)-min(cX))/len(h1)\r\n\r\n elif method == 'continuous':\r\n ###Use a continuous density function to calculate the coefficient (This is the most consistent, but also slightly slow):\r\n N_STEPS = 200\r\n #Get density functions:\r\n d1 = get_density(X1)\r\n d2 = get_density(X2)\r\n #Calc coeff:\r\n xs = np.linspace(min(cX),max(cX),N_STEPS)\r\n bht = 0\r\n for x in xs:\r\n p1 = d1(x)\r\n p2 = d2(x)\r\n bht += sqrt(p1*p2)*(max(cX)-min(cX))/N_STEPS\r\n\r\n else:\r\n raise ValueError(\"The value of the 'method' parameter does not match any known method\")\r\n\r\n ###Lastly, convert the coefficient into distance:\r\n if bht==0:\r\n return float('Inf')\r\n else:\r\n return -np.log(bht)\r\n\r\n\r\ndef bhatta_dist2(x, Y, Y_selection=None, method='continuous'):\r\n #Same as bhatta_dist, but takes different inputs. Takes a feature 'x' and separates it by class ('Y').\r\n if Y_selection is None:\r\n Y_selection = list(set(Y))\r\n #Make sure Y_selection is just 2 classes:\r\n if len(Y_selection) != 2:\r\n raise ValueError(\"Use parameter Y_selection to select just 2 classes.\")\r\n #Separate x into X1 and X2:\r\n X1 = np.array(x,dtype=np.float64)[Y==Y_selection[0]]\r\n X2 = np.array(x,dtype=np.float64)[Y==Y_selection[1]]\r\n #Plug X1 and X2 into bhatta_dist():\r\n return bhatta_dist(X1, X2, method=method)\r\n" ]
[ [ "numpy.histogram", "scipy.stats.gaussian_kde", "numpy.log", "numpy.array", "numpy.concatenate", "numpy.unique" ] ]
zenetio/AI-4-Clinical-Workflow
[ "7128f2eeafb5e5fc5a70e7c3770847ca1c924dea" ]
[ "src/inference/UNetInferenceAgent.py" ]
[ "\"\"\"\nContains class that runs inferencing\n\"\"\"\nimport torch\nimport numpy as np\n\nfrom networks.RecursiveUNet import UNet\n\nfrom utils.utils import med_reshape\n\nclass UNetInferenceAgent:\n \"\"\"\n Stores model and parameters and some methods to handle inferencing\n \"\"\"\n def __init__(self, parameter_file_path='', model=None, device=\"cpu\", patch_size=64):\n\n self.model = model\n self.patch_size = patch_size\n self.device = device\n\n if model is None:\n self.model = UNet(num_classes=3)\n\n if parameter_file_path:\n self.model.load_state_dict(torch.load(parameter_file_path, map_location=self.device))\n\n self.model.to(device)\n\n def single_volume_inference_unpadded(self, volume):\n \"\"\"\n Runs inference on a single volume of arbitrary patch size,\n padding it to the conformant size first\n\n Arguments:\n volume {Numpy array} -- 3D array representing the volume\n\n Returns:\n 3D NumPy array with prediction mask\n \"\"\"\n \n # normalize the data volume \n image = (volume.astype(np.single) - np.min(volume))/(np.max(volume) - np.min(volume))\n # reshape the image volume to the same patch size used for training\n img_reshaped = med_reshape(image, new_shape=(self.patch_size, self.patch_size, image.shape[2]))\n # create a new 3d mask to store predicted results\n mask3d = np.zeros(img_reshaped.shape)\n # iterate over the image array and predict the all the slices\n for slc_idx in range(img_reshaped.shape[2]):\n # compute for each slice\n slc = torch.from_numpy(img_reshaped[:,:,slc_idx].astype(np.single)).unsqueeze(0).unsqueeze(0)\n # make prediction\n pred = self.model(slc.to(self.device))\n pred = np.squeeze(pred.cpu().detach())\n # store predicted data\n mask3d[:,:,slc_idx] = torch.argmax(pred, dim=0)\n # return the predicted volume\n return mask3d\n\n def single_volume_inference(self, volume):\n \"\"\"\n Runs inference on a single volume of conformant patch size\n\n Arguments:\n volume {Numpy array} -- 3D array representing the volume\n\n Returns:\n 3D NumPy array with prediction mask\n \"\"\"\n self.model.eval()\n\n # Assuming volume is a numpy array of shape [X,Y,Z] and we need to slice X axis\n slices = []\n\n # Write code that will create mask for each slice across the X (0th) dimension. After \n # that, put all slices into a 3D Numpy array. You can verify if your method is \n # correct by running it on one of the volumes in your training set and comparing \n # with the label in 3D Slicer.\n \n # normalize\n image = (volume.astype(np.single) - np.min(volume))/(np.max(volume) - np.min(volume))\n \n new_image = med_reshape(image, new_shape=(self.patch_size, self.patch_size, image.shape[2]))\n mask3d = np.zeros(new_image.shape)\n \n for slc_ix in range(new_image.shape[2]):\n tsr_test = torch.from_numpy(new_image[:,:,slc_ix].astype(np.single)).unsqueeze(0).unsqueeze(0)\n #image = torch.from_numpy(self.data[slc[0]][\"image\"][:,:,slc[1]]).unsqueeze(0)\n #tsr_test = torch.from_numpy(slc.astype(np.single)).unsqueeze(0).unsqueeze(0)\n pred = self.model(tsr_test.to(self.device))\n pred = np.squeeze(pred.cpu().detach())\n mask3d[:,:,slc_ix] = torch.argmax(pred, dim=0)\n\n return mask3d\n" ]
[ [ "torch.load", "numpy.zeros", "torch.argmax", "numpy.max", "numpy.min" ] ]
WouterKoch/Naturalis_data_preparation
[ "05d60d2913838297d30959ccf1388028ac8553bc" ]
[ "combine.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nimport sys\nimport hashlib\n\ndef generateId(image_url, prefix, exisiting_ids):\n id = f\"{prefix}:{hashlib.md5(image_url.encode()).hexdigest()}\"\n # while id in exisiting_ids:\n # print(f\"id {id} exists!\")\n # image_url = image_url + \"1\"\n # id = f\"{prefix}:{hashlib.blake2s(image_url.encode()).hexdigest()}\"\n # print(f\"Changed to {id}\")\n return id\n\n\ndef combine(taxonfiles, imagefiles, outputfolder, previousImageList):\n tqdm.pandas()\n taxa = pd.read_csv(taxonfiles[0])\n for i, file in enumerate(taxonfiles):\n if i > 0:\n taxa = pd.concat([taxa, pd.read_csv(file)], ignore_index=True)\n\n taxa.drop_duplicates(subset=['taxon_id_at_source'], inplace=True)\n taxa['taxon_id_at_source'] = taxa['taxon_id_at_source'].apply(lambda x: \"NBIC:\" + str(int(x)))\n taxa['accepted_taxon_id_at_source'] = taxa['accepted_taxon_id_at_source'].apply(lambda x: \"NBIC:\" + str(int(x)))\n\n if 'specific_epithet' not in taxa.columns.values:\n taxa['specific_epithet'] = \"\"\n\n if 'infraspecific_epithet' not in taxa.columns.values:\n taxa['infraspecific_epithet'] = \"\"\n\n taxa.to_csv(os.path.join(outputfolder, 'taxa.csv'), index=False)\n\n print(f\"{len(taxa)} taxa\")\n\n\n images = pd.read_csv(imagefiles[0])\n images[\"dataset\"] = imagefiles[0].split(\"/\")[-1].split(\"_\")[0].upper()\n for i, file in enumerate(imagefiles):\n if i > 0:\n adding = pd.read_csv(file)\n adding[\"dataset\"] = imagefiles[i].split(\"/\")[-1].split(\"_\")[0].upper()\n images = pd.concat([images, adding], ignore_index=True)\n\n if 'sex' not in images.columns.values:\n images['sex'] = \"\"\n if 'morph' not in images.columns.values:\n images['morph'] = \"\"\n if 'morph_id' not in images.columns.values:\n images['morph_id'] = \"\"\n if 'rijkdriehoeksstelsel_x' not in images.columns.values:\n images['rijkdriehoeksstelsel_x'] = \"\"\n if 'rijkdriehoeksstelsel_y' not in images.columns.values:\n images['rijkdriehoeksstelsel_y'] = \"\"\n\n images['taxon_id_at_source'] = images['taxon_id_at_source'].apply(lambda x: \"NBIC:\" + str(int(x)))\n images['accepted_taxon_id_at_source'] = images['accepted_taxon_id_at_source'].apply(lambda x: \"NBIC:\" + str(int(x)))\n\n images['location_latitude'] = images['location_latitude'].apply(lambda x: x if np.absolute(x) < 90 else 0)\n images['location_longitude'] = images['location_longitude'].apply(lambda x: x if np.absolute(x) < 180 else 0)\n\n images.drop_duplicates(subset=['image_url'], inplace=True)\n\n url_replacements = {\n 'https://purl.org/gbifnorway/img/ipt-specimens/barstow-garden/new/2011/P5159387.jpg': 'http://folk.ntnu.no/wouterk/replacements/P5159387.jpg',\n 'https://purl.org/gbifnorway/img/ipt-specimens/barstow-garden/new/2013/P6230493.jpg': 'http://folk.ntnu.no/wouterk/replacements/P6230493.jpg',\n 'https://purl.org/gbifnorway/img/ipt-specimens/barstow-garden/new/2011/P5159386.jpg': 'http://folk.ntnu.no/wouterk/replacements/P5159386.jpg',\n 'https://purl.org/gbifnorway/img/ipt-specimens/barstow-garden/new/2011/P5159381.jpg': 'http://folk.ntnu.no/wouterk/replacements/P5159381.jpg',\n 'https://purl.org/gbifnorway/img/ipt-specimens/barstow-garden/new/2011/P5159385.jpg': 'http://folk.ntnu.no/wouterk/replacements/P5159385.jpg',\n 'https://purl.org/gbifnorway/img/ipt-specimens/barstow-garden/new/2011/P5159382.jpg': 'http://folk.ntnu.no/wouterk/replacements/P5159382.jpg',\n 'https://purl.org/gbifnorway/img/ipt-specimens/barstow-garden/new/2011/P5159383.jpg': 'http://folk.ntnu.no/wouterk/replacements/P5159383.jpg',\n 'https://www.dagbladet.no/images/70576123.jpg?imageId=70576123&width=980&height=559&compression=80': 'http://folk.ntnu.no/wouterk/replacements/70576123.jpg',\n 'https://image.klikk.no/6732049.jpg?imageId=6732049&x=0&y=0&cropw=100&croph=85.581395348837&width=1600&height=913': 'http://folk.ntnu.no/wouterk/replacements/6732049.jpg',\n 'https://image.klikk.no/6732047.jpg?imageId=6732047&width=500&height=285': 'http://folk.ntnu.no/wouterk/replacements/6732047.jpg',\n 'https://image.forskning.no/1559391.jpg?imageId=1559391&width=706&height=403': 'http://folk.ntnu.no/wouterk/replacements/1559391.jpg',\n 'https://image.klikk.no/6732051.jpg?imageId=6732051&x=0&y=0&cropw=100&croph=85.549964054637&width=1600&height=912': 'http://folk.ntnu.no/wouterk/replacements/6732051.jpg',\n 'https://image.klikk.no/6732046.jpg?imageId=6732046&x=0&y=0&cropw=100&croph=83.4375&width=468&height=267': 'http://folk.ntnu.no/wouterk/replacements/6732046.jpg',\n 'https://image.klikk.no/6732048.jpg?imageId=6732048&width=1600&height=912': 'http://folk.ntnu.no/wouterk/replacements/6732048.jpg',\n 'https://1jv6g9n0pik3nvjug2t92dlh-wpengine.netdna-ssl.com/wp-content/uploads/2015/07/thinkstockphotos-178588991-352x431.jpg': 'http://folk.ntnu.no/wouterk/replacements/thinkstockphotos-178588991.jpg',\n 'https://1jv6g9n0pik3nvjug2t92dlh-wpengine.netdna-ssl.com/wp-content/uploads/2015/07/ulv-1100x551.jpg': 'http://folk.ntnu.no/wouterk/replacements/ulv-1100x551.jpg',\n 'https://1jv6g9n0pik3nvjug2t92dlh-wpengine.netdna-ssl.com/wp-content/uploads/2015/06/ulvespor_mogens_totsas-300x201.jpg': 'http://folk.ntnu.no/wouterk/replacements/ulvespor_mogens_totsas.jpg',\n 'https://1jv6g9n0pik3nvjug2t92dlh-wpengine.netdna-ssl.com/wp-content/uploads/2015/06/ulv_vinter-300x207.jpg': 'http://folk.ntnu.no/wouterk/replacements/ulv_vinter-300x207.jpg',\n 'https://1jv6g9n0pik3nvjug2t92dlh-wpengine.netdna-ssl.com/wp-content/uploads/2015/06/ulv_1-300x234.jpg': 'http://folk.ntnu.no/wouterk/replacements/ulv_1.jpg',\n 'https://image.forskning.no/1363982.jpg?imageId=1363982&x=0&y=11.714285714286&cropw=100&croph=86.714285714286&width=1050&height=608': 'http://folk.ntnu.no/wouterk/replacements/1363982.jpg',\n 'https://image.forskning.no/1347259.jpg?imageId=1347259&x=0&y=7.1005917159763&cropw=100&croph=42.011834319527&width=1058&height=604': 'http://folk.ntnu.no/wouterk/replacements/1347259.jpg',\n 'https://www.dagbladet.no/images/63196038.jpg?imageId=63196038&x=0&y=0&cropw=100.00&croph=100.00&width=980&height=552&compression=80': 'http://folk.ntnu.no/wouterk/replacements/63196038.jpg',\n 'https://www.dagbladet.no/images/63196036.jpg?imageId=63196036&x=0&y=0&cropw=100.00&croph=100.00&width=1470&height=754.5': 'http://folk.ntnu.no/wouterk/replacements/63196036.jpg',\n 'https://www.miljodirektoratet.no/globalassets/bilder/nyhetsbilder-2020/jerv-bard-bredesen.jpg?w=1150': 'http://folk.ntnu.no/wouterk/replacements/jerv-bard-bredesen.jpg',\n 'https://www.regjeringen.no/contentassets/b895dbabc684463fb805f5f0e970e2fc/dn_006326.jpg?preset=article&v=-444535606': 'http://folk.ntnu.no/wouterk/replacements/dn_006326.jpg',\n 'https://www.dagbladet.no/images/63445639.jpg?imageId=63445639&x=0&y=0&cropw=100.00&croph=100.00&width=1470&height=831': 'http://folk.ntnu.no/wouterk/replacements/63445639.jpg',\n 'https://www.dagbladet.no/images/63445641.jpg?imageId=63445641&x=0&y=0&cropw=100.00&croph=100.00&width=980&height=554&compression=80': 'http://folk.ntnu.no/wouterk/replacements/63445641.jpg',\n 'https://www.dagbladet.no/images/67460750.jpg?imageId=67460750&width=980&height=559&compression=80': 'http://folk.ntnu.no/wouterk/replacements/67460750.jpg',\n 'https://www.dagbladet.no/images/63947838.jpg?imageId=63947838&x=2.0040080160321&y=31.108144192256&cropw=95.145631067961&croph=39.301874595992&width=938&height=582&compression=80': 'http://folk.ntnu.no/wouterk/replacements/63947838.jpg',\n 'https://www.dagbladet.no/images/63971492.jpg?imageId=63971492&width=980&height=559&compression=80': 'http://folk.ntnu.no/wouterk/replacements/63971492.jpg',\n 'https://www.nysgjerrigper.no/siteassets/bilder-artikler/2017-2/isbjorn-foto-shutterstock.jpg?transform=DownFit&width=700': 'http://folk.ntnu.no/wouterk/replacements/isbjorn-foto-shutterstock.jpg',\n 'https://image.forskning.no/1348957.jpg?imageId=1348957&width=1058&height=604': 'http://folk.ntnu.no/wouterk/replacements/1348957.jpg',\n }\n\n images['image_url'] = images['image_url'].apply(lambda x: url_replacements[x] if x in url_replacements.keys() else x)\n\n\n # Ensure using the same id's as last time\n lasttime = pd.read_csv(previousImageList, usecols=[\"image_url\", \"image_id\"])\n lasttime.columns = [\"image_url\", \"old_image_id\"]\n\n images = pd.merge(images, lasttime, on=\"image_url\", how=\"left\")\n existing_ids = lasttime[\"old_image_id\"].to_list()\n\n images[\"image_id\"] = images.progress_apply(lambda x: x[\"old_image_id\"] if not pd.isna(x[\"old_image_id\"]) else (x[\"image_id\"] if \"AO:\" in x[\"image_id\"] else generateId(x[\"image_url\"], x[\"dataset\"], existing_ids)) , axis=1)\n images.drop([\"old_image_id\",\"dataset\"], axis=1, inplace=True)\n\n images.to_csv(os.path.join(outputfolder, 'images.csv'), index=False)\n # images = images[images['image_url'].apply(lambda x: x in url_replacements.keys())]\n # images['image_url'] = images['image_url'].apply(lambda x: url_replacements[x])\n # images.to_csv('Output/images_replacements.csv', index=False)\n print(f\"{len(images)} images\")\n\n taxon_counts = pd.DataFrame(taxa.value_counts(subset=['taxon_full_name']))\n taxon_counts.columns = ['Count']\n\n print(f\"{len(images.drop_duplicates(subset=['image_id']))} image id's\")\n\n\n print('Taxon names occurring more than once in taxa:')\n print(taxon_counts[taxon_counts['Count'] > 1])\n print('Taxon names in images but not in taxa:', list(set(images['taxon_full_name'].to_list()) - set(taxa['taxon_full_name'].to_list())))\n\n\n\n\n\n\nif __name__ == \"__main__\":\n print(\"USAGE: combine(inputfiles, outputfolder)\")\n" ]
[ [ "pandas.read_csv", "pandas.merge", "pandas.concat", "numpy.absolute", "pandas.isna" ] ]
dcdanko/MetaSUB_CAP
[ "db5672b0206afb3ffe3204b0577a4a5f84b9bcd4" ]
[ "scripts/beta_diversity_stats.py" ]
[ "#! /usr/bin/env python3\n\n\nimport sys\nimport click\nfrom scipy.spatial.distance import pdist, squareform\nfrom scipy.stats import gmean, entropy\nfrom numpy.linalg import norm\nimport numpy as np\nfrom math import sqrt\nfrom json import dumps as jdumps\nimport pandas as pd\n\n\nclass LevelNotFoundException(Exception):\n pass\n\n\ndef checkLevel(taxon, level):\n if level == 'species':\n return ('s__' in taxon) and ('t__' not in taxon)\n elif level == 'genus':\n return ('g__' in taxon) and ('s__' not in taxon)\n raise LevelNotFoundException()\n\n\ndef clr(X):\n _X = X + 0.0000001\n _X = _X / norm(_X, ord=1)\n g = gmean(_X)\n _X = np.divide(_X, g)\n _X = np.log(_X)\n return _X\n\n\ndef rhoProportionality(P, Q):\n _P, _Q = clr(P), clr(Q)\n N = np.var(_P - _Q)\n D = np.var(_P) + np.var(_Q)\n return 1 - (N / D)\n\n\ndef jensenShannonDistance(P, Q):\n _P = P / norm(P, ord=1)\n _Q = Q / norm(Q, ord=1)\n _M = 0.5 * (_P + _Q)\n J = 0.5 * (entropy(_P, _M) + entropy(_Q, _M))\n return sqrt(J)\n\n\nclass SampleSet:\n\n def __init__(self, tool, mpas):\n self.tool = tool\n self.mpaFiles = mpas\n\n def parse(self, level):\n mpas = {name: Sample.parseMPA(name, mpaf, level).abunds\n for name, mpaf in self.mpaFiles}\n self.mpas = pd.DataFrame(mpas).transpose()\n self.mpas.fillna(value=0, inplace=True)\n\n def distanceMatrix(self, metric):\n X = self.mpas.as_matrix()\n if metric == 'jensen_shannon_distance':\n distm = squareform(pdist(X, jensenShannonDistance))\n elif metric == 'rho_proportionality':\n distm = squareform(pdist(X, rhoProportionality))\n distm = pd.DataFrame(distm, \n index=self.mpas.index,\n columns=self.mpas.index)\n return distm.to_dict()\n\n\nclass Sample:\n\n def __init__(self, sname, level):\n self.sname = sname\n self.level = level\n self.abunds = {}\n\n def addLine(self, line):\n taxon, abund = line.split()\n if checkLevel(taxon, self.level):\n self.abunds[taxon] = float(abund)\n\n @classmethod\n def parseMPA(ctype, name, mpaFile, level):\n sample = Sample(name, level)\n with open(mpaFile) as mF:\n for line in mF:\n sample.addLine(line)\n return sample\n\n\[email protected]()\[email protected]('-t', '--tool-set', nargs=3, multiple=True)\ndef main(tool_set):\n toolSets = tool_set\n condensed = {}\n for toolSet in toolSets:\n tool = toolSet[0]\n sampleName = toolSet[1]\n mpa = toolSet[2]\n try:\n condensed[tool].append((sampleName, mpa))\n except KeyError:\n condensed[tool] = [(sampleName, mpa)]\n sampleSets = [SampleSet(tool, mpas) for tool, mpas in condensed.items()]\n\n obj = {\n 'species': {\n 'jensen_shannon_distance': {},\n 'rho_proportionality': {},\n },\n 'genus': {\n 'jensen_shannon_distance': {},\n 'rho_proportionality': {},\n }\n }\n for level in obj.keys():\n for sampleSet in sampleSets:\n sampleSet.parse(level)\n tool = sampleSet.tool\n for metric in obj[level].keys():\n obj[level][metric][tool] = sampleSet.distanceMatrix(metric)\n sys.stdout.write(jdumps(obj))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "scipy.spatial.distance.pdist", "numpy.divide", "scipy.stats.gmean", "numpy.var", "pandas.DataFrame", "scipy.stats.entropy", "numpy.log", "numpy.linalg.norm" ] ]
PratyushTripathy/momepy
[ "eac89eaff63dd6cb35dfd9a736981723ec77f496" ]
[ "momepy/graph.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# connectivity.py\n# definitions of connectivity characters\nimport math\nimport warnings\n\nimport networkx as nx\nimport numpy as np\nfrom tqdm import tqdm\n\n__all__ = [\n \"node_degree\",\n \"meshedness\",\n \"mean_node_dist\",\n \"cds_length\",\n \"mean_node_degree\",\n \"proportion\",\n \"cyclomatic\",\n \"edge_node_ratio\",\n \"gamma\",\n \"clustering\",\n \"local_closeness_centrality\",\n \"closeness_centrality\",\n \"betweenness_centrality\",\n \"local_betweenness_centrality\",\n \"local_straightness_centrality\",\n \"straightness_centrality\",\n \"subgraph\",\n \"mean_nodes\",\n]\n\n\ndef node_degree(graph, name=\"degree\"):\n \"\"\"\n Calculates node degree for each node.\n\n Wrapper around ``networkx.degree()``.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n name : str (default 'degree')\n calculated attribute name\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.node_degree(network_graph)\n \"\"\"\n netx = graph.copy()\n\n degree = dict(nx.degree(netx))\n nx.set_node_attributes(netx, degree, name)\n\n return netx\n\n\ndef _meshedness(graph):\n \"\"\"\n Calculates meshedness of a graph.\n \"\"\"\n e = graph.number_of_edges()\n v = graph.number_of_nodes()\n return (e - v + 1) / (2 * v - 5)\n\n\ndef meshedness(graph, radius=5, name=\"meshedness\", distance=None, verbose=True):\n \"\"\"\n Calculates meshedness for subgraph around each node if radius is set, or for\n whole graph, if ``radius=None``.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in distance\n attribute.\n\n .. math::\n \\\\alpha=\\\\frac{e-v+1}{2 v-5}\n\n where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.\n\n Adapted from :cite:`feliciotti2018`.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int, optional\n Include all neighbors of distance <= radius from n\n name : str, optional\n calculated attribute name\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph if radius is set\n float\n meshedness for graph if ``radius=None``\n\n Examples\n --------\n >>> network_graph = mm.meshedness(network_graph, radius=800, distance='edge_length')\n \"\"\"\n netx = graph.copy()\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _meshedness(\n sub\n ) # save value calulated for subgraph to node\n\n return netx\n\n return _meshedness(netx)\n\n\ndef mean_node_dist(graph, name=\"meanlen\", length=\"mm_len\", verbose=True):\n \"\"\"\n Calculates mean distance to neighbouring nodes.\n\n Mean of values in ``length`` attribute.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n name : str, optional\n calculated attribute name\n length : str, optional\n name of attribute of segment length (geographical)\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.mean_node_dist(network_graph)\n\n \"\"\"\n netx = graph.copy()\n\n for n, nbrs in tqdm(netx.adj.items(), total=len(netx), disable=not verbose):\n lengths = []\n for nbr, keydict in nbrs.items():\n for key, eattr in keydict.items():\n lengths.append(eattr[length])\n netx.nodes[n][name] = np.mean(lengths)\n\n return netx\n\n\ndef _cds_length(graph, mode, length):\n \"\"\"\n Calculates cul-de-sac length in a graph.\n \"\"\"\n lens = []\n for u, v, k, cds in graph.edges.data(\"cdsbool\", keys=True):\n if cds:\n lens.append(graph[u][v][k][length])\n if mode == \"sum\":\n return sum(lens)\n if mode == \"mean\":\n return np.mean(lens)\n raise ValueError(\"Mode {} is not supported. Use 'sum' or 'mean'.\".format(mode))\n\n\ndef cds_length(\n graph,\n radius=5,\n mode=\"sum\",\n name=\"cds_len\",\n degree=\"degree\",\n length=\"mm_len\",\n distance=None,\n verbose=True,\n):\n \"\"\"\n Calculates length of cul-de-sacs for subgraph around each node if radius is set, or for\n whole graph, if ``radius=None``.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in distance\n attribute.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius : int\n Include all neighbors of distance <= radius from n\n mode : str (default 'sum')\n if ``'sum'``, calculate total length, if ``'mean'`` calculate mean length\n name : str, optional\n calculated attribute name\n degree : str\n name of attribute of node degree (:py:func:`momepy.node_degree`)\n length : str, optional\n name of attribute of segment length (geographical)\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n\n Returns\n -------\n Graph\n networkx.Graph if radius is set\n float\n length of cul-de-sacs for graph if ``radius=None``\n\n Examples\n --------\n >>> network_graph = mm.cds_length(network_graph, radius=9, mode='mean')\n \"\"\"\n # node degree needed beforehand\n netx = graph.copy()\n\n for u, v, k in netx.edges(keys=True):\n if netx.nodes[u][degree] == 1 or netx.nodes[v][degree] == 1:\n netx[u][v][k][\"cdsbool\"] = True\n else:\n netx[u][v][k][\"cdsbool\"] = False\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _cds_length(\n sub, mode=mode, length=length\n ) # save value calculated for subgraph to node\n\n return netx\n\n return _cds_length(netx, mode=mode, length=length)\n\n\ndef _mean_node_degree(graph, degree):\n \"\"\"\n Calculates mean node degree in a graph.\n \"\"\"\n return np.mean(list(dict(graph.nodes(degree)).values()))\n\n\ndef mean_node_degree(\n graph, radius=5, name=\"mean_nd\", degree=\"degree\", distance=None, verbose=True\n):\n \"\"\"\n Calculates mean node degree for subgraph around each node if radius is set, or for\n whole graph, if ``radius=None``.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n radius defining the extent of subgraph\n name : str, optional\n calculated attribute name\n degree : str\n name of attribute of node degree (:py:func:`momepy.node_degree`)\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph if radius is set\n float\n mean node degree for graph if ``radius=None``\n\n Examples\n --------\n >>> network_graph = mm.mean_node_degree(network_graph, radius=3)\n \"\"\"\n netx = graph.copy()\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _mean_node_degree(sub, degree=degree)\n\n return netx\n\n return _mean_node_degree(netx, degree=degree)\n\n\ndef _proportion(graph, degree):\n \"\"\"\n Calculates the proportion of intersection types in a graph.\n \"\"\"\n import collections\n\n values = list(dict(graph.nodes(degree)).values())\n counts = collections.Counter(values)\n return counts\n\n\ndef proportion(\n graph,\n radius=5,\n three=None,\n four=None,\n dead=None,\n degree=\"degree\",\n distance=None,\n verbose=True,\n):\n \"\"\"\n Calculates the proportion of intersection types for subgraph around each node if radius is set, or for\n whole graph, if ``radius=None``.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n Include all neighbors of distance <= radius from n\n three : str, optional\n attribute name for 3-way intersections proportion\n four : str, optional\n attribute name for 4-way intersections proportion\n dead : str, optional\n attribute name for deadends proportion\n degree : str\n name of attribute of node degree (:py:func:`momepy.node_degree`)\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph if radius is set\n dict\n dict with proportions for graph if ``radius=None``\n\n Examples\n --------\n >>> network_graph = mm.proportion(network_graph, three='threeway', four='fourway', dead='deadends')\n \"\"\"\n if not three and not four and not dead:\n raise ValueError(\n \"Nothing to calculate. Define names for at least one proportion to be calculated: three, four, dead.\"\n )\n netx = graph.copy()\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n counts = _proportion(sub, degree=degree)\n if three:\n netx.nodes[n][three] = counts[3] / len(sub)\n if four:\n netx.nodes[n][four] = counts[4] / len(sub)\n if dead:\n netx.nodes[n][dead] = counts[1] / len(sub)\n return netx\n\n # add example to docs explaining keys\n counts = _proportion(netx, degree=degree)\n result = {}\n if three:\n result[three] = counts[3] / len(netx)\n if four:\n result[four] = counts[4] / len(netx)\n if dead:\n result[dead] = counts[1] / len(netx)\n\n return result\n\n\ndef _cyclomatic(graph):\n \"\"\"\n Calculates the cyclomatic complexity of a graph.\n \"\"\"\n e = graph.number_of_edges()\n v = graph.number_of_nodes()\n return e - v + 1\n\n\ndef cyclomatic(graph, radius=5, name=\"cyclomatic\", distance=None, verbose=True):\n \"\"\"\n Calculates cyclomatic complexity for subgraph around each node if radius is set, or for\n whole graph, if ``radius=None``.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute.\n\n .. math::\n \\\\alpha=e-v+1\n\n where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.\n\n Adapted from :cite:`bourdic2012`.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n Include all neighbors of distance <= radius from n\n name : str, optional\n calculated attribute name\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph if radius is set\n float\n cyclomatic complexity for graph if ``radius=None``\n\n Examples\n --------\n >>> network_graph = mm.cyclomatic(network_graph, radius=3)\n \"\"\"\n netx = graph.copy()\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _cyclomatic(\n sub\n ) # save value calulated for subgraph to node\n\n return netx\n\n return _cyclomatic(netx)\n\n\ndef _edge_node_ratio(graph):\n \"\"\"\n Calculates edge / node ratio of a graph.\n \"\"\"\n e = graph.number_of_edges()\n v = graph.number_of_nodes()\n return e / v\n\n\ndef edge_node_ratio(\n graph, radius=5, name=\"edge_node_ratio\", distance=None, verbose=True\n):\n \"\"\"\n Calculates edge / node ratio for subgraph around each node if radius is set, or for\n whole graph, if ``radius=None``.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute.\n\n .. math::\n \\\\alpha=e/v\n\n where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.\n\n Adapted from :cite:`dibble2017`.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n Include all neighbors of distance <= radius from n\n name : str, optional\n calculated attribute name\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph if radius is set\n float\n edge / node ratio for graph if ``radius=None``\n\n Examples\n --------\n >>> network_graph = mm.edge_node_ratio(network_graph, radius=3)\n \"\"\"\n netx = graph.copy()\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _edge_node_ratio(\n sub\n ) # save value calulated for subgraph to node\n\n return netx\n\n return _edge_node_ratio(netx)\n\n\ndef _gamma(graph):\n \"\"\"\n Calculates gamma index of a graph.\n \"\"\"\n e = graph.number_of_edges()\n v = graph.number_of_nodes()\n if v == 2:\n return np.nan\n return e / (3 * (v - 2)) # save value calulated for subgraph to node\n\n\ndef gamma(graph, radius=5, name=\"gamma\", distance=None, verbose=True):\n \"\"\"\n Calculates connectivity gamma index for subgraph around each node if radius is set, or for\n whole graph, if ``radius=None``.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute.\n\n .. math::\n \\\\alpha=\\\\frac{e}{3(v-2)}\n\n where :math:`e` is the number of edges in subgraph and :math:`v` is the number of nodes in subgraph.\n\n Adapted from :cite:`dibble2017`.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n Include all neighbors of distance <= radius from n\n name : str, optional\n calculated attribute name\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph if radius is set\n float\n gamma index for graph if ``radius=None``\n\n Examples\n --------\n >>> network_graph = mm.gamma(network_graph, radius=3)\n\n \"\"\"\n netx = graph.copy()\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _gamma(sub)\n\n return netx\n\n return _gamma(netx)\n\n\ndef clustering(graph, name=\"cluster\"):\n \"\"\"\n Calculates the squares clustering coefficient for nodes.\n\n Wrapper around ``networkx.square_clustering``.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n name : str, optional\n calculated attribute name\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.clustering(network_graph)\n \"\"\"\n netx = graph.copy()\n\n vals = nx.square_clustering(netx)\n nx.set_node_attributes(netx, vals, name)\n\n return netx\n\n\ndef _closeness_centrality(G, u=None, length=None, wf_improved=True, len_graph=None):\n r\"\"\"Compute closeness centrality for nodes. Slight adaptation of networkx\n `closeness_centrality` to allow normalisation for local closeness.\n Adapted script used in networkx.\n\n Closeness centrality [1]_ of a node `u` is the reciprocal of the\n average shortest path distance to `u` over all `n-1` reachable nodes.\n\n .. math::\n\n C(u) = \\frac{n - 1}{\\sum_{v=1}^{n-1} d(v, u)},\n\n where `d(v, u)` is the shortest-path distance between `v` and `u`,\n and `n` is the number of nodes that can reach `u`. Notice that the\n closeness distance function computes the incoming distance to `u`\n for directed graphs. To use outward distance, act on `G.reverse()`.\n\n Notice that higher values of closeness indicate higher centrality.\n\n Wasserman and Faust propose an improved formula for graphs with\n more than one connected component. The result is \"a ratio of the\n fraction of actors in the group who are reachable, to the average\n distance\" from the reachable actors [2]_. You might think this\n scale factor is inverted but it is not. As is, nodes from small\n components receive a smaller closeness value. Letting `N` denote\n the number of nodes in the graph,\n\n .. math::\n\n C_{WF}(u) = \\frac{n-1}{N-1} \\frac{n - 1}{\\sum_{v=1}^{n-1} d(v, u)},\n\n Parameters\n ----------\n G : graph\n A NetworkX graph\n\n u : node, optional\n Return only the value for node u\n\n distance : edge attribute key, optional (default=None)\n Use the specified edge attribute as the edge distance in shortest\n path calculations\n\n len_graph : int\n length of complete graph\n\n Returns\n -------\n nodes : dictionary\n Dictionary of nodes with closeness centrality as the value.\n\n References\n ----------\n .. [1] Linton C. Freeman: Centrality in networks: I.\n Conceptual clarification. Social Networks 1:215-239, 1979.\n http://leonidzhukov.ru/hse/2013/socialnetworks/papers/freeman79-centrality.pdf\n .. [2] pg. 201 of Wasserman, S. and Faust, K.,\n Social Network Analysis: Methods and Applications, 1994,\n Cambridge University Press.\n \"\"\"\n\n if length is not None:\n import functools\n\n # use Dijkstra's algorithm with specified attribute as edge weight\n path_length = functools.partial(\n nx.single_source_dijkstra_path_length, weight=length\n )\n else:\n path_length = nx.single_source_shortest_path_length\n\n nodes = [u]\n closeness_centrality = {}\n for n in nodes:\n sp = dict(path_length(G, n))\n totsp = sum(sp.values())\n if totsp > 0.0 and len(G) > 1:\n closeness_centrality[n] = (len(sp) - 1.0) / totsp\n # normalize to number of nodes-1 in connected part\n s = (len(sp) - 1.0) / (len_graph - 1)\n closeness_centrality[n] *= s\n else:\n closeness_centrality[n] = 0.0\n\n return closeness_centrality[u]\n\n\ndef local_closeness_centrality(\n graph, radius=5, name=\"closeness\", distance=None, weight=None\n):\n \"\"\"\n Calculates local closeness for each node based on the defined distance.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute. Based on ``networkx.closeness_centrality``.\n\n Local closeness centrality of a node `u` is the reciprocal of the\n average shortest path distance to `u` over all `n-1` nodes within subgraph.\n\n .. math::\n\n C(u) = \\\\frac{n - 1}{\\\\sum_{v=1}^{n-1} d(v, u)},\n\n where :math:`d(v, u)` is the shortest-path distance between :math:`v` and :math:`u`,\n and :math:`n` is the number of nodes that can reach :math:`u`.\n\n Adapted from :cite:`porta2006`.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n Include all neighbors of distance <= radius from n\n name : str, optional\n calculated attribute name\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n during ego_graph generation.\n weight : str, optional\n Use the specified edge attribute as the edge distance in shortest\n path calculations in closeness centrality algorithm\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.local_closeness_centrality(network_graph, radius=400, distance='edge_length')\n\n \"\"\"\n warnings.warn(\n \"local_closeness_centrality() is deprecated and will be removed in momepy 0.4.0. \"\n \"Use closeness_centrality() instead.\",\n FutureWarning,\n )\n\n return closeness_centrality(\n graph=graph, radius=radius, name=name, distance=distance, weight=weight\n )\n\n\ndef closeness_centrality(\n graph,\n name=\"closeness\",\n weight=\"mm_len\",\n radius=None,\n distance=None,\n verbose=True,\n **kwargs\n):\n \"\"\"\n Calculates the closeness centrality for nodes.\n\n Wrapper around ``networkx.closeness_centrality``.\n\n Closeness centrality of a node `u` is the reciprocal of the\n average shortest path distance to `u` over all `n-1` nodes within reachable nodes.\n\n .. math::\n\n C(u) = \\\\frac{n - 1}{\\\\sum_{v=1}^{n-1} d(v, u)},\n\n where :math:`d(v, u)` is the shortest-path distance between :math:`v` and :math:`u`,\n and :math:`n` is the number of nodes that can reach :math:`u`.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n name : str, optional\n calculated attribute name\n weight : str (default 'mm_len')\n attribute holding the weight of edge (e.g. length, angle)\n radius: int\n Include all neighbors of distance <= radius from n\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n during ego_graph generation.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n **kwargs\n kwargs for ``networkx.closeness_centrality``\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.closeness_centrality(network_graph)\n \"\"\"\n netx = graph.copy()\n\n if radius:\n lengraph = len(netx)\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _closeness_centrality(\n sub, n, length=weight, len_graph=lengraph\n )\n else:\n vals = nx.closeness_centrality(netx, distance=weight, **kwargs)\n nx.set_node_attributes(netx, vals, name)\n\n return netx\n\n\ndef betweenness_centrality(\n graph,\n name=\"betweenness\",\n mode=\"nodes\",\n weight=\"mm_len\",\n endpoints=True,\n radius=None,\n distance=None,\n normalized=False,\n verbose=True,\n **kwargs\n):\n \"\"\"\n Calculates the shortest-path betweenness centrality for nodes.\n\n Wrapper around ``networkx.betweenness_centrality`` or ``networkx.edge_betweenness_centrality``.\n\n Betweenness centrality of a node `v` is the sum of the\n fraction of all-pairs shortest paths that pass through `v`\n\n .. math::\n\n c_B(v) =\\\\sum_{s,t \\\\in V} \\\\frac{\\\\sigma(s, t|v)}{\\\\sigma(s, t)}\n\n where `V` is the set of nodes, :math:`\\\\sigma(s, t)` is the number of\n shortest :math:`(s, t)`-paths, and :math:`\\\\sigma(s, t|v)` is the number of\n those paths passing through some node `v` other than `s, t`.\n If `s = t`, :math:`\\\\sigma(s, t) = 1`, and if `v` in `{s, t}``,\n :math:`\\\\sigma(s, t|v) = 0`.\n\n Betweenness centrality of an edge `e` is the sum of the\n fraction of all-pairs shortest paths that pass through `e`\n\n .. math::\n\n c_B(e) =\\\\sum_{s,t \\\\in V} \\\\frac{\\\\sigma(s, t|e)}{\\\\sigma(s, t)}\n\n where `V` is the set of nodes, :math:`\\\\sigma(s, t)` is the number of\n shortest :math:`(s, t)`-paths, and :math:`\\\\sigma(s, t|e)` is the number of\n those paths passing through edge `e`.\n\n Adapted from :cite:`porta2006`.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n name : str, optional\n calculated attribute name\n mode : str, default 'nodes'\n mode of betweenness calculation. 'node' for node-based, 'edges' for edge-based\n weight : str (default 'mm_len')\n attribute holding the weight of edge (e.g. length, angle)\n radius: int\n Include all neighbors of distance <= radius from n\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n during ego_graph generation.\n normalized : bool, optional\n If True the betweenness values are normalized by `2/((n-1)(n-2))`,\n where n is the number of nodes in subgraph.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n **kwargs\n kwargs for ``networkx.betweenness_centrality`` or ``networkx.edge_betweenness_centrality``\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.betweenness_centrality(network_graph)\n\n Notes\n -----\n In case of angular betweenness, implementation is based on \"Tasos Implementation\".\n \"\"\"\n netx = graph.copy()\n\n # has to be Graph not MultiGraph as MG is not supported by networkx2.4\n G = nx.Graph()\n for u, v, k, data in netx.edges(data=True, keys=True):\n if G.has_edge(u, v):\n if G[u][v][weight] > netx[u][v][k][weight]:\n nx.set_edge_attributes(G, {(u, v): data})\n else:\n G.add_edge(u, v, **data)\n\n if radius:\n for n in tqdm(G, total=len(G), disable=not verbose):\n sub = nx.ego_graph(\n G, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = nx.betweenness_centrality(\n sub, weight=weight, normalized=normalized, **kwargs\n )[n]\n\n elif mode == \"nodes\":\n vals = nx.betweenness_centrality(\n G, weight=weight, endpoints=endpoints, **kwargs\n )\n nx.set_node_attributes(netx, vals, name)\n elif mode == \"edges\":\n vals = nx.edge_betweenness_centrality(G, weight=weight, **kwargs)\n for u, v, k in netx.edges(keys=True):\n try:\n val = vals[u, v]\n except KeyError:\n val = vals[v, u]\n netx[u][v][k][name] = val\n else:\n raise ValueError(\n \"Mode {} is not supported. Use 'nodes' or 'edges'.\".format(mode)\n )\n\n return netx\n\n\ndef local_betweenness_centrality(\n graph,\n radius=5,\n name=\"betweenness\",\n distance=None,\n weight=None,\n normalized=False,\n **kwargs\n):\n \"\"\"\n Calculates the shortest-path betweenness centrality for nodes within subgraph.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute. Based on ``networkx.betweenness_centrality``.\n\n Betweenness centrality of a node `v` is the sum of the\n fraction of all-pairs shortest paths that pass through `v`\n\n .. math::\n\n c_B(v) =\\\\sum_{s,t \\\\in V} \\\\frac{\\\\sigma(s, t|v)}{\\\\sigma(s, t)}\n\n where `V` is the set of nodes, :math:`\\\\sigma(s, t)` is the number of\n shortest :math:`(s, t)`-paths, and :math:`\\\\sigma(s, t|v)` is the number of\n those paths passing through some node `v` other than `s, t`.\n If `s = t`, :math:`\\\\sigma(s, t) = 1`, and if `v` in `{s, t}``,\n :math:`\\\\sigma(s, t|v) = 0`.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n Include all neighbors of distance <= radius from n\n name : str, optional\n calculated attribute name\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n during ego_graph generation.\n weight : str, optional\n Use the specified edge attribute as the edge distance in shortest\n path calculations in closeness centrality algorithm\n normalized : bool, optional\n If True the betweenness values are normalized by `2/((n-1)(n-2))`,\n where n is the number of nodes in subgraph.\n **kwargs\n kwargs for ``networkx.betweenness_centrality_subset``\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.local_betweenness_centrality(network_graph, radius=800, distance='edge_length')\n\n \"\"\"\n warnings.warn(\n \"local_betweenness_centrality() is deprecated and will be removed in momepy 0.4.0. \"\n \"Use betweenness_centrality() instead.\",\n FutureWarning,\n )\n\n return betweenness_centrality(\n graph,\n radius=radius,\n name=name,\n distance=distance,\n weight=weight,\n normalized=normalized,\n **kwargs\n )\n\n\ndef _euclidean(n, m):\n \"\"\"helper for straightness\"\"\"\n return math.sqrt((n[0] - m[0]) ** 2 + (n[1] - m[1]) ** 2)\n\n\ndef _straightness_centrality(G, weight, normalized=True):\n \"\"\"\n Calculates straightness centrality.\n \"\"\"\n straightness_centrality = {}\n\n for n in G.nodes():\n straightness = 0\n sp = nx.single_source_dijkstra_path_length(G, n, weight=weight)\n\n if len(sp) > 0 and len(G) > 1:\n for target in sp:\n if n != target:\n network_dist = sp[target]\n euclidean_dist = _euclidean(n, target)\n straightness = straightness + (euclidean_dist / network_dist)\n straightness_centrality[n] = straightness * (1.0 / (len(G) - 1.0))\n # normalize to number of nodes-1 in connected part\n if normalized:\n if len(sp) > 1:\n s = (len(G) - 1.0) / (len(sp) - 1.0)\n straightness_centrality[n] *= s\n else:\n straightness_centrality[n] = 0\n else:\n straightness_centrality[n] = 0.0\n return straightness_centrality\n\n\ndef straightness_centrality(\n graph,\n weight=\"mm_len\",\n normalized=True,\n name=\"straightness\",\n radius=None,\n distance=None,\n verbose=True,\n):\n \"\"\"\n Calculates the straightness centrality for nodes.\n\n .. math::\n C_{S}(i)=\\\\frac{1}{n-1} \\\\sum_{j \\\\in V, j \\\\neq i} \\\\frac{d_{i j}^{E u}}{d_{i j}}\n\n where :math:`\\\\mathrm{d}^{\\\\mathrm{E} \\\\mathrm{u}}_{\\\\mathrm{ij}}` is the Euclidean distance\n between nodes `i` and `j` along a straight line.\n\n Adapted from :cite:`porta2006`.\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n weight : str (default 'mm_len')\n attribute holding length of edge\n normalized : bool\n normalize to number of nodes-1 in connected part (for local straightness\n is recommended to set to normalized False)\n name : str, optional\n calculated attribute name\n radius: int\n Include all neighbors of distance <= radius from n\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n during ego_graph generation.\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.straightness_centrality(network_graph)\n \"\"\"\n netx = graph.copy()\n\n if radius:\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n netx.nodes[n][name] = _straightness_centrality(\n sub, weight=weight, normalized=normalized\n )[n]\n else:\n vals = _straightness_centrality(netx, weight=weight, normalized=normalized)\n nx.set_node_attributes(netx, vals, name)\n\n return netx\n\n\ndef local_straightness_centrality(\n graph, radius=5, name=\"straightness\", distance=None, weight=\"mm_len\"\n):\n \"\"\"\n Calculates local straightness for each node based on the defined distance.\n\n Subgraph is generated around each node within set radius. If ``distance=None``,\n radius will define topological distance, otherwise it uses values in ``distance``\n attribute.\n\n .. math::\n C_{S}(i)=\\\\frac{1}{n-1} \\\\sum_{j \\\\in V, j \\\\neq i} \\\\frac{d_{i j}^{E u}}{d_{i j}}\n\n where :math:`\\\\mathrm{d}^{\\\\mathrm{E} \\\\mathrm{u}}_{\\\\mathrm{ij}}` is the Euclidean distance\n between nodes `i` and `j` along a straight line.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n Include all neighbors of distance <= radius from n\n name : str, optional\n calculated attribute name\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n during ego_graph generation.\n weight : str, optional\n Use the specified edge attribute as the edge distance in shortest\n path calculations in closeness centrality algorithm\n\n Returns\n -------\n Graph\n networkx.Graph\n\n\n Examples\n --------\n >>> network_graph = mm.local_straightness_centrality(network_graph, radius=400, distance='edge_length')\n\n \"\"\"\n warnings.warn(\n \"local_straightness_centrality() is deprecated and will be removed in momepy 0.4.0. \"\n \"Use straightness_centrality() instead.\",\n FutureWarning,\n )\n\n return straightness_centrality(\n graph=graph, radius=radius, name=name, distance=distance, weight=weight\n )\n\n\ndef subgraph(\n graph,\n radius=5,\n distance=None,\n meshedness=True,\n cds_length=True,\n mode=\"sum\",\n degree=\"degree\",\n length=\"mm_len\",\n mean_node_degree=True,\n proportion={3: True, 4: True, 0: True},\n cyclomatic=True,\n edge_node_ratio=True,\n gamma=True,\n local_closeness=True,\n closeness_weight=None,\n verbose=True,\n):\n \"\"\"\n Calculates all subgraph-based characters.\n\n Generating subgraph might be a time consuming activity. If we want to use the same\n subgraph for more characters, ``subgraph`` allows this by generating subgraph and\n then analysing it using selected options.\n\n\n Parameters\n ----------\n graph : networkx.Graph\n Graph representing street network.\n Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`\n radius: int\n radius defining the extent of subgraph\n distance : str, optional\n Use specified edge data key as distance.\n For example, setting ``distance=’weight’`` will use the edge ``weight`` to\n measure the distance from the node n.\n meshedness : bool, default True\n Calculate meshedness (True/False)\n cds_length : bool, default True\n Calculate cul-de-sac length (True/False)\n mode : str (defualt 'sum')\n if ``'sum'``, calculate total cds_length, if ``'mean'`` calculate mean cds_length\n degree : str\n name of attribute of node degree (:py:func:`momepy.node_degree`)\n length : str, default `mm_len`\n name of attribute of segment length (geographical)\n mean_node_degree : bool, default True\n Calculate mean node degree (True/False)\n proportion : dict, default {3: True, 4: True, 0: True}\n Calculate proportion {3: True/False, 4: True/False, 0: True/False}\n cyclomatic : bool, default True\n Calculate cyclomatic complexity (True/False)\n edge_node_ratio : bool, default True\n Calculate edge node ratio (True/False)\n gamma : bool, default True\n Calculate gamma index (True/False)\n local_closeness : bool, default True\n Calculate local closeness centrality (True/False)\n closeness_weight : str, optional\n Use the specified edge attribute as the edge distance in shortest\n path calculations in closeness centrality algorithm\n verbose : bool (default True)\n if True, shows progress bars in loops and indication of steps\n\n\n Returns\n -------\n Graph\n networkx.Graph\n\n Examples\n --------\n >>> network_graph = mm.subgraph(network_graph)\n \"\"\"\n\n netx = graph.copy()\n\n for n in tqdm(netx, total=len(netx), disable=not verbose):\n sub = nx.ego_graph(\n netx, n, radius=radius, distance=distance\n ) # define subgraph of steps=radius\n\n if meshedness:\n netx.nodes[n][\"meshedness\"] = _meshedness(sub)\n\n if cds_length:\n for u, v, k in netx.edges(keys=True):\n if netx.nodes[u][degree] == 1 or netx.nodes[v][degree] == 1:\n netx[u][v][k][\"cdsbool\"] = True\n else:\n netx[u][v][k][\"cdsbool\"] = False\n\n netx.nodes[n][\"cds_length\"] = _cds_length(sub, mode=mode, length=length)\n\n if mean_node_degree:\n netx.nodes[n][\"mean_node_degree\"] = _mean_node_degree(sub, degree=degree)\n\n if proportion:\n counts = _proportion(sub, degree=degree)\n if proportion[3]:\n netx.nodes[n][\"proportion_3\"] = counts[3] / len(sub)\n if proportion[4]:\n netx.nodes[n][\"proportion_4\"] = counts[4] / len(sub)\n if proportion[0]:\n netx.nodes[n][\"proportion_0\"] = counts[1] / len(sub)\n\n if cyclomatic:\n netx.nodes[n][\"cyclomatic\"] = _cyclomatic(sub)\n\n if edge_node_ratio:\n netx.nodes[n][\"edge_node_ratio\"] = _edge_node_ratio(sub)\n\n if gamma:\n netx.nodes[n][\"gamma\"] = _gamma(sub)\n\n if local_closeness:\n lengraph = len(netx)\n netx.nodes[n][\"local_closeness\"] = _closeness_centrality(\n sub, n, length=closeness_weight, len_graph=lengraph\n )\n\n return netx\n\n\ndef mean_nodes(G, attr):\n \"\"\"\n Calculates mean value of nodes attr for each edge.\n \"\"\"\n for u, v, k in G.edges(keys=True):\n mean = (G.nodes[u][attr] + G.nodes[v][attr]) / 2\n G[u][v][k][attr] = mean\n" ]
[ [ "numpy.mean" ] ]
yangguohao/Paddle
[ "81622708a7c904092185ef04897b1e81629f51a6" ]
[ "python/paddle/fluid/tests/unittests/auto_parallel/test_dist_context.py" ]
[ "# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport os\nimport json\n\nimport paddle\nimport numpy as np\nimport paddle.nn as nn\nimport paddle.utils as utils\nimport paddle.static as static\nimport paddle.nn.functional as F\n\nfrom paddle.distributed import fleet\nimport paddle.distributed.auto_parallel as auto\nfrom paddle.distributed.auto_parallel.dist_context import DistributedContext\nfrom paddle.distributed.auto_parallel.utils import print_program_with_dist_attr\n\npaddle.enable_static()\n\nbatch_size = 4\nhidden_size = 1024\nsequence_len = 512\n_g_process_mesh = [[0, 1], [2, 3]]\n\n\ndef get_random_inputs_and_labels(input_shape, label_shape):\n input = np.random.random(size=input_shape).astype('float32')\n label = np.random.random(size=label_shape).astype('float32')\n return input, label\n\n\ndef batch_generator_creator():\n def __reader__():\n for _ in range(batch_size):\n batch_input, batch_label = get_random_inputs_and_labels(\n [batch_size, sequence_len, hidden_size],\n [batch_size, sequence_len, 1])\n yield batch_input, batch_label\n\n return __reader__\n\n\nclass MLPLayer(nn.Layer):\n def __init__(self,\n hidden_size=1024,\n intermediate_size=4 * 1024,\n dropout_ratio=0.1,\n initializer_range=0.02):\n super(MLPLayer, self).__init__()\n d_model = hidden_size\n dim_feedforward = intermediate_size\n param_initializer = nn.initializer.Normal(\n mean=0.0, std=initializer_range)\n\n self.norm = nn.LayerNorm(d_model, epsilon=1e-5)\n self.linear0 = nn.Linear(\n d_model,\n dim_feedforward,\n weight_attr=paddle.ParamAttr(initializer=param_initializer),\n bias_attr=None)\n self.linear1 = nn.Linear(\n dim_feedforward,\n d_model,\n weight_attr=paddle.ParamAttr(initializer=param_initializer),\n bias_attr=None)\n\n def forward(self, input):\n out = self.norm(input)\n auto.shard_tensor(\n self.linear0.weight,\n dist_attr={\n \"process_mesh\": _g_process_mesh[0],\n \"dims_mapping\": [-1, 0]\n })\n out = self.linear0(out)\n out = F.gelu(out, approximate=True)\n auto.shard_tensor(\n self.linear1.weight,\n dist_attr={\n \"process_mesh\": _g_process_mesh[1],\n \"dims_mapping\": [0, -1]\n })\n out = self.linear1(out)\n\n return out\n\n\ndef get_program():\n dist_strategy = fleet.DistributedStrategy()\n dist_strategy.semi_auto = True\n # fleet.init(is_collective=True, strategy=dist_strategy)\n\n train_program = static.Program()\n start_program = static.Program()\n with static.program_guard(train_program, start_program):\n # input\n input = static.data(\n name=\"input\",\n shape=[batch_size, sequence_len, hidden_size],\n dtype='float32')\n label = static.data(\n name=\"label\", shape=[batch_size, sequence_len, 1], dtype='float32')\n data_holder = [input, label]\n # dataloader\n dataloader = paddle.io.DataLoader.from_generator(\n feed_list=data_holder, capacity=4 * batch_size, iterable=False)\n dataloader.set_batch_generator(\n batch_generator_creator(), places=paddle.static.cuda_places())\n # data dist_attr\n auto.shard_tensor(\n input,\n dist_attr={\n \"process_mesh\": _g_process_mesh[0],\n \"dims_mapping\": [0, -1, -1]\n })\n auto.shard_tensor(\n label,\n dist_attr={\n \"process_mesh\": _g_process_mesh[0],\n \"dims_mapping\": [0, -1, -1]\n })\n\n mlp_start = MLPLayer(\n hidden_size=hidden_size,\n intermediate_size=4 * hidden_size,\n dropout_ratio=0.1,\n initializer_range=0.02)\n pred = mlp_start(input)\n\n mlp_mid = MLPLayer(\n hidden_size=hidden_size,\n intermediate_size=4 * hidden_size,\n dropout_ratio=0.1,\n initializer_range=0.02)\n pred = mlp_mid(pred)\n\n mlp_end = MLPLayer(\n hidden_size=hidden_size,\n intermediate_size=4 * hidden_size,\n dropout_ratio=0.1,\n initializer_range=0.02)\n pred = mlp_end(pred)\n\n error_cost = paddle.nn.functional.square_error_cost(pred, label)\n loss = paddle.mean(error_cost)\n\n optimizer = paddle.optimizer.Adam(\n learning_rate=0.00001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-08,\n grad_clip=None)\n\n feed_vars = {\"inputs\": [input], \"labels\": [label]}\n fetch_vars = {\"loss\": [loss]}\n\n return train_program, start_program, dataloader, loss, optimizer, feed_vars, fetch_vars\n\n\nclass TestDistributedContext(unittest.TestCase):\n def test_backup_restore(self):\n train_program, start_program, dataloader, loss, optimizer, feed_vars, fetch_vars = get_program(\n )\n dist_context = DistributedContext(train_program, start_program,\n optimizer, loss, feed_vars,\n fetch_vars)\n dist_context.initialize()\n\n dist_context._backup(serial=True, dist=True)\n dist_context._restore(\n serial=True,\n serial_mode=\"to_backup\",\n dist=True,\n dist_mode=\"to_backup\")\n\n dist_context._backup(serial=True, dist=True)\n dist_context._restore(\n serial=True,\n serial_mode=\"to_original\",\n dist=True,\n dist_mode=\"to_original\")\n\n dist_context._backup(serial=True, dist=True)\n dist_context._restore(serial=True, dist=True, dist_mode=\"to_default\")\n\n dist_context._backup(serial=True, dist=True)\n dist_context._restore(serial=True, dist=True, dist_mode=\"to_nothing\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.random.random" ] ]
siddharthteotia/arrow
[ "b33dfd9c6bd800308bb1619b237dbf24dea159be" ]
[ "python/pyarrow/tests/test_convert_pandas.py" ]
[ "# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom collections import OrderedDict\n\nfrom datetime import date, datetime, time, timedelta\nimport decimal\nimport json\n\nimport pytest\n\nimport numpy as np\nimport numpy.testing as npt\n\nimport pandas as pd\nimport pandas.util.testing as tm\n\nfrom pyarrow.compat import u, PY2\nimport pyarrow as pa\nimport pyarrow.types as patypes\n\nfrom .pandas_examples import dataframe_with_arrays, dataframe_with_lists\n\n\ndef _alltypes_example(size=100):\n return pd.DataFrame({\n 'uint8': np.arange(size, dtype=np.uint8),\n 'uint16': np.arange(size, dtype=np.uint16),\n 'uint32': np.arange(size, dtype=np.uint32),\n 'uint64': np.arange(size, dtype=np.uint64),\n 'int8': np.arange(size, dtype=np.int16),\n 'int16': np.arange(size, dtype=np.int16),\n 'int32': np.arange(size, dtype=np.int32),\n 'int64': np.arange(size, dtype=np.int64),\n 'float32': np.arange(size, dtype=np.float32),\n 'float64': np.arange(size, dtype=np.float64),\n 'bool': np.random.randn(size) > 0,\n # TODO(wesm): Pandas only support ns resolution, Arrow supports s, ms,\n # us, ns\n 'datetime': np.arange(\"2016-01-01T00:00:00.001\", size,\n dtype='datetime64[ms]'),\n 'str': [str(x) for x in range(size)],\n 'str_with_nulls': [None] + [str(x) for x in range(size - 2)] + [None],\n 'empty_str': [''] * size\n })\n\n\ndef _check_pandas_roundtrip(df, expected=None, nthreads=1,\n expected_schema=None,\n check_dtype=True, schema=None,\n preserve_index=False,\n as_batch=False):\n klass = pa.RecordBatch if as_batch else pa.Table\n table = klass.from_pandas(df, schema=schema,\n preserve_index=preserve_index,\n nthreads=nthreads)\n\n result = table.to_pandas(nthreads=nthreads)\n if expected_schema:\n assert table.schema.equals(expected_schema)\n if expected is None:\n expected = df\n tm.assert_frame_equal(result, expected, check_dtype=check_dtype,\n check_index_type=('equiv' if preserve_index\n else False))\n\n\ndef _check_series_roundtrip(s, type_=None):\n arr = pa.array(s, from_pandas=True, type=type_)\n\n result = pd.Series(arr.to_pandas(), name=s.name)\n if patypes.is_timestamp(arr.type) and arr.type.tz is not None:\n result = (result.dt.tz_localize('utc')\n .dt.tz_convert(arr.type.tz))\n\n tm.assert_series_equal(s, result)\n\n\ndef _check_array_roundtrip(values, expected=None, mask=None,\n type=None):\n arr = pa.array(values, from_pandas=True, mask=mask, type=type)\n result = arr.to_pandas()\n\n values_nulls = pd.isnull(values)\n if mask is None:\n assert arr.null_count == values_nulls.sum()\n else:\n assert arr.null_count == (mask | values_nulls).sum()\n\n if mask is None:\n tm.assert_series_equal(pd.Series(result), pd.Series(values),\n check_names=False)\n else:\n expected = pd.Series(np.ma.masked_array(values, mask=mask))\n tm.assert_series_equal(pd.Series(result), expected,\n check_names=False)\n\n\ndef _check_array_from_pandas_roundtrip(np_array):\n arr = pa.array(np_array, from_pandas=True)\n result = arr.to_pandas()\n npt.assert_array_equal(result, np_array)\n\n\nclass TestConvertMetadata(object):\n \"\"\"\n Conversion tests for Pandas metadata & indices.\n \"\"\"\n\n def test_non_string_columns(self):\n df = pd.DataFrame({0: [1, 2, 3]})\n table = pa.Table.from_pandas(df)\n assert table.column(0).name == '0'\n\n def test_column_index_names_are_preserved(self):\n df = pd.DataFrame({'data': [1, 2, 3]})\n df.columns.names = ['a']\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns(self):\n columns = pd.MultiIndex.from_arrays([\n ['one', 'two'], ['X', 'Y']\n ])\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns_with_dtypes(self):\n columns = pd.MultiIndex.from_arrays(\n [\n ['one', 'two'],\n pd.DatetimeIndex(['2017-08-01', '2017-08-02']),\n ],\n names=['level_1', 'level_2'],\n )\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_multiindex_columns_unicode(self):\n columns = pd.MultiIndex.from_arrays([[u'あ', u'い'], ['X', 'Y']])\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')], columns=columns)\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_integer_index_column(self):\n df = pd.DataFrame([(1, 'a'), (2, 'b'), (3, 'c')])\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_index_metadata_field_name(self):\n # test None case, and strangely named non-index columns\n df = pd.DataFrame(\n [(1, 'a', 3.1), (2, 'b', 2.2), (3, 'c', 1.3)],\n index=pd.MultiIndex.from_arrays(\n [['c', 'b', 'a'], [3, 2, 1]],\n names=[None, 'foo']\n ),\n columns=['a', None, '__index_level_0__'],\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n col1, col2, col3, idx0, foo = js['columns']\n\n assert col1['name'] == 'a'\n assert col1['name'] == col1['field_name']\n\n assert col2['name'] is None\n assert col2['field_name'] == 'None'\n\n assert col3['name'] == '__index_level_0__'\n assert col3['name'] == col3['field_name']\n\n idx0_name, foo_name = js['index_columns']\n assert idx0_name == '__index_level_0__'\n assert idx0['field_name'] == idx0_name\n assert idx0['name'] is None\n\n assert foo_name == 'foo'\n assert foo['field_name'] == foo_name\n assert foo['name'] == foo_name\n\n def test_categorical_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.Index(list('def'), dtype='category')\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] is None\n assert column_indexes['pandas_type'] == 'categorical'\n assert column_indexes['numpy_type'] == 'int8'\n\n md = column_indexes['metadata']\n assert md['num_categories'] == 3\n assert md['ordered'] is False\n\n def test_string_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.Index(list('def'), name='stringz')\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] == 'stringz'\n assert column_indexes['name'] == column_indexes['field_name']\n assert column_indexes['pandas_type'] == ('bytes' if PY2 else 'unicode')\n assert column_indexes['numpy_type'] == 'object'\n\n md = column_indexes['metadata']\n\n if not PY2:\n assert len(md) == 1\n assert md['encoding'] == 'UTF-8'\n else:\n assert md is None or 'encoding' not in md\n\n def test_datetimetz_column_index(self):\n df = pd.DataFrame(\n [(1, 'a', 2.0), (2, 'b', 3.0), (3, 'c', 4.0)],\n columns=pd.date_range(\n start='2017-01-01', periods=3, tz='America/New_York'\n )\n )\n t = pa.Table.from_pandas(df, preserve_index=True)\n raw_metadata = t.schema.metadata\n js = json.loads(raw_metadata[b'pandas'].decode('utf8'))\n\n column_indexes, = js['column_indexes']\n assert column_indexes['name'] is None\n assert column_indexes['pandas_type'] == 'datetimetz'\n assert column_indexes['numpy_type'] == 'datetime64[ns]'\n\n md = column_indexes['metadata']\n assert md['timezone'] == 'America/New_York'\n\n def test_datetimetz_row_index(self):\n df = pd.DataFrame({\n 'a': pd.date_range(\n start='2017-01-01', periods=3, tz='America/New_York'\n )\n })\n df = df.set_index('a')\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_categorical_row_index(self):\n df = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 2, 3]})\n df['a'] = df.a.astype('category')\n df = df.set_index('a')\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_duplicate_column_names_does_not_crash(self):\n df = pd.DataFrame([(1, 'a'), (2, 'b')], columns=list('aa'))\n with pytest.raises(ValueError):\n pa.Table.from_pandas(df)\n\n def test_dictionary_indices_boundscheck(self):\n # ARROW-1658. No validation of indices leads to segfaults in pandas\n indices = [[0, 1], [0, -1]]\n\n for inds in indices:\n arr = pa.DictionaryArray.from_arrays(inds, ['a'])\n batch = pa.RecordBatch.from_arrays([arr], ['foo'])\n table = pa.Table.from_batches([batch, batch, batch])\n\n with pytest.raises(pa.ArrowException):\n arr.to_pandas()\n\n with pytest.raises(pa.ArrowException):\n table.to_pandas()\n\n def test_unicode_with_unicode_column_and_index(self):\n df = pd.DataFrame({u'あ': [u'い']}, index=[u'う'])\n\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_mixed_unicode_column_names(self):\n df = pd.DataFrame({u'あ': [u'い'], b'a': 1}, index=[u'う'])\n\n # TODO(phillipc): Should this raise?\n with pytest.raises(AssertionError):\n _check_pandas_roundtrip(df, preserve_index=True)\n\n def test_binary_column_name(self):\n column_data = [u'い']\n data = {u'あ'.encode('utf8'): column_data}\n df = pd.DataFrame(data)\n\n # we can't use _check_pandas_roundtrip here because our metdata\n # is always decoded as utf8: even if binary goes in, utf8 comes out\n t = pa.Table.from_pandas(df, preserve_index=True)\n df2 = t.to_pandas()\n assert df.values[0] == df2.values[0]\n assert df.index.values[0] == df2.index.values[0]\n assert df.columns[0] == df2.columns[0].encode('utf8')\n\n def test_multiindex_duplicate_values(self):\n num_rows = 3\n numbers = list(range(num_rows))\n index = pd.MultiIndex.from_arrays(\n [['foo', 'foo', 'bar'], numbers],\n names=['foobar', 'some_numbers'],\n )\n\n df = pd.DataFrame({'numbers': numbers}, index=index)\n\n table = pa.Table.from_pandas(df)\n result_df = table.to_pandas()\n tm.assert_frame_equal(result_df, df)\n\n def test_metadata_with_mixed_types(self):\n df = pd.DataFrame({'data': [b'some_bytes', u'some_unicode']})\n table = pa.Table.from_pandas(df)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'bytes'\n assert data_column['numpy_type'] == 'object'\n\n def test_list_metadata(self):\n df = pd.DataFrame({'data': [[1], [2, 3, 4], [5] * 7]})\n schema = pa.schema([pa.field('data', type=pa.list_(pa.int64()))])\n table = pa.Table.from_pandas(df, schema=schema)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'list[int64]'\n assert data_column['numpy_type'] == 'object'\n\n def test_decimal_metadata(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('394092382910493.12341234678'),\n -decimal.Decimal('314292388910493.12343437128'),\n ]\n })\n table = pa.Table.from_pandas(expected)\n metadata = table.schema.metadata\n assert b'mixed' not in metadata[b'pandas']\n\n js = json.loads(metadata[b'pandas'].decode('utf8'))\n data_column = js['columns'][0]\n assert data_column['pandas_type'] == 'decimal'\n assert data_column['numpy_type'] == 'object'\n assert data_column['metadata'] == {'precision': 26, 'scale': 11}\n\n def test_table_column_subset_metadata(self):\n # ARROW-1883\n df = pd.DataFrame({\n 'a': [1, 2, 3],\n 'b': pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')})\n table = pa.Table.from_pandas(df)\n\n table_subset = table.remove_column(1)\n result = table_subset.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n table_subset2 = table_subset.remove_column(1)\n result = table_subset2.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n # non-default index\n for index in [\n pd.Index(['a', 'b', 'c'], name='index'),\n pd.date_range(\"2017-01-01\", periods=3, tz='Europe/Brussels')]:\n df = pd.DataFrame({'a': [1, 2, 3],\n 'b': [.1, .2, .3]}, index=index)\n table = pa.Table.from_pandas(df)\n\n table_subset = table.remove_column(1)\n result = table_subset.to_pandas()\n tm.assert_frame_equal(result, df[['a']])\n\n table_subset2 = table_subset.remove_column(1)\n result = table_subset2.to_pandas()\n tm.assert_frame_equal(result, df[['a']].reset_index(drop=True))\n\n def test_empty_list_metadata(self):\n # Create table with array of empty lists, forced to have type\n # list(string) in pyarrow\n c1 = [[\"test\"], [\"a\", \"b\"], None]\n c2 = [[], [], []]\n arrays = OrderedDict([\n ('c1', pa.array(c1, type=pa.list_(pa.string()))),\n ('c2', pa.array(c2, type=pa.list_(pa.string()))),\n ])\n rb = pa.RecordBatch.from_arrays(\n list(arrays.values()),\n list(arrays.keys())\n )\n tbl = pa.Table.from_batches([rb])\n\n # First roundtrip changes schema, because pandas cannot preserve the\n # type of empty lists\n df = tbl.to_pandas()\n tbl2 = pa.Table.from_pandas(df, preserve_index=True)\n md2 = json.loads(tbl2.schema.metadata[b'pandas'].decode('utf8'))\n\n # Second roundtrip\n df2 = tbl2.to_pandas()\n expected = pd.DataFrame(OrderedDict([('c1', c1), ('c2', c2)]))\n\n tm.assert_frame_equal(df2, expected)\n\n assert md2['columns'] == [\n {\n 'name': 'c1',\n 'field_name': 'c1',\n 'metadata': None,\n 'numpy_type': 'object',\n 'pandas_type': 'list[unicode]',\n },\n {\n 'name': 'c2',\n 'field_name': 'c2',\n 'metadata': None,\n 'numpy_type': 'object',\n 'pandas_type': 'list[empty]',\n },\n {\n 'name': None,\n 'field_name': '__index_level_0__',\n 'metadata': None,\n 'numpy_type': 'int64',\n 'pandas_type': 'int64',\n }\n ]\n\n\nclass TestConvertPrimitiveTypes(object):\n \"\"\"\n Conversion tests for primitive (e.g. numeric) types.\n \"\"\"\n\n def test_float_no_nulls(self):\n data = {}\n fields = []\n dtypes = [('f4', pa.float32()), ('f8', pa.float64())]\n num_values = 100\n\n for numpy_dtype, arrow_dtype in dtypes:\n values = np.random.randn(num_values)\n data[numpy_dtype] = values.astype(numpy_dtype)\n fields.append(pa.field(numpy_dtype, arrow_dtype))\n\n df = pd.DataFrame(data)\n schema = pa.schema(fields)\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_float_nulls(self):\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n dtypes = [('f4', pa.float32()), ('f8', pa.float64())]\n names = ['f4', 'f8']\n expected_cols = []\n\n arrays = []\n fields = []\n for name, arrow_dtype in dtypes:\n values = np.random.randn(num_values).astype(name)\n\n arr = pa.array(values, from_pandas=True, mask=null_mask)\n arrays.append(arr)\n fields.append(pa.field(name, arrow_dtype))\n values[null_mask] = np.nan\n\n expected_cols.append(values)\n\n ex_frame = pd.DataFrame(dict(zip(names, expected_cols)),\n columns=names)\n\n table = pa.Table.from_arrays(arrays, names)\n assert table.schema.equals(pa.schema(fields))\n result = table.to_pandas()\n tm.assert_frame_equal(result, ex_frame)\n\n def test_integer_no_nulls(self):\n data = OrderedDict()\n fields = []\n\n numpy_dtypes = [\n ('i1', pa.int8()), ('i2', pa.int16()),\n ('i4', pa.int32()), ('i8', pa.int64()),\n ('u1', pa.uint8()), ('u2', pa.uint16()),\n ('u4', pa.uint32()), ('u8', pa.uint64()),\n ('longlong', pa.int64()), ('ulonglong', pa.uint64())\n ]\n num_values = 100\n\n for dtype, arrow_dtype in numpy_dtypes:\n info = np.iinfo(dtype)\n values = np.random.randint(max(info.min, np.iinfo(np.int_).min),\n min(info.max, np.iinfo(np.int_).max),\n size=num_values)\n data[dtype] = values.astype(dtype)\n fields.append(pa.field(dtype, arrow_dtype))\n\n df = pd.DataFrame(data)\n schema = pa.schema(fields)\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_integer_with_nulls(self):\n # pandas requires upcast to float dtype\n\n int_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8']\n num_values = 100\n\n null_mask = np.random.randint(0, 10, size=num_values) < 3\n\n expected_cols = []\n arrays = []\n for name in int_dtypes:\n values = np.random.randint(0, 100, size=num_values)\n\n arr = pa.array(values, mask=null_mask)\n arrays.append(arr)\n\n expected = values.astype('f8')\n expected[null_mask] = np.nan\n\n expected_cols.append(expected)\n\n ex_frame = pd.DataFrame(dict(zip(int_dtypes, expected_cols)),\n columns=int_dtypes)\n\n table = pa.Table.from_arrays(arrays, int_dtypes)\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, ex_frame)\n\n def test_array_from_pandas_type_cast(self):\n arr = np.arange(10, dtype='int64')\n\n target_type = pa.int8()\n\n result = pa.array(arr, type=target_type)\n expected = pa.array(arr.astype('int8'))\n assert result.equals(expected)\n\n def test_boolean_no_nulls(self):\n num_values = 100\n\n np.random.seed(0)\n\n df = pd.DataFrame({'bools': np.random.randn(num_values) > 0})\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_boolean_nulls(self):\n # pandas requires upcast to object dtype\n num_values = 100\n np.random.seed(0)\n\n mask = np.random.randint(0, 10, size=num_values) < 3\n values = np.random.randint(0, 10, size=num_values) < 5\n\n arr = pa.array(values, mask=mask)\n\n expected = values.astype(object)\n expected[mask] = None\n\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n ex_frame = pd.DataFrame({'bools': expected})\n\n table = pa.Table.from_arrays([arr], ['bools'])\n assert table.schema.equals(schema)\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, ex_frame)\n\n def test_float_object_nulls(self):\n arr = np.array([None, 1.5, np.float64(3.5)] * 5, dtype=object)\n df = pd.DataFrame({'floats': arr})\n expected = pd.DataFrame({'floats': pd.to_numeric(arr)})\n field = pa.field('floats', pa.float64())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected=expected,\n expected_schema=schema)\n\n def test_int_object_nulls(self):\n arr = np.array([None, 1, np.int64(3)] * 5, dtype=object)\n df = pd.DataFrame({'ints': arr})\n expected = pd.DataFrame({'ints': pd.to_numeric(arr)})\n field = pa.field('ints', pa.int64())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected=expected,\n expected_schema=schema)\n\n def test_boolean_object_nulls(self):\n arr = np.array([False, None, True] * 100, dtype=object)\n df = pd.DataFrame({'bools': arr})\n field = pa.field('bools', pa.bool_())\n schema = pa.schema([field])\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_all_nulls_cast_numeric(self):\n arr = np.array([None], dtype=object)\n\n def _check_type(t):\n a2 = pa.array(arr, type=t)\n assert a2.type == t\n assert a2[0].as_py() is None\n\n _check_type(pa.int32())\n _check_type(pa.float64())\n\n\nclass TestConvertDateTimeLikeTypes(object):\n \"\"\"\n Conversion tests for datetime- and timestamp-like types (date64, etc.).\n \"\"\"\n\n def test_timestamps_notimezone_no_nulls(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n field = pa.field('datetime64', pa.timestamp('ns'))\n schema = pa.schema([field])\n _check_pandas_roundtrip(\n df,\n expected_schema=schema,\n )\n\n def test_timestamps_notimezone_nulls(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n field = pa.field('datetime64', pa.timestamp('ns'))\n schema = pa.schema([field])\n _check_pandas_roundtrip(\n df,\n expected_schema=schema,\n )\n\n def test_timestamps_with_timezone(self):\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123',\n '2006-01-13T12:34:56.432',\n '2010-08-13T05:46:57.437'],\n dtype='datetime64[ms]')\n })\n df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern')\n .to_frame())\n _check_pandas_roundtrip(df)\n\n _check_series_roundtrip(df['datetime64'])\n\n # drop-in a null and ns instead of ms\n df = pd.DataFrame({\n 'datetime64': np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n })\n df['datetime64'] = (df['datetime64'].dt.tz_localize('US/Eastern')\n .to_frame())\n\n _check_pandas_roundtrip(df)\n\n def test_python_datetime(self):\n # ARROW-2106\n date_array = [datetime.today() + timedelta(days=x) for x in range(10)]\n df = pd.DataFrame({\n 'datetime': pd.Series(date_array, dtype=object)\n })\n\n table = pa.Table.from_pandas(df)\n assert isinstance(table[0].data.chunk(0), pa.TimestampArray)\n\n result = table.to_pandas()\n expected_df = pd.DataFrame({\n 'datetime': date_array\n })\n tm.assert_frame_equal(expected_df, result)\n\n def test_datetime64_to_date32(self):\n # ARROW-1718\n arr = pa.array([date(2017, 10, 23), None])\n c = pa.Column.from_array(\"d\", arr)\n s = c.to_pandas()\n\n arr2 = pa.Array.from_pandas(s, type=pa.date32())\n\n assert arr2.equals(arr.cast('date32'))\n\n def test_date_infer(self):\n df = pd.DataFrame({\n 'date': [date(2000, 1, 1),\n None,\n date(1970, 1, 1),\n date(2040, 2, 26)]})\n table = pa.Table.from_pandas(df, preserve_index=False)\n field = pa.field('date', pa.date32())\n schema = pa.schema([field])\n assert table.schema.equals(schema)\n result = table.to_pandas()\n expected = df.copy()\n expected['date'] = pd.to_datetime(df['date'])\n tm.assert_frame_equal(result, expected)\n\n def test_date_mask(self):\n arr = np.array([date(2017, 4, 3), date(2017, 4, 4)],\n dtype='datetime64[D]')\n mask = [True, False]\n result = pa.array(arr, mask=np.array(mask))\n expected = np.array([None, date(2017, 4, 4)], dtype='datetime64[D]')\n expected = pa.array(expected, from_pandas=True)\n assert expected.equals(result)\n\n def test_date_objects_typed(self):\n arr = np.array([\n date(2017, 4, 3),\n None,\n date(2017, 4, 4),\n date(2017, 4, 5)], dtype=object)\n\n arr_i4 = np.array([17259, -1, 17260, 17261], dtype='int32')\n arr_i8 = arr_i4.astype('int64') * 86400000\n mask = np.array([False, True, False, False])\n\n t32 = pa.date32()\n t64 = pa.date64()\n\n a32 = pa.array(arr, type=t32)\n a64 = pa.array(arr, type=t64)\n\n a32_expected = pa.array(arr_i4, mask=mask, type=t32)\n a64_expected = pa.array(arr_i8, mask=mask, type=t64)\n\n assert a32.equals(a32_expected)\n assert a64.equals(a64_expected)\n\n # Test converting back to pandas\n colnames = ['date32', 'date64']\n table = pa.Table.from_arrays([a32, a64], colnames)\n table_pandas = table.to_pandas()\n\n ex_values = (np.array(['2017-04-03', '2017-04-04', '2017-04-04',\n '2017-04-05'],\n dtype='datetime64[D]')\n .astype('datetime64[ns]'))\n ex_values[1] = pd.NaT.value\n expected_pandas = pd.DataFrame({'date32': ex_values,\n 'date64': ex_values},\n columns=colnames)\n tm.assert_frame_equal(table_pandas, expected_pandas)\n\n def test_dates_from_integers(self):\n t1 = pa.date32()\n t2 = pa.date64()\n\n arr = np.array([17259, 17260, 17261], dtype='int32')\n arr2 = arr.astype('int64') * 86400000\n\n a1 = pa.array(arr, type=t1)\n a2 = pa.array(arr2, type=t2)\n\n expected = date(2017, 4, 3)\n assert a1[0].as_py() == expected\n assert a2[0].as_py() == expected\n\n @pytest.mark.xfail(reason=\"not supported ATM\",\n raises=NotImplementedError)\n def test_timedelta(self):\n # TODO(jreback): Pandas only support ns resolution\n # Arrow supports ??? for resolution\n df = pd.DataFrame({\n 'timedelta': np.arange(start=0, stop=3 * 86400000,\n step=86400000,\n dtype='timedelta64[ms]')\n })\n pa.Table.from_pandas(df)\n\n def test_pytime_from_pandas(self):\n pytimes = [time(1, 2, 3, 1356),\n time(4, 5, 6, 1356)]\n\n # microseconds\n t1 = pa.time64('us')\n\n aobjs = np.array(pytimes + [None], dtype=object)\n parr = pa.array(aobjs)\n assert parr.type == t1\n assert parr[0].as_py() == pytimes[0]\n assert parr[1].as_py() == pytimes[1]\n assert parr[2] is pa.NA\n\n # DataFrame\n df = pd.DataFrame({'times': aobjs})\n batch = pa.RecordBatch.from_pandas(df)\n assert batch[0].equals(parr)\n\n # Test ndarray of int64 values\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n\n a1 = pa.array(arr, type=pa.time64('us'))\n assert a1[0].as_py() == pytimes[0]\n\n a2 = pa.array(arr * 1000, type=pa.time64('ns'))\n assert a2[0].as_py() == pytimes[0]\n\n a3 = pa.array((arr / 1000).astype('i4'),\n type=pa.time32('ms'))\n assert a3[0].as_py() == pytimes[0].replace(microsecond=1000)\n\n a4 = pa.array((arr / 1000000).astype('i4'),\n type=pa.time32('s'))\n assert a4[0].as_py() == pytimes[0].replace(microsecond=0)\n\n def test_arrow_time_to_pandas(self):\n pytimes = [time(1, 2, 3, 1356),\n time(4, 5, 6, 1356),\n time(0, 0, 0)]\n\n expected = np.array(pytimes[:2] + [None])\n expected_ms = np.array([x.replace(microsecond=1000)\n for x in pytimes[:2]] +\n [None])\n expected_s = np.array([x.replace(microsecond=0)\n for x in pytimes[:2]] +\n [None])\n\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n arr = np.array([_pytime_to_micros(v) for v in pytimes],\n dtype='int64')\n\n null_mask = np.array([False, False, True], dtype=bool)\n\n a1 = pa.array(arr, mask=null_mask, type=pa.time64('us'))\n a2 = pa.array(arr * 1000, mask=null_mask,\n type=pa.time64('ns'))\n\n a3 = pa.array((arr / 1000).astype('i4'), mask=null_mask,\n type=pa.time32('ms'))\n a4 = pa.array((arr / 1000000).astype('i4'), mask=null_mask,\n type=pa.time32('s'))\n\n names = ['time64[us]', 'time64[ns]', 'time32[ms]', 'time32[s]']\n batch = pa.RecordBatch.from_arrays([a1, a2, a3, a4], names)\n arr = a1.to_pandas()\n assert (arr == expected).all()\n\n arr = a2.to_pandas()\n assert (arr == expected).all()\n\n arr = a3.to_pandas()\n assert (arr == expected_ms).all()\n\n arr = a4.to_pandas()\n assert (arr == expected_s).all()\n\n df = batch.to_pandas()\n expected_df = pd.DataFrame({'time64[us]': expected,\n 'time64[ns]': expected,\n 'time32[ms]': expected_ms,\n 'time32[s]': expected_s},\n columns=names)\n\n tm.assert_frame_equal(df, expected_df)\n\n def test_numpy_datetime64_columns(self):\n datetime64_ns = np.array([\n '2007-07-13T01:23:34.123456789',\n None,\n '2006-01-13T12:34:56.432539784',\n '2010-08-13T05:46:57.437699912'],\n dtype='datetime64[ns]')\n _check_array_from_pandas_roundtrip(datetime64_ns)\n\n datetime64_us = np.array([\n '2007-07-13T01:23:34.123456',\n None,\n '2006-01-13T12:34:56.432539',\n '2010-08-13T05:46:57.437699'],\n dtype='datetime64[us]')\n _check_array_from_pandas_roundtrip(datetime64_us)\n\n datetime64_ms = np.array([\n '2007-07-13T01:23:34.123',\n None,\n '2006-01-13T12:34:56.432',\n '2010-08-13T05:46:57.437'],\n dtype='datetime64[ms]')\n _check_array_from_pandas_roundtrip(datetime64_ms)\n\n datetime64_s = np.array([\n '2007-07-13T01:23:34',\n None,\n '2006-01-13T12:34:56',\n '2010-08-13T05:46:57'],\n dtype='datetime64[s]')\n _check_array_from_pandas_roundtrip(datetime64_s)\n\n def test_numpy_datetime64_day_unit(self):\n datetime64_d = np.array([\n '2007-07-13',\n None,\n '2006-01-15',\n '2010-08-19'],\n dtype='datetime64[D]')\n _check_array_from_pandas_roundtrip(datetime64_d)\n\n def test_array_from_pandas_date_with_mask(self):\n m = np.array([True, False, True])\n data = pd.Series([\n date(1990, 1, 1),\n date(1991, 1, 1),\n date(1992, 1, 1)\n ])\n\n result = pa.Array.from_pandas(data, mask=m)\n\n expected = pd.Series([None, date(1991, 1, 1), None])\n assert pa.Array.from_pandas(expected).equals(result)\n\n\nclass TestConvertStringLikeTypes(object):\n \"\"\"\n Conversion tests for string and binary types.\n \"\"\"\n\n def test_unicode(self):\n repeats = 1000\n values = [u'foo', None, u'bar', u'mañana', np.nan]\n df = pd.DataFrame({'strings': values * repeats})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n\n _check_pandas_roundtrip(df, expected_schema=schema)\n\n def test_bytes_to_binary(self):\n values = [u('qux'), b'foo', None, 'bar', 'qux', np.nan]\n df = pd.DataFrame({'strings': values})\n\n table = pa.Table.from_pandas(df)\n assert table[0].type == pa.binary()\n\n values2 = [b'qux', b'foo', None, b'bar', b'qux', np.nan]\n expected = pd.DataFrame({'strings': values2})\n _check_pandas_roundtrip(df, expected)\n\n @pytest.mark.large_memory\n def test_bytes_exceed_2gb(self):\n val = 'x' * (1 << 20)\n df = pd.DataFrame({\n 'strings': np.array([val] * 4000, dtype=object)\n })\n arr = pa.array(df['strings'])\n assert isinstance(arr, pa.ChunkedArray)\n assert arr.num_chunks == 2\n arr = None\n\n table = pa.Table.from_pandas(df)\n assert table[0].data.num_chunks == 2\n\n def test_fixed_size_bytes(self):\n values = [b'foo', None, b'bar', None, None, b'hey']\n df = pd.DataFrame({'strings': values})\n schema = pa.schema([pa.field('strings', pa.binary(3))])\n table = pa.Table.from_pandas(df, schema=schema)\n assert table.schema[0].type == schema[0].type\n assert table.schema[0].name == schema[0].name\n result = table.to_pandas()\n tm.assert_frame_equal(result, df)\n\n def test_fixed_size_bytes_does_not_accept_varying_lengths(self):\n values = [b'foo', None, b'ba', None, None, b'hey']\n df = pd.DataFrame({'strings': values})\n schema = pa.schema([pa.field('strings', pa.binary(3))])\n with pytest.raises(pa.ArrowInvalid):\n pa.Table.from_pandas(df, schema=schema)\n\n def test_table_empty_str(self):\n values = ['', '', '', '', '']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result1 = table.to_pandas(strings_to_categorical=False)\n expected1 = pd.DataFrame({'strings': values})\n tm.assert_frame_equal(result1, expected1, check_dtype=True)\n\n result2 = table.to_pandas(strings_to_categorical=True)\n expected2 = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result2, expected2, check_dtype=True)\n\n def test_table_str_to_categorical_without_na(self):\n values = ['a', 'a', 'b', 'b', 'c']\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result = table.to_pandas(strings_to_categorical=True)\n expected = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result, expected, check_dtype=True)\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas(strings_to_categorical=True,\n zero_copy_only=True)\n\n def test_table_str_to_categorical_with_na(self):\n values = [None, 'a', 'b', np.nan]\n df = pd.DataFrame({'strings': values})\n field = pa.field('strings', pa.string())\n schema = pa.schema([field])\n table = pa.Table.from_pandas(df, schema=schema)\n\n result = table.to_pandas(strings_to_categorical=True)\n expected = pd.DataFrame({'strings': pd.Categorical(values)})\n tm.assert_frame_equal(result, expected, check_dtype=True)\n\n with pytest.raises(pa.ArrowInvalid):\n table.to_pandas(strings_to_categorical=True,\n zero_copy_only=True)\n\n\nclass TestConvertDecimalTypes(object):\n \"\"\"\n Conversion test for decimal types.\n \"\"\"\n\n def test_decimal_32_from_pandas(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('-1234.123'),\n decimal.Decimal('1234.439'),\n ]\n })\n converted = pa.Table.from_pandas(expected, preserve_index=False)\n field = pa.field('decimals', pa.decimal128(7, 3))\n schema = pa.schema([field])\n assert converted.schema.equals(schema)\n\n def test_decimal_32_to_pandas(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('-1234.123'),\n decimal.Decimal('1234.439'),\n ]\n })\n converted = pa.Table.from_pandas(expected)\n df = converted.to_pandas()\n tm.assert_frame_equal(df, expected)\n\n def test_decimal_64_from_pandas(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('-129934.123331'),\n decimal.Decimal('129534.123731'),\n ]\n })\n converted = pa.Table.from_pandas(expected, preserve_index=False)\n field = pa.field('decimals', pa.decimal128(12, 6))\n schema = pa.schema([field])\n assert converted.schema.equals(schema)\n\n def test_decimal_64_to_pandas(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('-129934.123331'),\n decimal.Decimal('129534.123731'),\n ]\n })\n converted = pa.Table.from_pandas(expected)\n df = converted.to_pandas()\n tm.assert_frame_equal(df, expected)\n\n def test_decimal_128_from_pandas(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('394092382910493.12341234678'),\n -decimal.Decimal('314292388910493.12343437128'),\n ]\n })\n converted = pa.Table.from_pandas(expected, preserve_index=False)\n field = pa.field('decimals', pa.decimal128(26, 11))\n schema = pa.schema([field])\n assert converted.schema.equals(schema)\n\n def test_decimal_128_to_pandas(self):\n expected = pd.DataFrame({\n 'decimals': [\n decimal.Decimal('394092382910493.12341234678'),\n -decimal.Decimal('314292388910493.12343437128'),\n ]\n })\n converted = pa.Table.from_pandas(expected)\n df = converted.to_pandas()\n tm.assert_frame_equal(df, expected)\n\n\nclass TestListTypes(object):\n \"\"\"\n Conversion tests for list<> types.\n \"\"\"\n\n def test_column_of_arrays(self):\n df, schema = dataframe_with_arrays()\n _check_pandas_roundtrip(df, schema=schema, expected_schema=schema)\n table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)\n assert table.schema.equals(schema)\n\n for column in df.columns:\n field = schema.field_by_name(column)\n _check_array_roundtrip(df[column], type=field.type)\n\n def test_column_of_arrays_to_py(self):\n # Test regression in ARROW-1199 not caught in above test\n dtype = 'i1'\n arr = np.array([\n np.arange(10, dtype=dtype),\n np.arange(5, dtype=dtype),\n None,\n np.arange(1, dtype=dtype)\n ])\n type_ = pa.list_(pa.int8())\n parr = pa.array(arr, type=type_)\n\n assert parr[0].as_py() == list(range(10))\n assert parr[1].as_py() == list(range(5))\n assert parr[2].as_py() is None\n assert parr[3].as_py() == [0]\n\n def test_column_of_lists(self):\n df, schema = dataframe_with_lists()\n _check_pandas_roundtrip(df, schema=schema, expected_schema=schema)\n table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)\n assert table.schema.equals(schema)\n\n for column in df.columns:\n field = schema.field_by_name(column)\n _check_array_roundtrip(df[column], type=field.type)\n\n def test_column_of_lists_first_empty(self):\n # ARROW-2124\n num_lists = [[], [2, 3, 4], [3, 6, 7, 8], [], [2]]\n series = pd.Series([np.array(s, dtype=float) for s in num_lists])\n arr = pa.array(series)\n result = pd.Series(arr.to_pandas())\n tm.assert_series_equal(result, series)\n\n def test_column_of_lists_chunked(self):\n # ARROW-1357\n df = pd.DataFrame({\n 'lists': np.array([\n [1, 2],\n None,\n [2, 3],\n [4, 5],\n [6, 7],\n [8, 9]\n ], dtype=object)\n })\n\n schema = pa.schema([\n pa.field('lists', pa.list_(pa.int64()))\n ])\n\n t1 = pa.Table.from_pandas(df[:2], schema=schema)\n t2 = pa.Table.from_pandas(df[2:], schema=schema)\n\n table = pa.concat_tables([t1, t2])\n result = table.to_pandas()\n\n tm.assert_frame_equal(result, df)\n\n def test_column_of_lists_chunked2(self):\n data1 = [[0, 1], [2, 3], [4, 5], [6, 7], [10, 11],\n [12, 13], [14, 15], [16, 17]]\n data2 = [[8, 9], [18, 19]]\n\n a1 = pa.array(data1)\n a2 = pa.array(data2)\n\n t1 = pa.Table.from_arrays([a1], names=['a'])\n t2 = pa.Table.from_arrays([a2], names=['a'])\n\n concatenated = pa.concat_tables([t1, t2])\n\n result = concatenated.to_pandas()\n expected = pd.DataFrame({'a': data1 + data2})\n\n tm.assert_frame_equal(result, expected)\n\n def test_column_of_lists_strided(self):\n df, schema = dataframe_with_lists()\n df = pd.concat([df] * 6, ignore_index=True)\n\n arr = df['int64'].values[::3]\n assert arr.strides[0] != 8\n\n _check_array_roundtrip(arr)\n\n def test_nested_lists_all_none(self):\n data = np.array([[None, None], None], dtype=object)\n\n arr = pa.array(data)\n expected = pa.array(list(data))\n assert arr.equals(expected)\n assert arr.type == pa.list_(pa.null())\n\n data2 = np.array([None, None, [None, None],\n np.array([None, None], dtype=object)],\n dtype=object)\n arr = pa.array(data2)\n expected = pa.array([None, None, [None, None], [None, None]])\n assert arr.equals(expected)\n\n def test_nested_lists_all_empty(self):\n # ARROW-2128\n data = pd.Series([[], [], []])\n arr = pa.array(data)\n expected = pa.array(list(data))\n assert arr.equals(expected)\n assert arr.type == pa.list_(pa.null())\n\n def test_infer_lists(self):\n data = OrderedDict([\n ('nan_ints', [[None, 1], [2, 3]]),\n ('ints', [[0, 1], [2, 3]]),\n ('strs', [[None, u'b'], [u'c', u'd']]),\n ('nested_strs', [[[None, u'b'], [u'c', u'd']], None])\n ])\n df = pd.DataFrame(data)\n\n expected_schema = pa.schema([\n pa.field('nan_ints', pa.list_(pa.int64())),\n pa.field('ints', pa.list_(pa.int64())),\n pa.field('strs', pa.list_(pa.string())),\n pa.field('nested_strs', pa.list_(pa.list_(pa.string())))\n ])\n\n _check_pandas_roundtrip(df, expected_schema=expected_schema)\n\n def test_infer_numpy_array(self):\n data = OrderedDict([\n ('ints', [\n np.array([0, 1], dtype=np.int64),\n np.array([2, 3], dtype=np.int64)\n ])\n ])\n df = pd.DataFrame(data)\n expected_schema = pa.schema([\n pa.field('ints', pa.list_(pa.int64()))\n ])\n\n _check_pandas_roundtrip(df, expected_schema=expected_schema)\n\n @pytest.mark.parametrize('t,data,expected', [\n (\n pa.int64,\n [[1, 2], [3], None],\n [None, [3], None]\n ),\n (\n pa.string,\n [[u'aaa', u'bb'], [u'c'], None],\n [None, [u'c'], None]\n ),\n (\n pa.null,\n [[None, None], [None], None],\n [None, [None], None]\n )\n ])\n def test_array_from_pandas_typed_array_with_mask(self, t, data, expected):\n m = np.array([True, False, True])\n\n s = pd.Series(data)\n result = pa.Array.from_pandas(s, mask=m, type=pa.list_(t()))\n\n assert pa.Array.from_pandas(expected,\n type=pa.list_(t())).equals(result)\n\n def test_empty_list_roundtrip(self):\n empty_list_array = np.empty((3,), dtype=object)\n empty_list_array.fill([])\n\n df = pd.DataFrame({'a': np.array(['1', '2', '3']),\n 'b': empty_list_array})\n tbl = pa.Table.from_pandas(df)\n\n result = tbl.to_pandas()\n\n tm.assert_frame_equal(result, df)\n\n def test_array_from_nested_arrays(self):\n df, schema = dataframe_with_arrays()\n for field in schema:\n arr = df[field.name].values\n expected = pa.array(list(arr), type=field.type)\n result = pa.array(arr)\n assert result.type == field.type # == list<scalar>\n assert result.equals(expected)\n\n\nclass TestConvertStructTypes(object):\n \"\"\"\n Conversion tests for struct types.\n \"\"\"\n\n def test_structarray(self):\n ints = pa.array([None, 2, 3], type=pa.int64())\n strs = pa.array([u'a', None, u'c'], type=pa.string())\n bools = pa.array([True, False, None], type=pa.bool_())\n arr = pa.StructArray.from_arrays(\n [ints, strs, bools],\n ['ints', 'strs', 'bools'])\n\n expected = pd.Series([\n {'ints': None, 'strs': u'a', 'bools': True},\n {'ints': 2, 'strs': None, 'bools': False},\n {'ints': 3, 'strs': u'c', 'bools': None},\n ])\n\n series = pd.Series(arr.to_pandas())\n tm.assert_series_equal(series, expected)\n\n\nclass TestZeroCopyConversion(object):\n \"\"\"\n Tests that zero-copy conversion works with some types.\n \"\"\"\n\n def test_zero_copy_success(self):\n result = pa.array([0, 1, 2]).to_pandas(zero_copy_only=True)\n npt.assert_array_equal(result, [0, 1, 2])\n\n def test_zero_copy_dictionaries(self):\n arr = pa.DictionaryArray.from_arrays(\n np.array([0, 0]),\n np.array([5]))\n\n result = arr.to_pandas(zero_copy_only=True)\n values = pd.Categorical([5, 5])\n\n tm.assert_series_equal(pd.Series(result), pd.Series(values),\n check_names=False)\n\n def test_zero_copy_failure_on_object_types(self):\n with pytest.raises(pa.ArrowException):\n pa.array(['A', 'B', 'C']).to_pandas(zero_copy_only=True)\n\n def test_zero_copy_failure_with_int_when_nulls(self):\n with pytest.raises(pa.ArrowException):\n pa.array([0, 1, None]).to_pandas(zero_copy_only=True)\n\n def test_zero_copy_failure_with_float_when_nulls(self):\n with pytest.raises(pa.ArrowException):\n pa.array([0.0, 1.0, None]).to_pandas(zero_copy_only=True)\n\n def test_zero_copy_failure_on_bool_types(self):\n with pytest.raises(pa.ArrowException):\n pa.array([True, False]).to_pandas(zero_copy_only=True)\n\n def test_zero_copy_failure_on_list_types(self):\n arr = np.array([[1, 2], [8, 9]], dtype=object)\n\n with pytest.raises(pa.ArrowException):\n pa.array(arr).to_pandas(zero_copy_only=True)\n\n def test_zero_copy_failure_on_timestamp_types(self):\n arr = np.array(['2007-07-13'], dtype='datetime64[ns]')\n\n with pytest.raises(pa.ArrowException):\n pa.array(arr).to_pandas(zero_copy_only=True)\n\n\nclass TestConvertMisc(object):\n \"\"\"\n Miscellaneous conversion tests.\n \"\"\"\n\n type_pairs = [\n (np.int8, pa.int8()),\n (np.int16, pa.int16()),\n (np.int32, pa.int32()),\n (np.int64, pa.int64()),\n (np.uint8, pa.uint8()),\n (np.uint16, pa.uint16()),\n (np.uint32, pa.uint32()),\n (np.uint64, pa.uint64()),\n # (np.float16, pa.float16()), # XXX unsupported\n (np.float32, pa.float32()),\n (np.float64, pa.float64()),\n # XXX unsupported\n # (np.dtype([('a', 'i2')]), pa.struct([pa.field('a', pa.int16())])),\n (np.object, pa.string()),\n # (np.object, pa.binary()), # XXX unsupported\n (np.object, pa.binary(10)),\n (np.object, pa.list_(pa.int64())),\n ]\n\n def test_all_none_objects(self):\n df = pd.DataFrame({'a': [None, None, None]})\n _check_pandas_roundtrip(df)\n\n def test_all_none_category(self):\n df = pd.DataFrame({'a': [None, None, None]})\n df['a'] = df['a'].astype('category')\n _check_pandas_roundtrip(df)\n\n def test_empty_arrays(self):\n for dtype, pa_type in self.type_pairs:\n arr = np.array([], dtype=dtype)\n _check_array_roundtrip(arr, type=pa_type)\n\n def test_threaded_conversion(self):\n df = _alltypes_example()\n _check_pandas_roundtrip(df, nthreads=2)\n _check_pandas_roundtrip(df, nthreads=2, as_batch=True)\n\n def test_category(self):\n repeats = 5\n v1 = ['foo', None, 'bar', 'qux', np.nan]\n v2 = [4, 5, 6, 7, 8]\n v3 = [b'foo', None, b'bar', b'qux', np.nan]\n df = pd.DataFrame({'cat_strings': pd.Categorical(v1 * repeats),\n 'cat_ints': pd.Categorical(v2 * repeats),\n 'cat_binary': pd.Categorical(v3 * repeats),\n 'cat_strings_ordered': pd.Categorical(\n v1 * repeats, categories=['bar', 'qux', 'foo'],\n ordered=True),\n 'ints': v2 * repeats,\n 'ints2': v2 * repeats,\n 'strings': v1 * repeats,\n 'strings2': v1 * repeats,\n 'strings3': v3 * repeats})\n _check_pandas_roundtrip(df)\n\n arrays = [\n pd.Categorical(v1 * repeats),\n pd.Categorical(v2 * repeats),\n pd.Categorical(v3 * repeats)\n ]\n for values in arrays:\n _check_array_roundtrip(values)\n\n def test_mixed_types_fails(self):\n data = pd.DataFrame({'a': ['a', 1, 2.0]})\n with pytest.raises(pa.ArrowException):\n pa.Table.from_pandas(data)\n\n data = pd.DataFrame({'a': [1, True]})\n with pytest.raises(pa.ArrowException):\n pa.Table.from_pandas(data)\n\n def test_strided_data_import(self):\n cases = []\n\n columns = ['a', 'b', 'c']\n N, K = 100, 3\n random_numbers = np.random.randn(N, K).copy() * 100\n\n numeric_dtypes = ['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8',\n 'f4', 'f8']\n\n for type_name in numeric_dtypes:\n cases.append(random_numbers.astype(type_name))\n\n # strings\n cases.append(np.array([tm.rands(10) for i in range(N * K)],\n dtype=object)\n .reshape(N, K).copy())\n\n # booleans\n boolean_objects = (np.array([True, False, True] * N, dtype=object)\n .reshape(N, K).copy())\n\n # add some nulls, so dtype comes back as objects\n boolean_objects[5] = None\n cases.append(boolean_objects)\n\n cases.append(np.arange(\"2016-01-01T00:00:00.001\", N * K,\n dtype='datetime64[ms]')\n .reshape(N, K).copy())\n\n strided_mask = (random_numbers > 0).astype(bool)[:, 0]\n\n for case in cases:\n df = pd.DataFrame(case, columns=columns)\n col = df['a']\n\n _check_pandas_roundtrip(df)\n _check_array_roundtrip(col)\n _check_array_roundtrip(col, mask=strided_mask)\n\n def test_all_nones(self):\n def _check_series(s):\n converted = pa.array(s)\n assert isinstance(converted, pa.NullArray)\n assert len(converted) == 3\n assert converted.null_count == 3\n assert converted[0] is pa.NA\n\n _check_series(pd.Series([None] * 3, dtype=object))\n _check_series(pd.Series([np.nan] * 3, dtype=object))\n _check_series(pd.Series([np.sqrt(-1)] * 3, dtype=object))\n\n def test_partial_schema(self):\n data = OrderedDict([\n ('a', [0, 1, 2, 3, 4]),\n ('b', np.array([-10, -5, 0, 5, 10], dtype=np.int32)),\n ('c', [-10, -5, 0, 5, 10])\n ])\n df = pd.DataFrame(data)\n\n partial_schema = pa.schema([\n pa.field('a', pa.int64()),\n pa.field('b', pa.int32())\n ])\n\n expected_schema = pa.schema([\n pa.field('a', pa.int64()),\n pa.field('b', pa.int32()),\n pa.field('c', pa.int64())\n ])\n\n _check_pandas_roundtrip(df, schema=partial_schema,\n expected_schema=expected_schema)\n\n def test_table_batch_empty_dataframe(self):\n df = pd.DataFrame({})\n _check_pandas_roundtrip(df)\n _check_pandas_roundtrip(df, as_batch=True)\n\n df2 = pd.DataFrame({}, index=[0, 1, 2])\n _check_pandas_roundtrip(df2, preserve_index=True)\n _check_pandas_roundtrip(df2, as_batch=True, preserve_index=True)\n\n def test_convert_empty_table(self):\n arr = pa.array([], type=pa.int64())\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=np.int64))\n arr = pa.array([], type=pa.string())\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n arr = pa.array([], type=pa.list_(pa.int64()))\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n arr = pa.array([], type=pa.struct([pa.field('a', pa.int64())]))\n tm.assert_almost_equal(arr.to_pandas(), np.array([], dtype=object))\n\n\ndef _fully_loaded_dataframe_example():\n from distutils.version import LooseVersion\n\n index = pd.MultiIndex.from_arrays([\n pd.date_range('2000-01-01', periods=5).repeat(2),\n np.tile(np.array(['foo', 'bar'], dtype=object), 5)\n ])\n\n c1 = pd.date_range('2000-01-01', periods=10)\n data = {\n 0: c1,\n 1: c1.tz_localize('utc'),\n 2: c1.tz_localize('US/Eastern'),\n 3: c1[::2].tz_localize('utc').repeat(2).astype('category'),\n 4: ['foo', 'bar'] * 5,\n 5: pd.Series(['foo', 'bar'] * 5).astype('category').values,\n 6: [True, False] * 5,\n 7: np.random.randn(10),\n 8: np.random.randint(0, 100, size=10),\n 9: pd.period_range('2013', periods=10, freq='M')\n }\n\n if LooseVersion(pd.__version__) >= '0.21':\n # There is an issue with pickling IntervalIndex in pandas 0.20.x\n data[10] = pd.interval_range(start=1, freq=1, periods=10)\n\n return pd.DataFrame(data, index=index)\n\n\ndef _check_serialize_components_roundtrip(df):\n ctx = pa.default_serialization_context()\n\n components = ctx.serialize(df).to_components()\n deserialized = ctx.deserialize_components(components)\n\n tm.assert_frame_equal(df, deserialized)\n\n\ndef test_serialize_deserialize_pandas():\n # ARROW-1784, serialize and deserialize DataFrame by decomposing\n # BlockManager\n df = _fully_loaded_dataframe_example()\n _check_serialize_components_roundtrip(df)\n\n\ndef _pytime_from_micros(val):\n microseconds = val % 1000000\n val //= 1000000\n seconds = val % 60\n val //= 60\n minutes = val % 60\n hours = val // 60\n return time(hours, minutes, seconds, microseconds)\n\n\ndef _pytime_to_micros(pytime):\n return (pytime.hour * 3600000000 +\n pytime.minute * 60000000 +\n pytime.second * 1000000 +\n pytime.microsecond)\n" ]
[ [ "pandas.Series", "numpy.random.seed", "pandas.Categorical", "numpy.int64", "pandas.util.testing.assert_series_equal", "numpy.float64", "pandas.period_range", "numpy.ma.masked_array", "pandas.to_numeric", "numpy.testing.assert_array_equal", "pandas.util.testing.rands", "pandas.to_datetime", "pandas.isnull", "numpy.random.randint", "numpy.sqrt", "pandas.date_range", "numpy.arange", "pandas.interval_range", "pandas.concat", "pandas.Index", "pandas.DatetimeIndex", "numpy.empty", "pandas.MultiIndex.from_arrays", "pandas.DataFrame", "numpy.random.randn", "numpy.iinfo", "numpy.array", "pandas.util.testing.assert_frame_equal" ] ]
pattonw/diluvian
[ "3df1e0666f6e65c7719f703e629239b7f0493f86" ]
[ "diluvian/volumes.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"Volumes of raw image and labeled object data.\"\"\"\n\n\nfrom __future__ import division\n\nfrom collections import namedtuple\nimport csv\nimport logging\nimport os\nimport re\n\nimport h5py\nimport math\nimport numpy as np\nfrom PIL import Image\nimport pytoml as toml\nimport requests\nfrom scipy import ndimage\nimport six\nfrom six.moves import range as xrange\nimport pyn5\n\nfrom .config import CONFIG\nfrom .octrees import OctreeVolume\nfrom .util import get_nonzero_aabb\n\n\nDimOrder = namedtuple('DimOrder', ('X', 'Y', 'Z'))\n\n\ndef partition_volumes(volumes, downsample=True):\n \"\"\"Paritition volumes into training and validation based on configuration.\n\n Uses the regexes mapping partition sizes and indices in\n diluvian.config.TrainingConfig by applying them to matching volumes based\n on name.\n\n Parameters\n ----------\n volumes : dict\n Dictionary mapping volume name to diluvian.volumes.Volume.\n downsample : bool, optional\n Whether to downsample partitions automatically.\n\n Returns\n -------\n training_volumes, validation_volumes : dict\n Dictionary mapping volume name to partitioned, downsampled volumes.\n \"\"\"\n def apply_partitioning(volumes, partitioning):\n partitioned = {}\n for name, vol in six.iteritems(volumes):\n partitions = [p for rgx, p in CONFIG.training.partitions.items() if re.match(rgx, name)]\n partition_index = [idx for rgx, idx in partitioning.items() if re.match(rgx, name)]\n if len(partitions) > 1 or len(partition_index) > 1:\n raise ValueError('Volume \"{}\" matches more than one partition specifier'.format(name))\n elif len(partitions) == 1 and len(partition_index) == 1:\n v = vol.partition(partitions[0], partition_index[0])\n if downsample:\n v = v.downsample(CONFIG.volume.resolution)\n partitioned[name] = v\n\n return partitioned\n\n training_volumes = apply_partitioning(volumes, CONFIG.training.training_partition)\n validation_volumes = apply_partitioning(volumes, CONFIG.training.validation_partition)\n\n return training_volumes, validation_volumes\n\n\nclass SubvolumeBounds(object):\n \"\"\"Sufficient parameters to extract a subvolume from a volume.\"\"\"\n __slots__ = ('start', 'stop', 'seed', 'label_id', 'label_margin',)\n\n def __init__(self, start=None, stop=None, seed=None, label_id=None, label_margin=None):\n assert (start is not None and stop is not None) or seed is not None, \"Bounds or seed must be provided\"\n self.start = start\n self.stop = stop\n self.seed = seed\n self.label_id = label_id\n if label_margin is None:\n label_margin = np.zeros(3, dtype=np.int64)\n self.label_margin = label_margin\n\n @classmethod\n def iterable_from_csv(cls, filename):\n bounds = []\n with open(filename, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n for k, v in six.iteritems(row):\n if not v:\n row[k] = None\n elif v[0] == '[':\n row[k] = np.fromstring(v[1:-1], sep=' ', dtype=np.int64)\n else:\n row[k] = int(v)\n bounds.append(cls(**row))\n\n return bounds\n\n @classmethod\n def iterable_to_csv(cls, bounds, filename):\n with open(filename, 'w') as csvfile:\n fieldnames = cls.__slots__\n writer = csv.writer(csvfile)\n writer.writerow(fieldnames)\n for bound in bounds:\n writer.writerow([getattr(bound, f) for f in fieldnames])\n\n\nclass Subvolume(object):\n \"\"\"A subvolume of image data and an optional ground truth object mask.\"\"\"\n __slots__ = ('image', 'label_mask', 'seed', 'label_id',)\n\n def __init__(self, image, label_mask, seed, label_id):\n self.image = image\n self.label_mask = label_mask\n self.seed = seed\n self.label_id = label_id\n\n def f_a(self):\n \"\"\"Calculate the mask filling fraction of this subvolume.\n\n Returns\n -------\n float\n Fraction of the subvolume voxels in the object mask.\n \"\"\"\n return np.count_nonzero(self.label_mask) / float(self.label_mask.size)\n\n def has_seed_in_mask(self):\n ctr = self.seed - (np.asarray(self.image.shape) - np.asarray(self.label_mask.shape)) // 2\n return self.label_mask[tuple(ctr)]\n\n def has_uniform_seed_margin(self, seed_margin=20.0):\n \"\"\"Test if a subvolume has a margin of uniform label around its seed.\n\n Parameters\n ----------\n seed_margin : float, optional\n The minimum acceptable margin of uniform target label around the seed\n voxel (in nm, default 20.0).\n\n Returns\n -------\n bool\n True if the rectangular margin around the seed position is uniform.\n \"\"\"\n margin = np.ceil(np.reciprocal(np.array(CONFIG.volume.resolution),\n dtype=np.float64) * seed_margin).astype(np.int64)\n\n mask_target = self.label_mask\n # If data is unlabeled, can not test so always succeed.\n if mask_target is None:\n return True\n # Seed location in the mask accounting for offset of label from image.\n ctr = self.seed - (np.asarray(self.image.shape) - np.asarray(mask_target.shape)) // 2\n seed_fov = (ctr - margin, ctr + margin + 1)\n seed_region = mask_target[seed_fov[0][0]:seed_fov[1][0],\n seed_fov[0][1]:seed_fov[1][1],\n seed_fov[0][2]:seed_fov[1][2]]\n return np.all(seed_region)\n\n\nclass SubvolumeGenerator(six.Iterator):\n \"\"\"Combines a volume and a subvolume bounds generator into a generator.\n\n Parameters\n ----------\n volume : Volume\n bounds_generator : SubvolumeBoundsGenerator\n \"\"\"\n def __init__(self, volume, bounds_generator):\n self.volume = volume\n self.bounds_generator = bounds_generator\n\n @property\n def shape(self):\n return self.bounds_generator.shape\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.bounds_generator.reset()\n\n def __next__(self):\n return self.volume.get_subvolume(six.next(self.bounds_generator))\n\n\nclass ErodedMaskGenerator(six.Iterator):\n def __init__(self, subvolume_generator, erosion_px):\n self.subvolume_generator = subvolume_generator\n self.sel = np.ones(erosion_px * 2 + 1)\n\n @property\n def shape(self):\n return self.subvolume_generator.shape\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.subvolume_generator.reset()\n\n def __next__(self):\n while True:\n subv = six.next(self.subvolume_generator)\n\n subv.label_mask = ndimage.binary_erosion(subv.label_mask, structure=self.sel, border_value=1)\n\n if subv.has_seed_in_mask():\n return subv\n\n\nclass RelabelSeedComponentGenerator(six.Iterator):\n def __init__(self, subvolume_generator):\n self.subvolume_generator = subvolume_generator\n\n @property\n def shape(self):\n return self.subvolume_generator.shape\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.subvolume_generator.reset()\n\n def __next__(self):\n subv = six.next(self.subvolume_generator)\n\n label_im, _ = ndimage.label(subv.label_mask)\n label_axis_margin = (np.array(subv.image.shape) - np.array(subv.label_mask.shape)) // 2\n seed_label = label_im[tuple(subv.seed - label_axis_margin)]\n\n subv.label_mask = label_im == seed_label\n\n return subv\n\n\nclass SubvolumeAugmentGenerator(six.Iterator):\n \"\"\"Base class for subvolume generator augmenters.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n return_both : bool\n If true, return both the original and augmented volume in sequence.\n If false, return either with equal probability.\n \"\"\"\n def __init__(self, subvolume_generator, return_both):\n self.subvolume_generator = subvolume_generator\n self.return_both = return_both\n self.return_single_p = 0.5\n self.subvolume = None\n\n @property\n def shape(self):\n return self.subvolume_generator.shape\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.subvolume = None\n self.subvolume_generator.reset()\n\n def __next__(self):\n if self.return_both:\n if self.subvolume is None:\n self.subvolume = six.next(self.subvolume_generator)\n return self.subvolume\n else:\n subv = self.augment_subvolume()\n self.subvolume = None\n if subv is None:\n return six.next(self)\n else:\n return subv\n else:\n self.subvolume = six.next(self.subvolume_generator)\n if np.random.sample() < self.return_single_p:\n return self.subvolume\n else:\n subv = self.augment_subvolume()\n if subv is None:\n return self.subvolume\n else:\n return subv\n\n def augment_subvolume(self):\n raise NotImplementedError('Subclasses must implement this method.')\n\n\nclass ClipSubvolumeImageGenerator(six.Iterator):\n \"\"\"Clip subvolume image range (default between zero and one).\n\n Useful to apply after a sequence of augmentations.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n min_val, max_val : float, optional\n \"\"\"\n def __init__(self, subvolume_generator, min_val=0.0, max_val=1.0):\n self.subvolume_generator = subvolume_generator\n self.min_val = min_val\n self.max_val = max_val\n\n @property\n def shape(self):\n return self.subvolume_generator.shape\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.subvolume_generator.reset()\n\n def __next__(self):\n subv = six.next(self.subvolume_generator)\n return Subvolume(np.clip(subv.image, self.min_val, self.max_val),\n subv.label_mask,\n subv.seed,\n subv.label_id)\n\n\nclass MirrorAugmentGenerator(SubvolumeAugmentGenerator):\n \"\"\"Repeats subvolumes from a subvolume generator mirrored along an axis.\n\n For each subvolume in the original generator, this generator will yield two\n subvolumes: the original subvolume and the subvolume with the image,\n label mask, and seed mirrored along a given axis.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n return_both : bool\n If true, return both the original and augmented volume in sequence.\n If false, return either with equal probability.\n axis : int\n \"\"\"\n def __init__(self, subvolume_generator, return_both, axis):\n super(MirrorAugmentGenerator, self).__init__(subvolume_generator, return_both)\n self.axis = axis\n\n def augment_subvolume(self):\n subv = self.subvolume\n shape = subv.image.shape[self.axis]\n seed = subv.seed.copy()\n seed[self.axis] = shape - subv.seed[self.axis] - 1\n subv = Subvolume(np.flip(subv.image, self.axis),\n np.flip(subv.label_mask, self.axis) if subv.label_mask is not None else None,\n seed,\n subv.label_id)\n return subv\n\n\nclass PermuteAxesAugmentGenerator(SubvolumeAugmentGenerator):\n \"\"\"Repeats subvolumes from a subvolume generator with an axes permutation.\n\n For each subvolume in the original generator, this generator will yield two\n subvolumes: the original subvolume and the subvolume with the image,\n label mask, and seed axes permuted according to a given axes order.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n return_both : bool\n If true, return both the original and augmented volume in sequence.\n If false, return either with equal probability.\n axes : sequence of int\n \"\"\"\n def __init__(self, subvolume_generator, return_both, axes):\n super(PermuteAxesAugmentGenerator, self).__init__(subvolume_generator, return_both)\n self.axes = list(axes)\n\n def augment_subvolume(self):\n subv = self.subvolume\n subv = Subvolume(np.transpose(subv.image, self.axes),\n np.transpose(subv.label_mask, self.axes) if subv.label_mask is not None else None,\n subv.seed[self.axes],\n self.subvolume.label_id)\n return subv\n\n\nclass MissingDataAugmentGenerator(SubvolumeAugmentGenerator):\n \"\"\"Repeats subvolumes from a subvolume generator with missing data planes.\n\n For each subvolume in the original generator, this generator will yield the\n original subvolume and may yield a subvolume with missing planes of image\n and/or label mask data.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n return_both : bool\n If true, return both the original and augmented volume in sequence.\n If false, return either with equal probability.\n axis : int\n probability : float\n Independent probability that each plane of data along axis is missing.\n remove_label : bool\n Whether to also remove label mask data.\n \"\"\"\n def __init__(self, subvolume_generator, return_both, axis, probability, remove_label=False):\n super(MissingDataAugmentGenerator, self).__init__(subvolume_generator, return_both)\n self.axis = axis\n self.probability = probability\n self.remove_label = remove_label\n\n def augment_subvolume(self):\n rolls = np.random.sample(self.shape[self.axis])\n # Remove the seed plane from possibilities.\n rolls[self.subvolume.seed[self.axis]] = 1.1\n missing_sections = np.where(rolls < self.probability)\n\n if missing_sections and missing_sections[0].size:\n subv = self.subvolume\n mask = subv.label_mask.copy() if subv.label_mask is not None and self.remove_label else subv.label_mask\n subv = Subvolume(subv.image.copy(),\n mask,\n subv.seed,\n subv.label_id)\n slices = [slice(None), slice(None), slice(None)]\n slices[self.axis] = missing_sections\n subv.image[slices] = 0\n if self.remove_label:\n label_axis_margin = (subv.image.shape[self.axis] - subv.label_mask.shape[self.axis]) // 2\n label_sections = missing_sections[0] - label_axis_margin\n label_sections = label_sections[(label_sections >= 0) &\n (label_sections < subv.label_mask.shape[self.axis])]\n slices[self.axis] = (label_sections,)\n subv.label_mask[slices] = False\n return subv\n else:\n # No augmentations to be made. Superclass will automatically return\n # next subvolume.\n return None\n\n\nclass GaussianNoiseAugmentGenerator(SubvolumeAugmentGenerator):\n \"\"\"Repeats subvolumes from a subvolume generator with Gaussian noise.\n\n For each subvolume in the original generator, this generator will yield two\n subvolumes: the original subvolume and the subvolume with multiplicative\n and additive Gaussian noise applied to the image data.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n return_both : bool\n If true, return both the original and augmented volume in sequence.\n If false, return either with equal probability.\n axis : int\n Axis along which noise will be applied independently. For example,\n 0 will apply different noise to each z-section. -1 will apply\n uniform noise to the entire subvolume.\n multiplicative : float\n Standard deviation for 1-mean Gaussian multiplicative noise.\n multiplicative : float\n Standard deviation for 0-mean Gaussian additive noise.\n \"\"\"\n def __init__(self, subvolume_generator, return_both, axis, multiplicative, additive):\n super(GaussianNoiseAugmentGenerator, self).__init__(subvolume_generator, return_both)\n self.axis = axis\n self.multiplicative = multiplicative\n self.additive = additive\n\n def augment_subvolume(self):\n subv = self.subvolume\n\n # Generate a transformed shape that will apply vector addition\n # and multiplication along to correct axis.\n shape_xform = np.ones((1, 3), dtype=np.int32).ravel()\n shape_xform[self.axis] = -1\n\n dim_size = 1 if self.axis == -1 else self.shape[self.axis]\n mul_noise = np.random.normal(1.0, self.multiplicative, dim_size).astype(subv.image.dtype)\n add_noise = np.random.normal(0.0, self.additive, dim_size).astype(subv.image.dtype)\n\n subv = Subvolume(subv.image * mul_noise.reshape(shape_xform) + add_noise.reshape(shape_xform),\n subv.label_mask,\n subv.seed,\n subv.label_id)\n return subv\n\n\nclass ContrastAugmentGenerator(SubvolumeAugmentGenerator):\n \"\"\"Repeats subvolumes from a subvolume generator with altered contrast.\n\n For each subvolume in the original generator, this generator will yield the\n original subvolume and may yield a subvolume with image intensity contrast.\n\n Currently this augmentation performs simple rescaling of intensity values,\n not histogram based methods. This simple approach still yields results\n resembling TEM artifacts. A single rescaling is chosen for all selected\n sections in each subvolume, not independently per selected section.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n return_both : bool\n If true, return both the original and augmented volume in sequence.\n If false, return either with equal probability.\n axis : int\n Axis along which contrast may be altered. For example, 0 will alter\n contrast by z-sections.\n probability : float\n Independent probability that each plane of data along axis is altered.\n scaling_mean, scaling_std, center_mean, center_std : float\n Normal distribution parameters for the rescaling of intensity values.\n \"\"\"\n def __init__(self, subvolume_generator, return_both, axis, probability,\n scaling_mean, scaling_std, center_mean, center_std):\n super(ContrastAugmentGenerator, self).__init__(subvolume_generator, return_both)\n self.axis = axis\n self.probability = probability\n self.scaling_mean = scaling_mean\n self.scaling_std = scaling_std\n self.center_mean = center_mean\n self.center_std = center_std\n\n def augment_subvolume(self):\n rolls = np.random.sample(self.shape[self.axis])\n sections = np.where(rolls < self.probability)\n\n if sections and sections[0].size:\n subv = self.subvolume\n subv = Subvolume(subv.image.copy(),\n subv.label_mask,\n subv.seed,\n subv.label_id)\n slices = [slice(None), slice(None), slice(None)]\n slices[self.axis] = sections\n data = subv.image[slices]\n old_min = data.min()\n old_max = data.max()\n scaling = np.random.normal(self.scaling_mean, self.scaling_std)\n center = np.random.normal(self.center_mean, self.center_std)\n data = scaling*(data - old_min) + 0.5*scaling*center*(old_max - old_min) + old_min\n subv.image[slices] = data\n return subv\n else:\n return None\n\n\nclass MaskedArtifactAugmentGenerator(SubvolumeAugmentGenerator):\n \"\"\"Repeats subvolumes from a subvolume generator with artifact data added.\n\n For each subvolume in the original generator, this generator will yield the\n original subvolume and may yield a subvolume with planes of image mixed\n with artifact data from a separate volume.\n\n Parameters\n ----------\n subvolume_generator : SubvolumeGenerator\n return_both : bool\n If true, return both the original and augmented volume in sequence.\n If false, return either with equal probability.\n axis : int\n probability : float\n Independent probability that each plane of data along axis has\n artifacts.\n artifact_volume_file : string\n Filename of an TOML descriptor of an HDF5 dataset with image and mask\n data channels. Only the dataset named 'Artifacts' from this descriptor\n will be used. Mask data should be a float that will be interpreted\n as an alpha for blending image data from this artifact file with\n the original subvolume image data.\n \"\"\"\n def __init__(self, subvolume_generator, return_both, axis, probability, artifact_volume_file, cache):\n super(MaskedArtifactAugmentGenerator, self).__init__(subvolume_generator, return_both)\n self.axis = axis\n self.probability = probability\n if 'artifacts' not in cache:\n vol = HDF5Volume.from_toml(artifact_volume_file)['Artifacts']\n cache['mask'] = NdarrayVolume(\n vol.world_coord_to_local(vol.resolution),\n image_data=vol.world_mat_to_local(vol.mask_data[:]))\n vol.mask_data = None\n cache['artifacts'] = vol.to_memory_volume()\n self.mask = cache['mask']\n self.artifacts = cache['artifacts']\n artifact_shape = self.shape.copy()\n artifact_shape[self.axis] = 1\n self.art_bounds_gen = self.artifacts.subvolume_bounds_generator(shape=artifact_shape)\n\n def augment_subvolume(self):\n rolls = np.random.sample(self.shape[self.axis])\n artifact_sections = np.where(rolls < self.probability)\n\n if artifact_sections and artifact_sections[0].size:\n subv = self.subvolume\n subv = Subvolume(subv.image.copy(),\n subv.label_mask,\n subv.seed,\n subv.label_id)\n slices = [slice(None), slice(None), slice(None)]\n for z in artifact_sections[0]:\n slices[self.axis] = z\n mask_found = False\n # Since artifact data is usually sparse, reject patches\n # that have all zero mask.\n while not mask_found:\n art_bounds = six.next(self.art_bounds_gen)\n mask = self.mask.get_subvolume(art_bounds).image\n if mask.max() == 0.0:\n continue\n mask_found = True\n art = self.artifacts.get_subvolume(art_bounds).image\n raw = subv.image[slices]\n subv.image[slices] = raw * (1.0 - mask) + art * mask\n return subv\n else:\n return None\n\n\nclass Volume(object):\n DIM = DimOrder(Z=0, Y=1, X=2)\n\n def __init__(self, resolution, image_data=None, label_data=None, mask_data=None):\n self.resolution = resolution\n self.image_data = image_data\n self.label_data = label_data\n self.mask_data = mask_data\n self._mask_bounds = None\n\n def local_coord_to_world(self, a):\n return a\n\n def world_coord_to_local(self, a):\n return a\n\n def world_mat_to_local(self, m):\n return m\n\n @property\n def mask_bounds(self):\n if self._mask_bounds is not None:\n return self._mask_bounds\n if self.mask_data is None:\n return None\n\n # Explicitly copy the channel to memory. 3x speedup for np ops.\n mask_data = self.mask_data[:]\n\n self._mask_bounds = get_nonzero_aabb(mask_data)\n\n return self._mask_bounds\n\n @property\n def shape(self):\n return tuple(self.world_coord_to_local(np.array(self.image_data.shape)))\n\n def _get_downsample_from_resolution(self, resolution):\n resolution = np.asarray(resolution)\n downsample = np.log2(np.true_divide(resolution, self.resolution))\n if np.any(downsample < 0):\n raise ValueError('Requested resolution ({}) is higher than volume resolution ({}). '\n 'Upsampling is not supported.'.format(resolution, self.resolution))\n if not np.all(np.equal(np.mod(downsample, 1), 0)):\n raise ValueError('Requested resolution ({}) is not a power-of-2 downsample of '\n 'volume resolution ({}). '\n 'This is currently unsupported.'.format(resolution, self.resolution))\n return downsample.astype(np.int64)\n\n def downsample(self, resolution):\n downsample = self._get_downsample_from_resolution(resolution)\n if np.all(np.equal(downsample, 0)):\n return self\n return DownsampledVolume(self, downsample)\n\n def partition(self, partitioning, partition_index):\n if np.array_equal(partitioning, np.ones(3)) and np.array_equal(partition_index, np.zeros(3)):\n return self\n return PartitionedVolume(self, partitioning, partition_index)\n\n def sparse_wrapper(self, *args):\n return SparseWrappedVolume(self, *args)\n\n def subvolume_bounds_generator(self, shape=None, label_margin=None):\n return self.SubvolumeBoundsGenerator(self, shape, label_margin)\n\n def subvolume_generator(self, bounds_generator=None, **kwargs):\n if bounds_generator is None:\n if not kwargs:\n raise ValueError('Bounds generator arguments must be provided if no bounds generator is provided.')\n bounds_generator = self.subvolume_bounds_generator(**kwargs)\n return SubvolumeGenerator(self, bounds_generator)\n\n def get_subvolume(self, bounds):\n if bounds.start is None or bounds.stop is None:\n raise ValueError('This volume does not support sparse subvolume access.')\n\n image_subvol = self.image_data[\n bounds.start[0]:bounds.stop[0],\n bounds.start[1]:bounds.stop[1],\n bounds.start[2]:bounds.stop[2]]\n\n image_subvol = self.world_mat_to_local(image_subvol)\n if np.issubdtype(image_subvol.dtype, np.integer):\n image_subvol = image_subvol.astype(np.float32) / 256.0\n\n seed = bounds.seed\n if seed is None:\n seed = np.array(image_subvol.shape, dtype=np.int64) // 2\n\n if self.label_data is not None:\n label_start = bounds.start + bounds.label_margin\n label_stop = bounds.stop - bounds.label_margin\n\n label_subvol = self.label_data[\n label_start[0]:label_stop[0],\n label_start[1]:label_stop[1],\n label_start[2]:label_stop[2]]\n\n label_subvol = self.world_mat_to_local(label_subvol)\n\n label_id = bounds.label_id\n if label_id is None:\n label_id = label_subvol[tuple(seed - bounds.label_margin)]\n label_mask = label_subvol == label_id\n else:\n label_mask = None\n label_id = None\n\n return Subvolume(image_subvol, label_mask, seed, label_id)\n\n class SubvolumeBoundsGenerator(six.Iterator):\n def __init__(self, volume, shape, label_margin=None):\n self.volume = volume\n self.shape = shape\n self.margin = np.floor_divide(self.shape, 2).astype(np.int64)\n if label_margin is None:\n label_margin = np.zeros(3, dtype=np.int64)\n self.label_margin = label_margin\n self.skip_blank_sections = True\n self.ctr_min = self.margin\n self.ctr_max = (np.array(self.volume.shape) - self.margin - 1).astype(np.int64)\n self.random = np.random.RandomState(CONFIG.random_seed)\n\n # If the volume has a mask channel, further limit ctr_min and\n # ctr_max to lie inside a margin in the AABB of the mask.\n if self.volume.mask_data is not None:\n mask_min, mask_max = self.volume.mask_bounds\n\n mask_min = self.volume.world_coord_to_local(mask_min)\n mask_max = self.volume.world_coord_to_local(mask_max)\n\n self.ctr_min = np.maximum(self.ctr_min, mask_min + self.label_margin)\n self.ctr_max = np.minimum(self.ctr_max, mask_max - self.label_margin - 1)\n\n if np.any(self.ctr_min >= self.ctr_max):\n raise ValueError('Cannot generate subvolume bounds: bounds ({}, {}) too small for shape ({})'.format(\n np.array_str(self.ctr_min), np.array_str(self.ctr_max), np.array_str(self.shape)))\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.random.seed(0)\n\n def __next__(self):\n while True:\n ctr = np.array([self.random.randint(self.ctr_min[n], self.ctr_max[n])\n for n in range(3)]).astype(np.int64)\n start = ctr - self.margin\n stop = ctr + self.margin + np.mod(self.shape, 2).astype(np.int64)\n\n # If the volume has a mask channel, only accept subvolumes\n # entirely contained in it.\n if self.volume.mask_data is not None:\n start_local = self.volume.world_coord_to_local(start + self.label_margin)\n stop_local = self.volume.world_coord_to_local(stop - self.label_margin)\n mask = self.volume.mask_data[\n start_local[0]:stop_local[0],\n start_local[1]:stop_local[1],\n start_local[2]:stop_local[2]]\n if not mask.all():\n logging.debug('Skipping subvolume not entirely in mask.')\n continue\n\n # Skip subvolumes with seeds in blank sections.\n if self.skip_blank_sections and self.volume.image_data is not None:\n if self.volume.image_data[tuple(self.volume.local_coord_to_world(ctr))] == 0:\n logging.debug('Skipping subvolume with seed in blank section.')\n continue\n\n # Only accept subvolumes where the central seed voxel will be\n # of a uniform label after downsampling. For more stringent\n # seed region uniformity filtering, see has_uniform_seed_margin.\n if self.volume.label_data is None:\n label_id = None\n break\n seed_min = self.volume.local_coord_to_world(ctr)\n seed_max = self.volume.local_coord_to_world(ctr + 1)\n label_ids = self.volume.label_data[\n seed_min[0]:seed_max[0],\n seed_min[1]:seed_max[1],\n seed_min[2]:seed_max[2]]\n if (label_ids == label_ids.item(0)).all():\n label_id = label_ids.item(0)\n break\n\n return SubvolumeBounds(start, stop, label_id=label_id, label_margin=self.label_margin)\n\n\nclass NdarrayVolume(Volume):\n \"\"\"A NumPy ndarray-backed volume.\n\n Since all volumes assume image and label data are ndarray-like, this class\n exists mostly as a bookkeeping convenience to make actual ndarray volumes\n explicit.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(NdarrayVolume, self).__init__(*args, **kwargs)\n self.image_data.flags.writeable = False\n if self.label_data is not None:\n self.label_data.flags.writeable = False\n\n\nclass VolumeView(Volume):\n def __init__(self, parent, *args, **kwargs):\n super(VolumeView, self).__init__(*args, **kwargs)\n self.parent = parent\n\n def local_to_parent(self, a):\n return a\n\n def local_coord_to_world(self, a):\n return self.parent.local_coord_to_world(self.local_to_parent(a))\n\n def parent_to_local(self, a):\n return a\n\n def world_coord_to_local(self, a):\n return self.parent_to_local(self.parent.world_coord_to_local(a))\n\n def world_mat_to_local(self, m):\n return self.parent.world_mat_to_local(m)\n\n @property\n def mask_bounds(self):\n return self.parent.mask_bounds\n\n @property\n def shape(self):\n return self.parent.shape\n\n def get_subvolume(self, bounds):\n # assumes bounds given are in local coordinates\n parent_start = self.local_to_parent(bounds.start) if bounds.start is not None else None\n parent_stop = self.local_to_parent(bounds.stop) if bounds.stop is not None else None\n parent_seed = self.local_to_parent(bounds.seed) if bounds.seed is not None else None\n parent_bounds = SubvolumeBounds(start=parent_start,\n stop=parent_stop,\n seed=parent_seed,\n label_id=bounds.label_id,\n label_margin=bounds.label_margin)\n return self.parent.get_subvolume(parent_bounds)\n\n\nclass PartitionedVolume(VolumeView):\n \"\"\"Wrap an existing volume for partitioned access.\n\n Subvolume accesses to this volume will be offset and clipped to a partition\n of the wrapped volume.\n\n Parameters\n ----------\n parent : Volume\n The volume to wrap.\n partitioning : iterable of int\n Number of partitions along each axis. Only one axis should be greater\n than 1.\n partition_index : iterable of int\n Index of the partition which this volume will represent.\n \"\"\"\n def __init__(self, parent, partitioning, partition_index):\n super(PartitionedVolume, self).__init__(\n parent,\n parent.resolution,\n image_data=parent.image_data,\n label_data=parent.label_data,\n mask_data=parent.mask_data)\n self.partitioning = np.asarray(partitioning)\n self.partition_index = np.asarray(partition_index)\n partition_shape = np.floor_divide(np.array(self.parent.shape), self.partitioning)\n self.bounds = ((np.multiply(partition_shape, self.partition_index)).astype(np.int64),\n (np.multiply(partition_shape, self.partition_index + 1)).astype(np.int64))\n\n def local_to_parent(self, a):\n return a + self.bounds[0]\n\n def parent_to_local(self, a):\n return a - self.bounds[0]\n\n @property\n def mask_bounds(self):\n if self.parent.mask_bounds is None:\n return None\n else:\n bound_min = np.maximum(self.parent.mask_bounds[0], self.bounds[0])\n bound_max = np.minimum(self.parent.mask_bounds[1], self.bounds[1])\n return bound_min, bound_max\n\n @property\n def shape(self):\n return tuple(self.bounds[1] - self.bounds[0])\n\n\nclass DownsampledVolume(VolumeView):\n \"\"\"Wrap an existing volume for downsampled access.\n\n Subvolume accesses to this volume will be downsampled, but continue to use\n the wrapped volume and its data at the original resolution.\n\n Parameters\n ----------\n parent : Volume\n The volume to wrap.\n downsample : iterable of int\n Integral zoom levels to downsample the wrapped volume.\n \"\"\"\n def __init__(self, parent, downsample):\n self.scale = np.exp2(downsample).astype(np.int64)\n super(DownsampledVolume, self).__init__(\n parent,\n np.multiply(parent.resolution, self.scale),\n image_data=parent.image_data,\n label_data=parent.label_data,\n mask_data=parent.mask_data)\n\n def local_to_parent(self, a):\n return np.multiply(a, self.scale)\n\n def parent_to_local(self, a):\n return np.floor_divide(a, self.scale)\n\n @property\n def shape(self):\n return tuple(np.floor_divide(np.array(self.parent.shape), self.scale))\n\n def get_subvolume(self, bounds):\n subvol_shape = bounds.stop - bounds.start\n label_shape = subvol_shape - 2 * bounds.label_margin\n parent_bounds = SubvolumeBounds(self.local_to_parent(bounds.start),\n self.local_to_parent(bounds.stop),\n label_margin=self.local_to_parent(bounds.label_margin))\n subvol = self.parent.get_subvolume(parent_bounds)\n subvol.image = subvol.image.reshape(\n [subvol_shape[0], self.scale[0],\n subvol_shape[1], self.scale[1],\n subvol_shape[2], self.scale[2]]).mean(5).mean(3).mean(1)\n\n if subvol.label_mask is not None:\n # Downsample body mask by considering blocks where the majority\n # of voxels are in the body to be in the body. Alternatives are:\n # - Conjunction (tends to introduce false splits)\n # - Disjunction (tends to overdilate and merge)\n # - Mode label (computationally expensive)\n if CONFIG.volume.label_downsampling == 'conjunction':\n subvol.label_mask = subvol.label_mask.reshape(\n [label_shape[0], self.scale[0],\n label_shape[1], self.scale[1],\n label_shape[2], self.scale[2]]).all(5).all(3).all(1)\n else:\n subvol.label_mask = subvol.label_mask.reshape(\n [label_shape[0], self.scale[0],\n label_shape[1], self.scale[1],\n label_shape[2], self.scale[2]]).mean(5).mean(3).mean(1) > 0.5\n\n # Note that this is not a coordinate xform to parent in the typical\n # sense, just a rescaling of the coordinate in the subvolume-local\n # coordinates. Hence no similar call in VolumeView.get_subvolume.\n subvol.seed = self.parent_to_local(subvol.seed)\n\n return subvol\n\n\nclass SparseWrappedVolume(VolumeView):\n \"\"\"Wrap a existing volume for memory cached block sparse access.\"\"\"\n def __init__(self, parent, image_leaf_shape=None, label_leaf_shape=None):\n if image_leaf_shape is None:\n image_leaf_shape = list(CONFIG.model.input_fov_shape)\n if label_leaf_shape is None:\n label_leaf_shape = list(CONFIG.model.input_fov_shape)\n\n image_data = OctreeVolume(image_leaf_shape,\n (np.zeros(3), parent.image_data.shape),\n parent.image_data.dtype,\n populator=self.image_populator)\n label_data = OctreeVolume(label_leaf_shape,\n (np.zeros(3), parent.label_data.shape),\n parent.label_data.dtype,\n populator=self.label_populator)\n\n super(SparseWrappedVolume, self).__init__(\n parent,\n parent.resolution,\n image_data=image_data,\n label_data=label_data)\n\n def image_populator(self, bounds):\n return self.parent.image_data[\n bounds[0][0]:bounds[1][0],\n bounds[0][1]:bounds[1][1],\n bounds[0][2]:bounds[1][2]]\n\n def label_populator(self, bounds):\n return self.parent.label_data[\n bounds[0][0]:bounds[1][0],\n bounds[0][1]:bounds[1][1],\n bounds[0][2]:bounds[1][2]]\n\n\nclass HDF5Volume(Volume):\n \"\"\"A volume backed by data views to HDF5 file arrays.\n\n Parameters\n ----------\n orig_file : str\n Filename of the HDF5 file to load.\n image_dataaset : str\n Full dataset path including groups to the raw image data array.\n label_dataset : str\n Full dataset path including groups to the object label data array.\n \"\"\"\n @staticmethod\n def from_toml(filename):\n from keras.utils.data_utils import get_file\n\n volumes = {}\n with open(filename, 'rb') as fin:\n datasets = toml.load(fin).get('dataset', [])\n for dataset in datasets:\n hdf5_file = dataset['hdf5_file']\n if dataset.get('use_keras_cache', False):\n hdf5_file = get_file(hdf5_file, dataset['download_url'], md5_hash=dataset.get('download_md5', None))\n image_dataset = dataset.get('image_dataset', None)\n label_dataset = dataset.get('label_dataset', None)\n mask_dataset = dataset.get('mask_dataset', None)\n mask_bounds = dataset.get('mask_bounds', None)\n resolution = dataset.get('resolution', None)\n hdf5_pathed_file = os.path.join(os.path.dirname(filename), hdf5_file)\n volume = HDF5Volume(hdf5_pathed_file,\n image_dataset,\n label_dataset,\n mask_dataset,\n mask_bounds=mask_bounds)\n # If the volume configuration specifies an explicit resolution,\n # override any provided in the HDF5 itself.\n if resolution:\n logging.info('Overriding resolution for volume \"%s\"', dataset['name'])\n volume.resolution = np.array(resolution)\n volumes[dataset['name']] = volume\n\n return volumes\n\n @staticmethod\n def write_file(filename, resolution, **kwargs):\n h5file = h5py.File(filename, 'w')\n config = {'hdf5_file': os.path.basename(filename)}\n channels = ['image', 'label', 'mask']\n default_datasets = {\n 'image': 'volumes/raw',\n 'label': 'volumes/labels/neuron_ids',\n 'mask': 'volumes/labels/mask',\n }\n for channel in channels:\n data = kwargs.get('{}_data'.format(channel), None)\n dataset_name = kwargs.get('{}_dataset'.format(channel), default_datasets[channel])\n if data is not None:\n dataset = h5file.create_dataset(dataset_name, data=data, dtype=data.dtype)\n dataset.attrs['resolution'] = resolution\n config['{}_dataset'.format(channel)] = dataset_name\n\n h5file.close()\n\n return config\n\n def __init__(self, orig_file, image_dataset, label_dataset, mask_dataset, mask_bounds=None):\n logging.debug('Loading HDF5 file \"{}\"'.format(orig_file))\n self.file = h5py.File(orig_file, 'r')\n self.resolution = None\n self._mask_bounds = tuple(map(np.asarray, mask_bounds)) if mask_bounds is not None else None\n\n if image_dataset is None and label_dataset is None:\n raise ValueError('HDF5 volume must have either an image or label dataset: {}'.format(orig_file))\n\n if image_dataset is not None:\n self.image_data = self.file[image_dataset]\n if 'resolution' in self.file[image_dataset].attrs:\n self.resolution = np.array(self.file[image_dataset].attrs['resolution'])\n\n if label_dataset is not None:\n self.label_data = self.file[label_dataset]\n if 'resolution' in self.file[label_dataset].attrs:\n resolution = np.array(self.file[label_dataset].attrs['resolution'])\n if self.resolution is not None and not np.array_equal(self.resolution, resolution):\n logging.warning('HDF5 image and label dataset resolutions differ in %s: %s, %s',\n orig_file, self.resolution, resolution)\n else:\n self.resolution = resolution\n else:\n self.label_data = None\n\n if mask_dataset is not None:\n self.mask_data = self.file[mask_dataset]\n else:\n self.mask_data = None\n\n if image_dataset is None:\n self.image_data = np.full_like(self.label_data, np.NaN, dtype=np.float32)\n\n if self.resolution is None:\n self.resolution = np.ones(3)\n\n def to_memory_volume(self):\n data = ['image_data', 'label_data', 'mask_data']\n data = {\n k: self.world_mat_to_local(getattr(self, k)[:])\n for k in data if getattr(self, k) is not None}\n return NdarrayVolume(self.world_coord_to_local(self.resolution), **data)\n\n\nclass ImageStackVolume(Volume):\n \"\"\"A volume for block sparse access to image pyramids over HTTP.\n\n Coordinate Systems\n ----------\n Real: Physical coordinates, generally measured in nanometers\n World: pixel coordinates, starts at (0,0,0) and accounts for pixel resolution\n often (4x4x40) nanometers per pixel\n Local: Downsampled pixel space\n\n Parameters\n ----------\n bounds : iterable of int\n Shape of the stack at zoom level 0 in pixels.\n resolution : iterable of float\n Resolution of the stack at zoom level 0 in nm.\n tile_width, tile_height : int\n Size of tiles in pixels\n format_url : str\n Format string for building tile URLs from tile parameters.\n zoom_level : int, optional\n Zoom level to use for this volume.\n missing_z : iterable of int, optional\n Voxel z-indices where data is not available.\n image_leaf_shape : tuple of int or ndarray, optional\n Shape of image octree leaves in voxels. Defaults to 10 stacked tiles.\n label_leaf_shape : tuple of int or ndarray, optional\n Shape of label octree leaves in voxels. Defaults to FFN model FOV.\n \"\"\"\n @staticmethod\n def from_catmaid_stack(stack_info, tile_source_parameters):\n # See https://catmaid.readthedocs.io/en/stable/tile_sources.html\n format_url = {\n 1: '{source_base_url}{{z}}/{{row}}_{{col}}_{{zoom_level}}.{file_extension}',\n 4: '{source_base_url}{{z}}/{{zoom_level}}/{{row}}_{{col}}.{file_extension}',\n 5: '{source_base_url}{{zoom_level}}/{{z}}/{{row}}/{{col}}.{file_extension}',\n 7: '{source_base_url}largeDataTileSource/{tile_width}/{tile_height}/'\n '{{zoom_level}}/{{z}}/{{row}}/{{col}}.{file_extension}',\n 9: '{source_base_url}{{z}}/{{row}}_{{col}}_{{zoom_level}}.{file_extension}',\n }[tile_source_parameters['tile_source_type']].format(**tile_source_parameters)\n bounds = np.flipud(np.array(stack_info['bounds'], dtype=np.int64))\n resolution = np.flipud(np.array(stack_info['resolution']))\n translation = np.flipud(np.array(stack_info['translation']))\n tile_width = int(tile_source_parameters['tile_width'])\n tile_height = int(tile_source_parameters['tile_height'])\n return ImageStackVolume(bounds, resolution, translation, tile_width, tile_height,\n format_url, missing_z=stack_info.get(\"broken_slices\", None))\n\n def from_toml(filename):\n volumes = {}\n with open(filename, \"rb\") as fin:\n datasets = toml.load(fin).get(\"ImageStack\", [])\n for dataset in datasets:\n # stack info\n si = [\n \"bounds\",\n \"resolution\",\n \"translation\",\n \"broken_slices\",\n ]\n # tile stack parameters\n tsp = [\n \"source_base_url\",\n \"file_extension\",\n \"tile_width\",\n \"tile_height\",\n \"tile_source_type\",\n ]\n volume = ImageStackVolume.from_catmaid_stack(\n {si[key]: dataset[key] for key in si},\n {tsp[key]: dataset[key] for key in tsp},\n )\n volumes[dataset[\"title\"]] = volume\n\n return volumes\n\n def __init__(self, bounds, orig_resolution, translation, tile_width, tile_height,\n tile_format_url, zoom_level=0, missing_z=None, image_leaf_shape=None):\n self.orig_bounds = bounds\n self.orig_resolution = orig_resolution\n self.translation = translation\n self.tile_width = tile_width\n self.tile_height = tile_height\n self.tile_format_url = tile_format_url\n self.mask_data = None\n\n self.zoom_level = int(zoom_level)\n if missing_z is None:\n missing_z = []\n self.missing_z = frozenset(missing_z)\n if image_leaf_shape is None:\n image_leaf_shape = [10, tile_height, tile_width]\n\n self.scale = np.exp2(np.array([0, self.zoom_level, self.zoom_level])).astype(np.int64)\n\n data_shape = (np.zeros(3), np.divide(bounds, self.scale).astype(np.int64))\n self.image_data = OctreeVolume(image_leaf_shape,\n data_shape,\n 'float32',\n populator=self.image_populator)\n\n self.label_data = None\n\n def local_coord_to_world(self, a):\n return np.multiply(a, self.scale)\n\n def world_coord_to_local(self, a):\n return np.floor_divide(a, self.scale)\n\n def real_coord_to_world(self, a):\n return np.floor_divide(a - self.translation, self.orig_resolution)\n\n def world_coord_to_real(self, a):\n return np.multiply(a, self.orig_resolution) + self.translation\n\n @property\n def resolution(self):\n return self.orig_resolution * np.exp2([0, self.zoom_level, self.zoom_level])\n\n def downsample(self, resolution):\n downsample = self._get_downsample_from_resolution(resolution)\n zoom_level = np.min(downsample[[self.DIM.X, self.DIM.Y]])\n if zoom_level > 0:\n return ImageStackVolume(\n self.orig_bounds,\n self.orig_resolution,\n self.translation,\n self.tile_width,\n self.tile_height,\n self.tile_format_url,\n zoom_level=self.zoom_level + zoom_level,\n missing_z=self.missing_z,\n image_leaf_shape=self.image_data.leaf_shape).downsample(resolution)\n if np.all(np.equal(downsample, 0)):\n return self\n return DownsampledVolume(self, downsample)\n\n def subvolume_bounds_generator(self, sparse_margin=None, **kwargs):\n if sparse_margin is not None:\n if kwargs:\n raise ValueError('sparse_margin can not be combined with other arguments.')\n return self.SparseSubvolumeBoundsGenerator(self, sparse_margin)\n return super(ImageStackVolume, self).subvolume_bounds_generator(**kwargs)\n\n def get_subvolume(self, bounds):\n if bounds.start is None or bounds.stop is None:\n image_subvol = self.image_data\n label_subvol = self.label_data\n else:\n image_subvol = self.image_data[\n bounds.start[0]:bounds.stop[0],\n bounds.start[1]:bounds.stop[1],\n bounds.start[2]:bounds.stop[2]]\n label_subvol = None\n\n if np.issubdtype(image_subvol.dtype, np.integer):\n raise ValueError('Sparse volume access does not support image data coercion.')\n\n seed = bounds.seed\n if seed is None:\n seed = np.array(image_subvol.shape, dtype=np.int64) // 2\n\n return Subvolume(image_subvol, label_subvol, seed, bounds.label_id)\n\n def image_populator(self, bounds):\n image_subvol = np.zeros(tuple(bounds[1] - bounds[0]), dtype=np.float32)\n col_range = list(map(int, (math.floor(bounds[0][self.DIM.X] / self.tile_width),\n math.ceil(bounds[1][self.DIM.X] / self.tile_width))))\n row_range = list(map(int, (math.floor(bounds[0][self.DIM.Y] / self.tile_height),\n math.ceil(bounds[1][self.DIM.Y] / self.tile_height))))\n tile_size = np.array([1, self.tile_height, self.tile_width]).astype(np.int64)\n for z in xrange(bounds[0][self.DIM.Z], bounds[1][self.DIM.Z]):\n if z in self.missing_z:\n image_subvol[int(z - bounds[0][self.DIM.Z]), :, :] = 0\n continue\n for r in xrange(*row_range):\n for c in xrange(*col_range):\n url = self.tile_format_url.format(zoom_level=self.zoom_level, z=z, row=r, col=c)\n try:\n im = np.array(Image.open(requests.get(url, stream=True).raw))\n # If the image is multichannel, throw our hands up and\n # just use the first channel.\n if im.ndim > 2:\n im = im[:, :, 0].squeeze()\n im = im / 256.0\n except IOError:\n logging.debug('Failed to load tile: %s', url)\n im = np.full((self.tile_height, self.tile_width), 0, dtype=np.float32)\n tile_coord = np.array([z, r, c]).astype(np.int64)\n tile_loc = np.multiply(tile_coord, tile_size)\n\n subvol = (np.maximum(np.zeros(3), tile_loc - bounds[0]).astype(np.int64),\n np.minimum(np.array(image_subvol.shape),\n tile_loc + tile_size - bounds[0]).astype(np.int64))\n tile_sub = (np.maximum(np.zeros(3), bounds[0] - tile_loc).astype(np.int64),\n np.minimum(tile_size, bounds[1] - tile_loc).astype(np.int64))\n\n image_subvol[subvol[0][self.DIM.Z],\n subvol[0][self.DIM.Y]:subvol[1][self.DIM.Y],\n subvol[0][self.DIM.X]:subvol[1][self.DIM.X]] = \\\n im[tile_sub[0][self.DIM.Y]:tile_sub[1][self.DIM.Y],\n tile_sub[0][self.DIM.X]:tile_sub[1][self.DIM.X]]\n\n return image_subvol\n\n class SparseSubvolumeBoundsGenerator(six.Iterator):\n def __init__(self, volume, margin):\n self.volume = volume\n self.margin = np.asarray(margin).astype(np.int64)\n self.ctr_min = self.margin\n self.ctr_max = (np.array(self.volume.shape) - self.margin - 1).astype(np.int64)\n self.random = np.random.RandomState(CONFIG.random_seed)\n\n @property\n def shape(self):\n return self.volume.shape\n\n def __iter__(self):\n return self\n\n def reset(self):\n self.random.seed(0)\n\n def __next__(self):\n ctr = np.array([self.random.randint(self.ctr_min[n], self.ctr_max[n])\n for n in range(3)]).astype(np.int64)\n return SubvolumeBounds(seed=ctr)\n\n\nclass N5Volume(Volume):\n \"\"\"A Volume for using an N5 filesystem for image retrieval\n\n Parameters\n ----------\n root_path : string\n /absolute/path/to/data.n5\n dataset : dict of dicts (dataset name to dataset config)\n possible keys: (\"mask\",\"labels\",\"image\")\n values: {\"path\": path, \"dtype\": dtype, \"read_only\": read_only}\n resolution : iterable of float\n Resolution of the pixels at zoom level 0 in nm.\n translation : iterable of float\n Translational offset in nm s.t. for given coordinate\n a in pixel space, a*resolution+translation = b where\n b is in the desired nm coordinates\n bounds: iterable of int, optional\n Shape of the stack at zoom level 0 in pixels.\n necessary if the volume is missing an attributes file\n tile_width, tile_height : int, optional\n Size of tiles in pixels\n necessary if the volume is missing an attributes file\n \"\"\"\n\n def from_toml(filename):\n volumes = {}\n with open(filename, \"rb\") as fin:\n volume_configs = toml.load(fin).get(\"N5Volume\", [])\n for volume_config in volume_configs:\n root_path = volume_config[\"root_path\"]\n datasets = volume_config[\"datasets\"]\n resolution = volume_config.get(\"resolution\", None)\n translation = volume_config.get[\"translation\", None]\n bounds = volume_config.get(\"bounds\", None)\n volume = N5Volume(\n root_path,\n datasets,\n bounds,\n resolution,\n translation,\n )\n volumes[volume_config[\"title\"]] = volume\n\n return volumes\n\n def __init__(\n self,\n root_path,\n datasets,\n bounds=None,\n resolution=None,\n translation=None,\n ):\n\n self._dtype_map = {\n \"UINT8\": np.uint8,\n \"UINT16\": np.uint16,\n \"UINT32\": np.uint32,\n \"UINT64\": np.uint64,\n \"INT8\": np.int8,\n \"INT16\": np.int16,\n \"INT32\": np.int32,\n \"INT64\": np.int64,\n \"FLOAT32\": np.float32,\n \"FLOAT64\": np.float64,\n }\n self.bounds = bounds\n self.resolution = resolution\n self.translation = translation\n\n self.scale = np.exp2(np.array([0, 0, 0])).astype(np.int64)\n self.data_shape = (np.array([0, 0, 0]), self.bounds / self.scale)\n\n # Initialization of data sources done in setter methods\n self.root_path = root_path\n self.image_config = datasets.get(\"image\", None)\n self.mask_config = datasets.get(\"mask\", None)\n self.label_config = datasets.get(\"label\", None)\n\n @property\n def dtype_map(self):\n return self._dtype_map\n\n def local_coord_to_world(self, a):\n return np.multiply(a, self.scale)\n\n def world_coord_to_local(self, a):\n return np.floor_divide(a, self.scale)\n\n def real_coord_to_world(self, a):\n return np.floor_divide(a - self.translation, self.orig_resolution)\n\n def world_coord_to_real(self, a):\n return np.multiply(a, self.orig_resolution) + self.translation\n\n @property\n def octree_leaf_shape(self):\n return np.array([10, 10, 10])\n\n @property\n def image_config(self):\n return self._image_config\n\n @image_config.setter\n def image_config(self, dataset):\n self._image_config = dataset\n if dataset is not None:\n self._image_data = OctreeVolume(\n self.octree_leaf_shape,\n self.data_shape,\n self.dtype_map[dataset.get(\"dtype\", \"FLOAT32\")],\n populator=self.image_populator,\n )\n else:\n self._image_data = None\n\n @property\n def image_data(self):\n return self._image_data\n\n @property\n def mask_config(self):\n return self._mask_config\n\n @mask_config.setter\n def mask_config(self, dataset):\n self._mask_config = dataset\n if dataset is not None:\n self._mask_data = OctreeVolume(\n self.octree_leaf_shape,\n self.data_shape,\n self.dtype_map[dataset.get(\"dtype\", \"FLOAT32\")],\n populator=self.mask_populator,\n )\n else:\n self._mask_data = None\n\n @property\n def mask_data(self):\n return self._mask_data\n\n @property\n def label_config(self):\n return self._label_config\n\n @label_config.setter\n def label_config(self, dataset):\n self._label_config = dataset\n if dataset is not None:\n self._label_data = OctreeVolume(\n self.octree_leaf_shape,\n self.data_shape,\n self.dtype_map[dataset.get(\"dtype\", \"FLOAT32\")],\n populator=self.label_populator,\n )\n else:\n self._label_data = None\n\n @property\n def label_data(self):\n return self._label_data\n\n @property\n def image_n5(self):\n \"\"\"\n Create a new pyn5.Dataset every time you ask for image_n5.\n This is necessary to accomadate parrallel reads since multiple\n threads can't use the same reader.\n \"\"\"\n if self.image_config is not None:\n return pyn5.open(\n self.root_path,\n self.image_config.get(\"path\"),\n self.image_config.get(\"dtype\", \"UINT8\"),\n self.image_config.get(\"read_only\", True),\n )\n else:\n return None\n\n def image_populator(self, bounds):\n return pyn5.read(self.image_n5, (bounds[0], bounds[1]))\n\n @property\n def mask_n5(self):\n if self.mask_config is not None:\n return pyn5.open(\n self.root_path,\n self.mask_config.get(\"path\"),\n self.mask_config.get(\"dtype\", \"UINT8\"),\n self.mask_config.get(\"read_only\", True),\n )\n else:\n return None\n\n def mask_populator(self, bounds):\n return pyn5.read(self.mask_n5, (bounds[0], bounds[1]))\n\n @property\n def label_n5(self):\n if self.label_config is not None:\n return pyn5.open(\n self.root_path,\n self.label_config.get(\"path\"),\n self.label_config.get(\"dtype\", \"UINT8\"),\n self.label_config.get(\"read_only\", True),\n )\n else:\n return None\n\n def label_populator(self, bounds):\n return pyn5.read(self.label_n5, bounds)\n" ]
[ [ "numpy.ones", "numpy.multiply", "numpy.array_str", "numpy.any", "numpy.issubdtype", "numpy.asarray", "numpy.random.RandomState", "numpy.full_like", "numpy.transpose", "numpy.where", "numpy.fromstring", "numpy.minimum", "scipy.ndimage.label", "numpy.zeros", "numpy.equal", "numpy.exp2", "numpy.floor_divide", "numpy.count_nonzero", "numpy.mod", "scipy.ndimage.binary_erosion", "numpy.all", "numpy.min", "numpy.maximum", "numpy.array", "numpy.divide", "numpy.true_divide", "numpy.clip", "numpy.flip", "numpy.array_equal", "numpy.random.normal", "numpy.full", "numpy.random.sample" ] ]
DavidNaizheZhou/stanpy
[ "257072bd52154e9e4d68be957fd12eee1ad3dc56" ]
[ "tests/src/stanpy/test_reduction.py" ]
[ "import stanpy as stp\nimport numpy as np\nimport os\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\ndef test_multiple_w0():\n\n EI = 32000 # kN/m2\n l = 3 # m\n\n hinged_support = {\"w\": 0, \"M\": 0}\n roller_support = {\"w\": 0, \"M\": 0, \"H\": 0}\n fixed_support = {\"w\": 0, \"phi\": 0}\n\n s1 = {\"EI\": EI, \"l\": l, \"bc_i\": hinged_support, \"bc_k\": {\"w\": 0}, \"q\": 10}\n s2 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"q\": 10}\n # s2 = {\"EI\": EI, \"l\": l, \"q\": 10}\n s3 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"q\": 10}\n s4 = {\"EI\": EI, \"l\": l, \"bc_k\": roller_support}\n\n s = [s1, s2, s3, s4]\n\n x = np.linspace(0,4*l,5)\n Zi, Zk = stp.tr_solver(*s)\n Fx = stp.tr(*s, x=x)\n Zx = Fx.dot(Zi)\n\n path = os.path.join(dir_path, \"reduction_method_npz\", \"test_multiple_w0.npz\")\n # np.savez_compressed(path, Fx=Fx, Zx=Zx)\n npz = np.load(path)\n Zx_test = npz[\"Zx\"]\n Fx_test = npz[\"Fx\"]\n\n np.testing.assert_allclose(Fx, Fx_test,rtol=1e-5)\n np.testing.assert_allclose(Zx.round(10), Zx_test,rtol=1e-5)\n\ndef test_multiple_w0_M0():\n\n import numpy as np\n np.set_printoptions(precision=6, threshold=5000)\n import matplotlib.pyplot as plt\n import stanpy as stp\n\n EI = 32000 # kN/m2\n l = 3 # m\n\n hinged_support = {\"w\": 0, \"M\": 0}\n roller_support = {\"w\": 0, \"M\": 0, \"H\": 0}\n fixed_support = {\"w\": 0, \"phi\": 0}\n\n s1 = {\"EI\": EI, \"l\": l, \"bc_i\": hinged_support, \"bc_k\": {\"w\": 0}, \"q\": 10}\n s2 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"M\": 0}, \"q\": 8}\n # s2 = {\"EI\": EI, \"l\": l, \"q\": 10}\n s3 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"q\": 6}\n s4 = {\"EI\": EI, \"l\": l, \"bc_k\": roller_support}\n\n s = [s1, s2, s3, s4]\n\n\n x = np.sort(np.append(np.linspace(0,4*l,4000), [l,2*l, 3*l, 4*l]))\n\n Zi, Zk = stp.tr_solver(*s)\n Fx = stp.tr(*s, x=x)\n Zx = Fx.dot(Zi).round(10)\n \n path = os.path.join(dir_path, \"reduction_method_npz\", \"test_multiple_w0_M0.npz\")\n # np.savez_compressed(path, Fx=Fx, Zx=Zx)\n npz = np.load(path)\n Zx_test = npz[\"Zx\"]\n Fx_test = npz[\"Fx\"]\n\n np.testing.assert_allclose(Fx, Fx_test,rtol=1e-5)\n np.testing.assert_allclose(Zx, Zx_test,rtol=1e-5)\n\ndef test_multiple_w0_combination():\n \"\"\"testet einwertige Bindungen mit zusammengesetzten Stäben\n \"\"\"\n\n import numpy as np\n np.set_printoptions(precision=6, threshold=5000)\n import matplotlib.pyplot as plt\n import stanpy as stp\n\n EI = 32000 # kN/m2\n l = 3 # m\n\n hinged_support = {\"w\": 0, \"M\": 0}\n roller_support = {\"w\": 0, \"M\": 0, \"H\": 0}\n fixed_support = {\"w\": 0, \"phi\": 0}\n\n s1 = {\"EI\": EI, \"l\": l, \"bc_i\": hinged_support, \"bc_k\": {\"w\": 0}, \"q\": 10}\n # s2 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"M\": 0}, \"q\": 10}\n s2 = {\"EI\": EI, \"l\": l, \"q\": 8}\n s3 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"q\": 6}\n s4 = {\"EI\": EI, \"l\": l, \"bc_k\": roller_support}\n\n s = [s1, s2, s3, s4]\n\n x = np.sort(np.append(np.linspace(0,4*l,4000), [l,2*l, 3*l, 4*l]))\n\n Zi, Zk = stp.tr_solver(*s)\n Fx = stp.tr(*s, x=x)\n Zx = Fx.dot(Zi).round(10)\n \n path = os.path.join(dir_path, \"reduction_method_npz\", \"test_multiple_w0_combination.npz\")\n # np.savez_compressed(path, Fx=Fx, Zx=Zx)\n\n npz = np.load(path)\n Zx_test = npz[\"Zx\"]\n Fx_test = npz[\"Fx\"]\n\n np.testing.assert_allclose(Fx, Fx_test,rtol=1e-5)\n np.testing.assert_allclose(Zx, Zx_test,rtol=1e-5)\n\ndef test_large_system():\n import numpy as np\n import sympy as sym\n import stanpy as stp\n import matplotlib.pyplot as plt\n\n EI = 32000 # kN/m2\n P = 5 # kN\n q = 4 # kN/m\n l = 3 # m\n\n roller_support = {\"w\": 0, \"M\": 0, \"H\": 0}\n fixed_support = {\"w\": 0, \"phi\": 0}\n hinge = {\"M\": 0}\n\n s0 = {\"EI\": EI, \"l\": l, \"bc_i\": fixed_support, \"bc_k\": {\"w\": 0}}\n s1 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"q\": q}\n s2 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}}\n s3 = {\"EI\": EI, \"l\": l, \"bc_k\": hinge, \"q\": q, \"P\": (P, l)}\n s4 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}}\n s5 = {\"EI\": EI, \"l\": l, \"bc_k\": hinge}\n s6 = {\"EI\": EI, \"l\": l, \"bc_k\": roller_support, \"P\": (P, l / 2), }\n\n s = [s0, s1, s2, s3, s4, s5, s6]\n\n # fig, ax = plt.subplots(figsize=(12, 5))\n # stp.plot_system(ax, s=22, *s)\n # stp.plot_load(ax, *s, P_scale=0.5, q_scale=0.5)\n # ax.set_ylim(-0.5, 1)\n # plt.show()\n\n x = np.sort(np.append(np.linspace(0,7*l,70),[l,2*l, 3*l, 4*l, 5*l, 6*l]))\n Zi, Zk = stp.tr_solver(*s)\n Fx = stp.tr(*s, x=x)\n Zx = Fx.dot(Zi)\n\n path = os.path.join(dir_path, \"reduction_method_npz\", \"test_large_system.npz\")\n # np.savez_compressed(path, Fx=Fx, Zx=Zx)\n\n npz = np.load(path)\n Zx_test = npz[\"Zx\"]\n Fx_test = npz[\"Fx\"]\n\n np.testing.assert_allclose(Fx, Fx_test,rtol=1e-5)\n np.testing.assert_allclose(Zx, Zx_test,rtol=1e-5)\n\n # scale = 0.5\n # fig, ax = plt.subplots()\n # stp.plot_system(ax, *s, watermark=False)\n # stp.plot_M(\n # ax,\n # x=x,\n # Mx=Zx[:, 2],\n # annotate_x=[l,2*l, 3*l, 4*l, 5*l, 6*l],\n # fill_p=\"red\",\n # fill_n=\"blue\",\n # scale=scale,\n # alpha=0.2,\n # )\n\n # ax.set_ylim(-1, 1)\n # ax.axis('off')\n # plt.show()\n\ndef test_large_system_II():\n import numpy as np\n import sympy as sym\n import stanpy as stp\n import matplotlib.pyplot as plt\n\n EI = 32000 # kN/m2\n P = 5 # kN\n q = 4 # kN/m\n l = 3 # m\n\n roller_support = {\"w\": 0, \"M\": 0, \"H\": 0}\n fixed_support = {\"w\": 0, \"phi\": 0}\n hinge = {\"M\": 0}\n\n s0 = {\"EI\": EI, \"l\": l, \"bc_i\": fixed_support, \"bc_k\": {\"w\": 0}, \"N\": -1000}\n s1 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"q\": q, \"N\": -1000}\n s2 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"N\": -1000}\n s3 = {\"EI\": EI, \"l\": l, \"bc_k\": hinge, \"q\": q, \"P\": (P, l), \"N\": -1000}\n s4 = {\"EI\": EI, \"l\": l, \"bc_k\": {\"w\": 0}, \"N\": -1000}\n s5 = {\"EI\": EI, \"l\": l, \"bc_k\": hinge, \"N\": -1000}\n s6 = {\"EI\": EI, \"l\": l, \"bc_k\": roller_support, \"P\": (P, l / 2), \"N\": -1000}\n\n s = [s0, s1, s2, s3, s4, s5, s6]\n\n # fig, ax = plt.subplots(figsize=(12, 5))\n # stp.plot_system(ax, s=22, *s)\n # stp.plot_load(ax, *s, P_scale=0.5, q_scale=0.5)\n # ax.set_ylim(-0.5, 1)\n # plt.show()\n\n x = np.sort(np.append(np.linspace(0,7*l,70),[l,2*l, 3*l, 4*l, 5*l, 6*l]))\n Zi, Zk = stp.tr_solver(*s)\n Fx = stp.tr(*s, x=x)\n Zx = Fx.dot(Zi)\n\n path = os.path.join(dir_path, \"reduction_method_npz\", \"test_large_system_II.npz\")\n # np.savez_compressed(path, Fx=Fx, Zx=Zx)\n\n npz = np.load(path)\n Zx_test = npz[\"Zx\"]\n Fx_test = npz[\"Fx\"]\n\n np.testing.assert_allclose(Fx, Fx_test,rtol=1e-5)\n np.testing.assert_allclose(Zx, Zx_test,rtol=1e-5)\n\n # scale = 0.5\n # fig, ax = plt.subplots()\n # stp.plot_system(ax, *s, watermark=False)\n # stp.plot_M(\n # ax,\n # x=x,\n # Mx=Zx[:, 2],\n # annotate_x=[l,2*l, 3*l, 4*l, 5*l, 6*l],\n # fill_p=\"red\",\n # fill_n=\"blue\",\n # scale=scale,\n # alpha=0.2,\n # )\n\n # ax.set_ylim(-1, 1)\n # ax.axis('off')\n # plt.show()\n\ndef empty():\n import matplotlib.pyplot as plt\n import numpy as np\n\n EI = 32000 # kNm²\n GA = 20000 # kN\n l = 6 # m\n q = 4 # kN/m\n P = 1500 # kN\n H = 10 # kN\n\n fixed = {\"w\":0, \"phi\":0}\n hinged = {\"w\":0, \"M\":0, \"H\":0}\n\n s = {\"EI\":EI, \"GA\":GA, \"l\":l, \"q\":q, \"w_0\":0.03,\"N\":(-P ),\"P1\":(H, l/2),\"P2\":(H, l/3),\"P3\":(H, 2*l/3), \"bc_i\":fixed, \"bc_k\":hinged}\n fig, ax = plt.subplots()\n stp.plot_system(ax, s)\n stp.plot_load(ax, s)\n stp.plot_w_0(ax, s, scale=0.4, dy=-0.2)\n ax.set_ylim(-1,1)\n plt.show()\n x = np\n\n Zi, Zk = stp.tr_solver(s)\n Fxx = stp.tr(s)\n Zx = Fxx.dot(Zi)\n\n print(Zx)\n\nif __name__==\"__main__\":\n # test_large_system_II()\n empty()" ]
[ [ "numpy.load", "numpy.set_printoptions", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "numpy.testing.assert_allclose", "numpy.linspace" ] ]
lleiou/causalml
[ "2d3cacacad5ed3b0e57b593803a33c61c554f3b2" ]
[ "causalml/inference/tree/models.py" ]
[ "\"\"\"\nForest of trees-based ensemble methods for Uplift modeling on Classification\nProblem. Those methods include random forests and extremely randomized trees.\n\nThe module structure is the following:\n- The ``UpliftRandomForestClassifier`` base class implements different\n variants of uplift models based on random forest, with 'fit' and 'predict'\n method.\n- The ``UpliftTreeClassifier`` base class implements the uplift trees (without\n Bootstrapping for random forest), this class is called within\n ``UpliftRandomForestClassifier`` for constructing random forest.\n\"\"\"\n\n# Authors: Zhenyu Zhao <[email protected]>\n# Totte Harinen <[email protected]>\n\nfrom collections import defaultdict\nfrom joblib import Parallel, delayed\nimport multiprocessing as mp\nimport numpy as np\nfrom packaging import version\nimport pandas as pd\nimport scipy.stats as stats\nimport sklearn\nif version.parse(sklearn.__version__) >= version.parse('0.22.0'):\n from sklearn.utils._testing import ignore_warnings\nelse:\n from sklearn.utils.testing import ignore_warnings\n\n\nclass DecisionTree:\n \"\"\" Tree Node Class\n\n Tree node class to contain all the statistics of the tree node.\n\n Parameters\n ----------\n\n col : int, optional (default = -1)\n The column index for splitting the tree node to children nodes.\n\n value : float, optional (default = None)\n The value of the feature column to split the tree node to children nodes.\n\n trueBranch : object of DecisionTree\n The true branch tree node (feature > value).\n\n falseBranch : object of DecisionTree\n The false branch tree node (feature > value).\n\n results : dictionary\n The classification probability Pr(1) for each experiment group in the tree node.\n\n summary : dictionary\n Summary statistics of the tree nodes, including impurity, sample size, uplift score, etc.\n\n maxDiffTreatment : string\n The treatment name generating the maximum difference between treatment and control group.\n\n maxDiffSign : float\n The sign of the maximum difference (1. or -1.).\n\n nodeSummary : dictionary\n Summary statistics of the tree nodes {treatment: [y_mean, n]}, where y_mean stands for the target metric mean\n and n is the sample size.\n\n backupResults : dictionary\n The conversion probabilities in each treatment in the parent node {treatment: y_mean}. The parent node\n information is served as a backup for the children node, in case no valid statistics can be calculated from the\n children node, the parent node information will be used in certain cases.\n\n bestTreatment : string\n The treatment name providing the best uplift (treatment effect).\n\n upliftScore : list\n The uplift score of this node: [max_Diff, p_value], where max_Diff stands for the maximum treatment effect, and\n p_value stands for the p_value of the treatment effect.\n\n matchScore : float\n The uplift score by filling a trained tree with validation dataset or testing dataset.\n\n \"\"\"\n\n def __init__(self, col=-1, value=None, trueBranch=None, falseBranch=None,\n results=None, summary=None, maxDiffTreatment=None,\n maxDiffSign=1., nodeSummary=None, backupResults=None,\n bestTreatment=None, upliftScore=None, matchScore=None):\n self.col = col\n self.value = value\n self.trueBranch = trueBranch\n self.falseBranch = falseBranch\n self.results = results # None for nodes, not None for leaves\n self.summary = summary\n # the treatment with max( |p(y|treatment) - p(y|control)| )\n self.maxDiffTreatment = maxDiffTreatment\n # the sign for p(y|maxDiffTreatment) - p(y|control)\n self.maxDiffSign = maxDiffSign\n self.nodeSummary = nodeSummary\n self.backupResults = backupResults\n self.bestTreatment = bestTreatment\n self.upliftScore = upliftScore\n # match actual treatment for validation and testing\n self.matchScore = matchScore\n\n\n# Uplift Tree Classifier\nclass UpliftTreeClassifier:\n \"\"\" Uplift Tree Classifier for Classification Task.\n\n A uplift tree classifier estimates the individual treatment effect by modifying the loss function in the\n classification trees.\n\n The uplift tree classifier is used in uplift random forest to construct the trees in the forest.\n\n Parameters\n ----------\n\n evaluationFunction : string\n Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS'.\n\n max_features: int, optional (default=None)\n The number of features to consider when looking for the best split.\n\n max_depth: int, optional (default=3)\n The maximum depth of the tree.\n\n min_samples_leaf: int, optional (default=100)\n The minimum number of samples required to be split at a leaf node.\n\n min_samples_treatment: int, optional (default=10)\n The minimum number of samples required of the experiment group to be split at a leaf node.\n\n n_reg: int, optional (default=100)\n The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the\n parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods.\n\n control_name: string\n The name of the control group (other experiment groups will be regarded as treatment groups)\n\n normalization: boolean, optional (default=True)\n The normalization factor defined in Rzepakowski et al. 2012, correcting for tests with large number of splits\n and imbalanced treatment and control splits\n\n \"\"\"\n def __init__(self, max_features=None, max_depth=3, min_samples_leaf=100,\n min_samples_treatment=10, n_reg=100, evaluationFunction='KL',\n control_name=None, normalization=True):\n self.max_depth = max_depth\n self.min_samples_leaf = min_samples_leaf\n self.min_samples_treatment = min_samples_treatment\n self.n_reg = n_reg\n self.max_features = max_features\n if evaluationFunction == 'KL':\n self.evaluationFunction = self.evaluate_KL\n elif evaluationFunction == 'ED':\n self.evaluationFunction = self.evaluate_ED\n elif evaluationFunction == 'Chi':\n self.evaluationFunction = self.evaluate_Chi\n else:\n self.evaluationFunction = self.evaluate_CTS\n self.fitted_uplift_tree = None\n self.control_name = control_name\n self.normalization = normalization\n\n def fit(self, X, treatment, y):\n \"\"\" Fit the uplift model.\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n\n Returns\n -------\n self : object\n \"\"\"\n assert len(X) == len(y) and len(X) == len(treatment), 'Data length must be equal for X, treatment, and y.'\n\n self.treatment_group = list(set(treatment))\n self.feature_imp_dict = defaultdict(float)\n\n self.fitted_uplift_tree = self.growDecisionTreeFrom(\n X, treatment, y, evaluationFunction=self.evaluationFunction,\n max_depth=self.max_depth, min_samples_leaf=self.min_samples_leaf,\n depth=1, min_samples_treatment=self.min_samples_treatment,\n n_reg=self.n_reg, parentNodeSummary=None\n )\n\n self.feature_importances_ = np.zeros(X.shape[1])\n for col, imp in self.feature_imp_dict.items():\n self.feature_importances_[col] = imp\n self.feature_importances_ /= self.feature_importances_.sum() # normalize to add to 1\n\n # Prune Trees\n def prune(self, X, treatment, y, minGain=0.0001, rule='maxAbsDiff'):\n \"\"\" Prune the uplift model.\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n minGain : float, optional (default = 0.0001)\n The minimum gain required to make a tree node split. The children\n tree branches are trimmed if the actual split gain is less than\n the minimum gain.\n rule : string, optional (default = 'maxAbsDiff')\n The prune rules. Supported values are 'maxAbsDiff' for optimizing\n the maximum absolute difference, and 'bestUplift' for optimizing\n the node-size weighted treatment effect.\n Returns\n -------\n self : object\n \"\"\"\n assert len(X) == len(y) and len(X) == len(treatment), 'Data length must be equal for X, treatment, and y.'\n\n self.pruneTree(X, treatment, y,\n tree=self.fitted_uplift_tree,\n rule=rule,\n minGain=minGain,\n evaluationFunction=self.evaluationFunction,\n notify=False,\n n_reg=self.n_reg,\n parentNodeSummary=None)\n return self\n\n def pruneTree(self, X, treatment, y, tree, rule='maxAbsDiff', minGain=0.,\n evaluationFunction=None, notify=False, n_reg=0,\n parentNodeSummary=None):\n \"\"\"Prune one single tree node in the uplift model.\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n rule : string, optional (default = 'maxAbsDiff')\n The prune rules. Supported values are 'maxAbsDiff' for optimizing the maximum absolute difference, and\n 'bestUplift' for optimizing the node-size weighted treatment effect.\n minGain : float, optional (default = 0.)\n The minimum gain required to make a tree node split. The children tree branches are trimmed if the actual\n split gain is less than the minimum gain.\n evaluationFunction : string, optional (default = None)\n Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS'.\n notify: bool, optional (default = False)\n n_reg: int, optional (default=0)\n The regularization parameter defined in Rzepakowski et al. 2012, the weight (in terms of sample size) of the\n parent node influence on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods.\n parentNodeSummary : dictionary, optional (default = None)\n Node summary statistics of the parent tree node.\n Returns\n -------\n self : object\n \"\"\"\n # Current Node Summary for Validation Data Set\n currentNodeSummary = self.tree_node_summary(\n treatment, y, min_samples_treatment=self.min_samples_treatment,\n n_reg=n_reg, parentNodeSummary=parentNodeSummary\n )\n tree.nodeSummary = currentNodeSummary\n # Divide sets for child nodes\n X_l, X_r, w_l, w_r, y_l, y_r = self.divideSet(X, treatment, y, tree.col, tree.value)\n\n # recursive call for each branch\n if tree.trueBranch.results is None:\n self.pruneTree(X_l, w_l, y_l, tree.trueBranch, rule, minGain,\n evaluationFunction, notify, n_reg,\n parentNodeSummary=currentNodeSummary)\n if tree.falseBranch.results is None:\n self.pruneTree(X_r, w_r, y_r, tree.falseBranch, rule, minGain,\n evaluationFunction, notify, n_reg,\n parentNodeSummary=currentNodeSummary)\n\n # merge leaves (potentially)\n if (tree.trueBranch.results is not None and\n tree.falseBranch.results is not None):\n if rule == 'maxAbsDiff':\n # Current D\n if (tree.maxDiffTreatment in currentNodeSummary and\n self.control_name in currentNodeSummary):\n currentScoreD = tree.maxDiffSign * (currentNodeSummary[tree.maxDiffTreatment][0]\n - currentNodeSummary[self.control_name][0])\n else:\n currentScoreD = 0\n\n # trueBranch D\n trueNodeSummary = self.tree_node_summary(\n w_l, y_l, min_samples_treatment=self.min_samples_treatment,\n n_reg=n_reg, parentNodeSummary=currentNodeSummary\n )\n if (tree.trueBranch.maxDiffTreatment in trueNodeSummary and\n self.control_name in trueNodeSummary):\n trueScoreD = tree.trueBranch.maxDiffSign * (trueNodeSummary[tree.trueBranch.maxDiffTreatment][0]\n - trueNodeSummary[self.control_name][0])\n trueScoreD = (\n trueScoreD\n * (trueNodeSummary[tree.trueBranch.maxDiffTreatment][1]\n + trueNodeSummary[self.control_name][1])\n / (currentNodeSummary[tree.trueBranch.maxDiffTreatment][1]\n + currentNodeSummary[self.control_name][1])\n )\n else:\n trueScoreD = 0\n\n # falseBranch D\n falseNodeSummary = self.tree_node_summary(\n w_r, y_r, min_samples_treatment=self.min_samples_treatment,\n n_reg=n_reg, parentNodeSummary=currentNodeSummary\n )\n if (tree.falseBranch.maxDiffTreatment in falseNodeSummary and\n self.control_name in falseNodeSummary):\n falseScoreD = (\n tree.falseBranch.maxDiffSign *\n (falseNodeSummary[tree.falseBranch.maxDiffTreatment][0]\n - falseNodeSummary[self.control_name][0])\n )\n\n falseScoreD = (\n falseScoreD *\n (falseNodeSummary[tree.falseBranch.maxDiffTreatment][1]\n + falseNodeSummary[self.control_name][1])\n / (currentNodeSummary[tree.falseBranch.maxDiffTreatment][1]\n + currentNodeSummary[self.control_name][1])\n )\n else:\n falseScoreD = 0\n\n if ((trueScoreD + falseScoreD) - currentScoreD <= minGain or\n (trueScoreD + falseScoreD < 0.)):\n tree.trueBranch, tree.falseBranch = None, None\n tree.results = tree.backupResults\n\n elif rule == 'bestUplift':\n # Current D\n if (tree.bestTreatment in currentNodeSummary and\n self.control_name in currentNodeSummary):\n currentScoreD = (\n currentNodeSummary[tree.bestTreatment][0]\n - currentNodeSummary[self.control_name][0]\n )\n else:\n currentScoreD = 0\n\n # trueBranch D\n trueNodeSummary = self.tree_node_summary(\n w_l, y_l, min_samples_treatment=self.min_samples_treatment,\n n_reg=n_reg, parentNodeSummary=currentNodeSummary\n )\n if (tree.trueBranch.bestTreatment in trueNodeSummary and\n self.control_name in trueNodeSummary):\n trueScoreD = (\n trueNodeSummary[tree.trueBranch.bestTreatment][0]\n - trueNodeSummary[self.control_name][0]\n )\n else:\n trueScoreD = 0\n\n # falseBranch D\n falseNodeSummary = self.tree_node_summary(\n w_r, y_r, min_samples_treatment=self.min_samples_treatment,\n n_reg=n_reg, parentNodeSummary=currentNodeSummary\n )\n if (tree.falseBranch.bestTreatment in falseNodeSummary and\n self.control_name in falseNodeSummary):\n falseScoreD = (\n falseNodeSummary[tree.falseBranch.bestTreatment][0]\n - falseNodeSummary[self.control_name][0]\n )\n else:\n falseScoreD = 0\n gain = ((1. * len(y_l) / len(y) * trueScoreD\n + 1. * len(y_r) / len(y) * falseScoreD)\n - currentScoreD)\n if gain <= minGain or (trueScoreD + falseScoreD < 0.):\n tree.trueBranch, tree.falseBranch = None, None\n tree.results = tree.backupResults\n return self\n\n def fill(self, X, treatment, y):\n \"\"\" Fill the data into an existing tree.\n This is a higher-level function to transform the original data inputs\n into lower level data inputs (list of list and tree).\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n\n Returns\n -------\n self : object\n \"\"\"\n assert len(X) == len(y) and len(X) == len(treatment), 'Data length must be equal for X, treatment, and y.'\n\n self.fillTree(X, treatment, y, tree=self.fitted_uplift_tree)\n return self\n\n def fillTree(self, X, treatment, y, tree):\n \"\"\" Fill the data into an existing tree.\n This is a lower-level function to execute on the tree filling task.\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n tree : object\n object of DecisionTree class\n\n Returns\n -------\n self : object\n \"\"\"\n # Current Node Summary for Validation Data Set\n currentNodeSummary = self.tree_node_summary(treatment, y,\n min_samples_treatment=0,\n n_reg=0,\n parentNodeSummary=None)\n tree.nodeSummary = currentNodeSummary\n # Divide sets for child nodes\n X_l, X_r, w_l, w_r, y_l, y_r = self.divideSet(X, treatment, y, tree.col, tree.value)\n\n # recursive call for each branch\n if tree.trueBranch is not None:\n self.fillTree(X_l, w_l, y_l, tree.trueBranch)\n if tree.falseBranch is not None:\n self.fillTree(X_r, w_r, y_r, tree.falseBranch)\n\n # Update Information\n\n # matchScore\n matchScore = (currentNodeSummary[tree.bestTreatment][0] - currentNodeSummary[self.control_name][0])\n tree.matchScore = round(matchScore, 4)\n tree.summary['matchScore'] = round(matchScore, 4)\n\n # Samples, Group_size\n tree.summary['samples'] = len(y)\n tree.summary['group_size'] = ''\n for treatment_group in currentNodeSummary:\n tree.summary['group_size'] += ' ' + treatment_group + ': ' + str(currentNodeSummary[treatment_group][1])\n # classProb\n if tree.results is not None:\n tree.results = self.uplift_classification_results(treatment, y)\n return self\n\n def predict(self, X, full_output=False):\n '''\n Returns the recommended treatment group and predicted optimal\n probability conditional on using the recommended treatment group.\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n\n full_output : bool, optional (default=False)\n Whether the UpliftTree algorithm returns upliftScores, pred_nodes\n alongside the recommended treatment group and p_hat in the treatment group.\n\n Returns\n -------\n df_res : DataFrame, shape = [num_samples, (num_treatments + 1)]\n A DataFrame containing the predicted delta in each treatment group,\n the best treatment group and the maximum delta.\n\n '''\n\n p_hat_optimal = []\n treatment_optimal = []\n pred_nodes = {}\n upliftScores = []\n for xi in range(len(X)):\n pred_leaf, upliftScore = self.classify(X[xi], self.fitted_uplift_tree, dataMissing=False)\n # Predict under uplift optimal treatment\n opt_treat = max(pred_leaf, key=pred_leaf.get)\n p_hat_optimal.append(pred_leaf[opt_treat])\n treatment_optimal.append(opt_treat)\n if full_output:\n if xi == 0:\n for key_i in pred_leaf:\n pred_nodes[key_i] = [pred_leaf[key_i]]\n else:\n for key_i in pred_leaf:\n pred_nodes[key_i].append(pred_leaf[key_i])\n upliftScores.append(upliftScore)\n if full_output:\n return treatment_optimal, p_hat_optimal, upliftScores, pred_nodes\n else:\n return treatment_optimal, p_hat_optimal\n\n @staticmethod\n def divideSet(X, treatment, y, column, value):\n '''\n Tree node split.\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n column : int\n The column used to split the data.\n value : float or int\n The value in the column for splitting the data.\n\n Returns\n -------\n (X_l, X_r, treatment_l, treatment_r, y_l, y_r) : list of ndarray\n The covariates, treatments and outcomes of left node and the right node.\n '''\n # for int and float values\n if isinstance(value, int) or isinstance(value, float):\n filt = X[:, column] >= value\n else: # for strings\n filt = X[:, column] == value\n\n return X[filt], X[~filt], treatment[filt], treatment[~filt], y[filt], y[~filt]\n\n def group_uniqueCounts(self, treatment, y):\n '''\n Count sample size by experiment group.\n\n Args\n ----\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n\n Returns\n -------\n results : dictionary\n The control and treatment sample size.\n '''\n results = {}\n for t in self.treatment_group:\n filt = treatment == t\n n_t = y[filt].sum()\n results[t] = (filt.sum() - n_t, n_t)\n\n return results\n\n @staticmethod\n def kl_divergence(pk, qk):\n '''\n Calculate KL Divergence for binary classification.\n\n sum(np.array(pk) * np.log(np.array(pk) / np.array(qk)))\n\n Args\n ----\n pk : float\n The probability of 1 in one distribution.\n qk : float\n The probability of 1 in the other distribution.\n\n Returns\n -------\n S : float\n The KL divergence.\n '''\n\n eps = 1e-6\n qk = np.clip(qk, eps, 1 - eps)\n\n if pk == 0:\n S = -np.log(1 - qk)\n elif pk == 1:\n S = -np.log(qk)\n else:\n S = pk * np.log(pk / qk) + (1 - pk) * np.log((1 - pk) / (1 - qk))\n\n return S\n\n def evaluate_KL(self, nodeSummary, control_name):\n '''\n Calculate KL Divergence as split evaluation criterion for a given node.\n\n Args\n ----\n nodeSummary : dictionary\n The tree node summary statistics, produced by tree_node_summary()\n method.\n\n control_name : string\n The control group name.\n\n Returns\n -------\n d_res : KL Divergence\n '''\n if control_name not in nodeSummary:\n return 0\n pc = nodeSummary[control_name][0]\n d_res = 0\n for treatment_group in nodeSummary:\n if treatment_group != control_name:\n d_res += self.kl_divergence(nodeSummary[treatment_group][0], pc)\n return d_res\n\n @staticmethod\n def evaluate_ED(nodeSummary, control_name):\n '''\n Calculate Euclidean Distance as split evaluation criterion for a given node.\n\n Args\n ----\n nodeSummary : dictionary\n The tree node summary statistics, produced by tree_node_summary()\n method.\n\n control_name : string\n The control group name.\n\n Returns\n -------\n d_res : Euclidean Distance\n '''\n if control_name not in nodeSummary:\n return 0\n pc = nodeSummary[control_name][0]\n d_res = 0\n for treatment_group in nodeSummary:\n if treatment_group != control_name:\n d_res += 2*(nodeSummary[treatment_group][0] - pc)**2\n return d_res\n\n @staticmethod\n def evaluate_Chi(nodeSummary, control_name):\n '''\n Calculate Chi-Square statistic as split evaluation criterion for a given node.\n\n Args\n ----\n nodeSummary : dictionary\n The tree node summary statistics, produced by tree_node_summary() method.\n\n control_name : string\n The control group name.\n\n Returns\n -------\n d_res : Chi-Square\n '''\n if control_name not in nodeSummary:\n return 0\n pc = nodeSummary[control_name][0]\n d_res = 0\n for treatment_group in nodeSummary:\n if treatment_group != control_name:\n d_res += ((nodeSummary[treatment_group][0] - pc) ** 2 / max(0.1 ** 6, pc)\n + (nodeSummary[treatment_group][0] - pc) ** 2 / max(0.1 ** 6, 1 - pc))\n return d_res\n\n @staticmethod\n def evaluate_CTS(currentNodeSummary):\n '''\n Calculate CTS (conditional treatment selection) as split evaluation criterion for a given node.\n\n Args\n ----\n nodeSummary : dictionary\n The tree node summary statistics, produced by tree_node_summary() method.\n\n control_name : string\n The control group name.\n\n Returns\n -------\n d_res : Chi-Square\n '''\n mu = 0.0\n # iterate treatment group\n for r in currentNodeSummary:\n mu = max(mu, currentNodeSummary[r][0])\n return -mu\n\n @staticmethod\n def entropyH(p, q=None):\n '''\n Entropy\n\n Entropy calculation for normalization.\n\n Args\n ----\n p : float\n The probability used in the entropy calculation.\n\n q : float, optional, (default = None)\n The second probability used in the entropy calculation.\n\n Returns\n -------\n entropy : float\n '''\n if q is None and p > 0:\n return -p * np.log(p)\n elif q > 0:\n return -p * np.log(q)\n else:\n return 0\n\n def normI(self, currentNodeSummary, leftNodeSummary, rightNodeSummary, control_name, alpha=0.9):\n '''\n Normalization factor.\n\n Args\n ----\n currentNodeSummary : dictionary\n The summary statistics of the current tree node.\n\n leftNodeSummary : dictionary\n The summary statistics of the left tree node.\n\n rightNodeSummary : dictionary\n The summary statistics of the right tree node.\n\n control_name : string\n The control group name.\n\n alpha : float\n The weight used to balance different normalization parts.\n\n Returns\n -------\n norm_res : float\n Normalization factor.\n '''\n norm_res = 0\n # n_t, n_c: sample size for all treatment, and control\n # pt_a, pc_a: % of treatment is in left node, % of control is in left node\n n_c = currentNodeSummary[control_name][1]\n n_c_left = leftNodeSummary[control_name][1]\n n_t = []\n n_t_left = []\n for treatment_group in currentNodeSummary:\n if treatment_group != control_name:\n n_t.append(currentNodeSummary[treatment_group][1])\n if treatment_group in leftNodeSummary:\n n_t_left.append(leftNodeSummary[treatment_group][1])\n else:\n n_t_left.append(0)\n pt_a = 1. * np.sum(n_t_left) / (np.sum(n_t) + 0.1)\n pc_a = 1. * n_c_left / (n_c + 0.1)\n # Normalization Part 1\n norm_res += (\n alpha * self.entropyH(1. * np.sum(n_t) / (np.sum(n_t) + n_c), 1. * n_c / (np.sum(n_t) + n_c))\n * self.kl_divergence(pt_a, pc_a)\n )\n # Normalization Part 2 & 3\n for i in range(len(n_t)):\n pt_a_i = 1. * n_t_left[i] / (n_t[i] + 0.1)\n norm_res += (\n (1 - alpha) * self.entropyH(1. * n_t[i] / (n_t[i] + n_c), 1. * n_c / (n_t[i] + n_c))\n * self.kl_divergence(1. * pt_a_i, pc_a)\n )\n norm_res += (1. * n_t[i] / (np.sum(n_t) + n_c) * self.entropyH(pt_a_i))\n # Normalization Part 4\n norm_res += 1. * n_c/(np.sum(n_t) + n_c) * self.entropyH(pc_a)\n\n # Normalization Part 5\n norm_res += 0.5\n return norm_res\n\n def tree_node_summary(self, treatment, y, min_samples_treatment=10, n_reg=100, parentNodeSummary=None):\n '''\n Tree node summary statistics.\n\n Args\n ----\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n min_samples_treatment: int, optional (default=10)\n The minimum number of samples required of the experiment group t be split at a leaf node.\n n_reg : int, optional (default=10)\n The regularization parameter defined in Rzepakowski et al. 2012,\n the weight (in terms of sample size) of the parent node influence\n on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods.\n parentNodeSummary : dictionary\n Node summary statistics of the parent tree node.\n\n Returns\n -------\n nodeSummary : dictionary\n The node summary of the current tree node.\n '''\n # returns {treatment_group: p(1)}\n results = self.group_uniqueCounts(treatment, y)\n # node Summary: {treatment_group: [p(1), size]}\n nodeSummary = {}\n # iterate treatment group\n for r in results:\n n1 = results[r][1]\n ntot = results[r][0] + n1\n if parentNodeSummary is None:\n y_mean = n1 / ntot\n elif ntot > min_samples_treatment:\n y_mean = (n1 + parentNodeSummary[r][0] * n_reg) / (ntot + n_reg)\n else:\n y_mean = parentNodeSummary[r][0]\n\n nodeSummary[r] = [y_mean, ntot]\n\n return nodeSummary\n\n def uplift_classification_results(self, treatment, y):\n '''\n Classification probability for each treatment in the tree node.\n\n Args\n ----\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n\n Returns\n -------\n res : dictionary\n The probability of 1 in each treatment in the tree node.\n '''\n results = self.group_uniqueCounts(treatment, y)\n res = {}\n for r in results:\n p = float(results[r][1]) / (results[r][0] + results[r][1])\n res[r] = round(p, 6)\n return res\n\n def growDecisionTreeFrom(self, X, treatment, y, evaluationFunction, max_depth=10,\n min_samples_leaf=100, depth=1,\n min_samples_treatment=10, n_reg=100,\n parentNodeSummary=None):\n '''\n Train the uplift decision tree.\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n evaluationFunction : string\n Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS'.\n max_depth: int, optional (default=10)\n The maximum depth of the tree.\n min_samples_leaf: int, optional (default=100)\n The minimum number of samples required to be split at a leaf node.\n depth : int, optional (default = 1)\n The current depth.\n min_samples_treatment: int, optional (default=10)\n The minimum number of samples required of the experiment group to be split at a leaf node.\n n_reg: int, optional (default=10)\n The regularization parameter defined in Rzepakowski et al. 2012,\n the weight (in terms of sample size) of the parent node influence\n on the child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods.\n parentNodeSummary : dictionary, optional (default = None)\n Node summary statistics of the parent tree node.\n\n Returns\n -------\n object of DecisionTree class\n '''\n\n if len(X) == 0:\n return DecisionTree()\n\n # Current Node Info and Summary\n currentNodeSummary = self.tree_node_summary(treatment, y,\n min_samples_treatment=min_samples_treatment,\n n_reg=n_reg,\n parentNodeSummary=parentNodeSummary)\n if evaluationFunction == self.evaluate_CTS:\n currentScore = evaluationFunction(currentNodeSummary)\n else:\n currentScore = evaluationFunction(currentNodeSummary, control_name=self.control_name)\n\n # Prune Stats\n maxAbsDiff = 0\n maxDiff = -1.\n bestTreatment = self.control_name\n suboptTreatment = self.control_name\n maxDiffTreatment = self.control_name\n maxDiffSign = 0\n for treatment_group in currentNodeSummary:\n if treatment_group != self.control_name:\n diff = (currentNodeSummary[treatment_group][0]\n - currentNodeSummary[self.control_name][0])\n if abs(diff) >= maxAbsDiff:\n maxDiffTreatment = treatment_group\n maxDiffSign = np.sign(diff)\n maxAbsDiff = abs(diff)\n if diff >= maxDiff:\n maxDiff = diff\n suboptTreatment = treatment_group\n if diff > 0:\n bestTreatment = treatment_group\n if maxDiff > 0:\n pt = currentNodeSummary[bestTreatment][0]\n nt = currentNodeSummary[bestTreatment][1]\n pc = currentNodeSummary[self.control_name][0]\n nc = currentNodeSummary[self.control_name][1]\n p_value = (1. - stats.norm.cdf((pt - pc) / np.sqrt(pt * (1 - pt) / nt + pc * (1 - pc) / nc))) * 2\n else:\n pt = currentNodeSummary[suboptTreatment][0]\n nt = currentNodeSummary[suboptTreatment][1]\n pc = currentNodeSummary[self.control_name][0]\n nc = currentNodeSummary[self.control_name][1]\n p_value = (1. - stats.norm.cdf((pc - pt) / np.sqrt(pt * (1 - pt) / nt + pc * (1 - pc) / nc))) * 2\n upliftScore = [maxDiff, p_value]\n\n bestGain = 0.0\n bestAttribute = None\n\n # last column is the result/target column, 2nd to the last is the treatment group\n columnCount = X.shape[1]\n if (self.max_features and self.max_features > 0 and self.max_features <= columnCount):\n max_features = self.max_features\n else:\n max_features = columnCount\n\n for col in list(np.random.choice(a=range(columnCount), size=max_features, replace=False)):\n columnValues = X[:, col]\n # unique values\n lsUnique = np.unique(columnValues)\n\n if (isinstance(lsUnique[0], int) or\n isinstance(lsUnique[0], float)):\n if len(lsUnique) > 10:\n lspercentile = np.percentile(columnValues, [3, 5, 10, 20, 30, 50, 70, 80, 90, 95, 97])\n else:\n lspercentile = np.percentile(lsUnique, [10, 50, 90])\n lsUnique = np.unique(lspercentile)\n\n for value in lsUnique:\n X_l, X_r, w_l, w_r, y_l, y_r = self.divideSet(X, treatment, y, col, value)\n # check the split validity on min_samples_leaf 372\n if (len(X_l) < min_samples_leaf or len(X_r) < min_samples_leaf):\n continue\n # summarize notes\n # Gain -- Entropy or Gini\n p = float(len(X_l)) / len(X)\n leftNodeSummary = self.tree_node_summary(w_l, y_l,\n min_samples_treatment=min_samples_treatment,\n n_reg=n_reg,\n parentNodeSummary=currentNodeSummary)\n\n rightNodeSummary = self.tree_node_summary(w_r, y_r,\n min_samples_treatment=min_samples_treatment,\n n_reg=n_reg,\n parentNodeSummary=currentNodeSummary)\n\n # check the split validity on min_samples_treatment\n if set(leftNodeSummary.keys()) != set(rightNodeSummary.keys()):\n continue\n node_mst = 10**8\n for ti in leftNodeSummary:\n node_mst = np.min([node_mst, leftNodeSummary[ti][1]])\n node_mst = np.min([node_mst, rightNodeSummary[ti][1]])\n if node_mst < min_samples_treatment:\n continue\n # evaluate the split\n\n if evaluationFunction == self.evaluate_CTS:\n leftScore1 = evaluationFunction(leftNodeSummary)\n rightScore2 = evaluationFunction(rightNodeSummary)\n gain = (currentScore - p * leftScore1 - (1 - p) * rightScore2)\n gain_for_imp = (len(X) * currentScore - len(X_l) * leftScore1 - len(X_r) * rightScore2)\n else:\n if (self.control_name in leftNodeSummary and\n self.control_name in rightNodeSummary):\n leftScore1 = evaluationFunction(leftNodeSummary, control_name=self.control_name)\n rightScore2 = evaluationFunction(rightNodeSummary, control_name=self.control_name)\n gain = (p * leftScore1 + (1 - p) * rightScore2 - currentScore)\n gain_for_imp = (len(X_l) * leftScore1 + len(X_r) * rightScore2 - len(X) * currentScore)\n if self.normalization:\n norm_factor = self.normI(currentNodeSummary,\n leftNodeSummary,\n rightNodeSummary,\n self.control_name,\n alpha=0.9)\n else:\n norm_factor = 1\n gain = gain / norm_factor\n else:\n gain = 0\n if (gain > bestGain and len(X_l) > min_samples_leaf and len(X_r) > min_samples_leaf):\n bestGain = gain\n bestAttribute = (col, value)\n best_set_left = [X_l, w_l, y_l]\n best_set_right = [X_r, w_r, y_r]\n self.feature_imp_dict[bestAttribute[0]] += gain_for_imp\n\n dcY = {'impurity': '%.3f' % currentScore, 'samples': '%d' % len(X)}\n # Add treatment size\n dcY['group_size'] = ''\n for treatment_group in currentNodeSummary:\n dcY['group_size'] += ' ' + treatment_group + ': ' + str(currentNodeSummary[treatment_group][1])\n dcY['upliftScore'] = [round(upliftScore[0], 4), round(upliftScore[1], 4)]\n dcY['matchScore'] = round(upliftScore[0], 4)\n\n if bestGain > 0 and depth < max_depth:\n trueBranch = self.growDecisionTreeFrom(\n *best_set_left, evaluationFunction, max_depth, min_samples_leaf,\n depth + 1, min_samples_treatment=min_samples_treatment,\n n_reg=n_reg, parentNodeSummary=currentNodeSummary\n )\n falseBranch = self.growDecisionTreeFrom(\n *best_set_right, evaluationFunction, max_depth, min_samples_leaf,\n depth + 1, min_samples_treatment=min_samples_treatment,\n n_reg=n_reg, parentNodeSummary=currentNodeSummary\n )\n\n return DecisionTree(\n col=bestAttribute[0], value=bestAttribute[1],\n trueBranch=trueBranch, falseBranch=falseBranch, summary=dcY,\n maxDiffTreatment=maxDiffTreatment, maxDiffSign=maxDiffSign,\n nodeSummary=currentNodeSummary,\n backupResults=self.uplift_classification_results(treatment, y),\n bestTreatment=bestTreatment, upliftScore=upliftScore\n )\n else:\n if evaluationFunction == self.evaluate_CTS:\n return DecisionTree(\n results=self.uplift_classification_results(treatment, y),\n summary=dcY, nodeSummary=currentNodeSummary,\n bestTreatment=bestTreatment, upliftScore=upliftScore\n )\n else:\n return DecisionTree(\n results=self.uplift_classification_results(treatment, y),\n summary=dcY, maxDiffTreatment=maxDiffTreatment,\n maxDiffSign=maxDiffSign, nodeSummary=currentNodeSummary,\n bestTreatment=bestTreatment, upliftScore=upliftScore\n )\n\n @staticmethod\n def classify(observations, tree, dataMissing=False):\n '''\n Classifies (prediction) the observations according to the tree.\n\n Args\n ----\n observations : list of list\n The internal data format for the training data (combining X, Y, treatment).\n\n dataMissing: boolean, optional (default = False)\n An indicator for if data are missing or not.\n\n Returns\n -------\n tree.results, tree.upliftScore :\n The results in the leaf node.\n '''\n\n def classifyWithoutMissingData(observations, tree):\n '''\n Classifies (prediction) the observations according to the tree, assuming without missing data.\n\n Args\n ----\n observations : list of list\n The internal data format for the training data (combining X, Y, treatment).\n\n Returns\n -------\n tree.results, tree.upliftScore :\n The results in the leaf node.\n '''\n if tree.results is not None: # leaf\n return tree.results, tree.upliftScore\n else:\n v = observations[tree.col]\n branch = None\n if isinstance(v, int) or isinstance(v, float):\n if v >= tree.value:\n branch = tree.trueBranch\n else:\n branch = tree.falseBranch\n else:\n if v == tree.value:\n branch = tree.trueBranch\n else:\n branch = tree.falseBranch\n return classifyWithoutMissingData(observations, branch)\n\n def classifyWithMissingData(observations, tree):\n '''\n Classifies (prediction) the observations according to the tree, assuming with missing data.\n\n Args\n ----\n observations : list of list\n The internal data format for the training data (combining X, Y, treatment).\n\n Returns\n -------\n tree.results, tree.upliftScore :\n The results in the leaf node.\n '''\n if tree.results is not None: # leaf\n return tree.results\n else:\n v = observations[tree.col]\n if v is None:\n tr = classifyWithMissingData(observations, tree.trueBranch)\n fr = classifyWithMissingData(observations, tree.falseBranch)\n tcount = sum(tr.values())\n fcount = sum(fr.values())\n tw = float(tcount) / (tcount + fcount)\n fw = float(fcount) / (tcount + fcount)\n\n # Problem description: http://blog.ludovf.net/python-collections-defaultdict/\n result = defaultdict(int)\n for k, v in tr.items():\n result[k] += v * tw\n for k, v in fr.items():\n result[k] += v * fw\n return dict(result)\n else:\n branch = None\n if isinstance(v, int) or isinstance(v, float):\n if v >= tree.value:\n branch = tree.trueBranch\n else:\n branch = tree.falseBranch\n else:\n if v == tree.value:\n branch = tree.trueBranch\n else:\n branch = tree.falseBranch\n return classifyWithMissingData(observations, branch)\n\n # function body\n if dataMissing:\n return classifyWithMissingData(observations, tree)\n else:\n return classifyWithoutMissingData(observations, tree)\n\n\n# Uplift Random Forests\nclass UpliftRandomForestClassifier:\n \"\"\" Uplift Random Forest for Classification Task.\n\n Parameters\n ----------\n n_estimators : integer, optional (default=10)\n The number of trees in the uplift random forest.\n\n evaluationFunction : string\n Choose from one of the models: 'KL', 'ED', 'Chi', 'CTS'.\n\n max_features: int, optional (default=10)\n The number of features to consider when looking for the best split.\n\n random_state: int, optional (default=2019)\n The seed used by the random number generator.\n\n max_depth: int, optional (default=5)\n The maximum depth of the tree.\n\n min_samples_leaf: int, optional (default=100)\n The minimum number of samples required to be split at a leaf node.\n\n min_samples_treatment: int, optional (default=10)\n The minimum number of samples required of the experiment group to be split at a leaf node.\n\n n_reg: int, optional (default=10)\n The regularization parameter defined in Rzepakowski et al. 2012, the\n weight (in terms of sample size) of the parent node influence on the\n child node, only effective for 'KL', 'ED', 'Chi', 'CTS' methods.\n\n control_name: string\n The name of the control group (other experiment groups will be regarded as treatment groups)\n\n normalization: boolean, optional (default=True)\n The normalization factor defined in Rzepakowski et al. 2012,\n correcting for tests with large number of splits and imbalanced\n treatment and control splits\n \n n_jobs: int, optional (default=-1)\n The parallelization parameter to define how many parallel jobs need to be created. \n This is passed on to joblib library for parallelizing uplift-tree creation.\n\n Outputs\n ----------\n df_res: pandas dataframe\n A user-level results dataframe containing the estimated individual treatment effect.\n \"\"\"\n def __init__(self,\n n_estimators=10,\n max_features=10,\n random_state=2019,\n max_depth=5,\n min_samples_leaf=100,\n min_samples_treatment=10,\n n_reg=10,\n evaluationFunction=None,\n control_name=None,\n normalization=True,\n n_jobs=-1):\n \"\"\"\n Initialize the UpliftRandomForestClassifier class.\n \"\"\"\n self.classes_ = {}\n self.n_estimators = n_estimators\n self.max_features = max_features\n self.random_state = random_state\n self.max_depth = max_depth\n self.min_samples_leaf = min_samples_leaf\n self.min_samples_treatment = min_samples_treatment\n self.n_reg = n_reg\n self.evaluationFunction = evaluationFunction\n self.control_name = control_name\n self.n_jobs = n_jobs\n\n # Create forest\n self.uplift_forest = []\n for _ in range(n_estimators):\n uplift_tree = UpliftTreeClassifier(\n max_features=self.max_features, max_depth=self.max_depth,\n min_samples_leaf=self.min_samples_leaf,\n min_samples_treatment=self.min_samples_treatment,\n n_reg=self.n_reg,\n evaluationFunction=self.evaluationFunction,\n control_name=self.control_name,\n normalization=normalization)\n\n self.uplift_forest.append(uplift_tree)\n\n if self.n_jobs == -1:\n self.n_jobs = mp.cpu_count()\n\n def fit(self, X, treatment, y):\n \"\"\"\n Fit the UpliftRandomForestClassifier.\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n\n treatment : array-like, shape = [num_samples]\n An array containing the treatment group for each unit.\n\n y : array-like, shape = [num_samples]\n An array containing the outcome of interest for each unit.\n \"\"\"\n np.random.seed(self.random_state)\n\n # Get treatment group keys\n treatment_group_keys = list(set(treatment))\n treatment_group_keys.remove(self.control_name)\n treatment_group_keys.sort()\n self.classes_ = {}\n for i, treatment_group_key in enumerate(treatment_group_keys):\n self.classes_[treatment_group_key] = i\n\n self.uplift_forest = (\n Parallel(n_jobs=self.n_jobs)\n (delayed(self.bootstrap)(X, treatment, y, tree) for tree in self.uplift_forest)\n )\n\n all_importances = [tree.feature_importances_ for tree in self.uplift_forest]\n self.feature_importances_ = np.mean(all_importances, axis=0)\n self.feature_importances_ /= self.feature_importances_.sum() # normalize to add to 1\n\n @staticmethod\n def bootstrap(X, treatment, y, tree):\n bt_index = np.random.choice(len(X), len(X))\n x_train_bt = X[bt_index]\n y_train_bt = y[bt_index]\n treatment_train_bt = treatment[bt_index]\n tree.fit(X=x_train_bt, treatment=treatment_train_bt, y=y_train_bt)\n return tree\n\n @ignore_warnings(category=FutureWarning)\n def predict(self, X, full_output=False):\n '''\n Returns the recommended treatment group and predicted optimal\n probability conditional on using the recommended treatment group.\n\n Args\n ----\n X : ndarray, shape = [num_samples, num_features]\n An ndarray of the covariates used to train the uplift model.\n\n full_output : bool, optional (default=False)\n Whether the UpliftTree algorithm returns upliftScores, pred_nodes\n alongside the recommended treatment group and p_hat in the treatment group.\n\n Returns\n -------\n y_pred_list : ndarray, shape = (num_samples, num_treatments])\n An ndarray containing the predicted delta in each treatment group,\n the best treatment group and the maximum delta.\n \n df_res : DataFrame, shape = [num_samples, (num_treatments + 1)]\n If full_output, a DataFrame containing the predicted delta in each treatment group,\n the best treatment group and the maximum delta.\n\n '''\n df_res = pd.DataFrame()\n y_pred_ensemble = dict()\n y_pred_list = np.zeros((X.shape[0], len(self.classes_)))\n\n # Make prediction by each tree\n for tree_i in range(len(self.uplift_forest)):\n\n _, _, _, y_pred_full = self.uplift_forest[tree_i].predict(X=X, full_output=True)\n\n if tree_i == 0:\n for treatment_group in y_pred_full:\n y_pred_ensemble[treatment_group] = (\n np.array(y_pred_full[treatment_group]) / len(self.uplift_forest)\n )\n else:\n for treatment_group in y_pred_full:\n y_pred_ensemble[treatment_group] = (\n np.array(y_pred_ensemble[treatment_group])\n + np.array(y_pred_full[treatment_group]) / len(self.uplift_forest)\n )\n\n # Summarize results into dataframe\n for treatment_group in y_pred_ensemble:\n df_res[treatment_group] = y_pred_ensemble[treatment_group]\n\n df_res['recommended_treatment'] = df_res.apply(np.argmax, axis=1)\n\n # Calculate delta\n delta_cols = []\n for treatment_group in y_pred_ensemble:\n if treatment_group != self.control_name:\n delta_cols.append('delta_%s' % (treatment_group))\n df_res['delta_%s' % (treatment_group)] = df_res[treatment_group] - df_res[self.control_name]\n # Add deltas to results list\n y_pred_list[:, self.classes_[treatment_group]] = df_res['delta_%s' % (treatment_group)].values\n df_res['max_delta'] = df_res[delta_cols].max(axis=1)\n\n if full_output:\n return df_res\n else:\n return y_pred_list\n" ]
[ [ "numpy.sqrt", "numpy.sum", "numpy.sign", "numpy.zeros", "pandas.DataFrame", "numpy.random.seed", "numpy.percentile", "numpy.clip", "numpy.log", "sklearn.utils.testing.ignore_warnings", "numpy.min", "numpy.array", "numpy.unique", "numpy.mean" ] ]
Open-Speech-EkStep/speech_music_classification
[ "0e394ec0f0d0ac7a177171f7ac7c254b1db38c2a" ]
[ "check.py" ]
[ "import torch\nfrom torch.utils.data import DataLoader\n\nfrom configs.train_config import SpectConfig\nfrom loader.data_loader import SpectrogramDataset, collate_fn\nfrom models.model import Conformer, get_conv_output_sizes\n\nif __name__ == \"__main__\":\n spect_cfg = SpectConfig()\n songs_dset = SpectrogramDataset('/home/soma/song_speech/speech', 1, spect_cfg)\n print(len(songs_dset))\n feat, label = songs_dset[1000]\n print(feat.shape, label) # [257, T]\n\n model = Conformer()\n batch = feat.unsqueeze(0)\n print(batch.shape)\n\n # out = model(batch)\n # print(\"out shape: \", out.shape)\n\n lengths = get_conv_output_sizes([feat.shape[1]])\n print('conv out lengths: ', lengths)\n\n loader = DataLoader(songs_dset, batch_size=10, collate_fn=collate_fn)\n print('data loader len: ', len(loader))\n\n mini_batch = iter(loader).next()\n out = model(mini_batch[0], mini_batch[1], mini_batch[2])\n print('mini batch output ', out.shape)\n " ]
[ [ "torch.utils.data.DataLoader" ] ]
buzem/inzpeech
[ "9e03b876bb3fd1956774c84683cd02661d650c81" ]
[ "models/model_keras_params.py" ]
[ "import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.layers import Dropout, GlobalMaxPooling2D\nfrom tensorflow.keras.layers import Flatten, Conv2D, MaxPooling2D, ZeroPadding2D, AveragePooling1D, BatchNormalization ,Reshape\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.layers import Activation, Layer\nfrom tensorflow.keras.initializers import GlorotUniform\nimport tensorflow.keras.backend as K\n\nclass SelfAttention(Layer):\n def __init__(self, \n n_hop,\n hidden_dim,\n nc=256,\n penalty=1.0,\n return_attention=False,\n kernel_initializer=GlorotUniform(),\n kernel_regularizer=None,\n kernel_constraint=None,\n **kwargs):\n self.n_hop = n_hop\n self.hidden_dim = hidden_dim\n self.nc=nc\n self.penalty = penalty\n self.kernel_initializer = GlorotUniform() # tf.keras.initializers.get(kernel_initializer)\n self.kernel_regularizer = None #tf.keras.regularizers.get(kernel_regularizer)\n self.kernel_constraint = None #tf.keras.constraints.get(kernel_constraint)\n self.return_attention = return_attention\n super(SelfAttention, self).__init__(**kwargs)\n\n def build(self, input_shape):\n # input_shape: (None, Sequence_size, Sequence_hidden_dim)\n assert len(input_shape) >= 3\n batch_size, T, nh = input_shape\n \n self.Ws1 = self.add_weight(shape=(self.hidden_dim, self.nc),\n initializer=self.kernel_initializer,\n name='SelfAttention-Ws1',\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint)\n \n self.Ws2 = self.add_weight(shape=(self.nc, self.n_hop), \n initializer=self.kernel_initializer,\n name='SelfAttention-Ws2',\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint)\n \n super(SelfAttention, self).build(input_shape)\n\n def compute_output_shape(self, input_shape):\n assert input_shape and len(input_shape) >= 3\n assert input_shape[-1]\n batch_size, sequence_size, sequence_hidden_dim = input_shape\n output_shape = tuple([batch_size, self.n_hop, sequence_hidden_dim])\n \n if self.return_attention:\n attention_shape = tuple([batch_size, self.n_hop, sequence_size])\n return [output_shape, attention_shape]\n else: return output_shape\n\n\n\n \n def _frobenius_norm(self, inputs):\n outputs = K.sqrt(K.sum(K.square(inputs)))\n return outputs \n\n def call(self, inputs):\n shape=inputs.shape\n H=inputs\n x = K.tanh(tf.matmul(H,self.Ws1))\n x = tf.matmul(x,self.Ws2)\n A = K.softmax(x,axis=0) # A = softmax(dot(Ws2, d1))\n At=K.permute_dimensions(A,(0,2,1))\n E = tf.matmul(At,H)\n \n return E\n \n def get_config(self):\n\n config = super().get_config().copy()\n config.update({\n 'n_hop': self.n_hop,\n 'hidden_dim': self.hidden_dim,\n 'nc': self.nc,\n 'penalty': self.penalty,\n 'kernel_initializer': self.kernel_initializer,\n 'kernel_regularizer': self.kernel_regularizer,\n 'kernel_constraint': self.kernel_constraint,\n 'return_attention': self.return_attention,\n })\n return config\n\n\ndef vgg_att(n_class):\n inputs = Input(shape=(300,40,1))\n x=Conv2D(64, (3, 3), padding='same', name='block1_conv1',activation='relu')(inputs)\n x=Conv2D(64, (3, 3), padding='same', name='block1_conv2',activation='relu')(x)\n x=MaxPooling2D(pool_size = (2, 2), strides = (2, 2))(x)\n x=BatchNormalization()(x)\n x=Dropout(0.2)(x)\n\n\n print(x.shape)\n\n x=Conv2D(128, (3, 3), padding='same', name='block2_conv1',activation='relu')(x)\n x=Conv2D(128, (3, 3), padding='same', name='block2_conv2',activation='relu')(x)\n x=MaxPooling2D(pool_size = (2, 2), strides = (2, 2))(x)\n x=BatchNormalization()(x)\n x=Dropout(0.2)(x)\n print(x.shape)\n\n\n x=Conv2D(256, (3, 3), padding='same', name='block3_conv1',activation='relu')(x)\n x=Conv2D(256, (3, 3), padding='same', name='block3_conv2',activation='relu')(x)\n x=MaxPooling2D(pool_size = (2, 2), strides = (2, 2),padding=\"same\")(x)\n x=BatchNormalization()(x)\n x=Dropout(0.2)(x)\n print(x.shape)\n\n x=Conv2D(512, (3, 3), padding='same', name='block4_conv1',activation='relu')(x)\n x=Conv2D(512, (3, 3), padding='same', name='block4_conv2',activation='relu')(x)\n x=MaxPooling2D(pool_size = (2, 2), strides = (2, 2),padding=\"same\")(x)\n x=BatchNormalization()(x)\n x=Dropout(0.2)(x)\n print(x.shape)\n\n att=SelfAttention(n_hop=4,hidden_dim=1536)\n x=Reshape((x.shape[1], x.shape[2]*x.shape[3]))(x)\n print(\"after reshape\")\n print(x.shape)\n x=att(x)\n print(\"after attention\")\n print(x.shape)\n x=AveragePooling1D(pool_size=4,data_format=\"channels_last\")(x)\n #x = GlobalMaxPooling2D()(x)\n print(\"after avgpool\")\n print(x.shape)\n x = Flatten()(x)\n x = Dense(256, activation = 'relu')(x)\n x=Dropout(0.4)(x)\n output = Dense(n_class,activation = 'softmax')(x)\n model = Model(inputs=inputs, outputs=output)\n\n model.compile(loss='categorical_crossentropy',optimizer ='adam')#need hyperparam-tuning \n model.summary()\n return model\n\n\n\n\n\n\n\n\n" ]
[ [ "tensorflow.keras.layers.Flatten", "tensorflow.keras.initializers.GlorotUniform", "tensorflow.keras.backend.softmax", "tensorflow.keras.layers.Dropout", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Reshape", "tensorflow.keras.backend.square", "tensorflow.matmul", "tensorflow.keras.layers.AveragePooling1D", "tensorflow.keras.models.Model", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.backend.permute_dimensions", "tensorflow.keras.layers.Input" ] ]
latticetower/dr-derks-mutants
[ "5c3ab86137ecb478a3013985172d160568a86b13" ]
[ "experiments/train_v1.py" ]
[ "\"\"\"Basic 'network'.\n\nThis code is based on example\nhttp://docs.gym.derkgame.com/#neural-network-example\n\"\"\"\nimport gym\nfrom gym_derk.envs import DerkEnv\nfrom gym_derk import ObservationKeys\nimport math\nimport numpy as np\nimport os.path\n\nfrom models.network_v1 import Network\n\nSEED = 137\nnp.random.seed(SEED)\n\nNPZ_FILENAME = \"weights/model_v2.npz\"\nREWARD_FUNCTION = {\n \"damageEnemyStatue\": 4,\n \"damageEnemyUnit\": 2,\n \"killEnemyStatue\": 4,\n \"killEnemyUnit\": 2,\n \"healFriendlyStatue\": 1,\n \"healTeammate1\": 2,\n \"healTeammate2\": 2,\n \"timeSpentHomeBase\": 0,\n \"timeSpentHomeTerritory\": 0,\n \"timeSpentAwayTerritory\": 0,\n \"timeSpentAwayBase\": 0,\n \"damageTaken\": -1,\n \"friendlyFire\": -1,\n \"healEnemy\": -1,\n \"fallDamageTaken\": -10,\n \"statueDamageTaken\": 0,\n \"manualBonus\": 0,\n \"victory\": 100,\n \"loss\": -100,\n \"tie\": 0,\n \"teamSpirit\": 0.5,\n \"timeScaling\": 0.8,\n}\n\n\nenv = DerkEnv(\n mode=\"train\",\n turbo_mode=True,\n home_team=[\n {'primaryColor': '#ff00ff'},\n {'primaryColor': '#00ff00', 'slots': ['Talons', None, None]},\n {'primaryColor': '#ff0000', 'rewardFunction': {'healTeammate1': 1}}\n ],\n away_team=[\n {'primaryColor': '#c0c0c0'},\n {'primaryColor': 'navy', 'slots': ['Talons', None, None]},\n {'primaryColor': 'red', 'rewardFunction': {'healTeammate1': 1}}\n ],\n session_args = {\n \"reward_function\": REWARD_FUNCTION\n }\n)\n\n\nif os.path.exists(NPZ_FILENAME):\n with np.load(NPZ_FILENAME) as data:\n weights = np.asarray(data['weights']).copy()\n biases = np.asarray(data['biases']).copy()\nelse:\n weights = None\n biases = None\n\n\nnetworks = [\n Network(weights, biases) for i in range(env.n_agents)\n]\n\nfor e in range(1): # 20\n observation_n = env.reset()\n while True:\n action_n = [\n networks[i].forward(observation_n[i])\n for i in range(env.n_agents)\n ]\n observation_n, reward_n, done_n, info = env.step(action_n)\n if all(done_n):\n print(\"Episode finished\")\n break\n if env.mode == 'train':\n reward_n = env.total_reward\n print(reward_n)\n top_network_i = np.argmax(reward_n)\n top_network = networks[top_network_i].clone()\n for network in networks:\n network.copy_and_mutate(top_network)\n print(f'Round {e} top reward', reward_n[top_network_i])\n np.savez_compressed(\n NPZ_FILENAME,\n weights=top_network.weights,\n biases=top_network.biases\n )\nenv.close()\n" ]
[ [ "numpy.load", "numpy.random.seed", "numpy.asarray", "numpy.argmax", "numpy.savez_compressed" ] ]
TingFree/AI_Conference_Timeline
[ "788dd5a4a8cd5009d8de3a1306ddb38f044cc7c5" ]
[ "codes/nlper/models/text_clf.py" ]
[ "r\"\"\"\n各种文本分类模型的实现\n\"\"\"\n\nimport os\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.optim import AdamW\nfrom torch.utils.data import DataLoader\nfrom transformers import AutoModel\nfrom transformers.models.bert.modeling_bert import BertModel\nfrom transformers import DataCollatorWithPadding, get_linear_schedule_with_warmup\nfrom codes.nlper.modules import MLP\nfrom codes.nlper.utils import DatasetCLF, Dict2Obj\nfrom codes.nlper.utils import load_nlp_data, save_data\nfrom codes.nlper import mini_pytorch_lightning as mpl\n\n\nclass LightningCLF(mpl.StandardModel):\n def __init__(self, model, tokenizer, configs: Dict2Obj, metrics, convert_fn):\n super(LightningCLF, self).__init__(configs, metrics)\n self.configs = configs\n self.aux_configs = Dict2Obj()\n self.metrics = metrics\n self.model = model\n self.tokenizer = tokenizer\n self.convert_fn = convert_fn\n\n def training_step(self, batch, batch_idx):\n labels = batch['labels']\n logits = self.model(**batch)\n loss = F.cross_entropy(logits.view(-1, self.configs.num_class),\n labels.view(-1))\n return loss,\n\n def validation_step(self, batch, batch_idx):\n labels = batch['labels']\n logits = self.model(**batch)\n loss = F.cross_entropy(logits.view(-1, self.configs.num_class),\n labels.view(-1))\n batch_preds = logits.argmax(1).cpu().tolist()\n batch_golds = labels.cpu().tolist()\n return loss, batch_preds, batch_golds\n\n def validation_epoch_end(self, outputs):\n epoch_preds, epoch_golds = [], []\n for (batch_loss, batch_preds, batch_golds) in outputs:\n epoch_preds += batch_preds\n epoch_golds += batch_golds\n self.metrics.scores(epoch_golds, epoch_preds)\n self.metrics.print_values()\n return self.metrics.return_target_score()\n\n def test_step(self, batch, batch_idx):\n logits = self.model(**batch)\n # prob, pred\n return F.softmax(logits, dim=-1).cpu().tolist(),\\\n logits.argmax(1).cpu().tolist()\n\n def test_epoch_end(self, outputs):\n probs, preds = [], []\n for (batch_probs, batch_preds) in outputs:\n probs += [' '.join([str(p) for p in prob]) for prob in batch_probs]\n preds += batch_preds\n save_data(probs, os.path.join(self.configs.out_dir, 'test_pred.probs.txt'))\n save_data(preds, os.path.join(self.configs.out_dir, 'test_pred.txt'))\n\n def configure_optimizers(self):\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in self.named_parameters() if not any(nd in n for nd in no_decay)],\n 'weight_decay': self.configs.weight_decay},\n {'params': [p for n, p in self.named_parameters()if any(nd in n for nd in no_decay)],\n 'weight_decay': 0.0}\n ]\n optimizer = AdamW(optimizer_grouped_parameters,\n lr=self.configs.lr)\n scheduler = get_linear_schedule_with_warmup(optimizer,\n self.configs.warmup_steps,\n self.configs.trainer_args.max_epochs * self.aux_configs.num_train_batch)\n return optimizer, scheduler\n\n def prepare_data(self) -> None:\n \"\"\" check & load data, the format of each line is 'text label', separated by tab and 'label'\n must be int, such as 0~num_labels-1\n \"\"\"\n train_file = self.configs.train_file\n val_file = self.configs.val_file\n test_file = self.configs.test_file\n self.collate_fn = DataCollatorWithPadding(tokenizer=self.tokenizer)\n if self.convert_fn:\n self._train_data = self.convert_fn(train_file, load_label=True)\n self._val_data = self.convert_fn(val_file, load_label=True)\n self._test_data = self.convert_fn(test_file, load_label=self.configs.is_eval_test)\n else:\n self._train_data = load_nlp_data(train_file, task_name=self.configs.task_name)\n self._val_data = load_nlp_data(val_file, task_name=self.configs.task_name)\n self._test_data = load_nlp_data(test_file, task_name=self.configs.task_name)\n\n def train_dataloader(self):\n self.train_data = DatasetCLF(self._train_data,\n self.tokenizer,\n self.configs.max_len,\n load_label=True)\n return DataLoader(self.train_data,\n batch_size=self.configs.train_batch_size,\n collate_fn=self.collate_fn,\n shuffle=True,\n num_workers=16)\n\n def val_dataloader(self):\n self.val_data = DatasetCLF(self._val_data,\n self.tokenizer,\n self.configs.max_len,\n load_label=True)\n return DataLoader(self.val_data,\n batch_size=self.configs.val_batch_size,\n collate_fn=self.collate_fn,\n num_workers=16)\n\n def test_dataloader(self):\n self.test_data = DatasetCLF(self._test_data,\n self.tokenizer,\n self.configs.max_len,\n load_label=self.configs.is_eval_test)\n return DataLoader(self.test_data,\n batch_size=self.configs.val_batch_size,\n collate_fn=self.collate_fn,\n num_workers=16)\n\n\nclass BertCLF(nn.Module):\n def __init__(self, args):\n super(BertCLF, self).__init__()\n self.bert = AutoModel.from_pretrained(args.pretrained_model)\n self.dropout = nn.Dropout(self.bert.config.hidden_dropout_prob)\n self.clf = MLP([self.bert.config.hidden_size, args.num_class],\n 'tanh',\n dropout=args.dropout)\n\n def forward(self, input_ids, attention_mask, token_type_ids, return_pooler_output=False, **kwargs):\n \"\"\"\n\n :param input_ids:\n :param attention_mask:\n :param token_type_ids:\n :param return_pooler_output: 是否返回最后用于分类的句子表示\n :return:\n \"\"\"\n outputs = self.bert(input_ids, attention_mask, token_type_ids)\n logits = self.clf(outputs[1])\n if return_pooler_output:\n return logits, outputs[1]\n return logits\n" ]
[ [ "torch.utils.data.DataLoader", "torch.nn.functional.softmax", "torch.optim.AdamW", "torch.nn.Dropout" ] ]
shadiakiki1986/garage
[ "095bb5d25b32df1d44b47e99a78a9b01796941d9" ]
[ "garage/replay_buffer/simple_replay_buffer.py" ]
[ "\"\"\"This module implements a simple replay buffer.\"\"\"\nimport numpy as np\n\nfrom garage.misc.overrides import overrides\nfrom garage.replay_buffer.base import ReplayBuffer\n\n\nclass SimpleReplayBuffer(ReplayBuffer):\n \"\"\"\n This class implements SimpleReplayBuffer.\n\n It uses random batch sample to minimize correlations between samples.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Initialize the data used in SimpleReplayBuffer.\"\"\"\n super(SimpleReplayBuffer, self).__init__(**kwargs)\n\n @overrides\n def sample(self, batch_size):\n \"\"\"Sample a transition of batch_size.\"\"\"\n assert self._n_transitions_stored > batch_size\n buffer = {}\n for key in self._buffer.keys():\n buffer[key] = self._buffer[key][:self._current_size]\n\n # Select which episodes to use\n time_horizon = buffer[\"action\"].shape[1]\n rollout_batch_size = buffer[\"action\"].shape[0]\n episode_idxs = np.random.randint(rollout_batch_size, size=batch_size)\n # Select time steps to use\n t_samples = np.random.randint(time_horizon, size=batch_size)\n\n transitions = {}\n for key in buffer.keys():\n samples = buffer[key][episode_idxs, t_samples].copy()\n transitions[key] = samples.reshape(batch_size, *samples.shape[1:])\n\n assert (transitions[\"action\"].shape[0] == batch_size)\n return transitions\n" ]
[ [ "numpy.random.randint" ] ]
Jee-King/STNet
[ "221ab60c4fccfce5a03e8878fb168e0baa7152f4" ]
[ "videoanalyst/model/backbone/backbone_impl/snn3.py" ]
[ "# -*- coding: utf-8 -*\n# --------------------------------------------------------\n# SNNformer Feature Extractor (SFE) - SNN branch\n# --------------------------------------------------------\n\nimport torch.nn as nn\nimport torch\n\nfrom videoanalyst.model.backbone.backbone_base import (TRACK_BACKBONES,\n VOS_BACKBONES)\nfrom videoanalyst.model.common_opr.common_block import conv_bn_relu\nfrom videoanalyst.model.module_base import ModuleBase\n\nthresh_bais = 0.3\n# thresh = 0.3 # neuronal threshold\nlens = 0.5 # hyper-parameters of approximate function\ndecay = 0.2 # decay constants\nglobal thresh\n\nclass SpatialGroupEnhance(nn.Module):\n \"\"\" Dynamic Spiking Threshold from spatial features\"\"\"\n def __init__(self):\n super(SpatialGroupEnhance, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.weight = nn.Parameter(torch.zeros(1, 1, 1, 1))\n self.bias = nn.Parameter(torch.ones(1, 1, 1, 1))\n self.sig = nn.Sigmoid()\n\n def forward(self, x): # (b, c, h, w)\n b, c, h, w = x.size()\n xn = x * self.avg_pool(x)\n xn = xn.mean(dim=1, keepdim=True)\n entro = torch.mean(xn, dim=0).squeeze()\n h,w = entro.size()\n entro = entro.view(-1)\n max = torch.max(entro)\n min = torch.min(entro)\n entro = (entro - min) / (max-min) * 255\n his = torch.histc(entro, bins=256, min=0, max=255) / (h*w)\n entro_final = torch.sum(his * -torch.log(his + 0.00000001))\n entro_final = entro_final / torch.count_nonzero(his)\n x = self.sig(xn)\n x = torch.mean(x)\n return x + entro_final*10\n\nclass ActFun(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input):\n ctx.save_for_backward(input)\n return input.gt(thresh).float()\n\n @staticmethod\n def backward(ctx, grad_output):\n input, = ctx.saved_tensors\n grad_input = grad_output.clone()\n temp = abs(input - thresh) < lens\n return grad_input * temp.float()\n\nact_fun = ActFun.apply\n\n\n# membrane potential update\ndef mem_update(ops, x, mem, spike):\n mem = mem * decay * (1. - spike) + ops(x)\n spike = act_fun(mem) # act_fun : approximation firing function\n return mem, spike\n\ncfg_cnn = [(6, 64, 2, 0, 11),\n (64, 128, 2, 0, 9),\n (128, 256, 2, 0, 5),\n (64, 128, 1, 1, 3),\n (128, 256, 1, 1, 3)]\n# kernel size\ncfg_kernel = [147, 70, 33, 31, 31]\ncfg_kernel_first = [59, 26, 11, 15, 15]\n# fc layer\ncfg_fc = [128, 10]\n\n@VOS_BACKBONES.register\n@TRACK_BACKBONES.register\n\n\nclass SNN3(ModuleBase):\n r\"\"\"\n SNN branch\n\n Hyper-parameters\n ----------------\n pretrain_model_path: string\n Path to pretrained backbone parameter file,\n Parameter to be loaded in _update_params_\n \"\"\"\n default_hyper_params = {\"pretrain_model_path\": \"\"}\n\n def __init__(self):\n super(SNN3, self).__init__()\n\n cfg_cnn = [(3, 64, 2, 0, 11),\n (64, 128, 2, 0, 9),\n (128, 256, 2, 0, 5),\n (64, 128, 1, 1, 3),\n (128, 256, 1, 1, 3)]\n # kernel size\n cfg_kernel = [147, 70, 33, 31, 31]\n cfg_kernel_first = [59, 26, 11, 15, 15]\n\n in_planes, out_planes, stride, padding, kernel_size = cfg_cnn[0]\n self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding)\n in_planes, out_planes, stride, padding, kernel_size = cfg_cnn[1]\n self.conv2 = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding)\n in_planes, out_planes, stride, padding, kernel_size = cfg_cnn[2]\n self.conv3 = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding)\n self.bn_tem = nn.BatchNorm2d(256)\n self.relu_tem = nn.ReLU()\n\n self.fuse_snn_transfor = nn.Conv2d(out_planes*2, out_planes, kernel_size=1, stride=1, padding=0)\n self.thre_w = SpatialGroupEnhance()\n self.conv33_11 = nn.Conv2d(256, 256, kernel_size=13, stride=2, padding=0)\n self.bn_spa = nn.BatchNorm2d(256)\n self.relu_spa = nn.ReLU()\n\n def forward(self, input_pos, input_neg, trans_snn, transformer_sig, transformer_fea, first_seq):\n global thresh\n if transformer_fea is None:\n thresh = 0.3\n else:\n thresh = self.thre_w(transformer_fea) * thresh_bais\n if first_seq:\n time_window = len(input_pos)\n tem_c3m = 0\n for step in range(time_window):\n x_pos = input_pos[step]\n x_neg = input_neg[step]\n x = torch.where(x_pos > x_neg, x_pos, x_neg)\n c1_mem, c1_spike = mem_update(self.conv1, x.float(), trans_snn[0], trans_snn[1])\n c2_mem, c2_spike = mem_update(self.conv2, c1_spike, trans_snn[2], trans_snn[3])\n c3_mem, c3_spike = mem_update(self.conv3, c2_spike, trans_snn[4], trans_snn[5])\n trans_snn = [c1_mem, c1_spike, c2_mem, c2_spike, c3_mem, c3_spike]\n tem_c3m = tem_c3m + c3_mem\n tem_fea = tem_c3m / time_window\n tem_fea = self.relu_tem(self.bn_tem(tem_fea))\n spa_fea = self.relu_spa(self.bn_spa(self.conv33_11(transformer_fea)))\n return tem_fea, spa_fea, trans_snn\n else:\n time_window = len(input_pos)\n tem_c3m = 0\n for step in range(time_window):\n x_pos = input_pos[step]\n x_neg = input_neg[step]\n x = torch.where(x_pos > x_neg, x_pos, x_neg)\n c1_mem, c1_spike = mem_update(self.conv1, x.float(), trans_snn[0], trans_snn[1])\n c2_mem, c2_spike = mem_update(self.conv2, c1_spike, trans_snn[2], trans_snn[3])\n c3_mem, c3_spike = mem_update(self.conv3, c2_spike, trans_snn[4], trans_snn[5])\n trans_snn = [c1_mem, c1_spike, c2_mem, c2_spike, c3_mem, c3_spike]\n tem_c3m = tem_c3m + c3_mem\n tem_fea = tem_c3m / time_window\n tem_fea = self.relu_tem(self.bn_tem(tem_fea))\n spa_fea = transformer_fea\n return tem_fea, spa_fea, trans_snn\n" ]
[ [ "torch.nn.BatchNorm2d", "torch.min", "torch.ones", "torch.nn.AdaptiveAvgPool2d", "torch.count_nonzero", "torch.where", "torch.log", "torch.nn.Conv2d", "torch.max", "torch.zeros", "torch.histc", "torch.nn.Sigmoid", "torch.nn.ReLU", "torch.mean" ] ]
tobsen2code/pyleecan
[ "1faedde4b24acc6361fa1fdd4e980eaec4ca3a62" ]
[ "Tests/Plot/LamWind/test_Slot_12_plot.py" ]
[ "# -*- coding: utf-8 -*-\nfrom os.path import join\n\nimport matplotlib.pyplot as plt\nfrom numpy import array, pi, zeros\n\nfrom pyleecan.Classes.Frame import Frame\nfrom pyleecan.Classes.LamSlotWind import LamSlotWind\nfrom pyleecan.Classes.LamSquirrelCage import LamSquirrelCage\nfrom pyleecan.Classes.MachineDFIM import MachineDFIM\nfrom pyleecan.Classes.Shaft import Shaft\nfrom pyleecan.Classes.VentilationCirc import VentilationCirc\nfrom pyleecan.Classes.VentilationPolar import VentilationPolar\nfrom pyleecan.Classes.VentilationTrap import VentilationTrap\nfrom pyleecan.Classes.Winding import Winding\nfrom pyleecan.Classes.WindingUD import WindingUD\nfrom pyleecan.Classes.MatMagnetics import MatMagnetics\nfrom pyleecan.Classes.SlotW12 import SlotW12\n\nfrom Tests import save_plot_path as save_path\nfrom Tests.Plot.LamWind import wind_mat\n\nimport pytest\n\n\n\"\"\"pytest for Lamination with winding plot\"\"\"\n\n\nclass Test_Slot_12_plot(object):\n def test_Lam_Wind_12_wind_22(self):\n \"\"\"Test machine plot with Slot 12 and winding rad=2, tan=2\"\"\"\n print(\"\\nTest plot Slot 12\")\n plt.close(\"all\")\n test_obj = MachineDFIM()\n test_obj.rotor = LamSlotWind(\n Rint=0.2,\n Rext=0.5,\n is_internal=True,\n is_stator=False,\n L1=0.9,\n Nrvd=2,\n Wrvd=0.05,\n )\n test_obj.rotor.axial_vent = [\n VentilationPolar(Zh=6, Alpha0=pi / 6, W1=pi / 6, D0=100e-3, H0=0.3)\n ]\n test_obj.rotor.slot = SlotW12(Zs=6, R2=35e-3, H0=20e-3, R1=17e-3, H1=130e-3)\n test_obj.rotor.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n test_obj.rotor.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n test_obj.shaft = Shaft(Drsh=test_obj.rotor.Rint * 2, Lshaft=1)\n\n test_obj.stator = LamSlotWind(\n Rint=0.51,\n Rext=0.8,\n is_internal=False,\n is_stator=True,\n L1=0.9,\n Nrvd=2,\n Wrvd=0.05,\n )\n test_obj.stator.slot = SlotW12(Zs=18, R2=25e-3, H0=30e-3, R1=0, H1=150e-3)\n test_obj.stator.winding.Lewout = 60e-3\n test_obj.stator.winding = Winding(qs=3, p=3, Nlayer=2, coil_pitch=2)\n test_obj.stator.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n test_obj.frame = Frame(Rint=0.8, Rext=0.9, Lfra=1)\n\n test_obj.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s12_1-Machine.png\"))\n # Rotor + Stator + 2 for frame + 1 for Shaft\n assert len(fig.axes[0].patches) == 73\n\n test_obj.rotor.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s12_2-Rotor.png\"))\n # 2 for lam + Zs*4 for wind + 6 vents\n assert len(fig.axes[0].patches) == 32\n\n test_obj.stator.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s12_3-Stator.png\"))\n # 2 for lam + Zs*2 for wind\n assert len(fig.axes[0].patches) == 38\n\n tooth = test_obj.rotor.slot.get_surface_tooth()\n tooth.plot(color=\"r\", is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s12_Tooth_in.png\"))\n\n tooth = test_obj.stator.slot.get_surface_tooth()\n tooth.plot(color=\"r\", is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"test_Lam_Wind_s12_Tooth_out.png\"))\n" ]
[ [ "matplotlib.pyplot.gcf", "matplotlib.pyplot.close" ] ]
brianhie/icml18-jtnn
[ "fabede920d7def1d248c3157dd31f7cc5a2132e0" ]
[ "jtnn/datautils.py" ]
[ "from torch.utils.data import Dataset\nfrom .mol_tree import MolTree\nimport numpy as np\n\nclass MoleculeDataset(Dataset):\n\n def __init__(self, data_file):\n with open(data_file) as f:\n self.data = [line.strip(\"\\r\\n \").split()[0] for line in f]\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n smiles = self.data[idx]\n mol_tree = MolTree(smiles)\n mol_tree.recover()\n mol_tree.assemble()\n return mol_tree\n\nclass PropDataset(Dataset):\n\n def __init__(self, data_file, prop_file):\n self.prop_data = np.loadtxt(prop_file)\n with open(data_file) as f:\n self.data = [line.strip(\"\\r\\n \").split()[0] for line in f]\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n smiles = self.data[idx]\n mol_tree = MolTree(smiles)\n mol_tree.recover()\n mol_tree.assemble()\n return mol_tree, self.prop_data[idx]\n" ]
[ [ "numpy.loadtxt" ] ]
Takezo87/torchtools
[ "4230305d9063dabee3614f0dcd8557739b90f817" ]
[ "torchtools/models.py" ]
[ "# AUTOGENERATED! DO NOT EDIT! File to edit: 01_models.ipynb (unless otherwise specified).\n\n__all__ = ['noop', 'shortcut', 'Inception', 'InceptionBlock', 'InceptionTime', 'Squeeze', 'Unsqueeze', 'Add', 'Concat',\n 'Permute', 'Transpose', 'View', 'Reshape', 'Max', 'LastStep', 'Noop', 'TransformerModel',\n 'ScaledDotProductAttention', 'MultiHeadAttention', 'TSTEncoderLayer', 'TSTEncoder', 'TST', 'Sigmoid',\n 'InceptionTimeSgmOld', 'InceptionTimeSgm', 'TransformerSgm', 'TransformerSgmD', 'InceptionTimeD',\n 'InceptionTime_NH', 'InceptionTimeD_Mixed', 'InceptionTime_Mixed', 'TabNetTT', 'InceptionTimeVar',\n 'nll_regression', 'nll_leaky_loss', 'qd_loss', 'InceptionTimeBounds']\n\n# Cell\nfrom .core import *\n\n# Cell\nimport torch.nn as nn\nimport torch as torch\nimport torch.nn.functional as F\n\nfrom functools import partial\n\nfrom fastai.layers import SigmoidRange\nfrom fastai.torch_basics import *\n# from ..imports import *\n# from .layers import *\n# from .utils import *\nfrom torch.nn.modules.transformer import TransformerEncoder, TransformerEncoderLayer\n\n# Cell\n# This is an unofficial PyTorch implementation by Ignacio Oguiza - [email protected] based on:\n\n# Fawaz, H. I., Lucas, B., Forestier, G., Pelletier, C., Schmidt, D. F., Weber, J., ... & Petitjean, F. (2019). InceptionTime: Finding AlexNet for Time Series Classification. arXiv preprint arXiv:1909.04939.\n# Official InceptionTime tensorflow implementation: https://github.com/hfawaz/InceptionTime\n\n\ndef noop(x):\n return x\n\ndef shortcut(c_in, c_out):\n return nn.Sequential(*[nn.Conv1d(c_in, c_out, kernel_size=1),\n nn.BatchNorm1d(c_out)])\n\nclass Inception(nn.Module):\n def __init__(self, c_in, bottleneck=32, ks=40, nb_filters=32):\n\n super().__init__()\n self.bottleneck = nn.Conv1d(c_in, bottleneck, 1) if bottleneck and c_in > 1 else noop\n mts_feat = bottleneck or c_in\n conv_layers = []\n kss = [ks // (2**i) for i in range(3)]\n # ensure odd kss until nn.Conv1d with padding='same' is available in pytorch 1.3\n kss = [ksi if ksi % 2 != 0 else ksi - 1 for ksi in kss]\n for i in range(len(kss)):\n conv_layers.append(\n nn.Conv1d(mts_feat, nb_filters, kernel_size=kss[i], padding=kss[i] // 2))\n self.conv_layers = nn.ModuleList(conv_layers)\n self.maxpool = nn.MaxPool1d(3, stride=1, padding=1)\n self.conv = nn.Conv1d(c_in, nb_filters, kernel_size=1)\n self.bn = nn.BatchNorm1d(nb_filters * 4)\n self.act = nn.ReLU()\n\n def forward(self, x):\n input_tensor = x.to(torch.float)\n x = self.bottleneck(input_tensor)\n for i in range(3):\n out_ = self.conv_layers[i](x)\n if i == 0: out = out_\n else: out = torch.cat((out, out_), 1)\n mp = self.conv(self.maxpool(input_tensor))\n inc_out = torch.cat((out, mp), 1)\n return self.act(self.bn(inc_out))\n\n\nclass InceptionBlock(nn.Module):\n def __init__(self,c_in,bottleneck=32,ks=40,nb_filters=32,residual=True,depth=6):\n\n super().__init__()\n\n self.residual = residual\n self.depth = depth\n\n #inception & residual layers\n inc_mods = []\n res_layers = []\n res = 0\n for d in range(depth):\n inc_mods.append(\n Inception(c_in if d == 0 else nb_filters * 4, bottleneck=bottleneck if d > 0 else 0,ks=ks,\n nb_filters=nb_filters))\n if self.residual and d % 3 == 2:\n res_layers.append(shortcut(c_in if res == 0 else nb_filters * 4, nb_filters * 4))\n res += 1\n else: res_layer = res_layers.append(None)\n self.inc_mods = nn.ModuleList(inc_mods)\n self.res_layers = nn.ModuleList(res_layers)\n self.act = nn.ReLU()\n\n def forward(self, x):\n res = x\n for d, l in enumerate(range(self.depth)):\n x = self.inc_mods[d](x)\n if self.residual and d % 3 == 2:\n res = self.res_layers[d](res)\n x += res\n res = x\n x = self.act(x)\n return x\n\n# Cell\nclass InceptionTime(nn.Module):\n def __init__(self,c_in,c_out,bottleneck=32,ks=40,nb_filters=32,residual=True,depth=6):\n super().__init__()\n self.block = InceptionBlock(c_in,bottleneck=bottleneck,ks=ks,nb_filters=nb_filters,\n residual=residual,depth=depth)\n self.gap = nn.AdaptiveAvgPool1d(1)\n self.fc = nn.Linear(nb_filters * 4, c_out)\n\n def forward(self, *x):\n x = torch.cat(x, dim=-2)\n x = self.block(x)\n x = self.gap(x).squeeze(-1)\n x = self.fc(x)\n return x\n\n# Cell\nclass Squeeze(Module):\n def __init__(self, dim=-1): self.dim = dim\n def forward(self, x): return x.squeeze(dim=self.dim)\n def __repr__(self): return f'{self.__class__.__name__}(dim={self.dim})'\n\n\nclass Unsqueeze(Module):\n def __init__(self, dim=-1): self.dim = dim\n def forward(self, x): return x.unsqueeze(dim=self.dim)\n def __repr__(self): return f'{self.__class__.__name__}(dim={self.dim})'\n\n\nclass Add(Module):\n def forward(self, x, y): return x.add(y)\n def __repr__(self): return f'{self.__class__.__name__}'\n\n\nclass Concat(Module):\n def __init__(self, dim=1): self.dim = dim\n def forward(self, *x): return torch.cat(*x, dim=self.dim)\n def __repr__(self): return f'{self.__class__.__name__}(dim={self.dim})'\n\n\nclass Permute(Module):\n def __init__(self, *dims): self.dims = dims\n def forward(self, x): return x.permute(self.dims)\n def __repr__(self): return f\"{self.__class__.__name__}(dims={', '.join([str(d) for d in self.dims])})\"\n\n\nclass Transpose(Module):\n def __init__(self, *dims, contiguous=False): self.dims, self.contiguous = dims, contiguous\n def forward(self, x):\n if self.contiguous: return x.transpose(*self.dims).contiguous()\n else: return x.transpose(*self.dims)\n def __repr__(self):\n if self.contiguous: return f\"{self.__class__.__name__}(dims={', '.join([str(d) for d in self.dims])}).contiguous()\"\n else: return f\"{self.__class__.__name__}({', '.join([str(d) for d in self.dims])})\"\n\n\nclass View(Module):\n def __init__(self, *shape): self.shape = shape\n def forward(self, x): return x.view(x.shape[0], *self.shape)\n def __repr__(self): return f\"{self.__class__.__name__}({', '.join(['bs'] + [str(s) for s in self.shape])})\"\n\n\nclass Reshape(Module):\n def __init__(self, *shape): self.shape = shape\n def forward(self, x): return x.reshape(x.shape[0], *self.shape)\n def __repr__(self): return f\"{self.__class__.__name__}({', '.join(['bs'] + [str(s) for s in self.shape])})\"\n\n\nclass Max(Module):\n def __init__(self, dim=None, keepdim=False): self.dim, self.keepdim = dim, keepdim\n def forward(self, x): return x.max(self.dim, keepdim=self.keepdim)[0]\n def __repr__(self): return f'{self.__class__.__name__}(dim={self.dim}, keepdim={self.keepdim})'\n\n\nclass LastStep(Module):\n def forward(self, x): return x[..., -1]\n def __repr__(self): return f'{self.__class__.__name__}()'\n\n\nNoop = nn.Sequential()\n\n# Cell\nclass TransformerModel(Module):\n def __init__(self, c_in, c_out, d_model=64, n_head=1, d_ffn=128, dropout=0.1, activation=\"relu\", n_layers=1):\n \"\"\"\n Args:\n c_in: the number of features (aka variables, dimensions, channels) in the time series dataset\n c_out: the number of target classes\n d_model: total dimension of the model.\n nhead: parallel attention heads.\n d_ffn: the dimension of the feedforward network model.\n dropout: a Dropout layer on attn_output_weights.\n activation: the activation function of intermediate layer, relu or gelu.\n num_layers: the number of sub-encoder-layers in the encoder.\n Input shape:\n bs (batch size) x nvars (aka variables, dimensions, channels) x seq_len (aka time steps)\n \"\"\"\n self.permute = Permute(2, 0, 1)\n self.inlinear = nn.Linear(c_in, d_model)\n self.relu = nn.ReLU()\n encoder_layer = TransformerEncoderLayer(d_model, n_head, dim_feedforward=d_ffn, dropout=dropout, activation=activation)\n encoder_norm = nn.LayerNorm(d_model)\n self.transformer_encoder = TransformerEncoder(encoder_layer, n_layers, norm=encoder_norm)\n self.transpose = Transpose(1, 0)\n self.max = Max(1)\n self.outlinear = nn.Linear(d_model, c_out)\n\n def forward(self,x):\n x = self.permute(x) # bs x nvars x seq_len -> seq_len x bs x nvars\n x = self.inlinear(x) # seq_len x bs x nvars -> seq_len x bs x d_model\n x = self.relu(x)\n x = self.transformer_encoder(x)\n x = self.transpose(x) # seq_len x bs x d_model -> bs x seq_len x d_model\n x = self.max(x)\n x = self.relu(x)\n x = self.outlinear(x)\n return x\n\n# Cell\nclass ScaledDotProductAttention(Module):\n def __init__(self, d_k:int): self.d_k = d_k\n def forward(self, q:Tensor, k:Tensor, v:Tensor, mask:Optional[Tensor]=None):\n\n # MatMul (q, k) - similarity scores for all pairs of positions in an input sequence\n scores = torch.matmul(q, k) # scores : [bs x n_heads x q_len x q_len]\n\n # Scale\n scores = scores / (self.d_k ** 0.5)\n\n # Mask (optional)\n if mask is not None: scores.masked_fill_(mask, -1e9)\n\n # SoftMax\n attn = F.softmax(scores, dim=-1) # attn : [bs x n_heads x q_len x q_len]\n\n # MatMul (attn, v)\n context = torch.matmul(attn, v) # context: [bs x n_heads x q_len x d_v]\n\n return context, attn\n\n# Cell\nclass MultiHeadAttention(Module):\n def __init__(self, d_model:int, n_heads:int, d_k:int, d_v:int):\n r\"\"\"\n Input shape: Q, K, V:[batch_size (bs) x q_len x d_model], mask:[q_len x q_len]\n \"\"\"\n self.n_heads, self.d_k, self.d_v = n_heads, d_k, d_v\n\n self.W_Q = nn.Linear(d_model, d_k * n_heads, bias=False)\n self.W_K = nn.Linear(d_model, d_k * n_heads, bias=False)\n self.W_V = nn.Linear(d_model, d_v * n_heads, bias=False)\n\n self.W_O = nn.Linear(n_heads * d_v, d_model, bias=False)\n\n def forward(self, Q:Tensor, K:Tensor, V:Tensor, mask:Optional[Tensor]=None):\n\n bs = Q.size(0)\n\n # Linear (+ split in multiple heads)\n q_s = self.W_Q(Q).view(bs, -1, self.n_heads, self.d_k).transpose(1,2) # q_s : [bs x n_heads x q_len x d_k]\n k_s = self.W_K(K).view(bs, -1, self.n_heads, self.d_k).permute(0,2,3,1) # k_s : [bs x n_heads x d_k x q_len] - transpose(1,2) + transpose(2,3)\n v_s = self.W_V(V).view(bs, -1, self.n_heads, self.d_v).transpose(1,2) # v_s : [bs x n_heads x q_len x d_v]\n\n # Scaled Dot-Product Attention (multiple heads)\n context, attn = ScaledDotProductAttention(self.d_k)(q_s, k_s, v_s) # context: [bs x n_heads x q_len x d_v], attn: [bs x n_heads x q_len x q_len]\n\n # Concat\n context = context.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * self.d_v) # context: [bs x q_len x n_heads * d_v]\n\n # Linear\n output = self.W_O(context) # context: [bs x q_len x d_model]\n\n return output, attn\n\n# Cell\nclass TSTEncoderLayer(Module):\n def __init__(self, d_model:int, n_heads:int, d_k:Optional[int]=None, d_v:Optional[int]=None, d_ff:int=256, res_dropout:float=0.1, activation:str=\"gelu\"):\n\n assert d_model // n_heads, f\"d_model ({d_model}) must be divisible by n_heads ({n_heads})\"\n d_k = ifnone(d_k, d_model // n_heads)\n d_v = ifnone(d_v, d_model // n_heads)\n\n # Multi-Head attention\n self.self_attn = MultiHeadAttention(d_model, n_heads, d_k, d_v)\n\n # Add & Norm\n self.dropout_attn = nn.Dropout(res_dropout)\n self.batchnorm_attn = nn.BatchNorm1d(d_model)\n\n # Position-wise Feed-Forward\n self.ff = nn.Sequential(nn.Linear(d_model, d_ff), self._get_activation_fn(activation), nn.Linear(d_ff, d_model))\n\n # Add & Norm\n self.dropout_ffn = nn.Dropout(res_dropout)\n self.batchnorm_ffn = nn.BatchNorm1d(d_model)\n\n def forward(self, src:Tensor, mask:Optional[Tensor]=None) -> Tensor:\n\n # Multi-Head attention sublayer\n ## Multi-Head attention\n src2, attn = self.self_attn(src, src, src, mask=mask)\n ## Add & Norm\n src = src + self.dropout_attn(src2) # Add: residual connection with residual dropout\n src = self.batchnorm_attn(src.permute(1,2,0)).permute(2,0,1) # Norm: batchnorm (requires d_model features to be in dim 1)\n\n # Feed-forward sublayer\n ## Position-wise Feed-Forward\n src2 = self.ff(src)\n ## Add & Norm\n src = src + self.dropout_ffn(src2) # Add: residual connection with residual dropout\n src = self.batchnorm_ffn(src.permute(1,2,0)).permute(2,0,1) # Norm: batchnorm (requires d_model features to be in dim 1)\n\n return src\n\n def _get_activation_fn(self, activation):\n if activation == \"relu\": return nn.ReLU()\n elif activation == \"gelu\": return nn.GELU()\n raise ValueError(f'{activation} is not available. You can use \"relu\" or \"gelu\"')\n\n# Cell\nclass TSTEncoder(Module):\n def __init__(self, encoder_layer, n_layers):\n self.layers = nn.ModuleList([deepcopy(encoder_layer) for i in range(n_layers)])\n\n def forward(self, src:Tensor, mask:Optional[Tensor]=None) -> Tensor:\n output = src\n for mod in self.layers: output = mod(output, mask=mask)\n return output\n\n\n# Cell\nclass TST(Module):\n def __init__(self, c_in:int, c_out:int, seq_len:int, max_seq_len:Optional[int]=None,\n n_layers:int=3, d_model:int=128, n_heads:int=16, d_k:Optional[int]=None, d_v:Optional[int]=None,\n d_ff:int=256, res_dropout:float=0.1, activation:str=\"gelu\", fc_dropout:float=0.,\n y_range:Optional[tuple]=None, verbose:bool=False, **kwargs):\n r\"\"\"TST (Time Series Transformer) is a Transformer that takes continuous time series as inputs.\n As mentioned in the paper, the input must be standardized by_var based on the entire training set.\n Args:\n c_in: the number of features (aka variables, dimensions, channels) in the time series dataset.\n c_out: the number of target classes.\n seq_len: number of time steps in the time series.\n max_seq_len: useful to control the temporal resolution in long time series to avoid memory issues.\n d_model: total dimension of the model (number of features created by the model)\n n_heads: parallel attention heads.\n d_k: size of the learned linear projection of queries and keys in the MHA. Usual values: 16-512. Default: None -> (d_model/n_heads) = 32.\n d_v: size of the learned linear projection of values in the MHA. Usual values: 16-512. Default: None -> (d_model/n_heads) = 32.\n d_ff: the dimension of the feedforward network model.\n res_dropout: amount of residual dropout applied in the encoder.\n activation: the activation function of intermediate layer, relu or gelu.\n num_layers: the number of sub-encoder-layers in the encoder.\n fc_dropout: dropout applied to the final fully connected layer.\n y_range: range of possible y values (used in regression tasks).\n kwargs: nn.Conv1d kwargs. If not {}, a nn.Conv1d with those kwargs will be applied to original time series.\n Input shape:\n bs (batch size) x nvars (aka features, variables, dimensions, channels) x seq_len (aka time steps)\n \"\"\"\n self.c_out, self.seq_len = c_out, seq_len\n\n # Input encoding\n q_len = seq_len\n self.new_q_len = False\n if max_seq_len is not None and seq_len > max_seq_len: # Control temporal resolution\n self.new_q_len = True\n q_len = max_seq_len\n tr_factor = math.ceil(seq_len / q_len)\n total_padding = (tr_factor * q_len - seq_len)\n padding = (total_padding // 2, total_padding - total_padding // 2)\n self.W_P = nn.Sequential(Pad1d(padding), Conv1d(c_in, d_model, kernel_size=tr_factor, stride=tr_factor))\n pv(f'temporal resolution modified: {seq_len} --> {q_len} time steps: kernel_size={tr_factor}, stride={tr_factor}, padding={padding}.\\n', verbose)\n elif kwargs:\n self.new_q_len = True\n t = torch.rand(1, 1, seq_len)\n q_len = nn.Conv1d(1, 1, **kwargs)(t).shape[-1]\n self.W_P = nn.Conv1d(c_in, d_model, **kwargs) # Eq 2\n pv(f'Conv1d with kwargs={kwargs} applied to input to create input encodings\\n', verbose)\n else:\n self.W_P = nn.Linear(c_in, d_model) # Eq 1: projection of feature vectors onto a d-dim vector space\n\n # Positional encoding\n W_pos = torch.normal(0, .1, (q_len, d_model), device=default_device())\n self.W_pos = nn.Parameter(W_pos, requires_grad=True)\n\n # Residual dropout\n self.res_dropout = nn.Dropout(res_dropout)\n\n # Encoder\n encoder_layer = TSTEncoderLayer(d_model, n_heads, d_k=d_k, d_v=d_v, d_ff=d_ff, res_dropout=res_dropout, activation=activation)\n self.encoder = TSTEncoder(encoder_layer, n_layers)\n self.flatten = Flatten()\n\n # Head\n self.head_nf = q_len * d_model\n self.head = self.create_head(self.head_nf, c_out, fc_dropout=fc_dropout, y_range=y_range)\n\n def create_head(self, nf, c_out, fc_dropout=0., y_range=None, **kwargs):\n layers = [nn.Dropout(fc_dropout)] if fc_dropout else []\n layers += [nn.Linear(nf, c_out)]\n if y_range: layers += [SigmoidRange(*y_range)]\n return nn.Sequential(*layers)\n\n\n def forward(self, x:Tensor, mask:Optional[Tensor]=None) -> Tensor: # x: [bs x nvars x q_len]\n\n # Input encoding\n if self.new_q_len: u = self.W_P(x).transpose(2,1) # Eq 2 # u: [bs x d_model x q_len] transposed to [bs x q_len x d_model]\n else: u = self.W_P(x.transpose(2,1)) # Eq 1 # u: [bs x q_len x d_model] transposed to [bs x q_len x d_model]\n\n # Positional encoding\n u = self.res_dropout(u + self.W_pos)\n\n # Encoder\n z = self.encoder(u) # z: [bs x q_len x d_model]\n if self.flatten is not None: z = self.flatten(z) # z: [bs x q_len * d_model]\n else: z = z.transpose(2,1).contiguous() # z: [bs x d_model x q_len]\n\n # Classification/ Regression head\n return self.head(z) # output: [bs x c_out]\n\n# Cell\nclass Sigmoid(nn.Module):\n '''\n sigmoid layer\n '''\n def __init__(self, low, high):\n super().__init__()\n self.high, self.low = high, low\n\n def forward(self, x):\n return torch.sigmoid(x)*(self.high-self.low)+self.low\n\n# Cell\nclass InceptionTimeSgmOld(nn.Module):\n '''\n add a sigmoid layer to InceptionTime to get the ouput in a certain range\n '''\n\n def __init__(self, n_in, n_out):\n super().__init__()\n nn.Sequential()\n self.inc = InceptionTime(n_in, n_out)\n self.low, self.high = -1., 1.\n\n def forward(self, x):\n return torch.sigmoid(self.inc(x)) * (self.high - self.low) + self.low\n\n\n# Cell\nclass InceptionTimeSgm(nn.Module):\n '''\n add a sigmoid layer to InceptionTime to get the ouput in a certain range\n '''\n\n def __init__(self, n_in, n_out, range=(-1,1)):\n super().__init__()\n self.mod = nn.Sequential(InceptionTime(n_in, n_out), SigmoidRange(*range))\n\n def forward(self, x):\n x = x.float()\n return self.mod(x)\n\n\n# Cell\nclass TransformerSgm(nn.Module):\n '''\n add a sigmoid layer to Transformer to get the ouput in a certain range\n '''\n\n def __init__(self, n_in, n_out, seq_len=10, range=(-1,1), **kwargs):\n super().__init__()\n self.mod = nn.Sequential(TST(n_in, n_out, seq_len, **kwargs), SigmoidRange(*range))\n\n def forward(self, x):\n x = x.float()\n return self.mod(x)\n\n\n# Cell\nclass TransformerSgmD(nn.Module):\n '''\n add a sigmoid layer to Transformer to get the ouput in a certain range\n discrete input channels\n '''\n\n def __init__(self, n_in, n_out, seq_len=10, range=(-1,1), **kwargs):\n super().__init__()\n self.mod = nn.Sequential(TST(n_in, n_out, seq_len, **kwargs), SigmoidRange(*range))\n\n def forward(self, xc, xd):\n xc, xd = TensorBase(xc), TensorBase(xd)\n x = torch.cat([xc.float(), xd.float()], dim=-2)\n x = x.float()\n return self.mod(x)\n\n# Cell\nclass InceptionTimeD(nn.Module):\n '''\n add a sigmoid layer to InceptionTime to get the ouput in a certain range\n '''\n\n def __init__(self, n_in, n_out):\n super().__init__()\n self.mod = nn.Sequential(InceptionTime(n_in, n_out), Sigmoid(-1., 1.))\n\n def forward(self, xc, xd):\n #cast to TensorBase for pytorch 1.7 compatibility\n xc, xd = TensorBase(xc), TensorBase(xd)\n x = torch.cat([xc.float(), xd.float()], dim=-2)\n x = x.float()\n# print(f'InceptionTimeSgm dtype {x.dtype}')\n return self.mod(x)\n\n# Cell\nclass InceptionTime_NH(nn.Module):\n '''inceptiontime, no final layer'''\n def __init__(self,c_in,c_out,bottleneck=32,ks=40,nb_filters=32,residual=True,depth=6):\n super().__init__()\n self.block = InceptionBlock(c_in,bottleneck=bottleneck,ks=ks,nb_filters=nb_filters,\n residual=residual,depth=depth)\n self.gap = nn.AdaptiveAvgPool1d(1)\n# self.fc = nn.Linear(nb_filters * 4, c_out)\n\n def forward(self, x):\n x = self.block(x)\n# print(x.shape)\n x = self.gap(x).squeeze(-1)\n# x = self.fc(x)\n return x\n\n# Cell\ndef _map_xs(xs, xs_mask):\n '''\n xs: i-tuple of tensors\n xs_mask: length j>=i mask\n xs_id: lenght j>=i string list of x identifiers\n '''\n assert np.array(xs_mask).sum()==len(xs)\n res = np.array([None]*len(xs_mask))\n res[np.where(xs_mask)[0]]=xs\n return res\n\n# Cell\nclass InceptionTimeD_Mixed(nn.Module):\n '''\n mixed model for timeseries and tabular data\n ts_mod: InceptionTime model without final fully connected lay\n tab_mod: MLP or TabNet, currently both cont and cat is required\n outputs are concatenated, then put through a fully connected layer, then sigmoid range\n '''\n\n def __init__(self, n_c, n_d, n_out, n_cont, emb_szs=None):\n super().__init__()\n self.n_c, self.n_d, self.n_cont, self.emb_szs = n_c, n_d, n_out, emb_szs\n assert n_c>0, 'at least one continuous channel required'\n self.ts_mod = InceptionTime_NH(n_c+n_d, n_out) #128\n self.sgm = Sigmoid(-1,1)\n# self.mod = nn.Sequential(InceptionTime(n_in, n_out), Sigmoid(-1., 1.))\n# self.tab_mod = nn.Sequential(nn.Linear(2,100), nn.ReLU(), nn.Linear(100,64))\n self.tab_mod = TabNetModel(emb_szs=emb_szs, n_cont=n_cont, out_sz=64)\n self.fc = nn.Linear(192,n_out)\n\n# def forward(self, xc, xd, xt, xcat=None):\n def forward(self, *xs):\n\n\n xs_mask = [self.n_c>0, self.n_d>0, self.n_cont>0, len(self.emb_szs)>0]\n# x_type_idxs = [i for i in range(4) if has_x[i]]\n xc,xd,xt,xcat = map_xs(xs, xs_mask)\n\n x_ts=xc.float()\n if xd is not None: x_ts = torch.cat([x_ts, xd.float()], dim=-2)\n\n# x_ts=torch.cat([xs[0].float(), xd.float()], dim=-2) if self.n_d>0 else x_ts\n\n\n# x = t\n# x = x.float()\n# print(f'InceptionTimeSgm dtype {x.dtype}')\n# print(self.ts_mod(x).shape, self.tab_mod(xt.float().squeeze(-2)).shape )\n xcat=xcat.long() if xcat is not None else None\n xt=xt.float() if xt is not None else None\n x_all = torch.cat([self.ts_mod(x_ts), self.tab_mod(xcat, xt)], dim=-1)\n return self.sgm(self.fc(x_all))\n\n# Cell\nclass InceptionTime_Mixed(nn.Module):\n '''\n mixed model for timeseries and tabular data\n ts_mod: InceptionTime model without final fully connected lay\n tab_mod: MLP or TabNet, currently both cont and cat is required\n outputs are concatenated, then put through a fully connected layer, no sigmoid for classification\n '''\n\n def __init__(self, n_c, n_d, n_out, n_cont, emb_szs=None):\n super().__init__()\n self.n_c, self.n_d, self.n_cont, self.emb_szs = n_c, n_d, n_out, emb_szs\n assert n_c>0, 'at least one continuous channel required'\n self.ts_mod = InceptionTime_NH(n_c+n_d, n_out) #128\n# self.mod = nn.Sequential(InceptionTime(n_in, n_out), Sigmoid(-1., 1.))\n# self.tab_mod = nn.Sequential(nn.Linear(2,100), nn.ReLU(), nn.Linear(100,64))\n self.tab_mod = TabNetModel(emb_szs=emb_szs, n_cont=n_cont, out_sz=64)\n self.fc = nn.Linear(192,n_out)\n\n# def forward(self, xc, xd, xt, xcat=None):\n def forward(self, *xs):\n\n\n xs_mask = [self.n_c>0, self.n_d>0, self.n_cont>0, len(self.emb_szs)>0]\n# x_type_idxs = [i for i in range(4) if has_x[i]]\n xc,xd,xt,xcat = map_xs(xs, xs_mask)\n\n x_ts=xc.float()\n if xd is not None: x_ts = torch.cat([x_ts, xd.float()], dim=-2)\n\n# x_ts=torch.cat([xs[0].float(), xd.float()], dim=-2) if self.n_d>0 else x_ts\n\n\n# x = t\n# x = x.float()\n# print(f'InceptionTimeSgm dtype {x.dtype}')\n# print(self.ts_mod(x).shape, self.tab_mod(xt.float().squeeze(-2)).shape )\n xcat=xcat.long() if xcat is not None else None\n xt=xt.float() if xt is not None else None\n x_all = torch.cat([self.ts_mod(x_ts), self.tab_mod(xcat, xt)], dim=-1)\n return self.fc(x_all)\n\n# Cell\nclass TabNetTT(nn.Module):\n '''\n convenience wrapper for pure TabNetModel models\n '''\n def __init__(self, emb_szs, n_cont, out_sz, **kwargs):\n super().__init__()\n self.tab = TabNetModel(emb_szs, n_cont, out_sz, **kwargs)\n\n def forward(self, xt, xcat):\n xcat=xcat.long() if xcat is not None else None\n xt=xt.float() if xt is not None else None\n return self.tab(xcat, xt)\n\n# Cell\nclass InceptionTimeVar(nn.Module):\n '''\n output mean and variance\n regression model, sigmoid for the mean output optional\n '''\n\n def __init__(self, n_in, n_out, meanrange=None):\n super().__init__()\n models = [InceptionTime(n_in, n_out+1)]\n if meanrange:\n self.sigmoid = Sigmoid(*meanrange)\n self.mod = nn.Sequential(*models)\n\n def forward(self, x):\n x = x.float()\n output = self.mod(x)\n ## enforce positivity of sigma^2\n ##output_sig_pos = tf.log(1 + tf.exp(output_sig)) + 1e-06\n# output[:,-1] = (output[:,-1].exp()+1).log_() + 1e-06\n output[:,-1] = F.softplus(output[:,-1].clone())\n\n if getattr(self, 'sigmoid', None): output[:,:-1] = self.sigmoid(output[:,:-1])\n return output\n\n\n# Cell\ndef nll_regression(preds, y_true, c=5):\n '''\n negative log likelihood loss for regression, both mu and sigma are predicted\n\n Simple and Scalable Predictive UncertaintyEstimation using Deep Ensembles\n Balaji Lakshminarayanan, Alexander Pritzel, Charles Blundell, DeepMind\n\n '''\n\n s1 = 0.5*preds[:,1].log()\n s2 = 0.5*(yb.squeeze()-preds[:,0]).pow(2).div(preds[:,1])\n loss = (s1+s2).mean() + c\n return loss\n\n# Cell\ndef nll_leaky_loss(preds, y_true, c=5, alpha=0.5):\n '''\n leaky_loss with variance\n\n Simple and Scalable Predictive UncertaintyEstimation using Deep Ensembles\n Balaji Lakshminarayanan, Alexander Pritzel, Charles Blundell, DeepMind\n\n '''\n\n s1 = 0.5*preds[:,1].log()\n l1 = -F.leaky_relu(preds[:,0], alpha)*y_true.float().squeeze()\n s2 = 0.5*(l1.div(preds[:,1]+1)) ## +1 to prevent optimizing for variance, maybe just an artifical problem\n loss = (s1+s2).mean() + c\n return loss\n\n# Cell\ndef qd_loss(preds, y_true, alpha=0.4, l=0.01, s=0.01, add=False, slope=1.):\n '''\n qd loss implementation adapted for \"leaky loss problems\"\n preds: predictions for both lower and upper bounds\n alpha: confidence intervall parameter, different from alpha in leaky_loss\n s: smoothing factor for sigmoid\n l: agrangian controlling width vs coverage (default in the paper impl. is 0.01 which seems lowI)\n '''\n ll = lambda x: F.leaky_relu(x, negative_slope=slope)\n\n y_lower = preds[:,0].clone()\n y_upper = preds[:,1].clone() if not add else y_lower+preds[:,1]\n\n# if not add:\n# y_lower, y_upper = preds[:, 0].clone(), preds[:, 1].clone()\n# else:\n# y_lower, y_upper = preds[:, 0].clone(), preds[:,0].clone()+preds[:, 1].clone()\n# # hard counts, how many of the predictions have the right sign?\n khu = (torch.sign(y_upper*y_true) > 0).int()\n khl = (torch.sign(y_lower*y_true) > 0).int()\n\n# return preds.mean()\n # soft counts, sign step function replaced by a smoother sigmoid\n\n ksu = torch.sigmoid((ll(y_upper)*y_true)*s)\n ksl = torch.sigmoid((y_true*ll(y_lower))*s)\n kh,ks = khu*khl, ksu*ksl\n# print(kh)\n# print(kh.sum(), ks.sum())\n\n #mpiw: mean predicted interval width\n f = 1/(kh.sum()+1e-6)\n# print((y_upper-y_lower))\n mpiw = ((y_upper-y_lower)*kh).sum()*f\n\n #picp: predicted interval coverage probability\n picp_s = ks.mean()\n\n print(f'mpiw {mpiw}, pcip_soft: {picp_s}')\n s2 = l*preds.shape[0]/(alpha*(1-alpha))\n s3 = torch.max(torch.zeros(1, device=preds.device), picp_s).pow(2)\n loss_s = mpiw + l*preds.shape[0]/(alpha*(1-alpha)) * torch.max(torch.zeros(1, device=preds.device),\n picp_s).pow(2)\n return loss_s\n\n# Cell\nclass InceptionTimeBounds(nn.Module):\n '''\n use InceptionTimeVar implementation for bounds\n output[:, -1] is positive and y_upper corresponds to output[:,0]+output[:,1] --> loss\n '''\n\n def __init__(self, n_in, n_out, meanrange=None):\n super().__init__()\n models = [InceptionTime(n_in, n_out+1)]\n if meanrange:\n self.sigmoid = Sigmoid(*meanrange)\n self.mod = nn.Sequential(*models)\n\n def forward(self, x):\n x = x.float()\n output = self.mod(x)\n ## enforce positivity of sigma^2\n ##output_sig_pos = tf.log(1 + tf.exp(output_sig)) + 1e-06\n# output[:,-1] = (output[:,-1].exp()+1).log_() + 1e-06\n output[:,-1] = F.softplus(output[:,-1].clone()) ## autograd problems when not using clone, why???\n\n if getattr(self, 'sigmoid', None): output[:,:-1] = self.sigmoid(output[:,:-1])\n return output" ]
[ [ "torch.nn.functional.softmax", "torch.rand", "torch.nn.ModuleList", "torch.nn.AdaptiveAvgPool1d", "torch.cat", "torch.nn.Dropout", "torch.nn.modules.transformer.TransformerEncoderLayer", "torch.nn.modules.transformer.TransformerEncoder", "torch.nn.BatchNorm1d", "torch.sign", "torch.nn.LayerNorm", "torch.nn.functional.leaky_relu", "torch.sigmoid", "torch.nn.MaxPool1d", "torch.nn.Conv1d", "torch.nn.Linear", "torch.nn.Parameter", "torch.nn.GELU", "torch.nn.Sequential", "torch.zeros", "torch.nn.ReLU", "torch.matmul" ] ]
mehak-sachdeva/mgwr
[ "eae8ac3d61ecbbba60b180e9ed8bab074bfb3522" ]
[ "mgwr/gwr.py" ]
[ "# Main GWR classes\n\n__author__ = \"Taylor Oshan [email protected]\"\n\nimport copy\nimport numpy as np\nimport numpy.linalg as la\nfrom scipy.stats import t\nfrom scipy.special import factorial\nfrom itertools import combinations as combo\nfrom spglm.family import Gaussian, Binomial, Poisson\nfrom spglm.glm import GLM, GLMResults\nfrom spglm.iwls import iwls, _compute_betas_gwr\nfrom spglm.utils import cache_readonly\nfrom .diagnostics import get_AIC, get_AICc, get_BIC, corr\nfrom .kernels import *\nfrom .summary import *\nimport multiprocessing as mp\n\n\nclass GWR(GLM):\n \"\"\"\n Geographically weighted regression. Can currently estimate Gaussian,\n Poisson, and logistic models(built on a GLM framework). GWR object prepares\n model input. Fit method performs estimation and returns a GWRResults object.\n\n Parameters\n ----------\n coords : array-like\n n*2, collection of n sets of (x,y) coordinates of\n observatons; also used as calibration locations is\n 'points' is set to None\n\n y : array\n n*1, dependent variable\n\n X : array\n n*k, independent variable, exlcuding the constant\n\n bw : scalar\n bandwidth value consisting of either a distance or N\n nearest neighbors; user specified or obtained using\n Sel_BW\n\n family : family object\n underlying probability model; provides\n distribution-specific calculations\n\n offset : array\n n*1, the offset variable at the ith location. For Poisson model\n this term is often the size of the population at risk or\n the expected size of the outcome in spatial epidemiology\n Default is None where Ni becomes 1.0 for all locations;\n only for Poisson models\n\n sigma2_v1 : boolean\n specify form of corrected denominator of sigma squared to use for\n model diagnostics; Acceptable options are:\n\n 'True': n-tr(S) (defualt)\n 'False': n-2(tr(S)+tr(S'S))\n\n kernel : string\n type of kernel function used to weight observations;\n available options:\n 'gaussian'\n 'bisquare'\n 'exponential'\n\n fixed : boolean\n True for distance based kernel function and False for\n adaptive (nearest neighbor) kernel function (default)\n\n constant : boolean\n True to include intercept (default) in model and False to exclude\n intercept.\n\n spherical : boolean\n True for shperical coordinates (long-lat),\n False for projected coordinates (defalut).\n hat_matrix : boolean\n True to store full n by n hat matrix,\n False to not store full hat matrix to minimize memory footprint (defalut).\n\n Attributes\n ----------\n coords : array-like\n n*2, collection of n sets of (x,y) coordinates used for\n calibration locations\n\n y : array\n n*1, dependent variable\n\n X : array\n n*k, independent variable, exlcuding the constant\n\n bw : scalar\n bandwidth value consisting of either a distance or N\n nearest neighbors; user specified or obtained using\n Sel_BW\n\n family : family object\n underlying probability model; provides\n distribution-specific calculations\n\n offset : array\n n*1, the offset variable at the ith location. For Poisson model\n this term is often the size of the population at risk or\n the expected size of the outcome in spatial epidemiology\n Default is None where Ni becomes 1.0 for all locations\n\n sigma2_v1 : boolean\n specify form of corrected denominator of sigma squared to use for\n model diagnostics; Acceptable options are:\n\n 'True': n-tr(S) (defualt)\n 'False': n-2(tr(S)+tr(S'S))\n\n kernel : string\n type of kernel function used to weight observations;\n available options:\n 'gaussian'\n 'bisquare'\n 'exponential'\n\n fixed : boolean\n True for distance based kernel function and False for\n adaptive (nearest neighbor) kernel function (default)\n\n constant : boolean\n True to include intercept (default) in model and False to exclude\n intercept\n\n spherical : boolean\n True for shperical coordinates (long-lat),\n False for projected coordinates (defalut).\n \n hat_matrix : boolean\n True to store full n by n hat matrix,\n False to not store full hat matrix to minimize memory footprint (defalut).\n\n n : integer\n number of observations\n\n k : integer\n number of independent variables\n\n mean_y : float\n mean of y\n\n std_y : float\n standard deviation of y\n\n fit_params : dict\n parameters passed into fit method to define estimation\n routine\n\n points : array-like\n n*2, collection of n sets of (x,y) coordinates used for\n calibration locations instead of all observations;\n defaults to None unles specified in predict method\n\n P : array\n n*k, independent variables used to make prediction;\n exlcuding the constant; default to None unless specified\n in predict method\n\n exog_scale : scalar\n estimated scale using sampled locations; defualt is None\n unless specified in predict method\n\n exog_resid : array-like\n estimated residuals using sampled locations; defualt is None\n unless specified in predict method\n\n Examples\n --------\n #basic model calibration\n\n >>> import libpysal as ps\n >>> from mgwr.gwr import GWR\n >>> data = ps.io.open(ps.examples.get_path('GData_utm.csv'))\n >>> coords = list(zip(data.by_col('X'), data.by_col('Y')))\n >>> y = np.array(data.by_col('PctBach')).reshape((-1,1))\n >>> rural = np.array(data.by_col('PctRural')).reshape((-1,1))\n >>> pov = np.array(data.by_col('PctPov')).reshape((-1,1))\n >>> african_amer = np.array(data.by_col('PctBlack')).reshape((-1,1))\n >>> X = np.hstack([rural, pov, african_amer])\n >>> model = GWR(coords, y, X, bw=90.000, fixed=False, kernel='bisquare')\n >>> results = model.fit()\n >>> print(results.params.shape)\n (159, 4)\n\n #predict at unsampled locations\n\n >>> index = np.arange(len(y))\n >>> test = index[-10:]\n >>> X_test = X[test]\n >>> coords_test = np.array(coords)[test]\n >>> model = GWR(coords, y, X, bw=94, fixed=False, kernel='bisquare')\n >>> results = model.predict(coords_test, X_test)\n >>> print(results.params.shape)\n (10, 4)\n\n \"\"\"\n\n def __init__(self, coords, y, X, bw, family=Gaussian(), offset=None,\n sigma2_v1=True, kernel='bisquare', fixed=False, constant=True,\n spherical=False, hat_matrix=False):\n \"\"\"\n Initialize class\n \"\"\"\n GLM.__init__(self, y, X, family, constant=constant)\n self.constant = constant\n self.sigma2_v1 = sigma2_v1\n self.coords = np.array(coords)\n self.bw = bw\n self.kernel = kernel\n self.fixed = fixed\n if offset is None:\n self.offset = np.ones((self.n, 1))\n else:\n self.offset = offset * 1.0\n self.fit_params = {}\n\n self.points = None\n self.exog_scale = None\n self.exog_resid = None\n self.P = None\n self.spherical = spherical\n self.hat_matrix = hat_matrix\n\n def _build_wi(self, i, bw):\n\n try:\n wi = Kernel(i, self.coords, bw, fixed=self.fixed,\n function=self.kernel, points=self.points,\n spherical=self.spherical).kernel\n except BaseException:\n raise # TypeError('Unsupported kernel function ', kernel)\n\n return wi\n\n def _local_fit(self, i):\n \"\"\"\n Local fitting at location i.\n \"\"\"\n wi = self._build_wi(i, self.bw).reshape(-1, 1) #local spatial weights\n\n if isinstance(self.family, Gaussian):\n betas, inv_xtx_xt = _compute_betas_gwr(self.y, self.X, wi)\n predy = np.dot(self.X[i], betas)[0]\n resid = self.y[i] - predy\n influ = np.dot(self.X[i], inv_xtx_xt[:, i])\n w = 1\n\n elif isinstance(self.family, (Poisson, Binomial)):\n rslt = iwls(self.y, self.X, self.family, self.offset, None,\n self.fit_params['ini_params'], self.fit_params['tol'],\n self.fit_params['max_iter'], wi=wi)\n inv_xtx_xt = rslt[5]\n w = rslt[3][i][0]\n influ = np.dot(self.X[i], inv_xtx_xt[:, i]) * w\n predy = rslt[1][i]\n resid = self.y[i] - predy\n betas = rslt[0]\n\n if self.fit_params['lite']:\n return influ, resid, predy, betas.reshape(-1)\n else:\n Si = np.dot(self.X[i], inv_xtx_xt).reshape(-1)\n tr_STS_i = np.sum(Si * Si * w * w)\n CCT = np.diag(np.dot(inv_xtx_xt, inv_xtx_xt.T)).reshape(-1)\n if not self.hat_matrix:\n Si = None\n return influ, resid, predy, betas.reshape(-1), w, Si, tr_STS_i, CCT\n\n def fit(self, ini_params=None, tol=1.0e-5, max_iter=20, solve='iwls',\n lite=False, pool=None):\n \"\"\"\n Method that fits a model with a particular estimation routine.\n\n Parameters\n ----------\n\n ini_betas : array, optional\n k*1, initial coefficient values, including constant.\n Default is None, which calculates initial values during\n estimation.\n tol: float, optional\n Tolerence for estimation convergence.\n Default is 1.0e-5.\n max_iter : integer, optional\n Maximum number of iterations if convergence not\n achieved. Default is 20.\n solve : string, optional\n Technique to solve MLE equations.\n Default is 'iwls', meaning iteratively (\n re)weighted least squares.\n lite : bool, optional\n Whether to estimate a lightweight GWR that\n computes the minimum diagnostics needed for\n bandwidth selection (could speed up\n bandwidth selection for GWR) or to estimate\n a full GWR. Default is False.\n pool : A multiprocessing Pool object to enable parallel fitting; default is None.\n\n Returns\n -------\n :\n If lite=False, return a GWRResult\n instance; otherwise, return a GWRResultLite\n instance.\n\n \"\"\"\n self.fit_params['ini_params'] = ini_params\n self.fit_params['tol'] = tol\n self.fit_params['max_iter'] = max_iter\n self.fit_params['solve'] = solve\n self.fit_params['lite'] = lite\n\n if solve.lower() == 'iwls':\n\n if self.points is None:\n m = self.y.shape[0]\n else:\n m = self.points.shape[0]\n\n if pool:\n rslt = pool.map(self._local_fit,\n range(m)) #parallel using mp.Pool\n else:\n rslt = map(self._local_fit, range(m)) #sequential\n\n rslt_list = list(zip(*rslt))\n influ = np.array(rslt_list[0]).reshape(-1, 1)\n resid = np.array(rslt_list[1]).reshape(-1, 1)\n params = np.array(rslt_list[3])\n\n if lite:\n return GWRResultsLite(self, resid, influ, params)\n else:\n predy = np.array(rslt_list[2]).reshape(-1, 1)\n w = np.array(rslt_list[-4]).reshape(-1, 1)\n if self.hat_matrix:\n S = np.array(rslt_list[-3])\n else:\n S = None\n tr_STS = np.sum(np.array(rslt_list[-2]))\n CCT = np.array(rslt_list[-1])\n return GWRResults(self, params, predy, S, CCT, influ, tr_STS,\n w)\n\n def predict(self, points, P, exog_scale=None, exog_resid=None,\n fit_params={}):\n \"\"\"\n Method that predicts values of the dependent variable at un-sampled\n locations\n\n Parameters\n ----------\n points : array-like\n n*2, collection of n sets of (x,y) coordinates used for\n calibration prediction locations\n P : array\n n*k, independent variables used to make prediction;\n exlcuding the constant\n exog_scale : scalar\n estimated scale using sampled locations; defualt is None\n which estimates a model using points from \"coords\"\n exog_resid : array-like\n estimated residuals using sampled locations; defualt is None\n which estimates a model using points from \"coords\"; if\n given it must be n*1 where n is the length of coords\n fit_params : dict\n key-value pairs of parameters that will be passed into fit\n method to define estimation routine; see fit method for more details\n\n \"\"\"\n if (exog_scale is None) & (exog_resid is None):\n train_gwr = self.fit(**fit_params)\n self.exog_scale = train_gwr.scale\n self.exog_resid = train_gwr.resid_response\n elif (exog_scale is not None) & (exog_resid is not None):\n self.exog_scale = exog_scale\n self.exog_resid = exog_resid\n else:\n raise InputError('exog_scale and exog_resid must both either be'\n 'None or specified')\n self.points = points\n if self.constant:\n P = np.hstack([np.ones((len(P), 1)), P])\n self.P = P\n else:\n self.P = P\n gwr = self.fit(**fit_params)\n\n return gwr\n\n @cache_readonly\n def df_model(self):\n return None\n\n @cache_readonly\n def df_resid(self):\n return None\n\n\nclass GWRResults(GLMResults):\n \"\"\"\n Basic class including common properties for all GWR regression models\n\n Parameters\n ----------\n model : GWR object\n pointer to GWR object with estimation parameters\n\n params : array\n n*k, estimated coefficients\n\n predy : array\n n*1, predicted y values\n\n S : array\n n*n, hat matrix\n\n CCT : array\n n*k, scaled variance-covariance matrix\n\n w : array\n n*1, final weight used for iteratively re-weighted least\n sqaures; default is None\n\n Attributes\n ----------\n model : GWR Object\n points to GWR object for which parameters have been\n estimated\n\n params : array\n n*k, parameter estimates\n\n predy : array\n n*1, predicted value of y\n\n y : array\n n*1, dependent variable\n\n X : array\n n*k, independent variable, including constant\n\n family : family object\n underlying probability model; provides\n distribution-specific calculations\n\n n : integer\n number of observations\n\n k : integer\n number of independent variables\n\n df_model : integer\n model degrees of freedom\n\n df_resid : integer\n residual degrees of freedom\n\n offset : array\n n*1, the offset variable at the ith location.\n For Poisson model this term is often the size of\n the population at risk or the expected size of\n the outcome in spatial epidemiology; Default is\n None where Ni becomes 1.0 for all locations\n\n scale : float\n sigma squared used for subsequent computations\n\n w : array\n n*1, final weights from iteratively re-weighted least\n sqaures routine\n\n resid_response : array\n n*1, residuals of the repsonse\n\n resid_ss : scalar\n residual sum of sqaures\n\n W : array\n n*n; spatial weights for each observation from each\n calibration point\n\n S : array\n n*n, hat matrix\n\n CCT : array\n n*k, scaled variance-covariance matrix\n\n ENP : scalar\n effective number of paramters, which depends on\n sigma2\n\n tr_S : float\n trace of S (hat) matrix\n\n tr_STS : float\n trace of STS matrix\n\n y_bar : array\n n*1, weighted mean value of y\n\n TSS : array\n n*1, geographically weighted total sum of squares\n\n RSS : array\n n*1, geographically weighted residual sum of squares\n\n R2 : float\n R-squared for the entire model (1- RSS/TSS)\n \n adj_R2 : float\n adjusted R-squared for the entire model\n \n aic : float\n Akaike information criterion\n\n aicc : float\n corrected Akaike information criterion to account\n to account for model complexity (smaller\n bandwidths)\n\n bic : float\n Bayesian information criterio\n\n localR2 : array\n n*1, local R square\n\n sigma2 : float\n sigma squared (residual variance) that has been\n corrected to account for the ENP\n\n std_res : array\n n*1, standardised residuals\n\n bse : array\n n*k, standard errors of parameters (betas)\n\n influ : array\n n*1, leading diagonal of S matrix\n\n CooksD : array\n n*1, Cook's D\n\n tvalues : array\n n*k, local t-statistics\n\n adj_alpha : array\n 3*1, corrected alpha values to account for multiple\n hypothesis testing for the 90%, 95%, and 99% confidence\n levels; tvalues with an absolute value larger than the\n corrected alpha are considered statistically\n significant.\n\n deviance : array\n n*1, local model deviance for each calibration point\n\n resid_deviance : array\n n*1, local sum of residual deviance for each\n calibration point\n\n llf : scalar\n log-likelihood of the full model; see\n pysal.contrib.glm.family for damily-sepcific\n log-likelihoods\n\n pDev : float\n local percent of deviation accounted for; analogous to\n r-squared for GLM's\n \n D2 : float\n percent deviance explained for GLM, equivaleng to R2 for\n Gaussian.\n \n adj_D2 : float\n adjusted percent deviance explained, equivaleng to adjusted\n R2 for Gaussian.\n\n mu : array\n n*, flat one dimensional array of predicted mean\n response value from estimator\n\n fit_params : dict\n parameters passed into fit method to define estimation\n routine\n\n predictions : array\n p*1, predicted values generated by calling the GWR\n predict method to predict dependent variable at\n unsampled points ()\n \"\"\"\n\n def __init__(self, model, params, predy, S, CCT, influ, tr_STS=None,\n w=None):\n GLMResults.__init__(self, model, params, predy, w)\n self.offset = model.offset\n if w is not None:\n self.w = w\n self.predy = predy\n self.S = S\n self.tr_STS = tr_STS\n self.influ = influ\n self.CCT = self.cov_params(CCT, model.exog_scale)\n self._cache = {}\n\n @cache_readonly\n def W(self):\n W = np.array(\n [self.model._build_wi(i, self.model.bw) for i in range(self.n)])\n return W\n\n @cache_readonly\n def resid_ss(self):\n if self.model.points is not None:\n raise NotImplementedError('Not available for GWR prediction')\n else:\n u = self.resid_response.flatten()\n return np.dot(u, u.T)\n\n @cache_readonly\n def scale(self, scale=None):\n if isinstance(self.family, Gaussian):\n scale = self.sigma2\n else:\n scale = 1.0\n return scale\n\n def cov_params(self, cov, exog_scale=None):\n \"\"\"\n Returns scaled covariance parameters\n\n Parameters\n ----------\n cov : array\n estimated covariance parameters\n\n Returns\n -------\n Scaled covariance parameters\n\n \"\"\"\n if exog_scale is not None:\n return cov * exog_scale\n else:\n return cov * self.scale\n\n @cache_readonly\n def tr_S(self):\n \"\"\"\n trace of S (hat) matrix\n \"\"\"\n return np.sum(self.influ)\n\n @cache_readonly\n def ENP(self):\n \"\"\"\n effective number of parameters\n\n Defualts to tr(s) as defined in yu et. al (2018) Inference in\n Multiscale GWR\n\n but can alternatively be based on 2tr(s) - tr(STS)\n\n and the form depends on the specification of sigma2\n \"\"\"\n if self.model.sigma2_v1:\n return self.tr_S\n else:\n return 2 * self.tr_S - self.tr_STS\n\n @cache_readonly\n def y_bar(self):\n \"\"\"\n weighted mean of y\n \"\"\"\n if self.model.points is not None:\n n = len(self.model.points)\n else:\n n = self.n\n off = self.offset.reshape((-1, 1))\n arr_ybar = np.zeros(shape=(self.n, 1))\n for i in range(n):\n w_i = np.reshape(self.model._build_wi(i, self.model.bw), (-1, 1))\n sum_yw = np.sum(self.y.reshape((-1, 1)) * w_i)\n arr_ybar[i] = 1.0 * sum_yw / np.sum(w_i * off)\n return arr_ybar\n\n @cache_readonly\n def TSS(self):\n \"\"\"\n geographically weighted total sum of squares\n\n Methods: p215, (9.9)\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n\n \"\"\"\n if self.model.points is not None:\n n = len(self.model.points)\n else:\n n = self.n\n TSS = np.zeros(shape=(n, 1))\n for i in range(n):\n TSS[i] = np.sum(\n np.reshape(self.model._build_wi(i, self.model.bw),\n (-1, 1)) * (self.y.reshape(\n (-1, 1)) - self.y_bar[i])**2)\n return TSS\n\n @cache_readonly\n def RSS(self):\n \"\"\"\n geographically weighted residual sum of squares\n\n Methods: p215, (9.10)\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n \"\"\"\n if self.model.points is not None:\n n = len(self.model.points)\n resid = self.model.exog_resid.reshape((-1, 1))\n else:\n n = self.n\n resid = self.resid_response.reshape((-1, 1))\n RSS = np.zeros(shape=(n, 1))\n for i in range(n):\n RSS[i] = np.sum(\n np.reshape(self.model._build_wi(i, self.model.bw),\n (-1, 1)) * resid**2)\n return RSS\n\n @cache_readonly\n def localR2(self):\n \"\"\"\n local R square\n\n Methods: p215, (9.8)\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n \"\"\"\n if isinstance(self.family, Gaussian):\n return (self.TSS - self.RSS) / self.TSS\n else:\n raise NotImplementedError('Only applicable to Gaussian')\n\n @cache_readonly\n def sigma2(self):\n \"\"\"\n residual variance\n\n if sigma2_v1 is True: only use n-tr(S) in denominator\n\n Methods: p214, (9.6),\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n\n and as defined in Yu et. al. (2018) Inference in Multiscale GWR\n\n if sigma2_v1 is False (v1v2): use n-2(tr(S)+tr(S'S)) in denominator\n\n Methods: p55 (2.16)-(2.18)\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n\n \"\"\"\n if self.model.sigma2_v1:\n return (self.resid_ss / (self.n - self.tr_S))\n else:\n # could be changed to SWSTW - nothing to test against\n return self.resid_ss / (self.n - 2.0 * self.tr_S + self.tr_STS)\n\n @cache_readonly\n def std_res(self):\n \"\"\"\n standardized residuals\n\n Methods: p215, (9.7)\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n \"\"\"\n return self.resid_response.reshape(\n (-1, 1)) / (np.sqrt(self.scale * (1.0 - self.influ)))\n\n @cache_readonly\n def bse(self):\n \"\"\"\n standard errors of Betas\n\n Methods: p215, (2.15) and (2.21)\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n \"\"\"\n return np.sqrt(self.CCT)\n\n @cache_readonly\n def cooksD(self):\n \"\"\"\n Influence: leading diagonal of S Matrix\n\n Methods: p216, (9.11),\n Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).\n Geographically weighted regression: the analysis of spatially varying\n relationships.\n Note: in (9.11), p should be tr(S), that is, the effective number of parameters\n \"\"\"\n return self.std_res**2 * self.influ / (self.tr_S * (1.0 - self.influ))\n\n @cache_readonly\n def deviance(self):\n off = self.offset.reshape((-1, 1)).T\n y = self.y\n ybar = self.y_bar\n if isinstance(self.family, Gaussian):\n raise NotImplementedError(\n 'deviance not currently used for Gaussian')\n elif isinstance(self.family, Poisson):\n dev = np.sum(\n 2.0 * self.W * (y * np.log(y / (ybar * off)) -\n (y - ybar * off)), axis=1)\n elif isinstance(self.family, Binomial):\n dev = self.family.deviance(self.y, self.y_bar, self.W, axis=1)\n return dev.reshape((-1, 1))\n\n @cache_readonly\n def resid_deviance(self):\n if isinstance(self.family, Gaussian):\n raise NotImplementedError(\n 'deviance not currently used for Gaussian')\n else:\n off = self.offset.reshape((-1, 1)).T\n y = self.y\n ybar = self.y_bar\n global_dev_res = ((self.family.resid_dev(self.y, self.mu))**2)\n dev_res = np.repeat(global_dev_res.flatten(), self.n)\n dev_res = dev_res.reshape((self.n, self.n))\n dev_res = np.sum(dev_res * self.W.T, axis=0)\n return dev_res.reshape((-1, 1))\n\n @cache_readonly\n def pDev(self):\n \"\"\"\n Local percentage of deviance accounted for. Described in the GWR4\n manual. Equivalent to 1 - (deviance/null deviance)\n \"\"\"\n if isinstance(self.family, Gaussian):\n raise NotImplementedError('Not implemented for Gaussian')\n else:\n return 1.0 - (self.resid_deviance / self.deviance)\n\n @cache_readonly\n def adj_alpha(self):\n \"\"\"\n Corrected alpha (critical) values to account for multiple testing during hypothesis\n testing. Includes corrected value for 90% (.1), 95% (.05), and 99%\n (.01) confidence levels. Correction comes from:\n\n da Silva, A. R., & Fotheringham, A. S. (2015). The Multiple Testing Issue in\n Geographically Weighted Regression. Geographical Analysis.\n\n \"\"\"\n alpha = np.array([.1, .05, .001])\n pe = self.ENP\n p = self.k\n return (alpha * p) / pe\n\n def critical_tval(self, alpha=None):\n \"\"\"\n Utility function to derive the critial t-value based on given alpha\n that are needed for hypothesis testing\n\n Parameters\n ----------\n alpha : scalar\n critical value to determine which tvalues are\n associated with statistically significant parameter\n estimates. Default to None in which case the adjusted\n alpha value at the 95 percent CI is automatically\n used.\n\n Returns\n -------\n critical : scalar\n critical t-val based on alpha\n \"\"\"\n n = self.n\n if alpha is not None:\n alpha = np.abs(alpha) / 2.0\n critical = t.ppf(1 - alpha, n - 1)\n else:\n alpha = np.abs(self.adj_alpha[1]) / 2.0\n critical = t.ppf(1 - alpha, n - 1)\n return critical\n\n def filter_tvals(self, critical_t=None, alpha=None):\n \"\"\"\n Utility function to set tvalues with an absolute value smaller than the\n absolute value of the alpha (critical) value to 0. If critical_t\n is supplied than it is used directly to filter. If alpha is provided\n than the critical t value will be derived and used to filter. If neither\n are critical_t nor alpha are provided, an adjusted alpha at the 95\n percent CI will automatically be used to define the critical t-value and\n used to filter. If both critical_t and alpha are supplied then the alpha\n value will be ignored.\n\n Parameters\n ----------\n critical : scalar\n critical t-value to determine whether parameters are\n statistically significant\n\n alpha : scalar\n alpha value to determine which tvalues are\n associated with statistically significant parameter\n estimates\n\n Returns\n -------\n filtered : array\n n*k; new set of n tvalues for each of k variables\n where absolute tvalues less than the absolute value of\n alpha have been set to 0.\n \"\"\"\n n = self.n\n if critical_t is not None:\n critical = critical_t\n else:\n critical = self.critical_tval(alpha=alpha)\n\n subset = (self.tvalues < critical) & (self.tvalues > -1.0 * critical)\n tvalues = self.tvalues.copy()\n tvalues[subset] = 0\n return tvalues\n\n @cache_readonly\n def df_model(self):\n return self.n - self.tr_S\n\n @cache_readonly\n def df_resid(self):\n return self.n - 2.0 * self.tr_S + self.tr_STS\n\n @cache_readonly\n def normalized_cov_params(self):\n return None\n\n @cache_readonly\n def resid_pearson(self):\n return None\n\n @cache_readonly\n def resid_working(self):\n return None\n\n @cache_readonly\n def resid_anscombe(self):\n return None\n\n @cache_readonly\n def pearson_chi2(self):\n return None\n\n @cache_readonly\n def llnull(self):\n return None\n\n @cache_readonly\n def null_deviance(self):\n return self.family.deviance(self.y, self.null)\n\n @cache_readonly\n def global_deviance(self):\n deviance = np.sum(self.family.resid_dev(self.y, self.mu)**2)\n return deviance\n\n @cache_readonly\n def D2(self):\n \"\"\"\n Percentage of deviance explanied. Equivalent to 1 - (deviance/null deviance)\n \"\"\"\n D2 = 1.0 - (self.global_deviance / self.null_deviance)\n return D2\n\n @cache_readonly\n def R2(self):\n \"\"\"\n Global r-squared value for a Gaussian model.\n \"\"\"\n if isinstance(self.family, Gaussian):\n return self.D2\n else:\n raise NotImplementedError('R2 only for Gaussian')\n\n @cache_readonly\n def adj_D2(self):\n \"\"\"\n Adjusted percentage of deviance explanied.\n \"\"\"\n adj_D2 = 1 - (1 - self.D2) * (self.n - 1) / (self.n - self.ENP - 1)\n return adj_D2\n\n @cache_readonly\n def adj_R2(self):\n \"\"\"\n Adjusted global r-squared for a Gaussian model.\n \"\"\"\n if isinstance(self.family, Gaussian):\n return self.adj_D2\n else:\n raise NotImplementedError('adjusted R2 only for Gaussian')\n\n @cache_readonly\n def aic(self):\n return get_AIC(self)\n\n @cache_readonly\n def aicc(self):\n return get_AICc(self)\n\n @cache_readonly\n def bic(self):\n return get_BIC(self)\n\n @cache_readonly\n def pseudoR2(self):\n return None\n\n @cache_readonly\n def adj_pseudoR2(self):\n return None\n\n @cache_readonly\n def pvalues(self):\n return None\n\n @cache_readonly\n def conf_int(self):\n return None\n\n @cache_readonly\n def use_t(self):\n return None\n\n def local_collinearity(self):\n \"\"\"\n Computes several indicators of multicollinearity within a geographically\n weighted design matrix, including:\n\n local correlation coefficients (n, ((p**2) + p) / 2)\n local variance inflation factors (VIF) (n, p-1)\n local condition number (n, 1)\n local variance-decomposition proportions (n, p)\n\n Returns four arrays with the order and dimensions listed above where n\n is the number of locations used as calibrations points and p is the\n nubmer of explanatory variables. Local correlation coefficient and local\n VIF are not calculated for constant term.\n\n \"\"\"\n x = self.X\n w = self.W\n nvar = x.shape[1]\n nrow = len(w)\n if self.model.constant:\n ncor = (((nvar - 1)**2 + (nvar - 1)) / 2) - (nvar - 1)\n jk = list(combo(range(1, nvar), 2))\n else:\n ncor = (((nvar)**2 + (nvar)) / 2) - nvar\n jk = list(combo(range(nvar), 2))\n corr_mat = np.ndarray((nrow, int(ncor)))\n if self.model.constant:\n vifs_mat = np.ndarray((nrow, nvar - 1))\n else:\n vifs_mat = np.ndarray((nrow, nvar))\n vdp_idx = np.ndarray((nrow, nvar))\n vdp_pi = np.ndarray((nrow, nvar, nvar))\n\n for i in range(nrow):\n wi = self.model._build_wi(i, self.model.bw)\n sw = np.sum(wi)\n wi = wi / sw\n tag = 0\n\n for j, k in jk:\n corr_mat[i, tag] = corr(np.cov(x[:, j], x[:, k],\n aweights=wi))[0][1]\n tag = tag + 1\n\n if self.model.constant:\n corr_mati = corr(np.cov(x[:, 1:].T, aweights=wi))\n vifs_mat[i, ] = np.diag(\n np.linalg.solve(corr_mati, np.identity((nvar - 1))))\n\n else:\n corr_mati = corr(np.cov(x.T, aweights=wi))\n vifs_mat[i, ] = np.diag(\n np.linalg.solve(corr_mati, np.identity((nvar))))\n\n xw = x * wi.reshape((nrow, 1))\n sxw = np.sqrt(np.sum(xw**2, axis=0))\n sxw = np.transpose(xw.T / sxw.reshape((nvar, 1)))\n svdx = np.linalg.svd(sxw)\n vdp_idx[i, ] = svdx[1][0] / svdx[1]\n phi = np.dot(svdx[2].T, np.diag(1 / svdx[1]))\n phi = np.transpose(phi**2)\n pi_ij = phi / np.sum(phi, axis=0)\n vdp_pi[i, :, :] = pi_ij\n\n local_CN = vdp_idx[:, nvar - 1].reshape((-1, 1))\n VDP = vdp_pi[:, nvar - 1, :]\n\n return corr_mat, vifs_mat, local_CN, VDP\n\n def spatial_variability(self, selector, n_iters=1000, seed=None):\n \"\"\"\n Method to compute a Monte Carlo test of spatial variability for each\n estimated coefficient surface.\n\n WARNING: This test is very computationally demanding!\n\n Parameters\n ----------\n selector : sel_bw object\n should be the sel_bw object used to select a bandwidth\n for the gwr model that produced the surfaces that are\n being tested for spatial variation\n\n n_iters : int\n the number of Monte Carlo iterations to include for\n the tests of spatial variability.\n\n seed : int\n optional parameter to select a custom seed to ensure\n stochastic results are replicable. Default is none\n which automatically sets the seed to 5536\n\n Returns\n -------\n\n p values : list\n a list of psuedo p-values that correspond to the model\n parameter surfaces. Allows us to assess the\n probability of obtaining the observed spatial\n variation of a given surface by random chance.\n\n\n \"\"\"\n temp_sel = copy.deepcopy(selector)\n temp_gwr = copy.deepcopy(self.model)\n\n if seed is None:\n np.random.seed(5536)\n else:\n np.random.seed(seed)\n\n fit_params = temp_gwr.fit_params\n search_params = temp_sel.search_params\n kernel = temp_gwr.kernel\n fixed = temp_gwr.fixed\n\n if self.model.constant:\n X = self.X[:, 1:]\n else:\n X = self.X\n\n init_sd = np.std(self.params, axis=0)\n SDs = []\n\n for x in range(n_iters):\n temp_coords = np.random.permutation(self.model.coords)\n temp_sel.coords = temp_coords\n temp_bw = temp_sel.search(**search_params)\n temp_gwr.bw = temp_bw\n temp_gwr.coords = temp_coords\n temp_params = temp_gwr.fit(**fit_params).params\n temp_sd = np.std(temp_params, axis=0)\n SDs.append(temp_sd)\n\n p_vals = (np.sum(np.array(SDs) > init_sd, axis=0) / float(n_iters))\n return p_vals\n\n @cache_readonly\n def predictions(self):\n P = self.model.P\n if P is None:\n raise TypeError('predictions only avaialble if predict'\n 'method is previously called on GWR model')\n else:\n predictions = np.sum(P * self.params, axis=1).reshape((-1, 1))\n return predictions\n\n def summary(self):\n \"\"\"\n Print out GWR summary\n \"\"\"\n summary = summaryModel(self) + summaryGLM(self) + summaryGWR(self)\n print(summary)\n return\n\n\nclass GWRResultsLite(object):\n \"\"\"\n Lightweight GWR that computes the minimum diagnostics needed for bandwidth\n selection\n\n Parameters\n ----------\n model : GWR object\n pointer to GWR object with estimation parameters\n\n resid : array\n n*1, residuals of the repsonse\n\n influ : array\n n*1, leading diagonal of S matrix\n\n Attributes\n ----------\n tr_S : float\n trace of S (hat) matrix\n\n llf : scalar\n log-likelihood of the full model; see\n pysal.contrib.glm.family for damily-sepcific\n log-likelihoods\n\n mu : array\n n*, flat one dimensional array of predicted mean\n response value from estimator\n\n resid_ss : scalar\n residual sum of sqaures\n\n \"\"\"\n\n def __init__(self, model, resid, influ, params):\n self.y = model.y\n self.family = model.family\n self.n = model.n\n self.influ = influ\n self.resid_response = resid\n self.model = model\n self.params = params\n\n @cache_readonly\n def tr_S(self):\n return np.sum(self.influ)\n\n @cache_readonly\n def llf(self):\n return self.family.loglike(self.y, self.mu)\n\n @cache_readonly\n def mu(self):\n return self.y - self.resid_response\n\n @cache_readonly\n def predy(self):\n return self.y - self.resid_response\n\n @cache_readonly\n def resid_ss(self):\n u = self.resid_response.flatten()\n return np.dot(u, u.T)\n\n\nclass MGWR(GWR):\n \"\"\"\n Multiscale GWR estimation and inference.\n\n Parameters\n ----------\n coords : array-like\n n*2, collection of n sets of (x,y) coordinates of\n observatons; also used as calibration locations is\n 'points' is set to None\n\n y : array\n n*1, dependent variable\n\n X : array\n n*k, independent variable, exlcuding the constant\n\n selector : sel_bw object\n valid sel_bw object that has successfully called\n the \"search\" method. This parameter passes on\n information from GAM model estimation including optimal\n bandwidths.\n\n family : family object\n underlying probability model; provides\n distribution-specific calculations\n\n sigma2_v1 : boolean\n specify form of corrected denominator of sigma squared to use for\n model diagnostics; Acceptable options are:\n\n 'True': n-tr(S) (defualt)\n 'False': n-2(tr(S)+tr(S'S))\n\n kernel : string\n type of kernel function used to weight observations;\n available options:\n 'gaussian'\n 'bisquare'\n 'exponential'\n\n fixed : boolean\n True for distance based kernel function and False for\n adaptive (nearest neighbor) kernel function (default)\n\n constant : boolean\n True to include intercept (default) in model and False to exclude\n intercept.\n\n spherical : boolean\n True for shperical coordinates (long-lat),\n False for projected coordinates (defalut).\n hat_matrix : boolean\n True for computing and storing covariate-specific\n hat matrices R (n,n,k) and model hat matrix S (n,n).\n False (default) for computing MGWR inference on the fly.\n\n Attributes\n ----------\n coords : array-like\n n*2, collection of n sets of (x,y) coordinates of\n observatons; also used as calibration locations is\n 'points' is set to None\n\n y : array\n n*1, dependent variable\n\n X : array\n n*k, independent variable, exlcuding the constant\n\n selector : sel_bw object\n valid sel_bw object that has successfully called\n the \"search\" method. This parameter passes on\n information from GAM model estimation including optimal\n bandwidths.\n\n bw : array-like\n collection of bandwidth values consisting of either a distance or N\n nearest neighbors; user specified or obtained using\n Sel_BW with fb=True. Order of values should the same as\n the order of columns associated with X\n\n family : family object\n underlying probability model; provides\n distribution-specific calculations\n\n sigma2_v1 : boolean\n specify form of corrected denominator of sigma squared to use for\n model diagnostics; Acceptable options are:\n\n 'True': n-tr(S) (defualt)\n 'False': n-2(tr(S)+tr(S'S))\n\n kernel : string\n type of kernel function used to weight observations;\n available options:\n 'gaussian'\n 'bisquare'\n 'exponential'\n\n fixed : boolean\n True for distance based kernel function and False for\n adaptive (nearest neighbor) kernel function (default)\n\n constant : boolean\n True to include intercept (default) in model and False to exclude\n intercept.\n\n spherical : boolean\n True for shperical coordinates (long-lat),\n False for projected coordinates (defalut).\n\n n : integer\n number of observations\n\n k : integer\n number of independent variables\n\n mean_y : float\n mean of y\n\n std_y : float\n standard deviation of y\n\n fit_params : dict\n parameters passed into fit method to define estimation\n routine\n\n W : array-like\n list of n*n arrays, spatial weights matrices for weighting all\n observations from each calibration point: one for each\n covariate (k)\n\n Examples\n --------\n\n #basic model calibration\n\n >>> import libpysal as ps\n >>> from mgwr.gwr import MGWR\n >>> from mgwr.sel_bw import Sel_BW\n >>> data = ps.io.open(ps.examples.get_path('GData_utm.csv'))\n >>> coords = list(zip(data.by_col('X'), data.by_col('Y')))\n >>> y = np.array(data.by_col('PctBach')).reshape((-1,1))\n >>> rural = np.array(data.by_col('PctRural')).reshape((-1,1))\n >>> fb = np.array(data.by_col('PctFB')).reshape((-1,1))\n >>> african_amer = np.array(data.by_col('PctBlack')).reshape((-1,1))\n >>> X = np.hstack([fb, african_amer, rural])\n >>> X = (X - X.mean(axis=0)) / X.std(axis=0)\n >>> y = (y - y.mean(axis=0)) / y.std(axis=0)\n >>> selector = Sel_BW(coords, y, X, multi=True)\n >>> selector.search(multi_bw_min=[2])\n [92.0, 101.0, 136.0, 158.0]\n >>> model = MGWR(coords, y, X, selector, fixed=False, kernel='bisquare', sigma2_v1=True)\n >>> results = model.fit()\n >>> print(results.params.shape)\n (159, 4)\n\n \"\"\"\n\n def __init__(self, coords, y, X, selector, sigma2_v1=True,\n kernel='bisquare', fixed=False, constant=True,\n spherical=False, hat_matrix=False):\n \"\"\"\n Initialize class\n \"\"\"\n self.selector = selector\n self.bws = self.selector.bw[0] #final set of bandwidth\n self.bws_history = selector.bw[1] #bws history in backfitting\n self.bw_init = self.selector.bw_init #initialization bandiwdth\n self.family = Gaussian(\n ) # manually set since we only support Gassian MGWR for now\n GWR.__init__(self, coords, y, X, self.bw_init, family=self.family,\n sigma2_v1=sigma2_v1, kernel=kernel, fixed=fixed,\n constant=constant, spherical=spherical,\n hat_matrix=hat_matrix)\n self.selector = selector\n self.sigma2_v1 = sigma2_v1\n self.points = None\n self.P = None\n self.offset = None\n self.exog_resid = None\n self.exog_scale = None\n self_fit_params = None\n\n def _chunk_compute_R(self, chunk_id=0):\n \"\"\"\n Compute MGWR inference by chunks to reduce memory footprint.\n \"\"\"\n n = self.n\n k = self.k\n n_chunks = self.n_chunks\n chunk_size = int(np.ceil(float(n / n_chunks)))\n ENP_j = np.zeros(self.k)\n CCT = np.zeros((self.n, self.k))\n\n chunk_index = np.arange(n)[chunk_id * chunk_size:(chunk_id + 1) *\n chunk_size]\n init_pR = np.zeros((n, len(chunk_index)))\n init_pR[chunk_index, :] = np.eye(len(chunk_index))\n pR = np.zeros((n, len(chunk_index),\n k)) #partial R: n by chunk_size by k\n\n for i in range(n):\n wi = self._build_wi(i, self.bw_init).reshape(-1, 1)\n xT = (self.X * wi).T\n P = np.linalg.solve(xT.dot(self.X), xT).dot(init_pR).T\n pR[i, :, :] = P * self.X[i]\n\n err = init_pR - np.sum(pR, axis=2) #n by chunk_size\n\n for iter_i in range(self.bws_history.shape[0]):\n for j in range(k):\n pRj_old = pR[:, :, j] + err\n Xj = self.X[:, j]\n n_chunks_Aj = n_chunks\n chunk_size_Aj = int(np.ceil(float(n / n_chunks_Aj)))\n for chunk_Aj in range(n_chunks_Aj):\n chunk_index_Aj = np.arange(n)[chunk_Aj * chunk_size_Aj:(\n chunk_Aj + 1) * chunk_size_Aj]\n pAj = np.empty((len(chunk_index_Aj), n))\n for i in range(len(chunk_index_Aj)):\n index = chunk_index_Aj[i]\n wi = self._build_wi(index, self.bws_history[iter_i, j])\n xw = Xj * wi\n pAj[i, :] = Xj[index] / np.sum(xw * Xj) * xw\n pR[chunk_index_Aj, :, j] = pAj.dot(pRj_old)\n err = pRj_old - pR[:, :, j]\n\n for j in range(k):\n CCT[:, j] += ((pR[:, :, j] / self.X[:, j].reshape(-1, 1))**2).sum(\n axis=1)\n for i in range(len(chunk_index)):\n ENP_j += pR[chunk_index[i], i, :]\n\n if self.hat_matrix:\n return ENP_j, CCT, pR\n return ENP_j, CCT\n\n def fit(self, n_chunks=1, pool=None):\n \"\"\"\n Compute MGWR inference by chunk to reduce memory footprint.\n \n Parameters\n ----------\n\n n_chunks : integer, optional\n A number of chunks parameter to reduce memory usage. \n e.g. n_chunks=2 should reduce overall memory usage by 2.\n pool : A multiprocessing Pool object to enable parallel fitting; default is None.\n \n Returns\n -------\n : MGWRResults\n \"\"\"\n params = self.selector.params\n predy = np.sum(self.X * params, axis=1).reshape(-1, 1)\n\n try:\n from tqdm.autonotebook import tqdm #progress bar\n except ImportError:\n\n def tqdm(x, total=0,\n desc=''): #otherwise, just passthrough the range\n return x\n\n if pool:\n self.n_chunks = pool._processes * n_chunks\n rslt = tqdm(\n pool.imap(self._chunk_compute_R, range(self.n_chunks)),\n total=self.n_chunks, desc='Inference')\n else:\n self.n_chunks = n_chunks\n rslt = map(self._chunk_compute_R,\n tqdm(range(self.n_chunks), desc='Inference'))\n\n rslt_list = list(zip(*rslt))\n ENP_j = np.sum(np.array(rslt_list[0]), axis=0)\n CCT = np.sum(np.array(rslt_list[1]), axis=0)\n\n w = np.ones(self.n)\n if self.hat_matrix:\n R = np.hstack(rslt_list[2])\n else:\n R = None\n return MGWRResults(self, params, predy, CCT, ENP_j, w, R)\n\n def predict(self):\n '''\n Not implemented.\n '''\n raise NotImplementedError('N/A')\n\n\nclass MGWRResults(GWRResults):\n \"\"\"\n Class including common properties for a MGWR model.\n\n Parameters\n ----------\n model : MGWR object\n pointer to MGWR object with estimation parameters\n\n params : array\n n*k, estimated coefficients\n\n predy : array\n n*1, predicted y values\n\n S : array\n n*n, model hat matrix (if MGWR(hat_matrix=True))\n\n R : array\n n*n*k, covariate-specific hat matrices (if MGWR(hat_matrix=True))\n\n CCT : array\n n*k, scaled variance-covariance matrix\n\n w : array\n n*1, final weight used for iteratively re-weighted least\n sqaures; default is None\n\n Attributes\n ----------\n model : GWR Object\n points to GWR object for which parameters have been\n estimated\n\n params : array\n n*k, parameter estimates\n\n predy : array\n n*1, predicted value of y\n\n y : array\n n*1, dependent variable\n\n X : array\n n*k, independent variable, including constant\n\n family : family object\n underlying probability model; provides\n distribution-specific calculations\n\n n : integer\n number of observations\n\n k : integer\n number of independent variables\n\n df_model : integer\n model degrees of freedom\n\n df_resid : integer\n residual degrees of freedom\n\n scale : float\n sigma squared used for subsequent computations\n\n w : array\n n*1, final weights from iteratively re-weighted least\n sqaures routine\n\n resid_response : array\n n*1, residuals of the repsonse\n\n resid_ss : scalar\n residual sum of sqaures\n\n W : array-like\n list of n*n arrays, spatial weights matrices for weighting all\n observations from each calibration point: one for each\n covariate (k)\n\n S : array\n n*n, model hat matrix (if MGWR(hat_matrix=True))\n\n R : array\n n*n*k, covariate-specific hat matrices (if MGWR(hat_matrix=True))\n\n CCT : array\n n*k, scaled variance-covariance matrix\n\n ENP : scalar\n effective number of paramters, which depends on\n sigma2, for the entire model\n\n ENP_j : array-like\n effective number of paramters, which depends on\n sigma2, for each covariate in the model\n\n adj_alpha : array\n 3*1, corrected alpha values to account for multiple\n hypothesis testing for the 90%, 95%, and 99% confidence\n levels; tvalues with an absolute value larger than the\n corrected alpha are considered statistically\n significant.\n\n adj_alpha_j : array\n k*3, corrected alpha values to account for multiple\n hypothesis testing for the 90%, 95%, and 99% confidence\n levels; tvalues with an absolute value larger than the\n corrected alpha are considered statistically\n significant. A set of alpha calues is computed for\n each covariate in the model.\n\n tr_S : float\n trace of S (hat) matrix\n\n tr_STS : float\n trace of STS matrix\n\n R2 : float\n R-squared for the entire model (1- RSS/TSS)\n \n adj_R2 : float\n adjusted R-squared for the entire model\n\n aic : float\n Akaike information criterion\n\n aicc : float\n corrected Akaike information criterion to account\n to account for model complexity (smaller\n bandwidths)\n\n bic : float\n Bayesian information criterio\n\n sigma2 : float\n sigma squared (residual variance) that has been\n corrected to account for the ENP\n\n std_res : array\n n*1, standardised residuals\n\n bse : array\n n*k, standard errors of parameters (betas)\n\n influ : array\n n*1, leading diagonal of S matrix\n\n CooksD : array\n n*1, Cook's D\n\n tvalues : array\n n*k, local t-statistics\n\n llf : scalar\n log-likelihood of the full model; see\n pysal.contrib.glm.family for damily-sepcific\n log-likelihoods\n\n mu : array\n n*, flat one dimensional array of predicted mean\n response value from estimator\n\n \"\"\"\n\n def __init__(self, model, params, predy, CCT, ENP_j, w, R):\n \"\"\"\n Initialize class\n \"\"\"\n self.ENP_j = ENP_j\n self.R = R\n GWRResults.__init__(self, model, params, predy, None, CCT, None, w)\n if model.hat_matrix:\n self.S = np.sum(self.R, axis=2)\n self.predy = predy\n\n @cache_readonly\n def tr_S(self):\n return np.sum(self.ENP_j)\n\n @cache_readonly\n def W(self):\n Ws = []\n for bw_j in self.model.bws:\n W = np.array(\n [self.model._build_wi(i, bw_j) for i in range(self.n)])\n Ws.append(W)\n return Ws\n\n @cache_readonly\n def adj_alpha_j(self):\n \"\"\"\n Corrected alpha (critical) values to account for multiple testing during hypothesis\n testing. Includes corrected value for 90% (.1), 95% (.05), and 99%\n (.01) confidence levels. Correction comes from:\n\n da Silva, A. R., & Fotheringham, A. S. (2015). The Multiple Testing Issue in\n Geographically Weighted Regression. Geographical Analysis.\n\n \"\"\"\n alpha = np.array([.1, .05, .001])\n pe = np.array(self.ENP_j).reshape((-1, 1))\n p = 1.\n return (alpha * p) / pe\n\n def critical_tval(self, alpha=None):\n \"\"\"\n Utility function to derive the critial t-value based on given alpha\n that are needed for hypothesis testing\n\n Parameters\n ----------\n alpha : scalar\n critical value to determine which tvalues are\n associated with statistically significant parameter\n estimates. Default to None in which case the adjusted\n alpha value at the 95 percent CI is automatically\n used.\n\n Returns\n -------\n critical : scalar\n critical t-val based on alpha\n \"\"\"\n n = self.n\n if alpha is not None:\n alpha = np.abs(alpha) / 2.0\n critical = t.ppf(1 - alpha, n - 1)\n else:\n alpha = np.abs(self.adj_alpha_j[:, 1]) / 2.0\n critical = t.ppf(1 - alpha, n - 1)\n return critical\n\n def filter_tvals(self, critical_t=None, alpha=None):\n \"\"\"\n Utility function to set tvalues with an absolute value smaller than the\n absolute value of the alpha (critical) value to 0. If critical_t\n is supplied than it is used directly to filter. If alpha is provided\n than the critical t value will be derived and used to filter. If neither\n are critical_t nor alpha are provided, an adjusted alpha at the 95\n percent CI will automatically be used to define the critical t-value and\n used to filter. If both critical_t and alpha are supplied then the alpha\n value will be ignored.\n\n Parameters\n ----------\n critical : scalar\n critical t-value to determine whether parameters are\n statistically significant\n\n alpha : scalar\n alpha value to determine which tvalues are\n associated with statistically significant parameter\n estimates\n\n Returns\n -------\n filtered : array\n n*k; new set of n tvalues for each of k variables\n where absolute tvalues less than the absolute value of\n alpha have been set to 0.\n \"\"\"\n n = self.n\n if critical_t is not None:\n critical = np.array(critical_t)\n elif alpha is not None and critical_t is None:\n critical = self.critical_tval(alpha=alpha)\n elif alpha is None and critical_t is None:\n critical = self.critical_tval()\n\n subset = (self.tvalues < critical) & (self.tvalues > -1.0 * critical)\n tvalues = self.tvalues.copy()\n tvalues[subset] = 0\n return tvalues\n\n @cache_readonly\n def RSS(self):\n raise NotImplementedError(\n 'Not yet implemented for multiple bandwidths')\n\n @cache_readonly\n def TSS(self):\n raise NotImplementedError(\n 'Not yet implemented for multiple bandwidths')\n\n @cache_readonly\n def localR2(self):\n raise NotImplementedError(\n 'Not yet implemented for multiple bandwidths')\n\n @cache_readonly\n def y_bar(self):\n raise NotImplementedError(\n 'Not yet implemented for multiple bandwidths')\n\n @cache_readonly\n def predictions(self):\n raise NotImplementedError('Not yet implemented for MGWR')\n\n def local_collinearity(self):\n \"\"\"\n Computes several indicators of multicollinearity within a geographically\n weighted design matrix, including:\n\n local condition number (n, 1)\n local variance-decomposition proportions (n, p)\n\n Returns four arrays with the order and dimensions listed above where n\n is the number of locations used as calibrations points and p is the\n nubmer of explanatory variables\n\n \"\"\"\n x = self.X\n w = self.W\n nvar = x.shape[1]\n nrow = self.n\n vdp_idx = np.ndarray((nrow, nvar))\n vdp_pi = np.ndarray((nrow, nvar, nvar))\n\n for i in range(nrow):\n xw = np.zeros((x.shape))\n for j in range(nvar):\n wi = w[j][i]\n sw = np.sum(wi)\n wi = wi / sw\n xw[:, j] = x[:, j] * wi\n\n sxw = np.sqrt(np.sum(xw**2, axis=0))\n sxw = np.transpose(xw.T / sxw.reshape((nvar, 1)))\n svdx = np.linalg.svd(sxw)\n vdp_idx[i, ] = svdx[1][0] / svdx[1]\n\n phi = np.dot(svdx[2].T, np.diag(1 / svdx[1]))\n phi = np.transpose(phi**2)\n pi_ij = phi / np.sum(phi, axis=0)\n vdp_pi[i, :, :] = pi_ij\n\n local_CN = vdp_idx[:, nvar - 1].reshape((-1, 1))\n VDP = vdp_pi[:, nvar - 1, :]\n\n return local_CN, VDP\n\n def spatial_variability(self, selector, n_iters=1000, seed=None):\n \"\"\"\n Method to compute a Monte Carlo test of spatial variability for each\n estimated coefficient surface.\n\n WARNING: This test is very computationally demanding!\n\n Parameters\n ----------\n selector : sel_bw object\n should be the sel_bw object used to select a bandwidth\n for the gwr model that produced the surfaces that are\n being tested for spatial variation\n\n n_iters : int\n the number of Monte Carlo iterations to include for\n the tests of spatial variability.\n\n seed : int\n optional parameter to select a custom seed to ensure\n stochastic results are replicable. Default is none\n which automatically sets the seed to 5536\n\n Returns\n -------\n\n p values : list\n a list of psuedo p-values that correspond to the model\n parameter surfaces. Allows us to assess the\n probability of obtaining the observed spatial\n variation of a given surface by random chance.\n\n\n \"\"\"\n temp_sel = copy.deepcopy(selector)\n\n if seed is None:\n np.random.seed(5536)\n else:\n np.random.seed(seed)\n\n search_params = temp_sel.search_params\n\n if self.model.constant:\n X = self.X[:, 1:]\n else:\n X = self.X\n\n init_sd = np.std(self.params, axis=0)\n SDs = []\n\n for x in range(n_iters):\n temp_coords = np.random.permutation(self.model.coords)\n temp_sel.coords = temp_coords\n temp_sel.search(**search_params)\n temp_params = temp_sel.params\n temp_sd = np.std(temp_params, axis=0)\n SDs.append(temp_sd)\n\n p_vals = (np.sum(np.array(SDs) > init_sd, axis=0) / float(n_iters))\n return p_vals\n\n def summary(self):\n \"\"\"\n Print out MGWR summary\n \"\"\"\n summary = summaryModel(self) + summaryGLM(self) + summaryMGWR(self)\n print(summary)\n return\n" ]
[ [ "numpy.sum", "numpy.ones", "numpy.diag", "numpy.random.seed", "numpy.log", "numpy.cov", "numpy.transpose", "numpy.abs", "numpy.ndarray", "numpy.identity", "numpy.zeros", "scipy.stats.t.ppf", "numpy.arange", "numpy.hstack", "numpy.std", "numpy.array", "numpy.random.permutation", "numpy.linalg.svd", "numpy.sqrt", "numpy.dot" ] ]
XiaoSanchez/autophase
[ "3d8d173ad27b9786e36efd22d0ceacbcf1cb1dfb" ]
[ "algos/rl/policies.py" ]
[ "# Code in this file is copied and adapted from\n# https://github.com/openai/evolution-strategies-starter.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\n\nimport ray\nfrom ray.rllib.evaluation.sampler import _unbatch_tuple_actions\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.utils.filter import get_filter\n\n\ndef rollout(policy, env, timestep_limit=None, add_noise=False):\n \"\"\"Do a rollout.\n\n If add_noise is True, the rollout will take noisy actions with\n noise drawn from that stream. Otherwise, no action noise will be added.\n \"\"\"\n env_timestep_limit = env.max_episode_steps\n timestep_limit = (env_timestep_limit if timestep_limit is None else min(\n timestep_limit, env_timestep_limit))\n rews = []\n t = 0\n observation = env.reset()\n for _ in range(timestep_limit or 999999):\n ac = policy.compute(observation, add_noise=add_noise)[0]\n observation, rew, done, _ = env.step(ac)\n rews.append(rew)\n t += 1\n if done:\n break\n rews = np.array(rews, dtype=np.float32)\n return rews, t\n\n\nclass GenericPolicy(object):\n def __init__(self, sess, action_space, obs_space, preprocessor,\n observation_filter, model_options, action_noise_std):\n self.sess = sess\n self.action_space = action_space\n self.action_noise_std = action_noise_std\n self.preprocessor = preprocessor\n self.observation_filter = get_filter(observation_filter,\n self.preprocessor.shape)\n self.inputs = tf.placeholder(tf.float32,\n [None] + list(self.preprocessor.shape))\n\n # Policy network.\n dist_class, dist_dim = ModelCatalog.get_action_dist(\n self.action_space, model_options, dist_type=\"deterministic\")\n model = ModelCatalog.get_model({\n \"obs\": self.inputs\n }, obs_space, dist_dim, model_options)\n dist = dist_class(model.outputs)\n self.sampler = dist.sample()\n\n self.variables = ray.experimental.TensorFlowVariables(\n model.outputs, self.sess)\n\n self.num_params = sum(\n np.prod(variable.shape.as_list())\n for _, variable in self.variables.variables.items())\n self.sess.run(tf.global_variables_initializer())\n\n def compute(self, observation, add_noise=False, update=True):\n observation = self.preprocessor.transform(observation)\n observation = self.observation_filter(observation[None], update=update)\n #observation = self.observation_filter(observation, update=update)\n action = self.sess.run(\n self.sampler, feed_dict={self.inputs: observation})\n action = _unbatch_tuple_actions(action)\n if add_noise and isinstance(self.action_space, gym.spaces.Box):\n action += np.random.randn(*action.shape) * self.action_noise_std\n return action\n\n def set_weights(self, x):\n self.variables.set_flat(x)\n\n def get_weights(self):\n return self.variables.get_flat()\n\n def get_filter(self):\n return self.observation_filter\n\n def set_filter(self, observation_filter):\n self.observation_filter = observation_filter\n" ]
[ [ "numpy.array", "numpy.random.randn", "tensorflow.global_variables_initializer" ] ]
koetjen/steinbock
[ "b0abcc16120f7a028167cc0a6f9b4f78d010844b" ]
[ "steinbock/preprocessing/imc.py" ]
[ "import logging\nimport numpy as np\nimport pandas as pd\nimport re\n\nfrom os import PathLike\nfrom pathlib import Path\nfrom scipy.ndimage import maximum_filter\nfrom typing import (\n Generator,\n List,\n Optional,\n Sequence,\n Tuple,\n Union,\n)\n\nfrom steinbock import io\n\ntry:\n from readimc import MCDFile, TXTFile\n from readimc.data import Acquisition, AcquisitionBase\n\n imc_available = True\nexcept:\n imc_available = False\n\n\n_logger = logging.getLogger(__name__)\n\n\ndef list_mcd_files(mcd_dir: Union[str, PathLike]) -> List[Path]:\n return sorted(Path(mcd_dir).rglob(\"*.mcd\"))\n\n\ndef list_txt_files(txt_dir: Union[str, PathLike]) -> List[Path]:\n return sorted(Path(txt_dir).rglob(\"*.txt\"))\n\n\ndef create_panel_from_imc_panel(\n imc_panel_file: Union[str, PathLike],\n imc_panel_channel_col: str = \"Metal Tag\",\n imc_panel_name_col: str = \"Target\",\n imc_panel_keep_col: str = \"full\",\n imc_panel_ilastik_col: str = \"ilastik\",\n) -> pd.DataFrame:\n imc_panel = pd.read_csv(\n imc_panel_file,\n sep=\",|;\",\n dtype={\n imc_panel_channel_col: pd.StringDtype(),\n imc_panel_name_col: pd.StringDtype(),\n imc_panel_keep_col: pd.BooleanDtype(),\n imc_panel_ilastik_col: pd.BooleanDtype(),\n },\n engine=\"python\",\n true_values=[\"1\"],\n false_values=[\"0\"],\n )\n for required_col in (imc_panel_channel_col, imc_panel_name_col):\n if required_col not in imc_panel:\n raise ValueError(f\"Missing '{required_col}' column in IMC panel\")\n for notnan_col in (\n imc_panel_channel_col,\n imc_panel_keep_col,\n imc_panel_ilastik_col,\n ):\n if notnan_col in imc_panel and imc_panel[notnan_col].isna().any():\n raise ValueError(f\"Missing values for '{notnan_col}' in IMC panel\")\n rename_columns = {\n imc_panel_channel_col: \"channel\",\n imc_panel_name_col: \"name\",\n imc_panel_keep_col: \"keep\",\n imc_panel_ilastik_col: \"ilastik\",\n }\n drop_columns = [\n panel_col\n for imc_panel_col, panel_col in rename_columns.items()\n if panel_col in imc_panel.columns and panel_col != imc_panel_col\n ]\n panel = imc_panel.drop(columns=drop_columns).rename(columns=rename_columns)\n for _, g in panel.groupby(\"channel\"):\n panel.loc[g.index, \"name\"] = \" / \".join(g[\"name\"].dropna().unique())\n if \"keep\" in panel:\n panel.loc[g.index, \"keep\"] = g[\"keep\"].any()\n if \"ilastik\" in panel:\n panel.loc[g.index, \"ilastik\"] = g[\"ilastik\"].any()\n panel = panel.groupby(panel[\"channel\"].values).aggregate(\"first\")\n panel = _clean_panel(panel) # ilastik column may be nullable uint8 now\n ilastik_mask = panel[\"ilastik\"].fillna(False).astype(bool)\n panel[\"ilastik\"] = pd.Series(dtype=pd.UInt8Dtype())\n panel.loc[ilastik_mask, \"ilastik\"] = range(1, ilastik_mask.sum() + 1)\n return panel\n\n\ndef create_panel_from_mcd_files(\n mcd_files: Sequence[Union[str, PathLike]]\n) -> pd.DataFrame:\n panels = []\n for mcd_file in mcd_files:\n with MCDFile(mcd_file) as f:\n for slide in f.slides:\n for acquisition in slide.acquisitions:\n panel = _create_panel_from_acquisition(acquisition)\n panels.append(panel)\n panel = pd.concat(panels, ignore_index=True, copy=False)\n return _clean_panel(panel)\n\n\ndef create_panel_from_txt_files(\n txt_files: Sequence[Union[str, PathLike]]\n) -> pd.DataFrame:\n panels = []\n for txt_file in txt_files:\n with TXTFile(txt_file) as f:\n panel = _create_panel_from_acquisition(f)\n panels.append(panel)\n panel = pd.concat(panels, ignore_index=True, copy=False)\n return _clean_panel(panel)\n\n\ndef filter_hot_pixels(img: np.ndarray, thres: float) -> np.ndarray:\n kernel = np.ones((1, 3, 3), dtype=bool)\n kernel[0, 1, 1] = False\n max_neighbor_img = maximum_filter(img, footprint=kernel, mode=\"mirror\")\n return np.where(img - max_neighbor_img > thres, max_neighbor_img, img)\n\n\ndef preprocess_image(\n img: np.ndarray, hpf: Optional[float] = None\n) -> np.ndarray:\n img = img.astype(np.float32)\n if hpf is not None:\n img = filter_hot_pixels(img, hpf)\n return io._to_dtype(img, io.img_dtype)\n\n\ndef try_preprocess_images_from_disk(\n mcd_files: Sequence[Union[str, PathLike]],\n txt_files: Sequence[Union[str, PathLike]],\n channel_names: Optional[Sequence[str]] = None,\n hpf: Optional[float] = None,\n) -> Generator[\n Tuple[Path, Optional[\"Acquisition\"], np.ndarray, Optional[Path], bool],\n None,\n None,\n]:\n unmatched_txt_files = list(txt_files)\n for mcd_file in mcd_files:\n try:\n with MCDFile(mcd_file) as f_mcd:\n for slide in f_mcd.slides:\n for acquisition in slide.acquisitions:\n matched_txt_file = _match_txt_file(\n mcd_file, acquisition, unmatched_txt_files\n )\n if matched_txt_file is not None:\n unmatched_txt_files.remove(matched_txt_file)\n channel_ind = None\n if channel_names is not None:\n channel_ind = _get_channel_indices(\n acquisition, channel_names\n )\n if isinstance(channel_ind, str):\n _logger.warning(\n f\"Channel {channel_ind} not found for \"\n f\"acquisition {acquisition.id} in file \"\n \"{mcd_file}; skipping acquisition\"\n )\n continue\n img = None\n recovered = False\n try:\n img = f_mcd.read_acquisition(acquisition)\n except IOError:\n _logger.warning(\n f\"Error reading acquisition {acquisition.id} \"\n f\"from file {mcd_file}\"\n )\n if matched_txt_file is not None:\n _logger.warning(\n f\"Restoring from file {matched_txt_file}\"\n )\n try:\n with TXTFile(matched_txt_file) as f_txt:\n img = f_txt.read_acquisition()\n if channel_names is not None:\n channel_ind = _get_channel_indices(\n f_txt, channel_names\n )\n if isinstance(channel_ind, str):\n _logger.warning(\n f\"Channel {channel_ind} \"\n \"not found in file \"\n f\"{matched_txt_file}; \"\n \"skipping acquisition\"\n )\n continue\n recovered = True\n except IOError:\n _logger.exception(\n \"Error reading file \"\n f\"{matched_txt_file}\"\n )\n if img is not None: # exceptions ...\n if channel_ind is not None:\n img = img[channel_ind, :, :]\n img = preprocess_image(img, hpf=hpf)\n yield (\n Path(mcd_file),\n acquisition,\n img,\n Path(matched_txt_file)\n if matched_txt_file is not None\n else None,\n recovered,\n )\n del img\n except:\n _logger.exception(f\"Error reading file {mcd_file}\")\n while len(unmatched_txt_files) > 0:\n txt_file = unmatched_txt_files.pop(0)\n try:\n channel_ind = None\n with TXTFile(txt_file) as f:\n if channel_names is not None:\n channel_ind = _get_channel_indices(f, channel_names)\n if isinstance(channel_ind, str):\n _logger.warning(\n f\"Channel {channel_ind} not found in file \"\n f\"{txt_file}; skipping acquisition\"\n )\n continue\n img = f.read_acquisition()\n if channel_ind is not None:\n img = img[channel_ind, :, :]\n img = preprocess_image(img, hpf=hpf)\n yield Path(txt_file), None, img, None, False\n del img\n except:\n _logger.exception(f\"Error reading file {txt_file}\")\n\n\ndef _create_panel_from_acquisition(\n acquisition: \"AcquisitionBase\",\n) -> pd.DataFrame:\n panel = pd.DataFrame(\n data={\n \"channel\": acquisition.channel_names,\n \"name\": acquisition.channel_labels,\n \"keep\": True,\n \"ilastik\": range(1, acquisition.num_channels + 1),\n \"deepcell\": np.nan,\n },\n )\n panel[\"channel\"] = panel[\"channel\"].astype(pd.StringDtype())\n panel[\"name\"] = panel[\"name\"].astype(pd.StringDtype())\n panel[\"keep\"] = panel[\"keep\"].astype(pd.BooleanDtype())\n panel[\"ilastik\"] = panel[\"ilastik\"].astype(pd.UInt8Dtype())\n panel[\"deepcell\"] = panel[\"deepcell\"].astype(pd.UInt8Dtype())\n panel.sort_values(\n \"channel\",\n key=lambda s: pd.to_numeric(s.str.replace(\"[^0-9]\", \"\", regex=True)),\n inplace=True,\n )\n return panel\n\n\ndef _clean_panel(panel: pd.DataFrame) -> pd.DataFrame:\n panel.sort_values(\n \"channel\",\n key=lambda s: pd.to_numeric(s.str.replace(\"[^0-9]\", \"\", regex=True)),\n inplace=True,\n )\n name_dupl_mask = panel[\"name\"].duplicated(keep=False)\n name_suffixes = panel.groupby(\"name\").cumcount().map(lambda i: f\" {i + 1}\")\n panel.loc[name_dupl_mask, \"name\"] += name_suffixes[name_dupl_mask]\n if \"keep\" not in panel:\n panel[\"keep\"] = pd.Series(True, dtype=pd.BooleanDtype())\n if \"ilastik\" not in panel:\n panel[\"ilastik\"] = pd.Series(dtype=pd.UInt8Dtype())\n panel.loc[panel[\"keep\"], \"ilastik\"] = range(1, panel[\"keep\"].sum() + 1)\n if \"deepcell\" not in panel:\n panel[\"deepcell\"] = pd.Series(dtype=pd.UInt8Dtype())\n next_column_index = 0\n for column in (\"channel\", \"name\", \"keep\", \"ilastik\", \"deepcell\"):\n if column in panel:\n column_data = panel[column]\n panel.drop(columns=[column], inplace=True)\n panel.insert(next_column_index, column, column_data)\n next_column_index += 1\n return panel\n\n\ndef _match_txt_file(\n mcd_file: Union[str, PathLike],\n acquisition: Acquisition,\n txt_files: Sequence[Union[str, PathLike]],\n) -> Union[str, PathLike, None]:\n txt_file_name_pattern = re.compile(\n rf\"{Path(mcd_file).stem}.*_0*{acquisition.id}.txt\"\n )\n filtered_txt_files = [\n txt_file\n for txt_file in txt_files\n if txt_file_name_pattern.match(Path(txt_file).name)\n ]\n if len(filtered_txt_files) == 1:\n return filtered_txt_files[0]\n return None\n\n\ndef _get_channel_indices(\n acquisition: AcquisitionBase, channel_names: Sequence[str]\n) -> Union[Sequence[int], str]:\n channel_indices = []\n for channel_name in channel_names:\n if channel_name not in acquisition.channel_names:\n return channel_name\n channel_indices.append(acquisition.channel_names.index(channel_name))\n return channel_indices\n" ]
[ [ "numpy.ones", "scipy.ndimage.maximum_filter", "pandas.UInt8Dtype", "pandas.concat", "pandas.StringDtype", "pandas.BooleanDtype", "numpy.where" ] ]
abarcis/robot-framework
[ "a2cef7850784ae4c12b47fc7fb297f3772c2e2fe" ]
[ "robot_framework/position_feedback/px4.py" ]
[ "#! /usr/bin/env python\n\nfrom pyquaternion import Quaternion\nimport numpy as np\n\nfrom rclpy.node import Node\nfrom px4_msgs.msg import VehicleGlobalPosition\n\n\nclass PX4PositionFeedback:\n def __init__(self, system_state, time_delta):\n self.node = Node('position_feedback')\n self.system_state = system_state\n self.time_delta = time_delta\n self.poses = {ident: {'position': None, 'orientation': None}\n for ident in self.system_state.states.keys()}\n self.subscribers = [\n self.node.create_subscription(\n VehicleGlobalPosition,\n f'/d{ident}/VehicleGlobalPosition_PubSubTopic',\n self.set_new_pose_callback(ident),\n 1,\n )\n for ident in self.system_state.states.keys()\n ]\n\n def set_new_pose_callback(self, ident):\n def _set_new_pose_callback(msg):\n self.poses[ident]['position'] = np.array([\n msg.lat, msg.lon, 0\n ])\n # self.poses[ident]['orientation'] = Quaternion([\n # msg.pose.orientation.w, msg.pose.orientation.x,\n # msg.pose.orientation.y, msg.pose.orientation.z\n # ])\n # vec = self.poses[ident]['orientation'].rotate([1, 0, 0])\n # vec_xy = vec\n # vec_xy[2] = 0\n return _set_new_pose_callback\n\n def get_new_position(self, ident):\n return self.poses[ident]['position']\n\n def get_new_orientation(self, ident):\n return self.poses[ident]['orientation']\n\n def get_node(self):\n return self.node\n" ]
[ [ "numpy.array" ] ]
bb912/MATS-DRS
[ "6e1ae9ba3b865e321d6a2d100d29693b776e1d36" ]
[ "autograph/play/maze_nn_aut_adv.py" ]
[ "import math\nimport os\nimport signal\nimport sys\nfrom typing import Callable, Any, Tuple, List, Union, Optional\n\nimport ptan\nimport torch\nimport torch.nn.functional as F\nfrom tensorboardX import SummaryWriter\nfrom torch import multiprocessing\nfrom torch.optim import Adam, SGD\n\nimport autograph.lib.envs.mazeenv\nfrom autograph.lib.automata import AutomatonSet\nfrom autograph.lib.envs.mazeenv import FuelMazeEnv, FuelMazeObservation\nfrom autograph.lib.envs.mazeenv import transform_coordinate\nfrom autograph.lib.envs.mineworldenv_adv import MineWorldEnv\nfrom autograph.lib.loss_functions import TakeSimilarActionsLossFunction, PPOLossFunction, \\\n AdvantageActorCriticLossFunction\nfrom autograph.lib.mcts_aut_adv import MCTSAut_adv, AutStats, ExponentialAnnealedAutStats, UCBAnnealedAutStats\nfrom autograph.lib.running import get_parallel_queue, RandomReplayTrainingLoop, run_episode_generic\nfrom autograph.lib.shaping import AutShapingWrapperAdv\nfrom autograph.lib.util import element_add\nfrom autograph.lib.util.checkpoint_manager import CheckpointManager, StateDictLoadHandler, CombinedLoadHandler, \\\n InitZeroLoadHandler, PickleLoadHandler, TransplantCheckpointManager\nfrom autograph.lib.util.trace_return_step import TraceStep, TraceReturnStep\nfrom autograph.net.curiosity.curiosity_optimizer import ModuleCuriosityOptimizer, NoopCuriosityOptimizer\nfrom autograph.net.maze_constructors import mazenet_v1, mazernd_v1, maze_obs_rewrite_creator\nfrom autograph.net.mine_constructors import minenet_v1, mine_obs_rewriter_creator, minernd_v1, mine_mazenet_v1\nfrom autograph.net.misc_constructors import gym_make, no_op_cur_make, basic_net, no_op_make\nimport random\n\nmath.sqrt(1) # So that the import isn't optimized away (very useful when setting conditional debug breakpoints)\n\nsys.modules[\"autograph.lib.mazeenv\"] = autograph.lib.envs.mazeenv # Fix broken pickle loading\n\n\ndef throwKeyInterr():\n raise KeyboardInterrupt()\n\ndef full_fuel(action, obs: FuelMazeObservation, rew, done, info):\n return obs.fuel_level == info[\"max_fuel\"]\n\n\ndef key(action, obs: FuelMazeObservation, rew, done, info):\n return len(obs.keys) == 0\n\n\ndef goal(action, obs: FuelMazeObservation, rew, done, info):\n corner = element_add(info[\"maze_shape\"], (-1, -1))\n trans_corner = transform_coordinate(corner)\n return obs.position == trans_corner\n\n\nclass MineInfoAutAP:\n def __init__(self, apname: str = None, ap_name: str = None):\n if not (apname or ap_name):\n raise ValueError(\"Did not provide ap_name to info aut\")\n self.name = apname or ap_name\n\n def __call__(self, action, obs, rew, done, info):\n return self.name in info[\"atomic_propositions\"]\n\n\nclass MineInventoryAP:\n def __init__(self, inventory_item, quantity):\n self.item = inventory_item\n self.quantity = quantity\n\n def __call__(self, action, obs, rew, done, info):\n return info[\"inventory\"][self.item] == self.quantity\n\n\nclass MineLocationAP:\n def __init__(self, location):\n self.location = tuple(location)\n\n def __call__(self, action, obs, rew, done, info):\n position, *_ = obs\n return position == self.location\n\n\noptimizers = {\n \"Adam\": Adam,\n \"SGD\": SGD\n}\n\naut_funcs = {\n \"full_fuel\": full_fuel,\n \"key\": key,\n \"goal\": goal,\n \"info_aut\": MineInfoAutAP,\n \"mine_inventory\": MineInventoryAP,\n \"mine_location\": MineLocationAP\n}\n\nenv_constructors = {\n \"minecraft\": MineWorldEnv.from_dict,\n \"maze\": FuelMazeEnv.from_dict,\n \"gym\": gym_make\n}\n\n\ndef no_op_rewriter(x):\n return torch.Tensor([0.0])\n\n\ntraining_nets = {\n \"mazenet_v1\": (mazenet_v1, maze_obs_rewrite_creator),\n \"minenet_v1\": (minenet_v1, mine_obs_rewriter_creator),\n \"mine_mazenet_v1\": (mine_mazenet_v1, mine_obs_rewriter_creator),\n \"basicnet\": (basic_net, lambda e: torch.Tensor),\n \"no-op\": (no_op_make, lambda e: no_op_rewriter)\n}\n\ncuriosity_nets = {\n \"mazernd_v1\": (mazernd_v1, maze_obs_rewrite_creator),\n \"minernd_v1\": (minernd_v1, mine_obs_rewriter_creator),\n \"no-op\": (no_op_cur_make, no_op_rewriter)\n}\n\nloss_funcs = {\n \"MCTS\": TakeSimilarActionsLossFunction,\n \"PPO\": PPOLossFunction,\n \"A2C\": AdvantageActorCriticLossFunction\n}\n\naut_transplant_anneals = {\n \"Exponential\": ExponentialAnnealedAutStats,\n \"UCB\": UCBAnnealedAutStats\n}\n\nif __name__ == '__main__':\n import argparse\n import json5 as json\n\n p = argparse.ArgumentParser()\n p.add_argument(\"config\")\n p.add_argument(\"--device\", default=(\"cuda:0\" if torch.cuda.is_available() else \"cpu\"))\n p.add_argument(\"--log\")\n p.add_argument(\"--checkpoint\")\n p.add_argument(\"--run-name\")\n p.add_argument(\"--do-not-load-from-checkpoint\", dest=\"load_checkpoint\", action=\"store_false\")\n p.add_argument(\"--do-not-save-checkpoint\", dest=\"save_checkpoint\", action=\"store_false\")\n p.add_argument(\"--checkpoint-every\", default=1)\n p.add_argument(\"--workers\", default=8)\n p.add_argument(\"--post\", help=\"Add a postfix to the checkpoint and tensorboard names\")\n p.add_argument(\"--stop-after\", dest=\"stop_after\",\n help=\"Stop after roughly a certain number of steps have been reached\")\n\n args = vars(p.parse_args())\n\n run_name = args.get(\"run_name\")\n STOP_AFTER = args.get(\"stop_after\")\n if STOP_AFTER:\n STOP_AFTER = int(STOP_AFTER)\n\n\n def interpolate(text):\n if not text:\n return text\n\n if run_name and \"%s\" in text:\n return text % (run_name,)\n else:\n return text\n\n\n config_file = interpolate(args[\"config\"])\n\n postfix = \"\"\n\n if args.get(\"post\"):\n postfix = \"_\" + args[\"post\"]\n\n with open(config_file) as f:\n config = json.load(f)\n\n aut: dict = config[\"automaton\"]\n\n LTLF_SPEC = aut[\"spec\"]\n AUT_PARAM_NAMES = [param[\"name\"] for param in aut[\"params\"]]\n\n\n def get_func(param: dict):\n func_or_generator = aut_funcs[param[\"func\"]]\n func_params = param.get(\"params\")\n if func_params is None:\n return func_or_generator\n else:\n return func_or_generator(**func_params)\n\n\n AUT_PARAM_FUNCS = [get_func(p) for p in aut[\"params\"]]\n\n AUT_OTHER_PARAMS = {\n \"terminate_on_fail\": aut.get(\"terminate_on_fail\", True),\n \"termination_fail_reward\": aut.get(\"termination_fail_reward\", 0),\n \"terminate_on_accept\": aut.get(\"terminate_on_accept\", False),\n \"termination_accept_reward\": aut.get(\"termination_accept_reward\", 1)\n }\n\n AUT_STATS_PARAMS = aut.get(\"aut_stats_params\", dict())\n\n DISCOUNT = config[\"discount\"]\n\n if \"maze\" in config:\n maze = config[\"maze\"]\n\n config[\"env\"] = dict()\n config[\"env\"][\"type\"] = \"maze\"\n config[\"env\"][\"max_episode_len\"] = maze[\"max_episode_len\"]\n del maze[\"max_episode_len\"]\n config[\"env\"][\"params\"] = maze\n del config[\"maze\"]\n\n env = config[\"env\"]\n MAX_EPISODE_LEN = env[\"max_episode_len\"]\n MAX_LEN_REWARD = env.get(\"max_len_reward\")\n ENV_CONFIG = env[\"params\"]\n ENV_TYPE = env[\"type\"]\n\n # Policy training hyperparameters\n training: dict = config[\"training\"]\n\n LEARNING_RATE = training[\"learning_rate\"]\n REPLAY_BUFFER = training[\"replay_buffer\"]\n MIN_TRACE_TO_TRAIN = training[\"min_trace_to_train\"]\n PPO_TRAIN_ROUNDS = training[\"train_rounds\"]\n NETWORK = training.get(\"network\", \"mazenet_v1\")\n NETWORK_PARAMS = training.get(\"params\", dict())\n\n OPTIMIZER = optimizers[training.get(\"optimizer\")]\n OPTIMIZER_PARAMS = training.get(\"opt_params\", {})\n\n # Loss function\n loss: dict = config.get(\"loss\")\n if loss:\n LOSS_FUNC = loss[\"type\"]\n LOSS_PARAMS = loss.get(\"params\", dict())\n else:\n LOSS_FUNC = \"MCTS\"\n LOSS_PARAMS = dict()\n\n if config.get(\"mcts\"):\n config[\"episode_runner\"] = {\n \"type\": \"mcts_aut_episode\",\n \"params\": config.pop(\"mcts\")\n }\n\n # Policy runner parameters\n episode_runner = config[\"episode_runner\"]\n EPISODE_RUNNER_TYPE = episode_runner[\"type\"]\n EPISODE_RUNNER_PARAMS = episode_runner.get(\"params\", dict())\n\n # Curiosity Parameters\n curiosity: dict = config.get(\"curiosity\")\n\n if curiosity:\n if \"feature_space\" in curiosity:\n curiosity[\"type\"] = \"mazernd_v1\"\n curiosity[\"params\"] = {\"feature_space\": curiosity[\"feature_space\"]}\n del curiosity[\"feature_space\"]\n\n CURIOSITY_LEARNING_RATE = curiosity[\"learning_rate\"]\n CURIOSITY_NET = curiosity[\"type\"]\n CURIOSITY_PARAMS = curiosity.get(\"params\", dict())\n else:\n CURIOSITY_NET = None\n\n # Logging and checkpointing\n\n LOG_FOLDER = interpolate(args.get(\"log\")) + postfix\n CHECKPOINT_EVERY = int(args[\"checkpoint_every\"])\n CHECKPOINT_PATH = interpolate(args.get(\"checkpoint\")) + postfix\n\n \"\"\"\n There are two types of \"transplants\":\n 1. \"Old\" transplant, this just literally loads the state from the \"from\" checkpoint instead of creating the state\n from scratch\n 2. \"Regular\" transplant, this is only for the automaton statistics, and it anneals between the imported values and\n the values created during this run.\"\"\"\n transplant_config = config.get(\"transplant\")\n TRANSPLANT = False\n OLD_TRANSPLANT: Union[bool, List[str]] = False\n\n if transplant_config:\n TRANSPLANT_FROM = transplant_config[\"from\"]\n if transplant_config.get(\"fields\"):\n OLD_TRANSPLANT = transplant_config[\"fields\"]\n else:\n TRANSPLANT = True\n aut_transplant = transplant_config[\"automaton\"]\n ANNEAL_AUT_TRANSPLANT = aut_transplant[\"type\"]\n ANNEAL_AUT_TRANSPLANT_PARAMS = aut_transplant.get(\"params\", {})\n\n if CHECKPOINT_PATH:\n LOAD_FROM_CHECKPOINT = args[\"load_checkpoint\"]\n if not os.path.isfile(CHECKPOINT_PATH):\n LOAD_FROM_CHECKPOINT = False\n print(\"NOTE: no existing checkpoint found, will create new one if checkpoint saving is enabled.\")\n else:\n if OLD_TRANSPLANT:\n OLD_TRANSPLANT = False\n print(\"NOTE: Loading from checkpoint, so transplant disabled\")\n\n SAVE_CHECKPOINTS = args[\"save_checkpoint\"]\n else:\n CHECKPOINT_PATH = None\n LOAD_FROM_CHECKPOINT = False\n SAVE_CHECKPOINTS = False\n if not args[\"save_checkpoint\"]:\n print(\"WARNING: This run is not being checkpointed! Use --do-not-save-checkpoint to suppress.\")\n\n NUM_PROCESSES = int(args[\"workers\"])\n DEVICE = torch.device(args[\"device\"])\n\n\ndef run_mcts_aut_episode(net: torch.nn.Module, env: AutShapingWrapperAdv, max_length: int,\n max_len_reward: Union[int, None],\n curiosity: ModuleCuriosityOptimizer,\n device, c_puct, c_aut,\n num_batches, batch_size, stats: AutStats, train_state_rewriter: Callable[[Any], torch.Tensor],\n state_observer: Callable[[Any], None] = None, c_sigma=1, c_intrins=1, **kwargs) \\\n -> Tuple[List[TraceStep], float]:\n \"\"\"\n Run an episode using MCTS with curiosity as the action selection\n :param net: The policy/value network\n :param env: The environment to run the simulation in\n :param max_length: When to cut off the simulation\n :param curiosity: Something to calculate the relative \"newness\" of a state\n :param device: The device to run the simulation on\n :param c_puct: Puct constant of MCTS\n :param num_batches: How many groups of MCTS sims to run\n :param batch_size: How many MCTS sims per group\n :param state_observer: Function to call for every state seen\n :return: A trace and final value estimate\n \"\"\"\n\n def curiosity_evaluator(sars):\n states, actions, rewards, next_states, _ = zip(*sars)\n rewards = curiosity.get_curiosity(states, actions, next_states)\n return rewards.tolist()\n\n def curiosity_trainer(sars):\n states, actions, rewards, next_states, _ = zip(*sars)\n curiosity.train(states, actions, next_states, train_rounds=1)\n\n def state_evaluator(states):\n states_transformed = torch.stack(tuple(train_state_rewriter(s) for s in states))\n pols, vals = net(states_transformed.to(device))\n pollist = F.softmax(pols, dim=-1).tolist()\n vallist = vals.squeeze(-1).tolist()\n\n return list(zip(pollist, vallist))\n\n stats.synchronize()\n\n mcts = MCTSAut_adv(env.action_space.n, curiosity_evaluator, state_evaluator, curiosity_trainer, c_puct=c_puct,\n aut_stats=stats, c_aut=c_aut, c_sigma=c_sigma, c_intrins=c_intrins, **kwargs)\n\n def action_value_generator(state, step):\n mcts.mcts_batch(env, state, num_batches, batch_size)\n probs, values = mcts.get_policy_value(state, 1)\n return probs, max(values)\n\n return run_episode_generic(env, action_value_generator, max_length, max_len_reward,\n ptan.actions.ProbabilityActionSelector(),\n state_observer)\n\n\ndef run_aut_episode(net: torch.nn.Module, env: AutShapingWrapperAdv, max_length: int, max_len_reward: Optional[int],\n curiosity: ModuleCuriosityOptimizer, device,\n train_state_rewriter: Callable[[Any], torch.Tensor], stats: AutStats,\n state_observer: Callable[[Any], None] = None, render_every_frame=False) -> Tuple[\n List[TraceStep], float]:\n stats.synchronize()\n\n def action_value_generator(state, step):\n obs_tensor = train_state_rewriter(state).to(device)\n obs_batch = obs_tensor.unsqueeze(dim=0)\n probs, values = net(obs_batch)\n pols_soft = F.softmax(probs.double(), dim=-1).squeeze(0)\n pols_soft /= pols_soft.sum()\n pols_soft = pols_soft.tolist()\n val = values.squeeze(0).tolist()[0]\n if render_every_frame:\n env.render()\n\n return pols_soft, val\n\n # TODO curiosity and automaton bonuses\n return run_episode_generic(env, action_value_generator, max_length, max_len_reward,\n ptan.actions.EpsilonGreedyActionSelector(\n selector=ptan.actions.ProbabilityActionSelector(),\n epsilon=.1),\n state_observer)\n\n\nepisode_runners = {\n \"mcts_aut_episode\": run_mcts_aut_episode,\n \"aut_episode\": run_aut_episode\n}\n\n\ndef run():\n torch.multiprocessing.set_start_method(\"spawn\", force=True)\n signal.signal(signal.SIGHUP, throwKeyInterr)\n\n try:\n cman = CheckpointManager(CHECKPOINT_PATH, LOAD_FROM_CHECKPOINT, SAVE_CHECKPOINTS, device=DEVICE)\n except EOFError:\n cman = CheckpointManager(CHECKPOINT_PATH + \"_copy\", LOAD_FROM_CHECKPOINT, SAVE_CHECKPOINTS, device=DEVICE)\n\n if TRANSPLANT:\n cman = TransplantCheckpointManager(cman, TRANSPLANT_FROM)\n cman.transplant(\"aut\") # Generating the automaton may not be completely deterministic, we want the same states\n elif OLD_TRANSPLANT:\n cman = TransplantCheckpointManager(cman, TRANSPLANT_FROM)\n for field in OLD_TRANSPLANT:\n cman.transplant(field)\n\n aut = cman.load(\"aut\", AutomatonSet.from_ltlf(LTLF_SPEC, AUT_PARAM_NAMES), PickleLoadHandler())\n\n orig_env = env_constructors[ENV_TYPE](ENV_CONFIG)\n\n env = AutShapingWrapperAdv(orig_env, AUT_PARAM_FUNCS, aut, use_potential=False, **AUT_OTHER_PARAMS)\n\n action_space = env.action_space.n\n writer = SummaryWriter(LOG_FOLDER)\n\n train_net_creator, train_rewriter_creator = training_nets[NETWORK]\n\n net = cman.load(\"net\", train_net_creator(orig_env, **NETWORK_PARAMS),\n CombinedLoadHandler(StateDictLoadHandler(), InitZeroLoadHandler())).to(DEVICE)\n net.share_memory()\n\n if CURIOSITY_NET:\n curiosity_net_creator, curiosity_rewriter_creator = curiosity_nets[CURIOSITY_NET]\n\n icm = cman.load(\"icm\", curiosity_net_creator(orig_env, **CURIOSITY_PARAMS), StateDictLoadHandler()).to(\n DEVICE)\n icm.share_memory()\n\n icm_opt = cman.load(\"icm_opt\", ModuleCuriosityOptimizer(icm, curiosity_rewriter_creator(orig_env), action_space,\n CURIOSITY_LEARNING_RATE,\n DEVICE), StateDictLoadHandler())\n else:\n icm_opt = NoopCuriosityOptimizer()\n\n loss_func = loss_funcs[LOSS_FUNC](net=net, device=DEVICE, discount=DISCOUNT, **LOSS_PARAMS)\n\n optimizer = cman.load(\"opt\", OPTIMIZER(net.parameters(), lr=LEARNING_RATE, **OPTIMIZER_PARAMS),\n StateDictLoadHandler())\n\n train_rewriter = train_rewriter_creator(orig_env)\n train_loop = cman.load(\"train_loop\",\n RandomReplayTrainingLoop(DISCOUNT, REPLAY_BUFFER, MIN_TRACE_TO_TRAIN, PPO_TRAIN_ROUNDS,\n train_rewriter, writer, DEVICE),\n StateDictLoadHandler())\n\n aut_stats = cman.load(\"aut_stats\", AutStats(len(aut.graph.network), **AUT_STATS_PARAMS), StateDictLoadHandler())\n\n if TRANSPLANT:\n orig_alt_stats = cman.load_from_alt(\"aut_stats\", AutStats(len(aut.graph.network)), StateDictLoadHandler())\n wrapped_aut_stats = aut_transplant_anneals[ANNEAL_AUT_TRANSPLANT](orig_alt_stats, aut_stats,\n **ANNEAL_AUT_TRANSPLANT_PARAMS)\n wrapped_aut_stats.set_step(train_loop.num_rounds)\n train_loop.add_round_hook(wrapped_aut_stats.set_step)\n else:\n wrapped_aut_stats = aut_stats\n\n def aut_hook(trace: List[TraceReturnStep], final_value):\n # Only count each state once per run\n prev_edges = set()\n last_state = None\n for trst in trace: # TODO does this need to be reversed?\n this_state = frozenset(trst.info[\"automaton_states\"])\n\n if len(this_state) > 0:\n this_state = set(this_state).pop()\n else:\n this_state = None\n\n edge = (last_state, this_state)\n last_state = this_state\n if edge[0] is not None and edge[1] is not None:\n if edge not in prev_edges:\n aut_stats.visit(edge, trst.discounted_return)\n prev_edges.add(edge)\n\n train_loop.add_trace_hook(aut_hook)\n\n with get_parallel_queue(num_processes=NUM_PROCESSES, episode_runner=episode_runners[EPISODE_RUNNER_TYPE],\n net=net, env=env, max_length=MAX_EPISODE_LEN, max_len_reward=MAX_LEN_REWARD,\n curiosity=icm_opt, state_observer=None, device=DEVICE,\n stats=wrapped_aut_stats, train_state_rewriter=train_rewriter,\n **EPISODE_RUNNER_PARAMS) as sim_round_queue:\n\n # random.seed(798)\n\n while True:\n\n\n train_loop(sim_round_queue, loss_func, optimizer)\n\n if train_loop.num_rounds % CHECKPOINT_EVERY == 0:\n print(\"num_rounds=\", train_loop.num_rounds)\n\n save_dict = {\n \"net\": net,\n \"opt\": optimizer,\n \"train_loop\": train_loop,\n \"aut_stats\": aut_stats,\n \"aut\": aut,\n }\n\n if CURIOSITY_NET:\n save_dict.update({\n \"icm\": icm,\n \"icm_opt\": icm_opt\n })\n cman.save(save_dict)\n\n if STOP_AFTER and train_loop.global_step > STOP_AFTER:\n print(\"STOPPING: step limit \" + str(train_loop.global_step) + \"/\" + str(STOP_AFTER))\n break\n\n\nif __name__ == '__main__':\n multiprocessing.freeze_support()\n run()\n" ]
[ [ "torch.nn.functional.softmax", "torch.multiprocessing.freeze_support", "torch.multiprocessing.set_start_method", "torch.cuda.is_available", "torch.device", "torch.Tensor" ] ]
EricUrbineer/OpenAeroStruct
[ "26c37a0e86074517680405687824e27b3b2caaec" ]
[ "openaerostruct/aerodynamics/panel_forces.py" ]
[ "from __future__ import print_function\nimport numpy as np\n\nfrom openmdao.api import ExplicitComponent\n\nfrom openaerostruct.utils.vector_algebra import compute_cross, compute_cross_deriv1, compute_cross_deriv2\n\n\nclass PanelForces(ExplicitComponent):\n \"\"\"\n Compute the panel forces acting on all surfaces in the system.\n\n Parameters\n ----------\n rho : float\n Air density at the flight condition.\n horseshoe_circulations[system_size] : numpy array\n The equivalent horseshoe circulations obtained by intelligently summing\n the vortex ring circulations, accounting for overlaps between rings.\n bound_vecs[system_size, 3] : numpy array\n The vectors representing the bound vortices for each panel in the\n problem.\n This array contains points for all lifting surfaces in the problem.\n force_pts_velocities[system_size, 3] : numpy array\n The actual velocities experienced at the evaluation points for each\n lifting surface in the system. This is the summation of the freestream\n velocities and the induced velocities caused by the circulations.\n\n Returns\n -------\n panel_forces[system_size, 3] : numpy array\n All of the forces acting on all panels in the total system.\n \"\"\"\n\n def initialize(self):\n self.options.declare('surfaces', types=list)\n\n def setup(self):\n surfaces = self.options['surfaces']\n\n system_size = 0\n\n for surface in surfaces:\n mesh = surface['mesh']\n nx = mesh.shape[0]\n ny = mesh.shape[1]\n\n system_size += (nx - 1) * (ny - 1)\n\n self.system_size = system_size\n\n self.add_input('rho', units='kg/m**3')\n self.add_input('horseshoe_circulations', shape=system_size, units='m**2/s')\n self.add_input('force_pts_velocities', shape=(system_size, 3), units='m/s')\n self.add_input('bound_vecs', shape=(system_size, 3), units='m')\n\n self.add_output('panel_forces', shape=(system_size, 3), units='N')\n\n # Set up all the sparse Jacobians\n self.declare_partials('panel_forces', 'rho',\n rows=np.arange(3 * system_size),\n cols=np.zeros(3 * system_size, int),\n )\n self.declare_partials('panel_forces', 'horseshoe_circulations',\n rows=np.arange(3 * system_size),\n cols=np.outer(np.arange(system_size), np.ones(3, int)).flatten(),\n )\n self.declare_partials('panel_forces', 'force_pts_velocities',\n rows=np.einsum('ij,k->ijk',\n np.arange(3 * system_size).reshape((system_size, 3)),\n np.ones(3, int),\n ).flatten(),\n cols=np.einsum('ik,j->ijk',\n np.arange(3 * system_size).reshape((system_size, 3)),\n np.ones(3, int),\n ).flatten(),\n )\n self.declare_partials('panel_forces', 'bound_vecs',\n rows=np.einsum('ij,k->ijk',\n np.arange(3 * system_size).reshape((system_size, 3)),\n np.ones(3, int),\n ).flatten(),\n cols=np.einsum('ik,j->ijk',\n np.arange(3 * system_size).reshape((system_size, 3)),\n np.ones(3, int),\n ).flatten(),\n )\n\n def compute(self, inputs, outputs):\n rho = inputs['rho'][0]\n horseshoe_circulations = np.outer(inputs['horseshoe_circulations'], np.ones(3))\n velocities = inputs['force_pts_velocities']\n bound_vecs = inputs['bound_vecs']\n\n # Actually compute the forces by taking the cross of velocities acting\n # at the force points with the bound vortex filament vector.\n outputs['panel_forces'] = \\\n rho * horseshoe_circulations * compute_cross(velocities, bound_vecs)\n\n def compute_partials(self, inputs, partials):\n rho = inputs['rho'][0]\n horseshoe_circulations = np.outer(inputs['horseshoe_circulations'], np.ones(3))\n velocities = inputs['force_pts_velocities']\n bound_vecs = inputs['bound_vecs']\n\n horseshoe_circulations_ones = np.einsum('i,jk->ijk', inputs['horseshoe_circulations'], np.ones((3, 3)))\n\n deriv_array = np.einsum('i,jk->ijk',\n np.ones(self.system_size),\n np.eye(3))\n\n partials['panel_forces', 'rho'] = \\\n (horseshoe_circulations * compute_cross(velocities, bound_vecs)).flatten()\n partials['panel_forces', 'horseshoe_circulations'] = \\\n (rho * compute_cross(velocities, bound_vecs)).flatten()\n partials['panel_forces', 'force_pts_velocities'] = \\\n (rho * horseshoe_circulations_ones * compute_cross_deriv1(deriv_array, bound_vecs)).flatten()\n partials['panel_forces', 'bound_vecs'] = \\\n (rho * horseshoe_circulations_ones * compute_cross_deriv2(velocities, deriv_array)).flatten()\n" ]
[ [ "numpy.arange", "numpy.ones", "numpy.eye", "numpy.zeros" ] ]
MiseryForMe/MDC
[ "470b2db76a71d7e4260de7e39e6cf9a61c80ca2b" ]
[ "evaluate.py" ]
[ "#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom tqdm import tqdm\nimport logging\nimport importlib\nimport argparse\nimport os.path as osp\nimport sys\nimport math\n\nfrom lib.model import DeepLabLargeFOV\nfrom lib.pascal_voc import PascalVoc\nfrom lib.pascal_voc_aug import PascalVoc_Aug\n# from utils.crf import crf\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Train a network')\n parser.add_argument(\n '--cfg',\n dest = 'cfg',\n type = str,\n default = 'config/pascal_voc_aug_multi_scale.py',\n help = 'config file used in training'\n )\n return parser.parse_args()\n\n\n\ndef compute_iou(mask, lb, ignore_lb = (255, )):\n assert mask.shape == lb.shape, 'prediction and gt do not agree in shape'\n classes = set(np.unique(lb).tolist())\n for cls in ignore_lb:\n if cls in classes:\n classes.remove(cls)\n\n iou_cls = []\n for cls in classes:\n gt = lb == cls\n pred = mask == cls\n intersection = np.logical_and(gt, pred)\n union = np.logical_or(gt, pred)\n iou = float(np.sum(intersection)) / float(np.sum(union))\n iou_cls.append(iou)\n return sum(iou_cls) / len(iou_cls)\n\n\ndef eval_model(net, cfg):\n logger = logging.getLogger(__name__)\n ## dataset\n dsval = PascalVoc(cfg, mode='val')\n ## evaluator\n evaluator = MscEval(\n dsval = dsval,\n scales = cfg.test_scales,\n n_classes = cfg.n_classes,\n lb_ignore = cfg.ignore_label,\n flip = cfg.flip,\n crop_size = cfg.crop_size,\n n_workers = 4,\n )\n ## inference\n logger.info('evaluating on standard voc2012 val set')\n mIOU = evaluator(net)\n\n return mIOU\n\n\nclass MscEval(object):\n def __init__(self,\n dsval,\n scales = [0.5, 0.75, 1, 1.25, 1.5, 1.75],\n n_classes = 19,\n lb_ignore = 255,\n flip = True,\n crop_size = 321,\n n_workers = 2,\n *args, **kwargs):\n self.scales = scales\n self.n_classes = n_classes\n self.lb_ignore = lb_ignore\n self.flip = flip\n self.crop_size = crop_size\n ## dataloader\n self.dsval = dsval\n self.net = None\n\n\n def pad_tensor(self, inten, size):\n N, C, H, W = inten.size()\n ## TODO: use zeros\n outten = torch.zeros(N, C, size[0], size[1]).cuda()\n outten.requires_grad = False\n margin_h, margin_w = size[0]-H, size[1]-W\n hst, hed = margin_h//2, margin_h//2+H\n wst, wed = margin_w//2, margin_w//2+W\n outten[:, :, hst:hed, wst:wed] = inten\n return outten, [hst, hed, wst, wed]\n\n\n def eval_chip(self, crop):\n with torch.no_grad():\n out = self.net(crop)\n prob = F.softmax(out, 1)\n if self.flip:\n crop = torch.flip(crop, dims=(3,))\n out = self.net(crop)\n out = torch.flip(out, dims=(3,))\n prob += F.softmax(out, 1)\n prob = torch.exp(prob)\n return prob\n\n\n def crop_eval(self, im):\n cropsize = self.crop_size\n stride_rate = 5/6.\n N, C, H, W = im.size()\n long_size, short_size = (H,W) if H>W else (W,H)\n if long_size < cropsize:\n im, indices = self.pad_tensor(im, (cropsize, cropsize))\n prob = self.eval_chip(im)\n prob = prob[:, :, indices[0]:indices[1], indices[2]:indices[3]]\n else:\n stride = math.ceil(cropsize*stride_rate)\n if short_size < cropsize:\n if H < W:\n im, indices = self.pad_tensor(im, (cropsize, W))\n else:\n im, indices = self.pad_tensor(im, (H, cropsize))\n N, C, H, W = im.size()\n n_x = math.ceil((W-cropsize)/stride)+1\n n_y = math.ceil((H-cropsize)/stride)+1\n prob = torch.zeros(N, self.n_classes, H, W).cuda()\n prob.requires_grad = False\n for iy in range(n_y):\n for ix in range(n_x):\n hed, wed = min(H, stride*iy+cropsize), min(W, stride*ix+cropsize)\n hst, wst = hed-cropsize, wed-cropsize\n chip = im[:, :, hst:hed, wst:wed]\n prob_chip = self.eval_chip(chip)\n prob[:, :, hst:hed, wst:wed] += prob_chip\n if short_size < cropsize:\n prob = prob[:, :, indices[0]:indices[1], indices[2]:indices[3]]\n return prob\n\n\n def scale_crop_eval(self, im, scale):\n N, C, H, W = im.size()\n new_hw = [int(H*scale), int(W*scale)]\n im = F.interpolate(im, new_hw, mode='bilinear', align_corners=True)\n prob = self.crop_eval(im)\n prob = F.interpolate(prob, (H, W), mode='bilinear', align_corners=True)\n return prob\n\n\n def compute_hist(self, pred, lb, lb_ignore=255):\n n_classes = self.n_classes\n keep = np.logical_not(lb==lb_ignore)\n merge = pred[keep] * n_classes + lb[keep]\n hist = np.bincount(merge, minlength=n_classes**2)\n hist = hist.reshape((n_classes, n_classes))\n return hist\n\n def __call__(self, net):\n self.net = net\n ## evaluate\n hist = np.zeros((self.n_classes, self.n_classes), dtype=np.float32)\n for i, (imgs, label) in enumerate(tqdm(self.dsval)):\n N, _, H, W = imgs.size()\n probs = torch.zeros((N, self.n_classes, H, W))\n probs.requires_grad = False\n imgs = imgs.cuda()\n for sc in self.scales:\n prob = self.scale_crop_eval(imgs, sc)\n probs += prob.detach().cpu()\n probs = probs.data.numpy()\n preds = np.argmax(probs, axis=1)\n\n hist_once = self.compute_hist(preds, label)\n hist = hist + hist_once\n IOUs = np.diag(hist) / (np.sum(hist, axis=0)+np.sum(hist, axis=1)-np.diag(hist))\n mIOU = np.mean(IOUs)\n return mIOU\n\n\ndef evaluate(args):\n ## set up logger and parse cfg\n FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'\n logging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout)\n logger = logging.getLogger(__name__)\n spec = importlib.util.spec_from_file_location('mod_cfg', args.cfg)\n mod_cfg = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(mod_cfg)\n cfg = mod_cfg.cfg\n\n ## initialize model\n net = DeepLabLargeFOV(3, cfg.n_classes)\n net.eval()\n net.cuda()\n model_pth = osp.join(cfg.res_pth, 'model_final.pkl')\n net.load_state_dict(torch.load(model_pth))\n\n ## evaluate\n mIOU = eval_model(net, cfg)\n logger.info('iou in whole is: {}'.format(mIOU))\n\n\nif __name__ == \"__main__\":\n args = get_args()\n evaluate(args)\n" ]
[ [ "numpy.logical_or", "numpy.sum", "numpy.bincount", "torch.load", "numpy.zeros", "numpy.diag", "torch.flip", "torch.nn.functional.softmax", "numpy.logical_and", "torch.no_grad", "torch.zeros", "torch.exp", "numpy.argmax", "numpy.logical_not", "numpy.mean", "numpy.unique", "torch.nn.functional.interpolate" ] ]
CaoQiNeng/python-classifier-2021
[ "a6350988e7ecf0453aac2655f5b0d8af1e538bfc" ]
[ "resnet.py" ]
[ "# -*- coding: utf-8 -*-\n'''\nupdate: 2021/5/18 lym\n'''\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport math\nimport torch.utils.model_zoo as model_zoo\nfrom torchsummary import summary\n\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\n 'resnet152']\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed1d.pth',\n}\n\n#Mish - \"Mish: A Self Regularized Non-Monotonic Neural Activation Function\"\n#https://arxiv.org/abs/1908.08681v1\n#implemented for PyTorch / FastAI by lessw2020 \n#github: https://github.com/lessw2020/mish\n\nclass Mish(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n #inlining this saves 1 second per epoch (V100 GPU) vs having a temp x and then returning x(!)\n return x *( torch.tanh(F.softplus(x)))\n\n# or: ELU+init (a=0.54; gain=1.55)\nact_fn = Mish()#nn.ReLU(inplace=True)\n\nclass Attention(nn.Module):\n def __init__(self, feature_dim, step_dim, bias=True, **kwargs):\n super(Attention, self).__init__(**kwargs)\n \n self.supports_masking = True\n\n self.bias = bias\n self.feature_dim = feature_dim\n self.step_dim = step_dim\n self.features_dim = 0\n \n weight = torch.zeros(feature_dim, 1)\n nn.init.kaiming_uniform_(weight)\n self.weight = nn.Parameter(weight)\n \n if bias:\n self.b = nn.Parameter(torch.zeros(step_dim))\n \n def forward(self, x, mask=None):\n feature_dim = self.feature_dim \n step_dim = self.step_dim\n\n eij = torch.mm(\n x.contiguous().view(-1, feature_dim), \n self.weight\n ).view(-1, step_dim)\n \n if self.bias:\n eij = eij + self.b\n \n eij = torch.tanh(eij)\n a = torch.exp(eij)\n \n if mask is not None:\n a = a * mask\n\n a = a / (torch.sum(a, 1, keepdim=True) + 1e-10)\n\n weighted_input = x * torch.unsqueeze(a, -1)\n return torch.sum(weighted_input, 1)\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv1d(in_planes, out_planes, kernel_size=7, stride=stride,\n padding=3, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm1d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm1d(planes)\n self.downsample = downsample\n self.stride = stride\n self.dropout = nn.Dropout(.2)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.dropout(out)\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv1d(inplanes, planes, kernel_size=7, bias=False, padding=3)\n self.bn1 = nn.BatchNorm1d(planes)\n self.conv2 = nn.Conv1d(planes, planes, kernel_size=11, stride=stride,\n padding=5, bias=False)\n self.bn2 = nn.BatchNorm1d(planes)\n self.conv3 = nn.Conv1d(planes, planes * 4, kernel_size=7, bias=False, padding=3)\n self.bn3 = nn.BatchNorm1d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n self.dropout = nn.Dropout(.2)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n out = self.dropout(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, in_channels, block, layers, num_classes=27):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv1d(in_channels, 64, kernel_size=15, stride=2, padding=7, bias=False) #12 6dao lian\n self.bn1 = nn.BatchNorm1d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.avgpool = nn.AdaptiveAvgPool1d(1)\n\n self.lstm = nn.LSTM(80, 512, bidirectional=True, batch_first=True)\n self.attention_layer = Attention(1024, 512)\n\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv1d):\n n = m.kernel_size[0] * m.kernel_size[0] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm1d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv1d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm1d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n # print(x.shape)\n # max_pooled = F.adaptive_max_pool1d(out, 1)\n # avg_pooled = F.adaptive_avg_pool1d(out, 1)\n # out = torch.cat([max_pooled, avg_pooled], dim=1)\n x = F.adaptive_max_pool1d(x, 1)#self.avgpool(x)\n # x,_ = self.lstm(x)\n # x = self.attention_layer(x)\n\n # print(x.shape)\n x = x.view(x.size(0), -1)\n # print(x.shape)\n x = self.fc(x)\n # print('x.shape:', x.shape)\n return x\n\n\ndef resnet18(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\n # if pretrained:\n # model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model\n\n\ndef resnet34(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n # if pretrained:\n # model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model\n\n\n# def resnet50(pretrained=False, **kwargs):\n# \"\"\"Constructs a ResNet-50 model.\n#\n# Args:\n# pretrained (bool): If True, returns a model pre-trained on ImageNet\n# \"\"\"\n# model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\n# if pretrained:\n# print('----------------downloading----------------')\n# model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n# return model\n\ndef resnet50(in_channels, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(in_channels,Bottleneck, [3, 4, 6, 3], **kwargs)\n # if pretrained:\n # print('----------------downloading----------------')\n # model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n\ndef resnet101(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\n # if pretrained:\n # model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\n return model\n\n\ndef resnet152(pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\n # if pretrained:\n # model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))\n return model\n\n\nif __name__ == '__main__':\n\n in_channels = 6\n x = torch.randn(2, in_channels, 72000)\n # x = torch.randn(1, 2560*6, 12)\n # net = resnet18()\n # net = resnet34()\n net = resnet50(in_channels)\n # net = resnet101()\n # net = resnet152()\n y = net(x)\n\n summary(net, (in_channels, 72000))\n\n # print(net)\n print(x.shape)\n print(y.shape)\n" ]
[ [ "torch.nn.functional.softplus", "torch.nn.AdaptiveAvgPool1d", "torch.nn.init.kaiming_uniform_", "torch.nn.Dropout", "torch.nn.BatchNorm1d", "torch.randn", "torch.tanh", "torch.unsqueeze", "torch.nn.MaxPool1d", "torch.nn.LSTM", "torch.nn.Conv1d", "torch.sum", "torch.nn.Linear", "torch.nn.Parameter", "torch.exp", "torch.nn.functional.adaptive_max_pool1d", "torch.nn.Sequential", "torch.zeros", "torch.nn.ReLU" ] ]
kew96/GraphcoreExamples
[ "22dc0d7e3755b0a7f16cdf694c6d10c0f91ee8eb" ]
[ "applications/popart/bert/phased_execution/bert_layers.py" ]
[ "# Copyright (c) 2020 Graphcore Ltd. 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\"\"\"BERT layers.\"\"\"\nimport numpy as np\n\nimport popart\nfrom phased_execution.layers import Dense, Dropout, Norm, Split\nfrom phased_execution.nn import Block, Parameter\n\n__all__ = [\n \"Attention\", \"FeedForward\", \"MaskLM\", \"NextSentencePred\", \"SquadProjection\"\n]\n\n\nclass Attention(Block):\n def __init__(self,\n name: str,\n input_size,\n hidden_size,\n num_heads,\n serialize_matmul,\n available_memory_proportion,\n epsilon,\n dropout,\n dropout_prob,\n attn_dropout,\n attn_dropout_prob,\n micro_batch_size,\n sequence_length,\n dtype,\n task,\n num_mask_tokens,\n split_qkv = False,\n attention_bias = False,\n residual=True,\n prefetch_masks=True,\n use_default_mem_proportion=True,\n mask=None,\n increment_scope=True,\n **kwargs):\n if split_qkv:\n params = [\n Parameter(name='Q',\n shape=[input_size, hidden_size],\n value=None),\n Parameter(name='K',\n shape=[input_size, hidden_size],\n value=None),\n Parameter(name='V',\n shape=[input_size, hidden_size],\n value=None),\n Parameter(name='Out', shape=[hidden_size, input_size], value=None)\n ]\n if attention_bias:\n bias_params = [\n Parameter(name='Q_Bias',\n shape=[hidden_size],\n value=None),\n Parameter(name='K_Bias',\n shape=[hidden_size],\n value=None),\n Parameter(name='V_Bias',\n shape=[hidden_size],\n value=None),\n Parameter(name='Out_Bias', shape=[hidden_size], value=None)\n ]\n params = params + bias_params\n else:\n params = [\n Parameter(name='QKV',\n shape=[input_size, 3 * hidden_size],\n value=None),\n Parameter(name='Out', shape=[hidden_size, input_size], value=None)\n ]\n if attention_bias:\n bias_params = [\n Parameter(name='QKV_Bias',\n shape=[3 * hidden_size],\n value=None),\n Parameter(name='Out_Bias', shape=[hidden_size], value=None)\n ]\n params = params + bias_params\n scope_provider = kwargs['scope_provider']\n super(Attention, self).__init__(params=params,\n scope=scope_provider.get_scope(\n name, 'next' if increment_scope else 'prev'),\n dtype=dtype,\n **kwargs)\n self.num_heads = num_heads\n self.hidden_size = hidden_size\n self.serialize_matmul = serialize_matmul\n self.available_memory_proportion = available_memory_proportion\n self.use_default_mem_proportion = use_default_mem_proportion\n self.split_qkv = split_qkv\n self.attention_bias = attention_bias\n self.micro_batch_size = micro_batch_size\n self.seq_len = sequence_length\n if hidden_size % num_heads != 0:\n raise ValueError('Hidden size must be a multiple of num_heads')\n self.qkv_length = hidden_size // num_heads\n self.dtype = dtype\n self.residual = residual\n self.task = task\n self.num_mask_tokens = num_mask_tokens\n self.mask = mask\n self.prefetch_masks = prefetch_masks\n if prefetch_masks:\n # Mask on chip would cause OOM for batch size 1024, choose off chip instead\n additional_scopes = [self.builder.recomputeOutput(popart.RecomputeType.Checkpoint)]\n self.mask_execution_phase = scope_provider.get_scope('Mask', 'prev').execution_phase % 2\n self.mask_scope = scope_provider.get_scope('Mask',\n self.mask_execution_phase,\n additional_scopes=additional_scopes)\n else:\n self.mask_scope = scope_provider.get_scope('Mask', 'prev')\n\n if self.residual:\n self.norm = Norm(scope_provider.get_scope('Norm', 'prev'), hidden_size,\n epsilon, dtype, **kwargs)\n if dropout:\n self.dropout = Dropout(scope_provider.get_scope('Dropout', 'prev'),\n dropout_prob, **kwargs)\n else:\n self.dropout = lambda x: x\n\n if attn_dropout:\n self.attn_dropout = Dropout(scope_provider.get_scope('AttnDropout', 'prev'),\n attn_dropout_prob, **kwargs)\n else:\n self.attn_dropout = lambda x: x\n\n self.total_execution_phases = self.total_phases()\n\n def attention_mask(self, masks):\n if self.prefetch_masks and (self.mask is not None):\n return self.mask\n\n with self.scope_provider(self.builder, self.mask_scope):\n all_indices_np = np.arange(self.seq_len, dtype=np.uint32)\n all_indices = self.builder.aiOnnx.constant(all_indices_np,\n \"mask_sequence\")\n if self.task == \"PRETRAINING\":\n # Mask tokens mask\n indices_less_than_maskidx = self.builder.aiOnnx.less(\n [all_indices, masks[0]])\n\n indices_greater_than_num_mask_token_np = np.greater_equal(\n all_indices_np, self.num_mask_tokens).astype(np.bool)\n indices_greater_than_num_mask_token = self.builder.aiOnnx.constant(\n indices_greater_than_num_mask_token_np)\n\n mask_tokens_mask = self.builder.aiOnnx.logical_or(\n [indices_less_than_maskidx, indices_greater_than_num_mask_token])\n\n # Sequence mask\n sequence_mask = self.builder.aiOnnx.less(\n [all_indices, masks[1]])\n\n final_mask = self.builder.aiOnnx.logical_and(\n [mask_tokens_mask, sequence_mask])\n else:\n final_mask = self.builder.aiOnnx.less([all_indices, masks[0]])\n\n final_mask = self.builder.aiOnnx.cast(\n [final_mask],\n 'FLOAT' if self.dtype == np.float32 else 'FLOAT16')\n final_mask = self.builder.aiOnnx.sub([\n final_mask,\n self.builder.aiOnnx.constant(np.array(1.0, self.dtype))\n ])\n final_mask = self.builder.aiOnnx.mul([\n final_mask,\n self.builder.aiOnnx.constant(np.array(1000.0, self.dtype))\n ])\n final_mask = self.builder.reshape_const(\n self.builder.aiOnnx, [final_mask],\n [self.micro_batch_size, 1, 1, self.seq_len])\n\n # TODO: This shouldn't be needed. No Variables on this path.\n final_mask = self.builder.customOp(\n opName=\"Detach\",\n opVersion=1,\n domain=\"ai.graphcore\",\n inputs=[final_mask],\n attributes={\"pass_through_creation\": 1})[0]\n self.mask = final_mask\n return final_mask\n\n def dotproduct_attention(self, qkv, masks):\n if self.split_qkv:\n split_qkv = qkv\n else:\n split_qkv = self.builder.aiOnnx.split([qkv],\n num_outputs=3,\n axis=1,\n split=[self.hidden_size] * 3,\n debugContext=\"QKV_Split\")\n\n def extract_heads(tensor, transpose=False):\n comb_shape = [\n self.micro_batch_size, self.seq_len, self.num_heads, self.qkv_length\n ]\n tensor = self.builder.reshape_const(self.builder.aiOnnx, [tensor],\n comb_shape)\n perm = [0, 2, 1, 3] if not transpose else [0, 2, 3, 1]\n return self.builder.aiOnnx.transpose([tensor], perm=perm)\n\n # q = [micro_batch_size * seq_len, hidden_size]\n # kt = [hidden_size, micro_batch_size * seq_len]\n # v = [micro_batch_size * seq_len, hidden_size]\n q, kt, v = [extract_heads(t, i == 1) for i, t in enumerate(split_qkv)]\n\n # Attention calculation\n with self.builder.nameScope('Z'):\n scores = self.builder.aiOnnx.matmul([q, kt], \"AttentionDotProduct\")\n if not self.use_default_mem_proportion:\n self.builder.setAvailableMemoryProportion(\n scores, self.available_memory_proportion)\n\n scale = self.builder.aiOnnx.constant(\n np.array(1 / np.sqrt(self.qkv_length), self.dtype), \"Scale\")\n scores = self.builder.aiOnnx.mul([scores, scale])\n\n if masks:\n mask = self.attention_mask(masks)\n scores = self.builder.aiOnnx.add([scores, mask], \"ApplyMask\")\n\n scores = self.builder.aiOnnx.softmax([scores], axis=-1)\n scores = self.attn_dropout(scores)\n\n # x[micro_batch_size, attention_heads, sequence_length, sequence_length] * v[micro_batch_size, attention_heads, sequence_length, qkv_length]\n z = self.builder.aiOnnx.matmul([scores, v])\n if not self.use_default_mem_proportion:\n self.builder.setAvailableMemoryProportion(\n z, self.available_memory_proportion)\n\n # [micro_batch_size, attention_heads, sequence_length, qkv_length] -> [micro_batch_size, sequence_length, attention_heads, qkv_length]\n z = self.builder.aiOnnx.transpose([z], perm=[0, 2, 1, 3])\n # [micro_batch_size, sequence_length, attention_heads, qkv_length] -> [micro_batch_size*sequence_length, attention_heads * qkv_length]\n z = self.builder.reshape_const(\n self.builder.aiOnnx, [z],\n [self.seq_len * self.micro_batch_size, self.hidden_size])\n return z\n\n def __qkv_mul_subgraph(self, input_x, wt, b=None):\n\n x = self.builder.aiOnnx.matmul([input_x, wt])\n if self.serialize_matmul:\n self.builder.setSerializeMatMul({x}, 'output_channels', 3, True)\n if not self.use_default_mem_proportion:\n self.builder.setAvailableMemoryProportion(\n x, self.available_memory_proportion)\n if self.attention_bias:\n x = self.builder.aiOnnx.add([x, b])\n mul = x\n perm = [1, 0]\n t = self.builder.aiOnnx.transpose([mul], perm=perm)\n return mul\n\n def forward(self, input_x: str, masks: str):\n # Transform input -> query, keys and value\n if self.split_qkv:\n if self.attention_bias:\n q, k, v, projection_weight, q_bias, k_bias, v_bias, projection_bias = [\n param.popart_tensor for param in self.params\n ]\n qt = self.__qkv_mul_subgraph(input_x, q, q_bias)\n kt = self.__qkv_mul_subgraph(input_x, k, k_bias)\n vt = self.__qkv_mul_subgraph(input_x, v, v_bias)\n else:\n q, k, v, projection_weight = [param.popart_tensor for param in self.params]\n qt = self.__qkv_mul_subgraph(input_x, q)\n kt = self.__qkv_mul_subgraph(input_x, k)\n vt = self.__qkv_mul_subgraph(input_x, v)\n qkv = [qt, kt, vt]\n else:\n if self.attention_bias:\n qkv_weight, projection_weight, qkv_bias, projection_bias = [\n param.popart_tensor for param in self.params\n ]\n else:\n qkv_weight, projection_weight = [\n param.popart_tensor for param in self.params\n ]\n qkv = self.builder.aiOnnx.matmul([input_x, qkv_weight],\n 'DenseTransform')\n if self.serialize_matmul:\n self.builder.setSerializeMatMul({qkv}, 'output_channels', 3, True)\n if not self.use_default_mem_proportion:\n self.builder.setAvailableMemoryProportion(\n qkv, self.available_memory_proportion)\n if self.attention_bias:\n qkv = self.builder.aiOnnx.add([qkv, qkv_bias],\n 'DenseTransformBias')\n\n # Self-attention\n x = self.dotproduct_attention(qkv, masks)\n\n # Projection\n x = self.builder.aiOnnx.matmul([x, projection_weight], 'Projection')\n if not self.use_default_mem_proportion:\n self.builder.setAvailableMemoryProportion(\n x, self.available_memory_proportion)\n if self.attention_bias:\n x = self.builder.aiOnnx.add([x, projection_bias], 'ProjectionBias')\n\n if not self.residual:\n return x\n\n # Residual\n x = self.dropout(x)\n x = self.builder.aiOnnx.add([input_x, x], 'Residual')\n x = self.norm(x)\n return x\n\n\nclass FeedForward(Block):\n def __init__(self,\n name,\n input_size,\n ff_size,\n dropout,\n dropout_prob,\n epsilon,\n residual=True,\n intermediate_act_func='gelu',\n alpha=None,\n increment_scope=True,\n serialize_matmul=False,\n use_default_memory_proportion=True,\n available_memory_proportion=None,\n **kwargs):\n scope_provider = kwargs['scope_provider']\n self.apply_dropout = dropout\n scope = scope_provider.get_scope(name, 'next' if increment_scope else 'prev')\n super(FeedForward, self).__init__(params=[], scope=scope, **kwargs)\n self.residual = residual\n\n if serialize_matmul:\n split = Split(dim='output_channels',\n num_splits=ff_size // input_size)\n else:\n split = None\n self.dense1 = Dense(scope_provider.get_scope(\"1\", 'prev'),\n input_size,\n ff_size,\n split=split,\n activation=intermediate_act_func,\n alpha=alpha,\n use_default_memory_proportion=use_default_memory_proportion,\n available_memory_proportion=available_memory_proportion,\n **kwargs)\n if serialize_matmul:\n split = Split(dim='reducing_dim', num_splits=ff_size // input_size)\n else:\n split = None\n self.dense2 = Dense(scope_provider.get_scope(\"2\", \"prev\"),\n ff_size,\n input_size,\n split=split,\n activation=None,\n use_default_memory_proportion=use_default_memory_proportion,\n available_memory_proportion=available_memory_proportion,\n **kwargs)\n if residual:\n if dropout:\n self.dropout = Dropout(scope_provider.get_scope(\"Dropout\", \"prev\"),\n dropout_prob, **kwargs)\n self.norm = Norm(scope_provider.get_scope(\"Norm\", \"prev\"), input_size,\n epsilon, **kwargs)\n self.total_execution_phases = self.total_phases()\n\n def forward(self, input_x):\n x = self.dense1(input_x)\n x = self.dense2(x)\n if not self.residual:\n return x\n if self.apply_dropout:\n x = self.dropout(x)\n x = self.builder.aiOnnx.add([input_x, x])\n x = self.norm(x)\n return x\n\n\nclass MaskLM(Block):\n def __init__(self,\n name,\n vocab_size,\n hidden_size,\n sequence_length,\n micro_batch_size,\n num_mask_tokens,\n projection_weight,\n activation,\n slice_input=True,\n no_cls_layer=False,\n epsilon=None,\n projection_bias=False,\n **kwargs):\n scope_provider = kwargs['scope_provider']\n super(MaskLM, self).__init__(params=[],\n scope=scope_provider.get_scope(name=f'{name}', execution_phase='next'),\n **kwargs)\n self.sequence_len = sequence_length\n self.hidden_size = hidden_size\n self.micro_batch_size = micro_batch_size\n self.vocab_length = vocab_size\n self.num_mask_tokens = num_mask_tokens\n self.slice_input = slice_input\n self.no_cls_layer = no_cls_layer\n if not no_cls_layer:\n scope = scope_provider.get_scope(\"LMPrediction\", self.scope.execution_phase)\n self.pred_head_transform = Dense(scope,\n hidden_size,\n hidden_size,\n activation=activation,\n **kwargs)\n scope = scope_provider.get_scope('LMPrediction/Norm', self.scope.execution_phase)\n self.norm = Norm(scope, hidden_size,\n epsilon, **kwargs)\n\n decoder_scope = scope_provider.get_scope(\"Projection\", self.scope.execution_phase)\n self.decoder = Dense(decoder_scope,\n hidden_size,\n vocab_size,\n split=None,\n activation=None,\n params=[projection_weight, None],\n bias=projection_bias,\n **kwargs)\n self.total_execution_phases = self.total_phases()\n\n def forward(self, x_in):\n if self.slice_input:\n x = self.builder.reshape_const(\n self.builder.aiOnnx, [x_in],\n [self.micro_batch_size, self.sequence_len, self.hidden_size])\n\n x = self.builder.aiOnnxOpset9.slice([x],\n axes=[1],\n starts=[0],\n ends=[self.num_mask_tokens])\n\n x = self.builder.reshape_const(self.builder.aiOnnx, [x],\n [self.micro_batch_size * self.num_mask_tokens, self.hidden_size])\n if not self.no_cls_layer:\n x = self.pred_head_transform(x)\n x = self.norm(x)\n\n else:\n x = x_in\n\n x = self.decoder(x)\n x = self.builder.reshape_const(\n self.builder.aiOnnx, [x],\n [self.micro_batch_size, self.num_mask_tokens, self.vocab_length])\n return x\n\n\nclass NextSentencePred(Block):\n def __init__(self, name, micro_batch_size, sequence_length, hidden_size, cls_token_pos,\n **kwargs):\n scope_provider = kwargs['scope_provider']\n additional_scopes = [kwargs['builder'].outlineAttributes({'outline_scope': 'NSP'})]\n scope = scope_provider.get_scope(name, execution_phase='next', additional_scopes=additional_scopes)\n params = []\n super().__init__(scope, params, **kwargs)\n self.micro_batch_size = micro_batch_size\n self.sequence_length = sequence_length\n self.hidden_size = hidden_size\n self.cls_token_pos = cls_token_pos\n pooler_scope = scope_provider.get_scope(\"Pool\", execution_phase=self.scope.execution_phase)\n self.pooler = Dense(scope=pooler_scope,\n input_dim=hidden_size,\n output_dim=hidden_size,\n split=None,\n activation='tanh',\n **kwargs)\n classifier_scope = scope_provider.get_scope(\"Classifier\",\n execution_phase=self.scope.execution_phase)\n self.classifier = Dense(scope=classifier_scope,\n input_dim=hidden_size,\n output_dim=2,\n split=None,\n **kwargs)\n self.total_execution_phases = self.total_phases()\n\n def forward(self, x_in):\n x = self.builder.reshape_const(self.builder.aiOnnx, [x_in],\n [self.micro_batch_size, self.sequence_length, self.hidden_size])\n\n x = self.builder.aiOnnxOpset9.slice([x],\n axes=[1],\n starts=[self.cls_token_pos],\n ends=[self.cls_token_pos + 1])\n # This reshape is doing the job of a squeeze, but allows for in-place\n # operation.\n x = self.builder.reshape_const(self.builder.aiOnnx, [x],\n [self.micro_batch_size, self.hidden_size])\n x = self.pooler(x)\n return self.classifier(x)\n\n\nclass SquadProjection(Block):\n def __init__(self, name, micro_batch_size, sequence_length, hidden_size,\n **kwargs):\n scope_provider = kwargs['scope_provider']\n scope = scope_provider.get_scope(name, execution_phase='next')\n params = []\n super().__init__(scope, params, **kwargs)\n self.micro_batch_size = micro_batch_size\n self.sequence_length = sequence_length\n self.hidden_size = hidden_size\n classifier_scope = scope_provider.get_scope(name='', execution_phase=self.scope.execution_phase)\n self.classifier = Dense(scope=classifier_scope,\n input_dim=hidden_size,\n output_dim=2,\n split=None,\n **kwargs)\n self.total_execution_phases = self.total_phases()\n\n def forward(self, x_in):\n x = self.classifier(x_in)\n\n start_logits = self.builder.aiOnnxOpset9.slice(\n [x], axes=[1], starts=[0], ends=[1], debugContext='slice_ans_start')\n end_logits = self.builder.aiOnnxOpset9.slice(\n [x], axes=[1], starts=[1], ends=[2], debugContext='slice_ans_end')\n\n start_logits = self.builder.reshape_const(\n self.builder.aiOnnx, [start_logits],\n [self.micro_batch_size, self.sequence_length],\n debugContext=\"answer_start\")\n end_logits = self.builder.reshape_const(\n self.builder.aiOnnx, [end_logits],\n [self.micro_batch_size, self.sequence_length],\n debugContext=\"answer_end\")\n\n return start_logits, end_logits\n" ]
[ [ "numpy.arange", "numpy.sqrt", "numpy.array", "numpy.greater_equal" ] ]
zkneupper/audio
[ "1f136671b84071a2fe1d5b762df64f3a76310c31" ]
[ "examples/pipeline_wav2letter/main.py" ]
[ "import argparse\nimport logging\nimport os\nimport string\nfrom datetime import datetime\nfrom time import time\n\nimport torch\nimport torchaudio\nfrom torch.optim import SGD, Adadelta, Adam, AdamW\nfrom torch.optim.lr_scheduler import ExponentialLR, ReduceLROnPlateau\nfrom torch.utils.data import DataLoader\nfrom torchaudio.datasets.utils import bg_iterator\nfrom torchaudio.models.wav2letter import Wav2Letter\n\nfrom ctc_decoders import GreedyDecoder\nfrom datasets import collate_factory, split_process_librispeech\nfrom languagemodels import LanguageModel\nfrom metrics import levenshtein_distance\nfrom transforms import Normalize, UnsqueezeFirst\nfrom utils import MetricLogger, count_parameters, save_checkpoint\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--type\",\n metavar=\"T\",\n default=\"mfcc\",\n choices=[\"waveform\", \"mfcc\"],\n help=\"input type for model\",\n )\n parser.add_argument(\n \"--freq-mask\",\n default=0,\n type=int,\n metavar=\"N\",\n help=\"maximal width of frequency mask\",\n )\n parser.add_argument(\n \"--win-length\",\n default=400,\n type=int,\n metavar=\"N\",\n help=\"width of spectrogram window\",\n )\n parser.add_argument(\n \"--hop-length\",\n default=160,\n type=int,\n metavar=\"N\",\n help=\"width of spectrogram window\",\n )\n parser.add_argument(\n \"--time-mask\",\n default=0,\n type=int,\n metavar=\"N\",\n help=\"maximal width of time mask\",\n )\n parser.add_argument(\n \"--workers\",\n default=0,\n type=int,\n metavar=\"N\",\n help=\"number of data loading workers\",\n )\n parser.add_argument(\n \"--checkpoint\",\n default=\"\",\n type=str,\n metavar=\"PATH\",\n help=\"path to latest checkpoint\",\n )\n parser.add_argument(\n \"--epochs\",\n default=200,\n type=int,\n metavar=\"N\",\n help=\"number of total epochs to run\",\n )\n parser.add_argument(\n \"--start-epoch\", default=0, type=int, metavar=\"N\", help=\"manual epoch number\"\n )\n parser.add_argument(\n \"--reduce-lr-valid\",\n action=\"store_true\",\n help=\"reduce learning rate based on validation loss\",\n )\n parser.add_argument(\n \"--normalize\", action=\"store_true\", help=\"normalize model input\"\n )\n parser.add_argument(\n \"--progress-bar\", action=\"store_true\", help=\"use progress bar while training\"\n )\n parser.add_argument(\n \"--decoder\",\n metavar=\"D\",\n default=\"greedy\",\n choices=[\"greedy\"],\n help=\"decoder to use\",\n )\n parser.add_argument(\n \"--batch-size\", default=128, type=int, metavar=\"N\", help=\"mini-batch size\"\n )\n parser.add_argument(\n \"--n-bins\",\n default=13,\n type=int,\n metavar=\"N\",\n help=\"number of bins in transforms\",\n )\n parser.add_argument(\n \"--optimizer\",\n metavar=\"OPT\",\n default=\"adadelta\",\n choices=[\"sgd\", \"adadelta\", \"adam\", \"adamw\"],\n help=\"optimizer to use\",\n )\n parser.add_argument(\n \"--scheduler\",\n metavar=\"S\",\n default=\"reduceonplateau\",\n choices=[\"exponential\", \"reduceonplateau\"],\n help=\"optimizer to use\",\n )\n parser.add_argument(\n \"--learning-rate\",\n default=0.6,\n type=float,\n metavar=\"LR\",\n help=\"initial learning rate\",\n )\n parser.add_argument(\n \"--gamma\",\n default=0.99,\n type=float,\n metavar=\"GAMMA\",\n help=\"learning rate exponential decay constant\",\n )\n parser.add_argument(\n \"--momentum\", default=0.8, type=float, metavar=\"M\", help=\"momentum\"\n )\n parser.add_argument(\n \"--weight-decay\", default=1e-5, type=float, metavar=\"W\", help=\"weight decay\"\n )\n parser.add_argument(\"--eps\", metavar=\"EPS\", type=float, default=1e-8)\n parser.add_argument(\"--rho\", metavar=\"RHO\", type=float, default=0.95)\n parser.add_argument(\"--clip-grad\", metavar=\"NORM\", type=float, default=0.0)\n parser.add_argument(\n \"--dataset-root\",\n type=str,\n help=\"specify dataset root folder\",\n )\n parser.add_argument(\n \"--dataset-folder-in-archive\",\n type=str,\n help=\"specify dataset folder in archive\",\n )\n parser.add_argument(\n \"--dataset-train\",\n default=[\"train-clean-100\"],\n nargs=\"+\",\n type=str,\n help=\"select which part of librispeech to train with\",\n )\n parser.add_argument(\n \"--dataset-valid\",\n default=[\"dev-clean\"],\n nargs=\"+\",\n type=str,\n help=\"select which part of librispeech to validate with\",\n )\n parser.add_argument(\n \"--distributed\", action=\"store_true\", help=\"enable DistributedDataParallel\"\n )\n parser.add_argument(\"--seed\", type=int, default=0, help=\"random seed\")\n parser.add_argument(\n \"--world-size\", type=int, default=8, help=\"the world size to initiate DPP\"\n )\n parser.add_argument(\"--jit\", action=\"store_true\", help=\"if used, model is jitted\")\n\n args = parser.parse_args()\n logging.info(args)\n return args\n\n\ndef setup_distributed(rank, world_size):\n os.environ[\"MASTER_ADDR\"] = \"localhost\"\n os.environ[\"MASTER_PORT\"] = \"12355\"\n\n # initialize the process group\n torch.distributed.init_process_group(\"nccl\", rank=rank, world_size=world_size)\n\n\ndef model_length_function(tensor):\n if tensor.shape[1] == 1:\n # waveform mode\n return int(tensor.shape[0]) // 160 // 2 + 1\n return int(tensor.shape[0]) // 2 + 1\n\n\ndef compute_error_rates(outputs, targets, decoder, language_model, metric):\n output = outputs.transpose(0, 1).to(\"cpu\")\n output = decoder(output)\n\n # Compute CER\n\n output = language_model.decode(output.tolist())\n target = language_model.decode(targets.tolist())\n\n print_length = 20\n for i in range(2):\n # Print a few examples\n output_print = output[i].ljust(print_length)[:print_length]\n target_print = target[i].ljust(print_length)[:print_length]\n logging.info(\"Target: %s Output: %s\", target_print, output_print)\n\n cers = [levenshtein_distance(t, o) for t, o in zip(target, output)]\n cers = sum(cers)\n n = sum(len(t) for t in target)\n metric[\"batch char error\"] = cers\n metric[\"batch char total\"] = n\n metric[\"batch char error rate\"] = cers / n\n metric[\"epoch char error\"] += cers\n metric[\"epoch char total\"] += n\n metric[\"epoch char error rate\"] = metric[\"epoch char error\"] / metric[\"epoch char total\"]\n\n # Compute WER\n\n output = [o.split(language_model.char_space) for o in output]\n target = [t.split(language_model.char_space) for t in target]\n\n wers = [levenshtein_distance(t, o) for t, o in zip(target, output)]\n wers = sum(wers)\n n = sum(len(t) for t in target)\n metric[\"batch word error\"] = wers\n metric[\"batch word total\"] = n\n metric[\"batch word error rate\"] = wers / n\n metric[\"epoch word error\"] += wers\n metric[\"epoch word total\"] += n\n metric[\"epoch word error rate\"] = metric[\"epoch word error\"] / metric[\"epoch word total\"]\n\n\ndef train_one_epoch(\n model,\n criterion,\n optimizer,\n scheduler,\n data_loader,\n decoder,\n language_model,\n device,\n epoch,\n clip_grad,\n disable_logger=False,\n reduce_lr_on_plateau=False,\n):\n\n model.train()\n\n metric = MetricLogger(\"train\", disable=disable_logger)\n metric[\"epoch\"] = epoch\n\n for inputs, targets, tensors_lengths, target_lengths in bg_iterator(\n data_loader, maxsize=2\n ):\n\n start = time()\n inputs = inputs.to(device, non_blocking=True)\n targets = targets.to(device, non_blocking=True)\n\n # keep batch first for data parallel\n outputs = model(inputs).transpose(-1, -2).transpose(0, 1)\n\n # CTC\n # outputs: input length, batch size, number of classes (including blank)\n # targets: batch size, max target length\n # input_lengths: batch size\n # target_lengths: batch size\n\n loss = criterion(outputs, targets, tensors_lengths, target_lengths)\n\n optimizer.zero_grad()\n loss.backward()\n\n if clip_grad > 0:\n metric[\"gradient\"] = torch.nn.utils.clip_grad_norm_(\n model.parameters(), clip_grad\n )\n\n optimizer.step()\n\n compute_error_rates(outputs, targets, decoder, language_model, metric)\n\n try:\n metric[\"lr\"] = scheduler.get_last_lr()[0]\n except AttributeError:\n metric[\"lr\"] = optimizer.param_groups[0][\"lr\"]\n\n metric[\"batch size\"] = len(inputs)\n metric[\"n_channel\"] = inputs.shape[1]\n metric[\"n_time\"] = inputs.shape[-1]\n metric[\"dataset length\"] += metric[\"batch size\"]\n metric[\"iteration\"] += 1\n metric[\"loss\"] = loss.item()\n metric[\"cumulative loss\"] += metric[\"loss\"]\n metric[\"average loss\"] = metric[\"cumulative loss\"] / metric[\"iteration\"]\n metric[\"iteration time\"] = time() - start\n metric[\"epoch time\"] += metric[\"iteration time\"]\n metric()\n\n if reduce_lr_on_plateau and isinstance(scheduler, ReduceLROnPlateau):\n scheduler.step(metric[\"average loss\"])\n elif not isinstance(scheduler, ReduceLROnPlateau):\n scheduler.step()\n\n\ndef evaluate(\n model,\n criterion,\n data_loader,\n decoder,\n language_model,\n device,\n epoch,\n disable_logger=False,\n):\n\n with torch.no_grad():\n\n model.eval()\n start = time()\n metric = MetricLogger(\"validation\", disable=disable_logger)\n metric[\"epoch\"] = epoch\n\n for inputs, targets, tensors_lengths, target_lengths in bg_iterator(\n data_loader, maxsize=2\n ):\n\n inputs = inputs.to(device, non_blocking=True)\n targets = targets.to(device, non_blocking=True)\n\n # keep batch first for data parallel\n outputs = model(inputs).transpose(-1, -2).transpose(0, 1)\n\n # CTC\n # outputs: input length, batch size, number of classes (including blank)\n # targets: batch size, max target length\n # input_lengths: batch size\n # target_lengths: batch size\n\n metric[\"cumulative loss\"] += criterion(\n outputs, targets, tensors_lengths, target_lengths\n ).item()\n\n metric[\"dataset length\"] += len(inputs)\n metric[\"iteration\"] += 1\n\n compute_error_rates(outputs, targets, decoder, language_model, metric)\n\n metric[\"average loss\"] = metric[\"cumulative loss\"] / metric[\"iteration\"]\n metric[\"validation time\"] = time() - start\n metric()\n\n return metric[\"average loss\"]\n\n\ndef main(rank, args):\n\n # Distributed setup\n\n if args.distributed:\n setup_distributed(rank, args.world_size)\n\n not_main_rank = args.distributed and rank != 0\n\n logging.info(\"Start time: %s\", datetime.now())\n\n # Explicitly set seed to make sure models created in separate processes\n # start from same random weights and biases\n torch.manual_seed(args.seed)\n\n # Empty CUDA cache\n torch.cuda.empty_cache()\n\n # Change backend for flac files\n torchaudio.set_audio_backend(\"soundfile\")\n\n # Transforms\n\n melkwargs = {\n \"n_fft\": args.win_length,\n \"n_mels\": args.n_bins,\n \"hop_length\": args.hop_length,\n }\n\n sample_rate_original = 16000\n\n if args.type == \"mfcc\":\n transforms = torch.nn.Sequential(\n torchaudio.transforms.MFCC(\n sample_rate=sample_rate_original,\n n_mfcc=args.n_bins,\n melkwargs=melkwargs,\n ),\n )\n num_features = args.n_bins\n elif args.type == \"waveform\":\n transforms = torch.nn.Sequential(UnsqueezeFirst())\n num_features = 1\n else:\n raise ValueError(\"Model type not supported\")\n\n if args.normalize:\n transforms = torch.nn.Sequential(transforms, Normalize())\n\n augmentations = torch.nn.Sequential()\n if args.freq_mask:\n augmentations = torch.nn.Sequential(\n augmentations,\n torchaudio.transforms.FrequencyMasking(freq_mask_param=args.freq_mask),\n )\n if args.time_mask:\n augmentations = torch.nn.Sequential(\n augmentations,\n torchaudio.transforms.TimeMasking(time_mask_param=args.time_mask),\n )\n\n # Text preprocessing\n\n char_blank = \"*\"\n char_space = \" \"\n char_apostrophe = \"'\"\n labels = char_blank + char_space + char_apostrophe + string.ascii_lowercase\n language_model = LanguageModel(labels, char_blank, char_space)\n\n # Dataset\n\n training, validation = split_process_librispeech(\n [args.dataset_train, args.dataset_valid],\n [transforms, transforms],\n language_model,\n root=args.dataset_root,\n folder_in_archive=args.dataset_folder_in_archive,\n )\n\n # Decoder\n\n if args.decoder == \"greedy\":\n decoder = GreedyDecoder()\n else:\n raise ValueError(\"Selected decoder not supported\")\n\n # Model\n\n model = Wav2Letter(\n num_classes=language_model.length,\n input_type=args.type,\n num_features=num_features,\n )\n\n if args.jit:\n model = torch.jit.script(model)\n\n if args.distributed:\n n = torch.cuda.device_count() // args.world_size\n devices = list(range(rank * n, (rank + 1) * n))\n model = model.to(devices[0])\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=devices)\n else:\n devices = [\"cuda\" if torch.cuda.is_available() else \"cpu\"]\n model = model.to(devices[0], non_blocking=True)\n model = torch.nn.DataParallel(model)\n\n n = count_parameters(model)\n logging.info(\"Number of parameters: %s\", n)\n\n # Optimizer\n\n if args.optimizer == \"adadelta\":\n optimizer = Adadelta(\n model.parameters(),\n lr=args.learning_rate,\n weight_decay=args.weight_decay,\n eps=args.eps,\n rho=args.rho,\n )\n elif args.optimizer == \"sgd\":\n optimizer = SGD(\n model.parameters(),\n lr=args.learning_rate,\n momentum=args.momentum,\n weight_decay=args.weight_decay,\n )\n elif args.optimizer == \"adam\":\n optimizer = Adam(\n model.parameters(),\n lr=args.learning_rate,\n momentum=args.momentum,\n weight_decay=args.weight_decay,\n )\n elif args.optimizer == \"adamw\":\n optimizer = AdamW(\n model.parameters(),\n lr=args.learning_rate,\n momentum=args.momentum,\n weight_decay=args.weight_decay,\n )\n else:\n raise ValueError(\"Selected optimizer not supported\")\n\n if args.scheduler == \"exponential\":\n scheduler = ExponentialLR(optimizer, gamma=args.gamma)\n elif args.scheduler == \"reduceonplateau\":\n scheduler = ReduceLROnPlateau(optimizer, patience=10, threshold=1e-3)\n else:\n raise ValueError(\"Selected scheduler not supported\")\n\n criterion = torch.nn.CTCLoss(\n blank=language_model.mapping[char_blank], zero_infinity=False\n )\n\n # Data Loader\n\n collate_fn_train = collate_factory(model_length_function, augmentations)\n collate_fn_valid = collate_factory(model_length_function)\n\n loader_training_params = {\n \"num_workers\": args.workers,\n \"pin_memory\": True,\n \"shuffle\": True,\n \"drop_last\": True,\n }\n loader_validation_params = loader_training_params.copy()\n loader_validation_params[\"shuffle\"] = False\n\n loader_training = DataLoader(\n training,\n batch_size=args.batch_size,\n collate_fn=collate_fn_train,\n **loader_training_params,\n )\n loader_validation = DataLoader(\n validation,\n batch_size=args.batch_size,\n collate_fn=collate_fn_valid,\n **loader_validation_params,\n )\n\n # Setup checkpoint\n\n best_loss = 1.0\n\n load_checkpoint = args.checkpoint and os.path.isfile(args.checkpoint)\n\n if args.distributed:\n torch.distributed.barrier()\n\n if load_checkpoint:\n logging.info(\"Checkpoint: loading %s\", args.checkpoint)\n checkpoint = torch.load(args.checkpoint)\n\n args.start_epoch = checkpoint[\"epoch\"]\n best_loss = checkpoint[\"best_loss\"]\n\n model.load_state_dict(checkpoint[\"state_dict\"])\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n scheduler.load_state_dict(checkpoint[\"scheduler\"])\n\n logging.info(\n \"Checkpoint: loaded '%s' at epoch %s\", args.checkpoint, checkpoint[\"epoch\"]\n )\n else:\n logging.info(\"Checkpoint: not found\")\n\n save_checkpoint(\n {\n \"epoch\": args.start_epoch,\n \"state_dict\": model.state_dict(),\n \"best_loss\": best_loss,\n \"optimizer\": optimizer.state_dict(),\n \"scheduler\": scheduler.state_dict(),\n },\n False,\n args.checkpoint,\n not_main_rank,\n )\n\n if args.distributed:\n torch.distributed.barrier()\n\n torch.autograd.set_detect_anomaly(False)\n\n for epoch in range(args.start_epoch, args.epochs):\n\n logging.info(\"Epoch: %s\", epoch)\n\n train_one_epoch(\n model,\n criterion,\n optimizer,\n scheduler,\n loader_training,\n decoder,\n language_model,\n devices[0],\n epoch,\n args.clip_grad,\n not_main_rank,\n not args.reduce_lr_valid,\n )\n\n loss = evaluate(\n model,\n criterion,\n loader_validation,\n decoder,\n language_model,\n devices[0],\n epoch,\n not_main_rank,\n )\n\n if args.reduce_lr_valid and isinstance(scheduler, ReduceLROnPlateau):\n scheduler.step(loss)\n\n is_best = loss < best_loss\n best_loss = min(loss, best_loss)\n save_checkpoint(\n {\n \"epoch\": epoch + 1,\n \"state_dict\": model.state_dict(),\n \"best_loss\": best_loss,\n \"optimizer\": optimizer.state_dict(),\n \"scheduler\": scheduler.state_dict(),\n },\n is_best,\n args.checkpoint,\n not_main_rank,\n )\n\n logging.info(\"End time: %s\", datetime.now())\n\n if args.distributed:\n torch.distributed.destroy_process_group()\n\n\ndef spawn_main(main, args):\n if args.distributed:\n torch.multiprocessing.spawn(\n main, args=(args,), nprocs=args.world_size, join=True\n )\n else:\n main(0, args)\n\n\nif __name__ == \"__main__\":\n\n logging.basicConfig(level=logging.INFO)\n args = parse_args()\n spawn_main(main, args)\n" ]
[ [ "torch.utils.data.DataLoader", "torch.jit.script", "torch.optim.lr_scheduler.ExponentialLR", "torch.no_grad", "torch.cuda.is_available", "torch.optim.lr_scheduler.ReduceLROnPlateau", "torch.cuda.empty_cache", "torch.distributed.init_process_group", "torch.cuda.device_count", "torch.nn.DataParallel", "torch.load", "torch.multiprocessing.spawn", "torch.manual_seed", "torch.distributed.barrier", "torch.nn.parallel.DistributedDataParallel", "torch.nn.CTCLoss", "torch.nn.Sequential", "torch.autograd.set_detect_anomaly", "torch.distributed.destroy_process_group" ] ]
EnergyModels/estorage
[ "0f84c87632dba1ff0564ffb68f59ece314f67022" ]
[ "estorage/archive/state.py" ]
[ "from CoolProp.CoolProp import PropsSI\nimport pandas as pd\n\n\nclass State:\n self.fluid = T\n self.T = T\n self.p = p\n self.h = PropsSI('H', 'T', T, 'P', p, fluid)\n self.s = PropsSI('S', 'T', T, 'P', p, fluid)\n self.D = PropsSI('D', 'T', T, 'P', p, fluid)\n\n\nclass Flow(State):\n self.m_dot = T\n\ndef def_state_init(fluid):\n\n # Standard temperature and preussre\n T = 273.15\n p = 101325.\n\n state = pd.Series(index=['fluid','T','p','h','s','D'])\n\n state.fluid = fluid\n state.T = T\n state.p = p\n state.h = PropsSI('H', 'T', T, 'P', p, fluid)\n state.s = PropsSI('S', 'T', T, 'P', p, fluid)\n state.D = PropsSI('D', 'T', T, 'P', p, fluid)\n\n return state\n\ndef def_state_tp(fluid, T, p):\n\n state = pd.Series(index=['fluid','T','p','h','s','D'])\n\n state.fluid = fluid\n state.T = T\n state.p = p\n state.h = PropsSI('H', 'T', T, 'P', p, fluid)\n state.s = PropsSI('S', 'T', T, 'P', p, fluid)\n state.D = PropsSI('D', 'T', T, 'P', p, fluid)\n\n return state\n\n\ndef def_state_ph(fluid, p, h):\n state = pd.Series(index=['fluid', 'T', 'p', 'h', 's','D'])\n\n state.fluid = fluid\n state.T = PropsSI('S', 'P', p, 'H', h, fluid)\n state.p = p\n state.h = h\n state.s = PropsSI('S', 'P', p, 'H', h, fluid)\n state.D = PropsSI('D', 'P', p, 'H', h, fluid)\n\n return state\n\n\ndef def_state_ps(fluid, p, s):\n state = pd.Series(index=['fluid', 'T', 'p', 'h', 's','D'])\n\n state.fluid = fluid\n state.T = PropsSI('H', 'P', p, 'S', s, fluid)\n state.p = p\n state.h = PropsSI('H', 'P', p, 'S', s, fluid)\n state.s = s\n state.D = PropsSI('D', 'P', p, 'S', s, fluid)\n\n return state\n" ]
[ [ "pandas.Series" ] ]
kerwinxu/rqalpha_local
[ "f90da95085df91706ebba8fc905b4cdc85492b11" ]
[ "rqalpha/mod/rqalpha_mod_sys_analyser/plot.py" ]
[ "# -*- coding: utf-8 -*-\n#\n# Last Change: 2018-01-09 09:24:03\n# Copyright 2017 Ricequant, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport rqalpha\nfrom rqalpha.utils.logger import system_log\nfrom rqalpha.utils.i18n import gettext\n\n\ndef plot_result(result_dict, show_windows=True, savefile=None):\n import os\n from matplotlib import rcParams, gridspec, ticker, image as mpimg, pyplot as plt\n from matplotlib.font_manager import findfont, FontProperties\n import numpy as np\n\n rcParams['font.family'] = 'sans-serif'\n rcParams['font.sans-serif'] = [\n u'SimHei',\n u'Microsoft Yahei',\n u'Heiti SC',\n u'Heiti TC',\n u'STHeiti',\n u'WenQuanYi Zen Hei',\n u'WenQuanYi Micro Hei',\n u\"文泉驿微米黑\",\n ] + rcParams['font.sans-serif']\n rcParams['axes.unicode_minus'] = False\n\n use_chinese_fonts = True\n font = findfont(FontProperties(family=['sans-serif']))\n if \"/matplotlib/\" in font:\n use_chinese_fonts = False\n system_log.warn(\"Missing Chinese fonts. Fallback to English.\")\n\n summary = result_dict[\"summary\"]\n\n title = summary['strategy_file']\n\n portfolio = result_dict[\"portfolio\"]\n benchmark_portfolio = result_dict.get(\"benchmark_portfolio\")\n\n index = portfolio.index\n\n # maxdrawdown\n portfolio_value = portfolio.unit_net_value * portfolio.units\n xs = portfolio_value.values\n rt = portfolio.unit_net_value.values\n max_dd_end = np.argmax(np.maximum.accumulate(xs) / xs)\n if max_dd_end == 0:\n max_dd_end = len(xs) - 1\n max_dd_start = np.argmax(xs[:max_dd_end]) if max_dd_end > 0 else 0\n\n # maxdrawdown duration\n al_cum = np.maximum.accumulate(xs)\n a = np.unique(al_cum, return_counts=True)\n start_idx = np.argmax(a[1])\n m = a[0][start_idx]\n al_cum_array = np.where(al_cum == m)\n max_ddd_start_day = al_cum_array[0][0]\n max_ddd_end_day = al_cum_array[0][-1]\n\n max_dd_info = \"MaxDD {}~{}, {} days\".format(index[max_dd_start], index[max_dd_end],\n (index[max_dd_end] - index[max_dd_start]).days)\n max_dd_info += \"\\nMaxDDD {}~{}, {} days\".format(index[max_ddd_start_day], index[max_ddd_end_day],\n (index[max_ddd_end_day] - index[max_ddd_start_day]).days)\n\n plt.style.use('ggplot')\n\n red = \"#aa4643\"\n blue = \"#4572a7\"\n black = \"#000000\"\n\n plots_area_size = 0\n if \"plots\" in result_dict:\n plots_area_size = 5\n\n figsize = (18, 6 + int(plots_area_size * 0.9))\n plt.figure(title, figsize=figsize)\n max_height = 10 + plots_area_size\n gs = gridspec.GridSpec(max_height, 8)\n\n # draw logo\n ax = plt.subplot(gs[:3, -1:])\n ax.axis(\"off\")\n filename = os.path.join(os.path.dirname(os.path.realpath(rqalpha.__file__)), \"resource\")\n filename = os.path.join(filename, \"ricequant-logo.png\")\n img = mpimg.imread(filename)\n ax.imshow(img, interpolation=\"nearest\")\n ax.autoscale_view()\n\n # draw risk and portfolio\n\n font_size = 12\n value_font_size = 11\n label_height, value_height = 0.8, 0.6\n label_height2, value_height2 = 0.35, 0.15\n\n def _(txt):\n return gettext(txt) if use_chinese_fonts else txt\n\n fig_data = [\n (0.00, label_height, value_height, _(u\"Total Returns\"), \"{0:.3%}\".format(summary[\"total_returns\"]), red, black),\n (0.15, label_height, value_height, _(u\"Annual Returns\"), \"{0:.3%}\".format(summary[\"annualized_returns\"]), red, black),\n (0.00, label_height2, value_height2, _(u\"Benchmark Returns\"), \"{0:.3%}\".format(summary.get(\"benchmark_total_returns\", 0)), blue,\n black),\n (0.15, label_height2, value_height2, _(u\"Benchmark Annual\"), \"{0:.3%}\".format(summary.get(\"benchmark_annualized_returns\", 0)),\n blue, black),\n\n (0.30, label_height, value_height, _(u\"Alpha\"), \"{0:.4}\".format(summary[\"alpha\"]), black, black),\n (0.40, label_height, value_height, _(u\"Beta\"), \"{0:.4}\".format(summary[\"beta\"]), black, black),\n (0.55, label_height, value_height, _(u\"Sharpe\"), \"{0:.4}\".format(summary[\"sharpe\"]), black, black),\n (0.70, label_height, value_height, _(u\"Sortino\"), \"{0:.4}\".format(summary[\"sortino\"]), black, black),\n (0.85, label_height, value_height, _(u\"Information Ratio\"), \"{0:.4}\".format(summary[\"information_ratio\"]), black, black),\n\n (0.30, label_height2, value_height2, _(u\"Volatility\"), \"{0:.4}\".format(summary[\"volatility\"]), black, black),\n (0.40, label_height2, value_height2, _(u\"MaxDrawdown\"), \"{0:.3%}\".format(summary[\"max_drawdown\"]), black, black),\n (0.55, label_height2, value_height2, _(u\"Tracking Error\"), \"{0:.4}\".format(summary[\"tracking_error\"]), black, black),\n (0.70, label_height2, value_height2, _(u\"Downside Risk\"), \"{0:.4}\".format(summary[\"downside_risk\"]), black, black),\n ]\n\n ax = plt.subplot(gs[:3, :-1])\n ax.axis(\"off\")\n for x, y1, y2, label, value, label_color, value_color in fig_data:\n ax.text(x, y1, label, color=label_color, fontsize=font_size)\n ax.text(x, y2, value, color=value_color, fontsize=value_font_size)\n for x, y1, y2, label, value, label_color, value_color in [\n (0.85, label_height2, value_height2, _(u\"MaxDD/MaxDDD\"), max_dd_info, black, black)]:\n ax.text(x, y1, label, color=label_color, fontsize=font_size)\n ax.text(x, y2, value, color=value_color, fontsize=8)\n\n # strategy vs benchmark\n ax = plt.subplot(gs[4:10, :])\n\n ax.get_xaxis().set_minor_locator(ticker.AutoMinorLocator())\n ax.get_yaxis().set_minor_locator(ticker.AutoMinorLocator())\n ax.grid(b=True, which='minor', linewidth=.2)\n ax.grid(b=True, which='major', linewidth=1)\n\n # plot two lines\n ax.plot(portfolio[\"unit_net_value\"] - 1.0, label=_(u\"strategy\"), alpha=1, linewidth=2, color=red)\n if benchmark_portfolio is not None:\n ax.plot(benchmark_portfolio[\"unit_net_value\"] - 1.0, label=_(u\"benchmark\"), alpha=1, linewidth=2, color=blue)\n\n # plot MaxDD/MaxDDD\n ax.plot([index[max_dd_end], index[max_dd_start]], [rt[max_dd_end] - 1.0, rt[max_dd_start] - 1.0],\n 'v', color='Green', markersize=8, alpha=.7, label=_(u\"MaxDrawdown\"))\n ax.plot([index[max_ddd_start_day], index[max_ddd_end_day]],\n [rt[max_ddd_start_day] - 1.0, rt[max_ddd_end_day] - 1.0], 'D', color='Blue', markersize=8, alpha=.7,\n label=_(u\"MaxDDD\"))\n\n # place legend\n leg = plt.legend(loc=\"best\")\n leg.get_frame().set_alpha(0.5)\n\n # manipulate axis\n vals = ax.get_yticks()\n ax.set_yticklabels(['{:3.2f}%'.format(x * 100) for x in vals])\n\n # plot user plots\n if \"plots\" in result_dict:\n plots_df = result_dict[\"plots\"]\n\n ax2 = plt.subplot(gs[11:, :])\n for column in plots_df.columns:\n ax2.plot(plots_df[column], label=column)\n\n leg = plt.legend(loc=\"best\")\n leg.get_frame().set_alpha(0.5)\n\n if show_windows:\n plt.show()\n\n if savefile:\n fnmame = savefile\n if os.path.isdir(savefile):\n fnmame = os.path.join(savefile, \"{}.png\".format(summary[\"strategy_name\"]))\n plt.savefig(fnmame, bbox_inches='tight')\n" ]
[ [ "matplotlib.pyplot.style.use", "matplotlib.pyplot.legend", "numpy.maximum.accumulate", "matplotlib.pyplot.figure", "matplotlib.image.imread", "matplotlib.pyplot.savefig", "numpy.argmax", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.font_manager.FontProperties", "numpy.where", "matplotlib.gridspec.GridSpec", "matplotlib.ticker.AutoMinorLocator", "numpy.unique" ] ]
novid1134/solar-3d
[ "1e5b77173abb0d805b3cc613e0a7ab3f063fb7e3" ]
[ "uvf.py" ]
[ "# universal variable formulation, 3rd order differential equation solver for orbital prediction,\n# implemented due to huge efficiency issues when using conventional methods (loops, recursion),\n# algorithms based on Vectorized Analytic Two Body Propagator in MATLAB Copyright (c) 2012, Darin Koblick\n\nfrom scipy.spatial.distance import cdist\nfrom vis import *\nfrom parameters import u, sun_radius\nimport numpy as np\n\nu2 = np.sqrt(u)\n\n\ndef c2c3(psi): # Stumpff functions definitions\n\n c2, c3 = 0, 0\n\n if np.any(psi > 1e-6):\n c2 = (1 - np.cos(np.sqrt(psi))) / psi\n c3 = (np.sqrt(psi) - np.sin(np.sqrt(psi))) / np.sqrt(psi ** 3)\n\n if np.any(psi < -1e-6):\n c2 = (1 - np.cosh(np.sqrt(-psi))) / psi\n c3 = (np.sinh(np.sqrt(-psi)) - np.sqrt(-psi)) / np.sqrt(-psi ** 3)\n\n if np.any(abs(psi) <= 1e-6):\n c2 = 0.5\n c3 = 1. / 6.\n\n return c2, c3\n\n\ndef position(r0, v0, t, trailer, tol=100):\n r0mag = mag(r0) # magnitude of the distance from the Sun\n v0mag = mag(v0) # magnitude of spacecraft velocity\n\n alpha = -(v0mag * v0mag) / u + 2. / r0mag # constant term in differential equation\n\n # compute initial guess (x0) for Newton-Raphson solver:\n\n s0 = 0\n\n if alpha > 0.000001: # elliptical orbits\n s0 = u2 * t * alpha\n\n if abs(alpha) < 0.000001: # parabolic orbits\n h = cross(r0, v0) # cross product of vectors r0 and v0\n hmag = mag(h) # magnitude of the h vector\n p = hmag / u\n s = np.arctan(1 / (3. * np.sqrt(u / (p ** 3)) * t)) / 2.\n w = np.arctan(np.tan(s) ** (1 / 3.))\n s0 = np.sqrt(p) * 2. * np.tan(1 / (2. * w))\n\n if alpha < -0.000001: # hyperbolic orbits\n a = 1. / alpha\n s0 = np.sign(t) * np.sqrt(-a) * np.log(-2. * u * alpha * t / (r0.dot(v0) + np.sign(t) *\n np.sqrt(-u * a) * (1 - r0mag * alpha)))\n\n # Newton-Raphson solver:\n\n err = np.inf\n dr0v0 = r0.dot(v0) / u2\n u2t = u2 * t\n i, s, c2, c3 = 0, 0, 0, 0\n\n while np.any(abs(err) > tol) and i < 25:\n s2 = s0 * s0 # s^2\n s3 = s2 * s0 # s^3\n psi = s2 * alpha # alpha * s^2\n\n c2, c3 = c2c3(psi) # Stumpff functions\n\n s0psic3 = s0 * (1.0 - psi * c3)\n s2c2 = s2 * c2\n\n r = s2c2 + dr0v0 * s0psic3 + r0mag * (1 - psi * c2) # f'(s)\n\n s = s0 + (u2t - s3 * c3 - dr0v0 * s2c2 - r0mag * s0psic3) / r # old value + f(s)/f'(s)\n\n err = s - s0 # convergence check\n s0 = s\n\n i += 1\n\n # identify non-converging array entries and remove them:\n\n del2 = np.where(abs(err) > tol)\n s, c2, c3, t = np.delete(s, del2), np.delete(c2, del2), np.delete(c3, del2), np.delete(t, del2)\n\n # calculate final coefficients:\n\n f = 1 - (s * s) * c2 / r0mag\n g = t - (s * s * s) * c3 / u2\n\n # calculate final path prediction:\n\n r2 = np.array(r0.astuple()) # convert vPython vectors to numpy arrays\n v2 = np.array(v0.astuple())\n\n path = r2 * f[:, None] + v2 * g[:, None] # (changing shape to enable numpy broadcasting)\n\n dst = cdist(path, [[0, 0, 0]]) # compute distance of all points in the path from the origin\n\n # draw path:\n\n trailer.trail.color = color.green # default color (green)\n\n if np.any(dst <= sun_radius):\n\n trailer.trail.color = color.red # turn path RED, if collision detected\n trailer.trail.pos = path[0:np.argmax(dst <= sun_radius)] # draw path only up to the Sun collision point\n\n else:\n trailer.trail.pos = path # update full path\n\n return trailer\n" ]
[ [ "scipy.spatial.distance.cdist", "numpy.sign", "numpy.any", "numpy.argmax", "numpy.tan", "numpy.delete", "numpy.sqrt" ] ]
hecoding/pytorch-lightning-bolts
[ "4d254fde6112b21436003028d553a726bf7ea6ef" ]
[ "tests/models/self_supervised/test_scripts.py" ]
[ "from unittest import mock\n\nimport pytest\nimport torch\n\nfrom tests import DATASETS_PATH\n\n\[email protected]('cli_args', [\n f\"--data_dir {DATASETS_PATH} --max_epochs 1 --max_steps 3 --fast_dev_run --batch_size 2\"\n])\ndef test_cli_run_self_supervised_amdim(cli_args):\n \"\"\"Test running CLI for an example with default params.\"\"\"\n from pl_bolts.models.self_supervised.amdim.amdim_module import cli_main\n\n cli_args = cli_args.split(' ') if cli_args else []\n with mock.patch(\"argparse._sys.argv\", [\"any.py\"] + cli_args):\n cli_main()\n\n\n# TODO: this test is hanging (runs for more then 10min) so we need to use GPU or optimize it...\[email protected](not torch.cuda.is_available(), reason=\"test requires GPU machine\")\[email protected]('cli_args', [\n f'--data_dir {DATASETS_PATH} --max_epochs 1 --max_steps 3 --fast_dev_run --batch_size 2 --encoder resnet18'\n])\ndef test_cli_run_self_supervised_cpc(cli_args):\n \"\"\"Test running CLI for an example with default params.\"\"\"\n from pl_bolts.models.self_supervised.cpc.cpc_module import cli_main\n\n cli_args = cli_args.split(' ') if cli_args else []\n with mock.patch(\"argparse._sys.argv\", [\"any.py\"] + cli_args):\n cli_main()\n\n\[email protected]('cli_args', [\n f'--data_dir {DATASETS_PATH} --max_epochs 1 --max_steps 3 --fast_dev_run --batch_size 2'\n])\ndef test_cli_run_self_supervised_moco(cli_args):\n \"\"\"Test running CLI for an example with default params.\"\"\"\n from pl_bolts.models.self_supervised.moco.moco2_module import cli_main\n\n cli_args = cli_args.split(' ') if cli_args else []\n with mock.patch(\"argparse._sys.argv\", [\"any.py\"] + cli_args):\n cli_main()\n\n\[email protected]('cli_args', [\n f'--data_dir {DATASETS_PATH} --max_epochs 1 --max_steps 3 --fast_dev_run --batch_size 2 --online_ft'\n])\ndef test_cli_run_self_supervised_simclr(cli_args):\n \"\"\"Test running CLI for an example with default params.\"\"\"\n from pl_bolts.models.self_supervised.simclr.simclr_module import cli_main\n\n cli_args = cli_args.split(' ') if cli_args else []\n with mock.patch(\"argparse._sys.argv\", [\"any.py\"] + cli_args):\n cli_main()\n\n\[email protected]('cli_args', [\n f'--data_dir {DATASETS_PATH} --max_epochs 1 --max_steps 3 --fast_dev_run --batch_size 2 --online_ft'\n])\ndef test_cli_run_self_supervised_byol(cli_args):\n \"\"\"Test running CLI for an example with default params.\"\"\"\n from pl_bolts.models.self_supervised.byol.byol_module import cli_main\n\n cli_args = cli_args.split(' ') if cli_args else []\n with mock.patch(\"argparse._sys.argv\", [\"any.py\"] + cli_args):\n cli_main()\n\n\[email protected](\n 'cli_args', [\n f'--dataset cifar10 --data_path {DATASETS_PATH} --max_epochs 1 --max_steps 3 --fast_dev_run --batch_size 2'\n ' --gpus 0 --arch resnet18 --hidden_mlp 512 --fp32 --sinkhorn_iterations 1 --nmb_prototypes 2'\n ]\n)\ndef test_cli_run_self_supervised_swav(cli_args):\n \"\"\"Test running CLI for an example with default params.\"\"\"\n from pl_bolts.models.self_supervised.swav.swav_module import cli_main\n\n cli_args = cli_args.split(' ') if cli_args else []\n with mock.patch(\"argparse._sys.argv\", [\"any.py\"] + cli_args):\n cli_main()\n" ]
[ [ "torch.cuda.is_available" ] ]
arokem/picard
[ "1ca98a51b60bc51bfcf8767dea989cc4f5b8b522" ]
[ "picard/_tools.py" ]
[ "# Authors: Pierre Ablin <[email protected]>\n# Alexandre Gramfort <[email protected]>\n# Jean-Francois Cardoso <[email protected]>\n#\n# License: BSD (3-clause)\nimport numbers\n\nimport numpy as np\n\n\ndef permute(A, scale=True):\n '''Get a permutation to diagonalize and scale a matrix\n\n Parameters\n ----------\n A : ndarray, shape (n_features, n_features)\n A matrix close from a permutation and scale matrix.\n\n scale : boolean, optional\n If True, scales the matrix A wrt its diagonal\n Returns\n -------\n A : ndarray, shape (n_features, n_features)\n A permuted matrix.\n '''\n A = A.copy()\n n = A.shape[0]\n idx = np.arange(n)\n done = False\n while not done:\n done = True\n for i in range(n):\n for j in range(i):\n if A[i, i] ** 2 + A[j, j] ** 2 < A[i, j] ** 2 + A[j, i] ** 2:\n A[(i, j), :] = A[(j, i), :]\n idx[i], idx[j] = idx[j], idx[i]\n done = False\n if scale:\n A /= np.diag(A)\n order_sort = np.argsort(np.sum(np.abs(A), axis=0))\n A = A[order_sort, :]\n A = A[:, order_sort]\n return A\n\n\ndef check_random_state(seed):\n \"\"\"Turn seed into a np.random.RandomState instance\n Parameters\n ----------\n seed : None | int | instance of RandomState\n If seed is None, return the RandomState singleton used by np.random.\n If seed is an int, return a new RandomState instance seeded with seed.\n If seed is already a RandomState instance, return it.\n Otherwise raise ValueError.\n \"\"\"\n if seed is None or seed is np.random:\n return np.random.mtrand._rand\n if isinstance(seed, (numbers.Integral, np.integer)):\n return np.random.RandomState(seed)\n if isinstance(seed, np.random.RandomState):\n return seed\n raise ValueError('%r cannot be used to seed a numpy.random.RandomState'\n ' instance' % seed)\n\n\ndef _sym_decorrelation(W):\n \"\"\" Symmetric decorrelation\n i.e. W <- (W * W.T) ^{-1/2} * W\n \"\"\"\n s, u = np.linalg.eigh(np.dot(W, W.T))\n return np.dot(np.dot(u * (1. / np.sqrt(s)), u.T), W)\n\n\ndef _ica_par(X, fun, max_iter, w_init, verbose):\n \"\"\"Parallel FastICA.\n Used internally by FastICA --main loop\n \"\"\"\n if verbose:\n print('Running %d iterations of FastICA...' % max_iter)\n W = _sym_decorrelation(w_init)\n del w_init\n p_ = float(X.shape[1])\n for ii in range(max_iter):\n gwtx, g_wtx = fun.score_and_der(np.dot(W, X))\n g_wtx = g_wtx.mean(axis=1)\n C = np.dot(gwtx, X.T) / p_ - g_wtx[:, np.newaxis] * W\n W = _sym_decorrelation(C)\n del gwtx, g_wtx\n if verbose:\n print('Running Picard...')\n return W\n\n\ndef amari_distance(W, A):\n \"\"\"\n Computes the Amari distance between two matrices W and A.\n It cancels when WA is a permutation and scale matrix.\n\n Parameters\n ----------\n W : ndarray, shape (n_features, n_features)\n Input matrix\n\n A : ndarray, shape (n_features, n_features)\n Input matrix\n\n Returns\n -------\n d : float\n The Amari distance\n \"\"\"\n P = np.dot(W, A)\n\n def s(r):\n return np.sum(np.sum(r ** 2, axis=1) / np.max(r ** 2, axis=1) - 1)\n return (s(np.abs(P)) + s(np.abs(P.T))) / (2 * P.shape[0])\n" ]
[ [ "numpy.sum", "numpy.diag", "numpy.abs", "numpy.arange", "numpy.random.RandomState", "numpy.max", "numpy.sqrt", "numpy.dot" ] ]
VitaNova1998/REP
[ "abc640dfca1b23237770b0508f79c45b84baf81b" ]
[ "utils/audio_utils.py" ]
[ "import numpy as np\nimport librosa\nfrom scipy import signal\nimport fnmatch\nimport os\n\n\ndef preemphasis(x, coeff=0.97):\n return signal.lfilter([1, -coeff], [1], x)\n\n\ndef inv_preemphasis(x, coeff=0.97):\n return signal.lfilter([1], [1, -coeff], x)\n\n\ndef griffin_lim(stft_matrix_,\n n_fft,\n hop_size,\n win_size=None,\n max_iter=50,\n delta=20):\n\n n_frames = stft_matrix_.shape[1]\n expected_len = n_fft + hop_size*(n_frames - 1)\n shape = (expected_len - n_fft,)\n y = np.random.random(shape)\n\n for i in range(max_iter):\n stft_matrix = librosa.core.stft(\n y,\n n_fft=n_fft,\n hop_length=hop_size,\n win_length=win_size)\n stft_matrix = stft_matrix_ * stft_matrix / np.abs(stft_matrix)\n y = librosa.core.istft(\n stft_matrix,\n hop_length=hop_size,\n win_length=win_size)\n return y\n\n\ndef log_magnitude_postproc(stftm, magnitude_enphasis):\n # emphasizing magnitude\n stftm = stftm * magnitude_enphasis\n # Undo log and square\n stftm = np.sqrt(np.exp(stftm))\n return stftm\n" ]
[ [ "scipy.signal.lfilter", "numpy.abs", "numpy.exp", "numpy.random.random" ] ]
judyheflin/amazon-s3-plugin-for-pytorch
[ "38284c8a5e92be3bbf47b08e8c90d94be0cb79e7" ]
[ "examples/s3_cv_map_example.py" ]
[ "\nfrom awsio.python.lib.io.s3.s3dataset import S3Dataset\nfrom torch.utils.data import DataLoader\n\nurl_list = ['s3://image-data-bucket/train/n01440764/n01440764_10026.JPEG',\n 's3://image-data-bucket/train/n01440764/n01440764_10027.JPEG',\n 's3://image-data-bucket/train/n01440764/n01440764_10029.JPEG']\n\ndataset = S3Dataset(url_list)\ndataloader = DataLoader(dataset,\n batch_size=2,\n num_workers=64)\n\nfor i, (image, label) in enumerate(dataloader):\n print(type(image), len(image))\n\n" ]
[ [ "torch.utils.data.DataLoader" ] ]
dvav/clonosGP
[ "e7f9a08869df0e1857fe24e4e311999f7ba6560f" ]
[ "run_models_on_simulated_data.py" ]
[ "import os\nimport sys\n\nIDX = int(sys.argv[1])\nos.environ['THEANO_FLAGS'] = f'base_compiledir=\"theano/p{IDX}\"'\n\nimport tqdm as tqd\nimport itertools as itr\nimport numpy as nmp\nimport pandas as pnd\nimport sklearn.metrics as mtr\nimport scipy.special as scp\n\nimport pymc3 as pmc\nimport clonosGP as cln\n\n\n\n##\ndef run_model(prior, cov, lik, R, K, M, N, tau, h2, data): \n nmp.random.seed(42)\n pmc.tt_rng(42)\n \n res = cln.infer(data, \n model_args={'K': 20, 'prior': prior, 'cov': cov, 'lik': lik, 'threshold': 0.0}, \n pymc3_args={'niters': 40000, 'method': 'advi', 'flow': 'scale-loc', 'learning_rate': 1e-2, 'random_seed': 42})\n\n z_true = data[['MUTID', 'CLUSTERID']].drop_duplicates().CLUSTERID.values\n z_pred = res['data'][['MUTID', 'CLUSTERID']].drop_duplicates().CLUSTERID.values\n \n return pnd.DataFrame({\n 'REP': R, \n 'NCLUSTERS': K, \n 'NSAMPLES': M, \n 'NMUTS': N,\n 'TAU': tau,\n 'H2': h2,\n 'PRIOR': prior,\n 'COV': cov,\n 'LIK': lik,\n 'ARI': mtr.adjusted_rand_score(z_true, z_pred),\n 'AMI': mtr.adjusted_mutual_info_score(z_true, z_pred),\n 'FMI': mtr.fowlkes_mallows_score(z_true, z_pred),\n }, index=[0]).reset_index(drop=True)\n\n\n## load template\ndepths = pnd.read_csv('data/cll_Rincon_2019_patient1.csv').R.values\n\n##\nprint(f'Generating data: {IDX}')\nnmp.random.seed(42)\nDATA = [[R, K, M, N, TAU, H2, cln.sim.get_Nsamples(nclusters=K, nmuts=N, nsamples=M, tau=TAU, h2=H2, mean_depth=(40, 40), depths=depths)] \n for R, K, M, N, TAU, H2 in itr.product([1, 2, 3], [2, 4, 8], [3, 6, 12], [25, 50, 100], [1, 10, 100], [1, 10, 20])]\n\n##\nprint(f\"Running model: {IDX}\")\nARGS = [('Flat', 'Exp', 'Bin'), ('Flat', 'Exp', 'BBin'), ('GP0', 'Exp', 'Bin'), ('GP0', 'Exp', 'BBin'),('GP0', 'ExpQ', 'Bin'),('GP0', 'ExpQ', 'BBin')]\nRES = [run_model(*args, *DATA[IDX-1]) for args in ARGS]\nRES = pnd.concat(RES).reset_index(drop=True)\nRES.to_csv(f'results/simdata{IDX}.csv', index=False)\n\n\n" ]
[ [ "pandas.read_csv", "sklearn.metrics.adjusted_rand_score", "sklearn.metrics.adjusted_mutual_info_score", "numpy.random.seed", "pandas.concat", "sklearn.metrics.fowlkes_mallows_score" ] ]
CancerDataScience/NuCLS
[ "c172b55b18d4ea78c3f51a8fd28ee6c2595c8360" ]
[ "TorchUtils.py" ]
[ "import torch\nimport nucls_model.torchvision_detection_utils.transforms as tvdt\n\n\nISCUDA = torch.cuda.is_available()\n\n\ndef tensor_isin(arr1, arr2):\n r\"\"\" Compares a tensor element-wise with a list of possible values.\n See :func:`torch.isin`\n\n Source: https://github.com/pytorch/pytorch/pull/26144\n \"\"\"\n result = (arr1[..., None] == arr2).any(-1)\n return result.type(torch.ByteTensor)\n\n\ndef transform_dlinput(\n tlist=None, make_tensor=True, flip_prob=0.5,\n augment_stain_sigma1=0.5, augment_stain_sigma2=0.5):\n \"\"\"Transform input image data for a DL model.\n\n Parameters\n ----------\n tlist: None or list. If testing mode, pass as None.\n flip_prob\n augment_stain_sigma1\n augment_stain_sigma2\n\n \"\"\"\n tmap = {\n 'hflip': tvdt.RandomHorizontalFlip(prob=flip_prob),\n 'augment_stain': tvdt.RandomHEStain(\n sigma1=augment_stain_sigma1, sigma2=augment_stain_sigma2),\n }\n tlist = [] if tlist is None else tlist\n transforms = []\n # go through various transforms\n for tname in tlist:\n transforms.append(tmap[tname])\n # maybe convert to tensor\n if make_tensor:\n # transforms.append(tvdt.PILToTensor(float16=ISCUDA))\n transforms.append(tvdt.PILToTensor(float16=False))\n return tvdt.Compose(transforms)\n" ]
[ [ "torch.cuda.is_available" ] ]
jingjieli95/UnarySim
[ "c03386efdbb8151f3c33f34b44d1d6a6fc960434" ]
[ "test/kernel/test_kernel_exp_comb.py" ]
[ "# %%\nimport torch\nimport math\nfrom UnarySim.kernel.exp import expN1\nfrom UnarySim.stream.gen import RNG, SourceGen, BSGen\nfrom UnarySim.metric.metric import ProgError\nimport matplotlib.pyplot as plt\nimport time\nimport math\nimport numpy as np\n\n# %%\ndef exp_comb_test(bw=8, mode=\"unipolar\", rng=\"Sobol\"):\n \n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n total_cnt = 100\n bitwidth = bw\n btype = torch.float\n rtype=torch.float\n stype=torch.float\n\n print(\"========================================================\")\n print(mode)\n print(\"========================================================\")\n # all input values are non-negative\n low_bound = 0\n if mode == \"unipolar\":\n up_bound = 2**bitwidth\n elif mode == \"bipolar\":\n low_bound = 0\n up_bound = 2**(bitwidth-1)\n\n input_list = []\n for input_val in range(low_bound, up_bound+1, 1):\n input_list.append(input_val)\n\n input = torch.tensor(input_list).type(torch.float).div(up_bound).to(device)\n output = torch.exp(input.mul(-1))\n \n result_pe_total = []\n for rand_idx in range(1, total_cnt+1):\n \n outputPE = ProgError(output, mode=mode).to(device)\n inputPE = ProgError(input, mode=mode).to(device)\n \n dut_exp_comb = expN1(mode=mode, \n rng=rng, \n rng_dim=rand_idx, \n rng_width=bitwidth).to(device)\n inputSRC = SourceGen(input, bitwidth, mode=mode, rtype=rtype)().to(device)\n inputRNG = RNG(bitwidth, rand_idx, rng, rtype)().to(device)\n inputBS = BSGen(inputSRC, inputRNG, stype).to(device)\n with torch.no_grad():\n start_time = time.time()\n for i in range(2**bitwidth):\n input_bs = inputBS(torch.tensor([i]))\n inputPE.Monitor(input_bs)\n\n output_bs = dut_exp_comb(input_bs)\n outputPE.Monitor(output_bs)\n \n # get the result for different rng\n result_pe = outputPE()[1].cpu().numpy()\n result_pe_total.append(result_pe) \n \n # get the result for different rng\n result_pe_total = np.array(result_pe_total)\n #######################################################################\n # check the error of all simulation\n #######################################################################\n print(\"RMSE:{:1.4}\".format(math.sqrt(np.mean(result_pe_total**2))))\n print(\"MAE: {:1.4}\".format(np.mean(np.abs(result_pe_total))))\n print(\"bias:{:1.4}\".format(np.mean(result_pe_total)))\n print(\"max: {:1.4}\".format(np.max(result_pe_total)))\n print(\"min: {:1.4}\".format(np.min(result_pe_total)))\n\n #######################################################################\n # check the error according to input value\n #######################################################################\n max_total = np.max(result_pe_total, axis=0)\n min_total = np.min(result_pe_total, axis=0)\n avg_total = np.mean(result_pe_total, axis=0)\n \n axis_len = outputPE()[1].size()[0]\n input_x_axis = []\n for axis_index in range(axis_len):\n input_x_axis.append((axis_index/(axis_len-1)*(up_bound-low_bound)+low_bound)/up_bound)\n fig, ax = plt.subplots()\n ax.fill_between(input_x_axis, max_total, avg_total, facecolor=\"red\", alpha=0.75)\n ax.fill_between(input_x_axis, avg_total, min_total, facecolor=\"blue\", alpha=0.75)\n ax.plot(input_x_axis, avg_total, label='Avg error', color=\"black\", linewidth=0.3)\n plt.tight_layout()\n plt.xlabel('Input value')\n plt.ylabel('Output error')\n plt.xticks(np.arange(0, 1.1, step=0.5))\n # ax.xaxis.set_ticklabels([])\n plt.xlim(0, 1)\n plt.yticks(np.arange(-0.2, 0.4, step=0.2))\n # ax.yaxis.set_ticklabels([])\n plt.ylim(-0.3, 0.55)\n plt.grid(b=True, which=\"both\", axis=\"y\", linestyle=\"--\", color=\"grey\", linewidth=0.3)\n fig.set_size_inches(4, 4)\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n plt.show()\n plt.close()\n\n# %%\nexp_comb_test(8,\"unipolar\", \"Sobol\")\n\n# %%\nexp_comb_test(8, \"unipolar\", \"SYS\")\n\n# %%\nexp_comb_test(8, \"unipolar\", \"LFSR\")" ]
[ [ "matplotlib.pyplot.grid", "matplotlib.pyplot.tight_layout", "torch.no_grad", "numpy.abs", "torch.tensor", "matplotlib.pyplot.subplots", "matplotlib.pyplot.xlim", "numpy.arange", "numpy.max", "matplotlib.pyplot.ylabel", "numpy.min", "matplotlib.pyplot.ylim", "matplotlib.pyplot.show", "numpy.array", "matplotlib.pyplot.close", "torch.cuda.is_available", "matplotlib.pyplot.xlabel", "numpy.mean" ] ]
ilvcd/Flux.jl
[ "d22479318b5f2a19a0003f3201d9b145b4562f9f" ]
[ "u2net.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport torch\nimport torch.nn as nn\nimport math\nimport time\n# class REBNCONVs(nn.Module):\n# def __init__(self,in_ch=3,out_ch=3,dirate=1):\n# super(REBNCONVs,self).__init__()\n\n# self.conv_s1 = nn.Conv2d(in_ch,out_ch,3,padding=1*dirate,dilation=1*dirate)\n# self.bn_s1 = nn.BatchNorm2d(out_ch)\n# self.relu_s1 = nn.ReLU(inplace=True)\n\n# def forward(self,x):\n\n# hx = x\n# xout = self.relu_s1(self.bn_s1(self.conv_s1(hx)))\n\n# return xout\n\n## upsample tensor 'src' to have the same spatial size with tensor 'tar'\ndef _upsample_like1(src,tar):\n src = F.upsample(src,size=tar.shape[2:],mode='bilinear')\n return src\n\ndef _upsample_like(src,tar):\n\n src_h,src_l = src\n tar_h,tar_l = tar\n src_h = F.upsample(src_h,size=tar_h.shape[2:],mode='bilinear')\n src_l = F.upsample(src_l,size=tar_l.shape[2:],mode='bilinear') if src_l is not None else None\n if src_l is None:\n return src_h\n return src_h,src_l\n\ndef comb(src,tar):\n src_h,src_l = src\n tar_h,tar_l = tar\n return src_h+tar_h,src_l+tar_l\n\ndef cat6(src1,src2,src3,src4,src5,src6,dim):\n src_h1,src_l1 = src1\n src_h2,src_l2 = src2\n src_h3,src_l3 = src3\n src_h4,src_l4 = src4\n src_h5,src_l5 = src5\n src_h6,src_l6 = src6\n return torch.cat((src_h1,src_h2,src_h3,src_h4,src_h5,src_h6),dim),torch.cat((src_l1,src_l2,src_l3,src_l4,src_l5,src_l6),dim)\n\ndef cat(src,tar,dim):\n src_h,src_l = src\n tar_h,tar_l = tar\n return torch.cat((src_h,tar_h),dim),torch.cat((src_l,tar_l),dim)\n\nclass OctConv(nn.Conv2d):\n \"\"\"\n Octave convolution layer.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int, default 1\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n oct_alpha : float, default 0.0\n Octave alpha coefficient.\n oct_mode : str, default 'std'\n Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.\n oct_value : int, default 2\n Octave value.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride,\n padding=1,\n dilation=1,\n groups=1,\n bias=False,\n oct_alpha=0.5,\n oct_mode=\"std\",\n oct_value=2):\n if isinstance(stride, int):\n stride = (stride, stride)\n self.downsample = (stride[0] > 1) or (stride[1] > 1)\n assert (stride[0] in [1, oct_value]) and (stride[1] in [1, oct_value])\n stride = (1, 1)\n if oct_mode == \"first\":\n in_alpha = 0.0\n out_alpha = oct_alpha\n elif oct_mode == \"norm\":\n in_alpha = oct_alpha\n out_alpha = oct_alpha\n elif oct_mode == \"last\":\n in_alpha = oct_alpha\n out_alpha = 0.0\n elif oct_mode == \"std\":\n in_alpha = 0.0\n out_alpha = 0.0\n else:\n raise ValueError(\"Unsupported octave convolution mode: {}\".format(oct_mode))\n self.h_in_channels = int(in_channels * (1.0 - in_alpha))\n self.h_out_channels = int(out_channels * (1.0 - out_alpha))\n self.l_out_channels = out_channels - self.h_out_channels\n self.oct_alpha = oct_alpha\n self.oct_mode = oct_mode\n self.oct_value = oct_value\n super(OctConv, self).__init__(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n bias=bias)\n self.conv_kwargs = {\n \"stride\": stride,\n \"padding\": padding,\n \"dilation\": dilation,\n \"groups\": groups}\n\n def forward(self,x):\n hx,lx=x\n if self.oct_mode == \"std\":\n return F.conv2d(\n input=hx,\n weight=self.weight,\n bias=self.bias,\n **self.conv_kwargs), None\n\n if self.downsample:\n hx = F.avg_pool2d(\n input=hx,\n kernel_size=(self.oct_value, self.oct_value),\n stride=(self.oct_value, self.oct_value))\n\n hhy = F.conv2d(\n input=hx,\n weight=self.weight[0:self.h_out_channels, 0:self.h_in_channels, :, :],\n bias=self.bias[0:self.h_out_channels] if self.bias is not None else None,\n **self.conv_kwargs)\n\n if self.oct_mode != \"first\":\n hlx = F.conv2d(\n input=lx,\n weight=self.weight[0:self.h_out_channels, self.h_in_channels:, :, :],\n bias=self.bias[0:self.h_out_channels] if self.bias is not None else None,\n **self.conv_kwargs)\n\n if self.oct_mode == \"last\":\n hlx = F.interpolate(\n input=hlx,\n scale_factor=self.oct_value,\n mode=\"nearest\")\n hy = hhy + hlx\n ly = None\n return hy\n\n lhx = F.avg_pool2d(\n input=hx,\n kernel_size=(self.oct_value, self.oct_value),\n stride=(self.oct_value, self.oct_value))\n lhy = F.conv2d(\n input=lhx,\n weight=self.weight[self.h_out_channels:, 0:self.h_in_channels, :, :],\n bias=self.bias[self.h_out_channels:] if self.bias is not None else None,\n **self.conv_kwargs)\n\n if self.oct_mode == \"first\":\n hy = hhy\n ly = lhy\n return hy, ly\n\n if self.downsample:\n hly = hlx\n llx = F.avg_pool2d(\n input=lx,\n kernel_size=(self.oct_value, self.oct_value),\n stride=(self.oct_value, self.oct_value))\n else:\n hly = F.interpolate(\n input=hlx,\n scale_factor=self.oct_value,\n mode=\"nearest\")\n llx = lx\n lly = F.conv2d(\n input=llx,\n weight=self.weight[self.h_out_channels:, self.h_in_channels:, :, :],\n bias=self.bias[self.h_out_channels:] if self.bias is not None else None,\n **self.conv_kwargs)\n\n hy = hhy + hly\n ly = lhy + lly\n return hy, ly\n\n\n\n\nclass OctaveConv(nn.Module):\n \"\"\"\n Octave convolution block with Batch normalization and ReLU/ReLU6 activation.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n oct_alpha : float, default 0.0\n Octave alpha coefficient.\n oct_mode : str, default 'std'\n Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n oct_alpha=0.5,\n padding=0,\n oct_mode=\"last\"):\n super(OctaveConv, self).__init__()\n self.last = (oct_mode == \"last\") or (oct_mode == \"std\")\n self.conv = OctConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=1,\n padding=padding,\n dilation=1,\n groups=1,\n bias=False,\n oct_alpha=oct_alpha,\n oct_mode=oct_mode)\n\n def forward(self, x):\n ret = self.conv(x)\n return ret\n\nclass REBNCONV(nn.Module):\n \"\"\"\n Octave convolution block with Batch normalization and ReLU/ReLU6 activation.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n stride : int or tuple/list of 2 int\n Strides of the convolution.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n dilation : int or tuple/list of 2 int, default 1\n Dilation value for convolution layer.\n groups : int, default 1\n Number of groups.\n bias : bool, default False\n Whether the layer uses a bias vector.\n oct_alpha : float, default 0.0\n Octave alpha coefficient.\n oct_mode : str, default 'std'\n Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.\n bn_eps : float, default 1e-5\n Small float added to variance in Batch norm.\n activation : function or str or None, default nn.ReLU(inplace=True)\n Activation function or name of activation function.\n activate : bool, default True\n Whether activate the convolution block.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size=3,\n dirate=1,\n oct_alpha=0.5,\n oct_mode=\"norm\",\n bn_eps=1e-5):\n super(REBNCONV, self).__init__()\n self.activate = nn.ReLU(inplace=True)\n self.last = (oct_mode == \"last\") or (oct_mode == \"std\")\n out_alpha = 0.0 if self.last else oct_alpha\n h_out_channels = int(out_channels * (1.0 - out_alpha))\n l_out_channels = out_channels - h_out_channels\n self.conv = OctConv(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=1,\n padding=1*dirate,\n dilation=1*dirate,\n groups=1,\n bias=False,\n oct_alpha=oct_alpha,\n oct_mode=oct_mode)\n self.h_bn = nn.BatchNorm2d(\n num_features=h_out_channels,\n eps=bn_eps)\n if not self.last:\n self.l_bn = nn.BatchNorm2d(\n num_features=l_out_channels,\n eps=bn_eps)\n\n def forward(self, x):\n hx, lx = self.conv(x)\n hx = self.h_bn(hx)\n if self.activate:\n hx = self.activate(hx)\n if not self.last:\n lx = self.l_bn(lx)\n lx = self.activate(lx)\n return hx, lx\n\n\n\nclass MaxPool2dx(nn.Module):\n def __init__(self):\n super(MaxPool2dx, self).__init__()\n self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True)\n\n def forward(self, x):\n x_h, x_l = x\n x_h = self.pool1(x_h)\n x_l = self.pool1(x_l) if x_l is not None else None\n return x_h, x_l\n\n\n\n### RSU-7 ###\nclass RSU7(nn.Module):#UNet07DRES(nn.Module):\n\n def __init__(self, in_ch=3, mid_ch=12, out_ch=3,first=False):\n super(RSU7,self).__init__()\n oct_mode = 'norm'\n if first:\n oct_mode = 'first'\n self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1,oct_mode = oct_mode)\n\n self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)\n self.pool1 = MaxPool2dx()\n\n self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool2 = MaxPool2dx()\n\n self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool3 = MaxPool2dx()\n\n self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool4 = MaxPool2dx()\n\n self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool5 = MaxPool2dx()\n\n self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=1)\n\n self.rebnconv7 = REBNCONV(mid_ch,mid_ch,dirate=2)\n\n self.rebnconv6d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)\n\n def forward(self,x):\n\n hx = x\n hxin = self.rebnconvin(hx)\n\n hx1 = self.rebnconv1(hxin)\n hx = self.pool1(hx1)\n\n hx2 = self.rebnconv2(hx)\n hx = self.pool2(hx2)\n\n hx3 = self.rebnconv3(hx)\n hx = self.pool3(hx3)\n\n hx4 = self.rebnconv4(hx)\n hx = self.pool4(hx4)\n\n hx5 = self.rebnconv5(hx)\n hx = self.pool5(hx5)\n\n hx6 = self.rebnconv6(hx)\n\n hx7 = self.rebnconv7(hx6)\n\n hx6d = self.rebnconv6d(cat(hx7,hx6,1))\n hx6dup = _upsample_like(hx6d,hx5)\n\n hx5d = self.rebnconv5d(cat(hx6dup,hx5,1))\n hx5dup = _upsample_like(hx5d,hx4)\n\n hx4d = self.rebnconv4d(cat(hx5dup,hx4,1))\n hx4dup = _upsample_like(hx4d,hx3)\n\n hx3d = self.rebnconv3d(cat(hx4dup,hx3,1))\n hx3dup = _upsample_like(hx3d,hx2)\n\n hx2d = self.rebnconv2d(cat(hx3dup,hx2,1))\n hx2dup = _upsample_like(hx2d,hx1)\n\n hx1d = self.rebnconv1d(cat(hx2dup,hx1,1))\n\n return comb(hx1d, hxin)\n\n### RSU-6 ###\nclass RSU6(nn.Module):#UNet06DRES(nn.Module):\n\n def __init__(self, in_ch=3, mid_ch=12, out_ch=3):\n super(RSU6,self).__init__()\n\n self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)\n\n self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)\n self.pool1 = MaxPool2dx()\n\n self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool2 = MaxPool2dx()\n\n self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool3 = MaxPool2dx()\n\n self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool4 = MaxPool2dx()\n\n self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1)\n\n self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=2)\n\n self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)\n\n def forward(self,x):\n\n hx = x\n\n hxin = self.rebnconvin(hx)\n\n hx1 = self.rebnconv1(hxin)\n hx = self.pool1(hx1)\n\n hx2 = self.rebnconv2(hx)\n hx = self.pool2(hx2)\n\n hx3 = self.rebnconv3(hx)\n hx = self.pool3(hx3)\n\n hx4 = self.rebnconv4(hx)\n hx = self.pool4(hx4)\n\n hx5 = self.rebnconv5(hx)\n\n hx6 = self.rebnconv6(hx5)\n\n\n hx5d = self.rebnconv5d(cat(hx6,hx5,1))\n hx5dup = _upsample_like(hx5d,hx4)\n\n hx4d = self.rebnconv4d(cat(hx5dup,hx4,1))\n hx4dup = _upsample_like(hx4d,hx3)\n\n hx3d = self.rebnconv3d(cat(hx4dup,hx3,1))\n hx3dup = _upsample_like(hx3d,hx2)\n\n hx2d = self.rebnconv2d(cat(hx3dup,hx2,1))\n hx2dup = _upsample_like(hx2d,hx1)\n\n hx1d = self.rebnconv1d(cat(hx2dup,hx1,1))\n\n return comb(hx1d, hxin)\n\n### RSU-5 ###\nclass RSU5(nn.Module):#UNet05DRES(nn.Module):\n\n def __init__(self, in_ch=3, mid_ch=12, out_ch=3):\n super(RSU5,self).__init__()\n\n self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)\n\n self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)\n self.pool1 = MaxPool2dx()\n\n self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool2 = MaxPool2dx()\n\n self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool3 = MaxPool2dx()\n\n self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1)\n\n self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=2)\n\n self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)\n\n def forward(self,x):\n\n hx = x\n\n hxin = self.rebnconvin(hx)\n\n hx1 = self.rebnconv1(hxin)\n hx = self.pool1(hx1)\n\n hx2 = self.rebnconv2(hx)\n hx = self.pool2(hx2)\n\n hx3 = self.rebnconv3(hx)\n hx = self.pool3(hx3)\n\n hx4 = self.rebnconv4(hx)\n\n hx5 = self.rebnconv5(hx4)\n\n hx4d = self.rebnconv4d(cat(hx5,hx4,1))\n hx4dup = _upsample_like(hx4d,hx3)\n\n hx3d = self.rebnconv3d(cat(hx4dup,hx3,1))\n hx3dup = _upsample_like(hx3d,hx2)\n\n hx2d = self.rebnconv2d(cat(hx3dup,hx2,1))\n hx2dup = _upsample_like(hx2d,hx1)\n\n hx1d = self.rebnconv1d(cat(hx2dup,hx1,1))\n\n return comb(hx1d, hxin)\n\n### RSU-4 ###\nclass RSU4(nn.Module):#UNet04DRES(nn.Module):\n\n def __init__(self, in_ch=3, mid_ch=12, out_ch=3):\n super(RSU4,self).__init__()\n\n self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)\n\n self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)\n self.pool1 = MaxPool2dx()\n\n self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1)\n self.pool2 = MaxPool2dx()\n\n self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1)\n\n self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=2)\n\n self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1)\n self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)\n\n def forward(self,x):\n\n hx = x\n\n hxin = self.rebnconvin(hx)\n\n hx1 = self.rebnconv1(hxin)\n hx = self.pool1(hx1)\n\n hx2 = self.rebnconv2(hx)\n hx = self.pool2(hx2)\n\n hx3 = self.rebnconv3(hx)\n\n hx4 = self.rebnconv4(hx3)\n\n hx3d = self.rebnconv3d(cat(hx4,hx3,1))\n hx3dup = _upsample_like(hx3d,hx2)\n\n hx2d = self.rebnconv2d(cat(hx3dup,hx2,1))\n hx2dup = _upsample_like(hx2d,hx1)\n\n hx1d = self.rebnconv1d(cat(hx2dup,hx1,1))\n\n return comb(hx1d, hxin)\n\n### RSU-4F ###\nclass RSU4F(nn.Module):#UNet04FRES(nn.Module):\n\n def __init__(self, in_ch=3, mid_ch=12, out_ch=3):\n super(RSU4F,self).__init__()\n\n self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1)\n\n self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1)\n self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=2)\n self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=4)\n\n self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=8)\n\n self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=4)\n self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=2)\n self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1)\n\n def forward(self,x):\n\n hx = x\n\n hxin = self.rebnconvin(hx)\n\n hx1 = self.rebnconv1(hxin)\n hx2 = self.rebnconv2(hx1)\n hx3 = self.rebnconv3(hx2)\n\n hx4 = self.rebnconv4(hx3)\n\n hx3d = self.rebnconv3d(cat(hx4,hx3,1))\n hx2d = self.rebnconv2d(cat(hx3d,hx2,1))\n hx1d = self.rebnconv1d(cat(hx2d,hx1,1))\n\n return comb(hx1d, hxin)\n\n\n### U^2-Net small ###\nclass U2NETP(nn.Module):\n\n def __init__(self,in_ch=2,out_ch=2):\n super(U2NETP,self).__init__()\n\n self.stage1 = RSU7(in_ch,16,64,first=True)\n self.pool12 = MaxPool2dx()\n\n self.stage2 = RSU6(64,16,64)\n self.pool23 = MaxPool2dx()\n\n self.stage3 = RSU5(64,16,64)\n self.pool34 = MaxPool2dx()\n\n self.stage4 = RSU4(64,16,64)\n self.pool45 = MaxPool2dx()\n\n self.stage5 = RSU4F(64,16,64)\n self.pool56 = MaxPool2dx()\n\n self.stage6 = RSU4F(64,16,64)\n\n # decoder\n self.stage5d = RSU4F(128,16,64)\n self.stage4d = RSU4(128,16,64)\n self.stage3d = RSU5(128,16,64)\n self.stage2d = RSU6(128,16,64)\n self.stage1d = RSU7(128,16,64)\n\n self.side1 = OctaveConv(64,out_ch,3,padding=1)\n self.side2 = OctaveConv(64,out_ch,3,padding=1)\n self.side3 = OctaveConv(64,out_ch,3,padding=1)\n self.side4 = OctaveConv(64,out_ch,3,padding=1)\n self.side5 = OctaveConv(64,out_ch,3,padding=1)\n self.side6 = OctaveConv(64,out_ch,3,padding=1)\n\n self.outconv = nn.Conv2d(6*out_ch,out_ch,1)\n\n def forward(self,x):\n #x1=torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)\n hx = x\n\n #stage 1\n hx1 = self.stage1((hx,None))\n hx = self.pool12(hx1)\n\n #stage 2\n hx2 = self.stage2(hx)\n hx = self.pool23(hx2)\n\n #stage 3\n hx3 = self.stage3(hx)\n hx = self.pool34(hx3)\n\n #stage 4\n hx4 = self.stage4(hx)\n hx = self.pool45(hx4)\n\n #stage 5\n hx5 = self.stage5(hx)\n hx = self.pool56(hx5)\n\n #stage 6\n hx6 = self.stage6(hx)\n hx6up = _upsample_like(hx6,hx5)\n\n #decoder\n hx5d = self.stage5d(cat(hx6up,hx5,1))\n hx5dup = _upsample_like(hx5d,hx4)\n\n hx4d = self.stage4d(cat(hx5dup,hx4,1))\n hx4dup = _upsample_like(hx4d,hx3)\n\n hx3d = self.stage3d(cat(hx4dup,hx3,1))\n hx3dup = _upsample_like(hx3d,hx2)\n\n hx2d = self.stage2d(cat(hx3dup,hx2,1))\n hx2dup = _upsample_like(hx2d,hx1)\n\n hx1d = self.stage1d(cat(hx2dup,hx1,1))\n\n\n #side output\n d1 = self.side1(hx1d)\n d2 = self.side2(hx2d)\n d3 = self.side3(hx3d)\n d4 = self.side4(hx4d)\n d5 = self.side5(hx5d)\n d6 = self.side6(hx6)\n\n d2 = _upsample_like1(d2,d1)\n d3 = _upsample_like1(d3,d1)\n d4 = _upsample_like1(d4,d1)\n d5 = _upsample_like1(d5,d1)\n d6 = _upsample_like1(d6,d1)\n\n d0 = self.outconv(torch.cat((d1,d2,d3,d4,d5,d6),1))\n d0 = _upsample_like1(d0,x)\n return x*F.relu(d0)#, F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)\n\nnet = U2NETP()\nd=torch.ones((1,2,512,512))\nnet.eval()\ns=net(d)\nt=time.time()\nfor i in range(10):\n s=net(d)\nt=time.time()-t\nprint(t/10.0)\n#dict=net.state_dict()\n#torch.save(dict,\"x.pt\")" ]
[ [ "torch.nn.BatchNorm2d", "torch.ones", "torch.nn.MaxPool2d", "torch.nn.functional.avg_pool2d", "torch.nn.functional.conv2d", "torch.nn.functional.upsample", "torch.nn.functional.relu", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.cat", "torch.nn.functional.interpolate" ] ]
daniel-dr-rojas/scipy
[ "8e418e38fe6c88105eeae8eeb53248d19a8286fb" ]
[ "scipy/special/_precompute/lambertw.py" ]
[ "\"\"\"Compute a Pade approximation for the principle branch of the\nLambert W function around 0 and compare it to various other\napproximations.\n\n\"\"\"\nimport numpy as np\n\ntry:\n import mpmath # type: ignore[import]\n import matplotlib.pyplot as plt\nexcept ImportError:\n pass\n\n\ndef lambertw_pade():\n derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)]\n p, q = mpmath.pade(derivs, 3, 2)\n return p, q\n\n\ndef main():\n print(__doc__)\n with mpmath.workdps(50):\n p, q = lambertw_pade()\n p, q = p[::-1], q[::-1]\n print(\"p = {}\".format(p))\n print(\"q = {}\".format(q))\n\n x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)\n x, y = np.meshgrid(x, y)\n z = x + 1j*y\n lambertw_std = []\n for z0 in z.flatten():\n lambertw_std.append(complex(mpmath.lambertw(z0)))\n lambertw_std = np.array(lambertw_std).reshape(x.shape)\n\n fig, axes = plt.subplots(nrows=3, ncols=1)\n # Compare Pade approximation to true result\n p = np.array([float(p0) for p0 in p])\n q = np.array([float(q0) for q0 in q])\n pade_approx = np.polyval(p, z)/np.polyval(q, z)\n pade_err = abs(pade_approx - lambertw_std)\n axes[0].pcolormesh(x, y, pade_err)\n # Compare two terms of asymptotic series to true result\n asy_approx = np.log(z) - np.log(np.log(z))\n asy_err = abs(asy_approx - lambertw_std)\n axes[1].pcolormesh(x, y, asy_err)\n # Compare two terms of the series around the branch point to the\n # true result\n p = np.sqrt(2*(np.exp(1)*z + 1))\n series_approx = -1 + p - p**2/3\n series_err = abs(series_approx - lambertw_std)\n im = axes[2].pcolormesh(x, y, series_err)\n\n fig.colorbar(im, ax=axes.ravel().tolist())\n plt.show()\n\n fig, ax = plt.subplots(nrows=1, ncols=1)\n pade_better = pade_err < asy_err\n im = ax.pcolormesh(x, y, pade_better)\n t = np.linspace(-0.3, 0.3)\n ax.plot(-2.5*abs(t) - 0.2, t, 'r')\n fig.colorbar(im, ax=ax)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.meshgrid", "matplotlib.pyplot.subplots", "numpy.exp", "matplotlib.pyplot.show", "numpy.log", "numpy.array", "numpy.polyval", "numpy.linspace" ] ]
alexpyattaev/pyquaternion
[ "19c3581799c220607ce327af5f1cbe9f98dba4e6" ]
[ "pyquaternion/test/test_quaternion.py" ]
[ "#!/usr/bin python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis file is part of the pyquaternion python module\n\nAuthor: Kieran Wynn\nWebsite: https://github.com/KieranWynn/pyquaternion\nDocumentation: http://kieranwynn.github.io/pyquaternion/\n\nVersion: 1.0.0\nLicense: The MIT License (MIT)\n\nCopyright (c) 2015 Kieran Wynn\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\ntest_quaternion.py - Unit test for quaternion module\n\n\"\"\"\n\nimport unittest\nfrom math import pi, sin, cos\nfrom random import random\n\nimport numpy as np\nimport pytest\n\nimport pyquaternion\nfrom pyquaternion.numba_opt import TypingError\nfrom pyquaternion.quaternion import z_axis, x_axis, to_str\n\nQuaternion = pyquaternion.Quaternion\n\nALMOST_EQUAL_TOLERANCE = 13\n\n\ndef randomElements():\n return tuple(np.random.uniform(-1, 1, 4))\n\n\ndef test_init_default():\n q = Quaternion()\n assert isinstance(q, Quaternion)\n assert q.eq(Quaternion(np.array((1., 0., 0., 0.))))\n\n\ndef test_init_junk():\n with pytest.raises(TypingError):\n q = Quaternion(\"blaaa\")\n with pytest.raises(TypingError):\n q = Quaternion(None)\n\n\ndef test_init_copy():\n q1 = Quaternion.random()\n q2 = q1.copy()\n\n assert q2.eq(q1)\n\n\ndef test_init_random(self):\n r1 = Quaternion.random()\n r2 = Quaternion.random()\n self.assertAlmostEqual(r1.norm, 1.0, ALMOST_EQUAL_TOLERANCE)\n self.assertIsInstance(r1, Quaternion)\n self.assertNotEqual(r1, r2) # TODO, this *may* fail at random\n\n\n\n\ndef test_init_from_elements():\n a, b, c, d = randomElements()\n q1 = Quaternion(np.array([a, b, c, d], dtype=float))\n\n # assert np.array_equal(q1.q, [a, b, c, d], dtype=float)\n with pytest.raises(ValueError):\n q = Quaternion(np.zeros(3))\n\n with pytest.raises(TypingError):\n q = Quaternion.from_scalar_and_vector(None, np.array([b, c, d]))\n\n\ndef test_init_from_array(self):\n r = randomElements()\n a = np.array(r)\n q = Quaternion(a)\n self.assertIsInstance(q, Quaternion)\n self.assertTrue(np.allclose(q.q, a))\n with self.assertRaises(ValueError):\n q = Quaternion(a[1:4]) # 3-vector\n with self.assertRaises(ValueError):\n q = Quaternion(np.hstack((a, a))) # 8-vector\n with self.assertRaises(ValueError):\n q = Quaternion(np.array([a, a])) # 2x4-\n\n\ndef test_init_from_explicit_rotation_params():\n vx = random()\n vy = random()\n vz = random()\n theta = random() * 2.0 * pi\n\n v1 = np.array([vx, vy, vz], dtype=float)\n v3 = np.copy(v1)\n\n q1 = Quaternion.from_axis_angle(axis=v1, angle=theta)\n\n with pytest.raises(ValueError):\n q1 = Quaternion.from_axis_angle(axis=np.zeros(3), angle=theta)\n # normalise v to a unit vector\n v3 = v3 / np.linalg.norm(v3)\n\n q4 = Quaternion.from_axis_angle(angle=theta, axis=v3)\n\n # Construct the true quaternion\n t = theta / 2.0\n\n a = cos(t)\n b = v3[0] * sin(t)\n c = v3[1] * sin(t)\n d = v3[2] * sin(t)\n\n truth = Quaternion(np.array([a, b, c, d]))\n\n assert q1.eq(truth)\n\n assert q4.eq(truth)\n\n assert Quaternion.from_axis_angle(np.array([1, 0, 0], dtype=float)).eq(Quaternion())\n\n # Result should be a versor (Unit Quaternion)\n assert abs(q1.norm - 1.0) < ALMOST_EQUAL_TOLERANCE\n\n with pytest.raises(Exception):\n q = Quaternion.from_axis_angle(angle=theta)\n with pytest.raises(TypingError):\n q = Quaternion.from_axis_angle(axis=[b, c], angle=theta)\n with pytest.raises(TypingError):\n q = Quaternion.from_axis_angle(axis=np.array([1, 2, 3], dtype=int), angle=theta)\n with pytest.raises(TypingError):\n q = Quaternion.from_axis_angle(axis=[b, c], angle=None)\n\n\ndef test_init_from_explicit_matrix():\n def R_z(theta):\n \"\"\"\n Generate a rotation matrix describing a rotation of theta degrees about the z-axis\n \"\"\"\n c = cos(theta)\n s = sin(theta)\n return np.array([\n [c, -s, 0],\n [s, c, 0],\n [0, 0, 1]])\n\n v = np.copy(x_axis)\n for angle in [0, pi / 6, pi / 4, pi / 2, pi, 4 * pi / 3, 3 * pi / 2, 2 * pi]:\n R = R_z(angle) # rotation matrix describing rotation of 90 about +z\n v_prime_r = np.dot(R, v)\n\n q1 = Quaternion.from_axis_angle(axis=z_axis, angle=angle)\n v_prime_q1 = q1.rotate(v)\n print(\"=====\" + str(angle))\n # assert np.allclose(v_prime_r, v_prime_q1)\n\n q2 = Quaternion.from_matrix(matrix=R)\n\n v_prime_q2 = q2.rotate(v)\n print(v_prime_q1)\n print(v_prime_q2)\n print(v_prime_r)\n # assert np.allclose(v_prime_q2, v_prime_r)\n\n R = np.matrix(np.eye(3))\n q3 = Quaternion.from_matrix(matrix=R)\n v_prime_q3 = q3.rotate(v)\n assert np.allclose(v, v_prime_q3)\n assert q3.eq(Quaternion())\n\n R[0, 1] += 3 # introduce error to make matrix non-orthogonal\n with pytest.raises(ValueError):\n q4 = Quaternion.from_matrix(matrix=R)\n\n\ndef test_init_from_explicit_matrix_with_optional_tolerance_arguments():\n \"\"\"\n The matrix defined in this test is orthogonal was carefully crafted\n such that it's orthogonal to a precision of 1e-06, but not to a precision\n of 1e-08.\n\n Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html\n \"\"\"\n m = [[0.73297226, -0.16524626, -0.65988294, -0.07654548],\n [0.13108627, 0.98617666, -0.10135052, -0.04878795],\n [0.66750896, -0.01221443, 0.74450167, -0.05474513],\n [0, 0, 0, 1, ]]\n npm = np.matrix(m)\n\n with pytest.raises(ValueError):\n Quaternion.from_matrix(matrix=npm)\n\n q1 = Quaternion.from_matrix(matrix=npm, atol=1e-6)\n\n\ndef test_str():\n a, b, c, d = randomElements()\n q = Quaternion(np.array([a, b, c, d], dtype=float))\n string = \"{:.3f} {:+.3f}i {:+.3f}j {:+.3f}k\".format(a, b, c, d)\n assert string == to_str(q)\n\n\ndef test_equality(self):\n r = randomElements()\n self.assertEqual(Quaternion(*r), Quaternion(*r))\n q = Quaternion(*r)\n self.assertEqual(q, q)\n # Equality should work with other types, if they can be interpreted as quaternions\n self.assertEqual(q, r)\n self.assertEqual(Quaternion(1., 0., 0., 0.), 1.0)\n with self.assertRaises(ValueError):\n Quaternion(\"1.32\")\n self.assertNotEqual(q, q + Quaternion(0.0, 0.002, 0.0, 0.0))\n\n # Equality should also cover small rounding and floating point errors\n self.assertEqual(Quaternion(1., 0., 0., 0.), Quaternion(1.0 - 1e-14, 0., 0., 0.))\n self.assertNotEqual(Quaternion(1., 0., 0., 0.), Quaternion(1.0 - 1e-12, 0., 0., 0.))\n self.assertNotEqual(Quaternion(160., 0., 0., 0.), Quaternion(160.0 - 1e-10, 0., 0., 0.))\n self.assertNotEqual(Quaternion(1600., 0., 0., 0.), Quaternion(1600.0 - 1e-9, 0., 0., 0.))\n\n with self.assertRaises(TypeError):\n q == None\n with self.assertRaises(ValueError):\n q == 's'\n\n\ndef test_assignment(self):\n a, b, c, d = randomElements()\n q1 = Quaternion(a, b, c, d)\n q2 = Quaternion(a, b * 0.1, c + 0.3, d)\n self.assertNotEqual(q1, q2)\n q2 = q1\n self.assertEqual(q1, q2)\n\n\ndef test_unary_minus(self):\n a, b, c, d = randomElements()\n q = Quaternion(a, b, c, d)\n self.assertEqual(-q, Quaternion(-a, -b, -c, -d))\n\n\ndef test_add(self):\n r1 = randomElements()\n r2 = randomElements()\n r = random()\n n = None\n\n q1 = Quaternion(*r1)\n q2 = Quaternion(*r2)\n q3 = Quaternion(array=np.array(r1) + np.array(r2))\n q4 = Quaternion(array=np.array(r2) + np.array([r, 0.0, 0.0, 0.0]))\n self.assertEqual(q1 + q2, q3)\n q1 += q2\n self.assertEqual(q1, q3)\n self.assertEqual(q2 + r, q4)\n self.assertEqual(r + q2, q4)\n\n with self.assertRaises(TypeError):\n q1 += n\n with self.assertRaises(TypeError):\n n += q1\n\n\ndef test_subtract(self):\n r1 = randomElements()\n r2 = randomElements()\n r = random()\n n = None\n\n q1 = Quaternion(*r1)\n q2 = Quaternion(*r2)\n q3 = Quaternion(array=np.array(r1) - np.array(r2))\n q4 = Quaternion(array=np.array(r2) - np.array([r, 0.0, 0.0, 0.0]))\n self.assertEqual(q1 - q2, q3)\n q1 -= q2\n self.assertEqual(q1, q3)\n self.assertEqual(q2 - r, q4)\n self.assertEqual(r - q2, -q4)\n\n with self.assertRaises(TypeError):\n q1 -= n\n with self.assertRaises(TypeError):\n n -= q1\n\n\ndef test_multiplication_of_bases():\n one = Quaternion(np.array([1.0, 0.0, 0.0, 0.0]))\n i = Quaternion(np.array([0.0, 1.0, 0.0, 0.0]))\n j = Quaternion(np.array([0.0, 0.0, 1.0, 0.0]))\n k = Quaternion(np.array([0.0, 0.0, 0.0, 1.0]))\n\n assert i.mul(i).eq(j.mul(j))\n assert j.mul(j).eq(k.mul(k))\n\n assert k.mul(k).eq(i.mul(j).mul(k))\n\n assert i.mul(j.mul(k)).eq(one.neg())\n\n assert i.mul(j).eq(k)\n assert i.mul(i).eq(one.neg())\n assert i.mul(k).eq(j.neg())\n assert j.mul(i).eq(k.neg())\n assert j.mul(j).eq(one.neg())\n assert j.mul(k).eq(i)\n assert k.mul(i).eq(j)\n assert k.mul(j).eq(i.neg())\n assert k.mul(k).eq(one.neg())\n assert i.mul(j).mul(k).eq(one.neg())\n\n # self.assertEqual(i * i, j * j)\n # self.assertEqual(j * j, k * k)\n # self.assertEqual(k * k, i * j * k)\n # self.assertEqual(i * j * k, -one)\n #\n # self.assertEqual(i * j, k)\n # self.assertEqual(i * i, -one)\n # self.assertEqual(i * k, -j)\n # self.assertEqual(j * i, -k)\n # self.assertEqual(j * j, -one)\n # self.assertEqual(j * k, i)\n # self.assertEqual(k * i, j)\n # self.assertEqual(k * j, -i)\n # self.assertEqual(k * k, -one)\n # self.assertEqual(i * j * k, -one)\n\n\ndef test_multiply_by_scalar():\n a, b, c, d = randomElements()\n q1 = Quaternion(np.array((a, b, c, d)))\n for s in [30.0, 0.3, -2, -4.7, 0]:\n\n q2 = Quaternion(s * a, s * b, s * c, s * d)\n S = Quaternion.from_scalar_and_vector(s)\n q3 = q1\n assert q1.mul(S).eq(q2) # post-multiply by scalar\n assert S.mul(q1).eq(q2) # pre-multiply by scalar\n q3 = q3.mul(S)\n assert q3.eq(q2)\n\n\ndef test_divide():\n r = np.random.rand(4)\n q = Quaternion(r)\n if q:\n assert q.div(q).eq(Quaternion())\n else:\n with pytest.raises(ZeroDivisionError):\n q.div(q)\n\n with pytest.raises(ZeroDivisionError):\n q.div(Quaternion.from_scalar_and_vector(0.0))\n\n\ndef test_division_of_bases():\n one = Quaternion(np.array([1.0, 0.0, 0.0, 0.0]))\n i = Quaternion(np.array([0.0, 1.0, 0.0, 0.0]))\n j = Quaternion(np.array([0.0, 0.0, 1.0, 0.0]))\n k = Quaternion(np.array([0.0, 0.0, 0.0, 1.0]))\n\n assert i.div(i).eq(j.div(j))\n # self.assertEqual(j / j, k / k)\n # self.assertEqual(k / k, one)\n # self.assertEqual(k / -k, -one)\n #\n # self.assertEqual(i / j, -k)\n # self.assertEqual(i / i, one)\n # self.assertEqual(i / k, j)\n # self.assertEqual(j / i, k)\n # self.assertEqual(j / j, one)\n # self.assertEqual(j / k, -i)\n # self.assertEqual(k / i, -j)\n # self.assertEqual(k / j, i)\n # self.assertEqual(k / k, one)\n # self.assertEqual(i / -j, k)\n\n\ndef test_divide_by_scalar():\n a, b, c, d = randomElements()\n q1 = Quaternion(a, b, c, d)\n for s in [30.0, 0.3, -2, -4.7]:\n q2 = Quaternion(a / s, b / s, c / s, d / s)\n q3 = q1\n self.assertEqual(q1 / s, q2)\n if q1:\n self.assertEqual(s / q1, q2.inverse)\n else:\n with self.assertRaises(ZeroDivisionError):\n s / q1\n\n q3 /= s\n self.assertEqual(q3, q2)\n\n with self.assertRaises(ZeroDivisionError):\n q4 = q1 / 0.0\n with self.assertRaises(TypeError):\n q4 = q1 / None\n with self.assertRaises(ValueError):\n q4 = q1 / 's'\n\n\ndef test_squared():\n one = Quaternion(1.0, 0.0, 0.0, 0.0)\n i = Quaternion(0.0, 1.0, 0.0, 0.0)\n j = Quaternion(0.0, 0.0, 1.0, 0.0)\n k = Quaternion(0.0, 0.0, 0.0, 1.0)\n\n self.assertEqual(i ** 2, j ** 2)\n self.assertEqual(j ** 2, k ** 2)\n self.assertEqual(k ** 2, -one)\n\n\ndef test_power():\n q1 = Quaternion.random()\n q2 = Quaternion(q1)\n self.assertEqual(q1 ** 0, Quaternion())\n self.assertEqual(q1 ** 1, q1)\n q2 **= 4\n self.assertEqual(q2, q1 * q1 * q1 * q1)\n self.assertEqual((q1 ** 0.5) * (q1 ** 0.5), q1)\n self.assertEqual(q1 ** -1, q1.inverse)\n self.assertEqual(4 ** Quaternion(2), Quaternion(16))\n with self.assertRaises(TypeError):\n q1 ** None\n with self.assertRaises(ValueError):\n q1 ** 's'\n q3 = Quaternion()\n self.assertEqual(q3 ** 0.5, q3) # Identity behaves as an identity\n self.assertEqual(q3 ** 5, q3)\n self.assertEqual(q3 ** 3.4, q3)\n q4 = Quaternion(scalar=5) # real number behaves as any other real number would\n self.assertEqual(q4 ** 4, Quaternion(scalar=5 ** 4))\n\n\ndef test_distributive():\n q1 = Quaternion.random()\n q2 = Quaternion.random()\n q3 = Quaternion.random()\n self.assertEqual(q1 * (q2 + q3), q1 * q2 + q1 * q3)\n\n\ndef test_noncommutative():\n q1 = Quaternion.random()\n q2 = Quaternion.random()\n if not q1 == q2: # Small chance of this happening with random initialisation\n self.assertNotEqual(q1 * q2, q2 * q1)\n\n\nclass TestQuaternionFeatures(unittest.TestCase):\n\n def test_conjugate(self):\n a, b, c, d = randomElements()\n q1 = Quaternion(a, b, c, d)\n q2 = Quaternion.random()\n self.assertEqual(q1.conjugate, Quaternion(a, -b, -c, -d))\n\n self.assertEqual((q1 * q2).conjugate, q2.conjugate * q1.conjugate)\n self.assertEqual((q1 + q1.conjugate) / 2, Quaternion(scalar=q1.scalar))\n self.assertEqual((q1 - q1.conjugate) / 2, Quaternion(vector=q1.vector))\n\n def test_double_conjugate(self):\n q = Quaternion.random()\n self.assertEqual(q, q.conjugate.conjugate)\n\n def test_norm(self):\n r = randomElements()\n q1 = Quaternion(*r)\n q2 = Quaternion.random()\n self.assertEqual(q1.norm, np.linalg.norm(np.array(r)))\n self.assertEqual(q1.magnitude, np.linalg.norm(np.array(r)))\n # Multiplicative norm\n self.assertAlmostEqual((q1 * q2).norm, q1.norm * q2.norm, ALMOST_EQUAL_TOLERANCE)\n # Scaled norm\n for s in [30.0, 0.3, -2, -4.7]:\n self.assertAlmostEqual((q1 * s).norm, q1.norm * abs(s), ALMOST_EQUAL_TOLERANCE)\n\n def test_inverse(self):\n q1 = Quaternion(randomElements())\n q2 = Quaternion.random()\n if q1:\n self.assertEqual(q1 * q1.inverse, Quaternion(1.0, 0.0, 0.0, 0.0))\n else:\n with self.assertRaises(ZeroDivisionError):\n q1 * q1.inverse\n\n self.assertEqual(q2 * q2.inverse, Quaternion(1.0, 0.0, 0.0, 0.0))\n\n def test_normalisation(self): # normalise to unit quaternion\n r = randomElements()\n q1 = Quaternion(*r)\n v = q1.unit\n n = q1.normalised\n\n if q1 == Quaternion(0): # small chance with random generation\n return # a 0 quaternion does not normalise\n\n # Test normalised objects are unit quaternions\n np.testing.assert_almost_equal(v.q, q1.elements / q1.norm, decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(n.q, q1.elements / q1.norm, decimal=ALMOST_EQUAL_TOLERANCE)\n self.assertAlmostEqual(v.norm, 1.0, ALMOST_EQUAL_TOLERANCE)\n self.assertAlmostEqual(n.norm, 1.0, ALMOST_EQUAL_TOLERANCE)\n # Test axis and angle remain the same\n np.testing.assert_almost_equal(q1.axis, v.axis, decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(q1.axis, n.axis, decimal=ALMOST_EQUAL_TOLERANCE)\n self.assertAlmostEqual(q1.angle, v.angle, ALMOST_EQUAL_TOLERANCE)\n self.assertAlmostEqual(q1.angle, n.angle, ALMOST_EQUAL_TOLERANCE)\n # Test special case where q is zero\n q2 = Quaternion(0)\n self.assertEqual(q2, q2.normalised)\n\n def test_is_unit(self):\n q1 = Quaternion()\n q2 = Quaternion(1.0, 0, 0, 0.0001)\n self.assertTrue(q1.is_unit())\n self.assertFalse(q2.is_unit())\n self.assertTrue(q2.is_unit(0.001))\n\n def test_q_matrix(self):\n a, b, c, d = randomElements()\n q = Quaternion(a, b, c, d)\n M = np.array([\n [a, -b, -c, -d],\n [b, a, -d, c],\n [c, d, a, -b],\n [d, -c, b, a]])\n self.assertTrue(np.array_equal(q._q_matrix(), M))\n\n def test_q_bar_matrix(self):\n a, b, c, d = randomElements()\n q = Quaternion(a, b, c, d)\n M = np.array([\n [a, -b, -c, -d],\n [b, a, d, -c],\n [c, -d, a, b],\n [d, c, -b, a]])\n self.assertTrue(np.array_equal(q._q_bar_matrix(), M))\n\n def test_output_of_components(self):\n a, b, c, d = randomElements()\n q = Quaternion(a, b, c, d)\n # Test scalar\n self.assertEqual(q.scalar, a)\n self.assertEqual(q.real, a)\n # Test vector\n self.assertTrue(np.array_equal(q.vector, [b, c, d]))\n self.assertTrue(np.array_equal(q.imaginary, [b, c, d]))\n self.assertEqual(tuple(q.vector), (b, c, d))\n self.assertEqual(list(q.imaginary), [b, c, d])\n self.assertEqual(q.w, a)\n self.assertEqual(q.x, b)\n self.assertEqual(q.y, c)\n self.assertEqual(q.z, d)\n\n def test_output_of_elements(self):\n r = randomElements()\n q = Quaternion(*r)\n self.assertEqual(tuple(q.elements), r)\n\n def test_element_access(self):\n r = randomElements()\n q = Quaternion(*r)\n self.assertEqual(q[0], r[0])\n self.assertEqual(q[1], r[1])\n self.assertEqual(q[2], r[2])\n self.assertEqual(q[3], r[3])\n self.assertEqual(q[-1], r[3])\n self.assertEqual(q[-4], r[0])\n with self.assertRaises(TypeError):\n q[None]\n with self.assertRaises(IndexError):\n q[4]\n with self.assertRaises(IndexError):\n q[-5]\n\n def test_element_assignment(self):\n q = Quaternion()\n self.assertEqual(q[1], 0.0)\n q[1] = 10.0\n self.assertEqual(q[1], 10.0)\n self.assertEqual(q, Quaternion(1.0, 10.0, 0.0, 0.0))\n with self.assertRaises(TypeError):\n q[2] = None\n with self.assertRaises(ValueError):\n q[2] = 's'\n\n def test_rotate(self):\n q = Quaternion(axis=[1, 1, 1], angle=2 * pi / 3)\n q2 = Quaternion(axis=[1, 0, 0], angle=-pi)\n q3 = Quaternion(axis=[1, 0, 0], angle=pi)\n precision = ALMOST_EQUAL_TOLERANCE\n for r in [1, 3.8976, -69.7, -0.000001]:\n # use np.testing.assert_almost_equal() to compare float sequences\n np.testing.assert_almost_equal(q.rotate((r, 0, 0)), (0, r, 0), decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(q.rotate([0, r, 0]), [0, 0, r], decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(q.rotate(np.array([0, 0, r])), np.array([r, 0, 0]),\n decimal=ALMOST_EQUAL_TOLERANCE)\n self.assertEqual(q.rotate(Quaternion(vector=[-r, 0, 0])), Quaternion(vector=[0, -r, 0]))\n np.testing.assert_almost_equal(q.rotate([0, -r, 0]), [0, 0, -r], decimal=ALMOST_EQUAL_TOLERANCE)\n self.assertEqual(q.rotate(Quaternion(vector=[0, 0, -r])), Quaternion(vector=[-r, 0, 0]))\n\n np.testing.assert_almost_equal(q2.rotate((r, 0, 0)), q3.rotate((r, 0, 0)), decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(q2.rotate((0, r, 0)), q3.rotate((0, r, 0)), decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(q2.rotate((0, 0, r)), q3.rotate((0, 0, r)), decimal=ALMOST_EQUAL_TOLERANCE)\n\n def test_conversion_to_matrix(self):\n q = Quaternion.random()\n a, b, c, d = tuple(q.elements)\n R = np.array([\n [a ** 2 + b ** 2 - c ** 2 - d ** 2, 2 * (b * c - a * d), 2 * (a * c + b * d)],\n [2 * (b * c + a * d), a ** 2 - b ** 2 + c ** 2 - d ** 2, 2 * (c * d - a * b)],\n [2 * (b * d - a * c), 2 * (a * b + c * d), a ** 2 - b ** 2 - c ** 2 + d ** 2]])\n t = np.array([[0], [0], [0]])\n T = np.vstack([np.hstack([R, t]), np.array([0, 0, 0, 1])])\n np.testing.assert_almost_equal(R, q.rotation_matrix, decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(T, q.transformation_matrix, decimal=ALMOST_EQUAL_TOLERANCE)\n\n # Test no scaling of rotated vectors\n v1 = np.array([1, 0, 0])\n v2 = np.hstack((np.random.uniform(-10, 10, 3), 1.0))\n v1_ = np.dot(q.rotation_matrix, v1)\n v2_ = np.dot(q.transformation_matrix, v2)\n self.assertAlmostEqual(np.linalg.norm(v1_), 1.0, ALMOST_EQUAL_TOLERANCE)\n self.assertAlmostEqual(np.linalg.norm(v2_), np.linalg.norm(v2), ALMOST_EQUAL_TOLERANCE)\n\n # Test transformation of vectors is equivalent for quaternion & matrix\n np.testing.assert_almost_equal(v1_, q.rotate(v1), decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(v2_[0:3], q.rotate(v2[0:3]), decimal=ALMOST_EQUAL_TOLERANCE)\n\n def test_conversion_to_ypr(self):\n\n def R_x(theta):\n c = cos(theta)\n s = sin(theta)\n return np.array([\n [1, 0, 0],\n [0, c, -s],\n [0, s, c]])\n\n def R_y(theta):\n c = cos(theta)\n s = sin(theta)\n return np.array([\n [c, 0, s],\n [0, 1, 0],\n [-s, 0, c]])\n\n def R_z(theta):\n c = cos(theta)\n s = sin(theta)\n return np.array([\n [c, -s, 0],\n [s, c, 0],\n [0, 0, 1]])\n\n p = np.random.randn(3)\n q = Quaternion.random()\n yaw, pitch, roll = q.yaw_pitch_roll\n\n p_q = q.rotate(p)\n R_q = q.rotation_matrix\n\n # build rotation matrix, R = R_z(yaw)*R_y(pitch)*R_x(roll)\n R_ypr = np.dot(R_x(roll), np.dot(R_y(pitch), R_z(yaw)))\n p_ypr = np.dot(R_ypr, p)\n\n np.testing.assert_almost_equal(p_q, p_ypr, decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(R_q, R_ypr, decimal=ALMOST_EQUAL_TOLERANCE)\n\n def test_matrix_io(self):\n v = np.random.uniform(-100, 100, 3)\n\n for i in range(10):\n q0 = Quaternion.random()\n R = q0.rotation_matrix\n q1 = Quaternion(matrix=R)\n np.testing.assert_almost_equal(q0.rotate(v), np.dot(R, v), decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(q0.rotate(v), q1.rotate(v), decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(q1.rotate(v), np.dot(R, v), decimal=ALMOST_EQUAL_TOLERANCE)\n\n self.assertTrue((q0 == q1) or (q0 == -q1)) # q1 and -q1 are equivalent rotations\n\n def validate_axis_angle(self, axis, angle):\n\n def wrap_angle(theta):\n \"\"\" Wrap any angle to lie between -pi and pi\n\n Odd multiples of pi are wrapped to +pi (as opposed to -pi)\n \"\"\"\n result = ((theta + pi) % (2 * pi)) - pi\n if result == -pi: result = pi\n return result\n\n theta = wrap_angle(angle)\n v = axis\n\n q = Quaternion(angle=theta, axis=v)\n\n v_ = q.axis\n theta_ = q.angle\n\n if theta == 0.0: # axis is irrelevant (check defaults to x=y=z)\n np.testing.assert_almost_equal(theta_, 0.0, decimal=ALMOST_EQUAL_TOLERANCE)\n np.testing.assert_almost_equal(v_, np.zeros(3), decimal=ALMOST_EQUAL_TOLERANCE)\n return\n elif abs(theta) == pi: # rotation in either direction is equivalent\n self.assertTrue(\n np.isclose(theta, pi) or np.isclose(theta, -pi)\n and\n np.isclose(v, v_).all() or np.isclose(v, -v_).all()\n )\n else:\n self.assertTrue(\n np.isclose(theta, theta_) and np.isclose(v, v_).all()\n or\n np.isclose(theta, -theta_) and np.isclose(v, -v_).all()\n )\n # Ensure the returned axis is a unit vector\n np.testing.assert_almost_equal(np.linalg.norm(v_), 1.0, decimal=ALMOST_EQUAL_TOLERANCE)\n\n def test_conversion_to_axis_angle(self):\n random_axis = np.random.uniform(-1, 1, 3)\n random_axis /= np.linalg.norm(random_axis)\n\n angles = np.array([-3, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 3]) * pi\n axes = [np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 1]), random_axis]\n\n for v in axes:\n for theta in angles:\n self.validate_axis_angle(v, theta)\n\n def test_axis_angle_io(self):\n for i in range(20):\n v = np.random.uniform(-1, 1, 3)\n v /= np.linalg.norm(v)\n theta = float(np.random.uniform(-2, 2, 1)) * pi\n self.validate_axis_angle(v, theta)\n\n def test_exp(self):\n from math import exp\n q = Quaternion(axis=[1, 0, 0], angle=pi)\n exp_q = Quaternion.exp(q)\n self.assertEqual(exp_q, exp(0) * Quaternion(scalar=cos(1.0), vector=[sin(1.0), 0, 0]))\n\n def test_log(self):\n from math import log\n q = Quaternion(axis=[1, 0, 0], angle=pi)\n log_q = Quaternion.log(q)\n self.assertEqual(log_q, Quaternion(scalar=0, vector=[pi / 2, 0, 0]))\n\n def test_distance(self):\n q = Quaternion(scalar=0, vector=[1, 0, 0])\n p = Quaternion(scalar=0, vector=[0, 1, 0])\n self.assertEqual(pi / 2, Quaternion.distance(q, p))\n q = Quaternion(angle=pi / 2, axis=[1, 0, 0])\n p = Quaternion(angle=pi / 2, axis=[0, 1, 0])\n self.assertEqual(pi / 3, Quaternion.distance(q, p))\n q = Quaternion(scalar=1, vector=[1, 1, 1])\n p = Quaternion(scalar=-1, vector=[-1, -1, -1])\n p._normalise()\n q._normalise()\n self.assertAlmostEqual(0, Quaternion.distance(q, p), places=8)\n\n def test_absolute_distance(self):\n q = Quaternion(scalar=0, vector=[1, 0, 0])\n p = Quaternion(scalar=0, vector=[0, 1, 0])\n self.assertEqual((q - p).norm, Quaternion.absolute_distance(q, p))\n q = Quaternion(angle=pi / 2, axis=[1, 0, 0])\n p = Quaternion(angle=pi / 2, axis=[0, 1, 0])\n self.assertEqual((q - p).norm, Quaternion.absolute_distance(q, p))\n q = Quaternion(scalar=0, vector=[1, 0, 0])\n p = Quaternion(scalar=-1, vector=[0, -1, 0])\n self.assertEqual((q + p).norm, Quaternion.absolute_distance(q, p))\n q = Quaternion(scalar=1, vector=[1, 1, 1])\n p = Quaternion(scalar=-1, vector=[-1, -1, -1])\n p._normalise()\n q._normalise()\n self.assertAlmostEqual(0, Quaternion.absolute_distance(q, p), places=8)\n\n def test_sym_distance(self):\n q = Quaternion(scalar=0, vector=[1, 0, 0])\n p = Quaternion(scalar=0, vector=[0, 1, 0])\n self.assertEqual(pi / 2, Quaternion.sym_distance(q, p))\n q = Quaternion(angle=pi / 2, axis=[1, 0, 0])\n p = Quaternion(angle=pi / 2, axis=[0, 1, 0])\n self.assertAlmostEqual(pi / 3, Quaternion.sym_distance(q, p), places=6)\n q = Quaternion(scalar=0, vector=[1, 0, 0])\n p = Quaternion(scalar=0, vector=[0, -1, 0])\n self.assertEqual(pi / 2, Quaternion.sym_distance(q, p))\n # TODO: this is numerically unstable, previous EPS of 1e-17 was too low for double precision floats\n # q = Quaternion(scalar=1, vector=[1, 1, 1])\n # p = Quaternion(scalar=-1, vector=[-1, -1, -1])\n # p._normalise()\n # q._normalise()\n # self.assertAlmostEqual(pi, Quaternion.sym_distance(q, p), places=8)\n\n def test_slerp(self):\n q1 = Quaternion(axis=[1, 0, 0], angle=0.0)\n q2 = Quaternion(axis=[1, 0, 0], angle=pi / 2)\n q3 = Quaternion.slerp(q1, q2, 0.5)\n self.assertEqual(q3, Quaternion(axis=[1, 0, 0], angle=pi / 4))\n\n def test_slerp_extensive(self):\n for axis in [[1, 0, 0], [0, 1, 0], [0, 0, 1]]:\n q1 = Quaternion(axis=axis, angle=0.0)\n q2 = Quaternion(axis=axis, angle=pi / 2.0)\n q3 = Quaternion(axis=axis, angle=pi * 3.0 / 2.0)\n for t in np.arange(0.1, 1, 0.1):\n q4 = Quaternion.slerp(q1, q2, t)\n q5 = Quaternion.slerp(q1, q3, t)\n q6 = Quaternion(axis=axis, angle=t * pi / 2)\n q7 = Quaternion(axis=axis, angle=-t * pi / 2)\n assert q4 == q6 or q4 == -q6\n assert q5 == q7 or q5 == -q7\n\n def test_interpolate(self):\n q1 = Quaternion(axis=[1, 0, 0], angle=0.0)\n q2 = Quaternion(axis=[1, 0, 0], angle=2 * pi / 3)\n num_intermediates = 3\n base = pi / 6\n list1 = list(Quaternion.intermediates(q1, q2, num_intermediates, include_endpoints=False))\n list2 = list(Quaternion.intermediates(q1, q2, num_intermediates, include_endpoints=True))\n self.assertEqual(len(list1), num_intermediates)\n self.assertEqual(len(list2), num_intermediates + 2)\n self.assertEqual(list1[0], list2[1])\n self.assertEqual(list1[1], list2[2])\n self.assertEqual(list1[2], list2[3])\n\n self.assertEqual(list2[0], q1)\n self.assertEqual(list2[1], Quaternion(axis=[1, 0, 0], angle=base))\n self.assertEqual(list2[2], Quaternion(axis=[1, 0, 0], angle=2 * base))\n self.assertEqual(list2[3], Quaternion(axis=[1, 0, 0], angle=3 * base))\n self.assertEqual(list2[4], q2)\n\n def test_differentiation(self):\n q = Quaternion.random()\n omega = np.random.uniform(-1, 1, 3) # Random angular velocity\n\n q_dash = 0.5 * q * Quaternion(vector=omega)\n\n self.assertEqual(q_dash, q.derivative(omega))\n\n def test_integration(self):\n rotation_rate = [0, 0, 2 * pi] # one rev per sec around z\n v = [1, 0, 0] # test vector\n for dt in [0, 0.25, 0.5, 0.75, 1, 2, 10, 1e-10, random() * 10]: # time step in seconds\n qt = Quaternion() # no rotation\n qt.integrate(rotation_rate, dt)\n q_truth = Quaternion(axis=[0, 0, 1], angle=dt * 2 * pi)\n a = qt.rotate(v)\n b = q_truth.rotate(v)\n np.testing.assert_almost_equal(a, b, decimal=ALMOST_EQUAL_TOLERANCE)\n self.assertTrue(qt.is_unit())\n # Check integrate() is norm-preserving over many calls\n q = Quaternion()\n for i in range(1000):\n q.integrate([pi, 0, 0], 0.001)\n self.assertTrue(q.is_unit())\n\n\nclass TestQuaternionUtilities(unittest.TestCase):\n def test_copy(self):\n from copy import copy\n q = Quaternion.random()\n q2 = copy(q)\n self.assertEqual(q, q2)\n self.assertFalse(q is q2)\n self.assertTrue(all(q.q == q2.q))\n\n def test_deep_copy(self):\n from copy import deepcopy\n q = Quaternion.random()\n q2 = deepcopy(q)\n self.assertEqual(q, q2)\n self.assertFalse(q is q2)\n self.assertFalse(q.q is q2.q)\n\n\nclass TestQuaternionHashing(unittest.TestCase):\n def test_equal_quaternions(self):\n q1 = Quaternion(np.array([1, 0, 0, 0]))\n q2 = Quaternion(np.array([1, 0, 0, 0]))\n\n self.assertEqual(hash(q1), hash(q2))\n\n def test_unequal_quaternions(self):\n q1 = Quaternion(np.array([1, 0, 0, 0]))\n q2 = Quaternion(np.array([0, 1, 0, 0]))\n\n self.assertNotEqual(hash(q1), hash(q2))\n\n\nclass TestSwingTwist(unittest.TestCase):\n \"\"\"\n tests the swing-twist decomposition\n source: https://github.com/CCP-NC/soprano/blob/master/tests/utils_tests.py\n \"\"\"\n\n def test_swing_twist(self):\n test_n = 10\n\n for t_i in range(test_n):\n # Create two quaternions with random rotations\n theta1, theta2 = np.random.random(2) * 2 * np.pi\n ax1 = np.random.random(3)\n ax2 = np.cross(np.random.random(3), ax1)\n ax1 /= np.linalg.norm(ax1)\n ax2 /= np.linalg.norm(ax2)\n\n q1 = Quaternion(np.array([np.cos(theta1 / 2)] + list(ax1 * np.sin(theta1 / 2))))\n q2 = Quaternion(np.array([np.cos(theta2 / 2)] + list(ax2 * np.sin(theta2 / 2))))\n\n qT = q1 * q2\n\n # Now decompose\n qsw, qtw = qT.swing_twist_decomp(ax2)\n # And check\n q1.q *= np.sign(q1.q[0])\n q2.q *= np.sign(q2.q[0])\n qsw.q *= np.sign(qsw.q[0])\n qtw.q *= np.sign(qtw.q[0])\n\n self.assertTrue(np.allclose(q1.q, qsw.q))\n self.assertTrue(np.allclose(q2.q, qtw.q))\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.isclose", "numpy.copy", "numpy.testing.assert_almost_equal", "numpy.allclose", "numpy.cos", "numpy.random.rand", "numpy.random.uniform", "numpy.eye", "numpy.zeros", "numpy.arange", "numpy.hstack", "numpy.linalg.norm", "numpy.sign", "numpy.matrix", "numpy.random.randn", "numpy.random.random", "numpy.array_equal", "numpy.array", "numpy.sin", "numpy.dot" ] ]
prajwal309/HAPILite_Modified
[ "e0527328569ef8bd576114b1619ac5c87ff8c5b2" ]
[ "GenerateDatabase.py" ]
[ "import glob\nimport numpy as np\nfrom lib.CrossSectionFunctions import GetWaveNumbers, BinModel\nimport matplotlib.pyplot as plt\nimport os\nimport itertools\nimport time\nimport multiprocessing as mp\n\n#parse the parameters.ini which contains the information\nData = [f.split(\":\") for f in open(\"CrossSectionParams/Parameters.ini\",'r+')][1:]\nValues = [Item[1].split(\"#\")[0] for Item in Data]\n\n\n#Load the parameters for creating\nTempStart = float(Values[0]) #Step size of the temperature\nTempStop = float(Values[1]) #Step size of the temperature\nTempStep = float(Values[2]) #Step size of the temperature\n\nexpP_Start = float(Values[3]) #The largest log10(pressure) in atm\nexpP_Stop = float(Values[4]) #The smallest log10(pressure) in atm\nexpP_Step = float(Values[5]) #Step size of the pressure\n\n\nBroadener = Values[6].replace(\" \",\"\") #Broadening either self or air at this point\nOmegaWidth = float(Values[7]) #Consider the omegawidth -- how far the lines have to be considered\nLowWavelength = float(Values[8]) #Shortest Wavelength coverage range\nHighWavelength = float(Values[9]) #Longest Wavelength coverage range\nWN_Resolution = float(Values[10]) #Resolution of the Wave Number\nLineShapeProfile = Values[11].replace(\" \",\"\") #Voigt profile by default\nMoleculeList = Values[12].split(\",\") #Get the list of Molecular species\nCores = int(Values[13])\nError = Values[14].replace(\"\\t\",\"\")\n\n\n\nTempRange = np.arange(TempStart,TempStop+TempStep, TempStep) #Temperature in K\nexpP_Range = np.arange(expP_Start, expP_Stop-expP_Step, -expP_Step) #Pressure in log(P) atm\n\n\n#Define the wavenumber range values...\nWaveNumberStart = 1./(HighWavelength*1.e-7) #in per cm\nWaveNumberStop= 1./(LowWavelength*1.e-7) #in per cm\nWaveNumberRange = np.arange(WaveNumberStart, WaveNumberStop, WN_Resolution)\n#Plotting in the ascending order\nWaveLengthRange = 1./WaveNumberRange\nWaveLengthRange = WaveLengthRange[::-1]\n\n\n\n#Now get the assign the resolution values\nResolution = 10000\n\n#Low resolution wavelength\nWavelength_LR, WaveNumber_LR = GetWaveNumbers(LowWavelength, HighWavelength, Resolution)\n\n\nFolder2Save = \"R1SIG\"+str(Resolution)\n\nif not(os.path.exists(Folder2Save)):\n os.system(\"mkdir %s\" %(Folder2Save))\n\nnp.savetxt(Folder2Save+\"/Temperature.txt\", TempRange, delimiter=\",\")\nnp.savetxt(Folder2Save+\"/exp_Pressure.txt\", expP_Range, delimiter=\",\")\nnp.savetxt(Folder2Save+\"/WaveLength.txt\", Wavelength_LR, delimiter=\",\")\nnp.savetxt(Folder2Save+\"/Molecules.txt\", MoleculeList, delimiter=\",\", fmt='%s')\n\nBaseLocation = \"DataMatrix1SIG/\"\nMoleculesFiles = glob.glob(BaseLocation+\"*.npy\")\nNumMolecules = len(MoleculesFiles)\nNumTempValues = len(TempRange)\nNumPValues = len(expP_Range)\nNumWL_Values = len(Wavelength_LR)\n\n#Initiate a database matrix\nDatabaseMatrix = np.ones((NumTempValues, NumPValues, NumMolecules, NumWL_Values), dtype=np.float32)\n\nStartTime = time.time()\nfor MoleculeCount, Molecule in enumerate(MoleculeList):\n #Read the molecule name\n MoleculeLocation = BaseLocation+Molecule+\".npy\"\n TP_Counter = list(itertools.product(range(len(TempRange)),range(len(expP_Range))))\n\n #Using multiprocessing\n SigmaMatrix = np.load(MoleculeLocation,mmap_mode='r')\n\n print(\"The molecule is given by::\", Molecule, \". Now loading the data....\")\n print(\"The location of the molecule is given by::\", MoleculeLocation)\n\n while(len(TP_Counter)>0):\n NUMCORES = min([mp.cpu_count(), len(TP_Counter)])\n CPU_Pool = mp.Pool(NUMCORES)\n Tasks = []\n TempCounterValues = []\n PCounterValues = []\n for i in range(NUMCORES):\n\n Item = TP_Counter[0]\n TempCounter, PCounter = Item\n TempCounterValues.append(TempCounter)\n PCounterValues.append(PCounter)\n TP_Counter.pop(0)\n\n #High resolution cross-section data\n Sigma_HR = SigmaMatrix[TempCounter, PCounter, :]\n Tasks.append(CPU_Pool.apply_async(BinModel, (WaveLengthRange, Sigma_HR, Wavelength_LR)))\n\n CPU_Pool.close()\n CPU_Pool.join()\n\n for Count, task in enumerate(Tasks):\n Result=task.get()\n #Assign the value to the datamatrix\n DatabaseMatrix[TempCounterValues[Count], PCounterValues[Count], MoleculeCount,:] = Result\n\n\n\n#Now save the datamatrix\nprint(\"Time taken::\", time.time() - StartTime)\nnp.save(Folder2Save+\"/DataBase_%d.npy\" %Resolution, DatabaseMatrix)\n" ]
[ [ "numpy.save", "numpy.load", "numpy.ones", "numpy.savetxt", "numpy.arange" ] ]
anzelpwj/arviz
[ "3aba6c9d1831199631a8e48ecc82ed482bdf00e8" ]
[ "arviz/plots/backends/bokeh/bokeh_violinplot.py" ]
[ "\"\"\"Bokeh Violinplot.\"\"\"\nimport bokeh.plotting as bkp\nfrom bokeh.layouts import gridplot\nfrom bokeh.models.annotations import Title\nimport numpy as np\n\nfrom ....stats import hpd\nfrom ....stats.stats_utils import histogram\nfrom ...kdeplot import _fast_kde\nfrom ...plot_utils import get_bins, make_label, _create_axes_grid\n\n\ndef _plot_violin(\n ax,\n plotters,\n figsize,\n rows,\n cols,\n sharey,\n kwargs_shade,\n shade,\n bw,\n credible_interval,\n linewidth,\n quartiles,\n show,\n):\n if ax is None:\n _, ax = _create_axes_grid(\n len(plotters),\n rows,\n cols,\n sharey=sharey,\n figsize=figsize,\n squeeze=False,\n backend=\"bokeh\",\n )\n\n ax = np.atleast_1d(ax)\n\n for (var_name, selection, x), ax_ in zip(plotters, ax.flatten()):\n val = x.flatten()\n if val[0].dtype.kind == \"i\":\n cat_hist(val, shade, ax_, **kwargs_shade)\n else:\n _violinplot(val, shade, bw, ax_, **kwargs_shade)\n\n per = np.percentile(val, [25, 75, 50])\n hpd_intervals = hpd(val, credible_interval, multimodal=False)\n\n if quartiles:\n ax_.line([0, 0], per[:2], line_width=linewidth * 3, line_color=\"black\")\n ax_.line([0, 0], hpd_intervals, line_width=linewidth, line_color=\"black\")\n ax_.circle(0, per[-1])\n\n _title = Title()\n _title.text = make_label(var_name, selection)\n ax_.title = _title\n ax_.xaxis.major_tick_line_color = None\n ax_.xaxis.minor_tick_line_color = None\n ax_.xaxis.major_label_text_font_size = \"0pt\"\n\n if show:\n grid = gridplot([list(item) for item in ax], toolbar_location=\"above\")\n bkp.show(grid)\n\n return ax\n\n\ndef _violinplot(val, shade, bw, ax, **kwargs_shade):\n \"\"\"Auxiliary function to plot violinplots.\"\"\"\n density, low_b, up_b = _fast_kde(val, bw=bw)\n x = np.linspace(low_b, up_b, len(density))\n\n x = np.concatenate([x, x[::-1]])\n density = np.concatenate([-density, density[::-1]])\n\n ax.patch(density, x, fill_alpha=shade, line_width=0, **kwargs_shade)\n\n\ndef cat_hist(val, shade, ax, **kwargs_shade):\n \"\"\"Auxiliary function to plot discrete-violinplots.\"\"\"\n bins = get_bins(val)\n _, binned_d, _ = histogram(val, bins=bins)\n\n bin_edges = np.linspace(np.min(val), np.max(val), len(bins))\n centers = 0.5 * (bin_edges + np.roll(bin_edges, 1))[:-1]\n heights = np.diff(bin_edges)\n\n lefts = -0.5 * binned_d\n\n ax.hbar(\n y=centers,\n left=lefts,\n right=-lefts,\n height=heights,\n fill_alpha=shade,\n line_alpha=shade,\n line_color=None,\n **kwargs_shade\n )\n" ]
[ [ "numpy.roll", "numpy.diff", "numpy.atleast_1d", "numpy.max", "numpy.min", "numpy.concatenate", "numpy.percentile" ] ]
jopasserat/he-transformer
[ "d2865be507d2e20568ca5289513925c813aa59e6" ]
[ "examples/pyclient_mnist.py" ]
[ "import time\nimport argparse\nimport numpy as np\nimport sys\nimport os\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport he_seal_client\n\nFLAGS = None\n\n\ndef test_mnist_cnn(FLAGS):\n mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)\n batch_size = FLAGS.batch_size\n x_test_batch = mnist.test.images[:batch_size]\n y_test_batch = mnist.test.labels[:batch_size]\n\n data = x_test_batch.flatten('F')\n print('Client batch size from FLAG: ', batch_size)\n\n complex_scale_factor = 1\n if ('NGRAPH_COMPLEX_PACK' in os.environ):\n complex_scale_factor = 2\n\n print('complex_scale_factor', complex_scale_factor)\n\n # TODO: support even batch sizes\n assert (batch_size % complex_scale_factor == 0)\n\n hostname = 'localhost'\n port = 34000\n\n new_batch_size = batch_size // complex_scale_factor\n print('new_batch_size', new_batch_size)\n\n client = he_seal_client.HESealClient(hostname, port, new_batch_size, data)\n\n print('Sleeping until client is done')\n while not client.is_done():\n time.sleep(1)\n\n results = client.get_results()\n results = np.round(results, 2)\n\n y_pred_reshape = np.array(results).reshape(10, batch_size)\n with np.printoptions(precision=3, suppress=True):\n print(y_pred_reshape.T)\n\n y_pred = y_pred_reshape.argmax(axis=0)\n print('y_pred', y_pred)\n y_true = y_test_batch.argmax(axis=1)\n\n correct = np.sum(np.equal(y_pred, y_true))\n acc = correct / float(batch_size)\n print('pred size', len(y_pred))\n print('correct', correct)\n print('Accuracy (batch size', batch_size, ') =', acc * 100., '%')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--data_dir',\n type=str,\n default='/tmp/tensorflow/mnist/input_data',\n help='Directory where input data is stored')\n parser.add_argument('--batch_size', type=int, default=1, help='Batch size')\n\n FLAGS, unparsed = parser.parse_known_args()\n\n test_mnist_cnn(FLAGS)\n" ]
[ [ "numpy.equal", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "numpy.printoptions", "numpy.round", "numpy.array" ] ]
ajweiss/tensorflow
[ "2f4d4da52f0c488417d7e917edaf1b7569b5e408" ]
[ "tensorflow/python/autograph/pyct/ast_util.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"AST manipulation utilities.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ast\n\nimport gast\n\nfrom tensorflow.python.autograph.pyct import anno\nfrom tensorflow.python.autograph.pyct import parser\nfrom tensorflow.python.util import tf_inspect\n\n\nclass CleanCopier(object):\n \"\"\"NodeTransformer-like visitor that copies an AST.\"\"\"\n\n def __init__(self, preserve_annos):\n super(CleanCopier, self).__init__()\n self.preserve_annos = preserve_annos\n\n def copy(self, node):\n \"\"\"Returns a deep copy of node (excluding some fields, see copy_clean).\"\"\"\n\n if isinstance(node, list):\n return [self.copy(n) for n in node]\n elif isinstance(node, tuple):\n return tuple(self.copy(n) for n in node)\n elif not isinstance(node, (gast.AST, ast.AST)):\n # Assuming everything that's not an AST, list or tuple is a value type\n # and may simply be assigned.\n return node\n\n assert isinstance(node, (gast.AST, ast.AST))\n\n new_fields = {}\n for f in node._fields:\n if not f.startswith('__') and hasattr(node, f):\n new_fields[f] = self.copy(getattr(node, f))\n new_node = type(node)(**new_fields)\n\n if self.preserve_annos:\n for k in self.preserve_annos:\n anno.copyanno(node, new_node, k)\n return new_node\n\n\ndef copy_clean(node, preserve_annos=None):\n \"\"\"Creates a deep copy of an AST.\n\n The copy will not include fields that are prefixed by '__', with the\n exception of user-specified annotations.\n\n Args:\n node: ast.AST\n preserve_annos: Optional[Set[Hashable]], annotation keys to include in the\n copy\n Returns:\n ast.AST\n \"\"\"\n return CleanCopier(preserve_annos).copy(node)\n\n\nclass SymbolRenamer(gast.NodeTransformer):\n \"\"\"Transformer that can rename symbols to a simple names.\"\"\"\n\n def __init__(self, name_map):\n self.name_map = name_map\n\n def _process(self, node):\n qn = anno.getanno(node, anno.Basic.QN)\n if qn in self.name_map:\n new_node = gast.Name(str(self.name_map[qn]), node.ctx, None)\n # All annotations get carried over.\n for k in anno.keys(node):\n anno.copyanno(node, new_node, k)\n return new_node\n return self.generic_visit(node)\n\n def visit_Name(self, node):\n return self._process(node)\n\n def visit_Attribute(self, node):\n if anno.hasanno(node, anno.Basic.QN):\n return self._process(node)\n # Attributes of dynamic objects will not have a QN.\n return self.generic_visit(node)\n\n\ndef rename_symbols(node, name_map):\n \"\"\"Renames symbols in an AST. Requires qual_names annotations.\"\"\"\n renamer = SymbolRenamer(name_map)\n if isinstance(node, list):\n return [renamer.visit(n) for n in node]\n elif isinstance(node, tuple):\n return tuple(renamer.visit(n) for n in node)\n return renamer.visit(node)\n\n\ndef keywords_to_dict(keywords):\n \"\"\"Converts a list of ast.keyword objects to a dict.\"\"\"\n keys = []\n values = []\n for kw in keywords:\n keys.append(gast.Str(kw.arg))\n values.append(kw.value)\n return gast.Dict(keys=keys, values=values)\n\n\nclass PatternMatcher(gast.NodeVisitor):\n \"\"\"Matches a node against a pattern represented by a node.\"\"\"\n\n def __init__(self, pattern):\n self.pattern = pattern\n self.pattern_stack = []\n self.matches = True\n\n def compare_and_visit(self, node, pattern):\n self.pattern_stack.append(self.pattern)\n self.pattern = pattern\n self.generic_visit(node)\n self.pattern = self.pattern_stack.pop()\n\n def no_match(self):\n self.matches = False\n return False\n\n def is_wildcard(self, p):\n if isinstance(p, (list, tuple)) and len(p) == 1:\n p, = p\n if isinstance(p, gast.Name) and p.id == '_':\n return True\n if p == '_':\n return True\n return False\n\n def generic_visit(self, node):\n if not self.matches:\n return\n\n pattern = self.pattern\n for f in node._fields:\n if f.startswith('__'):\n continue\n\n if not hasattr(node, f):\n if hasattr(pattern, f) and getattr(pattern, f):\n return self.no_match()\n else:\n continue\n if not hasattr(pattern, f):\n return self.no_match()\n\n v = getattr(node, f)\n p = getattr(pattern, f)\n\n if self.is_wildcard(p):\n continue\n if isinstance(v, (list, tuple)):\n if not isinstance(p, (list, tuple)) or len(v) != len(p):\n return self.no_match()\n for v_item, p_item in zip(v, p):\n self.compare_and_visit(v_item, p_item)\n elif isinstance(v, (gast.AST, ast.AST)):\n if not isinstance(v, type(p)) and not isinstance(p, type(v)):\n return self.no_match()\n self.compare_and_visit(v, p)\n else:\n # Assume everything else is a value type.\n if v != p:\n return self.no_match()\n\n\ndef matches(node, pattern):\n \"\"\"Basic pattern matcher for AST.\n\n The pattern may contain wildcards represented by the symbol '_'. A node\n matches a pattern if for every node in the tree, either there is a node of\n the same type in pattern, or a Name node with id='_'.\n\n Args:\n node: ast.AST\n pattern: ast.AST\n Returns:\n bool\n \"\"\"\n if isinstance(pattern, str):\n pattern, = parser.parse_str(pattern).body\n\n matcher = PatternMatcher(pattern)\n matcher.visit(node)\n return matcher.matches\n\n\n# TODO(mdan): Once we have error tracing, we may be able to just go to SSA.\ndef apply_to_single_assignments(targets, values, apply_fn):\n \"\"\"Applies a function to each individual assignment.\n\n This function can process a possibly-unpacked (e.g. a, b = c, d) assignment.\n It tries to break down the unpacking if possible. In effect, it has the same\n effect as passing the assigned values in SSA form to apply_fn.\n\n Examples:\n\n The following will result in apply_fn(a, c), apply_fn(b, d):\n\n a, b = c, d\n\n The following will result in apply_fn(a, c[0]), apply_fn(b, c[1]):\n\n a, b = c\n\n The following will result in apply_fn(a, (b, c)):\n\n a = b, c\n\n It uses the visitor pattern to allow subclasses to process single\n assignments individually.\n\n Args:\n targets: Union[List[ast.AST, ...], Tuple[ast.AST, ...], ast.AST, should be\n used with the targets field of an ast.Assign node\n values: ast.AST\n apply_fn: Callable[[ast.AST, ast.AST], None], called with the\n respective nodes of each single assignment\n \"\"\"\n if not isinstance(targets, (list, tuple)):\n targets = (targets,)\n for target in targets:\n if isinstance(target, (gast.Tuple, gast.List)):\n for i in range(len(target.elts)):\n target_el = target.elts[i]\n if isinstance(values, (gast.Tuple, gast.List)):\n value_el = values.elts[i]\n else:\n idx = parser.parse_expression(str(i))\n value_el = gast.Subscript(values, gast.Index(idx), ctx=gast.Load())\n apply_to_single_assignments(target_el, value_el, apply_fn)\n else:\n apply_fn(target, values)\n\n\ndef parallel_walk(node, other):\n \"\"\"Walks two ASTs in parallel.\n\n The two trees must have identical structure.\n\n Args:\n node: Union[ast.AST, Iterable[ast.AST]]\n other: Union[ast.AST, Iterable[ast.AST]]\n Yields:\n Tuple[ast.AST, ast.AST]\n Raises:\n ValueError: if the two trees don't have identical structure.\n \"\"\"\n if isinstance(node, (list, tuple)):\n node_stack = list(node)\n else:\n node_stack = [node]\n\n if isinstance(other, (list, tuple)):\n other_stack = list(other)\n else:\n other_stack = [other]\n\n while node_stack and other_stack:\n assert len(node_stack) == len(other_stack)\n n = node_stack.pop()\n o = other_stack.pop()\n\n if (not isinstance(n, (ast.AST, gast.AST)) or\n not isinstance(o, (ast.AST, gast.AST)) or\n n.__class__.__name__ != o.__class__.__name__):\n raise ValueError('inconsistent nodes: {} and {}'.format(n, o))\n\n yield n, o\n\n for f in n._fields:\n n_child = getattr(n, f, None)\n o_child = getattr(o, f, None)\n if f.startswith('__') or n_child is None or o_child is None:\n continue\n\n if isinstance(n_child, (list, tuple)):\n if (not isinstance(o_child, (list, tuple)) or\n len(n_child) != len(o_child)):\n raise ValueError(\n 'inconsistent values for field {}: {} and {}'.format(\n f, n_child, o_child))\n node_stack.extend(n_child)\n other_stack.extend(o_child)\n\n elif isinstance(n_child, (gast.AST, ast.AST)):\n node_stack.append(n_child)\n other_stack.append(o_child)\n\n elif n_child != o_child:\n raise ValueError(\n 'inconsistent values for field {}: {} and {}'.format(\n f, n_child, o_child))\n\n\nclass FunctionDefMatcher(gast.NodeVisitor):\n \"\"\"Finds nodes that match a given function's signature.\"\"\"\n\n def __init__(self, fn):\n self.fn = fn\n self.matching_nodes = []\n\n def _arg_name(self, node):\n if node is None:\n return None\n if isinstance(node, gast.Name):\n return node.id\n assert isinstance(node, str)\n return node\n\n def _argspec_matches(self, node):\n arg_spec = tf_inspect.getfullargspec(self.fn)\n\n node_args = tuple(self._arg_name(arg) for arg in node.args.args)\n if node_args != tuple(arg_spec.args):\n return False\n\n if arg_spec.varargs != self._arg_name(node.args.vararg):\n return False\n\n if arg_spec.varkw != self._arg_name(node.args.kwarg):\n return False\n\n node_kwonlyargs = tuple(self._arg_name(arg) for arg in node.args.kwonlyargs)\n if node_kwonlyargs != tuple(arg_spec.kwonlyargs):\n return False\n\n return True\n\n def _argspec_compatible(self, node):\n arg_spec = tf_inspect.getfullargspec(self.fn)\n\n node_args = tuple(self._arg_name(arg) for arg in node.args.args)\n if len(node_args) != len(arg_spec.args) and node.args.vararg is None:\n return False\n\n if arg_spec.varargs is not None and node.args.vararg is None:\n return False\n\n if arg_spec.varkw is not None and node.args.kwarg is None:\n return False\n\n node_kwonlyargs = tuple(self._arg_name(arg) for arg in node.args.kwonlyargs)\n if (len(node_kwonlyargs) != len(arg_spec.kwonlyargs) and\n node.args.kwarg is None):\n return False\n\n return True\n\n def visit_Lambda(self, node):\n self.generic_visit(node)\n\n if self.fn.__name__ != '<lambda>':\n return\n if not self._argspec_matches(node):\n return\n\n self.matching_nodes.append(node)\n\n def visit_FunctionDef(self, node):\n self.generic_visit(node)\n\n if self.fn.__name__ != node.name:\n return\n\n # Decorators have the ability to modify a function's signature. They usually\n # claim that the result is indistinguishable from the original function,\n # but it's very difficult to fool this test. As a consequence, we relax the\n # verification and just check that the arguments are compatible.\n if node.decorator_list:\n if not self._argspec_compatible(node):\n return\n else:\n if not self._argspec_matches(node):\n return\n\n self.matching_nodes.append(node)\n\n\ndef find_matching_definitions(node, f):\n matcher = FunctionDefMatcher(f)\n matcher.visit(node)\n return tuple(matcher.matching_nodes)\n" ]
[ [ "tensorflow.python.autograph.pyct.anno.hasanno", "tensorflow.python.autograph.pyct.anno.keys", "tensorflow.python.util.tf_inspect.getfullargspec", "tensorflow.python.autograph.pyct.anno.copyanno", "tensorflow.python.autograph.pyct.anno.getanno", "tensorflow.python.autograph.pyct.parser.parse_str" ] ]
ivis-kuwata/albert
[ "bd336ba2d324bb35b9d09599da3d635895bac379" ]
[ "export_to_tfhub.py" ]
[ "# coding=utf-8\n# Copyright 2018 The Google AI Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nr\"\"\"Exports a minimal TF-Hub module for ALBERT models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nfrom absl import app\nfrom absl import flags\nfrom albert import modeling\nimport tensorflow.compat.v1 as tf\nimport tensorflow_hub as hub\n\nflags.DEFINE_string(\n \"albert_directory\", None,\n \"The config json file corresponding to the pre-trained ALBERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\n \"checkpoint_name\", \"model.ckpt-best\",\n \"Name of the checkpoint under albert_directory to be exported.\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_bool(\n \"use_einsum\", True,\n \"Whether to use tf.einsum or tf.reshape+tf.matmul for dense layers. Must \"\n \"be set to False for TFLite compatibility.\")\n\nflags.DEFINE_string(\"export_path\", None, \"Path to the output TF-Hub module.\")\n\nFLAGS = flags.FLAGS\n\n\ndef gather_indexes(sequence_tensor, positions):\n \"\"\"Gathers the vectors at the specific positions over a minibatch.\"\"\"\n sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3)\n batch_size = sequence_shape[0]\n seq_length = sequence_shape[1]\n width = sequence_shape[2]\n\n flat_offsets = tf.reshape(\n tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])\n flat_positions = tf.reshape(positions + flat_offsets, [-1])\n flat_sequence_tensor = tf.reshape(sequence_tensor,\n [batch_size * seq_length, width])\n output_tensor = tf.gather(flat_sequence_tensor, flat_positions)\n return output_tensor\n\n\ndef get_mlm_logits(model, albert_config, mlm_positions):\n \"\"\"From run_pretraining.py.\"\"\"\n input_tensor = gather_indexes(model.get_sequence_output(), mlm_positions)\n with tf.variable_scope(\"cls/predictions\"):\n # We apply one more non-linear transformation before the output layer.\n # This matrix is not used after pre-training.\n with tf.variable_scope(\"transform\"):\n input_tensor = tf.layers.dense(\n input_tensor,\n units=albert_config.embedding_size,\n activation=modeling.get_activation(albert_config.hidden_act),\n kernel_initializer=modeling.create_initializer(\n albert_config.initializer_range))\n input_tensor = modeling.layer_norm(input_tensor)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n output_bias = tf.get_variable(\n \"output_bias\",\n shape=[albert_config.vocab_size],\n initializer=tf.zeros_initializer())\n logits = tf.matmul(\n input_tensor, model.get_embedding_table(), transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n return logits\n\n\ndef get_sop_log_probs(model, albert_config):\n \"\"\"Get loss and log probs for the next sentence prediction.\"\"\"\n input_tensor = model.get_pooled_output()\n # Simple binary classification. Note that 0 is \"next sentence\" and 1 is\n # \"random sentence\". This weight matrix is not used after pre-training.\n with tf.variable_scope(\"cls/seq_relationship\"):\n output_weights = tf.get_variable(\n \"output_weights\",\n shape=[2, albert_config.hidden_size],\n initializer=modeling.create_initializer(\n albert_config.initializer_range))\n output_bias = tf.get_variable(\n \"output_bias\", shape=[2], initializer=tf.zeros_initializer())\n\n logits = tf.matmul(input_tensor, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n return log_probs\n\n\ndef module_fn(is_training):\n \"\"\"Module function.\"\"\"\n input_ids = tf.placeholder(tf.int32, [None, None], \"input_ids\")\n input_mask = tf.placeholder(tf.int32, [None, None], \"input_mask\")\n segment_ids = tf.placeholder(tf.int32, [None, None], \"segment_ids\")\n mlm_positions = tf.placeholder(tf.int32, [None, None], \"mlm_positions\")\n\n albert_config_path = os.path.join(\n FLAGS.albert_directory, \"albert_config.json\")\n albert_config = modeling.AlbertConfig.from_json_file(albert_config_path)\n model = modeling.AlbertModel(\n config=albert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=False,\n use_einsum=FLAGS.use_einsum)\n\n mlm_logits = get_mlm_logits(model, albert_config, mlm_positions)\n sop_log_probs = get_sop_log_probs(model, albert_config)\n\n vocab_model_path = os.path.join(FLAGS.albert_directory, \"30k-clean.model\")\n vocab_file_path = os.path.join(FLAGS.albert_directory, \"30k-clean.vocab\")\n\n config_file = tf.constant(\n value=albert_config_path, dtype=tf.string, name=\"config_file\")\n vocab_model = tf.constant(\n value=vocab_model_path, dtype=tf.string, name=\"vocab_model\")\n # This is only for visualization purpose.\n vocab_file = tf.constant(\n value=vocab_file_path, dtype=tf.string, name=\"vocab_file\")\n\n # By adding `config_file, vocab_model and vocab_file`\n # to the ASSET_FILEPATHS collection, TF-Hub will\n # rewrite this tensor so that this asset is portable.\n tf.add_to_collection(tf.GraphKeys.ASSET_FILEPATHS, config_file)\n tf.add_to_collection(tf.GraphKeys.ASSET_FILEPATHS, vocab_model)\n tf.add_to_collection(tf.GraphKeys.ASSET_FILEPATHS, vocab_file)\n\n hub.add_signature(\n name=\"tokens\",\n inputs=dict(\n input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids),\n outputs=dict(\n sequence_output=model.get_sequence_output(),\n pooled_output=model.get_pooled_output()))\n\n hub.add_signature(\n name=\"sop\",\n inputs=dict(\n input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids),\n outputs=dict(\n sequence_output=model.get_sequence_output(),\n pooled_output=model.get_pooled_output(),\n sop_log_probs=sop_log_probs))\n\n hub.add_signature(\n name=\"mlm\",\n inputs=dict(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n mlm_positions=mlm_positions),\n outputs=dict(\n sequence_output=model.get_sequence_output(),\n pooled_output=model.get_pooled_output(),\n mlm_logits=mlm_logits))\n\n hub.add_signature(\n name=\"tokenization_info\",\n inputs={},\n outputs=dict(\n vocab_file=vocab_model,\n do_lower_case=tf.constant(FLAGS.do_lower_case)))\n\n\ndef main(_):\n tags_and_args = []\n for is_training in (True, False):\n tags = set()\n if is_training:\n tags.add(\"train\")\n tags_and_args.append((tags, dict(is_training=is_training)))\n spec = hub.create_module_spec(module_fn, tags_and_args=tags_and_args)\n checkpoint_path = os.path.join(FLAGS.albert_directory, FLAGS.checkpoint_name)\n tf.logging.info(\"Using checkpoint {}\".format(checkpoint_path))\n spec.export(FLAGS.export_path, checkpoint_path=checkpoint_path)\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"albert_directory\")\n flags.mark_flag_as_required(\"export_path\")\n app.run(main)\n" ]
[ [ "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.range", "tensorflow.compat.v1.zeros_initializer", "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.gather", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.nn.log_softmax", "tensorflow.compat.v1.nn.bias_add", "tensorflow.compat.v1.add_to_collection", "tensorflow.compat.v1.reshape" ] ]
acrucetta/Chicago_COVI_WebApp
[ "a37c9f492a20dcd625f8647067394617988de913" ]
[ ".venv/lib/python3.8/site-packages/pandas/core/reshape/tile.py" ]
[ "\"\"\"\nQuantilization functions and related stuff\n\"\"\"\nimport numpy as np\n\nfrom pandas._libs import Timedelta, Timestamp\nfrom pandas._libs.lib import infer_dtype\n\nfrom pandas.core.dtypes.common import (\n DT64NS_DTYPE,\n ensure_int64,\n is_bool_dtype,\n is_categorical_dtype,\n is_datetime64_dtype,\n is_datetime64tz_dtype,\n is_datetime_or_timedelta_dtype,\n is_extension_array_dtype,\n is_integer,\n is_integer_dtype,\n is_list_like,\n is_scalar,\n is_timedelta64_dtype,\n)\nfrom pandas.core.dtypes.generic import ABCSeries\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas import Categorical, Index, IntervalIndex, to_datetime, to_timedelta\nimport pandas.core.algorithms as algos\nimport pandas.core.nanops as nanops\n\n\ndef cut(\n x,\n bins,\n right: bool = True,\n labels=None,\n retbins: bool = False,\n precision: int = 3,\n include_lowest: bool = False,\n duplicates: str = \"raise\",\n ordered: bool = True,\n):\n \"\"\"\n Bin values into discrete intervals.\n\n Use `cut` when you need to segment and sort data values into bins. This\n function is also useful for going from a continuous variable to a\n categorical variable. For example, `cut` could convert ages to groups of\n age ranges. Supports binning into an equal number of bins, or a\n pre-specified array of bins.\n\n Parameters\n ----------\n x : array-like\n The input array to be binned. Must be 1-dimensional.\n bins : int, sequence of scalars, or IntervalIndex\n The criteria to bin by.\n\n * int : Defines the number of equal-width bins in the range of `x`. The\n range of `x` is extended by .1% on each side to include the minimum\n and maximum values of `x`.\n * sequence of scalars : Defines the bin edges allowing for non-uniform\n width. No extension of the range of `x` is done.\n * IntervalIndex : Defines the exact bins to be used. Note that\n IntervalIndex for `bins` must be non-overlapping.\n\n right : bool, default True\n Indicates whether `bins` includes the rightmost edge or not. If\n ``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]``\n indicate (1,2], (2,3], (3,4]. This argument is ignored when\n `bins` is an IntervalIndex.\n labels : array or False, default None\n Specifies the labels for the returned bins. Must be the same length as\n the resulting bins. If False, returns only integer indicators of the\n bins. This affects the type of the output container (see below).\n This argument is ignored when `bins` is an IntervalIndex. If True,\n raises an error. When `ordered=False`, labels must be provided.\n retbins : bool, default False\n Whether to return the bins or not. Useful when bins is provided\n as a scalar.\n precision : int, default 3\n The precision at which to store and display the bins labels.\n include_lowest : bool, default False\n Whether the first interval should be left-inclusive or not.\n duplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\n\n .. versionadded:: 0.23.0\n ordered : bool, default True\n Whether the labels are ordered or not. Applies to returned types\n Categorical and Series (with Categorical dtype). If True,\n the resulting categorical will be ordered. If False, the resulting\n categorical will be unordered (labels must be provided).\n\n .. versionadded:: 1.1.0\n\n Returns\n -------\n out : Categorical, Series, or ndarray\n An array-like object representing the respective bin for each value\n of `x`. The type depends on the value of `labels`.\n\n * True (default) : returns a Series for Series `x` or a\n Categorical for all other inputs. The values stored within\n are Interval dtype.\n\n * sequence of scalars : returns a Series for Series `x` or a\n Categorical for all other inputs. The values stored within\n are whatever the type in the sequence is.\n\n * False : returns an ndarray of integers.\n\n bins : numpy.ndarray or IntervalIndex.\n The computed or specified bins. Only returned when `retbins=True`.\n For scalar or sequence `bins`, this is an ndarray with the computed\n bins. If set `duplicates=drop`, `bins` will drop non-unique bin. For\n an IntervalIndex `bins`, this is equal to `bins`.\n\n See Also\n --------\n qcut : Discretize variable into equal-sized buckets based on rank\n or based on sample quantiles.\n Categorical : Array type for storing data that come from a\n fixed set of values.\n Series : One-dimensional array with axis labels (including time series).\n IntervalIndex : Immutable Index implementing an ordered, sliceable set.\n\n Notes\n -----\n Any NA values will be NA in the result. Out of bounds values will be NA in\n the resulting Series or Categorical object.\n\n Examples\n --------\n Discretize into three equal-sized bins.\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)\n ... # doctest: +ELLIPSIS\n [(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\n Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)\n ... # doctest: +ELLIPSIS\n ([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...\n Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...\n array([0.994, 3. , 5. , 7. ]))\n\n Discovers the same bins, but assign them specific labels. Notice that\n the returned Categorical's categories are `labels` and is ordered.\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]),\n ... 3, labels=[\"bad\", \"medium\", \"good\"])\n ['bad', 'good', 'medium', 'medium', 'good', 'bad']\n Categories (3, object): ['bad' < 'medium' < 'good']\n\n ``ordered=False`` will result in unordered categories when labels are passed.\n This parameter can be used to allow non-unique labels:\n\n >>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3,\n ... labels=[\"B\", \"A\", \"B\"], ordered=False)\n ['B', 'B', 'A', 'A', 'B', 'B']\n Categories (2, object): ['A', 'B']\n\n ``labels=False`` implies you just want the bins back.\n\n >>> pd.cut([0, 1, 1, 2], bins=4, labels=False)\n array([0, 1, 1, 3])\n\n Passing a Series as an input returns a Series with categorical dtype:\n\n >>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n ... index=['a', 'b', 'c', 'd', 'e'])\n >>> pd.cut(s, 3)\n ... # doctest: +ELLIPSIS\n a (1.992, 4.667]\n b (1.992, 4.667]\n c (4.667, 7.333]\n d (7.333, 10.0]\n e (7.333, 10.0]\n dtype: category\n Categories (3, interval[float64]): [(1.992, 4.667] < (4.667, ...\n\n Passing a Series as an input returns a Series with mapping value.\n It is used to map numerically to intervals based on bins.\n\n >>> s = pd.Series(np.array([2, 4, 6, 8, 10]),\n ... index=['a', 'b', 'c', 'd', 'e'])\n >>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False)\n ... # doctest: +ELLIPSIS\n (a 1.0\n b 2.0\n c 3.0\n d 4.0\n e NaN\n dtype: float64,\n array([ 0, 2, 4, 6, 8, 10]))\n\n Use `drop` optional when bins is not unique\n\n >>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,\n ... right=False, duplicates='drop')\n ... # doctest: +ELLIPSIS\n (a 1.0\n b 2.0\n c 3.0\n d 3.0\n e NaN\n dtype: float64,\n array([ 0, 2, 4, 6, 10]))\n\n Passing an IntervalIndex for `bins` results in those categories exactly.\n Notice that values not covered by the IntervalIndex are set to NaN. 0\n is to the left of the first bin (which is closed on the right), and 1.5\n falls between two bins.\n\n >>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])\n >>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)\n [NaN, (0.0, 1.0], NaN, (2.0, 3.0], (4.0, 5.0]]\n Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]]\n \"\"\"\n # NOTE: this binning code is changed a bit from histogram for var(x) == 0\n\n original = x\n x = _preprocess_for_cut(x)\n x, dtype = _coerce_to_type(x)\n\n if not np.iterable(bins):\n if is_scalar(bins) and bins < 1:\n raise ValueError(\"`bins` should be a positive integer.\")\n\n try: # for array-like\n sz = x.size\n except AttributeError:\n x = np.asarray(x)\n sz = x.size\n\n if sz == 0:\n raise ValueError(\"Cannot cut empty array\")\n\n rng = (nanops.nanmin(x), nanops.nanmax(x))\n mn, mx = [mi + 0.0 for mi in rng]\n\n if np.isinf(mn) or np.isinf(mx):\n # GH 24314\n raise ValueError(\n \"cannot specify integer `bins` when input data contains infinity\"\n )\n elif mn == mx: # adjust end points before binning\n mn -= 0.001 * abs(mn) if mn != 0 else 0.001\n mx += 0.001 * abs(mx) if mx != 0 else 0.001\n bins = np.linspace(mn, mx, bins + 1, endpoint=True)\n else: # adjust end points after binning\n bins = np.linspace(mn, mx, bins + 1, endpoint=True)\n adj = (mx - mn) * 0.001 # 0.1% of the range\n if right:\n bins[0] -= adj\n else:\n bins[-1] += adj\n\n elif isinstance(bins, IntervalIndex):\n if bins.is_overlapping:\n raise ValueError(\"Overlapping IntervalIndex is not accepted.\")\n\n else:\n if is_datetime64tz_dtype(bins):\n bins = np.asarray(bins, dtype=DT64NS_DTYPE)\n else:\n bins = np.asarray(bins)\n bins = _convert_bin_to_numeric_type(bins, dtype)\n\n # GH 26045: cast to float64 to avoid an overflow\n if (np.diff(bins.astype(\"float64\")) < 0).any():\n raise ValueError(\"bins must increase monotonically.\")\n\n fac, bins = _bins_to_cuts(\n x,\n bins,\n right=right,\n labels=labels,\n precision=precision,\n include_lowest=include_lowest,\n dtype=dtype,\n duplicates=duplicates,\n ordered=ordered,\n )\n\n return _postprocess_for_cut(fac, bins, retbins, dtype, original)\n\n\ndef qcut(\n x,\n q,\n labels=None,\n retbins: bool = False,\n precision: int = 3,\n duplicates: str = \"raise\",\n):\n \"\"\"\n Quantile-based discretization function.\n\n Discretize variable into equal-sized buckets based on rank or based\n on sample quantiles. For example 1000 values for 10 quantiles would\n produce a Categorical object indicating quantile membership for each data point.\n\n Parameters\n ----------\n x : 1d ndarray or Series\n q : int or list-like of float\n Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately\n array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles.\n labels : array or False, default None\n Used as labels for the resulting bins. Must be of the same length as\n the resulting bins. If False, return only integer indicators of the\n bins. If True, raises an error.\n retbins : bool, optional\n Whether to return the (bins, labels) or not. Can be useful if bins\n is given as a scalar.\n precision : int, optional\n The precision at which to store and display the bins labels.\n duplicates : {default 'raise', 'drop'}, optional\n If bin edges are not unique, raise ValueError or drop non-uniques.\n\n Returns\n -------\n out : Categorical or Series or array of integers if labels is False\n The return type (Categorical or Series) depends on the input: a Series\n of type category if input is a Series else Categorical. Bins are\n represented as categories when categorical data is returned.\n bins : ndarray of floats\n Returned only if `retbins` is True.\n\n Notes\n -----\n Out of bounds values will be NA in the resulting Categorical object\n\n Examples\n --------\n >>> pd.qcut(range(5), 4)\n ... # doctest: +ELLIPSIS\n [(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]\n Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ...\n\n >>> pd.qcut(range(5), 3, labels=[\"good\", \"medium\", \"bad\"])\n ... # doctest: +SKIP\n [good, good, medium, bad, bad]\n Categories (3, object): [good < medium < bad]\n\n >>> pd.qcut(range(5), 4, labels=False)\n array([0, 0, 1, 2, 3])\n \"\"\"\n original = x\n x = _preprocess_for_cut(x)\n x, dtype = _coerce_to_type(x)\n\n if is_integer(q):\n quantiles = np.linspace(0, 1, q + 1)\n else:\n quantiles = q\n bins = algos.quantile(x, quantiles)\n fac, bins = _bins_to_cuts(\n x,\n bins,\n labels=labels,\n precision=precision,\n include_lowest=True,\n dtype=dtype,\n duplicates=duplicates,\n )\n\n return _postprocess_for_cut(fac, bins, retbins, dtype, original)\n\n\ndef _bins_to_cuts(\n x,\n bins,\n right: bool = True,\n labels=None,\n precision: int = 3,\n include_lowest: bool = False,\n dtype=None,\n duplicates: str = \"raise\",\n ordered: bool = True,\n):\n if not ordered and not labels:\n raise ValueError(\"'labels' must be provided if 'ordered = False'\")\n\n if duplicates not in [\"raise\", \"drop\"]:\n raise ValueError(\n \"invalid value for 'duplicates' parameter, valid options are: raise, drop\"\n )\n\n if isinstance(bins, IntervalIndex):\n # we have a fast-path here\n ids = bins.get_indexer(x)\n result = Categorical.from_codes(ids, categories=bins, ordered=True)\n return result, bins\n\n unique_bins = algos.unique(bins)\n if len(unique_bins) < len(bins) and len(bins) != 2:\n if duplicates == \"raise\":\n raise ValueError(\n f\"Bin edges must be unique: {repr(bins)}.\\n\"\n f\"You can drop duplicate edges by setting the 'duplicates' kwarg\"\n )\n else:\n bins = unique_bins\n\n side = \"left\" if right else \"right\"\n ids = ensure_int64(bins.searchsorted(x, side=side))\n\n if include_lowest:\n ids[x == bins[0]] = 1\n\n na_mask = isna(x) | (ids == len(bins)) | (ids == 0)\n has_nas = na_mask.any()\n\n if labels is not False:\n if not (labels is None or is_list_like(labels)):\n raise ValueError(\n \"Bin labels must either be False, None or passed in as a \"\n \"list-like argument\"\n )\n\n elif labels is None:\n labels = _format_labels(\n bins, precision, right=right, include_lowest=include_lowest, dtype=dtype\n )\n elif ordered and len(set(labels)) != len(labels):\n raise ValueError(\n \"labels must be unique if ordered=True; pass ordered=False for duplicate labels\" # noqa\n )\n else:\n if len(labels) != len(bins) - 1:\n raise ValueError(\n \"Bin labels must be one fewer than the number of bin edges\"\n )\n if not is_categorical_dtype(labels):\n labels = Categorical(\n labels,\n categories=labels if len(set(labels)) == len(labels) else None,\n ordered=ordered,\n )\n # TODO: handle mismatch between categorical label order and pandas.cut order.\n np.putmask(ids, na_mask, 0)\n result = algos.take_nd(labels, ids - 1)\n\n else:\n result = ids - 1\n if has_nas:\n result = result.astype(np.float64)\n np.putmask(result, na_mask, np.nan)\n\n return result, bins\n\n\ndef _coerce_to_type(x):\n \"\"\"\n if the passed data is of datetime/timedelta, bool or nullable int type,\n this method converts it to numeric so that cut or qcut method can\n handle it\n \"\"\"\n dtype = None\n\n if is_datetime64tz_dtype(x.dtype):\n dtype = x.dtype\n elif is_datetime64_dtype(x.dtype):\n x = to_datetime(x)\n dtype = np.dtype(\"datetime64[ns]\")\n elif is_timedelta64_dtype(x.dtype):\n x = to_timedelta(x)\n dtype = np.dtype(\"timedelta64[ns]\")\n elif is_bool_dtype(x.dtype):\n # GH 20303\n x = x.astype(np.int64)\n # To support cut and qcut for IntegerArray we convert to float dtype.\n # Will properly support in the future.\n # https://github.com/pandas-dev/pandas/pull/31290\n # https://github.com/pandas-dev/pandas/issues/31389\n elif is_extension_array_dtype(x.dtype) and is_integer_dtype(x.dtype):\n x = x.to_numpy(dtype=np.float64, na_value=np.nan)\n\n if dtype is not None:\n # GH 19768: force NaT to NaN during integer conversion\n x = np.where(x.notna(), x.view(np.int64), np.nan)\n\n return x, dtype\n\n\ndef _convert_bin_to_numeric_type(bins, dtype):\n \"\"\"\n if the passed bin is of datetime/timedelta type,\n this method converts it to integer\n\n Parameters\n ----------\n bins : list-like of bins\n dtype : dtype of data\n\n Raises\n ------\n ValueError if bins are not of a compat dtype to dtype\n \"\"\"\n bins_dtype = infer_dtype(bins, skipna=False)\n if is_timedelta64_dtype(dtype):\n if bins_dtype in [\"timedelta\", \"timedelta64\"]:\n bins = to_timedelta(bins).view(np.int64)\n else:\n raise ValueError(\"bins must be of timedelta64 dtype\")\n elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):\n if bins_dtype in [\"datetime\", \"datetime64\"]:\n bins = to_datetime(bins).view(np.int64)\n else:\n raise ValueError(\"bins must be of datetime64 dtype\")\n\n return bins\n\n\ndef _convert_bin_to_datelike_type(bins, dtype):\n \"\"\"\n Convert bins to a DatetimeIndex or TimedeltaIndex if the original dtype is\n datelike\n\n Parameters\n ----------\n bins : list-like of bins\n dtype : dtype of data\n\n Returns\n -------\n bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is\n datelike\n \"\"\"\n if is_datetime64tz_dtype(dtype):\n bins = to_datetime(bins.astype(np.int64), utc=True).tz_convert(dtype.tz)\n elif is_datetime_or_timedelta_dtype(dtype):\n bins = Index(bins.astype(np.int64), dtype=dtype)\n return bins\n\n\ndef _format_labels(\n bins, precision: int, right: bool = True, include_lowest: bool = False, dtype=None\n):\n \"\"\" based on the dtype, return our labels \"\"\"\n closed = \"right\" if right else \"left\"\n\n if is_datetime64tz_dtype(dtype):\n formatter = lambda x: Timestamp(x, tz=dtype.tz)\n adjust = lambda x: x - Timedelta(\"1ns\")\n elif is_datetime64_dtype(dtype):\n formatter = Timestamp\n adjust = lambda x: x - Timedelta(\"1ns\")\n elif is_timedelta64_dtype(dtype):\n formatter = Timedelta\n adjust = lambda x: x - Timedelta(\"1ns\")\n else:\n precision = _infer_precision(precision, bins)\n formatter = lambda x: _round_frac(x, precision)\n adjust = lambda x: x - 10 ** (-precision)\n\n breaks = [formatter(b) for b in bins]\n if right and include_lowest:\n # adjust lhs of first interval by precision to account for being right closed\n breaks[0] = adjust(breaks[0])\n\n return IntervalIndex.from_breaks(breaks, closed=closed)\n\n\ndef _preprocess_for_cut(x):\n \"\"\"\n handles preprocessing for cut where we convert passed\n input to array, strip the index information and store it\n separately\n \"\"\"\n # Check that the passed array is a Pandas or Numpy object\n # We don't want to strip away a Pandas data-type here (e.g. datetimetz)\n ndim = getattr(x, \"ndim\", None)\n if ndim is None:\n x = np.asarray(x)\n if x.ndim != 1:\n raise ValueError(\"Input array must be 1 dimensional\")\n\n return x\n\n\ndef _postprocess_for_cut(fac, bins, retbins: bool, dtype, original):\n \"\"\"\n handles post processing for the cut method where\n we combine the index information if the originally passed\n datatype was a series\n \"\"\"\n if isinstance(original, ABCSeries):\n fac = original._constructor(fac, index=original.index, name=original.name)\n\n if not retbins:\n return fac\n\n bins = _convert_bin_to_datelike_type(bins, dtype)\n\n return fac, bins\n\n\ndef _round_frac(x, precision: int):\n \"\"\"\n Round the fractional part of the given number\n \"\"\"\n if not np.isfinite(x) or x == 0:\n return x\n else:\n frac, whole = np.modf(x)\n if whole == 0:\n digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision\n else:\n digits = precision\n return np.around(x, digits)\n\n\ndef _infer_precision(base_precision: int, bins) -> int:\n \"\"\"\n Infer an appropriate precision for _round_frac\n \"\"\"\n for precision in range(base_precision, 20):\n levels = [_round_frac(b, precision) for b in bins]\n if algos.unique(levels).size == bins.size:\n return precision\n return base_precision # default\n" ]
[ [ "pandas.core.algorithms.unique", "numpy.dtype", "numpy.asarray", "pandas._libs.Timestamp", "pandas.core.dtypes.common.is_integer", "pandas.core.dtypes.common.is_list_like", "numpy.isfinite", "pandas.core.dtypes.common.is_categorical_dtype", "numpy.iterable", "pandas.core.nanops.nanmax", "pandas.to_datetime", "pandas._libs.Timedelta", "numpy.around", "pandas.to_timedelta", "pandas.core.dtypes.common.is_datetime64_dtype", "numpy.linspace", "pandas._libs.lib.infer_dtype", "pandas.core.dtypes.common.is_bool_dtype", "pandas.IntervalIndex.from_breaks", "pandas.core.algorithms.take_nd", "pandas.core.dtypes.common.is_timedelta64_dtype", "pandas.Categorical.from_codes", "numpy.putmask", "pandas.core.dtypes.common.is_scalar", "pandas.core.dtypes.missing.isna", "pandas.core.dtypes.common.is_extension_array_dtype", "pandas.core.nanops.nanmin", "pandas.core.dtypes.common.is_datetime_or_timedelta_dtype", "numpy.modf", "numpy.isinf", "pandas.core.dtypes.common.is_datetime64tz_dtype", "pandas.core.algorithms.quantile", "pandas.core.dtypes.common.is_integer_dtype" ] ]
XDynames/pytorch-lightning
[ "a5d1176cf6ef9e637144f980da11bbe63290c994" ]
[ "pytorch_lightning/core/lightning.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\nimport inspect\nimport os\nimport re\nimport tempfile\nfrom abc import ABC, abstractmethod\nfrom argparse import Namespace\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union\n\nimport torch\nimport torch.distributed as torch_distrib\nfrom torch import Tensor\nfrom torch.nn import Module\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.optim.optimizer import Optimizer\nfrom torch.utils.data import DataLoader\n\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.core.grads import GradInformation\nfrom pytorch_lightning.core.hooks import ModelHooks\nfrom pytorch_lightning.core.memory import ModelSummary\nfrom pytorch_lightning.core.saving import ALLOWED_CONFIG_TYPES, PRIMITIVE_TYPES, ModelIO\nfrom pytorch_lightning.overrides.data_parallel import LightningDistributedDataParallel\nfrom pytorch_lightning.utilities import rank_zero_warn\nfrom pytorch_lightning.utilities.device_dtype_mixin import DeviceDtypeModuleMixin\nfrom pytorch_lightning.utilities.parsing import AttributeDict, collect_init_args, get_init_args\nfrom pytorch_lightning.core.step_result import TrainResult, EvalResult\n\ntry:\n import torch_xla.core.xla_model as xm\nexcept ImportError:\n XLA_AVAILABLE = False\nelse:\n XLA_AVAILABLE = True\n\n\nclass LightningModule(ABC, DeviceDtypeModuleMixin, GradInformation, ModelIO, ModelHooks, Module):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.exp_save_path = None\n\n #: The current epoch\n self.current_epoch = 0\n\n #: Total training batches seen across all epochs\n self.global_step = 0\n\n self.loaded_optimizer_states_dict = {}\n\n #: Pointer to the trainer object\n self.trainer = None\n\n #: Pointer to the logger object\n self.logger = None\n\n #: True if using dp\n self.use_dp = False\n\n #: True if using ddp\n self.use_ddp = False\n\n #: True if using ddp2\n self.use_ddp2 = False\n\n # True if on tpu\n self.use_tpu = False\n\n #: True if using amp\n self.use_amp = False\n\n #: The precision used\n self.precision = 32\n\n # optionally can be set by user\n self._example_input_array = None\n self._datamodule = None\n\n @property\n def example_input_array(self) -> Any:\n return self._example_input_array\n\n @example_input_array.setter\n def example_input_array(self, example: Any) -> None:\n self._example_input_array = example\n\n @property\n def datamodule(self) -> Any:\n return self._datamodule\n\n @datamodule.setter\n def datamodule(self, datamodule: Any) -> None:\n self._datamodule = datamodule\n\n @property\n def on_gpu(self):\n \"\"\"\n True if your model is currently running on GPUs.\n Useful to set flags around the LightningModule for different CPU vs GPU behavior.\n \"\"\"\n return self.device.type == 'cuda'\n\n def print(self, *args, **kwargs) -> None:\n r\"\"\"\n Prints only from process 0. Use this in any distributed mode to log only once.\n\n Args:\n *args: The thing to print. Will be passed to Python's built-in print function.\n **kwargs: Will be passed to Python's built-in print function.\n\n Example:\n\n .. code-block:: python\n\n def forward(self, x):\n self.print(x, 'in forward')\n\n \"\"\"\n if self.trainer.is_global_zero:\n print(*args, **kwargs)\n\n def forward(self, *args, **kwargs):\n r\"\"\"\n Same as :meth:`torch.nn.Module.forward()`, however in Lightning you want this to define\n the operations you want to use for prediction (i.e.: on a server or as a feature extractor).\n\n Normally you'd call ``self()`` from your :meth:`training_step` method.\n This makes it easy to write a complex system for training with the outputs\n you'd want in a prediction setting.\n\n You may also find the :func:`~pytorch_lightning.core.decorators.auto_move_data` decorator useful\n when using the module outside Lightning in a production setting.\n\n Args:\n *args: Whatever you decide to pass into the forward method.\n **kwargs: Keyword arguments are also possible.\n\n Return:\n Predicted output\n\n Examples:\n .. code-block:: python\n\n # example if we were using this model as a feature extractor\n def forward(self, x):\n feature_maps = self.convnet(x)\n return feature_maps\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n feature_maps = self(x)\n logits = self.classifier(feature_maps)\n\n # ...\n return loss\n\n # splitting it this way allows model to be used a feature extractor\n model = MyModelAbove()\n\n inputs = server.get_request()\n results = model(inputs)\n server.write_results(results)\n\n # -------------\n # This is in stark contrast to torch.nn.Module where normally you would have this:\n def forward(self, batch):\n x, y = batch\n feature_maps = self.convnet(x)\n logits = self.classifier(feature_maps)\n return logits\n\n \"\"\"\n\n def training_step(self, *args, **kwargs):\n r\"\"\"\n Here you compute and return the training loss and some additional metrics for e.g.\n the progress bar or logger.\n\n Args:\n batch (:class:`~torch.Tensor` | (:class:`~torch.Tensor`, ...) | [:class:`~torch.Tensor`, ...]):\n The output of your :class:`~torch.utils.data.DataLoader`. A tensor, tuple or list.\n batch_idx (int): Integer displaying index of this batch\n optimizer_idx (int): When using multiple optimizers, this argument will also be present.\n hiddens(:class:`~torch.Tensor`): Passed in if\n :paramref:`~pytorch_lightning.trainer.trainer.Trainer.truncated_bptt_steps` > 0.\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n .. note:: :class:`~pytorch_lightning.core.step_result.TrainResult` is simply a Dict with convenient\n functions for logging, distributed sync and error checking.\n\n In this step you'd normally do the forward pass and calculate the loss for a batch.\n You can also do fancier things like multiple forward passes or something model specific.\n\n Example::\n\n def training_step(self, batch, batch_idx):\n x, y, z = batch\n\n # implement your own\n out = self(x)\n loss = self.loss(out, x)\n\n # TrainResult auto-detaches the loss after the optimization steps are complete\n result = pl.TrainResult(minimize=loss)\n\n The return object :class:`~pytorch_lightning.core.step_result.TrainResult` controls where to log,\n when to log (step or epoch) and syncing with multiple GPUs.\n\n .. code-block:: python\n\n # log to progress bar and logger\n result.log('train_loss', loss, prog_bar=True, logger=True)\n\n # sync metric value across GPUs in distributed training\n result.log('train_loss_2', loss, sync_dist=True)\n\n # log to progress bar as well\n result.log('train_loss_2', loss, prog_bar=True)\n\n # assign arbitrary values\n result.predictions = predictions\n result.some_value = 'some_value'\n\n If you define multiple optimizers, this step will be called with an additional\n ``optimizer_idx`` parameter.\n\n .. code-block:: python\n\n # Multiple optimizers (e.g.: GANs)\n def training_step(self, batch, batch_idx, optimizer_idx):\n if optimizer_idx == 0:\n # do training_step with encoder\n if optimizer_idx == 1:\n # do training_step with decoder\n\n\n If you add truncated back propagation through time you will also get an additional\n argument with the hidden states of the previous step.\n\n .. code-block:: python\n\n # Truncated back-propagation through time\n def training_step(self, batch, batch_idx, hiddens):\n # hiddens are the hidden states from the previous truncated backprop step\n ...\n out, hiddens = self.lstm(data, hiddens)\n ...\n\n # TrainResult auto-detaches hiddens\n result = pl.TrainResult(minimize=loss, hiddens=hiddens)\n return result\n\n Notes:\n The loss value shown in the progress bar is smoothed (averaged) over the last values,\n so it differs from the actual loss returned in train/validation step.\n \"\"\"\n rank_zero_warn('`training_step` must be implemented to be used with the Lightning Trainer')\n\n def training_step_end(self, *args, **kwargs):\n \"\"\"\n Use this when training with dp or ddp2 because :meth:`training_step`\n will operate on only part of the batch. However, this is still optional\n and only needed for things like softmax or NCE loss.\n\n Note:\n If you later switch to ddp or some other mode, this will still be called\n so that you don't have to change your code\n\n .. code-block:: python\n\n # pseudocode\n sub_batches = split_batches_for_dp(batch)\n batch_parts_outputs = [training_step(sub_batch) for sub_batch in sub_batches]\n training_step_end(batch_parts_outputs)\n\n Args:\n batch_parts_outputs: What you return in `training_step` for each batch part.\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n .. note:: :class:`~pytorch_lightning.core.step_result.TrainResult` is simply a Dict with convenient\n functions for logging, distributed sync and error checking.\n\n When using dp/ddp2 distributed backends, only a portion of the batch is inside the training_step:\n\n .. code-block:: python\n\n def training_step(self, batch, batch_idx):\n # batch is 1/num_gpus big\n x, y = batch\n\n out = self(x)\n\n # softmax uses only a portion of the batch in the denomintaor\n loss = self.softmax(out)\n loss = nce_loss(loss)\n return pl.TrainResult(loss)\n\n If you wish to do something with all the parts of the batch, then use this method to do it:\n\n .. code-block:: python\n\n def training_step(self, batch, batch_idx):\n # batch is 1/num_gpus big\n x, y = batch\n\n out = self(x)\n result = pl.TrainResult()\n result.out = out\n\n def training_step_end(self, training_step_outputs):\n # this out is now the full size of the batch\n all_outs = training_step_outputs.out\n\n # this softmax now uses the full batch\n loss = nce_loss(all_outs)\n result = pl.TrainResult(loss)\n return result\n\n See Also:\n See the :ref:`multi-gpu-training` guide for more details.\n \"\"\"\n\n def training_epoch_end(\n self, outputs: Union[TrainResult, List[TrainResult]]\n ):\n \"\"\"\n Called at the end of the training epoch with the outputs of all training steps.\n Use this in case you need to do something with all the outputs for every training_step.\n\n .. code-block:: python\n\n # the pseudocode for these calls\n train_outs = []\n for train_batch in train_data:\n out = training_step(train_batch)\n train_outs.append(out)\n training_epoch_end(train_outs)\n\n Args:\n outputs: List of outputs you defined in :meth:`training_step`, or if there are\n multiple dataloaders, a list containing a list of outputs for each dataloader.\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n .. note:: :class:`~pytorch_lightning.core.step_result.TrainResult` is simply a Dict with convenient\n functions for logging, distributed sync and error checking.\n\n Note:\n If this method is not overridden, this won't be called.\n\n Example::\n\n def training_epoch_end(self, training_step_outputs):\n # do something with all training_step outputs\n return result\n\n With multiple dataloaders, ``outputs`` will be a list of lists. The outer list contains\n one entry per dataloader, while the inner list contains the individual outputs of\n each training step for that dataloader.\n\n .. code-block:: python\n\n def training_epoch_end(self, outputs):\n epoch_result = pl.TrainResult()\n for train_result in outputs:\n all_losses = train_result.minimize\n # do something with all losses\n return results\n \"\"\"\n\n def validation_step(self, *args, **kwargs) -> EvalResult:\n r\"\"\"\n Operates on a single batch of data from the validation set.\n In this step you'd might generate examples or calculate anything of interest like accuracy.\n\n .. code-block:: python\n\n # the pseudocode for these calls\n val_outs = []\n for val_batch in val_data:\n out = validation_step(train_batch)\n val_outs.append(out)\n validation_epoch_end(val_outs)\n\n Args:\n batch (:class:`~torch.Tensor` | (:class:`~torch.Tensor`, ...) | [:class:`~torch.Tensor`, ...]):\n The output of your :class:`~torch.utils.data.DataLoader`. A tensor, tuple or list.\n batch_idx (int): The index of this batch\n dataloader_idx (int): The index of the dataloader that produced this batch\n (only if multiple val datasets used)\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n .. code-block:: python\n\n # pseudocode of order\n out = validation_step()\n if defined('validation_step_end'):\n out = validation_step_end(out)\n out = validation_epoch_end(out)\n\n\n .. code-block:: python\n\n # if you have one val dataloader:\n def validation_step(self, batch, batch_idx)\n\n # if you have multiple val dataloaders:\n def validation_step(self, batch, batch_idx, dataloader_idx)\n\n Examples:\n .. code-block:: python\n\n # CASE 1: A single validation dataset\n def validation_step(self, batch, batch_idx):\n x, y = batch\n\n # implement your own\n out = self(x)\n loss = self.loss(out, y)\n\n # log 6 example images\n # or generated text... or whatever\n sample_imgs = x[:6]\n grid = torchvision.utils.make_grid(sample_imgs)\n self.logger.experiment.add_image('example_images', grid, 0)\n\n # calculate acc\n labels_hat = torch.argmax(out, dim=1)\n val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)\n\n # log the outputs!\n result = pl.EvalResult(checkpoint_on=loss)\n result.log_dict({'val_loss': loss, 'val_acc': val_acc})\n return result\n\n If you pass in multiple val datasets, validation_step will have an additional argument.\n\n .. code-block:: python\n\n # CASE 2: multiple validation datasets\n def validation_step(self, batch, batch_idx, dataloader_idx):\n # dataloader_idx tells you which dataset this is.\n\n Note:\n If you don't need to validate you don't need to implement this method.\n\n Note:\n When the :meth:`validation_step` is called, the model has been put in eval mode\n and PyTorch gradients have been disabled. At the end of validation,\n the model goes back to training mode and gradients are enabled.\n \"\"\"\n\n def validation_step_end(self, *args, **kwargs) -> EvalResult:\n \"\"\"\n Use this when validating with dp or ddp2 because :meth:`validation_step`\n will operate on only part of the batch. However, this is still optional\n and only needed for things like softmax or NCE loss.\n\n Note:\n If you later switch to ddp or some other mode, this will still be called\n so that you don't have to change your code.\n\n .. code-block:: python\n\n # pseudocode\n sub_batches = split_batches_for_dp(batch)\n batch_parts_outputs = [validation_step(sub_batch) for sub_batch in sub_batches]\n validation_step_end(batch_parts_outputs)\n\n Args:\n batch_parts_outputs: What you return in :meth:`validation_step`\n for each batch part.\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n .. code-block:: python\n\n # WITHOUT validation_step_end\n # if used in DP or DDP2, this batch is 1/num_gpus large\n def validation_step(self, batch, batch_idx):\n # batch is 1/num_gpus big\n x, y = batch\n\n out = self(x)\n loss = self.softmax(out)\n loss = nce_loss(loss)\n result = pl.EvalResult()\n result.log('val_loss', loss)\n return result\n\n # --------------\n # with validation_step_end to do softmax over the full batch\n def validation_step(self, batch, batch_idx):\n # batch is 1/num_gpus big\n x, y = batch\n\n out = self(x)\n result = pl.EvalResult()\n result.out = out\n return result\n\n def validation_epoch_end(self, output_results):\n # this out is now the full size of the batch\n all_val_step_outs = output_results.out\n loss = nce_loss(all_val_step_outs)\n\n result = pl.EvalResult(checkpoint_on=loss)\n result.log('val_loss', loss)\n return result\n\n See Also:\n See the :ref:`multi-gpu-training` guide for more details.\n \"\"\"\n\n def validation_end(self, outputs):\n \"\"\"\n Warnings:\n Deprecated in v0.7.0. Use :meth:`validation_epoch_end` instead.\n Will be removed in 1.0.0.\n \"\"\"\n\n def validation_epoch_end(\n self, outputs: Union[EvalResult, List[EvalResult]]\n ) -> EvalResult:\n \"\"\"\n Called at the end of the validation epoch with the outputs of all validation steps.\n\n .. code-block:: python\n\n # the pseudocode for these calls\n val_outs = []\n for val_batch in val_data:\n out = validation_step(val_batch)\n val_outs.append(out)\n validation_epoch_end(val_outs)\n\n Args:\n outputs: List of outputs you defined in :meth:`validation_step`, or if there\n are multiple dataloaders, a list containing a list of outputs for each dataloader.\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n Note:\n If you didn't define a :meth:`validation_step`, this won't be called.\n\n - The outputs here are strictly for logging or progress bar.\n - If you don't need to display anything, don't return anything.\n\n Examples:\n With a single dataloader:\n\n .. code-block:: python\n\n def validation_epoch_end(self, val_step_outputs):\n # do something with the outputs of all val batches\n all_val_preds = val_step_outputs.predictions\n\n val_step_outputs.some_result = calc_all_results(all_val_preds)\n return val_step_outputs\n\n With multiple dataloaders, `outputs` will be a list of lists. The outer list contains\n one entry per dataloader, while the inner list contains the individual outputs of\n each validation step for that dataloader.\n\n .. code-block:: python\n\n def validation_epoch_end(self, outputs):\n for dataloader_output_result in outputs:\n dataloader_outs = dataloader_output_result.dataloader_i_outputs\n\n result = pl.EvalResult()\n result.log('final_metric', final_value)\n return result\n \"\"\"\n\n def test_step(self, *args, **kwargs) -> EvalResult:\n r\"\"\"\n Operates on a single batch of data from the test set.\n In this step you'd normally generate examples or calculate anything of interest\n such as accuracy.\n\n .. code-block:: python\n\n # the pseudocode for these calls\n test_outs = []\n for test_batch in test_data:\n out = test_step(test_batch)\n test_outs.append(out)\n test_epoch_end(test_outs)\n\n Args:\n batch (:class:`~torch.Tensor` | (:class:`~torch.Tensor`, ...) | [:class:`~torch.Tensor`, ...]):\n The output of your :class:`~torch.utils.data.DataLoader`. A tensor, tuple or list.\n batch_idx (int): The index of this batch.\n dataloader_idx (int): The index of the dataloader that produced this batch\n (only if multiple test datasets used).\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n .. code-block:: python\n\n # if you have one test dataloader:\n def test_step(self, batch, batch_idx)\n\n # if you have multiple test dataloaders:\n def test_step(self, batch, batch_idx, dataloader_idx)\n\n Examples:\n .. code-block:: python\n\n # CASE 1: A single test dataset\n def test_step(self, batch, batch_idx):\n x, y = batch\n\n # implement your own\n out = self(x)\n loss = self.loss(out, y)\n\n # log 6 example images\n # or generated text... or whatever\n sample_imgs = x[:6]\n grid = torchvision.utils.make_grid(sample_imgs)\n self.logger.experiment.add_image('example_images', grid, 0)\n\n # calculate acc\n labels_hat = torch.argmax(out, dim=1)\n test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)\n\n # log the outputs!\n result = pl.EvalResult(checkpoint_on=loss)\n result.log_dict({'test_loss': loss, 'test_acc': test_acc})\n return resultt\n\n If you pass in multiple validation datasets, :meth:`test_step` will have an additional\n argument.\n\n .. code-block:: python\n\n # CASE 2: multiple test datasets\n def test_step(self, batch, batch_idx, dataloader_idx):\n # dataloader_idx tells you which dataset this is.\n\n Note:\n If you don't need to validate you don't need to implement this method.\n\n Note:\n When the :meth:`test_step` is called, the model has been put in eval mode and\n PyTorch gradients have been disabled. At the end of the test epoch, the model goes back\n to training mode and gradients are enabled.\n \"\"\"\n\n def test_step_end(self, *args, **kwargs) -> EvalResult:\n \"\"\"\n Use this when testing with dp or ddp2 because :meth:`test_step` will operate\n on only part of the batch. However, this is still optional\n and only needed for things like softmax or NCE loss.\n\n Note:\n If you later switch to ddp or some other mode, this will still be called\n so that you don't have to change your code.\n\n .. code-block:: python\n\n # pseudocode\n sub_batches = split_batches_for_dp(batch)\n batch_parts_outputs = [test_step(sub_batch) for sub_batch in sub_batches]\n test_step_end(batch_parts_outputs)\n\n Args:\n batch_parts_outputs: What you return in :meth:`test_step` for each batch part.\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n .. code-block:: python\n\n # WITHOUT test_step_end\n # if used in DP or DDP2, this batch is 1/num_gpus large\n def test_step(self, batch, batch_idx):\n # batch is 1/num_gpus big\n x, y = batch\n\n out = self(x)\n loss = self.softmax(out)\n loss = nce_loss(loss)\n result = pl.EvalResult()\n result.log('test_loss', loss)\n return result\n\n # --------------\n # with test_step_end to do softmax over the full batch\n def test_step(self, batch, batch_idx):\n # batch is 1/num_gpus big\n x, y = batch\n\n out = self(x)\n result = pl.EvalResult()\n result.out = out\n return result\n\n def test_epoch_end(self, output_results):\n # this out is now the full size of the batch\n all_test_step_outs = output_results.out\n loss = nce_loss(all_test_step_outs)\n\n result = pl.EvalResult(checkpoint_on=loss)\n result.log('test_loss', loss)\n return result\n\n See Also:\n See the :ref:`multi-gpu-training` guide for more details.\n \"\"\"\n\n def test_end(self, outputs):\n \"\"\"\n Warnings:\n Deprecated in v0.7.0. Use :meth:`test_epoch_end` instead.\n Will be removed in 1.0.0.\n \"\"\"\n\n def test_epoch_end(\n self, outputs: Union[EvalResult, List[EvalResult]]\n ) -> EvalResult:\n\n \"\"\"\n Called at the end of a test epoch with the output of all test steps.\n\n .. code-block:: python\n\n # the pseudocode for these calls\n test_outs = []\n for test_batch in test_data:\n out = test_step(test_batch)\n test_outs.append(out)\n test_epoch_end(test_outs)\n\n Args:\n outputs: List of outputs you defined in :meth:`test_step_end`, or if there\n are multiple dataloaders, a list containing a list of outputs for each dataloader\n\n Return:\n :class:`~pytorch_lightning.core.step_result.TrainResult`\n\n Note:\n If you didn't define a :meth:`test_step`, this won't be called.\n\n - The outputs here are strictly for logging or progress bar.\n - If you don't need to display anything, don't return anything.\n\n Examples:\n With a single dataloader:\n\n .. code-block:: python\n\n def test_epoch_end(self, outputs):\n # do something with the outputs of all test batches\n all_test_preds = test_step_outputs.predictions\n\n test_step_outputs.some_result = calc_all_results(all_test_preds)\n return test_step_outputs\n\n With multiple dataloaders, `outputs` will be a list of lists. The outer list contains\n one entry per dataloader, while the inner list contains the individual outputs of\n each test step for that dataloader.\n\n .. code-block:: python\n\n def test_epoch_end(self, outputs):\n for dataloader_output_result in outputs:\n dataloader_outs = dataloader_output_result.dataloader_i_outputs\n\n result = pl.EvalResult()\n result.log('final_metric', final_value)\n return results\n \"\"\"\n\n def configure_ddp(self, model: 'LightningModule', device_ids: List[int]) -> DistributedDataParallel:\n r\"\"\"\n Override to init DDP in your own way or with your own wrapper.\n The only requirements are that:\n\n 1. On a validation batch, the call goes to ``model.validation_step``.\n 2. On a training batch, the call goes to ``model.training_step``.\n 3. On a testing batch, the call goes to ``model.test_step``.\n\n Args:\n model: the :class:`LightningModule` currently being optimized.\n device_ids: the list of GPU ids.\n\n Return:\n DDP wrapped model\n\n Examples:\n .. code-block:: python\n\n # default implementation used in Trainer\n def configure_ddp(self, model, device_ids):\n # Lightning DDP simply routes to test_step, val_step, etc...\n model = LightningDistributedDataParallel(\n model,\n device_ids=device_ids,\n find_unused_parameters=True\n )\n return model\n\n \"\"\"\n model = LightningDistributedDataParallel(model, device_ids=device_ids, find_unused_parameters=True)\n return model\n\n def _init_slurm_connection(self) -> None:\n \"\"\"\"\"\"\n \"\"\"\n Sets up environment variables necessary for pytorch distributed communications\n based on slurm environment.\n \"\"\"\n # use slurm job id for the port number\n # guarantees unique ports across jobs from same grid search\n try:\n # use the last 4 numbers in the job id as the id\n default_port = os.environ['SLURM_JOB_ID']\n default_port = default_port[-4:]\n\n # all ports should be in the 10k+ range\n default_port = int(default_port) + 15000\n\n except Exception:\n default_port = 12910\n\n # if user gave a port number, use that one instead\n try:\n default_port = os.environ['MASTER_PORT']\n except Exception:\n os.environ['MASTER_PORT'] = str(default_port)\n\n # figure out the root node addr\n try:\n root_node = os.environ['SLURM_NODELIST'].split(' ')[0]\n except Exception:\n root_node = '127.0.0.1'\n\n root_node = self.trainer.resolve_root_node_address(root_node)\n os.environ['MASTER_ADDR'] = root_node\n\n def init_ddp_connection(self, global_rank: int, world_size: int, is_slurm_managing_tasks: bool = True) -> None:\n \"\"\"\n Override to define your custom way of setting up a distributed environment.\n\n Lightning's implementation uses env:// init by default and sets the first node as root\n for SLURM managed cluster.\n\n Args:\n global_rank: The global process idx.\n world_size: Number of GPUs being use across all nodes. (num_nodes * num_gpus).\n is_slurm_managing_tasks: is cluster managed by SLURM.\n\n \"\"\"\n if is_slurm_managing_tasks:\n self._init_slurm_connection()\n\n if 'MASTER_ADDR' not in os.environ:\n rank_zero_warn(\"MASTER_ADDR environment variable is not defined. Set as localhost\")\n os.environ['MASTER_ADDR'] = '127.0.0.1'\n log.debug(f\"MASTER_ADDR: {os.environ['MASTER_ADDR']}\")\n\n if 'MASTER_PORT' not in os.environ:\n rank_zero_warn(\"MASTER_PORT environment variable is not defined. Set as 12910\")\n os.environ['MASTER_PORT'] = '12910'\n log.debug(f\"MASTER_PORT: {os.environ['MASTER_PORT']}\")\n\n if 'WORLD_SIZE' in os.environ and int(os.environ['WORLD_SIZE']) != world_size:\n rank_zero_warn(\n f\"WORLD_SIZE environment variable ({os.environ['WORLD_SIZE']}) \"\n f\"is not equal to the computed world size ({world_size}). Ignored.\"\n )\n\n torch_backend = \"nccl\" if self.trainer.on_gpu else \"gloo\"\n log.info(f\"initializing ddp: GLOBAL_RANK: {global_rank}, MEMBER: {global_rank+1}/{world_size}\")\n torch_distrib.init_process_group(torch_backend, rank=global_rank, world_size=world_size)\n\n def configure_sync_batchnorm(self, model: 'LightningModule') -> 'LightningModule':\n \"\"\"\n Add global batchnorm for a model spread across multiple GPUs and nodes.\n\n Override to synchronize batchnorm between specific process groups instead\n of the whole world or use a different sync_bn like `apex`'s version.\n\n Args:\n model: pointer to current :class:`LightningModule`.\n\n Return:\n LightningModule with batchnorm layers synchronized between process groups\n \"\"\"\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model, process_group=None)\n\n return model\n\n def configure_apex(\n self, amp: object, model: 'LightningModule', optimizers: List[Optimizer], amp_level: str\n ) -> Tuple['LightningModule', List[Optimizer]]:\n r\"\"\"\n Override to init AMP your own way.\n Must return a model and list of optimizers.\n\n Args:\n amp: pointer to amp library object.\n model: pointer to current :class:`LightningModule`.\n optimizers: list of optimizers passed in :meth:`configure_optimizers`.\n amp_level: AMP mode chosen ('O1', 'O2', etc...)\n\n Return:\n Apex wrapped model and optimizers\n\n Examples:\n .. code-block:: python\n\n # Default implementation used by Trainer.\n def configure_apex(self, amp, model, optimizers, amp_level):\n model, optimizers = amp.initialize(\n model, optimizers, opt_level=amp_level,\n )\n\n return model, optimizers\n \"\"\"\n model, optimizers = amp.initialize(model, optimizers, opt_level=amp_level)\n\n return model, optimizers\n\n def configure_optimizers(\n self,\n ) -> Optional[Union[Optimizer, Sequence[Optimizer], Dict, Sequence[Dict], Tuple[List, List]]]:\n r\"\"\"\n Choose what optimizers and learning-rate schedulers to use in your optimization.\n Normally you'd need one. But in the case of GANs or similar you might have multiple.\n\n Return:\n Any of these 6 options.\n\n - Single optimizer.\n - List or Tuple - List of optimizers.\n - Two lists - The first list has multiple optimizers, the second a list of LR schedulers (or lr_dict).\n - Dictionary, with an 'optimizer' key, and (optionally) a 'lr_scheduler' key which value is a single LR scheduler or lr_dict.\n - Tuple of dictionaries as described, with an optional 'frequency' key.\n - None - Fit will run without any optimizer.\n\n Note:\n The 'frequency' value is an int corresponding to the number of sequential batches\n optimized with the specific optimizer. It should be given to none or to all of the optimizers.\n There is a difference between passing multiple optimizers in a list,\n and passing multiple optimizers in dictionaries with a frequency of 1:\n In the former case, all optimizers will operate on the given batch in each optimization step.\n In the latter, only one optimizer will operate on the given batch at every step.\n\n The lr_dict is a dictionary which contains scheduler and its associated configuration.\n It has five keys. The default configuration is shown below.\n\n .. code-block:: python\n\n {\n 'scheduler': lr_scheduler, # The LR schduler\n 'interval': 'epoch', # The unit of the scheduler's step size\n 'frequency': 1, # The frequency of the scheduler\n 'reduce_on_plateau': False, # For ReduceLROnPlateau scheduler\n 'monitor': 'val_loss' # Metric to monitor\n }\n\n If user only provides LR schedulers, then their configuration will set to default as shown above.\n\n Examples:\n .. code-block:: python\n\n # most cases\n def configure_optimizers(self):\n opt = Adam(self.parameters(), lr=1e-3)\n return opt\n\n # multiple optimizer case (e.g.: GAN)\n def configure_optimizers(self):\n generator_opt = Adam(self.model_gen.parameters(), lr=0.01)\n disriminator_opt = Adam(self.model_disc.parameters(), lr=0.02)\n return generator_opt, disriminator_opt\n\n # example with learning rate schedulers\n def configure_optimizers(self):\n generator_opt = Adam(self.model_gen.parameters(), lr=0.01)\n disriminator_opt = Adam(self.model_disc.parameters(), lr=0.02)\n discriminator_sched = CosineAnnealing(discriminator_opt, T_max=10)\n return [generator_opt, disriminator_opt], [discriminator_sched]\n\n # example with step-based learning rate schedulers\n def configure_optimizers(self):\n gen_opt = Adam(self.model_gen.parameters(), lr=0.01)\n dis_opt = Adam(self.model_disc.parameters(), lr=0.02)\n gen_sched = {'scheduler': ExponentialLR(gen_opt, 0.99),\n 'interval': 'step'} # called after each training step\n dis_sched = CosineAnnealing(discriminator_opt, T_max=10) # called every epoch\n return [gen_opt, dis_opt], [gen_sched, dis_sched]\n\n # example with optimizer frequencies\n # see training procedure in `Improved Training of Wasserstein GANs`, Algorithm 1\n # https://arxiv.org/abs/1704.00028\n def configure_optimizers(self):\n gen_opt = Adam(self.model_gen.parameters(), lr=0.01)\n dis_opt = Adam(self.model_disc.parameters(), lr=0.02)\n n_critic = 5\n return (\n {'optimizer': dis_opt, 'frequency': n_critic},\n {'optimizer': gen_opt, 'frequency': 1}\n )\n\n Note:\n\n Some things to know:\n\n - Lightning calls ``.backward()`` and ``.step()`` on each optimizer\n and learning rate scheduler as needed.\n\n - If you use 16-bit precision (``precision=16``), Lightning will automatically\n handle the optimizers for you.\n\n - If you use multiple optimizers, :meth:`training_step` will have an additional\n ``optimizer_idx`` parameter.\n\n - If you use LBFGS Lightning handles the closure function automatically for you.\n\n - If you use multiple optimizers, gradients will be calculated only\n for the parameters of current optimizer at each training step.\n\n - If you need to control how often those optimizers step or override the\n default ``.step()`` schedule, override the :meth:`optimizer_step` hook.\n\n - If you only want to call a learning rate scheduler every ``x`` step or epoch,\n or want to monitor a custom metric, you can specify these in a lr_dict:\n\n .. code-block:: python\n\n {\n 'scheduler': lr_scheduler,\n 'interval': 'step', # or 'epoch'\n 'monitor': 'val_f1',\n 'frequency': x,\n }\n\n \"\"\"\n rank_zero_warn('`configure_optimizers` must be implemented to be used with the Lightning Trainer')\n\n def optimizer_step(\n self,\n epoch: int,\n batch_idx: int,\n optimizer: Optimizer,\n optimizer_idx: int,\n second_order_closure: Optional[Callable] = None,\n on_tpu: bool = False,\n using_native_amp: bool = False,\n using_lbfgs: bool = False,\n ) -> None:\n r\"\"\"\n Override this method to adjust the default way the\n :class:`~pytorch_lightning.trainer.trainer.Trainer` calls each optimizer.\n By default, Lightning calls ``step()`` and ``zero_grad()`` as shown in the example\n once per optimizer.\n\n Args:\n epoch: Current epoch\n batch_idx: Index of current batch\n optimizer: A PyTorch optimizer\n optimizer_idx: If you used multiple optimizers this indexes into that list.\n second_order_closure: closure for second order methods\n on_tpu: true if TPU backward is required\n using_native_amp: True if using native amp\n using_lbfgs: True if the matching optimizer is lbfgs\n\n Examples:\n .. code-block:: python\n\n # DEFAULT\n def optimizer_step(self, current_epoch, batch_idx, optimizer, optimizer_idx,\n second_order_closure, on_tpu, using_native_amp, using_lbfgs):\n optimizer.step()\n\n # Alternating schedule for optimizer steps (i.e.: GANs)\n def optimizer_step(self, current_epoch, batch_idx, optimizer, optimizer_idx,\n second_order_closure, on_tpu, using_native_amp, using_lbfgs):\n # update generator opt every 2 steps\n if optimizer_idx == 0:\n if batch_idx % 2 == 0 :\n optimizer.step()\n optimizer.zero_grad()\n\n # update discriminator opt every 4 steps\n if optimizer_idx == 1:\n if batch_idx % 4 == 0 :\n optimizer.step()\n optimizer.zero_grad()\n\n # ...\n # add as many optimizers as you want\n\n\n Here's another example showing how to use this for more advanced things such as\n learning rate warm-up:\n\n .. code-block:: python\n\n # learning rate warm-up\n def optimizer_step(self, current_epoch, batch_idx, optimizer,\n optimizer_idx, second_order_closure, on_tpu, using_native_amp, using_lbfgs):\n # warm up lr\n if self.trainer.global_step < 500:\n lr_scale = min(1., float(self.trainer.global_step + 1) / 500.)\n for pg in optimizer.param_groups:\n pg['lr'] = lr_scale * self.learning_rate\n\n # update params\n optimizer.step()\n optimizer.zero_grad()\n\n Note:\n If you also override the :meth:`~pytorch_lightning.core.hooks.ModelHooks.on_before_zero_grad`\n model hook don't forget to add the call to it before ``optimizer.zero_grad()`` yourself.\n\n \"\"\"\n if on_tpu:\n xm.optimizer_step(optimizer)\n elif using_native_amp:\n self.trainer.scaler.step(optimizer)\n elif using_lbfgs:\n optimizer.step(second_order_closure)\n else:\n optimizer.step()\n\n def optimizer_zero_grad(self, epoch: int, batch_idx: int, optimizer: Optimizer, optimizer_idx: int):\n optimizer.zero_grad()\n\n def tbptt_split_batch(self, batch: Tensor, split_size: int) -> list:\n r\"\"\"\n When using truncated backpropagation through time, each batch must be split along the\n time dimension. Lightning handles this by default, but for custom behavior override\n this function.\n\n Args:\n batch: Current batch\n split_size: The size of the split\n\n Return:\n List of batch splits. Each split will be passed to :meth:`training_step` to enable truncated\n back propagation through time. The default implementation splits root level Tensors and\n Sequences at dim=1 (i.e. time dim). It assumes that each time dim is the same length.\n\n Examples:\n .. code-block:: python\n\n def tbptt_split_batch(self, batch, split_size):\n splits = []\n for t in range(0, time_dims[0], split_size):\n batch_split = []\n for i, x in enumerate(batch):\n if isinstance(x, torch.Tensor):\n split_x = x[:, t:t + split_size]\n elif isinstance(x, collections.Sequence):\n split_x = [None] * len(x)\n for batch_idx in range(len(x)):\n split_x[batch_idx] = x[batch_idx][t:t + split_size]\n\n batch_split.append(split_x)\n\n splits.append(batch_split)\n\n return splits\n\n Note:\n Called in the training loop after\n :meth:`~pytorch_lightning.callbacks.base.Callback.on_batch_start`\n if :paramref:`~pytorch_lightning.trainer.Trainer.truncated_bptt_steps` > 0.\n Each returned batch split is passed separately to :meth:`training_step`.\n\n \"\"\"\n time_dims = [len(x[0]) for x in batch if isinstance(x, (torch.Tensor, collections.Sequence))]\n assert len(time_dims) >= 1, \"Unable to determine batch time dimension\"\n assert all(x == time_dims[0] for x in time_dims), \"Batch time dimension length is ambiguous\"\n\n splits = []\n for t in range(0, time_dims[0], split_size):\n batch_split = []\n for i, x in enumerate(batch):\n if isinstance(x, torch.Tensor):\n split_x = x[:, t : t + split_size]\n elif isinstance(x, collections.Sequence):\n split_x = [None] * len(x)\n for batch_idx in range(len(x)):\n split_x[batch_idx] = x[batch_idx][t : t + split_size]\n\n batch_split.append(split_x)\n\n splits.append(batch_split)\n\n return splits\n\n def prepare_data(self) -> None:\n \"\"\"\n Use this to download and prepare data.\n\n .. warning:: DO NOT set state to the model (use `setup` instead)\n since this is NOT called on every GPU in DDP/TPU\n\n Example::\n\n def prepare_data(self):\n # good\n download_data()\n tokenize()\n etc()\n\n # bad\n self.split = data_split\n self.some_state = some_other_state()\n\n In DDP prepare_data can be called in two ways (using Trainer(prepare_data_per_node)):\n\n 1. Once per node. This is the default and is only called on LOCAL_RANK=0.\n 2. Once in total. Only called on GLOBAL_RANK=0.\n\n Example::\n\n # DEFAULT\n # called once per node on LOCAL_RANK=0 of that node\n Trainer(prepare_data_per_node=True)\n\n # call on GLOBAL_RANK=0 (great for shared file systems)\n Trainer(prepare_data_per_node=False)\n\n This is called before requesting the dataloaders:\n\n .. code-block:: python\n\n model.prepare_data()\n if ddp/tpu: init()\n model.setup(stage)\n model.train_dataloader()\n model.val_dataloader()\n model.test_dataloader()\n \"\"\"\n\n def train_dataloader(self) -> DataLoader:\n \"\"\"\n Implement a PyTorch DataLoader for training.\n\n Return:\n Single PyTorch :class:`~torch.utils.data.DataLoader`.\n\n The dataloader you return will not be called every epoch unless you set\n :paramref:`~pytorch_lightning.trainer.Trainer.reload_dataloaders_every_epoch` to ``True``.\n\n For data processing use the following pattern:\n\n - download in :meth:`prepare_data`\n - process and split in :meth:`setup`\n\n However, the above are only necessary for distributed processing.\n\n .. warning:: do not assign state in prepare_data\n\n - :meth:`~pytorch_lightning.trainer.Trainer.fit`\n - ...\n - :meth:`prepare_data`\n - :meth:`setup`\n - :meth:`train_dataloader`\n\n Note:\n Lightning adds the correct sampler for distributed and arbitrary hardware.\n There is no need to set it yourself.\n\n Example:\n .. code-block:: python\n\n def train_dataloader(self):\n transform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (1.0,))])\n dataset = MNIST(root='/path/to/mnist/', train=True, transform=transform,\n download=True)\n loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=self.batch_size,\n shuffle=True\n )\n return loader\n\n \"\"\"\n rank_zero_warn('`train_dataloader` must be implemented to be used with the Lightning Trainer')\n\n def tng_dataloader(self): # todo: remove in v1.0.0\n \"\"\"\n Warnings:\n Deprecated in v0.5.0. Use :meth:`train_dataloader` instead. Will be removed in 1.0.0.\n \"\"\"\n output = self.train_dataloader()\n rank_zero_warn(\n \"`tng_dataloader` has been renamed to `train_dataloader` since v0.5.0.\"\n \" and this method will be removed in v1.0.0\",\n DeprecationWarning,\n )\n return output\n\n def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]:\n r\"\"\"\n Implement one or multiple PyTorch DataLoaders for testing.\n\n The dataloader you return will not be called every epoch unless you set\n :paramref:`~pytorch_lightning.trainer.Trainer.reload_dataloaders_every_epoch` to ``True``.\n\n For data processing use the following pattern:\n\n - download in :meth:`prepare_data`\n - process and split in :meth:`setup`\n\n However, the above are only necessary for distributed processing.\n\n .. warning:: do not assign state in prepare_data\n\n\n - :meth:`~pytorch_lightning.trainer.Trainer.fit`\n - ...\n - :meth:`prepare_data`\n - :meth:`setup`\n - :meth:`train_dataloader`\n - :meth:`val_dataloader`\n - :meth:`test_dataloader`\n\n Note:\n Lightning adds the correct sampler for distributed and arbitrary hardware.\n There is no need to set it yourself.\n\n Return:\n Single or multiple PyTorch DataLoaders.\n\n Example:\n .. code-block:: python\n\n def test_dataloader(self):\n transform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (1.0,))])\n dataset = MNIST(root='/path/to/mnist/', train=False, transform=transform,\n download=True)\n loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=self.batch_size,\n shuffle=False\n )\n\n return loader\n\n # can also return multiple dataloaders\n def test_dataloader(self):\n return [loader_a, loader_b, ..., loader_n]\n\n Note:\n If you don't need a test dataset and a :meth:`test_step`, you don't need to implement\n this method.\n\n Note:\n In the case where you return multiple test dataloaders, the :meth:`test_step`\n will have an argument ``dataloader_idx`` which matches the order here.\n \"\"\"\n\n def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]:\n r\"\"\"\n Implement one or multiple PyTorch DataLoaders for validation.\n\n The dataloader you return will not be called every epoch unless you set\n :paramref:`~pytorch_lightning.trainer.Trainer.reload_dataloaders_every_epoch` to ``True``.\n\n It's recommended that all data downloads and preparation happen in :meth:`prepare_data`.\n\n - :meth:`~pytorch_lightning.trainer.Trainer.fit`\n - ...\n - :meth:`prepare_data`\n - :meth:`train_dataloader`\n - :meth:`val_dataloader`\n - :meth:`test_dataloader`\n\n Note:\n Lightning adds the correct sampler for distributed and arbitrary hardware\n There is no need to set it yourself.\n\n Return:\n Single or multiple PyTorch DataLoaders.\n\n Examples:\n .. code-block:: python\n\n def val_dataloader(self):\n transform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (1.0,))])\n dataset = MNIST(root='/path/to/mnist/', train=False,\n transform=transform, download=True)\n loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=self.batch_size,\n shuffle=False\n )\n\n return loader\n\n # can also return multiple dataloaders\n def val_dataloader(self):\n return [loader_a, loader_b, ..., loader_n]\n\n Note:\n If you don't need a validation dataset and a :meth:`validation_step`, you don't need to\n implement this method.\n\n Note:\n In the case where you return multiple validation dataloaders, the :meth:`validation_step`\n will have an argument ``dataloader_idx`` which matches the order here.\n \"\"\"\n\n def summarize(self, mode: str = ModelSummary.MODE_DEFAULT) -> ModelSummary:\n model_summary = ModelSummary(self, mode=mode)\n log.info('\\n' + str(model_summary))\n return model_summary\n\n def freeze(self) -> None:\n r\"\"\"\n Freeze all params for inference.\n\n Example:\n .. code-block:: python\n\n model = MyLightningModule(...)\n model.freeze()\n\n \"\"\"\n for param in self.parameters():\n param.requires_grad = False\n\n self.eval()\n\n def unfreeze(self) -> None:\n \"\"\"\n Unfreeze all parameters for training.\n\n .. code-block:: python\n\n model = MyLightningModule(...)\n model.unfreeze()\n\n \"\"\"\n for param in self.parameters():\n param.requires_grad = True\n\n self.train()\n\n def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None:\n r\"\"\"\n Called by Lightning to restore your model.\n If you saved something with :meth:`on_save_checkpoint` this is your chance to restore this.\n\n Args:\n checkpoint: Loaded checkpoint\n\n\n Example:\n .. code-block:: python\n\n def on_load_checkpoint(self, checkpoint):\n # 99% of the time you don't need to implement this method\n self.something_cool_i_want_to_save = checkpoint['something_cool_i_want_to_save']\n\n Note:\n Lightning auto-restores global step, epoch, and train state including amp scaling.\n There is no need for you to restore anything regarding training.\n \"\"\"\n\n def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None:\n r\"\"\"\n Called by Lightning when saving a checkpoint to give you a chance to store anything\n else you might want to save.\n\n Args:\n checkpoint: Checkpoint to be saved\n\n Example:\n .. code-block:: python\n\n def on_save_checkpoint(self, checkpoint):\n # 99% of use cases you don't need to implement this method\n checkpoint['something_cool_i_want_to_save'] = my_cool_pickable_object\n\n Note:\n Lightning saves all aspects of training (epoch, global step, etc...)\n including amp scaling.\n There is no need for you to store anything about training.\n\n \"\"\"\n\n def get_progress_bar_dict(self) -> Dict[str, Union[int, str]]:\n r\"\"\"\n Implement this to override the default items displayed in the progress bar.\n By default it includes the average loss value, split index of BPTT (if used)\n and the version of the experiment when using a logger.\n\n .. code-block::\n\n Epoch 1: 4%|▎ | 40/1095 [00:03<01:37, 10.84it/s, loss=4.501, v_num=10]\n\n Here is an example how to override the defaults:\n\n .. code-block:: python\n\n def get_progress_bar_dict(self):\n # don't show the version number\n items = super().get_progress_bar_dict()\n items.pop(\"v_num\", None)\n return items\n\n Return:\n Dictionary with the items to be displayed in the progress bar.\n \"\"\"\n # call .item() only once but store elements without graphs\n running_train_loss = self.trainer.running_loss.mean()\n avg_training_loss = running_train_loss.cpu().item() if running_train_loss is not None else float('NaN')\n tqdm_dict = {'loss': '{:.3f}'.format(avg_training_loss)}\n\n if self.trainer.truncated_bptt_steps is not None:\n tqdm_dict['split_idx'] = self.trainer.split_idx\n\n if self.trainer.logger is not None and self.trainer.logger.version is not None:\n version = self.trainer.logger.version\n # show last 4 places of long version strings\n version = version[-4:] if isinstance(version, str) else version\n tqdm_dict['v_num'] = version\n\n return tqdm_dict\n\n def get_tqdm_dict(self) -> Dict[str, Union[int, str]]:\n \"\"\"\n Additional items to be displayed in the progress bar.\n\n Return:\n Dictionary with the items to be displayed in the progress bar.\n\n Warning:\n Deprecated since v0.7.3.\n Use :meth:`get_progress_bar_dict` instead.\n \"\"\"\n rank_zero_warn(\n \"`get_tqdm_dict` was renamed to `get_progress_bar_dict` in v0.7.3\"\n \" and this method will be removed in v1.0.0\",\n DeprecationWarning,\n )\n return self.get_progress_bar_dict()\n\n @classmethod\n def _auto_collect_arguments(cls, frame=None) -> Tuple[Dict, Dict]:\n \"\"\"\"\"\"\n \"\"\"\n Collect all module arguments in the current constructor and all child constructors.\n The child constructors are all the ``__init__`` methods that reach the current class through\n (chained) ``super().__init__()`` calls.\n\n Args:\n frame: instance frame\n\n Returns:\n self_arguments: arguments dictionary of the first instance\n parents_arguments: arguments dictionary of the parent's instances\n \"\"\"\n if not frame:\n frame = inspect.currentframe()\n\n frame_args = collect_init_args(frame.f_back, [])\n self_arguments = frame_args[-1]\n\n # set module_arguments in child\n self_arguments = self_arguments\n parents_arguments = {}\n\n # add all arguments from parents\n for args in frame_args[:-1]:\n parents_arguments.update(args)\n return self_arguments, parents_arguments\n\n def save_hyperparameters(self, *args, frame=None) -> None:\n \"\"\"Save all model arguments.\n\n Args:\n args: single object of `dict`, `NameSpace` or `OmegaConf`\n or string names or argumenst from class `__init__`\n\n >>> from collections import OrderedDict\n >>> class ManuallyArgsModel(LightningModule):\n ... def __init__(self, arg1, arg2, arg3):\n ... super().__init__()\n ... # manually assign arguments\n ... self.save_hyperparameters('arg1', 'arg3')\n ... def forward(self, *args, **kwargs):\n ... ...\n >>> model = ManuallyArgsModel(1, 'abc', 3.14)\n >>> model.hparams\n \"arg1\": 1\n \"arg3\": 3.14\n\n >>> class AutomaticArgsModel(LightningModule):\n ... def __init__(self, arg1, arg2, arg3):\n ... super().__init__()\n ... # equivalent automatic\n ... self.save_hyperparameters()\n ... def forward(self, *args, **kwargs):\n ... ...\n >>> model = AutomaticArgsModel(1, 'abc', 3.14)\n >>> model.hparams\n \"arg1\": 1\n \"arg2\": abc\n \"arg3\": 3.14\n\n >>> class SingleArgModel(LightningModule):\n ... def __init__(self, params):\n ... super().__init__()\n ... # manually assign single argument\n ... self.save_hyperparameters(params)\n ... def forward(self, *args, **kwargs):\n ... ...\n >>> model = SingleArgModel(Namespace(p1=1, p2='abc', p3=3.14))\n >>> model.hparams\n \"p1\": 1\n \"p2\": abc\n \"p3\": 3.14\n \"\"\"\n if not frame:\n frame = inspect.currentframe().f_back\n init_args = get_init_args(frame)\n assert init_args, 'failed to inspect the self init'\n if not args:\n hp = init_args\n self._hparams_name = 'kwargs' if hp else None\n else:\n isx_non_str = [i for i, arg in enumerate(args) if not isinstance(arg, str)]\n if len(isx_non_str) == 1:\n hp = args[isx_non_str[0]]\n cand_names = [k for k, v in init_args.items() if v == hp]\n self._hparams_name = cand_names[0] if cand_names else None\n else:\n hp = {arg: init_args[arg] for arg in args if isinstance(arg, str)}\n self._hparams_name = 'kwargs'\n\n # `hparams` are expected here\n if hp:\n self._set_hparams(hp)\n\n def _set_hparams(self, hp: Union[dict, Namespace, str]) -> None:\n if isinstance(hp, Namespace):\n hp = vars(hp)\n if isinstance(hp, dict):\n hp = AttributeDict(hp)\n elif isinstance(hp, PRIMITIVE_TYPES):\n raise ValueError(f'Primitives {PRIMITIVE_TYPES} are not allowed.')\n elif not isinstance(hp, ALLOWED_CONFIG_TYPES):\n raise ValueError(f'Unsupported config type of {type(hp)}.')\n\n if isinstance(hp, dict) and isinstance(self.hparams, dict):\n self.hparams.update(hp)\n else:\n self._hparams = hp\n\n def to_onnx(self, file_path: str, input_sample: Optional[Tensor] = None, **kwargs):\n \"\"\"Saves the model in ONNX format\n\n Args:\n file_path: The path of the file the model should be saved to.\n input_sample: A sample of an input tensor for tracing.\n **kwargs: Will be passed to torch.onnx.export function.\n\n Example:\n >>> class SimpleModel(LightningModule):\n ... def __init__(self):\n ... super().__init__()\n ... self.l1 = torch.nn.Linear(in_features=64, out_features=4)\n ...\n ... def forward(self, x):\n ... return torch.relu(self.l1(x.view(x.size(0), -1)))\n\n >>> with tempfile.NamedTemporaryFile(suffix='.onnx', delete=False) as tmpfile:\n ... model = SimpleModel()\n ... input_sample = torch.randn((1, 64))\n ... model.to_onnx(tmpfile.name, input_sample, export_params=True)\n ... os.path.isfile(tmpfile.name)\n True\n \"\"\"\n\n if isinstance(input_sample, Tensor):\n input_data = input_sample\n elif self.example_input_array is not None:\n input_data = self.example_input_array\n else:\n if input_sample is not None:\n raise ValueError(f'Received `input_sample` of type {type(input_sample)}. Expected type is `Tensor`')\n else:\n raise ValueError('Could not export to ONNX since neither `input_sample` nor'\n ' `model.example_input_array` attribute is set.')\n input_data = input_data.to(self.device)\n if 'example_outputs' not in kwargs:\n self.eval()\n with torch.no_grad():\n kwargs['example_outputs'] = self(input_data)\n\n torch.onnx.export(self, input_data, file_path, **kwargs)\n\n @property\n def hparams(self) -> Union[AttributeDict, str]:\n if not hasattr(self, '_hparams'):\n self._hparams = AttributeDict()\n return self._hparams\n\n @hparams.setter\n def hparams(self, hp: Union[dict, Namespace, Any]):\n hparams_assignment_name = self.__get_hparams_assignment_variable()\n self._hparams_name = hparams_assignment_name\n self._set_hparams(hp)\n\n def __get_hparams_assignment_variable(self):\n \"\"\"\"\"\"\n \"\"\"\n looks at the code of the class to figure out what the user named self.hparams\n this only happens when the user explicitly sets self.hparams\n \"\"\"\n try:\n class_code = inspect.getsource(self.__class__)\n lines = class_code.split('\\n')\n for line in lines:\n line = re.sub(r\"\\s+\", \"\", line, flags=re.UNICODE)\n if '.hparams=' in line:\n return line.split('=')[1]\n except Exception as e:\n return 'hparams'\n\n return None\n" ]
[ [ "torch.distributed.init_process_group", "torch.no_grad", "torch.onnx.export", "torch.nn.SyncBatchNorm.convert_sync_batchnorm" ] ]
uw-loci/demo_wsi_superres
[ "38283031eee4823d332fae1b6b32b5da33fb957f" ]
[ "train_paired.py" ]
[ "import os, argparse, sys, shutil, warnings, glob\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nfrom math import log2, log10\nimport pandas as pd\nimport numpy as np\nfrom collections import OrderedDict\n\nfrom torchvision import transforms, utils\nimport torchvision\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nimport torch.optim.lr_scheduler as lr_scheduler\n\nfrom skimage import exposure, color, io, img_as_float, img_as_ubyte\nfrom skimage.util import view_as_windows, pad, montage\nfrom PIL import Image, ImageFilter\nimport imagej\n\nimport data_loader as data\nimport models\n\nimport pytorch_fid.fid_score as fid_score\n\n\ndef paired_dataloader(args, csv='train'):\n transformed_dataset = data.Paired_Dataset(csv_file=data.paired_csv_path(csv, dataset=args.dataset),\n img_size=args.patch_size,\n transform=data.Compose([data.ToTensor()])\n )\n dataloader = DataLoader(transformed_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers)\n return dataloader\n\ndef train(args, epoch, run, dataloader, generator, discriminator, optimizer_G, optimizer_D, criterionL, criterionMSE, Tensor=None, device='cuda:0', patch=None):\n l = args.percep_weight\n if args.gan == 0:\n gan = False\n else:\n gan = True\n epoch_loss = 0\n gan_loss = 0\n total_loss = 0\n dis_loss = 0\n generator.train()\n for iteration, batch in enumerate(dataloader):\n real_mid = Variable(batch['input'].type(Tensor).to(device), requires_grad=False)\n real_high = Variable(batch['output'].type(Tensor).to(device), requires_grad=False) \n # Adversarial ground truths\n valid = Variable(Tensor(np.ones((real_mid.size(0), *patch))).to(device), requires_grad=False)\n fake = Variable(Tensor(np.zeros((real_mid.size(0), *patch))).to(device), requires_grad=False) \n #---------------\n # Train Generator\n #--------------- \n optimizer_G.zero_grad() \n # GAN loss\n fake_high = generator(real_mid)\n if gan:\n pred_fake = discriminator(fake_high, real_mid)\n loss_GAN = criterionMSE(pred_fake, valid)\n \n # Identity\n lossL1 = criterionL(fake_high, real_high) \n loss_pixel = lossL1 \n # Total loss\n if gan:\n loss_G = l * loss_GAN + (1-l) * loss_pixel \n loss_G.backward()\n total_loss = total_loss + loss_G.item()\n gan_loss = gan_loss + loss_GAN.item()\n else:\n loss_pixel.backward()\n optimizer_G.step() \n #---------------\n # Train Discriminator\n #--------------- \n if gan and iteration % args.num_critic == 0:\n optimizer_D.zero_grad() \n # Real loss\n pred_real = discriminator(real_high, real_mid)\n loss_real = criterionMSE(pred_real, valid) \n # Fake loss\n pred_fake = discriminator(fake_high.detach(), real_mid)\n loss_fake = criterionMSE(pred_fake, fake)\n # Total loss\n loss_D = 0.5 * (loss_real + loss_fake)\n loss_D.backward()\n optimizer_D.step()\n dis_loss = dis_loss + loss_D.item() \n epoch_loss = epoch_loss + loss_pixel.item() \n if gan:\n sys.stdout.write('\\r[%d/%d][%d/%d] Discriminator_Loss: %.4f Generator_Loss (Identity/Advers/Total): %.4f/%.4f/%.4f' \n % (epoch, args.num_epochs, iteration, len(dataloader), loss_D.item(), \n loss_pixel.item(), loss_GAN.item(), loss_G.item()))\n else:\n sys.stdout.write('\\r[%d/%d][%d/%d] Generator_L1_Loss: %.4f' \n % (epoch, args.num_epochs, iteration, len(dataloader), loss_pixel.item()))\n print(\"\\n ===> Epoch {} Complete: Avg. Loss: {:.4f}\".format(epoch, epoch_loss / len(dataloader))) \n g_path = os.path.join('weights', run, 'generator.pth')\n d_path = os.path.join('weights', run, 'discriminator.pth')\n os.makedirs(os.path.join('weights', run), exist_ok=True)\n torch.save(generator.state_dict(), g_path)\n if gan:\n os.makedirs(os.path.join('weights', run), exist_ok=True)\n torch.save(discriminator.state_dict(), d_path)\n\ndef compute_p_snr(path_input, path_ref):\n MSE = nn.MSELoss()\n imgs_input = glob.glob(os.path.join(path_input, '*.tiff'))\n imgs_ref = glob.glob(os.path.join(path_ref, '*.tiff'))\n ave_psnr = 0\n for i in range(len(imgs_input)):\n img_input = torch.from_numpy(img_as_float(io.imread(imgs_input[i]).transpose(2, 1, 0))) \n img_ref = torch.from_numpy(img_as_float(io.imread(imgs_ref[i]).transpose(2, 1, 0)))\n img_input = img_input[None, :]\n img_ref = img_ref[None, :] \n mse = MSE(img_input, img_ref) \n psnr = 10 * log10(1 / mse.item())\n ave_psnr += psnr\n ave_psnr = ave_psnr / len(imgs_input)\n return ave_psnr\n\ndef print_output(generator, dataloader_valid, device='cuda:0'):\n os.makedirs('output/print', exist_ok=True)\n os.makedirs('output/print/lr', exist_ok=True)\n os.makedirs('output/print/hr', exist_ok=True)\n os.makedirs('output/print/sr', exist_ok=True)\n with torch.no_grad(): \n generator.eval()\n print(\"=> Printing sampled patches\")\n for k, batch in enumerate(dataloader_valid): \n input, target = batch['input'].to(device), batch['output'].to(device)\n imgs_input =input.float().to(device)\n prediction = generator(imgs_input)\n target = target.float()\n for i in range(target.shape[0]):\n utils.save_image(imgs_input[i], 'output/print/lr/{}_{}.tiff'.format(k, i))\n utils.save_image(target[i], 'output/print/hr/{}_{}.tiff'.format(k, i))\n utils.save_image(prediction[i], 'output/print/sr/{}_{}.tiff'.format(k, i))\n sys.stdout.write(\"\\r ==> Batch {}/{}\".format(k+1, len(dataloader_valid)))\n print(\"\\n Computing FID score\")\n fid = fid_score.calculate_fid_given_paths(('output/print/sr', 'output/print/hr'), 8, 'cuda:0', 2048)\n print(\"\\n Computing PSNR\")\n psnr = compute_p_snr('output/print/sr', 'output/print/hr')\n print(\"FID score: {}, PSNR: {}\".format(fid, psnr))\n return fid, psnr\n\ndef main():\n parser = argparse.ArgumentParser(description='Train WSISR on compressed TMA dataset')\n parser.add_argument('--batch-size', default=32, type=int, help='Batch size')\n parser.add_argument('--patch-size', default=256, type=int, help='Patch size')\n parser.add_argument('--num-workers', default=4, type=int, help='Number of workers')\n parser.add_argument('--num-epochs', default=900, type=int, help='Number of epochs, more epochs are desired for GAN training')\n parser.add_argument('--g-lr', default=0.0001, type=float, help='Learning rate of the generator')\n parser.add_argument('--d-lr', default=0.00001, type=float, help='Learning rate of the descriminator')\n parser.add_argument('--percep-weight', default=0.01, type=float, help='GAN loss weight')\n parser.add_argument('--run-from', default=None, type=str, help='Load weights from a previous run, use folder name in [weights] folder')\n parser.add_argument('--gan', default=1, type=int, help='Use GAN')\n parser.add_argument('--num-critic', default=1, type=int, help='Iteration interval for training the descriminator') \n parser.add_argument('--test-interval', default=50, type=int, help='Epoch interval for FID score testing')\n parser.add_argument('--print-interval', default=10, type=int, help='Epoch interval for output printing')\n parser.add_argument('--dataset', default='TMA', type=str, help='Dataset folder name')\n parser.add_argument('--in-folder', default='low', type=str, help='Low NA image folder name')\n parser.add_argument('--out-folder', default='high', type=str, help='High NA image folder name') \n parser.add_argument('--extension', default='jpg', type=str, help='Training image extension') \n args = parser.parse_args()\n warnings.filterwarnings('ignore')\n device = torch.device('cuda:0')\n tensor = torch.cuda.FloatTensor\n data.generate_paired_csv(dataset=args.dataset, in_folder=args.in_folder, out_folder=args.out_folder, ext=args.extension)\n valid_dataset = paired_dataloader(args, 'valid')\n train_dataset = paired_dataloader(args, 'train')\n test_dataset = paired_dataloader(args, 'test')\n generator = models.Generator()\n generator.to(device);\n discriminator = models.Discriminator()\n discriminator.to(device);\n criterionL = nn.L1Loss().cuda()\n criterionMSE = nn.MSELoss().cuda()\n optimizer_G = torch.optim.Adam(generator.parameters(), lr=args.g_lr)\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=args.d_lr)\n patch = (1, args.patch_size // 2 ** 4, args.patch_size // 2 ** 4)\n if args.run_from is not None:\n generator.load_state_dict(torch.load(os.path.join('weights', args.run_from, 'generator.pth')))\n try:\n discriminator.load_state_dict(torch.load(os.path.join('weights', args.run_from, 'discriminator.pth')))\n except:\n print('Discriminator weights not found!')\n pass\n optimizer_G = torch.optim.Adam(generator.parameters(), lr=args.g_lr)\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=args.d_lr)\n scheduler_G = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer_G, args.num_epochs, args.g_lr*0.05)\n scheduler_D = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer_D, args.num_epochs, args.d_lr*0.05)\n run = datetime.now().strftime(\"%Y-%m-%d--%H-%M-%S\")\n for epoch in range(0, args.num_epochs):\n train(args, epoch, run, train_dataset, generator, discriminator, optimizer_G, optimizer_D, criterionL, criterionMSE, tensor, device, patch)\n scheduler_G.step()\n scheduler_D.step()\n if epoch % args.print_interval == 0:\n print_output(generator, valid_dataset, device)\n print_output(generator, test_dataset, device)\n \nif __name__ == '__main__':\n main()\n\n" ]
[ [ "torch.optim.lr_scheduler.CosineAnnealingLR", "torch.utils.data.DataLoader", "torch.nn.MSELoss", "torch.nn.L1Loss", "torch.no_grad", "torch.device" ] ]
thomascherickal/Auto-PyTorch
[ "9e25a3bdef8e836e63979229eef77830cd64bb53" ]
[ "autoPyTorch/training/mixup.py" ]
[ "from autoPyTorch.training.base_training import BaseBatchLossComputationTechnique\nimport numpy as np\nfrom torch.autograd import Variable\nimport ConfigSpace\nimport torch\n\nclass Mixup(BaseBatchLossComputationTechnique):\n def set_up(self, pipeline_config, hyperparameter_config, logger):\n super(Mixup, self).set_up(pipeline_config, hyperparameter_config, logger)\n self.alpha = hyperparameter_config[\"alpha\"]\n\n def prepare_batch_data(self, X_batch, y_batch):\n '''Returns mixed inputs, pairs of targets, and lambda'''\n if self.alpha > 0:\n self.lam = np.random.beta(self.alpha, self.alpha)\n else:\n self.lam = 1\n\n batch_size = X_batch.size()[0]\n if X_batch.is_cuda:\n index = torch.randperm(batch_size).cuda()\n else:\n index = torch.randperm(batch_size)\n\n self.mixed_x = self.lam * X_batch + (1 - self.lam) * X_batch[index, :]\n self.y_a, self.y_b = y_batch, y_batch[index]\n \n def compute_batch_loss(self, loss_function, y_batch_pred):\n # self.logger.debug(\"Computing batch loss with mixup\")\n\n result = self.lam * loss_function(y_batch_pred, Variable(self.y_a)) + \\\n (1 - self.lam) * loss_function(y_batch_pred, Variable(self.y_b))\n self.lam = None\n self.mixed_x = None\n self.y_a = None\n self.y_b = None\n return result\n\n @staticmethod\n def get_hyperparameter_search_space(**pipeline_config):\n cs = ConfigSpace.ConfigurationSpace()\n cs.add_hyperparameter(ConfigSpace.hyperparameters.UniformFloatHyperparameter(\"alpha\", lower=0, upper=1, default_value=1))\n return cs" ]
[ [ "numpy.random.beta", "torch.autograd.Variable", "torch.randperm" ] ]
yick2232/google-research
[ "4a59cab927579ea9722e43252c695de5da4eb5e2", "4a59cab927579ea9722e43252c695de5da4eb5e2" ]
[ "unprocessing/network.py", "r4r/r4r_generate_data.py" ]
[ "# coding=utf-8\n# Copyright 2019 The Google Research 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\"\"\"Unprocessing neural network architecture.\n\nUnprocessing Images for Learned Raw Denoising\nhttp://timothybrooks.com/tech/unprocessing\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\ndef conv(features, num_channels, activation=tf.nn.leaky_relu):\n \"\"\"Applies a 3x3 conv layer.\"\"\"\n return tf.layers.conv2d(features, num_channels, 3, padding='same',\n activation=activation)\n\n\ndef conv_block(features, num_channels):\n \"\"\"Applies 3x conv layers.\"\"\"\n with tf.name_scope(None, 'conv_block'):\n features = conv(features, num_channels)\n features = conv(features, num_channels)\n features = conv(features, num_channels)\n return features\n\n\ndef downsample_2x(features):\n \"\"\"Applies a 2x spatial downsample via max pooling.\"\"\"\n with tf.name_scope(None, 'downsample_2x'):\n return tf.layers.max_pooling2d(features, 2, 2, padding='same')\n\n\ndef upsample_2x(features):\n \"\"\"Applies a 2x spatial upsample via bilinear interpolation.\"\"\"\n with tf.name_scope(None, 'upsample_2x'):\n shape = tf.shape(features)\n shape = [shape[1] * 2, shape[2] * 2]\n features = tf.image.resize_bilinear(features, shape)\n return features\n\n\ndef inference(noisy_img, variance):\n \"\"\"Residual U-Net with skip connections.\n\n Expects four input channels for the Bayer color filter planes (e.g. RGGB).\n This is the format of real raw images before they are processed, and an\n effective time to denoise images in an image processing pipelines.\n\n Args:\n noisy_img: Tensor of shape [B, H, W, 4].\n variance: Tensor of shape [B, H, W, 4].\n\n Returns:\n Denoised image in Tensor of shape [B, H, W, 4].\n \"\"\"\n\n noisy_img = tf.identity(noisy_img, 'noisy_img')\n noisy_img.set_shape([None, None, None, 4])\n variance = tf.identity(variance, 'variance')\n variance.shape.assert_is_compatible_with(noisy_img.shape)\n variance.set_shape([None, None, None, 4])\n\n features = tf.concat([noisy_img, variance], axis=-1)\n skip_connections = []\n\n with tf.name_scope(None, 'encoder'):\n for num_channels in (32, 64, 128, 256):\n features = conv_block(features, num_channels)\n skip_connections.append(features)\n features = downsample_2x(features)\n features = conv_block(features, 512)\n\n with tf.name_scope(None, 'decoder'):\n for num_channels in (256, 128, 64, 32):\n features = upsample_2x(features)\n with tf.name_scope(None, 'skip_connection'):\n features = tf.concat([features, skip_connections.pop()], axis=-1)\n features = conv_block(features, num_channels)\n\n residual = conv(features, 4, None)\n return tf.identity(noisy_img + residual, 'denoised_img')\n", "# coding=utf-8\n# Copyright 2019 The Google Research 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\"\"\"Script to build R4R data from the original R2R data.\n\nLink to the original R2R:\n https://niessner.github.io/Matterport/\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport collections\nimport json\nimport os\n\nimport graph_utils\n\nimport networkx as nx\nimport numpy as np\n\n\ndef main(args):\n \"\"\"Generate R4R data from the original R2R data.\n\n Args:\n args: argparse containing paths to input and output files.\n \"\"\"\n print('******Generating R4R Data********')\n print(' Distance threshold: {} meters'.format(args.distance_threshold))\n print(' Heading threshold: {} radians'.format(args.heading_threshold))\n\n def _connections_file_path(scan):\n return os.path.join(\n args.connections_dir, '{}_connectivity.json'.format(scan))\n\n inputs = json.load(open(args.input_file_path))\n outputs = list()\n filtered = collections.Counter()\n\n # Group by scan to save memory.\n scans = dict()\n for value in inputs:\n scan = value['scan']\n if scan not in scans:\n scans[scan] = []\n scans[scan].append(value)\n\n for scan, values in scans.items():\n print('Loading graph for scan {}.'.format(scan))\n graph = graph_utils.load(_connections_file_path(scan))\n pos2d = nx.get_node_attributes(graph, 'pos2d')\n\n # Cache format: (node, (distance, path)) ((node obj, (dict, dict)))\n cache = dict(nx.all_pairs_dijkstra(graph, weight='weight3d'))\n shortest_distance = {k: v[0] for k, v in cache.items()}\n shortest_path = {k: v[1] for k, v in cache.items()}\n\n for first in values:\n for second in values:\n first_target = first['path'][-1]\n second_source = second['path'][0]\n\n # Compute the end-start distance (meters).\n distance = shortest_distance[first_target][second_source]\n\n # Compute the absolute end-start heading difference (radians).\n x, y = pos2d[first['path'][-1]] - pos2d[first['path'][-2]]\n heading = abs(second['heading'] - np.arctan2(y, x) % (2 * np.pi))\n\n if (args.distance_threshold is not None\n and distance > args.distance_threshold):\n filtered['distance'] += 1\n elif (args.heading_threshold is not None\n and heading > args.heading_threshold):\n filtered['heading'] += 1\n else:\n value = dict()\n value['path'] = (\n first['path'][:-1]\n + shortest_path[first_target][second_source]\n + second['path'][1:])\n value['distance'] = (\n first['distance']\n + shortest_distance[first_target][second_source]\n + second['distance'])\n value['instructions'] = [\n x + y # pylint: disable=g-complex-comprehension\n for x in first['instructions']\n for y in second['instructions']]\n value['heading'] = first['heading']\n value['path_id'] = len(outputs)\n value['scan'] = scan\n\n # Additional data.\n path_source = first['path'][0]\n path_target = second['path'][-1]\n value['shortest_path_distance'] = cache[path_source][0][path_target]\n value['shortest_path'] = cache[path_source][1][path_target]\n value['first_path_id'] = first['path_id']\n value['second_path_id'] = second['path_id']\n\n outputs.append(value)\n\n with open(args.output_file_path, 'w') as f:\n json.dump(outputs, f, indent=2, sort_keys=True, separators=(',', ': '))\n\n # Dataset summary metrics.\n tot_instructions = np.sum([len(x['instructions']) for x in outputs])\n avg_distance = np.mean([x['distance'] for x in outputs])\n avg_path_len = np.mean([len(x['path']) for x in outputs])\n avg_sp_distance = np.mean([x['shortest_path_distance'] for x in outputs])\n avg_sp_path_len = np.mean([len(x['shortest_path']) for x in outputs])\n\n print('******Final Results********')\n print(' Total instructions generated: {}'.format(tot_instructions))\n print(' Average path distance (meters): {}'.format(avg_distance))\n print(' Average shortest path distance: {}'.format(avg_sp_distance))\n print(' Average path length (steps): {}'.format(avg_path_len))\n print(' Average shortest path length: {}'.format(avg_sp_path_len))\n print(' Total paths generated: {}'.format(len(outputs)))\n print(' Total distance filtered paths: {}'.format(filtered['distance']))\n print(' Total heading filtered paths: {}'.format(filtered['heading']))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--connections_dir',\n dest='connections_dir',\n required=True,\n help='Path to the Matterport simulator connection data.')\n parser.add_argument(\n '--input_file_path',\n dest='input_file_path',\n required=True,\n help='Path to read the R2R input data.')\n parser.add_argument(\n '--output_file_path',\n dest='output_file_path',\n required=True,\n help='Path to write the R4R output data.')\n parser.add_argument(\n '--distance_threshold',\n dest='distance_threshold',\n required=False,\n nargs='?',\n const=3.0,\n type=float,\n help='Maximum end-start distance (meters) to join R2R paths.')\n parser.add_argument(\n '--heading_threshold',\n dest='heading_threshold',\n required=False,\n nargs='?',\n const=None,\n type=float,\n help='Maximum end-start heading difference (radians) to join R2R paths.')\n main(parser.parse_args())\n" ]
[ [ "tensorflow.layers.conv2d", "tensorflow.shape", "tensorflow.name_scope", "tensorflow.layers.max_pooling2d", "tensorflow.image.resize_bilinear", "tensorflow.concat", "tensorflow.identity" ], [ "numpy.arctan2", "numpy.mean" ] ]
Room-10/Opymize
[ "8632e5b618f41a65b1a37df099a6da254500e14b" ]
[ "opymize/tools/__init__.py" ]
[ "\nimport numpy as np\n\ndef truncate(x, n):\n k = -int(np.floor(np.log10(abs(x))))\n # Example: x = 0.006142 => k = 3 / x = 2341.2 => k = -3\n k += n - 1\n if k > 0:\n x_str = str(abs(x))[:(k+2)]\n else:\n x_str = str(abs(x))[:n]+\"0\"*(-k)\n return np.sign(x)*float(x_str)\n\ndef solve_reduced_monic_cubic(a, b, soln=0):\n \"\"\" Solve x**3 + a*x + b = 0 using explicit formulas.\n\n Only real solutions are computed and in case more than one real\n solution exists, only one of them is returned.\n\n Args:\n a, b : array-like of floats, shape (nvals,)\n soln : int, one of 0,1,2\n Indicate which solution is returned in case of non-uniqueness.\n\n Returns:\n x : ndarray of floats, shape (nvals,)\n \"\"\"\n a, b = np.asarray(a), np.asarray(b)\n assert a.size == b.size\n a, b = a.ravel(), b.ravel()\n x, Q, Q3, R, D, arr1, arr2 = [np.zeros_like(a) for i in range(7)]\n\n # trivial case (a == 0):\n msk = (a == 0)\n x[msk] = np.cbrt(-b[msk])\n\n # nontrivial case (a != 0):\n msk = ~msk\n Q[msk], R[msk] = a[msk]/3, -b[msk]/2\n Q3[msk] = Q[msk]**3\n D[msk] = Q3[msk] + R[msk]**2\n\n # subcase with three real roots:\n msk2 = msk & (D <= 0)\n theta, sqrt_Q = arr1, arr2\n theta[msk2] = np.arccos(R[msk2]/np.sqrt(-Q3[msk2]))\n sqrt_Q[msk2] = np.sqrt(-Q[msk2])\n x[msk2] = 2*sqrt_Q[msk2]*np.cos((theta[msk2] + 2*soln*np.pi)/3.0)\n\n # subcase with unique real root:\n msk2 = msk & (D > 0)\n AD, BD = arr1, arr2\n AD[msk2] = np.cbrt(np.abs(R[msk2]) + np.sqrt(D[msk2]))*np.sign(R[msk2])\n msk3 = msk2 & (AD != 0)\n BD[msk3] = -Q[msk3]/AD[msk3]\n x[msk2] = AD[msk2] + BD[msk2]\n\n return x\n" ]
[ [ "numpy.cbrt", "numpy.zeros_like", "numpy.sign", "numpy.abs", "numpy.asarray", "numpy.cos", "numpy.sqrt" ] ]
kaka-lin/ML-Notes
[ "047b88d59346b2ec719b1b3e2fcd605e1ccfaf91" ]
[ "Object Detection/iou.py" ]
[ "import numpy as np\n\n\ndef calculate_iou(bbox1, bbox2):\n \"\"\"\n calculate iou\n args:\n - bbox1 [array]: 1x4 single bbox\n - bbox2 [array]: 1x4 single bbox\n returns:\n - iou [float]: iou between 2 bboxes\n \"\"\"\n xmin = max(bbox1[0], bbox2[0]) # x_left\n ymin = max(bbox1[1], bbox2[1]) # y_top\n xmax = min(bbox1[2], bbox2[2]) # x_right\n ymax = min(bbox1[3], bbox2[3]) # y_bottom\n\n intersection = max(0, xmax - xmin + 1) * max(0, ymax - ymin + 1)\n bbox1_area = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])\n bbox2_area = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])\n\n union = bbox1_area + bbox2_area - intersection\n return intersection / union\n\n\nif __name__ == \"__main__\":\n bbox1 = np.array([661, 27, 679, 47])\n bbox2 = np.array([662, 27, 682, 47])\n iou = calculate_iou(bbox1, bbox2)\n print(iou)\n\n bbox1 = np.array([0, 0, 100, 100])\n bbox2 = np.array([101, 101, 200, 200])\n iou = calculate_iou(bbox1, bbox2)\n print(iou)\n" ]
[ [ "numpy.array" ] ]
noatgnu/colossi
[ "c936bc25b5990f8dfbf4db3ed11ce8a893553668" ]
[ "model_test.py" ]
[ "import unittest\nfrom model import prediction_with_model\nimport pandas as pd\nimport numpy as np\n\nclass PredictionWithModel(unittest.TestCase):\n def test_prediction(self):\n d = pd.read_csv(r\"C:\\Users\\Toan\\Documents\\GitHub\\colossi\\static\\temp\\cc7deed8140745d89f2f42f716f6fd1b\\out_imac_atlas_expression_v7.1.tsv\", \" \")\n\n result = np.array([d['Freq'].to_list() + [0, 1800]])\n print(prediction_with_model(result))\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "pandas.read_csv" ] ]
mhrmm/geosolver
[ "13ae2972c58d5ba4c4878576f9fba8569cc99629" ]
[ "geosolver/diagram/select_primitives.py" ]
[ "import logging\n\nimport numpy as np\n\nfrom geosolver.diagram.states import PrimitiveParse\nfrom geosolver.diagram.computational_geometry import line_length, circumference, \\\n distance_between_circle_and_point, midpoint, line_unit_vector, line_normal_vector, \\\n distance_between_points_squared, distance_between_line_and_point\nfrom geosolver.ontology.instantiator_definitions import instantiators\nimport geosolver.parameters as params\n\n\n__author__ = 'minjoon'\n\n\ndef select_primitives(primitive_parse):\n assert isinstance(primitive_parse, PrimitiveParse)\n if len(primitive_parse.primitives) == 0:\n logging.error(\"No primitive detected.\")\n return primitive_parse\n pixels_dict = _get_pixels_dict(primitive_parse,\n params.LINE_EPS, params.CIRCLE_EPS)\n selected_primitives = {}\n remaining_primitives = primitive_parse.primitives.copy()\n reward = 0\n while len(remaining_primitives) > 0:\n key = _get_next_primitive_key(selected_primitives, remaining_primitives, pixels_dict)\n updated_selected_primitives = selected_primitives.copy()\n updated_selected_primitives[key] = remaining_primitives[key]\n new_reward = _evaluate_reward(updated_selected_primitives, pixels_dict)\n if new_reward - reward > params.PRIMITIVE_SELECTION_MIN_GAIN:\n selected_primitives = updated_selected_primitives\n del remaining_primitives[key]\n reward = new_reward\n else:\n break\n\n new_primitive_parse = _get_primitive_parse(primitive_parse.image_segment_parse, selected_primitives)\n return new_primitive_parse\n\ndef _get_primitive_parse(segment_parse, primitives):\n lines = dict(pair for pair in primitives.iteritems()\n if isinstance(pair[1], instantiators['line']))\n circles = dict(pair for pair in primitives.iteritems()\n if isinstance(pair[1], instantiators['circle']))\n return PrimitiveParse(segment_parse, lines, circles)\n\n\ndef _get_next_primitive_key(selected_primitives, remaining_primitives, pixels_dict):\n return max(remaining_primitives.items(),\n key=lambda p: _evaluate_reward(dict(selected_primitives.items()+[p]), pixels_dict))[0]\n\n\ndef _get_pixels_dict(primitive_parse, line_eps, circle_eps):\n primitives = primitive_parse.primitives\n pixels = primitive_parse.image_segment_parse.diagram_image_segment.pixels\n pixels_dict = {'all': pixels}\n for key, primitive in primitives.iteritems():\n if isinstance(primitive, instantiators['line']):\n eps = line_eps\n curr_pixels = _get_pixels_near_line(pixels, primitive, eps)\n pixels_dict[key] = curr_pixels\n\n \"\"\"\n image = cv2.cvtColor(primitive_parse.image_segment_parse.diagram_image_segment.segmented_image, cv2.COLOR_GRAY2BGR)\n draw_line(image, primitive)\n display_image(image)\n for pixel in curr_pixels:\n draw_point(image, pixel)\n display_image(image)\n \"\"\"\n\n a_pixels = _get_pixels_near_point(pixels, primitive.a, eps)\n b_pixels = _get_pixels_near_point(pixels, primitive.b, eps)\n pixels_dict[primitive.a] = a_pixels\n pixels_dict[primitive.b] = b_pixels\n\n elif isinstance(primitive, instantiators['circle']):\n eps = circle_eps\n curr_pixels = set(pixel for pixel in pixels if distance_between_circle_and_point(primitive, pixel) < eps)\n pixels_dict[key] = curr_pixels\n return pixels_dict\n\n\ndef _get_pixels_near_point(pixels, point, eps):\n return set(pixel for pixel in pixels if distance_between_points_squared(pixel, point) <= eps**2)\n\n\ndef _evaluate_reward(partial_primitives, pixels_dict):\n x = [_coverage(partial_primitives, pixels_dict),\n _pixel_num(partial_primitives, pixels_dict),\n _length_sum(partial_primitives),\n _coherence(partial_primitives),\n _end_pixel_num(partial_primitives, pixels_dict),\n ]\n w = [1, -0.1, -0.7, 00, 0.1]\n return np.dot(x, w)\n\n\ndef _coverage(partial_primitives, pixels_dict):\n if len(partial_primitives) == 0:\n return 0\n coverage = len(set.union(*[pixels_dict[key] for key in partial_primitives]))\n return coverage\n\n\ndef _pixel_num(partial_primitives, pixels_dict):\n if len(partial_primitives) == 0:\n return 0\n num = sum(len(pixels_dict[key]) for key in partial_primitives)\n return num\n\ndef _end_pixel_num(partial_primitives, pixels_dict):\n lines = _get_lines(partial_primitives)\n if len(lines) == 0:\n return 0\n coverage = set.union(*[pixels_dict[primitive.a] for primitive in lines])\n coverage2 = set.union(*[pixels_dict[primitive.b] for primitive in lines])\n return len(set.union(coverage, coverage2))\n\n\n\ndef _get_pixels_near_line(pixels, line, eps):\n \"\"\"\n This can be replaced with shorter, more inefficient code.\n Written to boost up the speed.\n :param pixels:\n :param line:\n :param eps:\n :return:\n \"\"\"\n #return set(pixel for pixel in pixels if distance_between_line_and_point(line, pixel) <= eps)\n\n p = midpoint(line.a, line.b)\n u = line_unit_vector(line)\n n = line_normal_vector(line)\n half_length = line_length(line)/2.0\n eps_squared = eps**2\n\n near_pixels = set()\n for point in pixels:\n vector = point.x - p.x, point.y - p.y\n perpendicular_distance = abs(np.dot(vector, n))\n if perpendicular_distance > eps:\n continue\n parallel_distance = abs(np.dot(vector, u))\n if parallel_distance <= half_length:\n near_pixels.add(point)\n else:\n if distance_between_points_squared(point, line.a) <= eps_squared or \\\n distance_between_points_squared(point, line.b) <= eps_squared:\n near_pixels.add(point)\n return near_pixels\n\n\ndef _length_sum(partial_primitives):\n \"\"\"\n Computes the sum of squareroot of sum of lengths.\n This way, longer lines / bigger circles are preferred.\n\n :param partial_primitives:\n :return:\n \"\"\"\n if len(partial_primitives) == 0:\n return 0\n total = 0\n for primitive in partial_primitives.values():\n if isinstance(primitive, instantiators['circle']):\n total += circumference(primitive)\n elif isinstance(primitive, instantiators['line']):\n pass\n else:\n raise Exception()\n return total\n\n\ndef _coherence(partial_primitives):\n scores = []\n for idx, primitive in partial_primitives.iteritems():\n if isinstance(primitive, instantiators['line']):\n score = _line_coherence(partial_primitives, idx)\n elif isinstance(primitive, instantiators['circle']):\n score = _circle_coherence(partial_primitives, idx)\n scores.append(score)\n return np.mean(scores)\n\n\ndef _line_coherence(partial_primitives, curr_idx):\n if len(partial_primitives) == 0:\n return 0\n line = partial_primitives[curr_idx]\n distances0 = [_distance_from_point(line.a, primitive) for primitive in partial_primitives.values()]\n distances1 = [_distance_from_point(line.b, primitive) for primitive in partial_primitives.values()]\n return _distance_score(np.mean([min(distances0), min(distances1)]))\n\n\ndef _circle_coherence(partial_primitives, curr_idx):\n if len(partial_primitives) == 0:\n return 0\n circle = partial_primitives[curr_idx]\n distances = [_distance_from_point(circle.center, primitive) for primitive in partial_primitives.values()]\n return _distance_score(min(distances))\n\n\ndef _distance_from_point(point, primitive):\n if isinstance(primitive, instantiators['line']):\n return distance_between_line_and_point(primitive, point)\n elif isinstance(primitive, instantiators['circle']):\n return distance_between_circle_and_point(primitive, point)\n\n\ndef _distance_score(distance):\n eps = 10\n if distance < eps:\n return float(eps-distance)/eps\n else:\n return 0\n\n\ndef _get_lines(partial_primitives):\n return [p for p in partial_primitives.values() if isinstance(p, instantiators['line'])]" ]
[ [ "numpy.dot", "numpy.mean" ] ]
focusunsink/study_python
[ "322326642db54df8725793d70a95d21ac40b6507" ]
[ "np/reference/ch9code/animation.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nN = 10\nx = np.random.rand(N)\ny = np.random.rand(N)\nz = np.random.rand(N)\ncircles, triangles, dots = ax.plot(x, 'ro', y, 'g^', z, 'b.')\nax.set_ylim(0, 1)\nplt.axis('off')\n\ndef update(data):\n circles.set_ydata(data[0])\n triangles.set_ydata(data[1])\n return circles, triangles\n\ndef generate():\n while True: yield np.random.rand(2, N)\n\nanim = animation.FuncAnimation(fig, update, generate, interval=150)\nplt.show()\n" ]
[ [ "matplotlib.pyplot.figure", "matplotlib.pyplot.axis", "matplotlib.pyplot.show", "numpy.random.rand", "matplotlib.animation.FuncAnimation" ] ]
BreastGAN/experiment2
[ "2a1d15c1f479bbd6ca58af4e3b1379bf34b89f51" ]
[ "models/breast_cycle_gan/data_provider.py" ]
[ "# Copyright 2018 Lukas Jendele and Ondrej Skopek.\n# Adapted from The TensorFlow Authors, under the ASL 2.0.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Contains code for loading and preprocessing image data.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nimport resources.synthetic_data as synth_data\n\n\ndef normalize_image(image, img_size):\n \"\"\"Rescale from range [0, 255] to [-1, 1].\"\"\"\n image = tf.expand_dims(image, axis=-1)\n image = tf.image.crop_to_bounding_box(image, 0, 0, img_size[0], img_size[1])\n image = tf.to_float(image) - tf.reduce_min(image)\n val = tf.reduce_max(image) / 2\n image = (image - val) / val\n image = tf.reshape(image, (img_size[0], img_size[1], 1))\n image.shape.assert_is_compatible_with([img_size[0], img_size[1], 1])\n return image\n\n\ndef undo_normalize_image(normalized_image):\n \"\"\"Convert to a numpy array that can be read by PIL.\"\"\"\n # Convert from NHWC to HWC.\n normalized_image = np.squeeze(normalized_image)\n return np.uint8(normalized_image * 127.5 + 127.5)\n\n\n# def _sample_patch(image, patch_size):\n# \"\"\"Crop image to square shape and resize it to `patch_size`.\n\n# Args:\n# image: A 3D `Tensor` of HWC format.\n# patch_size: A Python scalar. The output image size.\n\n# Returns:\n# A 3D `Tensor` of HWC format which has the shape of\n# [patch_size, patch_size, 3].\n# \"\"\"\n# image_shape = tf.shape(image)\n# height, width = image_shape[0], image_shape[1]\n# target_size = tf.minimum(height, width)\n# image = tf.image.resize_image_with_crop_or_pad(image, target_size,\n# target_size)\n# # tf.image.resize_area only accepts 4D tensor, so expand dims first.\n# image = tf.expand_dims(image, axis=0)\n# image = tf.image.resize_images(image, [patch_size, patch_size])\n# image = tf.squeeze(image, axis=0)\n# # Force image num_channels = 3\n# image = tf.tile(image, [1, 1, tf.maximum(1, 4 - tf.shape(image)[2])])\n# image = tf.slice(image, [0, 0, 0], [patch_size, patch_size, 1])\n# return image\n\n\ndef _provide_custom_dataset(image_file_pattern, batch_size, shuffle=True, num_threads=1, img_size=256):\n \"\"\"Provides batches of custom image data.\n\n Args:\n image_file_pattern: A string of glob pattern of image files.\n batch_size: The number of images in each batch.\n shuffle: Whether to shuffle the read images. Defaults to True.\n num_threads: Number of prefetching threads. Defaults to 1.\n img_size: Size of the image. Defaults to 256.\n\n Returns:\n A float `Tensor` of shape [batch_size, img_size, img_size, 3]\n representing a batch of images.\n \"\"\"\n filename_queue = tf.train.string_input_producer(\n tf.train.match_filenames_once(image_file_pattern), shuffle=shuffle, capacity=5 * batch_size)\n image_reader = tf.WholeFileReader()\n\n _, image_bytes = image_reader.read(filename_queue)\n image = tf.image.decode_image(image_bytes, channels=1)\n image_norm = normalize_image(image, (img_size, img_size))\n\n if shuffle:\n return tf.train.shuffle_batch([image_norm],\n batch_size=batch_size,\n num_threads=num_threads,\n capacity=5 * batch_size,\n min_after_dequeue=batch_size)\n else:\n return tf.train.batch(\n [image_norm],\n batch_size=batch_size,\n num_threads=1, # no threads so it's deterministic\n capacity=5 * batch_size)\n\n\ndef provide_custom_datasets(image_file_patterns, batch_size, shuffle=True, num_threads=1, img_size=256):\n \"\"\"Provides multiple batches of custom image data.\n\n Args:\n image_file_patterns: A list of glob patterns of image files.\n batch_size: The number of images in each batch.\n shuffle: Whether to shuffle the read images. Defaults to True.\n num_threads: Number of prefetching threads. Defaults to 1.\n img_size: Size of the patch to extract from the image. Defaults to 256.\n\n Returns:\n A list of float `Tensor`s with the same size of `image_file_patterns`.\n Each of the `Tensor` in the list has a shape of\n [batch_size, img_size, img_size, 1] representing a batch of images.\n\n Raises:\n ValueError: If image_file_patterns is not a list or tuple.\n \"\"\"\n if not isinstance(image_file_patterns, (list, tuple)):\n raise ValueError('`image_file_patterns` should be either list or tuple, but was {}.'.format(\n type(image_file_patterns)))\n custom_datasets = []\n for pattern in image_file_patterns:\n custom_datasets.append(\n _provide_custom_dataset(\n pattern, batch_size=batch_size, shuffle=shuffle, num_threads=num_threads, img_size=img_size))\n return custom_datasets\n\n\ndef normalize_synth_image(image, img_size):\n \"\"\"Rescale to [-1, 1].\"\"\"\n # 2* ((res + min(res)) / max(res)) - 1\n image = tf.to_float(image)\n maxs = tf.reduce_max(image, axis=[0, 1])\n mins = tf.reduce_min(image, axis=[0, 1])\n res = (2 * (image + mins) / maxs) - 1\n res = tf.reshape(res, (img_size[0], img_size[1], 1))\n res.shape.assert_is_compatible_with([img_size[0], img_size[1], 1])\n return res\n\n\ndef provide_synth_dataset(batch_size, num_threads=1, img_size=(256, 256), max_thresh=2.5):\n img_size = list(img_size)\n yield_generator = synth_data.generate_synth(size=img_size, max_thresh=max_thresh)\n\n def generate_synth_image():\n img1, mask1, _ = next(yield_generator)\n img2, mask2, _ = next(yield_generator)\n # Expand dims\n img_size_c = img_size + [1]\n img1, mask1 = np.reshape(img1, img_size_c), np.reshape(mask1, img_size_c)\n img2, mask2 = np.reshape(img2, img_size_c), np.reshape(mask2, img_size_c)\n # Concat mask\n h = np.concatenate([img1, mask1], axis=2)\n c = np.concatenate([img2 + mask2, mask2], axis=2)\n # print(\"generated healthy shape:\", h.shape, \" generated cancer shape:\", c.shape)\n return h.astype(np.float32), c.astype(np.float32)\n\n healthy_img, cancer_img = tf.py_func(generate_synth_image, [], (tf.float32, tf.float32))\n\n img_size_c = img_size + [2]\n healthy_img = tf.reshape(healthy_img, img_size_c)\n cancer_img = tf.reshape(cancer_img, img_size_c)\n\n # No shuffling needed. Pictures are random anyway.\n healthy_dataset = tf.train.batch(\n [healthy_img],\n batch_size=batch_size,\n num_threads=1, # no threads so it's deterministic\n capacity=5 * batch_size)\n cancer_dataset = tf.train.batch(\n [cancer_img],\n batch_size=batch_size,\n num_threads=1, # no threads so it's deterministic\n capacity=5 * batch_size)\n return [healthy_dataset, cancer_dataset]\n\n\ndef parse_example(proto, img_size):\n features = {\n \"path\": tf.FixedLenFeature((), tf.string, default_value=\"\"),\n \"image\": tf.FixedLenFeature((), tf.string, default_value=\"\"),\n \"mask\": tf.FixedLenFeature((), tf.string, default_value=\"\"),\n \"width\": tf.FixedLenFeature((), tf.int64, default_value=0),\n \"height\": tf.FixedLenFeature((), tf.int64, default_value=0),\n \"label\": tf.FixedLenFeature((), tf.int64, default_value=0),\n }\n parsed_features = tf.parse_single_example(proto, features)\n\n def decode_img(img):\n img = tf.decode_raw(img, tf.float32)\n img = tf.reshape(img, img_size)\n print('final img', img.get_shape())\n return img\n\n path = parsed_features[\"path\"]\n image = decode_img(parsed_features[\"image\"])\n mask = decode_img(parsed_features[\"mask\"])\n print('image decoded', image.get_shape())\n print('mask decoded', mask.get_shape())\n imgs = [normalize_image(img, img_size) for img in [image, mask]]\n print('normalized', imgs[0].get_shape())\n concat = tf.concat(imgs, axis=-1)\n print('concat', concat.get_shape())\n return concat, image, mask, parsed_features['label'], path\n\n\ndef provide_cbis_dataset(datasets, batch_size, img_size=(256, 208), num_threads=1, max_thresh=2.5):\n\n def load_dataset(filename):\n dataset = tf.data.TFRecordDataset(\n filename, compression_type=\"GZIP\", num_parallel_reads=num_threads, buffer_size=buffer_size)\n dataset = dataset.map(lambda x: parse_example(x, img_size)[0], num_parallel_calls=num_threads)\n dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat(shuffle_buffer_size, count=None, seed=42))\n dataset = dataset.batch(batch_size)\n # dataset = dataset.prefetch(1)\n iterator = dataset.make_one_shot_iterator()\n features = iterator.get_next()\n return features\n\n buffer_size = 100\n shuffle_buffer_size = 100\n\n return [load_dataset(x) for x in datasets]\n" ]
[ [ "tensorflow.data.TFRecordDataset", "tensorflow.reduce_max", "tensorflow.reshape", "tensorflow.decode_raw", "tensorflow.train.match_filenames_once", "tensorflow.train.batch", "tensorflow.concat", "tensorflow.WholeFileReader", "numpy.reshape", "tensorflow.FixedLenFeature", "tensorflow.train.shuffle_batch", "tensorflow.reduce_min", "numpy.uint8", "tensorflow.image.crop_to_bounding_box", "tensorflow.parse_single_example", "tensorflow.to_float", "tensorflow.expand_dims", "tensorflow.image.decode_image", "tensorflow.py_func", "numpy.squeeze", "tensorflow.contrib.data.shuffle_and_repeat", "numpy.concatenate" ] ]
Leandro-Bertoluzzi/pyspice-power-electronics
[ "960494b23e36c0fac61289744a64c991d62784a2" ]
[ "thyristor/half-wave-converter-RL.py" ]
[ "#r# ============================================\n#r# Controlled half-wave rectifier with an SCR\n#r# ============================================\n\n#r# This example shows the simulation of a controlled half-wave rectifier with an SCR with an RL load\n\n######################################### IMPORT MODULES #########################################\n\nimport matplotlib.pyplot as plt\nimport numpy\nfrom scipy.fft import fft, fftfreq\n\n######################################### IMPORT UTILITIES #########################################\n\nimport sys\nsys.path.insert(1, '../utilities/')\nfrom utilities import format_output\n\n#####################################################################################################\n\nimport PySpice.Logging.Logging as Logging\nlogger = Logging.setup_logging()\n\n#####################################################################################################\n\nfrom PySpice.Probe.Plot import plot\nfrom PySpice.Spice.Library import SpiceLibrary\nfrom PySpice.Spice.Netlist import Circuit\nfrom PySpice.Unit import *\n\n############################# LIBRARIES WITH DEFINITIONS OF COMPONENTS #############################\n\nlibraries_path = '..\\libraries'\nspice_library = SpiceLibrary(libraries_path)\n\n#####################################################################################################\n# DEFINING PLOTS\n#####################################################################################################\n\nfigure1, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 10))\nfigure2, (ax3, ax4) = plt.subplots(2, 1, figsize=(20, 10))\nfigure3, (ax5, ax6) = plt.subplots(2, 1, figsize=(20, 10))\n\n####################################################################################################\n# CIRCUIT DEFINITION\n####################################################################################################\n\ncircuit = Circuit('SCR half wave rectifier')\nR = 1@u_Ω\nL = 60@u_mH\nperiods = 20 # Amount of periods of source signal to show in plot\n\n####################################### UNFILTERED OUTPUT #######################################\n\n# Input voltage\nsource = circuit.SinusoidalVoltageSource('input', 'source', circuit.gnd, amplitude=220@u_V, frequency=50@u_Hz)\n# SCR gate triggering signal\nalpha = 0.5 # trigger angle [0; 1]\ndelay_time = (source.period/2) * alpha\npulse_width = (source.period/2) * (1- alpha)\ncircuit.PulseVoltageSource('trigger', 'gate', 'output', 0@u_V, 1@u_V, delay_time=delay_time, pulse_width=pulse_width, period=source.period, rise_time=1@u_ms, fall_time=1@u_ms)\n# SCR\ncircuit.include(spice_library['EC103D1'])\ncircuit.X('scr', 'EC103D1', 'source', 'gate', 'output')\n# Flyback diode Dm\ncircuit.include(spice_library['BAV21'])\ncircuit.X('Dm', 'BAV21', circuit.gnd, 'output')\n# Series RL load\ncircuit.R('load', 'output', 'RL_middle', R)\ncircuit.L('1', 'RL_middle', circuit.gnd, L)\n\n# Show the netlist\nprint('**** Circuit netlist: ****')\nprint(circuit)\n\n####################################################################################################\n# SIMULATION\n####################################################################################################\n\nsimulator = circuit.simulator(temperature=25, nominal_temperature=25)\nanalysis = simulator.transient(step_time=source.period/50000, end_time=source.period*periods)\n\n# Formatting results\nvoltages, currents = format_output(analysis, 'transient')\nv_source = voltages['source']\nv_gate = voltages['gate']\nv_output = voltages['output']\nt = voltages['time']\ni_load = currents['l1']\n\n#Voltages\nax1.set_title('Half-Wave Rectification - Voltage')\nax1.set_xlabel('Time [s]')\nax1.set_ylabel('Voltage [V]')\nax1.grid()\nax1.plot(t, v_source)\nax1.plot(t, v_gate)\nax1.plot(t, v_output)\nax1.legend(('source', 'gate', 'output'), loc=(.05,.1))\nax1.set_ylim(float(-source.amplitude*1.1), float(source.amplitude*1.1))\n\n# Current\nmax_current = i_load.max()\nmin_current = i_load.min()\n\nax2.set_title('Half-Wave Rectification - Current')\nax2.set_xlabel('Time [s]')\nax2.set_ylabel('Current [A]')\nax2.grid()\nax2.plot(t, i_load)\nax2.legend('l1', loc=(.05,.1))\nax2.set_ylim(float(1.1 * min_current), float(1.1 * max_current))\n\n####################################################################################################\n# FREQUENCY DOMAIN\n####################################################################################################\n\n# Number of samplepoints\nN = len(i_load)\nDURATION = source.period*periods\nSAMPLE_RATE = N / DURATION\n\nyf = fft(i_load)\nxf = fftfreq(N, 1 / SAMPLE_RATE)[:N//5000]\n\nax5.set_title('Half-Wave Rectification - Without filter')\nax5.set_xlabel('Frequency [Hz]')\nax5.set_ylabel('Amplitude')\nax5.grid()\nax5.plot(xf, 2.0/N * numpy.abs(yf[0:N//5000]))\n\n####################################################################################################\n# CIRCUIT DEFINITION - FILTERED\n####################################################################################################\n\n# We add a capacitor to filter the output voltage\ncircuit.C('1', 'output', circuit.gnd, 100@u_mF)\n\n# Show the netlist\nprint('**** Circuit netlist (with filter): ****')\nprint(circuit)\n\n####################################################################################################\n# SIMULATION\n####################################################################################################\n\nsimulator = circuit.simulator(temperature=25, nominal_temperature=25)\nsimulator.save_currents = True\nanalysis = simulator.transient(step_time=source.period/1000, end_time=source.period*periods)\n\n# Formatting results\nvoltages, currents = format_output(analysis, 'transient')\nv_source = voltages['source']\nv_gate = voltages['gate']\nv_output = voltages['output']\nt = voltages['time']\ni_load = currents['l1']\n\n# Voltages\nax3.set_title('Half-Wave Rectification with filtering')\nax3.set_xlabel('Time [s]')\nax3.set_ylabel('Voltage [V]')\nax3.grid()\nax3.plot(t, v_source)\nax3.plot(t, v_gate)\nax3.plot(t, v_output)\nax3.legend(('source', 'gate', 'output'), loc=(.05,.1))\nax3.set_ylim(float(-source.amplitude*1.1), float(source.amplitude*1.1))\n\n# Current\nmax_current = i_load.max()\nmin_current = i_load.min()\n\nax4.set_title('Half-Wave Rectification with filtering - Current')\nax4.set_xlabel('Time [s]')\nax4.set_ylabel('Current [A]')\nax4.grid()\nax4.plot(t, i_load)\nax4.legend('l1', loc=(.05,.1))\nax4.set_ylim(float(1.1 * min_current), float(1.1 * max_current))\n\n####################################################################################################\n# FREQUENCY DOMAIN\n####################################################################################################\n\nN = len(i_load)\nSAMPLE_RATE = N / DURATION\nyf = fft(i_load)\nxf = fftfreq(N, 1 / SAMPLE_RATE)[:N//100]\n\nax6.set_title('Half-Wave Rectification - Filtered')\nax6.set_xlabel('Frequency [Hz]')\nax6.set_ylabel('Amplitude')\nax6.grid()\nax6.plot(xf, 2.0/N * numpy.abs(yf[0:N//100]))\n\n####################################################################################################\n\n# Adjusts the spacing between subplots\nfigure1.tight_layout(pad=3.0)\nfigure2.tight_layout(pad=3.0)\nfigure3.tight_layout(pad=3.0)\n# Show plots\nplt.show()" ]
[ [ "scipy.fft.fft", "numpy.abs", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "scipy.fft.fftfreq" ] ]
yienxu/counting-strokes-in-chinese-characters
[ "6b8d532b78ec37842c4cf028a48271c6bb735cbf" ]
[ "scripts/df_visualization.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\ndf = pd.read_csv('data/dataset.csv', encoding='utf-8')\n\n\ndef plot_df_counts(df):\n x_ticks = np.asarray(list(set(df['count'])))\n xx = np.arange(np.max(x_ticks) + 1)\n yy = np.bincount(df['count'])\n\n for x, y in zip(xx, yy):\n print(\"{}->{}\\t\".format(x, y), end='')\n\n plt.bar(xx, yy)\n plt.title('Stroke Counts of Characters')\n plt.xlabel('Number of Strokes')\n plt.ylabel('Number of Characters')\n # plt.savefig('counts.eps')\n plt.show()\n\n\nprint('numdata = {}\\n'.format(np.sum((df['count'] > 30) | (df['count'] == 1))))\n\ndf = df[(df['count'] <= 30) & (df['count'] != 1)]\nplot_df_counts(df)\nprint(df.shape)\n" ]
[ [ "numpy.sum", "numpy.bincount", "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.max", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.bar" ] ]
mhashas/intelligent-systems
[ "a108887fa5b13bbc2343423f21a94ca20093ae5a" ]
[ "bots/smt/kb.py" ]
[ "import sys\nimport numpy as np\nimport scipy.optimize as opt\n\nclass Symbol(object):\n \"\"\"\n A class representing a single unit in the boolean SAT problem. This can either refer to an atomic boolean, or a\n constraint based on integer variables\n \"\"\"\n pass\n\nclass Boolean(Symbol):\n\n def __init__(self, name):\n self.__name = name\n\n def name(self):\n return self.__name\n\n def __invert__(self):\n # type: () -> Boolean\n \"\"\"\n\n :return:\n \"\"\"\n return _NegBoolean(self)\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.name() == other.name()\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.name())\n\n def __repr__(self):\n return self.name()\n\nclass _NegBoolean(Boolean):\n\n def __init__(self, symbol):\n self.__symbol = symbol\n\n def name(self):\n return self.__symbol.name()\n\n def __invert__(self):\n return self.__symbol\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.name() == other.name()\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.name(), False)\n\n def __repr__(self):\n return '~' + self.name()\n\nclass Constraint(Symbol):\n\n def __init__(self, left, right):\n self._left = left\n self._right = right\n\n if not isinstance(self._right, Constant):\n self._left = Sum(self._left, - self._right)\n self._right = Constant(0)\n\n # Cluster the symbols on the left\n symbols = {None: 0}\n self.cluster(self._left, symbols)\n\n # create new left and right\n self._right = Constant(self._right.value() - symbols[None])\n\n nwterms = []\n for name, mult in symbols.iteritems():\n if name is not None:\n nwterms.append(Integer(name, mult))\n\n self._left = Sum(*nwterms)\n\n def cluster(self, term, symbols):\n\n if isinstance(term, Constant):\n symbols[None] += term.value()\n return\n\n if isinstance(term, Integer):\n if term.name() not in symbols:\n symbols[term.name()] = 0\n symbols[term.name()] += term.mult()\n return\n\n if isinstance(term, Sum):\n for subterm in term.terms():\n self.cluster(subterm, symbols)\n return\n\n raise ValueError('Encountered element {} of type {}. Arithmetic expressions should contain only KB objects or integers.'.format(term, term.__class__))\n\n\n def symbol(self):\n return '?'\n\n def __repr__(self):\n return '[' + str(self._left) + ' ' + self.symbol() + ' ' + str(self._right) + ']'\n\n def symbols(self):\n '''\n Returns a list of all integer symbols appearing in this constraint\n :return:\n '''\n\n return union(self._left.symbols(), self._right.symbols())\n\nclass GT(Constraint):\n def __init__(self, left, right):\n super(GT, self).__init__(left, right)\n\n def symbol(self):\n return '>'\n\n def __invert__(self):\n return LEQ(self._left, self._right)\n\n def canonical(self):\n \"\"\"\n Convert to a LEQ relation\n \"\"\"\n return LEQ(self._right, self._left - 1)\n\nclass GEQ(Constraint):\n def __init__(self, left, right):\n super(GEQ, self).__init__(left, right)\n\n def symbol(self):\n return '>='\n\n def __invert__(self):\n return LT(self._left, self._right)\n\n def canonical(self):\n \"\"\"\n Convert to a LEQ relation\n \"\"\"\n return LEQ(self._right, self._left)\n\n\nclass LT(Constraint):\n def __init__(self, left, right):\n super(LT, self).__init__(left, right)\n\n def symbol(self):\n return '<'\n\n def __invert__(self):\n return GEQ(self._left, self._right)\n\n def canonical(self):\n \"\"\"\n Convert to a LEQ relation\n \"\"\"\n return LEQ(self._left, self._right - 1)\n\n\nclass LEQ(Constraint):\n def __init__(self, left, right):\n super(LEQ, self).__init__(left, right)\n\n def symbol(self):\n return '<='\n\n def __invert__(self):\n return GT(self._left, self._right)\n\n def canonical(self):\n \"\"\"\n Convert to a LEQ relation\n \"\"\"\n return self\n\n\nclass EQ(Constraint):\n def __init__(self, left, right):\n super(EQ, self).__init__(left, right)\n\n def symbol(self):\n return '=='\n\n def canonical(self):\n \"\"\"\n The canonical for of an EQ relation is itself.\n \"\"\"\n return self\n\n# Not used, as it makes the LP problem nonconvex\n#\n# class NEQ(Constraint):\n# def __init__(self, left, right):\n# super(NEQ, self).__init__(left, right)\n#\n# def symbol(self):\n# return '!='\n#\n# def __invert__(self):\n# return EQ(self._left, self._right)\n\nclass IntSymbol:\n \"\"\"\n A symbolic expression representing an integer: either an atomic symbol like 'x', a constant\n like 15 or a compound expression like 'x + 15 - y'\n \"\"\"\n\n def __lt__(self, other):\n other = self.check(other)\n return LT(self, other)\n\n def __gt__(self, other):\n other = self.check(other)\n return GT(self, other)\n\n def __le__(self, other):\n other = self.check(other)\n return LEQ(self, other)\n\n def __ge__(self, other):\n other = self.check(other)\n return GEQ(self, other)\n\n def __eq__(self, other):\n other = self.check(other)\n return EQ(self, other)\n\n # def __ne__(self, other):\n # other = self.check(other)\n # return NEQ(self, other)\n\n def __add__(self, other):\n other = self.check(other)\n return Sum(self, other)\n __radd__ = __add__\n\n def __sub__(self, other):\n other = self.check(other)\n return Sum(self, - other)\n __rub__ = __sub__\n\n\n def check(self, other):\n if not isinstance(other, IntSymbol):\n if isinstance(other, int):\n return Constant(other)\n raise ValueError('You can only use KB objects or ints in comparisons. Encountered: {} {}'.format(other, other.__class__))\n return other\n\n\nclass Sum(IntSymbol):\n\n def __init__(self, *terms):\n self.__terms = terms\n for term in self.__terms:\n if isinstance(term, int):\n raise ValueError('Unwrapped int {}, {}'.format(term, term.__class__))\n\n self.__name = ''\n for i, term in enumerate(terms):\n self.__name += ('' if i == 0 else ' + ') + str(term)\n\n def name(self):\n return self.__name\n\n def terms(self):\n return self.__terms\n\n def allterms(self):\n return self.__terms\n\n def __neg__(self):\n neg_terms = []\n\n for term in self.__terms:\n neg_terms.append(- term)\n\n return Sum(*neg_terms)\n\n def __hash__(self):\n return hash(self.name())\n\n def __repr__(self):\n return self.__name\n\n def symbols(self):\n '''\n Returns a set of all integer symbols appearing in this constraint\n :return:\n '''\n return union(*[term.symbols() for term in self.__terms])\n\nclass Integer(IntSymbol):\n\n def __init__(self, name, mult = 1):\n \"\"\"\n\n :rtype: object\n \"\"\"\n self.__name = name\n self.__mult = mult\n\n def name(self):\n return self.__name\n\n def mult(self):\n return self.__mult\n\n def __neg__(self):\n return Integer(self.name(), - self.__mult)\n\n def __hash__(self):\n return hash(self.name())\n\n def __mul__(self, other):\n if not isinstance(other, int):\n raise ValueError('Can only multiply number symbol by int.')\n\n return Integer(self.__name, other)\n __rmul__ = __mul__\n\n def __repr__(self):\n if self.__mult == 1:\n return self.name()\n if self.__mult == -1:\n return '(-{})'.format(self.name())\n if self.__mult < 0:\n return '({}{})'.format(self.__mult, self.name())\n return '{}{}'.format(self.__mult, self.name())\n\n def allterms(self):\n '''\n Returns a flat representation of this sum (ie. all elements returned are\n Integers or Constants). May return multiple copies of the same integer if\n the sum has not been simplified.\n :return:\n '''\n result = []\n for term in self.__terms:\n result.extend(term.allterms())\n\n return result\n\n\n def symbols(self):\n return [Integer(self.__name)]\n\nclass Constant(Integer):\n \"\"\"\n An integer with a fixed value\n \"\"\"\n def __init__(self, value):\n if not isinstance(value, int):\n raise ValueError('Constant should be instantiated with an integer value')\n\n self.__value = value\n\n def name(self):\n return str(self.__value)\n\n def value(self):\n return self.__value\n\n def __neg__(self):\n return Constant(-self.__value)\n\n def __hash__(self):\n return hash(self.__value)\n\n def __repr__(self):\n return self.name()\n\n def symbols(self):\n return []\n\n def allterms(self):\n return [self]\n\nclass KB(object):\n \"\"\"\n A class representing a knowledge base.\n \"\"\"\n\n def __init__(self):\n self._symbols = []\n self._clauses = []\n self._pos_occurrences = {}\n self._neg_occurrences = {}\n\n def add_clause(self, *symbols):\n \"\"\"\n Adds a clause. A clause is a disjunction of atomic symbols or theiur negations. For instance:\n ```\n A = Symbol('A')\n B = Symbol('B')\n C = Symbol('C')\n\n kb = KB()\n kb.add_clause(A, B, ~C) # A or B or not C\n kb.add_clause(A, ~B) # A or not B\n ```\n\n :param symbols:\n :return:\n \"\"\"\n\n clause = list(symbols)\n\n # Check the types of the input\n for elem in clause:\n if not (isinstance(elem, Boolean) or isinstance(elem, Constraint)):\n raise ValueError('Only constraints or boolean values can be part of clauses. Encountered {} of type {}'.format(elem, elem.__class__))\n\n if isinstance(elem, EQ) and len(clause) != 1:\n raise ValueError(\n 'Equality constraints may only occur in unit clauses (so kb.add_clause(x == 5, y > 3) is not allowed). Encountered clause {}'.format(clause))\n\n\n index = len(self._clauses)\n self._clauses.append(clause)\n\n for symbol in symbols:\n\n raw_symbol = ~symbol if isinstance(symbol, _NegBoolean) else symbol\n\n if raw_symbol not in self._symbols:\n self._symbols.append(raw_symbol)\n\n # Map symbols to the clauses they occur in\n if raw_symbol not in self._neg_occurrences:\n self._neg_occurrences[raw_symbol] = []\n if raw_symbol not in self._pos_occurrences:\n self._pos_occurrences[raw_symbol] = []\n\n if isinstance(symbol, _NegBoolean):\n self._neg_occurrences[raw_symbol].append(index)\n else:\n self._pos_occurrences[raw_symbol].append(index)\n\n def satisfiable(self):\n \"\"\"\n :return: True if there is a way to assign values to the variables in this knowledge base with\n creating inconsistencies.\n \"\"\"\n first = next(self.models(), None)\n\n return first is not None\n\n def models(self, check_theory=True):\n \"\"\"\n Generator for the models satisfying the current knowledge base\n :return:\n \"\"\"\n fringe = [_Node(self)]\n\n while len(fringe) > 0:\n head = fringe.pop()\n\n if head.consistent():\n if head.finished():\n # the SAT problem returned a model,\n # check if the underlying theory is satisfiable\n sat_model = head.model()\n\n if (not check_theory) or is_feasible(sat_model):\n yield sat_model\n else:\n fringe.extend(head.children())\n\n def __repr__(self):\n return 'symbols: {}, clauses {}'.format(self._symbols, self._clauses)\n\nclass _Node:\n \"\"\"\n Node in the KB's search tree.\n \"\"\"\n __assignments = {}\n __clauses = []\n __kb = None\n __consistent = True\n\n def __init__(self,\n kb # type: KB\n ):\n \"\"\"\n Creates a root node for the given knowledge base\n :param kb:\n \"\"\"\n self.__kb = kb\n\n self.__clauses = list(kb._clauses)\n\n def child(self, symbol, value):\n # type: (Symbol, bool) -> _Node\n \"\"\"\n Return the node reached by setting the given symbol to the given value\n \"\"\"\n\n # Copy the node\n child = _Node(self.__kb)\n child.__assignments = dict(self.__assignments)\n child.__clauses = list(self.__clauses)\n\n # Perform unit propagation\n nw_assignments = {symbol: value}\n while len(nw_assignments) > 0:\n nw_symbol, nw_value = nw_assignments.popitem()\n\n # Move the unit clause to the assignments\n child.__assignments[nw_symbol] = nw_value\n\n # Rewrite the knowledge base with the new information\n for index in child.__kb._pos_occurrences[nw_symbol]:\n if nw_value:\n child.__clauses[index] = None # Remove the clause\n else:\n # Remove the symbol from the clause\n if child.__clauses[index] is not None: # Clause was already removed earlier\n\n clause = list(child.__clauses[index])\n clause.remove(nw_symbol)\n\n if len(clause) == 0: # Empty clauses indicates inconsistency\n child.__consistent = False\n return child\n\n if len(clause) == 1: # New unit clause created\n s = clause[0]\n if isinstance(s, _NegBoolean):\n nw_assignments[~ s] = False\n else:\n nw_assignments[s] = True\n child.__clauses[index] = None\n\n child.__clauses[index] = clause\n\n for index in self.__kb._neg_occurrences[nw_symbol]:\n if nw_value:\n # Remove the symbol from the clause\n if child.__clauses[index] is not None: # Clause was already removed earlier\n\n clause = list(child.__clauses[index])\n clause.remove(~ nw_symbol)\n\n if len(clause) == 0: # Empty clauses indicates inconsistency\n child.__consistent = False\n return child\n\n if len(clause) == 1: # New unit clause created\n s = clause[0]\n if isinstance(s, _NegBoolean):\n nw_assignments[~ s] = False\n else:\n nw_assignments[s] = True\n child.__clauses[index] = None\n\n child.__clauses[index] = clause\n else:\n child.__clauses[index] = None # Remove the clause\n\n return child\n\n def children(self):\n if not self.consistent():\n return []\n\n next_symbol = next(self.free(), None)\n if not next_symbol:\n return []\n\n return self.child(next_symbol, True), self.child(next_symbol, False)\n\n def free(self):\n for symbol in self.__kb._symbols:\n if symbol not in self.__assignments:\n yield symbol\n\n def consistent(self):\n return self.__consistent\n\n def finished(self):\n \"\"\"\n :return: True if the current node represents a complete model, with all symbols\n assigned definite values.\n \"\"\"\n return len(self.__kb._symbols) == len(self.__assignments.keys())\n\n def model(self):\n if not self.finished():\n return None\n else:\n return self.__assignments\n\n def __repr__(self):\n return str(self.__assignments) + (' finished' if self.finished() else ' incomplete') \\\n + ' ' + (' consistent' if self.consistent() else ' inconsistent') \\\n + ', clauses:' + str(self.__clauses)\n\ndef optimize(*constraints):\n \"\"\"\n Minimizes the given set of symbols under the given linear arithmetical constraints\n :param constraint:\n :return:\n \"\"\"\n\n # Gather all symbols\n symbols = union(*[c.symbols() for c in constraints])\n symbols = [s.name() for s in symbols]\n n = len(symbols)\n\n # Canonicalize the constraints, and sort by equalities ad inequalities\n equalities = []\n inequalities = []\n\n for constraint in constraints:\n canonical = constraint.canonical()\n if isinstance(canonical, LEQ):\n inequalities.append(canonical)\n elif isinstance(canonical, EQ):\n equalities.append(canonical)\n else:\n raise ValueError('Encountered constraint that did not canonize to LEQ or EQ: {}, canonical class {}'.format(canonical, canonical.__class__))\n\n # Create matrices, add constraints\n A_ub = np.zeros((len(inequalities), len(symbols)))\n A_eq = np.zeros((len(equalities), len(symbols)))\n\n b_ub = np.zeros((len(inequalities)))\n b_eq = np.zeros((len(equalities)))\n\n c = np.ones((len(symbols)))\n\n for i, constraint in enumerate(inequalities):\n b_ub[i] = constraint._right.value()\n\n for term in constraint._left.allterms():\n if not isinstance(term, Constant):\n name = term.name()\n mult = term.mult()\n j = symbols.index(name)\n\n A_ub[i, j] += mult\n else:\n raise ValueError('Unexpected state: the left part of a constraint should not contain constants.')\n\n for i, constraint in enumerate(equalities):\n b_eq[i] = constraint._right.value()\n\n for term in constraint._left.allterms():\n if not isinstance(term, Constant):\n symbol = term.name()\n mult = term.mult()\n j = symbols.index(symbol)\n\n A_eq[i, j] += mult\n else:\n raise ValueError(\n 'Unexpected state: the left part of a constraint should not contain constants.')\n\n result = opt.linprog(c, A_ub, b_ub, A_eq, b_eq, bounds = [(None, None)] * n)\n\n return result\n\n\ndef is_feasible(model):\n\n constraints = []\n for symbol, value in model.iteritems():\n if isinstance(symbol, Constraint):\n if value:\n constraints.append(symbol)\n else:\n if isinstance(symbol, EQ):\n raise ValueError('Something went wrong. The SAT solver should not assign False to EQ constraints. Encountered model {}.'.format(model))\n constraints.append(~ symbol)\n if len(constraints) == 0:\n return True\n\n return optimize(*constraints).status != 2\n\ndef union(*lists):\n '''\n We can't store the Integer objects in sets, because we overwrote __eq__. So we'll store them\n in lists instead, and do unions this way.\n :param lists: Lists cotaining integers and constants\n :return:\n '''\n result = []\n seen = set()\n\n for list in lists:\n for symbol in list:\n if symbol.name() not in seen:\n seen.add(symbol.name())\n result.append(symbol)\n\n return result\n\n" ]
[ [ "scipy.optimize.linprog" ] ]
colesbury/fairo
[ "9e50a3aa7369c68c80e84d80abd5fcdee8a9277a" ]
[ "polymetis/tests/scripts/5_multithreaded.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\nimport time\nimport threading\n\nimport torch\n\nfrom polymetis import RobotInterface\nfrom utils import check_episode_log\n\n\nsuccess = []\nexceptions = []\n\n\ndef connect_and_send_policy():\n try:\n # Initialize robot interface\n robot = RobotInterface(\n ip_address=\"localhost\",\n )\n hz = robot.metadata.hz\n robot.go_home()\n time.sleep(0.5)\n\n # Get joint positions\n joint_pos = robot.get_joint_positions()\n print(f\"Initial joint positions: {joint_pos}\")\n\n # Go to joint positions\n print(\"=== RobotInterface.move_to_joint_positions ===\")\n delta_joint_pos_desired = torch.Tensor([0.0, 0.0, 0.0, 0.5, 0.0, -0.5, 0.0])\n joint_pos_desired = joint_pos + delta_joint_pos_desired\n\n time_to_go = 4.0\n state_log = robot.move_to_joint_positions(\n joint_pos_desired, time_to_go=time_to_go\n )\n check_episode_log(state_log, int(time_to_go * hz))\n\n joint_pos = robot.get_joint_positions()\n assert torch.allclose(joint_pos, joint_pos_desired, atol=0.01)\n\n success.append(True)\n except Exception as e:\n exceptions.append(e)\n\n\nif __name__ == \"__main__\":\n thread = threading.Thread(target=connect_and_send_policy)\n thread.start()\n thread.join()\n\n assert success, f\"Exception: {exceptions[0]}\"\n" ]
[ [ "torch.Tensor", "torch.allclose" ] ]
bf108/elo_package
[ "ec87eba14362ff1de1c4830be2761ef23a32c6e4" ]
[ "src/elopackage/preprocess.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom ast import literal_eval\n\n\ndef convert_scores_literal(score):\n try:\n return literal_eval(score)\n except:\n return f'Error: {score}'\n\n\ndef pts_diff(row):\n try:\n winner_pts = sum(row['winning_team_scores_lst'])\n loser_pts = sum(row['losing_team_scores_lst'])\n\n return winner_pts - loser_pts\n except:\n return np.nan\n\n\ndef game_pts_diff(win, lsr):\n winner_pts = np.array(win)\n loser_pts = np.array(lsr)\n\n return winner_pts - loser_pts\n\n\ndef preprocess_tour_data(csv_file):\n p = Path(csv_file).absolute()\n df = pd.read_csv(p)\n # Convert match date to datetime\n df['match_date_dt'] = pd.to_datetime(df['match_date'], errors='coerce')\n\n # Drop matches where score not present\n df = df[(df['losing_team_scores'] != 'n/a') & (df['winning_team_scores'] != 'n/a')]\n\n # Convert scores to list of int and get pts diff - Drop any rows with missing pts diff\n df['losing_team_scores_lst'] = df['losing_team_scores'].apply(lambda x: convert_scores_literal(x))\n df['winning_team_scores_lst'] = df['winning_team_scores'].apply(lambda x: convert_scores_literal(x))\n df['pts_diff'] = df.apply(lambda x: pts_diff(x), axis=1)\n\n df.dropna(subset=['pts_diff'], inplace=True)\n\n # Get score diff for winner of each game\n gme_pts_diff = []\n for row in df.itertuples():\n gme_pts_diff.append(game_pts_diff(row.winning_team_scores_lst, row.losing_team_scores_lst))\n\n df['gme_pts_diff'] = gme_pts_diff\n\n # Add a flag for doubles games\n df['Doubles'] = ~df.losing_team_p2.isna()\n\n df.sort_values(by=['match_date_dt'], ascending=True, inplace=True)\n\n df.reset_index(drop=True, inplace=True)\n\n return df\n\n\ndef briers_score(predictions, actual):\n return sum([(ft - ot) ** 2 for ft, ot in zip(predictions, actual)]) / len(predictions)\n\n" ]
[ [ "numpy.array", "pandas.to_datetime", "pandas.read_csv" ] ]
vkola-lab/multi-task
[ "6a61db4223e1812744f13028747b07e2f840cc0b" ]
[ "lookupcsv/derived_tables/FHS/get_T1_MRI.py" ]
[ "from glob import glob\nimport pydicom\nfrom pydicom import dcmread\nimport os\nimport numpy as np\nimport nibabel as nib\n\n\ndef dicom_to_nifti(folder):\n dicoms = None\n return\n\n\ndef read_a_dicom(dicom_file):\n ds = dcmread(dicom_file)\n\n\ndef get_array(dcm_file):\n ds = dcmread(dcm_file)\n location = float(ds[0x0020, 0x1041].value)\n array = ds.pixel_array\n return (array, location)\n\n\ndef stack_dicoms(dicoms):\n pool = []\n for file in dicoms:\n pool.append(get_array(file))\n pool.sort(key=lambda x : x[1])\n return np.stack([x[0] for x in pool], axis=0)\n\n\ndef find_subfolders(root_dir):\n count = 0\n for root, dirs, files in os.walk(root_dir):\n if 't1' in root and len(files) and '.dcm' in files[0]:\n full_path = [os.path.join(root, file) for file in files]\n count += 1\n identifier = full_path[0].split('/')[5]\n print(identifier)\n try:\n volume = stack_dicoms(full_path)\n print(volume.shape)\n nifti = nib.Nifti1Image(volume, affine=np.eye(4))\n nib.save(nifti, '/data_2/FHS/nifti/{}.nii'.format(identifier))\n except ValueError:\n print('value error')\n pass\n except RuntimeError:\n print('runtime error')\n pass\n print(count)\n\n\nif __name__ == \"__main__\":\n path = '/data_2/FHS/20200819/'\n find_subfolders(path)\n" ]
[ [ "numpy.stack", "numpy.eye" ] ]
getzlab/SMM_clustering_2020
[ "0a00e11fbde38a1da82167e1c924234a79cba4a5" ]
[ "funcs/plot.py" ]
[ "import matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport os\nfrom typing import Union\nimport pandas as pd\nimport signatureanalyzer as sa\n\n# Cluster Color map\nCOLORMAP={\n 0:'#0073C2FF',\n 1:'#EFC000FF',\n 2:'#868686FF',\n 3:'#CD534CFF',\n 4:'#7AA6DCFF',\n 5:'#003C67FF',\n}\n\nCOLORMAP2={\n \"C1\":'#0073C2FF',\n \"C2\":'#EFC000FF',\n \"C3\":'#868686FF',\n \"C4\":'#CD534CFF',\n \"C5\":'#7AA6DCFF',\n \"C6\":'#003C67FF'\n}\n\n# Plotting funcs\ndef plot_scatter(df: pd.DataFrame, group: str, ax: plt.Axes, pal=None):\n \"\"\"\n Generic scatterplot.\n ------------------------------\n Inputs:\n * df: dataframe wtih columns as axes\n * group: column in dataframe that defines group colors\n * ax: matplotlib axes\n * pal: dictionary mapping groups to colors\n\n Output:\n * none\n \"\"\"\n groups = list(set(df[group]))\n\n if pal is None:\n groups_cdict = {groups[i]:x for i,x, in enumerate(sns.color_palette(\"hls\", len(set(df[group]))))}\n else:\n groups_cdict = pal\n\n _ = ax.scatter(\n df['PC1'],\n df['PC2'],\n alpha=0.8,\n c=df[group].apply(lambda x: groups_cdict[x]),\n label=None,\n s=70,\n edgecolor='black',\n linewidth=0.5\n )\n\n ax.set_xlabel(\"PC1\", fontsize=14)\n ax.set_ylabel(\"PC2\", fontsize=14)\n\n xmin, xmax = ax.get_xlim()\n ymin, ymax = ax.get_ylim()\n\n for k,v in groups_cdict.items():\n try:\n m = ax.scatter(-1e4, -1e4, alpha=.8, c=np.array(v)[np.newaxis,:], label=k)\n except:\n m = ax.scatter(-1e4, -1e4, alpha=.8, c=v, label=k)\n\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n ax.legend(loc='lower left')\n ax.set_title(group, fontsize=14, fontweight='bold', x=0.05, y=0.025, ha='left')\n\ndef plot_metric_hm(X, sample_n, k_n, title: str = None, figsize: tuple = (8,6), ax: plt.Axes = None):\n \"\"\"\n Metrics heatmap for downsampling analysis.\n ------------------------------\n Inputs:\n * X\n * sample_n\n * k_n\n * title:\n * figsize: tuple of\n * ax: plt.Axes\n\n Outputs:\n * none\n \"\"\"\n if ax is None:\n fig,ax = plt.subplots(figsize=figsize)\n\n sns.heatmap(\n pd.DataFrame(X.mean(2), index=[\"n={}\".format(str(x)) for x in sample_n], columns=[str(x) for x in k_n]),\n annot=True,\n cmap='coolwarm',\n ax=ax,\n linewidth=0.1,\n linecolor='black',\n fmt='.2f'\n )\n\n [ax.spines[sp].set_visible(True) for sp in ['top','right','left','bottom']]\n\n ax.set_yticklabels(ax.get_yticklabels(), rotation = 0, fontsize=12, fontstyle='italic')\n ax.set_xlabel(\"K Factors\", fontsize=16)\n\n if title is not None:\n ax.set_title(title, fontsize=18)\n\ndef plot_dist_per_metric(X, k, sample_n, k_n, figsize=(8,6), ax=None, title=None, s=10):\n \"\"\"\n Plot distribution per for a given K.\n \"\"\"\n if ax is None:\n fig,ax = plt.subplots(figsize=figsize)\n\n X = pd.DataFrame(X[:,k-min(k_n),:], index=[\"n={}\".format(str(x)) for x in sample_n]).T\n\n sns.stripplot(\n data=X,\n s=s,\n ax=ax,\n linewidth=.25,\n alpha=0.25,\n rasterized=True\n )\n\n sns.violinplot(\n data=X,\n ax=ax,\n linewidth=1,\n alpha=0.6,\n color='White'\n )\n\n ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right', fontsize=14)\n ax.set_title(\"K = {}\".format(k), fontsize=14)\n\ndef plot_dist_per_metric_grid(X, sample_n, k_n, y_label=None):\n \"\"\"\n Plot distribution grid for a given metric.\n \"\"\"\n\n fig,axes = plt.subplots(3,3,figsize=(12,12), sharex=True)\n\n c=0\n for i in range(3):\n for j in range(3):\n plot_dist_per_metric(X, k_n[c], sample_n, k_n, ax=axes[i,j], s=8)\n c+=1\n if j==0: axes[i,j].set_ylabel(y_label, fontsize=14)\n\n plt.tight_layout()\n\ndef plot_marker_heatmap(\n X: pd.DataFrame,\n signatures: pd.DataFrame,\n order_series: pd.Series,\n signatures_idx: str = 'max_id',\n subset_genes: Union[pd.Series,None] = None,\n diff: float = 0.5,\n max_norm: float = 0.5,\n figsize: tuple = (16,12),\n cmap: str =\"YlGnBu\",\n vmax: float = None,\n vmin: float = None,\n cohort_s: Union[pd.Series,None] = None\n ):\n \"\"\"\n Plot marker map.\n -----------------------------\n Args:\n * X: pd.DataFrame of input sample x feature matrix\n * signatures: pd.DataFrame signatures output;\n this bundles information about the weightings of each feature (ex. gene) and\n what signature they map to\n * order_series: series of samples mapping to subgroups\n index: X.index\n values: subgrouping\n * signatures_idx: string for signature grouping\n * subset_series: a pd.Series with the index as the gene name or ID that\n matches the marker matrix & has a \"Subgroup\" column for labeling\n * diff: difference of loading for called signature vs. rest\n * max_norm: strength of loading for called signature\n * figsize: size of figure\n * cmap: colormap for plot\n * display_y: whether or not to display feature names\n * vmax: colorbar max\n * vmin: colorbar min\n * cohort_s: cohort_series dataframe (added on top of plot)\n * y_hm_label: label of y-axis on heatmap (ex. Genes, Protein LFC, etc.)\n * cbar_hm_label: label of heatmap colorbar\n Returns:\n * plt.Figure\n \"\"\"\n from scipy.cluster import hierarchy\n import scipy.cluster.hierarchy as shc\n from sklearn.cluster import AgglomerativeClustering\n\n import signatureanalyzer as sa\n\n # Remove signatures with no marker genes associated\n order_series = order_series[order_series.isin(set(signatures[signatures_idx].astype(int)))]\n\n # Filter X matrix\n sample_markers = X.loc[signatures.index, order_series.sort_values().index]\n\n # Set horizontal lines\n hz_lines = np.unique(sample_markers.join(signatures).loc[:,signatures_idx].values, return_index=True)[1]\n\n fig, ax = plt.subplots(figsize=figsize)\n\n x0 = ax.get_position().x0\n x1 = ax.get_position().x1\n y0 = ax.get_position().y0\n y1 = ax.get_position().y1\n buf = y1*0.01\n\n sns.heatmap(sample_markers, ax=ax, cmap=cmap, rasterized=True, vmax=vmax, vmin=vmin, cbar=False)\n v,c = np.unique(order_series, return_counts=True)\n\n # plot horizontal lines\n _c = np.cumsum(c)\n _ci = np.roll(_c,2)\n _ci[0] = 0\n _ci[1] = 0\n ax.hlines(hz_lines, _ci, _c, rasterized=True)\n\n # plot vertical lines\n _h = list(hz_lines)\n _h.append(ax.get_ylim()[0])\n ax.vlines(np.cumsum(c)[:-1], _h[:-2], _h[2:], rasterized=True)\n ax.vlines(np.cumsum(c)[:-1], *ax.get_ylim(), alpha=0.4, rasterized=True, linewidth=1)\n\n # Set yticks\n ax.yaxis.tick_right()\n ax.set_yticks(np.arange(sample_markers.index.values.shape[0])+0.5)\n ax.set_yticklabels(sample_markers.index.values, fontsize=7.5, rasterized=True, rotation=0, va=\"center\")\n\n # --------------cluster annot-------------------\n clust_ax = fig.add_axes([x0, y1+buf, x1*.861, 2*buf])\n\n clust_ax.set_xticks([])\n clust_ax.set_yticks([])\n\n colors_conversion, meta_colormap = sa.pl.series_to_colors(order_series.loc[sample_markers.columns])\n meta_colormap_inv = dict([[v,k] for k,v in meta_colormap.items()])\n meta_colormap_inv = {(k[0],k[1],k[2]):v for k,v in meta_colormap_inv.items()}\n\n mat,cmap = sa.pl.color_list_to_matrix_and_cmap(colors_conversion)\n\n sns.heatmap(\n mat,\n cmap=cmap,\n ax=clust_ax,\n yticklabels=False,\n xticklabels=False,\n cbar=False\n )\n\n [spine.set_visible(True) for _, spine in clust_ax.spines.items()]\n\n clust_ax.yaxis.set_label_position(\"right\")\n clust_ax.set_ylabel(\"Consensus NMF\", rotation=0, va='center', ha='left')\n # --------------cluster annot-------------------\n\n\n # --------------sample annot-------------------\n if cohort_s is not None:\n cdict = {'Low': 'Green', 'Intermediate':'Yellow', 'High': 'Red'}\n order_dict = {'Green': 0, 'Yellow': 1, 'Red': 2}\n\n # Get ordering and samples\n cohort_s = cohort_s.loc[sample_markers.columns]\n\n # Create axis\n cs_ax = fig.add_axes([x0, y1+4*buf, x1*.861, 2*buf])\n cs_ax.set_xticks([])\n cs_ax.set_yticks([])\n\n cbar_cs_ax = fig.add_axes([x0, y1+7*buf, x1*.25, 2*buf])\n\n colors_conversion, meta_colormap = sa.pl.series_to_colors(cohort_s, cdict=cdict)\n meta_colormap_inv = dict([[v,k] for k,v in meta_colormap.items()])\n\n mat,cmap = sa.pl.color_list_to_matrix_and_cmap(colors_conversion, order_dict=order_dict)\n\n sns.heatmap(\n mat,\n cmap=cmap,\n ax=cs_ax,\n yticklabels=False,\n xticklabels=False,\n cbar=True,\n cbar_ax=cbar_cs_ax,\n cbar_kws={\"orientation\": \"horizontal\"}\n )\n\n cb_ticks = [float(t.get_text().replace('−','-')) for t in cbar_cs_ax.get_yticklabels()]\n\n color_value_mapping = dict([[v,k] for k,v in order_dict.items()])\n\n cbar_cs_ax.get_xaxis().set_ticks([])\n\n n_labels = len(list(color_value_mapping.keys()))\n\n # FIX THIS\n vals = [x * ((n_labels)/(n_labels+1)) + 0.5 * ((n_labels)/(n_labels+1)) for x in list(color_value_mapping.keys())]\n #cbar_cs_ax.get_xaxis().set_ticks(vals)\n\n cbar_cs_ax.get_xaxis().set_ticks([0.375, 1, 1.675])\n cbar_cs_ax.get_xaxis().set_ticklabels(list(cdict.keys()))\n cbar_cs_ax.xaxis.set_ticks_position('top')\n\n cbar_cs_ax.set_frame_on(True)\n [spine.set_visible(True) for _, spine in cs_ax.spines.items()]\n\n cs_ax.yaxis.set_label_position(\"right\")\n cs_ax.set_ylabel(\"Risk\", rotation=0, va='center', ha='left')\n\n # --------------sample annot-------------------\n\n # --------------pval barplot-------------------\n p_ax = fig.add_axes([x1+12*buf, y0, 10*buf, y1-y0])\n p_ax.set_yticks([])\n\n log10_pval_adj = -np.log10(signatures.loc[sample_markers.index]['pval_adj'])\n\n p_ax.barh(np.arange(signatures.shape[0]), log10_pval_adj[::-1], edgecolor='black', linewidth=1, color='darkblue')\n plt.margins(y=0)\n p_ax.axvline(1, linewidth=1, color='red')\n\n p_ax.spines['top'].set_visible(False)\n p_ax.spines['right'].set_visible(False)\n p_ax.set_xticks([0,5,10,15,20])\n p_ax.set_xlabel(\"$-log_{10}$ (adj. p-val)\")\n # --------------pval barplot-------------------\n\n ax.set_title('')\n ax.set_xlabel('')\n ax.set_ylabel('')\n\n [spine.set_visible(True) for _, spine in ax.spines.items()]\n\n # Set xticks\n ax.set_xticks([])\n ax.set_xticklabels([])\n ax.set_xticks(np.cumsum(c)-c/2)\n ax.set_xticklabels(v, rotation=360, fontsize=14)\n ax.tick_params(axis='x', which=u'both',length=0)\n\n return fig\n\ndef plot_consensus_matrix(\n cmatrix: pd.DataFrame,\n metric: str = 'euclidean',\n method: str = 'ward',\n n_clusters: int = 10,\n color_thresh_scale: float = 0.3,\n figsize: tuple = (8,8),\n p: int = 30,\n metas: Union[list, None] = None,\n vmax: Union[float, None] = None,\n vmin: Union[float, None] = None,\n cbar_label: str = 'ARD-NMF \\nMembership',\n cmap: Union[str, None] = None,\n plot_cluster_lines: bool = False\n ):\n \"\"\"\n Plot consensus matrix.\n -----------------------\n Args:\n * cmatrix: consensus matrix. This may be generated by calling:\n df, assign_p = consensus_cluster_ardnmf(filepath)\n * metric: distance metric\n * method: method of clustering\n * n_clusters: number of clusters for agglomerative clustering\n * color_thresh_scale: asthetic scale for coloring of dendrogram\n * figsize: figsize\n * p: parameter for dendrogram\n * meta: list of pd.Series that includes a variable of interest to plot\n to left of plot; must be categorical in nature\n Returns:\n * fig\n \"\"\"\n from matplotlib.pyplot import cm\n import matplotlib as mpl\n from scipy.cluster import hierarchy\n import scipy.cluster.hierarchy as shc\n from sklearn.cluster import AgglomerativeClustering\n # -------------\n # Heatmap\n # -------------\n fig,ax = plt.subplots(figsize=figsize)\n cbar_ax = fig.add_axes([ax.get_position().x1 + ax.get_position().x1*0.1, ax.get_position().y0, .025, .1])\n\n # Compute initial linkage to grab ordering\n d_linkage = shc.linkage(cmatrix, metric=metric, method=method)\n dres = shc.dendrogram(d_linkage, p=p, no_plot=True)\n dgram_idx = list(map(int, dres['ivl']))\n\n # Create heatmap\n if vmax is None:\n cbar_top_lim = np.max(cmatrix.values)\n else:\n cbar_top_lim = vmax\n\n if vmin is None:\n cbar_bottom_lim = 0\n else:\n cbar_bottom_lim = vmin\n\n # Create heatmap\n sns.heatmap(\n cmatrix.iloc[dgram_idx,dgram_idx].values,\n ax=ax,\n square=True,\n cbar_ax=cbar_ax,\n cbar_kws = {'ticks':[cbar_bottom_lim, cbar_top_lim]},\n rasterized=True,\n vmax=vmax,\n vmin=vmin,\n cmap=cmap\n )\n\n cbar_ax.set_ylabel(cbar_label, fontsize=10,rotation=90)\n ax.set_xticks([])\n ax.set_yticks([])\n\n x0 = ax.get_position().x0\n x1 = ax.get_position().x1\n y0 = ax.get_position().y0\n y1 = ax.get_position().y1\n\n buf = y1*0.015\n\n # -------------\n # Clustering\n # -------------\n cluster = AgglomerativeClustering(\n n_clusters=n_clusters,\n affinity=metric,\n linkage=method\n )\n\n clusters = cluster.fit_predict(cmatrix.iloc[dgram_idx,dgram_idx])\n cluster_color_list, _ = sa.pl.series_to_colors(pd.Series(clusters), cdict=COLORMAP)\n\n # -------------\n # Dendrogram\n # -------------\n cmap = cm.rainbow(np.linspace(0, 1, 10))\n hierarchy.set_link_color_palette([mpl.colors.rgb2hex(rgb[:3]) for rgb in cmap])\n\n dax = fig.add_axes([x0, y1+buf, x1-x0, 0.15])\n\n dres = shc.dendrogram(\n d_linkage,\n p=p,\n ax=dax,\n above_threshold_color=\"grey\",\n color_threshold=color_thresh_scale*max(d_linkage[:,2])\n )\n\n dax.set_xticks([])\n dax.set_yticks([])\n [dax.spines[x].set_visible(False) for x in ['top','right','bottom','left']]\n\n # -------------\n # Metadata Axes\n # -------------\n if plot_cluster_lines:\n hz_lines = np.sort(np.unique(pd.Series(clusters), return_index=True)[1])\n v,c = np.unique(clusters, return_counts=True)\n\n _c = hz_lines\n _c = np.roll(hz_lines, 1)\n _c[0] = 0\n _c[1] = 0\n\n _ci = hz_lines[1:]\n _ci = np.append(_ci, clusters.shape[0])\n\n for idx, hz in enumerate(hz_lines):\n ax.hlines(hz, _c[idx], _ci[idx], rasterized=True)\n ax.vlines(hz, _c[idx], _ci[idx], rasterized=True)\n\n # Add axes\n # Plots agglomerative clustering results\n if metas is None:\n lax = fig.add_axes([x0-3*buf, y0, 2*buf, y1-y0])\n mat, cmap = sa.pl.color_list_to_matrix_and_cmap(cluster_color_list)\n sns.heatmap(mat.T, cmap=cmap, ax=lax, xticklabels=False, yticklabels=False, cbar=False, rasterized=True)\n\n uniq, idx, num_vals = np.unique(clusters.T, return_index=True, return_counts=True)\n y_locs = idx + num_vals / 2\n\n for idx,u in enumerate(uniq):\n lax.text(x0-50*buf, y_locs[idx], u, ha='center')\n\n for idx,u in enumerate(uniq):\n ax.text(\n mat.shape[1]+0.01*mat.shape[1],\n y_locs[idx],\n \"n={}\".format(num_vals[idx]),\n ha='left',\n fontsize=14\n )\n\n for _, spine in lax.spines.items():\n spine.set_visible(True)\n\n lax.set_xlabel(\"Consensus\", rotation=90)\n\n else:\n for idx,meta in enumerate(metas):\n new_ax = [x0-(idx+3)*buf-(idx*2)*buf, y0, 2*buf, y1-y0]\n lax = fig.add_axes(new_ax)\n\n if isinstance(meta, str) and meta=='aggr':\n mat, cmap = sa.pl.color_list_to_matrix_and_cmap(cluster_color_list)\n sns.heatmap(mat.T, cmap=cmap, ax=lax, xticklabels=False, yticklabels=False, cbar=False, rasterized=True)\n\n uniq, idx, num_vals = np.unique(clusters.T, return_index=True, return_counts=True)\n y_locs = idx + num_vals / 2\n\n for idx,u in enumerate(uniq):\n lax.text(0.5, y_locs[idx], \"C{}\".format(u+1), ha='center', color='white')\n\n for idx,u in enumerate(uniq):\n ax.text(\n mat.shape[1]+0.01*mat.shape[1],\n y_locs[idx],\n \"n={}\".format(num_vals[idx]),\n ha='left',\n fontsize=14\n )\n\n #lax.set_xlabel(\"Consensus\", rotation=90)\n\n else:\n meta = meta.loc[cmatrix.index[dgram_idx]].fillna(0).astype(int)\n cdict={1:'purple',0:'white'}\n\n cluster_color_list, _ = sa.pl.series_to_colors(meta, cdict=cdict)\n mat,cmap = sa.pl.color_list_to_matrix_and_cmap(cluster_color_list)\n sns.heatmap(mat.T, cmap=cmap, ax=lax, yticklabels=False, xticklabels=False, cbar=False)\n lax.set_xlabel(meta.name, rotation=90)\n\n for _, spine in lax.spines.items():\n spine.set_visible(True)\n\n rs = pd.DataFrame(clusters, index=cmatrix.index[dgram_idx]).rename(columns={0:'clusters'})\n\n for _, spine in ax.spines.items():\n spine.set_visible(True)\n\n ax.set_xlabel(\"Samples\", fontsize=14)\n\n return fig, rs\n\ndef plot_marker_heatmap_fig1(\n X: pd.DataFrame,\n signatures: pd.DataFrame,\n order_series: pd.Series,\n signatures_idx: str = 'max_id',\n figsize: tuple = (16,13),\n vmax: float = None,\n vmin: float = None,\n metas: Union[pd.Series,None] = None,\n order_x: Union[pd.Series,None] = None,\n ):\n \"\"\"\n Plot marker map.\n -----------------------------\n Args:\n * X: pd.DataFrame of input sample x feature matrix\n * signatures: pd.DataFrame signatures output;\n this bundles information about the weightings of each feature (ex. gene) and\n what signature they map to\n * order_series: series of samples mapping to subgroups\n index: X.index\n values: subgrouping\n * signatures_idx: string for signature grouping\n * subset_series: a pd.Series with the index as the gene name or ID that\n matches the marker matrix & has a \"Subgroup\" column for labeling\n * diff: difference of loading for called signature vs. rest\n * max_norm: strength of loading for called signature\n * figsize: size of figure\n * cmap: colormap for plot\n * display_y: whether or not to display feature names\n * vmax: colorbar max\n * vmin: colorbar min\n * cohort_s: cohort_series dataframe (added on top of plot)\n * y_hm_label: label of y-axis on heatmap (ex. Genes, Protein LFC, etc.)\n * cbar_hm_label: label of heatmap colorbar\n Returns:\n * plt.Figure\n \"\"\"\n from matplotlib.colors import ListedColormap\n from scipy.cluster import hierarchy\n import scipy.cluster.hierarchy as shc\n from sklearn.cluster import AgglomerativeClustering\n\n cmap = ListedColormap(['white','darkblue'])\n\n # Remove signatures with no marker genes associated\n order_series = order_series[order_series.isin(set(signatures[signatures_idx]))]\n\n # Filter X matrix\n if order_x is None:\n order_series = order_series.sort_values()\n else:\n order_series = order_series.loc[order_x]\n\n sample_markers = X.loc[signatures.index, order_series.sort_values().index]\n\n # Set horizontal lines\n hz_lines = np.unique(sample_markers.join(signatures).loc[:,signatures_idx].values, return_index=True)[1]\n\n # Create figure\n fig, ax = plt.subplots(figsize=figsize)\n\n x0 = ax.get_position().x0\n x1 = ax.get_position().x1\n y0 = ax.get_position().y0\n y1 = ax.get_position().y1\n buf = y1*0.01\n\n sns.heatmap(sample_markers, ax=ax, cmap=cmap, rasterized=True, vmax=vmax, vmin=vmin, cbar=False)\n v,c = np.unique(order_series, return_counts=True)\n\n # plot horizontal lines\n _c = np.cumsum(c)\n _ci = np.roll(_c,2)\n _ci[0] = 0\n _ci[1] = 0\n ax.hlines(hz_lines, _ci, _c, rasterized=True, color='k')\n\n # plot vertical lines\n _h = list(hz_lines)\n _h.append(ax.get_ylim()[0])\n ax.vlines(np.cumsum(c)[:-1], _h[:-2], _h[2:], rasterized=True , color='k')\n ax.vlines(np.cumsum(c)[:-1], *ax.get_ylim(), alpha=0.8, rasterized=True, linewidth=1 , color='lightgrey')\n\n # Set yticks\n ax.yaxis.tick_right()\n ax.set_yticks(np.arange(sample_markers.index.values.shape[0])+0.5)\n ax.set_yticklabels(sample_markers.index.values, fontsize=7.5, rasterized=True, rotation=0, va=\"center\")\n\n # --------------cluster annot-------------------\n for idx,meta in enumerate(metas):\n if meta.unique().shape[0]==2 and meta.dtype=='int64':\n meta = meta.astype(bool)\n cdict={True:'purple',False:'white'}\n elif meta.name =='Consensus':\n cdict=COLORMAP2\n else:\n cdict=None\n\n new_ax = [x0, y1+buf*(idx*3+1), x1*.861, 2*buf]\n clust_ax = fig.add_axes(new_ax)\n\n clust_ax.set_xticks([])\n clust_ax.set_yticks([])\n\n colors_conversion, meta_colormap = sa.pl.series_to_colors(meta.loc[sample_markers.columns],cdict=cdict)\n meta_colormap_inv = dict([[v,k] for k,v in meta_colormap.items()])\n meta_colormap_inv = {(k[0],k[1],k[2]):v for k,v in meta_colormap_inv.items()}\n\n mat,cmap = sa.pl.color_list_to_matrix_and_cmap(colors_conversion)\n\n sns.heatmap(\n mat,\n cmap=cmap,\n ax=clust_ax,\n yticklabels=False,\n xticklabels=False,\n cbar=False\n )\n\n [spine.set_visible(True) for _, spine in clust_ax.spines.items()]\n\n clust_ax.yaxis.set_label_position(\"right\")\n clust_ax.set_ylabel(meta.name, rotation=0, va='center', ha='left')\n # --------------cluster annot-------------------\n\n # --------------pval barplot-------------------\n p_ax = fig.add_axes([x1+12*buf, y0, 10*buf, y1-y0])\n p_ax.set_yticks([])\n\n log10_pval_adj = -np.log10(signatures.loc[sample_markers.index]['pval_adj'])\n\n p_ax.barh(np.arange(signatures.shape[0]), log10_pval_adj[::-1], edgecolor='black', linewidth=1, color='purple')\n plt.margins(y=0)\n p_ax.axvline(1, linewidth=1, color='red')\n\n p_ax.spines['top'].set_visible(False)\n p_ax.spines['right'].set_visible(False)\n p_ax.set_xticks([0,5,10,15,20])\n p_ax.set_xlabel(\"$-log_{10}$ (adj. p-val)\")\n # --------------pval barplot-------------------\n\n ax.set_title('')\n ax.set_xlabel('')\n ax.set_ylabel('')\n\n [spine.set_visible(True) for _, spine in ax.spines.items()]\n\n # Set xticks\n ax.set_xticks([])\n ax.set_xticklabels([])\n ax.set_xticks(np.cumsum(c)-c/2)\n v = [\"{}\\n(n={})\".format(x,y) for x,y in zip(*np.unique(order_series, return_counts=True))]\n ax.set_xticklabels(v, rotation=360, fontsize=12)\n ax.tick_params(axis='x', which=u'both',length=0)\n\n return fig\n\ndef plot_rnaseqc_metrics_grid(metrics: pd.DataFrame, median_exon_cv_cutoff: float, figsize: tuple = (9,9)):\n \"\"\"\n Plot RNASeQC Metrics grid.\n \"\"\"\n def _format_ax(ax):\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n for axis in ['bottom','left',]:\n ax.spines[axis].set_linewidth(1)\n\n # Plot figure\n fig,axes = plt.subplots(2, 2, figsize=figsize, sharey=True)\n cax = fig.add_axes([0.15, 0.6, 0.1, 0.01])\n\n im = axes[0,0].scatter(\n metrics[\"Duplicate Rate of Mapped\"],\n metrics['Genes Detected'],\n s=80,\n alpha=0.8,\n c=np.log(metrics['Unique Mapping, Vendor QC Passed Reads']),\n edgecolor='black',\n linewidth=0.4,\n cmap='coolwarm'\n )\n\n fig.colorbar(im, cax=cax, orientation='horizontal')\n cax.set_title(\"log Unique Mapping\", fontsize=8)\n\n axes[0,0].set_ylabel('Genes Detected',fontsize=16)\n\n _format_ax(axes[0,0])\n\n im = axes[0,1].scatter(\n metrics[\"Median Exon CV\"],\n metrics['Genes Detected'],\n s=80,\n alpha=0.8,\n c=np.log(metrics['Unique Mapping, Vendor QC Passed Reads']),\n edgecolor='black',\n linewidth=0.4,\n cmap='coolwarm'\n )\n _format_ax(axes[0,1])\n\n axes[1,0].set_xlabel('Duplicate Rate',fontsize=16)\n axes[1,1].set_xlabel('Median Exon CV',fontsize=16)\n\n im = axes[1,0].scatter(\n metrics[\"Duplicate Rate of Mapped\"],\n metrics['Genes Detected'],\n s=80,\n alpha=0.8,\n c=metrics['filter'].apply(lambda x: 'lightgrey' if x else 'red'),\n edgecolor='black',\n linewidth=0.4,\n cmap='coolwarm'\n )\n\n axes[1,0].set_ylabel('Genes Detected',fontsize=16)\n\n _format_ax(axes[1,0])\n\n im = axes[1,1].scatter(\n metrics[\"Median Exon CV\"],\n metrics['Genes Detected'],\n s=80,\n alpha=0.8,\n c=metrics['filter'].apply(lambda x: 'lightgrey' if x else 'red'),\n edgecolor='black',\n linewidth=0.4,\n cmap='coolwarm'\n )\n _format_ax(axes[1,1])\n\n axes[1,0].set_xlim(*axes[1,0].get_xlim())\n axes[1,0].set_ylim(*axes[1,0].get_ylim())\n\n axes[1,0].scatter(-1,0,c='red',label='Filter')\n axes[1,0].scatter(-1,0,c='lightgrey',label='Keep')\n axes[1,0].legend(loc='lower left')\n\n axes[1,1].axvspan(.8, axes[1,1].get_xlim()[1], zorder=0, alpha=0.1, color='lightgrey')\n axes[0,1].axvspan(.8, axes[1,1].get_xlim()[1], zorder=0, alpha=0.1, color='lightgrey')\n\n plt.tight_layout()\n" ]
[ [ "matplotlib.colors.rgb2hex", "pandas.Series", "matplotlib.pyplot.tight_layout", "numpy.log", "matplotlib.pyplot.margins", "scipy.cluster.hierarchy.dendrogram", "numpy.append", "scipy.cluster.hierarchy.linkage", "numpy.log10", "numpy.linspace", "numpy.unique", "matplotlib.pyplot.subplots", "numpy.arange", "numpy.max", "numpy.roll", "numpy.cumsum", "matplotlib.colors.ListedColormap", "pandas.DataFrame", "numpy.array", "sklearn.cluster.AgglomerativeClustering" ] ]
TeeKay53/Dialogue-systems-for-language-learning
[ "28e226a579b8f22bebf5ec133985d7d86aef6606" ]
[ "chatbot/models/hier_model.py" ]
[ "\"\"\"\nA dialogue system meant to be used for language learning.\n\nThis is based on Google Neural Machine Tranlation model\nhttps://github.com/tensorflow/nmt\nwhich is based on Thang Luong's thesis on\nNeural Machine Translation: https://github.com/lmthang/thesis\n\nAnd on the paper Building End-To-End Dialogue Systems\nUsing Generative Hierarchical Neural Network Models:\nhttps://arxiv.org/pdf/1507.04808.pdf\n\nCreated by Tudor Paraschivescu for the Cambridge UROP project\n\"Dialogue systems for language learning\"\n\nThe hierarchical model with dynamic RNN support.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom chatbot.models.base_model import BaseModel\n\nimport utils.misc_utils as utils\nfrom chatbot.models import model_helper\n\nutils.check_tensorflow_version(version=\"1.3.0\")\n\n\nclass HierarchicalModel(BaseModel):\n \"\"\"\n Sequence-to-sequence hierarchical model.\n\n This class implements a multi-layer recurrent neural network as encoder,\n a multi-layer recurrent neural network as a context encoder\n and a multi-layer recurrent neural network decoder.\n \"\"\"\n\n def _build_encoder(self, hparams):\n \"\"\"Build an encoder\"\"\"\n encoder_num_layers = hparams.num_layers\n encoder_num_residual_layers = hparams.num_residual_layers\n\n context_num_layers = hparams.context_num_layers\n context_num_residual_layers = hparams.context_num_residual_layers\n\n iterator = self.iterator\n sources = iterator.source # shape=[batch_size, dialogue_len src_max_len]\n sources = tf.transpose(sources, perm=[1, 0, 2]) # shape=[dialogue_len, batch_size, src_max_len]\n\n sequence_lengths = tf.transpose(iterator.source_sequence_length) # shape=[dialogue_len, batch_size]\n\n with tf.variable_scope(\"encoder\") as encoder_scope:\n dtype = encoder_scope.dtype\n if self.verbose:\n utils.print_out(\" Building encoder cell: num_layers = %d, num_residual_layers=%d\" %\n (encoder_num_layers, encoder_num_residual_layers))\n # Build the encoder cell. Decided to leave the default base gpu\n encoder_cell = self._build_encoder_cell(hparams,\n encoder_num_layers,\n encoder_num_residual_layers)\n if self.verbose:\n utils.print_out(\" Building context cell: num_layers = %d, num_residual_layers=%d\" %\n (encoder_num_layers, encoder_num_residual_layers))\n context_cell = self._build_encoder_cell(hparams,\n context_num_layers,\n context_num_residual_layers)\n max_dialogue_length = tf.shape(sources)[0]\n # Initialize the state using the current batch size\n current_batch_size = tf.shape(sources)[1]\n initial_state = context_cell.zero_state(current_batch_size, dtype=dtype)\n\n # Define the body and the condition for the while loop\n def body(context_state, counter):\n source = tf.gather(sources, counter)\n\n if self.time_major:\n source = tf.transpose(source) # [max_time, batch_size]\n\n seq_len = tf.gather(sequence_lengths, counter, name='get_current_source')\n encoder_emb_inp = tf.nn.embedding_lookup(\n self.embeddings, source)\n # Create RNN. Performs fully dynamic unrolling of inputs\n encoder_outputs, encoder_state = tf.nn.dynamic_rnn(\n cell=encoder_cell,\n inputs=encoder_emb_inp,\n sequence_length=seq_len,\n dtype=dtype,\n time_major=self.time_major,\n )\n # The encoder_state is a tuple. (cell state, memory state), aka (c, h).\n # Use the cell state as input.\n context_input = encoder_state[0]\n\n output, next_state = context_cell(inputs=context_input, state=context_state, scope=\"context\")\n\n return [next_state, tf.add(counter, 1, name='increment_counter')]\n\n def condition(context_state, counter):\n return tf.less(counter, max_dialogue_length, name='condition')\n\n # Initialize the counter\n counter = tf.Variable(0, name='counter', trainable=False, dtype=tf.int32)\n\n # Create the while loop, filling the encoder_states list\n final_context_state, _ = tf.while_loop(cond=condition, body=body,\n loop_vars=[initial_state, counter])\n\n return final_context_state\n\n def _build_decoder_cell(self, hparams, encoder_state):\n \"\"\"Build an RNN cell that can be used by decoder.\"\"\"\n # We only make use of encoder_outputs in attention-based models\n\n\n num_layers = hparams.num_layers\n num_residual_layers = hparams.num_residual_layers\n decoder_cell = model_helper.create_rnn_cell(\n unit_type=hparams.unit_type,\n num_units=hparams.num_units,\n num_layers=num_layers,\n num_residual_layers=num_residual_layers,\n forget_bias=hparams.forget_bias,\n dropout=hparams.dropout,\n num_gpus=hparams.num_gpus,\n mode=self.mode,\n verbose=self.verbose\n )\n\n # For beam search, we need to replicate encoder infos beam_width times\n if self.mode == tf.contrib.learn.ModeKeys.INFER and hparams.beam_width > 0:\n # Tile them along the batch_size. [batch_size, etc.] to [batch_size * multiplier, etc]\n # by copying each t[i], i in [0, batch_size - 1] 'multiplier' times\n decoder_initial_state = tf.contrib.seq2seq.tile_batch(\n encoder_state, multiplier=hparams.beam_width\n )\n else:\n decoder_initial_state = encoder_state\n\n return decoder_cell, decoder_initial_state\n" ]
[ [ "tensorflow.gather", "tensorflow.shape", "tensorflow.variable_scope", "tensorflow.add", "tensorflow.nn.dynamic_rnn", "tensorflow.while_loop", "tensorflow.less", "tensorflow.Variable", "tensorflow.contrib.seq2seq.tile_batch", "tensorflow.transpose", "tensorflow.nn.embedding_lookup" ] ]
Drkun/ZSTCI
[ "93543ee843dac680c33e34de5d61ba048ef1f6d3" ]
[ "models/inception.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n__all__ = ['Inception3', 'inception_v3']\n\ndef inception_v3(**kwargs):\n r\"\"\"Inception v3 model architecture from\n `\"Rethinking the Inception Architecture for Computer Vision\" <http://arxiv.org/abs/1512.00567>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n # \"\"\"\n\n return Inception3(**kwargs)\n\n\nclass Inception3(nn.Module):\n\n def __init__(self, Embed_dim=512, num_classes=100, dropout=0.5, aux_logits=False, transform_input=False):\n super(Inception3, self).__init__()\n self.aux_logits = aux_logits\n self.transform_input = transform_input\n self.dropout = dropout\n self.Embed_dim = Embed_dim\n self.Conv2d_1a_3x3 = BasicConv2d(3, 32, kernel_size=3, stride=2)\n self.Conv2d_2a_3x3 = BasicConv2d(32, 32, kernel_size=3)\n self.Conv2d_2b_3x3 = BasicConv2d(32, 64, kernel_size=3, padding=1)\n self.Conv2d_3b_1x1 = BasicConv2d(64, 80, kernel_size=1)\n self.Conv2d_4a_3x3 = BasicConv2d(80, 192, kernel_size=3)\n self.Mixed_5b = InceptionA(192, pool_features=32)\n self.Mixed_5c = InceptionA(256, pool_features=64)\n self.Mixed_5d = InceptionA(288, pool_features=64)\n self.Mixed_6a = InceptionB(288)\n self.Mixed_6b = InceptionC(768, channels_7x7=128)\n self.Mixed_6c = InceptionC(768, channels_7x7=160)\n self.Mixed_6d = InceptionC(768, channels_7x7=160)\n self.Mixed_6e = InceptionC(768, channels_7x7=192)\n if aux_logits:\n self.AuxLogits = InceptionAux(768, num_classes)\n self.Mixed_7a = InceptionD(768)\n self.Mixed_7b = InceptionE(1280)\n self.Mixed_7c = InceptionE(2048)\n\n if self.Embed_dim > 0:\n self.Embed = Embedding(2048, self.Embed_dim)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n import scipy.stats as stats\n stddev = m.stddev if hasattr(m, 'stddev') else 0.001\n X = stats.truncnorm(-2, 2, scale=stddev)\n values = torch.Tensor(X.rvs(m.weight.data.numel()))\n m.weight.data.copy_(values)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n if self.transform_input:\n x = x.clone()\n x[:, 0] = x[:, 0] * (0.229 / 0.5) + (0.485 - 0.5) / 0.5\n x[:, 1] = x[:, 1] * (0.224 / 0.5) + (0.456 - 0.5) / 0.5\n x[:, 2] = x[:, 2] * (0.225 / 0.5) + (0.406 - 0.5) / 0.5\n # 299 x 299 x 3\n x = self.Conv2d_1a_3x3(x)\n # 149 x 149 x 32\n x = self.Conv2d_2a_3x3(x)\n # 147 x 147 x 32\n x = self.Conv2d_2b_3x3(x)\n # 147 x 147 x 64\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # 73 x 73 x 64\n x = self.Conv2d_3b_1x1(x)\n # 73 x 73 x 80\n x = self.Conv2d_4a_3x3(x)\n # 71 x 71 x 192\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # 35 x 35 x 192\n x = self.Mixed_5b(x)\n # 35 x 35 x 256\n x = self.Mixed_5c(x)\n # 35 x 35 x 288\n x = self.Mixed_5d(x)\n # 35 x 35 x 288\n x = self.Mixed_6a(x)\n # 17 x 17 x 768\n x = self.Mixed_6b(x)\n # 17 x 17 x 768\n x = self.Mixed_6c(x)\n # 17 x 17 x 768\n x = self.Mixed_6d(x)\n # 17 x 17 x 768\n x = self.Mixed_6e(x)\n # 17 x 17 x 768\n if self.training and self.aux_logits:\n aux = self.AuxLogits(x)\n # 17 x 17 x 768\n x = self.Mixed_7a(x)\n # 8 x 8 x 1280\n x = self.Mixed_7b(x)\n # 8 x 8 x 2048\n x = self.Mixed_7c(x)\n # 8 x 8 x 2048\n x = F.adaptive_avg_pool2d(x, output_size=1)\n # 1 x 1 x 2048\n x = F.dropout(x, training=self.training)\n # 1 x 1 x 2048\n x = x.view(x.size(0), -1)\n # 2048\n if self.Embed_dim > 0:\n x = self.Embed(x)\n return x\n\n\nclass Embedding(nn.Module):\n def __init__(self, in_dim, out_dim, dropout=None, normalized=True):\n super(Embedding, self).__init__()\n self.bn = nn.BatchNorm2d(in_dim, eps=0.001)\n self.linear = nn.Linear(in_features=in_dim, out_features=out_dim)\n self.dropout = dropout\n self.normalized = normalized\n\n def forward(self, x):\n x = self.bn(x)\n x = F.relu(x, inplace=True)\n if self.dropout is not None:\n x = nn.Dropout(p=self.dropout)(x, inplace=True)\n x = self.linear(x)\n if self.normalized:\n norm = x.norm(dim=1, p=2, keepdim=True)\n x = x.div(norm.expand_as(x))\n return x\n\n\nclass InceptionA(nn.Module):\n\n def __init__(self, in_channels, pool_features):\n super(InceptionA, self).__init__()\n self.branch1x1 = BasicConv2d(in_channels, 64, kernel_size=1)\n\n self.branch5x5_1 = BasicConv2d(in_channels, 48, kernel_size=1)\n self.branch5x5_2 = BasicConv2d(48, 64, kernel_size=5, padding=2)\n\n self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1)\n self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1)\n self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, padding=1)\n\n self.branch_pool = BasicConv2d(in_channels, pool_features, kernel_size=1)\n\n def forward(self, x):\n branch1x1 = self.branch1x1(x)\n\n branch5x5 = self.branch5x5_1(x)\n branch5x5 = self.branch5x5_2(branch5x5)\n\n branch3x3dbl = self.branch3x3dbl_1(x)\n branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)\n branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)\n\n branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)\n branch_pool = self.branch_pool(branch_pool)\n\n outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]\n return torch.cat(outputs, 1)\n\n\nclass InceptionB(nn.Module):\n\n def __init__(self, in_channels):\n super(InceptionB, self).__init__()\n self.branch3x3 = BasicConv2d(in_channels, 384, kernel_size=3, stride=2)\n\n self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1)\n self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1)\n self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, stride=2)\n\n def forward(self, x):\n branch3x3 = self.branch3x3(x)\n\n branch3x3dbl = self.branch3x3dbl_1(x)\n branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)\n branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)\n\n branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)\n\n outputs = [branch3x3, branch3x3dbl, branch_pool]\n return torch.cat(outputs, 1)\n\n\nclass InceptionC(nn.Module):\n\n def __init__(self, in_channels, channels_7x7):\n super(InceptionC, self).__init__()\n self.branch1x1 = BasicConv2d(in_channels, 192, kernel_size=1)\n\n c7 = channels_7x7\n self.branch7x7_1 = BasicConv2d(in_channels, c7, kernel_size=1)\n self.branch7x7_2 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3))\n self.branch7x7_3 = BasicConv2d(c7, 192, kernel_size=(7, 1), padding=(3, 0))\n\n self.branch7x7dbl_1 = BasicConv2d(in_channels, c7, kernel_size=1)\n self.branch7x7dbl_2 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0))\n self.branch7x7dbl_3 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3))\n self.branch7x7dbl_4 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0))\n self.branch7x7dbl_5 = BasicConv2d(c7, 192, kernel_size=(1, 7), padding=(0, 3))\n\n self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1)\n\n def forward(self, x):\n branch1x1 = self.branch1x1(x)\n\n branch7x7 = self.branch7x7_1(x)\n branch7x7 = self.branch7x7_2(branch7x7)\n branch7x7 = self.branch7x7_3(branch7x7)\n\n branch7x7dbl = self.branch7x7dbl_1(x)\n branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)\n branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)\n branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)\n branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)\n\n branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)\n branch_pool = self.branch_pool(branch_pool)\n\n outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]\n return torch.cat(outputs, 1)\n\n\nclass InceptionD(nn.Module):\n\n def __init__(self, in_channels):\n super(InceptionD, self).__init__()\n self.branch3x3_1 = BasicConv2d(in_channels, 192, kernel_size=1)\n self.branch3x3_2 = BasicConv2d(192, 320, kernel_size=3, stride=2)\n\n self.branch7x7x3_1 = BasicConv2d(in_channels, 192, kernel_size=1)\n self.branch7x7x3_2 = BasicConv2d(192, 192, kernel_size=(1, 7), padding=(0, 3))\n self.branch7x7x3_3 = BasicConv2d(192, 192, kernel_size=(7, 1), padding=(3, 0))\n self.branch7x7x3_4 = BasicConv2d(192, 192, kernel_size=3, stride=2)\n\n def forward(self, x):\n branch3x3 = self.branch3x3_1(x)\n branch3x3 = self.branch3x3_2(branch3x3)\n\n branch7x7x3 = self.branch7x7x3_1(x)\n branch7x7x3 = self.branch7x7x3_2(branch7x7x3)\n branch7x7x3 = self.branch7x7x3_3(branch7x7x3)\n branch7x7x3 = self.branch7x7x3_4(branch7x7x3)\n\n branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)\n outputs = [branch3x3, branch7x7x3, branch_pool]\n return torch.cat(outputs, 1)\n\n\nclass InceptionE(nn.Module):\n\n def __init__(self, in_channels):\n super(InceptionE, self).__init__()\n self.branch1x1 = BasicConv2d(in_channels, 320, kernel_size=1)\n\n self.branch3x3_1 = BasicConv2d(in_channels, 384, kernel_size=1)\n self.branch3x3_2a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1))\n self.branch3x3_2b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0))\n\n self.branch3x3dbl_1 = BasicConv2d(in_channels, 448, kernel_size=1)\n self.branch3x3dbl_2 = BasicConv2d(448, 384, kernel_size=3, padding=1)\n self.branch3x3dbl_3a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1))\n self.branch3x3dbl_3b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0))\n\n self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1)\n\n def forward(self, x):\n branch1x1 = self.branch1x1(x)\n\n branch3x3 = self.branch3x3_1(x)\n branch3x3 = [\n self.branch3x3_2a(branch3x3),\n self.branch3x3_2b(branch3x3),\n ]\n branch3x3 = torch.cat(branch3x3, 1)\n\n branch3x3dbl = self.branch3x3dbl_1(x)\n branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)\n branch3x3dbl = [\n self.branch3x3dbl_3a(branch3x3dbl),\n self.branch3x3dbl_3b(branch3x3dbl),\n ]\n branch3x3dbl = torch.cat(branch3x3dbl, 1)\n\n branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)\n branch_pool = self.branch_pool(branch_pool)\n\n outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]\n return torch.cat(outputs, 1)\n\n\nclass InceptionAux(nn.Module):\n\n def __init__(self, in_channels, num_classes):\n super(InceptionAux, self).__init__()\n self.conv0 = BasicConv2d(in_channels, 128, kernel_size=1)\n self.conv1 = BasicConv2d(128, 768, kernel_size=5)\n self.conv1.stddev = 0.01\n self.fc = nn.Linear(768, num_classes)\n self.fc.stddev = 0.001\n\n def forward(self, x):\n # 17 x 17 x 768\n x = F.avg_pool2d(x, kernel_size=5, stride=3)\n # 5 x 5 x 768\n x = self.conv0(x)\n # 5 x 5 x 128\n x = self.conv1(x)\n # 1 x 1 x 768\n x = x.view(x.size(0), -1)\n # 768\n x = self.fc(x)\n # 1000\n return x\n\n\nclass BasicConv2d(nn.Module):\n\n def __init__(self, in_channels, out_channels, **kwargs):\n super(BasicConv2d, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm2d(out_channels, eps=0.001)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n return F.relu(x, inplace=True)\n\n" ]
[ [ "torch.nn.BatchNorm2d", "torch.nn.Linear", "torch.nn.functional.avg_pool2d", "torch.nn.functional.dropout", "torch.nn.functional.max_pool2d", "torch.nn.functional.relu", "scipy.stats.truncnorm", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.Conv2d", "torch.cat", "torch.nn.Dropout" ] ]
ziatdinovmax/sidpy
[ "299147bfc22741b5170aa00e92b34159dfc910c5" ]
[ "sidpy/hdf/dtype_utils.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nUtilities for transforming and validating data types\n\nGiven that many of the data transformations involve copying the data, they should\nideally happen in a lazy manner to avoid memory issues.\n\nCreated on Tue Nov 3 21:14:25 2015\n\n@author: Suhas Somnath, Chris Smith\n\"\"\"\n\nfrom __future__ import division, absolute_import, unicode_literals, print_function\nimport sys\nfrom warnings import warn\nimport h5py\nimport numpy as np\nimport dask.array as da\n\n__all__ = ['flatten_complex_to_real', 'get_compound_sub_dtypes', 'flatten_compound_to_real', 'check_dtype',\n 'stack_real_to_complex', 'validate_dtype', 'is_complex_dtype',\n 'stack_real_to_compound', 'stack_real_to_target_dtype', 'flatten_to_real']\n\nfrom sidpy.hdf.hdf_utils import lazy_load_array\n\nif sys.version_info.major == 3:\n unicode = str\n\n\ndef flatten_complex_to_real(dataset, lazy=False):\n \"\"\"\n Stacks the real values followed by the imaginary values in the last dimension of the given N dimensional matrix.\n Thus a complex matrix of shape (2, 3, 5) will turn into a matrix of shape (2, 3, 10)\n\n Parameters\n ----------\n dataset : array-like or :class:`numpy.ndarray`, or :class:`h5py.Dataset`, or :class:`dask.array.core.Array`\n Dataset of complex data type\n lazy : bool, optional. Default = False\n If set to True, will use lazy Dask arrays instead of in-memory numpy arrays\n\n Returns\n -------\n retval : :class:`numpy.ndarray`, or :class:`dask.array.core.Array`\n real valued dataset\n \"\"\"\n if not isinstance(dataset, (h5py.Dataset, np.ndarray, da.core.Array)):\n raise TypeError('dataset should either be a h5py.Dataset or numpy / dask array')\n if not is_complex_dtype(dataset.dtype):\n raise TypeError(\"Expected a complex valued dataset\")\n\n if isinstance(dataset, da.core.Array):\n lazy = True\n\n xp = np\n if lazy:\n dataset = lazy_load_array(dataset)\n xp = da\n\n axis = xp.array(dataset).ndim - 1\n if axis == -1:\n return xp.hstack([xp.real(dataset), xp.imag(dataset)])\n else: # along the last axis\n return xp.concatenate([xp.real(dataset), xp.imag(dataset)], axis=axis)\n\n\ndef flatten_compound_to_real(dataset, lazy=False):\n \"\"\"\n Flattens the individual components in a structured array or compound valued hdf5 dataset along the last axis to form\n a real valued array. Thus a compound h5py.Dataset or structured numpy matrix of shape (2, 3, 5) having 3 components\n will turn into a real valued matrix of shape (2, 3, 15), assuming that all the sub-dtypes of the matrix are real\n valued. ie - this function does not handle structured dtypes having complex values\n\n\n Parameters\n ----------\n dataset : :class:`numpy.ndarray`, or :class:`h5py.Dataset`, or :class:`dask.array.core.Array`\n Numpy array that is a structured array or a :class:`h5py.Dataset` of compound dtype\n lazy : bool, optional. Default = False\n If set to True, will use lazy Dask arrays instead of in-memory numpy arrays\n\n Returns\n -------\n retval : :class:`numpy.ndarray`, or :class:`dask.array.core.Array`\n real valued dataset\n \"\"\"\n if isinstance(dataset, h5py.Dataset):\n if len(dataset.dtype) == 0:\n raise TypeError(\"Expected compound h5py dataset\")\n\n if lazy:\n xp = da\n dataset = lazy_load_array(dataset)\n else:\n xp = np\n warn('HDF5 datasets will be loaded as Dask arrays in the future. ie - kwarg lazy will default to True in future releases of sidpy')\n\n return xp.concatenate([xp.array(dataset[name]) for name in dataset.dtype.names], axis=len(dataset.shape) - 1)\n\n elif isinstance(dataset, (np.ndarray, da.core.Array)):\n if isinstance(dataset, da.core.Array):\n lazy = True\n\n xp = np\n if lazy:\n dataset = lazy_load_array(dataset)\n xp = da\n\n if len(dataset.dtype) == 0:\n raise TypeError(\"Expected structured array\")\n if dataset.ndim > 0:\n return xp.concatenate([dataset[name] for name in dataset.dtype.names], axis=dataset.ndim - 1)\n else:\n return xp.hstack([dataset[name] for name in dataset.dtype.names])\n elif isinstance(dataset, np.void):\n return np.hstack([dataset[name] for name in dataset.dtype.names])\n else:\n raise TypeError('Datatype {} not supported'.format(type(dataset)))\n\n\ndef flatten_to_real(ds_main, lazy=False):\n \"\"\"\n Flattens complex / compound / real valued arrays to real valued arrays\n\n Parameters\n ----------\n ds_main : :class:`numpy.ndarray`, or :class:`h5py.Dataset`, or :class:`dask.array.core.Array`\n Compound, complex or real valued numpy array or HDF5 dataset\n lazy : bool, optional. Default = False\n If set to True, will use lazy Dask arrays instead of in-memory numpy arrays\n\n Returns\n ----------\n ds_main : :class:`numpy.ndarray`, or :class:`dask.array.core.Array`\n Array raveled to a float data type\n \"\"\"\n if not isinstance(ds_main, (h5py.Dataset, np.ndarray, da.core.Array)):\n ds_main = np.array(ds_main)\n if is_complex_dtype(ds_main.dtype):\n return flatten_complex_to_real(ds_main, lazy=lazy)\n elif len(ds_main.dtype) > 0:\n return flatten_compound_to_real(ds_main, lazy=lazy)\n else:\n return ds_main\n\n\ndef get_compound_sub_dtypes(struct_dtype):\n \"\"\"\n Returns a dictionary of the dtypes of each of the fields in the given structured array dtype\n\n Parameters\n ----------\n struct_dtype : :class:`numpy.dtype`\n dtype of a structured array\n\n Returns\n -------\n dtypes : dict\n Dictionary whose keys are the field names and values are the corresponding dtypes\n \"\"\"\n if not isinstance(struct_dtype, np.dtype):\n raise TypeError('Provided object must be a structured array dtype')\n dtypes = dict()\n for field_name in struct_dtype.fields:\n dtypes[field_name] = struct_dtype.fields[field_name][0]\n return dtypes\n\n\ndef check_dtype(h5_dset):\n \"\"\"\n Checks the datatype of the input HDF5 dataset and provides the appropriate\n function calls to convert it to a float\n\n Parameters\n ----------\n h5_dset : :class:`h5py.Dataset`\n Dataset of interest\n\n Returns\n -------\n func : callable\n function that will convert the dataset to a float\n is_complex : bool\n is the input dataset complex?\n is_compound : bool\n is the input dataset compound?\n n_features : Unsigned int\n Unsigned integer - the length of the 2nd dimension of the data after `func` is called on it\n type_mult : Unsigned int\n multiplier that converts from the typesize of the input :class:`~numpy.dtype` to the\n typesize of the data after func is run on it\n \"\"\"\n if not isinstance(h5_dset, h5py.Dataset):\n raise TypeError('h5_dset should be a h5py.Dataset object')\n is_complex = False\n is_compound = False\n in_dtype = h5_dset.dtype\n # TODO: avoid assuming 2d shape - why does one even need n_samples!? We only care about the last dimension!\n n_features = h5_dset.shape[-1]\n if is_complex_dtype(h5_dset.dtype):\n is_complex = True\n new_dtype = np.real(h5_dset[0, 0]).dtype\n type_mult = new_dtype.itemsize * 2\n func = flatten_complex_to_real\n n_features *= 2\n elif len(h5_dset.dtype) > 0:\n \"\"\"\n Some form of structured numpy is in use\n We only support real scalars for the component types at the current time\n \"\"\"\n is_compound = True\n # TODO: Avoid hard-coding to float32\n new_dtype = np.float32\n type_mult = len(in_dtype) * new_dtype(0).itemsize\n func = flatten_compound_to_real\n n_features *= len(in_dtype)\n else:\n if h5_dset.dtype not in [np.float32, np.float64]:\n new_dtype = np.float32\n else:\n new_dtype = h5_dset.dtype.type\n\n type_mult = new_dtype(0).itemsize\n\n func = new_dtype\n\n return func, is_complex, is_compound, n_features, type_mult\n\n\ndef stack_real_to_complex(ds_real, lazy=False):\n \"\"\"\n Puts the real and imaginary sections of the provided matrix (in the last axis) together to make complex matrix\n\n Parameters\n ------------\n ds_real : :class:`numpy.ndarray`, :class:`dask.array.core.Array`, or :class:`h5py.Dataset`\n n dimensional real-valued numpy array or HDF5 dataset where data arranged as [instance, 2 x features],\n where the first half of the features are the real component and the\n second half contains the imaginary components\n lazy : bool, optional. Default = False\n If set to True, will use lazy Dask arrays instead of in-memory numpy arrays\n\n Returns\n ----------\n ds_compound : :class:`numpy.ndarray` or :class:`dask.array.core.Array`\n 2D complex array arranged as [sample, features]\n \"\"\"\n if not isinstance(ds_real, (np.ndarray, da.core.Array, h5py.Dataset)):\n if not isinstance(ds_real, (tuple, list)):\n raise TypeError(\"Expected at least an iterable like a list or tuple\")\n ds_real = np.array(ds_real)\n if len(ds_real.dtype) > 0:\n raise TypeError(\"Array cannot have a compound dtype\")\n if is_complex_dtype(ds_real.dtype):\n raise TypeError(\"Array cannot have complex dtype\")\n\n if ds_real.shape[-1] / 2 != ds_real.shape[-1] // 2:\n raise ValueError(\"Last dimension must be even sized\")\n half_point = ds_real.shape[-1] // 2\n\n if isinstance(ds_real, da.core.Array):\n lazy = True\n\n if lazy and not isinstance(ds_real, da.core.Array):\n ds_real = lazy_load_array(ds_real)\n\n return ds_real[..., :half_point] + 1j * ds_real[..., half_point:]\n\n\ndef stack_real_to_compound(ds_real, compound_type, lazy=False):\n \"\"\"\n Converts a real-valued dataset to a compound dataset (along the last axis) of the provided compound d-type\n\n Parameters\n ------------\n ds_real : :class:`numpy.ndarray`, :class:`dask.array.core.Array`, or :class:`h5py.Dataset`\n n dimensional real-valued numpy array or HDF5 dataset where data arranged as [instance, features]\n compound_type : :class:`numpy.dtype`\n Target complex data-type\n lazy : bool, optional. Default = False\n If set to True, will use lazy Dask arrays instead of in-memory numpy arrays\n\n Returns\n ----------\n ds_compound : :class:`numpy.ndarray` or :class:`dask.array.core.Array`\n N-dimensional complex-valued array arranged as [sample, features]\n \"\"\"\n if lazy or isinstance(ds_real, da.core.Array):\n raise NotImplementedError('Lazy operation not available due to absence of Dask support')\n if not isinstance(ds_real, (np.ndarray, h5py.Dataset)):\n if not isinstance(ds_real, (list, tuple)):\n raise TypeError(\"Expected at least an iterable like a list or tuple\")\n ds_real = np.array(ds_real)\n if len(ds_real.dtype) > 0:\n raise TypeError(\"Array cannot have a compound dtype\")\n elif is_complex_dtype(ds_real.dtype):\n raise TypeError(\"Array cannot have complex dtype\")\n if not isinstance(compound_type, np.dtype):\n raise TypeError('Provided object must be a structured array dtype')\n\n new_spec_length = ds_real.shape[-1] / len(compound_type)\n if new_spec_length % 1:\n raise ValueError('Provided compound type was not compatible by number of elements')\n\n new_spec_length = int(new_spec_length)\n new_shape = list(ds_real.shape) # Make mutable\n new_shape[-1] = new_spec_length\n\n xp = np\n kwargs = {}\n \"\"\"\n if isinstance(ds_real, h5py.Dataset) and not lazy:\n warn('HDF5 datasets will be loaded as Dask arrays in the future. ie - kwarg lazy will default to True in future releases of sidpy')\n if isinstance(ds_real, da.core.Array):\n lazy = True \n if lazy:\n xp = da\n ds_real = lazy_load_array(ds_real)\n kwargs = {'chunks': 'auto'}\n \"\"\"\n\n ds_compound = xp.empty(new_shape, dtype=compound_type, **kwargs)\n for name_ind, name in enumerate(compound_type.names):\n i_start = name_ind * new_spec_length\n i_end = (name_ind + 1) * new_spec_length\n ds_compound[name] = ds_real[..., i_start:i_end]\n\n return ds_compound.squeeze()\n\n\ndef stack_real_to_target_dtype(ds_real, new_dtype, lazy=False):\n \"\"\"\n Transforms real data into the target dtype\n\n Parameters\n ----------\n ds_real : :class:`numpy.ndarray`, :class:`dask.array.core.Array` or :class:`h5py.Dataset`\n n dimensional real-valued numpy array or HDF5 dataset\n new_dtype : :class:`numpy.dtype`\n Target data-type\n\n Returns\n ----------\n ret_val : :class:`numpy.ndarray` or :class:`dask.array.core.Array`\n N-dimensional array of the target data-type\n \"\"\"\n if is_complex_dtype(new_dtype):\n return stack_real_to_complex(ds_real, lazy=lazy)\n try:\n if len(new_dtype) > 0:\n return stack_real_to_compound(ds_real, new_dtype, lazy=lazy)\n except TypeError:\n return new_dtype(ds_real)\n\n # catching all other cases, such as np.dtype('<f4')\n return new_dtype.type(ds_real)\n\n\ndef validate_dtype(dtype):\n \"\"\"\n Checks the provided object to ensure that it is a valid dtype that can be written to an HDF5 file.\n Raises a type error if invalid. Returns True if the object passed the tests\n\n Parameters\n ----------\n dtype : object\n Object that is hopefully a :class:`h5py.Datatype`, or :class:`numpy.dtype` object\n\n Returns\n -------\n status : bool\n True if the object was a valid data-type\n \"\"\"\n if isinstance(dtype, (h5py.Datatype, np.dtype)):\n pass\n elif isinstance(np.dtype(dtype), np.dtype):\n # This should catch all those instances when dtype is something familiar like - np.float32\n pass\n else:\n raise TypeError('dtype should either be a numpy or h5py dtype')\n return True\n\n\ndef is_complex_dtype(dtype):\n \"\"\"\n Checks if the provided dtype is a complex dtype\n\n Parameters\n ----------\n dtype : object\n Object that is a class:`h5py.Datatype`, or :class:`numpy.dtype` object\n\n Returns\n -------\n is_complex : bool\n True if the dtype was a complex dtype. Else returns False\n \"\"\"\n validate_dtype(dtype)\n if dtype in [np.complex, np.complex64, np.complex128]:\n return True\n return False\n" ]
[ [ "numpy.array", "numpy.dtype", "numpy.hstack", "numpy.real" ] ]
brandontrabucco/jetpack
[ "aa60488788b2e6fe1d09727943be043158a7af09" ]
[ "mineral/algorithms/tuners/entropy_tuner.py" ]
[ "\"\"\"Author: Brandon Trabucco, Copyright 2019\"\"\"\n\n\nimport tensorflow as tf\nfrom mineral.algorithms.tuners.tuner import Tuner\n\n\nclass EntropyTuner(Tuner):\n\n def __init__(\n self,\n policy,\n **kwargs\n ):\n Tuner.__init__(self, **kwargs)\n self.policy = policy\n\n def update_algorithm(\n self,\n observations,\n actions,\n rewards,\n terminals\n ):\n def loss_function():\n policy_actions = self.policy.get_expected_value(\n observations[:, :(-1), ...])\n policy_entropy = -terminals[:, :(-1)] * self.policy.get_log_probs(\n policy_actions,\n observations[:, :(-1), ...])\n entropy_error = policy_entropy - self.target\n entropy_loss = self.tuning_variable * tf.stop_gradient(entropy_error)\n self.record(\n \"entropy_tuning_variable\",\n self.tuning_variable)\n self.record(\n \"entropy_error_mean\",\n tf.reduce_mean(entropy_error))\n self.record(\n \"entropy_error_max\",\n tf.reduce_max(entropy_error))\n self.record(\n \"entropy_error_min\",\n tf.reduce_min(entropy_error))\n self.record(\n \"entropy\",\n tf.reduce_mean(policy_entropy))\n self.record(\n \"entropy_loss\",\n tf.reduce_mean(entropy_loss))\n return tf.reduce_mean(entropy_loss)\n self.optimizer.minimize(\n loss_function, [self.tuning_variable])\n" ]
[ [ "tensorflow.reduce_min", "tensorflow.reduce_mean", "tensorflow.reduce_max", "tensorflow.stop_gradient" ] ]
hassanmohsin/chemprop
[ "b6d84f064f682d6ff7fa42e1f231d7467a87105e" ]
[ "biasdb/split.py" ]
[ "import numpy as np\nfrom copy import deepcopy\n\n\n\ndef stratify(data, classes, ratios, one_hot=False):\n \"\"\"Stratifying procedure.\n\n data is a list of lists: a list of labels, for each sample.\n Each sample's labels should be ints, if they are one-hot encoded, use one_hot=True\n \n classes is the list of classes each label can take\n\n ratios is a list, summing to 1, of how the dataset should be split\n\n \"\"\"\n # one-hot decoding\n if one_hot:\n temp = [[] for _ in range(len(data))]\n indexes, values = np.where(np.array(data).astype(int) == 1)\n for k, v in zip(indexes, values):\n temp[k].append(v)\n data = temp\n\n # Organize data per label: for each label l, per_label_data[l] contains the list of samples\n # in data which have this label\n per_label_data = {c: set() for c in classes}\n for i, d in enumerate(data):\n for l in d:\n per_label_data[l].add(i)\n\n # number of samples\n size = len(data)\n\n # In order not to compute lengths each time, they are tracked here.\n subset_sizes = [r * size for r in ratios]\n target_subset_sizes = deepcopy(subset_sizes)\n per_label_subset_sizes = {\n c: [r * len(per_label_data[c]) for r in ratios]\n for c in classes\n }\n\n # For each subset we want, the set of sample-ids which should end up in it\n stratified_data_ids = [set() for _ in range(len(ratios))]\n\n # For each sample in the data set\n while size > 0:\n # Compute |Di|\n lengths = {\n l: len(label_data)\n for l, label_data in per_label_data.items()\n }\n try:\n # Find label of smallest |Di|\n label = min(\n {k: v for k, v in lengths.items() if v > 0}, key=lengths.get\n )\n except ValueError:\n # If the dictionary in `min` is empty we get a Value Error. \n # This can happen if there are unlabeled samples.\n # In this case, `size` would be > 0 but only samples without label would remain.\n # \"No label\" could be a class in itself: it's up to you to format your data accordingly.\n break\n current_length = lengths[label]\n\n # For each sample with label `label`\n while per_label_data[label]:\n # Select such a sample\n current_id = per_label_data[label].pop()\n\n subset_sizes_for_label = per_label_subset_sizes[label]\n # Find argmax clj i.e. subset in greatest need of the current label\n largest_subsets = np.argwhere(\n subset_sizes_for_label == np.amax(subset_sizes_for_label)\n ).flatten()\n\n if len(largest_subsets) == 1:\n subset = largest_subsets[0]\n # If there is more than one such subset, find the one in greatest need\n # of any label\n else:\n largest_subsets = np.argwhere(\n subset_sizes == np.amax(subset_sizes)\n ).flatten()\n if len(largest_subsets) == 1:\n subset = largest_subsets[0]\n else:\n # If there is more than one such subset, choose at random\n subset = np.random.choice(largest_subsets)\n\n # Store the sample's id in the selected subset\n stratified_data_ids[subset].add(current_id)\n\n # There is one fewer sample to distribute\n size -= 1\n # The selected subset needs one fewer sample\n subset_sizes[subset] -= 1\n\n # In the selected subset, there is one more example for each label\n # the current sample has\n for l in data[current_id]:\n per_label_subset_sizes[l][subset] -= 1\n \n # Remove the sample from the dataset, meaning from all per_label dataset created\n for l, label_data in per_label_data.items():\n if current_id in label_data:\n label_data.remove(current_id)\n\n # Create the stratified dataset as a list of subsets, each containing the orginal labels\n stratified_data_ids = [sorted(strat) for strat in stratified_data_ids]\n stratified_data = [\n [data[i] for i in strat] for strat in stratified_data_ids\n ]\n\n # Return both the stratified indexes, to be used to sample the `features` associated with your labels\n # And the stratified labels dataset\n return stratified_data_ids, stratified_data\n" ]
[ [ "numpy.array", "numpy.amax", "numpy.random.choice" ] ]