code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
# -------------------------------------------------------- # Motion R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by <NAME>, based on code by <NAME> # -------------------------------------------------------- from __future__ import absolute_import, division, print_function import numpy as np import os import sys import time from tqdm import tqdm import tensorflow as tf from tensorflow.contrib import slim from model.config import cfg from boxes.timer import Timer from datasets.cityscapes.cityscapesscripts.evaluate import evaluate_np_preds as evaluate_cs import datasets.cityscapes.cityscapesscripts.labels as labels from layers.mask_util import binary_mask class Trainer(object): """A wrapper class for the training process.""" def __init__(self, network_cls, dataset, ckpt_dir, tbdir, pretrained_model=None): self.network_cls = network_cls self.dataset = dataset self.ckpt_dir = ckpt_dir self.tbdir = tbdir self.tbvaldir = tbdir + '_val' if not os.path.exists(self.tbdir): os.makedirs(self.tbdir) if not os.path.exists(self.tbvaldir): os.makedirs(self.tbvaldir) if not os.path.exists(self.ckpt_dir): os.makedirs(self.ckpt_dir) self.pretrained_model = pretrained_model def train_val(self, schedule, val=True): for epochs, learning_rate in schedule: for epoch in range(epochs): self.train_epoch(learning_rate) if val: self.evaluate() def train(self, schedule): # TODO this doesn't work properly yet as we rely on the coord stop signal # after each epoch to save checkpoints tfconfig = tf.ConfigProto(allow_soft_placement=True) tfconfig.gpu_options.allow_growth = True with tf.Session(config=tfconfig) as sess: self._train_epochs(sess, list(schedule)) def train_epoch(self, learning_rate): with tf.Graph().as_default(): tfconfig = tf.ConfigProto(allow_soft_placement=True) tfconfig.gpu_options.allow_growth = True with tf.Session(config=tfconfig) as sess: self._train_epochs(sess, [(1, learning_rate)]) def _train_epochs(self, sess, schedule): total_epochs = sum([ep for ep, lr in schedule]) print("Training for {} epoch(s): {}.".format(total_epochs, schedule)) with tf.device('/cpu:0'): batch = self.dataset.get_train_batch(total_epochs) net = self.network_cls(batch, is_training=True) train_op, lr_placeholder = self._get_train_op(net) saver = tf.train.Saver(max_to_keep=cfg.TRAIN.CHECKPOINTS_MAX_TO_KEEP, keep_checkpoint_every_n_hours=4) ckpt = tf.train.get_checkpoint_state(self.ckpt_dir) sess.run(tf.local_variables_initializer()) sess.run(tf.global_variables_initializer()) if ckpt is None: assert self.pretrained_model, 'Pre-trained resnet_v1_50 not found. See README.' vars_to_restore = slim.get_variables_to_restore(include=['resnet_v1_50']) vars_to_restore = [v for v in vars_to_restore if not 'Momentum' in v.name] restorer = tf.train.Saver(vars_to_restore) print('Loading initial model weights from {}'.format(self.pretrained_model)) restorer.restore(sess, self.pretrained_model) print('Loaded.') epoch = 0 else: ckpt_path = ckpt.model_checkpoint_path print('Restoring model checkpoint from {}'.format(ckpt_path)) saver.restore(sess, ckpt_path) print('Restored.') epoch = int(ckpt_path.split('/')[-1].split('-')[-1]) + 1 seed = cfg.RNG_INITIAL_SEED + epoch * cfg.RNG_EPOCH_SEED_INCREMENT np.random.seed(seed) tf.set_random_seed(seed) writer = tf.summary.FileWriter(self.tbdir, sess.graph) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) timer = Timer() for local_epochs, lr in schedule: for _ in range(local_epochs): i = 0 max_i = cfg.TRAIN.EXAMPLES_PER_EPOCH - 1 try: while not coord.should_stop(): timer.tic() feed_dict = {lr_placeholder: lr} run_ops = [ net._losses['rpn_cross_entropy'], net._losses['rpn_loss_box'], net._losses['cross_entropy'], net._losses['loss_box'], net._losses['mask_loss'], net._losses['total_loss'], train_op ] if i % cfg.TRAIN.SUMMARY_INTERVAL == 0: run_ops.append(tf.summary.merge_all()) run_results = sess.run(run_ops, feed_dict=feed_dict) if i % cfg.TRAIN.SUMMARY_INTERVAL == 0: summary = run_results[-1] run_results = run_results[:-1] writer.add_summary(summary, float(i - 1) + epoch * max_i) rpn_loss_cls, rpn_loss_box, loss_cls, loss_box, mask_loss, total_loss, _ \ = run_results timer.toc() if i % cfg.TRAIN.DISPLAY_INTERVAL == 0: print('{} [{} / {} at {:.3f} s/batch & lr {}] ' 'loss: {:.4f} [RPN cls {:.4f} box {:.4f}] [cls {:.4f} box {:.4f} mask {:.4f}]' .format(epoch, i, max_i, timer.average_time, lr, total_loss, rpn_loss_cls, rpn_loss_box, loss_cls, loss_box, mask_loss)) i += 1 except tf.errors.OutOfRangeError: pass save_filename = os.path.join(self.ckpt_dir, 'model.ckpt') saver.save(sess, save_filename, global_step=epoch) epoch += 1 writer.close() coord.request_stop() coord.join(threads) print('Finished epoch {} and wrote checkpoint.'.format(epoch)) def _get_train_op(self, net): loss = net._losses['total_loss'] lr_placeholder = tf.placeholder(tf.float32, name='learning_rate') tf.summary.scalar('TRAIN/learning_rate', lr_placeholder) optimizer = tf.train.MomentumOptimizer(lr_placeholder, cfg.TRAIN.MOMENTUM) # Compute the gradients wrt the loss gvs = optimizer.compute_gradients(loss) # Double the gradient of the bias if set if cfg.TRAIN.DOUBLE_BIAS: final_gvs = [] with tf.variable_scope('Gradient_Mult') as scope: for grad, var in gvs: scale = 1. if cfg.TRAIN.DOUBLE_BIAS and '/biases:' in var.name: scale *= 2. if not np.allclose(scale, 1.0): grad = tf.multiply(grad, scale) final_gvs.append((grad, var)) train_op = optimizer.apply_gradients(final_gvs) else: train_op = optimizer.apply_gradients(gvs) return train_op, lr_placeholder def evaluate(self): with tf.Graph().as_default(): tfconfig = tf.ConfigProto(allow_soft_placement=True) tfconfig.gpu_options.allow_growth = True with tf.Session(config=tfconfig) as sess: self._evaluate_cs(sess) # TODO add KITTI 2015 eval def _evaluate_cs(self, sess): ckpt = tf.train.get_checkpoint_state(self.ckpt_dir) assert ckpt is not None writer = tf.summary.FileWriter(self.tbvaldir) ckpt_path = ckpt.model_checkpoint_path epoch = int(ckpt_path.split('/')[-1].split('-')[-1]) with tf.device('/cpu:0'): batch = self.dataset.get_val_batch() image = batch['image'] net = self.network_cls(batch, is_training=False) sess.run(tf.local_variables_initializer()) sess.run(tf.global_variables_initializer()) print('Loading model checkpoint for evaluation: {:s}'.format(ckpt_path)) saver = tf.train.Saver() saver.restore(sess, ckpt_path) print('Loaded.') coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) iters = 0 avg_losses = np.zeros([len(net._losses)]) pred_np_arrays = [] summary_images = [] #depths = [] try: while iters < 3: #not coord.should_stop(): loss_ops = [v for (k, v) in net._losses] pred_ops = [ net._predictions['mask_scores'], net._predictions['cls_scores'], net._predictions['scores'], net._predictions['rois'] ] run_results = sess.run(loss_ops + pred_ops + [tf.shape(image), net.summary_image]) loss_results = run_results[:len(loss_ops)] pred_results = run_results[len(loss_ops):-2] image_shape_np = run_results[-2] summary_image_np = run_results[-1] avg_losses += loss_results pred_np_arrays.append(pred_results) summary_images.append(summary_image_np) #depths.append(depth) iters += 1 print("\rPredicted: {}".format(iters), end=' ') sys.stdout.flush() print('') except tf.errors.OutOfRangeError: pass avg_losses /= iters height, width = image_shape_np[1:3] pred_lists = [] for masks, cls_scores, rpn_scores, rois in pred_np_arrays: print(np.mean(rois[:, 3] - rois[:, 1]), np.mean(rois[:, 4] - rois[:, 2]), np.mean(masks)) preds = [] for i in range(masks.shape[0]): train_id = np.argmax(cls_scores[i]) if train_id == 0: # Ignore background class continue print(cls_scores[i], rpn_scores[i], rois[i, 1:]) pred_dct = {} pred_dct['imgId'] = "todo" pred_dct['labelID'] = labels.trainId2label[train_id].id pred_dct['conf'] = rpn_scores[i] mask = binary_mask(rois[i, :], masks[i, :, :], height, width) pred_dct['binaryMask'] = mask.astype(np.uint8) preds.append(pred_dct) pred_lists.append(preds) cs_avgs = evaluate_cs(pred_lists) max_images = min(len(summary_images), cfg.TEST.MAX_SUMMARY_IMAGES) for i, im in enumerate(summary_images[:max_images]): tf.summary.image('cs_val_{}/image'.format(i), im, collections=['cs_val']) #tf.summary.image('cs_val_{}/depth'.format(i), depth, collections=['cs_val']) #tf.summary.image('cs_val_{}/gt_depth'.format(i), gt_depth, collections=['cs_val']) _summarize_value(cs_avgs['allAp'], 'Ap', 'allAp', 'cs_val') _summarize_value(cs_avgs['allAp50%'], 'Ap50', 'allAp', 'cs_val') for k, v in cs_avgs["classes"].items(): _summarize_value(v['ap'], k, 'ap', 'cs_val') _summarize_value(v['ap50%'], k, 'ap50', 'cs_val') for i, k in enumerate(net._losses.keys()): _summarize_value(avg_losses[i], k, 'losses', 'cs_val') summary_op = tf.summary.merge_all(key='cs_val') sess.run(tf.global_variables_initializer()) summary = sess.run(summary_op) writer.add_summary(summary, epoch) writer.close() print('Done evaluating.') def _summarize_value(value, name, prefix=None, key=tf.GraphKeys.SUMMARIES): prefix = '' if not prefix else prefix + '/' p = tf.Variable(value, dtype=tf.float32, name=name, trainable=False) tf.summary.scalar(prefix + name, p, collections=[key]) return p
[ "tensorflow.train.Coordinator", "numpy.random.seed", "tensorflow.contrib.slim.get_variables_to_restore", "numpy.argmax", "numpy.allclose", "layers.mask_util.binary_mask", "tensorflow.local_variables_initializer", "tensorflow.ConfigProto", "tensorflow.multiply", "tensorflow.Variable", "sys.stdout...
[((12214, 12278), 'tensorflow.Variable', 'tf.Variable', (['value'], {'dtype': 'tf.float32', 'name': 'name', 'trainable': '(False)'}), '(value, dtype=tf.float32, name=name, trainable=False)\n', (12225, 12278), True, 'import tensorflow as tf\n'), ((12283, 12337), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['(prefix + name)', 'p'], {'collections': '[key]'}), '(prefix + name, p, collections=[key])\n', (12300, 12337), True, 'import tensorflow as tf\n'), ((1762, 1803), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (1776, 1803), True, 'import tensorflow as tf\n'), ((2683, 2781), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': 'cfg.TRAIN.CHECKPOINTS_MAX_TO_KEEP', 'keep_checkpoint_every_n_hours': '(4)'}), '(max_to_keep=cfg.TRAIN.CHECKPOINTS_MAX_TO_KEEP,\n keep_checkpoint_every_n_hours=4)\n', (2697, 2781), True, 'import tensorflow as tf\n'), ((2825, 2869), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['self.ckpt_dir'], {}), '(self.ckpt_dir)\n', (2854, 2869), True, 'import tensorflow as tf\n'), ((3882, 3902), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3896, 3902), True, 'import numpy as np\n'), ((3911, 3935), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (3929, 3935), True, 'import tensorflow as tf\n'), ((3954, 3999), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['self.tbdir', 'sess.graph'], {}), '(self.tbdir, sess.graph)\n', (3975, 3999), True, 'import tensorflow as tf\n'), ((4016, 4038), 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), '()\n', (4036, 4038), True, 'import tensorflow as tf\n'), ((4058, 4110), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'sess': 'sess', 'coord': 'coord'}), '(sess=sess, coord=coord)\n', (4086, 4110), True, 'import tensorflow as tf\n'), ((4128, 4135), 'boxes.timer.Timer', 'Timer', ([], {}), '()\n', (4133, 4135), False, 'from boxes.timer import Timer\n'), ((6579, 6627), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""learning_rate"""'}), "(tf.float32, name='learning_rate')\n", (6593, 6627), True, 'import tensorflow as tf\n'), ((6636, 6692), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""TRAIN/learning_rate"""', 'lr_placeholder'], {}), "('TRAIN/learning_rate', lr_placeholder)\n", (6653, 6692), True, 'import tensorflow as tf\n'), ((6713, 6775), 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['lr_placeholder', 'cfg.TRAIN.MOMENTUM'], {}), '(lr_placeholder, cfg.TRAIN.MOMENTUM)\n', (6739, 6775), True, 'import tensorflow as tf\n'), ((7907, 7951), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['self.ckpt_dir'], {}), '(self.ckpt_dir)\n', (7936, 7951), True, 'import tensorflow as tf\n'), ((8002, 8038), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['self.tbvaldir'], {}), '(self.tbvaldir)\n', (8023, 8038), True, 'import tensorflow as tf\n'), ((8520, 8536), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (8534, 8536), True, 'import tensorflow as tf\n'), ((8618, 8640), 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), '()\n', (8638, 8640), True, 'import tensorflow as tf\n'), ((8659, 8711), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'sess': 'sess', 'coord': 'coord'}), '(sess=sess, coord=coord)\n', (8687, 8711), True, 'import tensorflow as tf\n'), ((10971, 10994), 'datasets.cityscapes.cityscapesscripts.evaluate.evaluate_np_preds', 'evaluate_cs', (['pred_lists'], {}), '(pred_lists)\n', (10982, 10994), True, 'from datasets.cityscapes.cityscapesscripts.evaluate import evaluate_np_preds as evaluate_cs\n'), ((11853, 11887), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {'key': '"""cs_val"""'}), "(key='cs_val')\n", (11873, 11887), True, 'import tensorflow as tf\n'), ((1058, 1084), 'os.path.exists', 'os.path.exists', (['self.tbdir'], {}), '(self.tbdir)\n', (1072, 1084), False, 'import os\n'), ((1098, 1121), 'os.makedirs', 'os.makedirs', (['self.tbdir'], {}), '(self.tbdir)\n', (1109, 1121), False, 'import os\n'), ((1137, 1166), 'os.path.exists', 'os.path.exists', (['self.tbvaldir'], {}), '(self.tbvaldir)\n', (1151, 1166), False, 'import os\n'), ((1180, 1206), 'os.makedirs', 'os.makedirs', (['self.tbvaldir'], {}), '(self.tbvaldir)\n', (1191, 1206), False, 'import os\n'), ((1222, 1251), 'os.path.exists', 'os.path.exists', (['self.ckpt_dir'], {}), '(self.ckpt_dir)\n', (1236, 1251), False, 'import os\n'), ((1265, 1291), 'os.makedirs', 'os.makedirs', (['self.ckpt_dir'], {}), '(self.ckpt_dir)\n', (1276, 1291), False, 'import os\n'), ((1866, 1893), 'tensorflow.Session', 'tf.Session', ([], {'config': 'tfconfig'}), '(config=tfconfig)\n', (1876, 1893), True, 'import tensorflow as tf\n'), ((2060, 2101), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (2074, 2101), True, 'import tensorflow as tf\n'), ((2465, 2484), 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), "('/cpu:0')\n", (2474, 2484), True, 'import tensorflow as tf\n'), ((2887, 2919), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (2917, 2919), True, 'import tensorflow as tf\n'), ((2938, 2971), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2969, 2971), True, 'import tensorflow as tf\n'), ((3120, 3175), 'tensorflow.contrib.slim.get_variables_to_restore', 'slim.get_variables_to_restore', ([], {'include': "['resnet_v1_50']"}), "(include=['resnet_v1_50'])\n", (3149, 3175), False, 'from tensorflow.contrib import slim\n'), ((3286, 3317), 'tensorflow.train.Saver', 'tf.train.Saver', (['vars_to_restore'], {}), '(vars_to_restore)\n', (3300, 3317), True, 'import tensorflow as tf\n'), ((7633, 7674), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (7647, 7674), True, 'import tensorflow as tf\n'), ((8161, 8180), 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), "('/cpu:0')\n", (8170, 8180), True, 'import tensorflow as tf\n'), ((8337, 8369), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (8367, 8369), True, 'import tensorflow as tf\n'), ((8388, 8421), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8419, 8421), True, 'import tensorflow as tf\n'), ((11905, 11938), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (11936, 11938), True, 'import tensorflow as tf\n'), ((2172, 2199), 'tensorflow.Session', 'tf.Session', ([], {'config': 'tfconfig'}), '(config=tfconfig)\n', (2182, 2199), True, 'import tensorflow as tf\n'), ((6189, 6230), 'os.path.join', 'os.path.join', (['self.ckpt_dir', '"""model.ckpt"""'], {}), "(self.ckpt_dir, 'model.ckpt')\n", (6201, 6230), False, 'import os\n'), ((6997, 7031), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Gradient_Mult"""'], {}), "('Gradient_Mult')\n", (7014, 7031), True, 'import tensorflow as tf\n'), ((7745, 7772), 'tensorflow.Session', 'tf.Session', ([], {'config': 'tfconfig'}), '(config=tfconfig)\n', (7755, 7772), True, 'import tensorflow as tf\n'), ((9845, 9863), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (9861, 9863), False, 'import sys\n'), ((10128, 10160), 'numpy.mean', 'np.mean', (['(rois[:, 3] - rois[:, 1])'], {}), '(rois[:, 3] - rois[:, 1])\n', (10135, 10160), True, 'import numpy as np\n'), ((10180, 10212), 'numpy.mean', 'np.mean', (['(rois[:, 4] - rois[:, 2])'], {}), '(rois[:, 4] - rois[:, 2])\n', (10187, 10212), True, 'import numpy as np\n'), ((10232, 10246), 'numpy.mean', 'np.mean', (['masks'], {}), '(masks)\n', (10239, 10246), True, 'import numpy as np\n'), ((10342, 10366), 'numpy.argmax', 'np.argmax', (['cls_scores[i]'], {}), '(cls_scores[i])\n', (10351, 10366), True, 'import numpy as np\n'), ((10758, 10812), 'layers.mask_util.binary_mask', 'binary_mask', (['rois[i, :]', 'masks[i, :, :]', 'height', 'width'], {}), '(rois[i, :], masks[i, :, :], height, width)\n', (10769, 10812), False, 'from layers.mask_util import binary_mask\n'), ((2012, 2022), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2020, 2022), True, 'import tensorflow as tf\n'), ((7585, 7595), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (7593, 7595), True, 'import tensorflow as tf\n'), ((7247, 7270), 'numpy.allclose', 'np.allclose', (['scale', '(1.0)'], {}), '(scale, 1.0)\n', (7258, 7270), True, 'import numpy as np\n'), ((7303, 7327), 'tensorflow.multiply', 'tf.multiply', (['grad', 'scale'], {}), '(grad, scale)\n', (7314, 7327), True, 'import tensorflow as tf\n'), ((9291, 9306), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (9299, 9306), True, 'import tensorflow as tf\n'), ((5012, 5034), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (5032, 5034), True, 'import tensorflow as tf\n')]
''' FEN -> Similar to Forsyth–Edwards Notation in chess Starting fen => "B3B/5/5/5/B3B G 0" {"B3B/5/5/5/B3B"(similar to chess,"B" - Bagh, "G" - Goat)} {"G" or "B" represents who has next move} {"0" number of moves by goat} PGN -> Portable Game Notation like in chess Move to move tracking notation <Move number>. G(<old_position>)<new_position> (...B<old_position><new_position>) Example : 1.G33 B1122 2.G44 [ Note: G<new_position> for unplaced piece ] ''' import re import os import baghchal from collections import Counter import numpy as np from baghchal.lookup_table import bagh_moves_dict, connected_points_dict, action_space from PIL import Image def render_points(p): return (103*(p[1]-1), 103*(p[0]-1)) # for pillow image BASEDIR = os.path.dirname(baghchal.__file__) os.chdir(BASEDIR) BOARD_IMG = Image.open('images/board.png', 'r') BAGH_SPRITE = Image.open('images/bagh.png', 'r') GOAT_SPRITE = Image.open('images/goat.png', 'r') class Board: def __init__(self, description=""): self.reset() if description.strip(): self.pgn_converter(description.strip()) def __getitem__(self, index): return self.board[index[0] - 1][index[1] - 1] def __setitem__(self, index, value): self.board[index[0] - 1][index[1] - 1] = value @property def no_of_moves_made(self): return self.no_of_goat_moves + self.no_of_bagh_moves def _possible_goat_moves(self): # the function is independent of whose turn it is to play, use at your own risk. move_list = set() if self.no_of_goat_moves < 20: return {f'G{x1}{y1}' for x1 in range(1, 6) for y1 in range(1, 6) if (x1, y1) not in self.bagh_points.union(self.goat_points)} else: for x1, y1 in self.goat_points: move_list.update({f'G{x1}{y1}{x2}{y2}' for x2, y2 in self[x1, y1].valid_moves()}) return move_list def _possible_bagh_moves(self): # the function is independent of whose turn it is to play, use at your own risk. move_list = set() for x1, y1 in self.bagh_points: move_list.update({f'B{x1}{y1}{x2}{y2}' for x2, y2 in self[x1, y1].valid_non_special_moves()}) move_list.update({f'Bx{x1}{y1}{x2}{y2}' for x2, y2 in self[x1, y1].valid_bagh_moves()}) return move_list def possible_moves(self): if self.is_game_over(): return 0 if self.next_turn == "G": return self._possible_goat_moves() else: return self._possible_bagh_moves() def possible_moves_vector(self): moves_vector = np.zeros(217) if self.is_game_over(): return moves_vector if self.next_turn == "G" and self.no_of_goat_moves < 20: for x1 in range(1, 6): for y1 in range(1, 6): if (x1, y1) not in self.bagh_points.union(self.goat_points): moves_vector[action_space[f'{x1}{y1}']] = 1 elif self.next_turn == "G" and self.no_of_goat_moves >= 20: for x1, y1 in self.goat_points: for x2, y2 in self[x1, y1].valid_moves(): moves_vector[action_space[f'{x1}{y1}{x2}{y2}']] = 1 else: for x1, y1 in self.bagh_points: for x2, y2 in self[x1, y1].valid_moves(): moves_vector[action_space[f'{x1}{y1}{x2}{y2}']] = 1 return moves_vector def pgn_converter(self, pgn): move_list = re.findall( r'[0-9]+\.\s*([G][1-5]{2,4})\s*([B][x]?[1-5]{4})?', pgn) for moves in move_list: for move in moves: if move == "": break self.move(move) def fen_to_board(self, fen): rows = fen.split(" ")[0].split("/") for x in range(5): counter = 1 for y in rows[x]: if y == "B": Bagh(self, (x + 1, counter)) counter += 1 elif y == "G": Bagh(self, (x + 1, counter)) counter += 1 else: for _ in range(int(y)): counter += 1 @property def baghs_trapped(self): counter = 0 for bagh in self.bagh_points: if not self[bagh[0], bagh[1]].valid_moves(): counter += 1 return counter @property def all_goats_trapped(self): return self.next_turn == "G" and not self._possible_goat_moves() def show_info(func): def wrapper(self): if self.no_of_moves_made: print(f"Last move: {self.moves[-1]}") print( f"Goats Placed: {self.goats_placed}, Goats Captured: {self.goats_captured}, Baghs Trapped: {self.baghs_trapped}") func(self) if self.is_game_over(): print("Game over.") if self.winner(): print(f"Winner : {self.winner()}") else: print(f"The game is a draw.") return print(f"{self.next_turn} to play.") print(f"Possible moves:", end="") for move in self.possible_moves(): print(f" {move}", end="") print() print() return wrapper @show_info def show_board(self): rep1 = ''' ¦ \ ¦ / ¦ \ ¦ / ¦ ¦ \ ¦ / ¦ \ ¦ / ¦ ¦ \ ¦ / ¦ \ ¦ / ¦ ¦ \ ¦ / ¦ \ ¦ / ¦ ¦ \ ¦ / ¦ \ ¦ / ¦ ''' rep2 = ''' ¦ / ¦ \ ¦ /¦ \ ¦ ¦ / ¦ \ ¦ / ¦ \ ¦ ¦ / ¦ \ ¦ / ¦ \ ¦ ¦ / ¦ \ ¦ / ¦ \ ¦ ¦ / ¦ \ ¦ / ¦ \ ¦ ''' print( f"[{self[1,1]}]11--------[{self[1,2]}]12--------[{self[1,3]}]13--------[{self[1,4]}]14--------[{self[1,5]}]15") print(rep1) print( f"[{self[2,1]}]21--------[{self[2,2]}]22--------[{self[2,3]}]23--------[{self[2,4]}]24--------[{self[2,5]}]25") print(rep2) print( f"[{self[3,1]}]31--------[{self[3,2]}]32--------[{self[3,3]}]33--------[{self[3,4]}]34--------[{self[3,5]}]35") print(rep1) print( f"[{self[4,1]}]41--------[{self[4,2]}]42--------[{self[4,3]}]43--------[{self[4,4]}]44--------[{self[4,5]}]45") print(rep2) print( f"[{self[5,1]}]51--------[{self[5,2]}]52--------[{self[5,3]}]53--------[{self[5,4]}]54--------[{self[5,5]}]55") def validate_placement(self, move): x1, y1 = int(move[1]), int(move[2]) self.validate_points(move, x1, y1) if not self.goats_placed < 20: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} More than 20 goats cannot be placed") if self[x1, y1]: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} The coordinate is already occupied.") return True def validate(self, move): if self.is_game_over(): raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} The game is already over.") move = move.strip() if len(move) not in {3, 5, 6}: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} Error ! Could not recognise the move.") if move[0] != self.next_turn: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} Illegal Move.It is other side's turn.") if move[:2] == "Bx": return self.validate_capture(move) if len(move) == 3: if self.goats_placed >= 20: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} Futher piece cannot be placed.") if move[0] == "B": raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} Further Bagh cannot be placed.") return self.validate_placement(move) if move[0] == "G" and len(move) == 5 and self.no_of_goat_moves < 20: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} All the goats must be placed first.") if move[:2] == "Gx": raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} Goats cannot capture.") x1, y1, x2, y2 = int(move[1]), int(move[2]), int(move[3]), int(move[4]) self.validate_points(move, x1, y1, x2, y2) self.validate_pp(move, x1, y1, move[0]) if move[0] == "G": if not ((x2, y2) in self[x1, y1].valid_moves()): raise Exception( f"{(self.no_of_moves_made+2)//2}.{move} is not a valid move.") elif move[0] == "B": if not ((x2, y2) in self[x1, y1].valid_non_special_moves()): raise Exception( f"{(self.no_of_moves_made+2)//2}.{move} is not a valid move.") return True def validate_capture(self, move): x1, y1, x2, y2 = int(move[2]), int(move[3]), int(move[4]), int(move[5]) self.validate_points(move, x1, y1, x2, y2) self.validate_pp(move, x1, y1, move[0]) if not ((x2, y2) in self[x1, y1].valid_bagh_moves()): raise Exception( f"{(self.no_of_moves_made+2)//2}.{move} is not a valid move.") return True def validate_points(self, move, x1, y1, x2=1, y2=1): if not (0 < x1 < 6 and 0 < y1 < 6 and 0 < x2 < 6 and 0 < y2 < 6): raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} Invalid PGN. Coordinates not in range.") def validate_pp(self, move, x1, y1, p): if not self[x1, y1]: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} ({x1},{y1}) is not occupied.") if self[x1, y1].__str__() != p: raise Exception(f"{(self.no_of_moves_made+2)//2}.{move} Piece at ({x1},{y1}) is other than specified.") def safe_move(self, move): if len(move) == 3: Goat(self, (int(move[1]), int(move[2]))) self.no_of_goat_moves += 1 self.goats_placed += 1 else: if len(move) == 5: x1, y1, x2, y2 = int(move[1]), int( move[2]), int(move[3]), int(move[4]) elif len(move) == 6: x1, y1, x2, y2 = int(move[2]), int( move[3]), int(move[4]), int(move[5]) x3, y3 = (x1 + x2) // 2, (y1 + y2) // 2 self[x3, y3] = 0 self.goat_points.remove((x3, y3)) self.goats_captured += 1 self[x1, y1] = 0 if move[0] == "G": self.goat_points.remove((x1, y1)) Goat(self, (x2, y2)) self.no_of_goat_moves += 1 elif move[0] == "B": self.bagh_points.remove((x1, y1)) Bagh(self, (x2, y2)) self.no_of_bagh_moves += 1 self.moves.append(move) pgn_update = "" if self.next_turn == "G": pgn_update += f"{self.no_of_goat_moves}. " pgn_update += move self.pgn += " " + pgn_update self.next_turn = "G" if self.next_turn == "B" else "B" self.fen = self.board_to_fen() self.fen_history.append(self.fen) if self.no_of_goat_moves >= 20: self.fen_count.update([self.fen.split(" ")[0]]) if self.is_game_over(): if self.winner() == "B": self.pgn += "# 0-1" elif self.winner() == "G": self.pgn += "# 1-0" else: self.pgn += "# 1/2-1/2" def board_to_fen(self): string = "" for x in range(1, 6): counter = 0 for y in range(1, 6): if self[x, y]: counter = 0 string += self[x, y].__str__() else: counter += 1 if y == 5 or self[x, y + 1] != 0: string += str(counter) string += "/" return f"{string[:-1]} {self.next_turn} {self.no_of_goat_moves}" def move(self, move): if self.validate(move): self.safe_move(move) def pure_move(self, move): if len(move) == 2: self.move(f"G{move}") else: x1, y1, x2, y2 = move if (int(x1) - int(x2))**2 + (int(y1) - int(y2))**2 <= 2: self.move(f"{self.next_turn}{move}") else: self.move(f'{self.next_turn}x{move}') def is_game_over(self): if self.goats_captured >= 5 or self.baghs_trapped == 4 or self.check_draw() or self.all_goats_trapped: return True return False def check_draw(self): if max(self.fen_count.values()) >= 3: return 1 return 0 def winner(self): if self.goats_captured >= 5 or self.all_goats_trapped: return "B" if self.baghs_trapped == 4: return "G" if self.check_draw(): return 0 raise Exception("Game is not over yet !") def fen_state(self, fen): state = np.zeros((2, 5, 5)) rows = fen.split(" ")[0].split("/") for x in range(5): counter = 0 for y in rows[x]: if y == "G": state[0, x, counter] = 1 counter += 1 elif y == "B": state[1, x, counter] = 1 counter += 1 else: for _ in range(int(y)): counter += 1 return state def board_repr(self): state = np.zeros((5, 5, 5)) state[[0, 1]] = self.fen_state(self.fen) state[2, :, :] = self.goats_captured state[3, :, :] = self.baghs_trapped if self.next_turn == "G": state[4, :, :] = 1 return state def reset(self): self.board = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] self.next_turn = "G" self.no_of_goat_moves = 0 self.no_of_bagh_moves = 0 self.goats_placed = 0 self.goats_captured = 0 self.goat_points = set() self.bagh_points = set() self.fen = "B3B/5/5/5/B3B G 0" self.fen_history = [self.fen] self.fen_count = Counter([self.fen.split(" ")[0]]) self.pgn = "" self.moves = list() self.fen_to_board(self.fen) def recent_player(self): return "G" if self.no_of_moves_made % 2 else "B" def undo(self, no_of_moves=1): if no_of_moves > self.no_of_moves_made: raise Exception( "The number of moves to undo is greater than the number of moves made in the board.") move_list = self.moves n = self.no_of_moves_made - no_of_moves self.reset() for move in move_list: if move == "" or n == 0: return move_list[-no_of_moves:] self.move(move) n -= 1 @show_info def lightweight_show_board(self): print("-" * 26) for row in self.board: for x in row: if x: print(f"| {x.__str__()} ", end=" ") else: print("| ", end=" ") print("|") print("-" * 26) def render(self): img = Image.new("RGBA", (480, 480), (255, 255, 255, 0)) img.paste(BOARD_IMG, (0, 0)) for point in self.goat_points: img.paste(GOAT_SPRITE, render_points(point), mask=GOAT_SPRITE) for point in self.bagh_points: img.paste(BAGH_SPRITE, render_points(point), mask=BAGH_SPRITE) img.show() class Piece: def __init__(self, board, position=0): if position: if not (1, 1) <= position <= (5, 5): raise Exception(f"Invalid Coordinate for {self.__repr__()} - {position}") if board[position[0], position[1]]: raise Exception( f"Cannot place {self.__repr__()} at coordinate {position} occupied by {board[position[0],position[1]].__repr__()}") self.position = position self.board = board self.board[position[0], position[1]] = self def connected_points(self): if self.position: return connected_points_dict[self.position] else: return 0 def valid_moves(self): return {x for x in self.connected_points() if not self.board[x[0], x[1]]} class Bagh(Piece): def __init__(self, board, position): super(Bagh, self).__init__(board, position) self.board.bagh_points.add(position) def __str__(self): return "B" def __repr__(self): return "Bagh" def special_connected_points(self): return bagh_moves_dict[self.position] def valid_bagh_moves(self): return {x for x in self.special_connected_points() if (not self.board[x[0], x[1]]) and self.board[ (x[0] + self.position[0]) // 2, (x[1] + self.position[1]) // 2].__class__ == Goat} def valid_moves(self): return super(Bagh, self).valid_moves().union(self.valid_bagh_moves()) def valid_non_special_moves(self): return super(Bagh, self).valid_moves() class Goat(Piece): def __init__(self, board, position): super(Goat, self).__init__(board, position) self.board.goat_points.add(position) def __str__(self): return "G" def __repr__(self): return "Goat"
[ "PIL.Image.new", "os.path.dirname", "numpy.zeros", "PIL.Image.open", "re.findall", "os.chdir" ]
[((805, 839), 'os.path.dirname', 'os.path.dirname', (['baghchal.__file__'], {}), '(baghchal.__file__)\n', (820, 839), False, 'import os\n'), ((840, 857), 'os.chdir', 'os.chdir', (['BASEDIR'], {}), '(BASEDIR)\n', (848, 857), False, 'import os\n'), ((871, 906), 'PIL.Image.open', 'Image.open', (['"""images/board.png"""', '"""r"""'], {}), "('images/board.png', 'r')\n", (881, 906), False, 'from PIL import Image\n'), ((921, 955), 'PIL.Image.open', 'Image.open', (['"""images/bagh.png"""', '"""r"""'], {}), "('images/bagh.png', 'r')\n", (931, 955), False, 'from PIL import Image\n'), ((970, 1004), 'PIL.Image.open', 'Image.open', (['"""images/goat.png"""', '"""r"""'], {}), "('images/goat.png', 'r')\n", (980, 1004), False, 'from PIL import Image\n'), ((2704, 2717), 'numpy.zeros', 'np.zeros', (['(217)'], {}), '(217)\n', (2712, 2717), True, 'import numpy as np\n'), ((3583, 3652), 're.findall', 're.findall', (['"""[0-9]+\\\\.\\\\s*([G][1-5]{2,4})\\\\s*([B][x]?[1-5]{4})?"""', 'pgn'], {}), "('[0-9]+\\\\.\\\\s*([G][1-5]{2,4})\\\\s*([B][x]?[1-5]{4})?', pgn)\n", (3593, 3652), False, 'import re\n'), ((13357, 13376), 'numpy.zeros', 'np.zeros', (['(2, 5, 5)'], {}), '((2, 5, 5))\n', (13365, 13376), True, 'import numpy as np\n'), ((13885, 13904), 'numpy.zeros', 'np.zeros', (['(5, 5, 5)'], {}), '((5, 5, 5))\n', (13893, 13904), True, 'import numpy as np\n'), ((15724, 15773), 'PIL.Image.new', 'Image.new', (['"""RGBA"""', '(480, 480)', '(255, 255, 255, 0)'], {}), "('RGBA', (480, 480), (255, 255, 255, 0))\n", (15733, 15773), False, 'from PIL import Image\n')]
############################################################## # # # <NAME> and <NAME> (2017) # # Machine Learning for the Quantified Self # # Springer # # Chapter 5 # # # ############################################################## import math import numbers import numpy as np import pandas as pd from scipy.stats import norm from scipy import stats import sys from sklearn.neighbors import DistanceMetric import sklearn # Class defining the distance metrics that are not available as standard ones.... class InstanceDistanceMetrics: # S for gowers distance def s(self, val1, val2, range): # If we compare numbers we look at the difference and normalize. if isinstance(val1, numbers.Number) and isinstance(val1, numbers.Number): return 1 - (float(abs(val1-val2))/range) # If we compare something else, we just look at whether they are equal. else: if val1 == val2: return 1 else: return 0 # Delta for gowers distance. def delta(self, val1, val2): # Check whether both values are known (i.e. nan), if so the delta is 1, 0 otherwise. if (not np.isnan(val1)) and (not np.isnan(val2)): return 1 return 0 # Define gowers distance between two rows, given the ranges of the variables # over the entire dataset (over all columns in row1 and row2) def gowers_similarity(self, data_row1, data_row2, ranges): # We cannot computer if the lengths are not equal. if len(data_row1.columns) != len(data_row2.columns): return -1 delta_total = 0 s_total = 0 # iterate over all columns. for i in range(0, len(data_row1.columns)): val1 = data_row1[data_row1.columns[i]].values[0] val2 = data_row2[data_row2.columns[i]].values[0] # compute the delta delta = self.delta(val1, val2) delta_total = delta_total + delta if delta > 0: # and compute the s if the delta is above 0. s_total = s_total + self.s(val1, val2, ranges[i]) return float(s_total)/delta_total # Class to flatten datasets or compute the statistical difference between cases. class PersonDistanceMetricsNoOrdering: gower = 'gower' minkowski = 'minkowski' # This returns a dataset with aggregated data instances based on the mean values # in the rows. def create_instances_mean(self, datasets): index = range(0, len(datasets)) cols = datasets[0].columns new_dataset = pd.DataFrame(index=index, columns=cols) for i in range(0, len(datasets)): for col in cols: # Compute the mean per column and assign that # value for the row representing the current # dataset. new_dataset.iloc[i, new_dataset.columns.get_loc(col)] = datasets[i][col].mean() return new_dataset # Fit datasets to normal distribution and use parameters as instances def create_instances_normal_distribution(self, datasets): index = range(0, len(datasets)) cols = datasets[0].columns new_cols = [] # Create new columns for the parameters of the distribution. for col in cols: new_cols.append(col + '_mu') new_cols.append(col + '_sigma') new_dataset = pd.DataFrame(index=index, columns=new_cols) for i in range(0, len(datasets)): for col in cols: # Fit the distribution and assign the values to the # row representing the dataset. mu, sigma = norm.fit(datasets[i][col]) new_dataset.iloc[i, new_dataset.columns.get_loc(col + '_mu')] = mu new_dataset.iloc[i, new_dataset.columns.get_loc(col + '_sigma')] = sigma return new_dataset # This defines the distance between datasets based on the statistical # differences between the distribution we can only compute # distances pairwise. def p_distance(self, dataset1, dataset2): cols = dataset1.columns distance = 0 for col in cols: D, p_value = stats.ks_2samp(dataset1[col], dataset2[col]) distance= distance + (1-p_value) return distance # Class to compare two time ordered datasets. class PersonDistanceMetricsOrdering: extreme_value = sys.float_info.max tiny_value = 0.000001 # Directly pair up the datasets and computer the euclidean # distances between the sequences of values. def euclidean_distance(self, dataset1, dataset2): dist = DistanceMetric.get_metric('euclidean') if not len(dataset1.index) == len(dataset2.index): return -1 distance = 0 for i in range(0, len(dataset1.index)): data_row1 = dataset1.iloc[:,i:i+1].transpose() data_row2 = dataset2.iloc[:,i:i+1].transpose() ecl_dist = dist.pairwise(data_row1, data_row2) distance = distance + ecl_dist return distance # Compute the distance between two datasets given a set lag. def lag_correlation_given_lag(self, dataset1, dataset2, lag): distance = 0 for i in range(0, len(dataset1.columns)): # consider the lengths of the series, and compare the # number of points in the smallest series. length_ds1 = len(dataset1.index) length_ds2 = len(dataset2.index) - lag length_used = min(length_ds1, length_ds2) if length_used < 1: return self.extreme_value # We multiply the values as expressed in the book. ccc = np.multiply(dataset1.ix[0:length_used, i].values, dataset2.ix[lag:length_used+lag, i].values) # We add the sum of the mutliplications to the distance. Correct for the difference in length. distance = distance + (float(1)/(float(max(ccc.sum(), self.tiny_value))))/length_used return distance # Compute the lag correlation. For this we find the best lag. def lag_correlation(self, dataset1, dataset2, max_lag): best_dist = -1 best_lag = 0 for i in range(0, max_lag+1): # Compute the distance given a lag. current_dist = self.lag_correlation_given_lag(dataset1, dataset2, i) if current_dist < best_dist or best_dist == -1: best_dist = current_dist best_lag = i return best_dist # Simple implementation of the dtw. Note that we use the euclidean distance here.. # The implementation follows the algorithm explained in the book very closely. def dynamic_time_warping(self, dataset1, dataset2): # Create a distance matrix between all time points. cheapest_path = np.full((len(dataset1.index), len(dataset2.index)), self.extreme_value) cheapest_path[0,0] = 0 DM = InstanceDistanceMetrics() for i in range(1, len(dataset1.index)): for j in range(1, len(dataset2.index)): data_row1 = dataset1.iloc[i:i+1,:] data_row2 = dataset2.iloc[j:j+1,:] d = sklearn.metrics.pairwise.euclidean_distances(data_row1, data_row2) cheapest_path[i,j] = d + min(cheapest_path[i-1, j], cheapest_path[i, j-1], cheapest_path[i-1, j-1]) return cheapest_path[len(dataset1.index)-1, len(dataset2.index)-1]
[ "pandas.DataFrame", "numpy.multiply", "sklearn.neighbors.DistanceMetric.get_metric", "sklearn.metrics.pairwise.euclidean_distances", "numpy.isnan", "scipy.stats.norm.fit", "scipy.stats.ks_2samp" ]
[((2856, 2895), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'index', 'columns': 'cols'}), '(index=index, columns=cols)\n', (2868, 2895), True, 'import pandas as pd\n'), ((3677, 3720), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'index', 'columns': 'new_cols'}), '(index=index, columns=new_cols)\n', (3689, 3720), True, 'import pandas as pd\n'), ((4924, 4962), 'sklearn.neighbors.DistanceMetric.get_metric', 'DistanceMetric.get_metric', (['"""euclidean"""'], {}), "('euclidean')\n", (4949, 4962), False, 'from sklearn.neighbors import DistanceMetric\n'), ((4478, 4522), 'scipy.stats.ks_2samp', 'stats.ks_2samp', (['dataset1[col]', 'dataset2[col]'], {}), '(dataset1[col], dataset2[col])\n', (4492, 4522), False, 'from scipy import stats\n'), ((5988, 6088), 'numpy.multiply', 'np.multiply', (['dataset1.ix[0:length_used, i].values', 'dataset2.ix[lag:length_used + lag, i].values'], {}), '(dataset1.ix[0:length_used, i].values, dataset2.ix[lag:\n length_used + lag, i].values)\n', (5999, 6088), True, 'import numpy as np\n'), ((1433, 1447), 'numpy.isnan', 'np.isnan', (['val1'], {}), '(val1)\n', (1441, 1447), True, 'import numpy as np\n'), ((1458, 1472), 'numpy.isnan', 'np.isnan', (['val2'], {}), '(val2)\n', (1466, 1472), True, 'import numpy as np\n'), ((3937, 3963), 'scipy.stats.norm.fit', 'norm.fit', (['datasets[i][col]'], {}), '(datasets[i][col])\n', (3945, 3963), False, 'from scipy.stats import norm\n'), ((7481, 7547), 'sklearn.metrics.pairwise.euclidean_distances', 'sklearn.metrics.pairwise.euclidean_distances', (['data_row1', 'data_row2'], {}), '(data_row1, data_row2)\n', (7525, 7547), False, 'import sklearn\n')]
from spear import * import numpy.random as rnd import matplotlib.pyplot as plt import numpy from statistics import mean a = 0.5 az0 = 0.75 az12 = 0.75 az23 = 0.75 g = 9.81 t_step = 0.1 #duration of a tick in seconds q_max = 6.0 q_step = q_max/5.0 q_med = q_max/2.0 l_max = 20.0 l_min = 0.0 l_goal = 10.0 delta_l = 0.5 epsilon = 0.3 q2_dev = 0.5 ### ENVIRONMENT EVOLUTION def compute_flow_rate(x1, x2, a, a12): if x1 > x2: return a12*a*numpy.sqrt(2*g)*numpy.sqrt(x1-x2) else: return -a12*a*numpy.sqrt(2*g)*numpy.sqrt(x2-x1) def compute_q12(ds): l1 = ds['l1'] l2 = ds['l2'] return compute_flow_rate(l1, l2, a, az12) def compute_q23(ds): l2 = ds['l2'] l3 = ds['l3'] return compute_flow_rate(l2, l3, a, az23) def Env_scenario1(ds): newds = ds.copy() q1 = ds['q1'] q2 = ds['q2'] q3 = ds['q3'] newds['q2'] = max(0.0, rnd.normal(q_med, q2_dev)) q12 = compute_q12(ds) q23 = compute_q23(ds) newds['l1'] = max(0.0 , ds['l1'] + q1*t_step - q12*t_step) newds['l2'] = max(0.0 , ds['l2'] + q12*t_step - q23*t_step) newds['l3'] = max(0.0 , ds['l3'] + q2*t_step + q23*t_step - q3*t_step) return newds def Env_scenario2(ds): newds = ds.copy() q1 = ds['q1'] q2 = ds['q2'] q3 = ds['q3'] newds['q2'] = min( max(0.0, q2 + rnd.normal(0,1)), q_max) q12 = compute_q12(ds) q23 = compute_q23(ds) newds['l1'] = max(0.0 , ds['l1'] + q1*t_step - q12*t_step) newds['l2'] = max(0.0 , ds['l2'] + q12*t_step - q23*t_step) newds['l3'] = max(0.0 , ds['l3'] + q2*t_step + q23*t_step - q3*t_step) return newds ### PENALTY FUNCTIONS def rho_fun(x): v = abs(x-l_goal)/max(l_max-l_goal,l_goal-l_min) return v def ranking_function_1(i, ds): return rho_fun(ds['l1']) def ranking_function_2(i, ds): return rho_fun(ds['l2']) def ranking_function_3(i, ds): return rho_fun(ds['l3']) def ranking_function_max(i, ds): return max(rho_fun(ds['l1']),rho_fun(ds['l2']),rho_fun(ds['l3'])) ### PROCESSES processes = { 'Pin': if_then_else_process(lambda d: d['l1'] > l_goal + d['delta_l'], act_process({'q1': lambda d: max(0.0, d['q1'] - q_step)}, 'Pin'), if_then_else_process(lambda d: d['l1'] < l_goal - d['delta_l'], act_process({'q1': lambda d: min(q_max, d['q1'] + q_step)}, 'Pin'), act_process({}, 'Pin'))), 'Pout': if_then_else_process(lambda d: d['l3'] > l_goal + d['delta_l'], act_process({'q3': lambda d: min(q_max, d['q3'] + q_step)}, 'Pout'), if_then_else_process(lambda d: d['l3'] < l_goal - d['delta_l'], act_process({'q3': lambda d: max(0.0, d['q3'] - q_step)}, 'Pout'), act_process({},'Pout'))) } PTanks = synch_parallel_process(processes['Pin'], processes['Pout']) def init_ds(q1, q2, q3, l1, l2, l3, delta_l): return {'q1': q1, 'q2': q2, 'q3': q3, 'l1': l1, 'l2': l2, 'l3': l3, 'delta_l': delta_l} ### EVALUATION OF STATISTICAL ERROR ds_basic = init_ds(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, delta_l) k = 151 n = 1000 l = 5 M = 100 ds_start = init_ds(0.0, 0.0, 0.0, 5.0, 5.0, 5.0, delta_l) err1000 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 1000) err5000 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 5000) err10000 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) lstl1_1000 = [ [] for i in range(k) ] lstl2_1000 = [ [] for i in range(k) ] lstl3_1000 = [ [] for i in range(k) ] standev_1000 = [ [] for i in range(k) ] standerr_1000 = [ [] for i in range(k) ] zscorel1_1000 = [ [] for i in range(k) ] zscorel2_1000 = [ [] for i in range(k) ] zscorel3_1000 = [ [] for i in range(k) ] lstl3_5000 = [ [] for i in range(k) ] standev_5000 = [ [] for i in range(k) ] standerr_5000 = [ [] for i in range(k) ] zscorel3_5000 = [ [] for i in range(k) ] lstl3_10000 = [ [] for i in range(k) ] standev_10000 = [ [] for i in range(k) ] standerr_10000 = [ [] for i in range(k) ] zscorel3_10000 = [ [] for i in range(k) ] for i in range(k): lstl3_1000[i] = list(map(lambda ds: ds['l3'], err1000[i])) standev_1000[i] = numpy.std(lstl3_1000[i]) standerr_1000[i] = standev_1000[i]/ numpy.sqrt(1000) lstl3_5000[i] = list(map(lambda ds: ds['l3'], err5000[i])) standev_5000[i] = numpy.std(lstl3_5000[i]) standerr_5000[i] = standev_5000[i]/ numpy.sqrt(5000) lstl3_10000[i] = list(map(lambda ds: ds['l3'], err10000[i])) standev_10000[i] = numpy.std(lstl3_10000[i]) standerr_10000[i] = standev_10000[i]/ numpy.sqrt(10000) fix, ax = plt.subplots() ax.plot(range(0,k),standev_1000,label="N = 1000") ax.plot(range(0,k),standev_5000,label="N = 5000") ax.plot(range(0,k),standev_10000,label="N = 10000") legend = ax.legend() plt.title("Standard deviation") plt.savefig("tanks_SD.png") plt.show() fix, ax = plt.subplots() ax.plot(range(0,k),standerr_1000,label="N = 1000") ax.plot(range(0,k),standerr_5000,label="N = 5000") ax.plot(range(0,k),standerr_10000,label="N = 10000") legend = ax.legend() plt.title("Standard error of the mean") plt.savefig("tanks_SEM.png") plt.show() print("I will now proceed to compute several simulations to obtain the analysis of the error, please wait") expected1 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected2 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected3 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected4 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected5 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected6 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected7 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected8 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected9 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) expected10 = simulate(processes, Env_scenario1, PTanks, ds_basic, k, 10000) print("Simulations completed. Next we compute the expected value of the (real) distribution") expectedl1_1 = [ [] for i in range(k) ] expectedl2_1 = [ [] for i in range(k) ] expectedl3_1 = [ [] for i in range(k) ] expectedl1_2 = [ [] for i in range(k) ] expectedl2_2 = [ [] for i in range(k) ] expectedl3_2 = [ [] for i in range(k) ] expectedl1_3 = [ [] for i in range(k) ] expectedl2_3 = [ [] for i in range(k) ] expectedl3_3 = [ [] for i in range(k) ] expectedl1_4 = [ [] for i in range(k) ] expectedl2_4 = [ [] for i in range(k) ] expectedl3_4 = [ [] for i in range(k) ] expectedl1_5 = [ [] for i in range(k) ] expectedl2_5 = [ [] for i in range(k) ] expectedl3_5 = [ [] for i in range(k) ] expectedl1_6 = [ [] for i in range(k) ] expectedl2_6 = [ [] for i in range(k) ] expectedl3_6 = [ [] for i in range(k) ] expectedl1_7 = [ [] for i in range(k) ] expectedl2_7 = [ [] for i in range(k) ] expectedl3_7 = [ [] for i in range(k) ] expectedl1_8 = [ [] for i in range(k) ] expectedl2_8 = [ [] for i in range(k) ] expectedl3_8 = [ [] for i in range(k) ] expectedl1_9 = [ [] for i in range(k) ] expectedl2_9 = [ [] for i in range(k) ] expectedl3_9 = [ [] for i in range(k) ] expectedl1_10 = [ [] for i in range(k) ] expectedl2_10 = [ [] for i in range(k) ] expectedl3_10 = [ [] for i in range(k) ] for i in range (0,k): expectedl1_1[i] = list(map(lambda ds: ds['l1'], expected1[i])) expectedl1_2[i] = list(map(lambda ds: ds['l1'], expected2[i])) expectedl1_3[i] = list(map(lambda ds: ds['l1'], expected3[i])) expectedl1_4[i] = list(map(lambda ds: ds['l1'], expected4[i])) expectedl1_5[i] = list(map(lambda ds: ds['l1'], expected5[i])) expectedl1_6[i] = list(map(lambda ds: ds['l1'], expected6[i])) expectedl1_7[i] = list(map(lambda ds: ds['l1'], expected7[i])) expectedl1_8[i] = list(map(lambda ds: ds['l1'], expected8[i])) expectedl1_9[i] = list(map(lambda ds: ds['l1'], expected9[i])) expectedl1_10[i] = list(map(lambda ds: ds['l1'], expected10[i])) expectedl2_1[i] = list(map(lambda ds: ds['l2'], expected1[i])) expectedl2_2[i] = list(map(lambda ds: ds['l2'], expected2[i])) expectedl2_3[i] = list(map(lambda ds: ds['l2'], expected3[i])) expectedl2_4[i] = list(map(lambda ds: ds['l2'], expected4[i])) expectedl2_5[i] = list(map(lambda ds: ds['l2'], expected5[i])) expectedl2_6[i] = list(map(lambda ds: ds['l2'], expected6[i])) expectedl2_7[i] = list(map(lambda ds: ds['l2'], expected7[i])) expectedl2_8[i] = list(map(lambda ds: ds['l2'], expected8[i])) expectedl2_9[i] = list(map(lambda ds: ds['l2'], expected9[i])) expectedl2_10[i] = list(map(lambda ds: ds['l2'], expected10[i])) expectedl3_1[i] = list(map(lambda ds: ds['l3'], expected1[i])) expectedl3_2[i] = list(map(lambda ds: ds['l3'], expected2[i])) expectedl3_3[i] = list(map(lambda ds: ds['l3'], expected3[i])) expectedl3_4[i] = list(map(lambda ds: ds['l3'], expected4[i])) expectedl3_5[i] = list(map(lambda ds: ds['l3'], expected5[i])) expectedl3_6[i] = list(map(lambda ds: ds['l3'], expected6[i])) expectedl3_7[i] = list(map(lambda ds: ds['l3'], expected7[i])) expectedl3_8[i] = list(map(lambda ds: ds['l3'], expected8[i])) expectedl3_9[i] = list(map(lambda ds: ds['l3'], expected9[i])) expectedl3_10[i] = list(map(lambda ds: ds['l3'], expected10[i])) expected_mean1 = [ [] for i in range(k) ] expected_mean2 = [ [] for i in range(k) ] expected_mean3 = [ [] for i in range(k) ] for j in range (k): expected_mean1[j] = mean([mean(expectedl1_1[j]),mean(expectedl1_2[j]), mean(expectedl1_3[j]),mean(expectedl1_4[j]), mean(expectedl1_5[j]),mean(expectedl1_6[j]), mean(expectedl1_7[j]),mean(expectedl1_8[j]), mean(expectedl1_9[j]),mean(expectedl1_10[j])]) expected_mean2[j] = mean([mean(expectedl2_1[j]),mean(expectedl2_2[j]), mean(expectedl2_3[j]),mean(expectedl2_4[j]), mean(expectedl2_5[j]),mean(expectedl2_6[j]), mean(expectedl2_7[j]),mean(expectedl2_8[j]), mean(expectedl2_9[j]),mean(expectedl2_10[j])]) expected_mean3[j] = mean([mean(expectedl3_1[j]),mean(expectedl3_2[j]), mean(expectedl3_3[j]),mean(expectedl3_4[j]), mean(expectedl3_5[j]),mean(expectedl3_6[j]), mean(expectedl3_7[j]),mean(expectedl3_8[j]), mean(expectedl3_9[j]),mean(expectedl3_10[j])]) print("Mean computed. Finally we evaluate the z-scores") for i in range (0,10): zscorel3_1000[i] = 0 zscorel3_5000[i] = 0 zscorel3_10000[i] = 0 for i in range (10,k): zscorel3_1000[i] = (mean(lstl3_1000[i]) - expected_mean3[i]) / standerr_1000[i] zscorel3_5000[i] = (mean(lstl3_5000[i]) - expected_mean3[i]) / standerr_5000[i] zscorel3_10000[i] = (mean(lstl3_10000[i]) - expected_mean3[i]) / standerr_10000[i] limit1 = [ [1.96] for i in range(k) ] limit2 = [ [-1.96] for i in range(k) ] fix, ax = plt.subplots() ax.plot(range(0,k),zscorel3_1000,label="N = 1000") ax.plot(range(0,k),zscorel3_5000,label="N = 5000") ax.plot(range(0,k),zscorel3_10000,label="N = 10000") ax.plot(range(0,k),limit1, 'r--') ax.plot(range(0,k),limit2, 'r--') legend = ax.legend() plt.xlim([10, k]) plt.title("Value of z-score in time") plt.savefig("tanks_zScore.png") plt.show() for i in range(k): lstl1_1000[i] = list(map(lambda ds: ds['l1'], err1000[i])) lstl2_1000[i] = list(map(lambda ds: ds['l2'], err1000[i])) for i in range (0,10): zscorel1_1000[i] = 0 zscorel2_1000[i] = 0 for i in range (10,k): zscorel1_1000[i] = (mean(lstl1_1000[i]) - expected_mean1[i])*numpy.sqrt(1000)/numpy.std(lstl1_1000[i]) zscorel2_1000[i] = (mean(lstl2_1000[i]) - expected_mean2[i])*numpy.sqrt(1000)/numpy.std(lstl2_1000[i]) fix, ax = plt.subplots() ax.plot(range(0,k),zscorel1_1000,label="z-score on l1") ax.plot(range(0,k),zscorel2_1000,label="z-score on l2") ax.plot(range(0,k),zscorel3_1000,label="z-score on l3") legend = ax.legend() plt.xlim([10, k]) plt.title("Comparison of the z-scores for the levels of water (N = 1000)") plt.savefig("tanks_total.png") plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "matplotlib.pyplot.show", "numpy.std", "statistics.mean", "numpy.random.normal", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.sqrt" ]
[((5011, 5025), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5023, 5025), True, 'import matplotlib.pyplot as plt\n'), ((5204, 5235), 'matplotlib.pyplot.title', 'plt.title', (['"""Standard deviation"""'], {}), "('Standard deviation')\n", (5213, 5235), True, 'import matplotlib.pyplot as plt\n'), ((5237, 5264), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""tanks_SD.png"""'], {}), "('tanks_SD.png')\n", (5248, 5264), True, 'import matplotlib.pyplot as plt\n'), ((5266, 5276), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5274, 5276), True, 'import matplotlib.pyplot as plt\n'), ((5290, 5304), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5302, 5304), True, 'import matplotlib.pyplot as plt\n'), ((5486, 5525), 'matplotlib.pyplot.title', 'plt.title', (['"""Standard error of the mean"""'], {}), "('Standard error of the mean')\n", (5495, 5525), True, 'import matplotlib.pyplot as plt\n'), ((5527, 5555), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""tanks_SEM.png"""'], {}), "('tanks_SEM.png')\n", (5538, 5555), True, 'import matplotlib.pyplot as plt\n'), ((5557, 5567), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5565, 5567), True, 'import matplotlib.pyplot as plt\n'), ((11733, 11747), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11745, 11747), True, 'import matplotlib.pyplot as plt\n'), ((11999, 12016), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[10, k]'], {}), '([10, k])\n', (12007, 12016), True, 'import matplotlib.pyplot as plt\n'), ((12018, 12055), 'matplotlib.pyplot.title', 'plt.title', (['"""Value of z-score in time"""'], {}), "('Value of z-score in time')\n", (12027, 12055), True, 'import matplotlib.pyplot as plt\n'), ((12057, 12088), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""tanks_zScore.png"""'], {}), "('tanks_zScore.png')\n", (12068, 12088), True, 'import matplotlib.pyplot as plt\n'), ((12090, 12100), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12098, 12100), True, 'import matplotlib.pyplot as plt\n'), ((12600, 12614), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (12612, 12614), True, 'import matplotlib.pyplot as plt\n'), ((12809, 12826), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[10, k]'], {}), '([10, k])\n', (12817, 12826), True, 'import matplotlib.pyplot as plt\n'), ((12828, 12902), 'matplotlib.pyplot.title', 'plt.title', (['"""Comparison of the z-scores for the levels of water (N = 1000)"""'], {}), "('Comparison of the z-scores for the levels of water (N = 1000)')\n", (12837, 12902), True, 'import matplotlib.pyplot as plt\n'), ((12904, 12934), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""tanks_total.png"""'], {}), "('tanks_total.png')\n", (12915, 12934), True, 'import matplotlib.pyplot as plt\n'), ((12936, 12946), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12944, 12946), True, 'import matplotlib.pyplot as plt\n'), ((4561, 4585), 'numpy.std', 'numpy.std', (['lstl3_1000[i]'], {}), '(lstl3_1000[i])\n', (4570, 4585), False, 'import numpy\n'), ((4731, 4755), 'numpy.std', 'numpy.std', (['lstl3_5000[i]'], {}), '(lstl3_5000[i])\n', (4740, 4755), False, 'import numpy\n'), ((4904, 4929), 'numpy.std', 'numpy.std', (['lstl3_10000[i]'], {}), '(lstl3_10000[i])\n', (4913, 4929), False, 'import numpy\n'), ((944, 969), 'numpy.random.normal', 'rnd.normal', (['q_med', 'q2_dev'], {}), '(q_med, q2_dev)\n', (954, 969), True, 'import numpy.random as rnd\n'), ((4627, 4643), 'numpy.sqrt', 'numpy.sqrt', (['(1000)'], {}), '(1000)\n', (4637, 4643), False, 'import numpy\n'), ((4797, 4813), 'numpy.sqrt', 'numpy.sqrt', (['(5000)'], {}), '(5000)\n', (4807, 4813), False, 'import numpy\n'), ((4973, 4990), 'numpy.sqrt', 'numpy.sqrt', (['(10000)'], {}), '(10000)\n', (4983, 4990), False, 'import numpy\n'), ((12450, 12474), 'numpy.std', 'numpy.std', (['lstl1_1000[i]'], {}), '(lstl1_1000[i])\n', (12459, 12474), False, 'import numpy\n'), ((12558, 12582), 'numpy.std', 'numpy.std', (['lstl2_1000[i]'], {}), '(lstl2_1000[i])\n', (12567, 12582), False, 'import numpy\n'), ((500, 519), 'numpy.sqrt', 'numpy.sqrt', (['(x1 - x2)'], {}), '(x1 - x2)\n', (510, 519), False, 'import numpy\n'), ((568, 587), 'numpy.sqrt', 'numpy.sqrt', (['(x2 - x1)'], {}), '(x2 - x1)\n', (578, 587), False, 'import numpy\n'), ((10071, 10092), 'statistics.mean', 'mean', (['expectedl1_1[j]'], {}), '(expectedl1_1[j])\n', (10075, 10092), False, 'from statistics import mean\n'), ((10093, 10114), 'statistics.mean', 'mean', (['expectedl1_2[j]'], {}), '(expectedl1_2[j])\n', (10097, 10114), False, 'from statistics import mean\n'), ((10147, 10168), 'statistics.mean', 'mean', (['expectedl1_3[j]'], {}), '(expectedl1_3[j])\n', (10151, 10168), False, 'from statistics import mean\n'), ((10169, 10190), 'statistics.mean', 'mean', (['expectedl1_4[j]'], {}), '(expectedl1_4[j])\n', (10173, 10190), False, 'from statistics import mean\n'), ((10223, 10244), 'statistics.mean', 'mean', (['expectedl1_5[j]'], {}), '(expectedl1_5[j])\n', (10227, 10244), False, 'from statistics import mean\n'), ((10245, 10266), 'statistics.mean', 'mean', (['expectedl1_6[j]'], {}), '(expectedl1_6[j])\n', (10249, 10266), False, 'from statistics import mean\n'), ((10299, 10320), 'statistics.mean', 'mean', (['expectedl1_7[j]'], {}), '(expectedl1_7[j])\n', (10303, 10320), False, 'from statistics import mean\n'), ((10321, 10342), 'statistics.mean', 'mean', (['expectedl1_8[j]'], {}), '(expectedl1_8[j])\n', (10325, 10342), False, 'from statistics import mean\n'), ((10375, 10396), 'statistics.mean', 'mean', (['expectedl1_9[j]'], {}), '(expectedl1_9[j])\n', (10379, 10396), False, 'from statistics import mean\n'), ((10397, 10419), 'statistics.mean', 'mean', (['expectedl1_10[j]'], {}), '(expectedl1_10[j])\n', (10401, 10419), False, 'from statistics import mean\n'), ((10453, 10474), 'statistics.mean', 'mean', (['expectedl2_1[j]'], {}), '(expectedl2_1[j])\n', (10457, 10474), False, 'from statistics import mean\n'), ((10475, 10496), 'statistics.mean', 'mean', (['expectedl2_2[j]'], {}), '(expectedl2_2[j])\n', (10479, 10496), False, 'from statistics import mean\n'), ((10529, 10550), 'statistics.mean', 'mean', (['expectedl2_3[j]'], {}), '(expectedl2_3[j])\n', (10533, 10550), False, 'from statistics import mean\n'), ((10551, 10572), 'statistics.mean', 'mean', (['expectedl2_4[j]'], {}), '(expectedl2_4[j])\n', (10555, 10572), False, 'from statistics import mean\n'), ((10605, 10626), 'statistics.mean', 'mean', (['expectedl2_5[j]'], {}), '(expectedl2_5[j])\n', (10609, 10626), False, 'from statistics import mean\n'), ((10627, 10648), 'statistics.mean', 'mean', (['expectedl2_6[j]'], {}), '(expectedl2_6[j])\n', (10631, 10648), False, 'from statistics import mean\n'), ((10681, 10702), 'statistics.mean', 'mean', (['expectedl2_7[j]'], {}), '(expectedl2_7[j])\n', (10685, 10702), False, 'from statistics import mean\n'), ((10703, 10724), 'statistics.mean', 'mean', (['expectedl2_8[j]'], {}), '(expectedl2_8[j])\n', (10707, 10724), False, 'from statistics import mean\n'), ((10757, 10778), 'statistics.mean', 'mean', (['expectedl2_9[j]'], {}), '(expectedl2_9[j])\n', (10761, 10778), False, 'from statistics import mean\n'), ((10779, 10801), 'statistics.mean', 'mean', (['expectedl2_10[j]'], {}), '(expectedl2_10[j])\n', (10783, 10801), False, 'from statistics import mean\n'), ((10835, 10856), 'statistics.mean', 'mean', (['expectedl3_1[j]'], {}), '(expectedl3_1[j])\n', (10839, 10856), False, 'from statistics import mean\n'), ((10857, 10878), 'statistics.mean', 'mean', (['expectedl3_2[j]'], {}), '(expectedl3_2[j])\n', (10861, 10878), False, 'from statistics import mean\n'), ((10911, 10932), 'statistics.mean', 'mean', (['expectedl3_3[j]'], {}), '(expectedl3_3[j])\n', (10915, 10932), False, 'from statistics import mean\n'), ((10933, 10954), 'statistics.mean', 'mean', (['expectedl3_4[j]'], {}), '(expectedl3_4[j])\n', (10937, 10954), False, 'from statistics import mean\n'), ((10987, 11008), 'statistics.mean', 'mean', (['expectedl3_5[j]'], {}), '(expectedl3_5[j])\n', (10991, 11008), False, 'from statistics import mean\n'), ((11009, 11030), 'statistics.mean', 'mean', (['expectedl3_6[j]'], {}), '(expectedl3_6[j])\n', (11013, 11030), False, 'from statistics import mean\n'), ((11063, 11084), 'statistics.mean', 'mean', (['expectedl3_7[j]'], {}), '(expectedl3_7[j])\n', (11067, 11084), False, 'from statistics import mean\n'), ((11085, 11106), 'statistics.mean', 'mean', (['expectedl3_8[j]'], {}), '(expectedl3_8[j])\n', (11089, 11106), False, 'from statistics import mean\n'), ((11139, 11160), 'statistics.mean', 'mean', (['expectedl3_9[j]'], {}), '(expectedl3_9[j])\n', (11143, 11160), False, 'from statistics import mean\n'), ((11161, 11183), 'statistics.mean', 'mean', (['expectedl3_10[j]'], {}), '(expectedl3_10[j])\n', (11165, 11183), False, 'from statistics import mean\n'), ((11406, 11425), 'statistics.mean', 'mean', (['lstl3_1000[i]'], {}), '(lstl3_1000[i])\n', (11410, 11425), False, 'from statistics import mean\n'), ((11491, 11510), 'statistics.mean', 'mean', (['lstl3_5000[i]'], {}), '(lstl3_5000[i])\n', (11495, 11510), False, 'from statistics import mean\n'), ((11577, 11597), 'statistics.mean', 'mean', (['lstl3_10000[i]'], {}), '(lstl3_10000[i])\n', (11581, 11597), False, 'from statistics import mean\n'), ((12433, 12449), 'numpy.sqrt', 'numpy.sqrt', (['(1000)'], {}), '(1000)\n', (12443, 12449), False, 'import numpy\n'), ((12541, 12557), 'numpy.sqrt', 'numpy.sqrt', (['(1000)'], {}), '(1000)\n', (12551, 12557), False, 'import numpy\n'), ((484, 501), 'numpy.sqrt', 'numpy.sqrt', (['(2 * g)'], {}), '(2 * g)\n', (494, 501), False, 'import numpy\n'), ((552, 569), 'numpy.sqrt', 'numpy.sqrt', (['(2 * g)'], {}), '(2 * g)\n', (562, 569), False, 'import numpy\n'), ((1395, 1411), 'numpy.random.normal', 'rnd.normal', (['(0)', '(1)'], {}), '(0, 1)\n', (1405, 1411), True, 'import numpy.random as rnd\n'), ((12392, 12411), 'statistics.mean', 'mean', (['lstl1_1000[i]'], {}), '(lstl1_1000[i])\n', (12396, 12411), False, 'from statistics import mean\n'), ((12500, 12519), 'statistics.mean', 'mean', (['lstl2_1000[i]'], {}), '(lstl2_1000[i])\n', (12504, 12519), False, 'from statistics import mean\n')]
# coding: utf-8 from PIL import Image import numpy as np def up_side_down(array): up_side_down=[] for i in range(len(array)-1,-1,-1): up_side_down.append(array[i]) up_side_down=np.array(up_side_down) up_side_down = Image.fromarray(up_side_down) return up_side_down def right_side_left(array): right_side_left=[] for i in range(len(array)): right_side_left.append([]) for j in range(len(array)-1,-1,-1): right_side_left[i].append(array[i][j]) right_side_left=np.array(right_side_left) right_side_left = Image.fromarray(right_side_left) return right_side_left def diagonally_mirrored(array): output=[] diagonally_mirrored=np.array(right_side_left(array)) for i in range(len(diagonally_mirrored)-1,-1,-1): output.append(diagonally_mirrored[:,i]) output=np.array(output) output = Image.fromarray(output) return output lena = Image.open("lena.bmp") array=np.array(lena) a=up_side_down(array) b=right_side_left(array) c=diagonally_mirrored(array) a.show(),b.show(),c.show()
[ "PIL.Image.fromarray", "numpy.array", "PIL.Image.open" ]
[((934, 956), 'PIL.Image.open', 'Image.open', (['"""lena.bmp"""'], {}), "('lena.bmp')\n", (944, 956), False, 'from PIL import Image\n'), ((963, 977), 'numpy.array', 'np.array', (['lena'], {}), '(lena)\n', (971, 977), True, 'import numpy as np\n'), ((199, 221), 'numpy.array', 'np.array', (['up_side_down'], {}), '(up_side_down)\n', (207, 221), True, 'import numpy as np\n'), ((241, 270), 'PIL.Image.fromarray', 'Image.fromarray', (['up_side_down'], {}), '(up_side_down)\n', (256, 270), False, 'from PIL import Image\n'), ((529, 554), 'numpy.array', 'np.array', (['right_side_left'], {}), '(right_side_left)\n', (537, 554), True, 'import numpy as np\n'), ((577, 609), 'PIL.Image.fromarray', 'Image.fromarray', (['right_side_left'], {}), '(right_side_left)\n', (592, 609), False, 'from PIL import Image\n'), ((854, 870), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (862, 870), True, 'import numpy as np\n'), ((884, 907), 'PIL.Image.fromarray', 'Image.fromarray', (['output'], {}), '(output)\n', (899, 907), False, 'from PIL import Image\n')]
import os, time, sys import numpy as np import pandas as pd from matplotlib import pyplot as plt from scipy.stats import bayes_mvs as bayesest sys.path.insert(0, '../../PyEcoLib') from simulator import Simulator mean_size = 3 # micron doubling_time = 18 #min tmax = 180 #min sample_time = 2 #min div_steps = 10 ncells = 5000 gr = np.log(2)/doubling_time CV2div = 0.001 CV2gr = 0.01 CV2sz = 0.015 v0 = mean_size*np.random.gamma(shape=1/CV2sz,scale=CV2sz,size=ncells) if not os.path.exists('./data'): os.makedirs('./data') if not os.path.exists('./figures'): os.makedirs('./figures') start = time.time() sim = Simulator(sample_time = sample_time, ncells=ncells, gr = gr, sb=mean_size, steps = div_steps, CV2div = CV2div, CV2gr = CV2gr, V0array = v0) sim.szdyn(tmax = tmax, sample_time= 0.1*doubling_time, nameCRM = "./data/dataCRMnoisy.csv") print('It took', np.int(time.time()-start), 'seconds.') data1=pd.read_csv("./data/dataCRMnoisy.csv") timearray=data1.time.unique() mnszarray=[] cvszarray=[] errcv2sz=[] errmnsz=[] df=data1 del df['time'] for m in range(len(df)): szs=df.loc[m, :].values.tolist() mean_cntr, var_cntr, std_cntr = bayesest(szs,alpha=0.95) mnszarray.append(np.mean(szs)) errmnsz.append(mean_cntr[1][1]-mean_cntr[0]) cvszarray.append(np.var(szs)/np.mean(szs)**2) errv=(var_cntr[1][1]-var_cntr[0])/mean_cntr[0]**2+2*(mean_cntr[1][1]-mean_cntr[0])*var_cntr[0]/mean_cntr[0]**3 errcv2sz.append(errv) fig, ax = plt.subplots(1,2, figsize=(12,4)) ax[0].plot(np.array(timearray)/doubling_time,np.array(mnszarray)) ax[0].fill_between(np.array(timearray)/doubling_time,np.array(mnszarray)-np.array(errmnsz),np.array(mnszarray)+np.array(errmnsz), alpha=1, edgecolor='#4db8ff', facecolor='#4db8ff',linewidth=0,label="SSA") ax[1].plot(np.array(timearray)/doubling_time,np.array(cvszarray)) ax[1].fill_between(np.array(timearray)/doubling_time,np.array(cvszarray)-np.array(errcv2sz),np.array(cvszarray)+np.array(errcv2sz), alpha=1, edgecolor='#4db8ff', facecolor='#4db8ff',linewidth=0) ax[0].set_ylabel("$s$ $(\mu m)$",size=20) ax[1].set_ylabel("$C_V^2(s)$",size=20) ax[0].set_xlabel(r"$t/\tau$",size=20) ax[1].set_xlabel(r"$t/\tau$",size=20) ax[0].set_ylim([np.min(mnszarray),1.1*np.max(mnszarray)]) ax[1].set_ylim([0,1.1*np.max(cvszarray)]) for l in [0,1]: ax[l].set_xlim([0,7]) taqui=np.arange(0,8,step=1) ax[l].set_xticks(np.array(taqui)) ax[l].grid() ax[l].tick_params(axis='x', labelsize=15) ax[l].tick_params(axis='y', labelsize=15) for axis in ['bottom','left']: ax[l].spines[axis].set_linewidth(2) ax[l].tick_params(axis='both', width=2,length=6) for axis in ['top','right']: ax[l].spines[axis].set_linewidth(0) ax[l].tick_params(axis='both', width=0,length=6) plt.subplots_adjust(hspace=0.3,wspace=0.3) if not os.path.exists('./figures'): os.makedirs('./figures') #ax[0].legend(fontsize=15) plt.savefig('./figures/size_statisticsnoisy.svg',bbox_inches='tight') plt.savefig('./figures/size_statisticsnoisy.png',bbox_inches='tight')
[ "numpy.log", "os.makedirs", "pandas.read_csv", "os.path.exists", "sys.path.insert", "numpy.var", "time.time", "numpy.random.gamma", "numpy.min", "numpy.mean", "numpy.array", "numpy.arange", "numpy.max", "matplotlib.pyplot.subplots_adjust", "scipy.stats.bayes_mvs", "matplotlib.pyplot.su...
[((144, 180), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../PyEcoLib"""'], {}), "(0, '../../PyEcoLib')\n", (159, 180), False, 'import os, time, sys\n'), ((605, 616), 'time.time', 'time.time', ([], {}), '()\n', (614, 616), False, 'import os, time, sys\n'), ((623, 754), 'simulator.Simulator', 'Simulator', ([], {'sample_time': 'sample_time', 'ncells': 'ncells', 'gr': 'gr', 'sb': 'mean_size', 'steps': 'div_steps', 'CV2div': 'CV2div', 'CV2gr': 'CV2gr', 'V0array': 'v0'}), '(sample_time=sample_time, ncells=ncells, gr=gr, sb=mean_size,\n steps=div_steps, CV2div=CV2div, CV2gr=CV2gr, V0array=v0)\n', (632, 754), False, 'from simulator import Simulator\n'), ((918, 956), 'pandas.read_csv', 'pd.read_csv', (['"""./data/dataCRMnoisy.csv"""'], {}), "('./data/dataCRMnoisy.csv')\n", (929, 956), True, 'import pandas as pd\n'), ((1470, 1505), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(12, 4)'}), '(1, 2, figsize=(12, 4))\n', (1482, 1505), True, 'from matplotlib import pyplot as plt\n'), ((2820, 2863), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.3)', 'wspace': '(0.3)'}), '(hspace=0.3, wspace=0.3)\n', (2839, 2863), True, 'from matplotlib import pyplot as plt\n'), ((2955, 3025), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./figures/size_statisticsnoisy.svg"""'], {'bbox_inches': '"""tight"""'}), "('./figures/size_statisticsnoisy.svg', bbox_inches='tight')\n", (2966, 3025), True, 'from matplotlib import pyplot as plt\n'), ((3025, 3095), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./figures/size_statisticsnoisy.png"""'], {'bbox_inches': '"""tight"""'}), "('./figures/size_statisticsnoisy.png', bbox_inches='tight')\n", (3036, 3095), True, 'from matplotlib import pyplot as plt\n'), ((333, 342), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (339, 342), True, 'import numpy as np\n'), ((415, 473), 'numpy.random.gamma', 'np.random.gamma', ([], {'shape': '(1 / CV2sz)', 'scale': 'CV2sz', 'size': 'ncells'}), '(shape=1 / CV2sz, scale=CV2sz, size=ncells)\n', (430, 473), True, 'import numpy as np\n'), ((478, 502), 'os.path.exists', 'os.path.exists', (['"""./data"""'], {}), "('./data')\n", (492, 502), False, 'import os, time, sys\n'), ((508, 529), 'os.makedirs', 'os.makedirs', (['"""./data"""'], {}), "('./data')\n", (519, 529), False, 'import os, time, sys\n'), ((537, 564), 'os.path.exists', 'os.path.exists', (['"""./figures"""'], {}), "('./figures')\n", (551, 564), False, 'import os, time, sys\n'), ((570, 594), 'os.makedirs', 'os.makedirs', (['"""./figures"""'], {}), "('./figures')\n", (581, 594), False, 'import os, time, sys\n'), ((1159, 1184), 'scipy.stats.bayes_mvs', 'bayesest', (['szs'], {'alpha': '(0.95)'}), '(szs, alpha=0.95)\n', (1167, 1184), True, 'from scipy.stats import bayes_mvs as bayesest\n'), ((1549, 1568), 'numpy.array', 'np.array', (['mnszarray'], {}), '(mnszarray)\n', (1557, 1568), True, 'import numpy as np\n'), ((1839, 1858), 'numpy.array', 'np.array', (['cvszarray'], {}), '(cvszarray)\n', (1847, 1858), True, 'import numpy as np\n'), ((2381, 2404), 'numpy.arange', 'np.arange', (['(0)', '(8)'], {'step': '(1)'}), '(0, 8, step=1)\n', (2390, 2404), True, 'import numpy as np\n'), ((2870, 2897), 'os.path.exists', 'os.path.exists', (['"""./figures"""'], {}), "('./figures')\n", (2884, 2897), False, 'import os, time, sys\n'), ((2903, 2927), 'os.makedirs', 'os.makedirs', (['"""./figures"""'], {}), "('./figures')\n", (2914, 2927), False, 'import os, time, sys\n'), ((1205, 1217), 'numpy.mean', 'np.mean', (['szs'], {}), '(szs)\n', (1212, 1217), True, 'import numpy as np\n'), ((1515, 1534), 'numpy.array', 'np.array', (['timearray'], {}), '(timearray)\n', (1523, 1534), True, 'import numpy as np\n'), ((1589, 1608), 'numpy.array', 'np.array', (['timearray'], {}), '(timearray)\n', (1597, 1608), True, 'import numpy as np\n'), ((1623, 1642), 'numpy.array', 'np.array', (['mnszarray'], {}), '(mnszarray)\n', (1631, 1642), True, 'import numpy as np\n'), ((1643, 1660), 'numpy.array', 'np.array', (['errmnsz'], {}), '(errmnsz)\n', (1651, 1660), True, 'import numpy as np\n'), ((1661, 1680), 'numpy.array', 'np.array', (['mnszarray'], {}), '(mnszarray)\n', (1669, 1680), True, 'import numpy as np\n'), ((1681, 1698), 'numpy.array', 'np.array', (['errmnsz'], {}), '(errmnsz)\n', (1689, 1698), True, 'import numpy as np\n'), ((1805, 1824), 'numpy.array', 'np.array', (['timearray'], {}), '(timearray)\n', (1813, 1824), True, 'import numpy as np\n'), ((1879, 1898), 'numpy.array', 'np.array', (['timearray'], {}), '(timearray)\n', (1887, 1898), True, 'import numpy as np\n'), ((1913, 1932), 'numpy.array', 'np.array', (['cvszarray'], {}), '(cvszarray)\n', (1921, 1932), True, 'import numpy as np\n'), ((1933, 1951), 'numpy.array', 'np.array', (['errcv2sz'], {}), '(errcv2sz)\n', (1941, 1951), True, 'import numpy as np\n'), ((1952, 1971), 'numpy.array', 'np.array', (['cvszarray'], {}), '(cvszarray)\n', (1960, 1971), True, 'import numpy as np\n'), ((1972, 1990), 'numpy.array', 'np.array', (['errcv2sz'], {}), '(errcv2sz)\n', (1980, 1990), True, 'import numpy as np\n'), ((2245, 2262), 'numpy.min', 'np.min', (['mnszarray'], {}), '(mnszarray)\n', (2251, 2262), True, 'import numpy as np\n'), ((2424, 2439), 'numpy.array', 'np.array', (['taqui'], {}), '(taqui)\n', (2432, 2439), True, 'import numpy as np\n'), ((879, 890), 'time.time', 'time.time', ([], {}), '()\n', (888, 890), False, 'import os, time, sys\n'), ((1289, 1300), 'numpy.var', 'np.var', (['szs'], {}), '(szs)\n', (1295, 1300), True, 'import numpy as np\n'), ((2267, 2284), 'numpy.max', 'np.max', (['mnszarray'], {}), '(mnszarray)\n', (2273, 2284), True, 'import numpy as np\n'), ((2309, 2326), 'numpy.max', 'np.max', (['cvszarray'], {}), '(cvszarray)\n', (2315, 2326), True, 'import numpy as np\n'), ((1301, 1313), 'numpy.mean', 'np.mean', (['szs'], {}), '(szs)\n', (1308, 1313), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np import pandas as pd from pyfaidx import Fasta from functools import partial from random import randrange # efficient way for one hot encoding DNA sequence from string # modified from https://gist.github.com/hannes-brt/54ca5d4094b3d96237fa2e820c0945dd embed = np.zeros([89, 4], np.float32) embed[ord('A')] = np.array([1, 0, 0, 0]) embed[ord('C')] = np.array([0, 1, 0, 0]) embed[ord('G')] = np.array([0, 0, 1, 0]) embed[ord('T')] = np.array([0, 0, 0, 1]) embed[ord('a')] = np.array([1, 0, 0, 0]) embed[ord('c')] = np.array([0, 1, 0, 0]) embed[ord('g')] = np.array([0, 0, 1, 0]) embed[ord('t')] = np.array([0, 0, 0, 1]) embed[ord('.')] = np.array([.25, .25, .25, .25]) embedding_table = tf.convert_to_tensor(embed) def one_hot_encode_seq(dna_input, embed, name = "encode_seq"): with tf.name_scope(name): b = bytearray() b.extend(map(ord, str(dna_input))) t = tf.convert_to_tensor(b) t = tf.cast(t, tf.int32) encoded_dna = tf.nn.embedding_lookup(embedding_table, t) return encoded_dna # fetching longer context based on fasta file and pyfaidx def get_datum( ind, fasta_ref, bed_df, context_length = None, rand_shift_range = None ): row = bed_df.iloc[ind] chrname, start, end, t = bed_df.iloc[ind].tolist() interval_length = end - start chromosome = fasta_ref[chrname] chromosome_length = len(chromosome) if rand_shift_range is not None: min_shift, max_shift = rand_shift_range adj_min_shift = max(start + min_shift, 0) - start adj_max_shift = min(end + max_shift, chromosome_length) - end left_padding = adj_min_shift - min_shift right_padding = max_shift - adj_max_shift start += adj_min_shift end += adj_max_shift if context_length is None or context_length <= interval_length: seq = chromosome[start:end] return one_hot_encode_seq(seq, embed) left_padding = right_padding = 0 extra_seq = context_length - interval_length extra_left_seq = extra_seq // 2 extra_right_seq = extra_seq - extra_left_seq start -= extra_left_seq end += extra_right_seq if start < 0: left_padding = -start start = 0 if end > chromosome_length: right_padding = end - chromosome_length end = chromosome_length seq = ('.' * left_padding) + str(chromosome[start:end]) + ('.' * right_padding) return one_hot_encode_seq(seq, embed) def get_dna_sample( bed_file, fasta_file, filter_type = None, context_length = None, rand_shift_range = (-2, 2) ): df = pd.read_csv(bed_file, sep = '\t', header = None) if filter_type is not None: df = df[df[3] == filter_type] fasta = Fasta(fasta_file, sequence_always_upper = True) yield_data_fn = partial(get_datum, fasta_ref = fasta, bed_df = df, context_length = context_length, rand_shift_range = rand_shift_range) def inner(): for ind in range(len(df)): yield yield_data_fn(ind) return inner # main function if __name__ == '__main__': generator_fn = get_dna_sample( bed_file = './human-sequences.bed', fasta_file = './hg38.ml.fa', filter_type = 'valid', context_length = 196_608 ) dataset = tf.data.Dataset.from_generator(generator_fn, tf.float32) print(next(iter(dataset)).shape)
[ "functools.partial", "pandas.read_csv", "tensorflow.convert_to_tensor", "tensorflow.nn.embedding_lookup", "pyfaidx.Fasta", "numpy.zeros", "tensorflow.cast", "numpy.array", "tensorflow.data.Dataset.from_generator", "tensorflow.name_scope" ]
[((305, 334), 'numpy.zeros', 'np.zeros', (['[89, 4]', 'np.float32'], {}), '([89, 4], np.float32)\n', (313, 334), True, 'import numpy as np\n'), ((353, 375), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (361, 375), True, 'import numpy as np\n'), ((394, 416), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (402, 416), True, 'import numpy as np\n'), ((435, 457), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '([0, 0, 1, 0])\n', (443, 457), True, 'import numpy as np\n'), ((476, 498), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (484, 498), True, 'import numpy as np\n'), ((517, 539), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (525, 539), True, 'import numpy as np\n'), ((558, 580), 'numpy.array', 'np.array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (566, 580), True, 'import numpy as np\n'), ((599, 621), 'numpy.array', 'np.array', (['[0, 0, 1, 0]'], {}), '([0, 0, 1, 0])\n', (607, 621), True, 'import numpy as np\n'), ((640, 662), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (648, 662), True, 'import numpy as np\n'), ((681, 715), 'numpy.array', 'np.array', (['[0.25, 0.25, 0.25, 0.25]'], {}), '([0.25, 0.25, 0.25, 0.25])\n', (689, 715), True, 'import numpy as np\n'), ((731, 758), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['embed'], {}), '(embed)\n', (751, 758), True, 'import tensorflow as tf\n'), ((2519, 2563), 'pandas.read_csv', 'pd.read_csv', (['bed_file'], {'sep': '"""\t"""', 'header': 'None'}), "(bed_file, sep='\\t', header=None)\n", (2530, 2563), True, 'import pandas as pd\n'), ((2644, 2689), 'pyfaidx.Fasta', 'Fasta', (['fasta_file'], {'sequence_always_upper': '(True)'}), '(fasta_file, sequence_always_upper=True)\n', (2649, 2689), False, 'from pyfaidx import Fasta\n'), ((2710, 2827), 'functools.partial', 'partial', (['get_datum'], {'fasta_ref': 'fasta', 'bed_df': 'df', 'context_length': 'context_length', 'rand_shift_range': 'rand_shift_range'}), '(get_datum, fasta_ref=fasta, bed_df=df, context_length=\n context_length, rand_shift_range=rand_shift_range)\n', (2717, 2827), False, 'from functools import partial\n'), ((3150, 3206), 'tensorflow.data.Dataset.from_generator', 'tf.data.Dataset.from_generator', (['generator_fn', 'tf.float32'], {}), '(generator_fn, tf.float32)\n', (3180, 3206), True, 'import tensorflow as tf\n'), ((830, 849), 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), '(name)\n', (843, 849), True, 'import tensorflow as tf\n'), ((918, 941), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['b'], {}), '(b)\n', (938, 941), True, 'import tensorflow as tf\n'), ((950, 970), 'tensorflow.cast', 'tf.cast', (['t', 'tf.int32'], {}), '(t, tf.int32)\n', (957, 970), True, 'import tensorflow as tf\n'), ((989, 1031), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embedding_table', 't'], {}), '(embedding_table, t)\n', (1011, 1031), True, 'import tensorflow as tf\n')]
""" Implementation of the method proposed in the paper: 'Adversarial Attacks on Classification Models for Graphs' by <NAME>, <NAME>, <NAME>, <NAME> Published at ICML 2018 in Stockholm, Sweden. Copyright (C) 2018 <NAME> Technical University of Munich """ #import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import src.netgan.netgan.utils as utils import time import numpy as np from sklearn.metrics import roc_auc_score, average_precision_score #from matplotlib import pyplot as plt tf.logging.set_verbosity(tf.logging.ERROR) class NetGAN: """ NetGAN class, an implicit generative model for graphs using random walks. """ def __init__(self, N, rw_len, walk_generator, generator_layers=[40], discriminator_layers=[30], W_down_generator_size=128, W_down_discriminator_size=128, batch_size=128, noise_dim=16, noise_type="Gaussian", learning_rate=0.0003, disc_iters=3, wasserstein_penalty=10, l2_penalty_generator=1e-7, l2_penalty_discriminator=5e-5, temp_start=5.0, min_temperature=0.5, temperature_decay=1-5e-5, seed=15, gpu_id=0, use_gumbel=True, legacy_generator=False): """ Initialize NetGAN. Parameters ---------- N: int Number of nodes in the graph to generate. rw_len: int Length of random walks to generate. walk_generator: function Function that generates a single random walk and takes no arguments. generator_layers: list of integers, default: [40], i.e. a single layer with 40 units. The layer sizes of the generator LSTM layers discriminator_layers: list of integers, default: [30], i.e. a single layer with 30 units. The sizes of the discriminator LSTM layers W_down_generator_size: int, default: 128 The size of the weight matrix W_down of the generator. See our paper for details. W_down_discriminator_size: int, default: 128 The size of the weight matrix W_down of the discriminator. See our paper for details. batch_size: int, default: 128 The batch size. noise_dim: int, default: 16 The dimension of the random noise that is used as input to the generator. noise_type: str in ["Gaussian", "Uniform], default: "Gaussian" The noise type to feed into the generator. learning_rate: float, default: 0.0003 The learning rate. disc_iters: int, default: 3 The number of discriminator iterations per generator training iteration. wasserstein_penalty: float, default: 10 The Wasserstein gradient penalty applied to the discriminator. See the Wasserstein GAN paper for details. l2_penalty_generator: float, default: 1e-7 L2 penalty on the generator weights. l2_penalty_discriminator: float, default: 5e-5 L2 penalty on the discriminator weights. temp_start: float, default: 5.0 The initial temperature for the Gumbel softmax. min_temperature: float, default: 0.5 The minimal temperature for the Gumbel softmax. temperature_decay: float, default: 1-5e-5 After each evaluation, the current temperature is updated as current_temp := max(temperature_decay*current_temp, min_temperature) seed: int, default: 15 Random seed. gpu_id: int or None, default: 0 The ID of the GPU to be used for training. If None, CPU only. use_gumbel: bool, default: True Use the Gumbel softmax trick. legacy_generator: bool, default: False If True, the hidden and cell states of the generator LSTM are initialized by two separate feed-forward networks. If False (recommended), the hidden layer is shared, which has less parameters and performs just as good. """ self.params = { 'noise_dim': noise_dim, 'noise_type': noise_type, 'Generator_Layers': generator_layers, 'Discriminator_Layers': discriminator_layers, 'W_Down_Generator_size': W_down_generator_size, 'W_Down_Discriminator_size': W_down_discriminator_size, 'l2_penalty_generator': l2_penalty_generator, 'l2_penalty_discriminator': l2_penalty_discriminator, 'learning_rate': learning_rate, 'batch_size': batch_size, 'Wasserstein_penalty': wasserstein_penalty, 'temp_start': temp_start, 'min_temperature': min_temperature, 'temperature_decay': temperature_decay, 'disc_iters': disc_iters, 'use_gumbel': use_gumbel, 'legacy_generator': legacy_generator } assert rw_len > 1, "Random walk length must be > 1." tf.set_random_seed(seed) #tf.random.set_seed(seed) self.N = N self.rw_len = rw_len self.noise_dim = self.params['noise_dim'] self.G_layers = self.params['Generator_Layers'] self.D_layers = self.params['Discriminator_Layers'] self.tau = tf.placeholder(1.0 , shape=(), name="temperature") # W_down and W_up for generator and discriminator self.W_down_generator = tf.get_variable('Generator.W_Down', shape=[self.N, self.params['W_Down_Generator_size']], dtype=tf.float32, initializer=tf.glorot_uniform_initializer()) self.W_down_discriminator = tf.get_variable('Discriminator.W_Down', shape=[self.N, self.params['W_Down_Discriminator_size']], dtype=tf.float32, initializer=tf.glorot_uniform_initializer()) self.W_up = tf.get_variable("Generator.W_up", shape = [self.G_layers[-1], self.N], dtype=tf.float32, initializer=tf.glorot_uniform_initializer()) self.b_W_up = tf.get_variable("Generator.W_up_bias", dtype=tf.float32, initializer=tf.zeros_initializer, shape=self.N) self.generator_function = self.generator_recurrent self.discriminator_function = self.discriminator_recurrent self.fake_inputs = self.generator_function(self.params['batch_size'], reuse=False, gumbel=use_gumbel, legacy=legacy_generator) self.fake_inputs_discrete = self.generate_discrete(self.params['batch_size'], reuse=True, gumbel=use_gumbel, legacy=legacy_generator) # Pre-fetch real random walks dataset = tf.data.Dataset.from_generator(walk_generator, tf.int32, [self.params['batch_size'], self.rw_len]) #dataset_batch = dataset.prefetch(2).batch(self.params['batch_size']) dataset_batch = dataset.prefetch(100) batch_iterator = dataset_batch.make_one_shot_iterator() real_data = batch_iterator.get_next() self.real_inputs_discrete = real_data self.real_inputs = tf.one_hot(self.real_inputs_discrete, self.N) self.disc_real = self.discriminator_function(self.real_inputs) self.disc_fake = self.discriminator_function(self.fake_inputs, reuse=True) self.disc_cost = tf.reduce_mean(self.disc_fake) - tf.reduce_mean(self.disc_real) self.gen_cost = -tf.reduce_mean(self.disc_fake) # WGAN lipschitz-penalty alpha = tf.random_uniform( shape=[self.params['batch_size'], 1, 1], minval=0., maxval=1. ) self.differences = self.fake_inputs - self.real_inputs self.interpolates = self.real_inputs + (alpha * self.differences) self.gradients = tf.gradients(self.discriminator_function(self.interpolates, reuse=True), self.interpolates)[0] self.slopes = tf.sqrt(tf.reduce_sum(tf.square(self.gradients), reduction_indices=[1, 2])) self.gradient_penalty = tf.reduce_mean((self.slopes - 1.) ** 2) self.disc_cost += self.params['Wasserstein_penalty'] * self.gradient_penalty # weight regularization; we omit W_down from regularization self.disc_l2_loss = tf.add_n([ tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'Disc' in v.name and not 'W_down' in v.name]) * self.params['l2_penalty_discriminator'] self.disc_cost += self.disc_l2_loss # weight regularization; we omit W_down from regularization self.gen_l2_loss = tf.add_n([ tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'Gen' in v.name and not 'W_down' in v.name]) * self.params['l2_penalty_generator'] self.gen_cost += self.gen_l2_loss self.gen_params = [v for v in tf.trainable_variables() if 'Generator' in v.name] self.disc_params = [v for v in tf.trainable_variables() if 'Discriminator' in v.name] self.gen_train_op = tf.train.AdamOptimizer(learning_rate=self.params['learning_rate'], beta1=0.5, beta2=0.9).minimize(self.gen_cost, var_list=self.gen_params) self.disc_train_op = tf.train.AdamOptimizer(learning_rate=self.params['learning_rate'], beta1=0.5, beta2=0.9).minimize(self.disc_cost, var_list=self.disc_params) if gpu_id is None: config = tf.ConfigProto( device_count={'GPU': 0} ) else: gpu_options = tf.GPUOptions(visible_device_list='{}'.format(gpu_id), allow_growth=True) config = tf.ConfigProto(gpu_options=gpu_options, intra_op_parallelism_threads=3, inter_op_parallelism_threads=3) self.session = tf.InteractiveSession(config=config) self.init_op = tf.global_variables_initializer() def generate_discrete(self, n_samples, reuse=True, z=None, gumbel=True, legacy=False): """ Generate a random walk in index representation (instead of one hot). This is faster but prevents the gradients from flowing into the generator, so we only use it for evaluation purposes. Parameters ---------- n_samples: int The number of random walks to generate. reuse: bool, default: None If True, generator variables will be reused. z: None or tensor of shape (n_samples, noise_dim) The input noise. None means that the default noise generation function will be used. gumbel: bool, default: False Whether to use the gumbel softmax for generating discrete output. legacy: bool, default: False If True, the hidden and cell states of the generator LSTM are initialized by two separate feed-forward networks. If False (recommended), the hidden layer is shared, which has less parameters and performs just as good. Returns ------- The generated random walks, shape [None, rw_len, N] """ return tf.argmax(self.generator_function(n_samples, reuse, z, gumbel=gumbel, legacy=legacy), axis=-1) def generator_recurrent(self, n_samples, reuse=None, z=None, gumbel=True, legacy=False): """ Generate random walks using LSTM. Parameters ---------- n_samples: int The number of random walks to generate. reuse: bool, default: None If True, generator variables will be reused. z: None or tensor of shape (n_samples, noise_dim) The input noise. None means that the default noise generation function will be used. gumbel: bool, default: False Whether to use the gumbel softmax for generating discrete output. legacy: bool, default: False If True, the hidden and cell states of the generator LSTM are initialized by two separate feed-forward networks. If False (recommended), the hidden layer is shared, which has less parameters and performs just as good. Returns ------- The generated random walks, shape [None, rw_len, N] """ with tf.variable_scope('Generator') as scope: if reuse is True: scope.reuse_variables() def lstm_cell(lstm_size): return tf.nn.rnn_cell.BasicLSTMCell(lstm_size, reuse=tf.get_variable_scope().reuse) self.stacked_lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_cell(size) for size in self.G_layers]) # initial states h and c are randomly sampled for each lstm cell if z is None: initial_states_noise = make_noise([n_samples, self.noise_dim], self.params['noise_type']) else: initial_states_noise = z initial_states = [] # Noise preprocessing for ix,size in enumerate(self.G_layers): if legacy: # old version to initialize LSTM. new version has less parameters and performs just as good. h_intermediate = tf.layers.dense(initial_states_noise, size, name="Generator.h_int_{}".format(ix+1), reuse=reuse, activation=tf.nn.tanh) h = tf.layers.dense(h_intermediate, size, name="Generator.h_{}".format(ix+1), reuse=reuse, activation=tf.nn.tanh) c_intermediate = tf.layers.dense(initial_states_noise, size, name="Generator.c_int_{}".format(ix+1), reuse=reuse, activation=tf.nn.tanh) c = tf.layers.dense(c_intermediate, size, name="Generator.c_{}".format(ix+1), reuse=reuse, activation=tf.nn.tanh) else: intermediate = tf.layers.dense(initial_states_noise, size, name="Generator.int_{}".format(ix+1), reuse=reuse, activation=tf.nn.tanh) h = tf.layers.dense(intermediate, size, name="Generator.h_{}".format(ix+1), reuse=reuse, activation=tf.nn.tanh) c = tf.layers.dense(intermediate, size, name="Generator.c_{}".format(ix+1), reuse=reuse, activation=tf.nn.tanh) initial_states.append((c, h)) state = initial_states inputs = tf.zeros([n_samples, self.params['W_Down_Generator_size']]) outputs = [] # LSTM tine steps for i in range(self.rw_len): if i > 0: tf.get_variable_scope().reuse_variables() # Get LSTM output output, state = self.stacked_lstm.call(inputs, state) # Blow up to dimension N using W_up output_bef = tf.matmul(output, self.W_up) + self.b_W_up # Perform Gumbel softmax to ensure gradients flow if gumbel: output = gumbel_softmax(output_bef, temperature=self.tau, hard = True) else: output = tf.nn.softmax(output_bef) # Back to dimension d inputs = tf.matmul(output, self.W_down_generator) outputs.append(output) outputs = tf.stack(outputs, axis=1) return outputs def discriminator_recurrent(self, inputs, reuse=None): """ Discriminate real from fake random walks using LSTM. Parameters ---------- inputs: tf.tensor, shape (None, rw_len, N) The inputs to process reuse: bool, default: None If True, discriminator variables will be reused. Returns ------- final_score: tf.tensor, shape [None,], i.e. a scalar A score measuring how "real" the input random walks are perceived. """ with tf.variable_scope('Discriminator') as scope: if reuse == True: scope.reuse_variables() input_reshape = tf.reshape(inputs, [-1, self.N]) output = tf.matmul(input_reshape, self.W_down_discriminator) output = tf.reshape(output, [-1, self.rw_len, int(self.W_down_discriminator.get_shape()[-1])]) def lstm_cell(lstm_size): return tf.nn.rnn_cell.BasicLSTMCell(lstm_size, reuse=tf.get_variable_scope().reuse) disc_lstm_cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell(size) for size in self.D_layers]) output_disc, state_disc = tf.nn.static_rnn(cell=disc_lstm_cell, inputs=tf.unstack(output, axis=1), dtype='float32') last_output = output_disc[-1] final_score = tf.layers.dense(last_output, 1, reuse=reuse, name="Discriminator.Out") return final_score def train(self, A_orig, val_ones, val_zeros, max_iters=50000, stopping=None, eval_transitions=15e6, transitions_per_iter=150000, max_patience=5, eval_every=500, plot_every=-1, save_directory="../snapshots", model_name=None, continue_training=False): """ Parameters ---------- A_orig: sparse matrix, shape: (N,N) Adjacency matrix of the original graph to be trained on. val_ones: np.array, shape (n_val, 2) The indices of the hold-out set of validation edges val_zeros: np.array, shape (n_val, 2) The indices of the hold-out set of validation non-edges max_iters: int, default: 50,000 The maximum number of training iterations if early stopping does not apply. stopping: float in (0,1] or None, default: None The early stopping strategy. None means VAL criterion will be used (i.e. evaluation on the validation set and stopping after there has not been an improvement for *max_patience* steps. Set to a value in the interval (0,1] to stop when the edge overlap exceeds this threshold. eval_transitions: int, default: 15e6 The number of transitions that will be used for evaluating the validation performance, e.g. if the random walk length is 5, each random walk contains 4 transitions. transitions_per_iter: int, default: 150000 The number of transitions that will be generated in one batch. Higher means faster generation, but more RAM usage. max_patience: int, default: 5 Maximum evaluation steps without improvement of the validation accuracy to tolerate. Only applies to the VAL criterion. eval_every: int, default: 500 Evaluate the model every X iterations. plot_every: int, default: -1 Plot the generator/discriminator losses every X iterations. Set to None or a negative number to disable plotting. save_directory: str, default: "../snapshots" The directory to save model snapshots to. model_name: str, default: None Name of the model (will be used for saving the snapshots). continue_training: bool, default: False Whether to start training without initializing the weights first. If False, weights will be initialized. Returns ------- log_dict: dict A dictionary with the following values observed during training: * The generator and discriminator losses * The validation performances (ROC and AP) * The edge overlap values between the generated and original graph * The sampled graphs for all evaluation steps. """ if stopping == None: # use VAL criterion best_performance = 0.0 patience = max_patience #print("**** Using VAL criterion for early stopping ****") else: # use EO criterion assert "float" in str(type(stopping)) and stopping > 0 and stopping <= 1 #print("**** Using EO criterion of {} for early stopping".format(stopping)) if not os.path.isdir(save_directory): os.makedirs(save_directory) # if model_name is None: # # Find the file corresponding to the lowest vacant model number to store the snapshots into. # model_number = 0 # while os.path.exists("{}/model_best_{}.ckpt".format(save_directory, model_number)): # model_number += 1 # save_file = "{}/model_best_{}.ckpt".format(save_directory, model_number) # open(save_file, 'a').close() # touch file # else: # save_file = "{}/{}_best.ckpt".format(save_directory, model_name) #print("**** Saving snapshots into {} ****".format(save_file)) if not continue_training: #print("**** Initializing... ****") self.session.run(self.init_op) #print("**** Done. ****") #else: # print("**** Continuing training without initializing weights. ****") # Validation labels actual_labels_val = np.append(np.ones(len(val_ones)), np.zeros(len(val_zeros))) # Some lists to store data into. gen_losses = [] disc_losses = [] graphs = [] val_performances = [] eo=[] temperature = self.params['temp_start'] starting_time = time.time() # saver = tf.train.Saver() transitions_per_walk = self.rw_len - 1 # Sample lots of random walks, used for evaluation of model. sample_many_count = int(np.round(transitions_per_iter/transitions_per_walk)) sample_many = self.generate_discrete(sample_many_count, reuse=True) n_eval_walks = eval_transitions/transitions_per_walk n_eval_iters = int(np.round(n_eval_walks/sample_many_count)) print("**** Starting training. ****") for _it in range(max_iters): if _it % 50 == 0: print(_it, end=' ', flush=True) if _it > 0 and _it % (2500) == 0: t = time.time() - starting_time print('{:<7}/{:<8} training iterations, took {} seconds so far...'.format(_it, max_iters, int(t))) # Generator training iteration gen_loss, _ = self.session.run([self.gen_cost, self.gen_train_op], feed_dict={self.tau: temperature}) _disc_l = [] # Multiple discriminator training iterations. for _ in range(self.params['disc_iters']): disc_loss, _ = self.session.run( [self.disc_cost, self.disc_train_op], feed_dict={self.tau: temperature} ) _disc_l.append(disc_loss) gen_losses.append(gen_loss) disc_losses.append(np.mean(_disc_l)) # Evaluate the model's progress. if _it > 0 and _it % eval_every == 0: # Sample lots of random walks. smpls = [] for _ in range(n_eval_iters): smpls.append(self.session.run(sample_many, {self.tau: 0.5})) # Compute score matrix gr = utils.score_matrix_from_random_walks(np.array(smpls).reshape([-1, self.rw_len]), self.N) gr = gr.tocsr() # Assemble a graph from the score matrix _graph = utils.graph_from_scores(gr, A_orig.sum()) # Compute edge overlap edge_overlap = utils.edge_overlap(A_orig.toarray(), _graph) graphs.append(_graph) eo.append(edge_overlap) edge_scores = np.append(gr[tuple(val_ones.T)].A1, gr[tuple(val_zeros.T)].A1) # Compute Validation ROC-AUC and average precision scores. val_performances.append((roc_auc_score(actual_labels_val, edge_scores), average_precision_score(actual_labels_val, edge_scores))) # Update Gumbel temperature temperature = np.maximum(self.params['temp_start'] * np.exp(-(1-self.params['temperature_decay']) * _it), self.params['min_temperature']) print("**** Iter {:<6} Val ROC {:.3f}, AP: {:.3f}, EO {:.3f} ****".format(_it, val_performances[-1][0], val_performances[-1][1], edge_overlap/A_orig.sum())) if stopping is None: # Evaluate VAL criterion if np.sum(val_performances[-1]) > best_performance: # New "best" model best_performance = np.sum(val_performances[-1]) patience = max_patience # _ = saver.save(self.session, save_file) else: patience -= 1 if patience == 0: print("**** EARLY STOPPING AFTER {} ITERATIONS ****".format(_it)) break elif edge_overlap/A_orig.sum() >= stopping: # Evaluate EO criterion print("**** EARLY STOPPING AFTER {} ITERATIONS ****".format(_it)) break ''' if plot_every > 0 and (_it+1) % plot_every == 0: if len(disc_losses) > 10: plt.plot(disc_losses[9::], label="Critic loss") plt.plot(gen_losses[9::], label="Generator loss") else: plt.plot(disc_losses, label="Critic loss") plt.plot(gen_losses, label="Generator loss") plt.legend() plt.show() ''' print("**** Training completed after {} iterations. ****".format(_it)) #plt.plot(disc_losses[9::], label="Critic loss") #plt.plot(gen_losses[9::], label="Generator loss") #plt.legend() #plt.show() if stopping is None: # saver.restore(self.session, save_file) pass #### Training completed. log_dict = {"disc_losses": disc_losses, 'gen_losses': gen_losses, 'val_performances': val_performances, 'edge_overlaps': eo, 'generated_graphs': graphs} return log_dict def make_noise(shape, type="Gaussian"): """ Generate random noise. Parameters ---------- shape: List or tuple indicating the shape of the noise type: str, "Gaussian" or "Uniform", default: "Gaussian". Returns ------- noise tensor """ if type == "Gaussian": noise = tf.random_normal(shape) elif type == 'Uniform': noise = tf.random_uniform(shape, minval=-1, maxval=1) else: print("ERROR: Noise type {} not supported".format(type)) return noise def sample_gumbel(shape, eps=1e-20): """ Sample from a uniform Gumbel distribution. Code by <NAME> available at http://blog.evjang.com/2016/11/tutorial-categorical-variational.html Parameters ---------- shape: Shape of the Gumbel noise eps: Epsilon for numerical stability. Returns ------- Noise drawn from a uniform Gumbel distribution. """ """Sample from Gumbel(0, 1)""" U = tf.random_uniform(shape, minval=0, maxval=1) return -tf.log(-tf.log(U + eps) + eps) def gumbel_softmax_sample(logits, temperature): """ Draw a sample from the Gumbel-Softmax distribution""" y = logits + sample_gumbel(tf.shape(logits)) return tf.nn.softmax(y / temperature) def gumbel_softmax(logits, temperature, hard=False): """Sample from the Gumbel-Softmax distribution and optionally discretize. Args: logits: [batch_size, n_class] unnormalized log-probs temperature: non-negative scalar hard: if True, take argmax, but differentiate w.r.t. soft sample y Returns: [batch_size, n_class] sample from the Gumbel-Softmax distribution. If hard=True, then the returned sample will be one-hot, otherwise it will be a probabilitiy distribution that sums to 1 across classes """ y = gumbel_softmax_sample(logits, temperature) if hard: y_hard = tf.cast(tf.equal(y, tf.reduce_max(y, 1, keepdims=True)), y.dtype) y = tf.stop_gradient(y_hard - y) + y return y
[ "tensorflow.compat.v1.stack", "tensorflow.compat.v1.zeros", "numpy.sum", "tensorflow.compat.v1.InteractiveSession", "tensorflow.compat.v1.log", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.data.Dataset.from_generator", "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.get_variable_sc...
[((366, 390), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.disable_v2_behavior', ([], {}), '()\n', (388, 390), True, 'import tensorflow.compat.v1 as tf\n'), ((568, 610), 'tensorflow.compat.v1.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (592, 610), True, 'import tensorflow.compat.v1 as tf\n'), ((28509, 28553), 'tensorflow.compat.v1.random_uniform', 'tf.random_uniform', (['shape'], {'minval': '(0)', 'maxval': '(1)'}), '(shape, minval=0, maxval=1)\n', (28526, 28553), True, 'import tensorflow.compat.v1 as tf\n'), ((28769, 28799), 'tensorflow.compat.v1.nn.softmax', 'tf.nn.softmax', (['(y / temperature)'], {}), '(y / temperature)\n', (28782, 28799), True, 'import tensorflow.compat.v1 as tf\n'), ((5240, 5264), 'tensorflow.compat.v1.set_random_seed', 'tf.set_random_seed', (['seed'], {}), '(seed)\n', (5258, 5264), True, 'import tensorflow.compat.v1 as tf\n'), ((5534, 5583), 'tensorflow.compat.v1.placeholder', 'tf.placeholder', (['(1.0)'], {'shape': '()', 'name': '"""temperature"""'}), "(1.0, shape=(), name='temperature')\n", (5548, 5583), True, 'import tensorflow.compat.v1 as tf\n'), ((6577, 6686), 'tensorflow.compat.v1.get_variable', 'tf.get_variable', (['"""Generator.W_up_bias"""'], {'dtype': 'tf.float32', 'initializer': 'tf.zeros_initializer', 'shape': 'self.N'}), "('Generator.W_up_bias', dtype=tf.float32, initializer=tf.\n zeros_initializer, shape=self.N)\n", (6592, 6686), True, 'import tensorflow.compat.v1 as tf\n'), ((7241, 7344), 'tensorflow.compat.v1.data.Dataset.from_generator', 'tf.data.Dataset.from_generator', (['walk_generator', 'tf.int32', "[self.params['batch_size'], self.rw_len]"], {}), "(walk_generator, tf.int32, [self.params[\n 'batch_size'], self.rw_len])\n", (7271, 7344), True, 'import tensorflow.compat.v1 as tf\n'), ((7648, 7693), 'tensorflow.compat.v1.one_hot', 'tf.one_hot', (['self.real_inputs_discrete', 'self.N'], {}), '(self.real_inputs_discrete, self.N)\n', (7658, 7693), True, 'import tensorflow.compat.v1 as tf\n'), ((8045, 8131), 'tensorflow.compat.v1.random_uniform', 'tf.random_uniform', ([], {'shape': "[self.params['batch_size'], 1, 1]", 'minval': '(0.0)', 'maxval': '(1.0)'}), "(shape=[self.params['batch_size'], 1, 1], minval=0.0,\n maxval=1.0)\n", (8062, 8131), True, 'import tensorflow.compat.v1 as tf\n'), ((8560, 8600), 'tensorflow.compat.v1.reduce_mean', 'tf.reduce_mean', (['((self.slopes - 1.0) ** 2)'], {}), '((self.slopes - 1.0) ** 2)\n', (8574, 8600), True, 'import tensorflow.compat.v1 as tf\n'), ((10421, 10457), 'tensorflow.compat.v1.InteractiveSession', 'tf.InteractiveSession', ([], {'config': 'config'}), '(config=config)\n', (10442, 10457), True, 'import tensorflow.compat.v1 as tf\n'), ((10481, 10514), 'tensorflow.compat.v1.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (10512, 10514), True, 'import tensorflow.compat.v1 as tf\n'), ((22415, 22426), 'time.time', 'time.time', ([], {}), '()\n', (22424, 22426), False, 'import time\n'), ((27870, 27893), 'tensorflow.compat.v1.random_normal', 'tf.random_normal', (['shape'], {}), '(shape)\n', (27886, 27893), True, 'import tensorflow.compat.v1 as tf\n'), ((7875, 7905), 'tensorflow.compat.v1.reduce_mean', 'tf.reduce_mean', (['self.disc_fake'], {}), '(self.disc_fake)\n', (7889, 7905), True, 'import tensorflow.compat.v1 as tf\n'), ((7908, 7938), 'tensorflow.compat.v1.reduce_mean', 'tf.reduce_mean', (['self.disc_real'], {}), '(self.disc_real)\n', (7922, 7938), True, 'import tensorflow.compat.v1 as tf\n'), ((7964, 7994), 'tensorflow.compat.v1.reduce_mean', 'tf.reduce_mean', (['self.disc_fake'], {}), '(self.disc_fake)\n', (7978, 7994), True, 'import tensorflow.compat.v1 as tf\n'), ((10088, 10127), 'tensorflow.compat.v1.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'GPU': 0}"}), "(device_count={'GPU': 0})\n", (10102, 10127), True, 'import tensorflow.compat.v1 as tf\n'), ((10293, 10400), 'tensorflow.compat.v1.ConfigProto', 'tf.ConfigProto', ([], {'gpu_options': 'gpu_options', 'intra_op_parallelism_threads': '(3)', 'inter_op_parallelism_threads': '(3)'}), '(gpu_options=gpu_options, intra_op_parallelism_threads=3,\n inter_op_parallelism_threads=3)\n', (10307, 10400), True, 'import tensorflow.compat.v1 as tf\n'), ((12843, 12873), 'tensorflow.compat.v1.variable_scope', 'tf.variable_scope', (['"""Generator"""'], {}), "('Generator')\n", (12860, 12873), True, 'import tensorflow.compat.v1 as tf\n'), ((15153, 15212), 'tensorflow.compat.v1.zeros', 'tf.zeros', (["[n_samples, self.params['W_Down_Generator_size']]"], {}), "([n_samples, self.params['W_Down_Generator_size']])\n", (15161, 15212), True, 'import tensorflow.compat.v1 as tf\n'), ((16057, 16082), 'tensorflow.compat.v1.stack', 'tf.stack', (['outputs'], {'axis': '(1)'}), '(outputs, axis=1)\n', (16065, 16082), True, 'import tensorflow.compat.v1 as tf\n'), ((16674, 16708), 'tensorflow.compat.v1.variable_scope', 'tf.variable_scope', (['"""Discriminator"""'], {}), "('Discriminator')\n", (16691, 16708), True, 'import tensorflow.compat.v1 as tf\n'), ((16818, 16850), 'tensorflow.compat.v1.reshape', 'tf.reshape', (['inputs', '[-1, self.N]'], {}), '(inputs, [-1, self.N])\n', (16828, 16850), True, 'import tensorflow.compat.v1 as tf\n'), ((16872, 16923), 'tensorflow.compat.v1.matmul', 'tf.matmul', (['input_reshape', 'self.W_down_discriminator'], {}), '(input_reshape, self.W_down_discriminator)\n', (16881, 16923), True, 'import tensorflow.compat.v1 as tf\n'), ((17534, 17604), 'tensorflow.compat.v1.layers.dense', 'tf.layers.dense', (['last_output', '(1)'], {'reuse': 'reuse', 'name': '"""Discriminator.Out"""'}), "(last_output, 1, reuse=reuse, name='Discriminator.Out')\n", (17549, 17604), True, 'import tensorflow.compat.v1 as tf\n'), ((21112, 21141), 'os.path.isdir', 'os.path.isdir', (['save_directory'], {}), '(save_directory)\n', (21125, 21141), False, 'import os\n'), ((21155, 21182), 'os.makedirs', 'os.makedirs', (['save_directory'], {}), '(save_directory)\n', (21166, 21182), False, 'import os\n'), ((22611, 22664), 'numpy.round', 'np.round', (['(transitions_per_iter / transitions_per_walk)'], {}), '(transitions_per_iter / transitions_per_walk)\n', (22619, 22664), True, 'import numpy as np\n'), ((22828, 22870), 'numpy.round', 'np.round', (['(n_eval_walks / sample_many_count)'], {}), '(n_eval_walks / sample_many_count)\n', (22836, 22870), True, 'import numpy as np\n'), ((27938, 27983), 'tensorflow.compat.v1.random_uniform', 'tf.random_uniform', (['shape'], {'minval': '(-1)', 'maxval': '(1)'}), '(shape, minval=-1, maxval=1)\n', (27955, 27983), True, 'import tensorflow.compat.v1 as tf\n'), ((28740, 28756), 'tensorflow.compat.v1.shape', 'tf.shape', (['logits'], {}), '(logits)\n', (28748, 28756), True, 'import tensorflow.compat.v1 as tf\n'), ((29528, 29556), 'tensorflow.compat.v1.stop_gradient', 'tf.stop_gradient', (['(y_hard - y)'], {}), '(y_hard - y)\n', (29544, 29556), True, 'import tensorflow.compat.v1 as tf\n'), ((5940, 5971), 'tensorflow.compat.v1.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (5969, 5971), True, 'import tensorflow.compat.v1 as tf\n'), ((6294, 6325), 'tensorflow.compat.v1.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (6323, 6325), True, 'import tensorflow.compat.v1 as tf\n'), ((6521, 6552), 'tensorflow.compat.v1.glorot_uniform_initializer', 'tf.glorot_uniform_initializer', ([], {}), '()\n', (6550, 6552), True, 'import tensorflow.compat.v1 as tf\n'), ((8474, 8499), 'tensorflow.compat.v1.square', 'tf.square', (['self.gradients'], {}), '(self.gradients)\n', (8483, 8499), True, 'import tensorflow.compat.v1 as tf\n'), ((9453, 9477), 'tensorflow.compat.v1.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (9475, 9477), True, 'import tensorflow.compat.v1 as tf\n'), ((9543, 9567), 'tensorflow.compat.v1.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (9565, 9567), True, 'import tensorflow.compat.v1 as tf\n'), ((9627, 9720), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': "self.params['learning_rate']", 'beta1': '(0.5)', 'beta2': '(0.9)'}), "(learning_rate=self.params['learning_rate'], beta1=\n 0.5, beta2=0.9)\n", (9649, 9720), True, 'import tensorflow.compat.v1 as tf\n'), ((9846, 9939), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': "self.params['learning_rate']", 'beta1': '(0.5)', 'beta2': '(0.9)'}), "(learning_rate=self.params['learning_rate'], beta1=\n 0.5, beta2=0.9)\n", (9868, 9939), True, 'import tensorflow.compat.v1 as tf\n'), ((15954, 15994), 'tensorflow.compat.v1.matmul', 'tf.matmul', (['output', 'self.W_down_generator'], {}), '(output, self.W_down_generator)\n', (15963, 15994), True, 'import tensorflow.compat.v1 as tf\n'), ((23875, 23891), 'numpy.mean', 'np.mean', (['_disc_l'], {}), '(_disc_l)\n', (23882, 23891), True, 'import numpy as np\n'), ((29470, 29504), 'tensorflow.compat.v1.reduce_max', 'tf.reduce_max', (['y', '(1)'], {'keepdims': '(True)'}), '(y, 1, keepdims=True)\n', (29483, 29504), True, 'import tensorflow.compat.v1 as tf\n'), ((8793, 8809), 'tensorflow.compat.v1.nn.l2_loss', 'tf.nn.l2_loss', (['v'], {}), '(v)\n', (8806, 8809), True, 'import tensorflow.compat.v1 as tf\n'), ((9161, 9177), 'tensorflow.compat.v1.nn.l2_loss', 'tf.nn.l2_loss', (['v'], {}), '(v)\n', (9174, 9177), True, 'import tensorflow.compat.v1 as tf\n'), ((15585, 15613), 'tensorflow.compat.v1.matmul', 'tf.matmul', (['output', 'self.W_up'], {}), '(output, self.W_up)\n', (15594, 15613), True, 'import tensorflow.compat.v1 as tf\n'), ((15864, 15889), 'tensorflow.compat.v1.nn.softmax', 'tf.nn.softmax', (['output_bef'], {}), '(output_bef)\n', (15877, 15889), True, 'import tensorflow.compat.v1 as tf\n'), ((17357, 17383), 'tensorflow.compat.v1.unstack', 'tf.unstack', (['output'], {'axis': '(1)'}), '(output, axis=1)\n', (17367, 17383), True, 'import tensorflow.compat.v1 as tf\n'), ((23099, 23110), 'time.time', 'time.time', ([], {}), '()\n', (23108, 23110), False, 'import time\n'), ((28574, 28589), 'tensorflow.compat.v1.log', 'tf.log', (['(U + eps)'], {}), '(U + eps)\n', (28580, 28589), True, 'import tensorflow.compat.v1 as tf\n'), ((8819, 8843), 'tensorflow.compat.v1.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (8841, 8843), True, 'import tensorflow.compat.v1 as tf\n'), ((9187, 9211), 'tensorflow.compat.v1.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (9209, 9211), True, 'import tensorflow.compat.v1 as tf\n'), ((24902, 24947), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['actual_labels_val', 'edge_scores'], {}), '(actual_labels_val, edge_scores)\n', (24915, 24947), False, 'from sklearn.metrics import roc_auc_score, average_precision_score\n'), ((24996, 25051), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['actual_labels_val', 'edge_scores'], {}), '(actual_labels_val, edge_scores)\n', (25019, 25051), False, 'from sklearn.metrics import roc_auc_score, average_precision_score\n'), ((25168, 25221), 'numpy.exp', 'np.exp', (["(-(1 - self.params['temperature_decay']) * _it)"], {}), "(-(1 - self.params['temperature_decay']) * _it)\n", (25174, 25221), True, 'import numpy as np\n'), ((25793, 25821), 'numpy.sum', 'np.sum', (['val_performances[-1]'], {}), '(val_performances[-1])\n', (25799, 25821), True, 'import numpy as np\n'), ((25928, 25956), 'numpy.sum', 'np.sum', (['val_performances[-1]'], {}), '(val_performances[-1])\n', (25934, 25956), True, 'import numpy as np\n'), ((13062, 13085), 'tensorflow.compat.v1.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (13083, 13085), True, 'import tensorflow.compat.v1 as tf\n'), ((15356, 15379), 'tensorflow.compat.v1.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (15377, 15379), True, 'import tensorflow.compat.v1 as tf\n'), ((17139, 17162), 'tensorflow.compat.v1.get_variable_scope', 'tf.get_variable_scope', ([], {}), '()\n', (17160, 17162), True, 'import tensorflow.compat.v1 as tf\n'), ((24288, 24303), 'numpy.array', 'np.array', (['smpls'], {}), '(smpls)\n', (24296, 24303), True, 'import numpy as np\n')]
from abc import ABCMeta, abstractmethod import logging import numpy as np from pygam import LogisticGAM, s from sklearn.metrics import roc_auc_score as auc from sklearn.linear_model import LogisticRegressionCV from sklearn.model_selection import StratifiedKFold, train_test_split import xgboost as xgb logger = logging.getLogger('causalml') class PropensityModel(metaclass=ABCMeta): def __init__(self, clip_bounds=(1e-3, 1 - 1e-3), **model_kwargs): """ Args: clip_bounds (tuple): lower and upper bounds for clipping propensity scores. Bounds should be implemented such that: 0 < lower < upper < 1, to avoid division by zero in BaseRLearner.fit_predict() step. model_kwargs: Keyword arguments to be passed to the underlying classification model. """ self.clip_bounds = clip_bounds self.model_kwargs = model_kwargs self.model = self._model @property @abstractmethod def _model(self): pass def __repr__(self): return self.model.__repr__() def fit(self, X, y): """ Fit a propensity model. Args: X (numpy.ndarray): a feature matrix y (numpy.ndarray): a binary target vector """ self.model.fit(X, y) def predict(self, X): """ Predict propensity scores. Args: X (numpy.ndarray): a feature matrix Returns: (numpy.ndarray): Propensity scores between 0 and 1. """ return np.clip( self.model.predict_proba(X)[:, 1], *self.clip_bounds ) def fit_predict(self, X, y): """ Fit a propensity model and predict propensity scores. Args: X (numpy.ndarray): a feature matrix y (numpy.ndarray): a binary target vector Returns: (numpy.ndarray): Propensity scores between 0 and 1. """ self.fit(X, y) propensity_scores = self.predict(X) logger.info('AUC score: {:.6f}'.format(auc(y, propensity_scores))) return propensity_scores class LogisticRegressionPropensityModel(PropensityModel): """ Propensity regression model based on the LogisticRegression algorithm. """ @property def _model(self): kwargs = { 'penalty': 'elasticnet', 'solver': 'saga', 'Cs': np.logspace(1e-3, 1 - 1e-3, 4), 'l1_ratios': np.linspace(1e-3, 1 - 1e-3, 4), 'cv': StratifiedKFold( n_splits=self.model_kwargs.pop('n_fold') if 'n_fold' in self.model_kwargs else 4, shuffle=True, random_state=self.model_kwargs.get('random_state', 42) ), 'random_state': 42, } kwargs.update(self.model_kwargs) return LogisticRegressionCV(**kwargs) class ElasticNetPropensityModel(LogisticRegressionPropensityModel): pass class GradientBoostedPropensityModel(PropensityModel): """ Gradient boosted propensity score model with optional early stopping. Notes ----- Please see the xgboost documentation for more information on gradient boosting tuning parameters: https://xgboost.readthedocs.io/en/latest/python/python_api.html """ def __init__( self, early_stop=False, clip_bounds=(1e-3, 1 - 1e-3), **model_kwargs ): super(GradientBoostedPropensityModel, self).__init__(clip_bounds, **model_kwargs) self.early_stop = early_stop @property def _model(self): kwargs = { 'max_depth': 8, 'learning_rate': 0.1, 'n_estimators': 100, 'objective': 'binary:logistic', 'nthread': -1, 'colsample_bytree': 0.8, 'random_state': 42, } kwargs.update(self.model_kwargs) return xgb.XGBClassifier(**kwargs) def fit(self, X, y, early_stopping_rounds=10, stop_val_size=0.2): """ Fit a propensity model. Args: X (numpy.ndarray): a feature matrix y (numpy.ndarray): a binary target vector """ if self.early_stop: X_train, X_val, y_train, y_val = train_test_split( X, y, test_size=stop_val_size ) self.model.fit( X_train, y_train, eval_set=[(X_val, y_val)], early_stopping_rounds=early_stopping_rounds ) else: super(GradientBoostedPropensityModel, self).fit(X, y) def predict(self, X): """ Predict propensity scores. Args: X (numpy.ndarray): a feature matrix Returns: (numpy.ndarray): Propensity scores between 0 and 1. """ if self.early_stop: return np.clip( self.model.predict_proba( X, ntree_limit=self.model.best_ntree_limit )[:, 1], *self.clip_bounds ) else: return super(GradientBoostedPropensityModel, self).predict(X) def calibrate(ps, treatment): """Calibrate propensity scores with logistic GAM. Ref: https://pygam.readthedocs.io/en/latest/api/logisticgam.html Args: ps (numpy.array): a propensity score vector treatment (numpy.array): a binary treatment vector (0: control, 1: treated) Returns: (numpy.array): a calibrated propensity score vector """ gam = LogisticGAM(s(0)).fit(ps, treatment) return gam.predict_proba(ps) def compute_propensity_score(X, treatment, p_model=None, X_pred=None, treatment_pred=None, calibrate_p=True): """Generate propensity score if user didn't provide Args: X (np.matrix): features for training treatment (np.array or pd.Series): a treatment vector for training p_model (propensity model object, optional): ElasticNetPropensityModel (default) / GradientBoostedPropensityModel X_pred (np.matrix, optional): features for prediction treatment_pred (np.array or pd.Series, optional): a treatment vector for prediciton calibrate_p (bool, optional): whether calibrate the propensity score Returns: (tuple) - p (numpy.ndarray): propensity score - p_model (PropensityModel): a trained PropensityModel object """ if treatment_pred is None: treatment_pred = treatment.copy() if p_model is None: p_model = ElasticNetPropensityModel() p_model.fit(X, treatment) if X_pred is None: p = p_model.predict(X) else: p = p_model.predict(X_pred) if calibrate_p: logger.info('Calibrating propensity scores.') p = calibrate(p, treatment_pred) # force the p values within the range eps = np.finfo(float).eps p = np.where(p < 0 + eps, 0 + eps*1.001, p) p = np.where(p > 1 - eps, 1 - eps*1.001, p) return p, p_model
[ "numpy.logspace", "sklearn.model_selection.train_test_split", "sklearn.metrics.roc_auc_score", "pygam.s", "sklearn.linear_model.LogisticRegressionCV", "numpy.finfo", "numpy.where", "numpy.linspace", "xgboost.XGBClassifier", "logging.getLogger" ]
[((313, 342), 'logging.getLogger', 'logging.getLogger', (['"""causalml"""'], {}), "('causalml')\n", (330, 342), False, 'import logging\n'), ((6949, 6990), 'numpy.where', 'np.where', (['(p < 0 + eps)', '(0 + eps * 1.001)', 'p'], {}), '(p < 0 + eps, 0 + eps * 1.001, p)\n', (6957, 6990), True, 'import numpy as np\n'), ((6997, 7038), 'numpy.where', 'np.where', (['(p > 1 - eps)', '(1 - eps * 1.001)', 'p'], {}), '(p > 1 - eps, 1 - eps * 1.001, p)\n', (7005, 7038), True, 'import numpy as np\n'), ((2851, 2881), 'sklearn.linear_model.LogisticRegressionCV', 'LogisticRegressionCV', ([], {}), '(**kwargs)\n', (2871, 2881), False, 'from sklearn.linear_model import LogisticRegressionCV\n'), ((3911, 3938), 'xgboost.XGBClassifier', 'xgb.XGBClassifier', ([], {}), '(**kwargs)\n', (3928, 3938), True, 'import xgboost as xgb\n'), ((6921, 6936), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (6929, 6936), True, 'import numpy as np\n'), ((2414, 2446), 'numpy.logspace', 'np.logspace', (['(0.001)', '(1 - 0.001)', '(4)'], {}), '(0.001, 1 - 0.001, 4)\n', (2425, 2446), True, 'import numpy as np\n'), ((2471, 2503), 'numpy.linspace', 'np.linspace', (['(0.001)', '(1 - 0.001)', '(4)'], {}), '(0.001, 1 - 0.001, 4)\n', (2482, 2503), True, 'import numpy as np\n'), ((4257, 4304), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': 'stop_val_size'}), '(X, y, test_size=stop_val_size)\n', (4273, 4304), False, 'from sklearn.model_selection import StratifiedKFold, train_test_split\n'), ((2061, 2086), 'sklearn.metrics.roc_auc_score', 'auc', (['y', 'propensity_scores'], {}), '(y, propensity_scores)\n', (2064, 2086), True, 'from sklearn.metrics import roc_auc_score as auc\n'), ((5592, 5596), 'pygam.s', 's', (['(0)'], {}), '(0)\n', (5593, 5596), False, 'from pygam import LogisticGAM, s\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # HarmonicNet. # Copyright (C) 2021 <NAME>, <NAME>, S.Koppers, <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Liceense at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Please refer to the documentation for more information about the software # as well as for installation instructions. # # If you use this application for your work, please cite the following # publication: # # <NAME>, <NAME>, S.Koppers, <NAME>, # "Spherical Harmonics for Shape-Constrained 3D Cell Segmentation", ISBI, 2021. # """ import os import h5py import csv import itertools import numpy as np from skimage import io from scipy.ndimage import filters, distance_transform_edt from torch.utils.data import Dataset from dataloader.augmenter import intensity_augmenter class MeristemH5Dataset(Dataset): """ Dataset of fluorescently labeled cell membranes """ def __init__(self, list_path, data_dir, patch_size=(64,128,128), norm_method='percentile', shuffle=True,\ image_group='data/image', sh_order=5, strides=[2,4,8], augmentation_dict=None): # Sanity checks assert len(patch_size)==3, 'Patch size must be 3-dimensional.' # Parameters self.data_dir = data_dir self.list_path = list_path self.patch_size = patch_size self.norm_method = norm_method # Read the filelist and construct full paths to each file self.shuffle = shuffle self.image_group = image_group self.sh_order = sh_order self.num_coefficients = int((self.sh_order+1)**2) self.strides = strides self.data_list = self._read_list() # Get image statistics from up to 10 files print('Getting statistics from images...') self.data_statistics = {'min':[], 'max':[], 'mean':[], 'std':[], 'perc02':[], 'perc98':[]} for file_pair in self.data_list[:2]: with h5py.File(file_pair[0], 'r') as f_handle: image = f_handle[self.image_group] self.data_statistics['min'].append(np.min(image)) self.data_statistics['max'].append(np.max(image)) self.data_statistics['mean'].append(np.mean(image)) self.data_statistics['std'].append(np.std(image)) perc02, perc98 = np.percentile(image, [2,98]) self.data_statistics['perc02'].append(perc02) self.data_statistics['perc98'].append(perc98) # Construct data set statistics self.data_statistics['min'] = np.min(self.data_statistics['min']) self.data_statistics['max'] = np.max(self.data_statistics['max']) self.data_statistics['mean'] = np.mean(self.data_statistics['mean']) self.data_statistics['std'] = np.mean(self.data_statistics['std']) self.data_statistics['perc02'] = np.mean(self.data_statistics['perc02']) self.data_statistics['perc98'] = np.mean(self.data_statistics['perc98']) # Get the normalization values if self.norm_method == 'minmax': self.norm1 = self.data_statistics['min'] self.norm2 = self.data_statistics['max']-self.data_statistics['min'] elif self.norm_method == 'meanstd': self.norm1 = self.data_statistics['mean'] self.norm2 = self.data_statistics['std'] elif self.norm_method == 'percentile': self.norm1 = self.data_statistics['perc02'] self.norm2 = self.data_statistics['perc98']-self.data_statistics['perc02'] else: self.norm1 = 0.0 self.norm2 = 1.0 # Construct the augmentation dict if augmentation_dict is None: self.augmentation_dict = {} else: self.augmentation_dict = augmentation_dict self.intensity_augmenter = intensity_augmenter(self.augmentation_dict) self.augmentation_dict = self.intensity_augmenter.augmentation_dict def test(self, test_folder='', num_files=20): os.makedirs(test_folder, exist_ok=True) for i in range(num_files): test_sample = self.__getitem__(i%self.__len__()) for num_img in range(test_sample['image'].shape[0]): io.imsave(os.path.join(test_folder, 'test_img{0}_group{1}.tif'.format(i,num_img)), test_sample['image'][num_img,...]) for num_mask in range(test_sample['stride{0}/centroid_map'.format(self.strides[0])].shape[0]): io.imsave(os.path.join(test_folder, 'test_mask{0}_group{1}.tif'.format(i,num_mask)), test_sample['stride{0}/centroid_map'.format(self.strides[0])][num_mask,...]) def _read_list(self): # Read the filelist and create full paths to each file filelist = [] with open(self.list_path, 'r') as f: reader = csv.reader(f, delimiter=';') for row in reader: if len(row)==0 or np.sum([len(r) for r in row])==0: continue row = [os.path.join(self.data_dir, r) for r in row] filelist.append(row) if self.shuffle: np.random.shuffle(filelist) return filelist def __len__(self): return len(self.data_list) def _normalize(self, data, group_name): # Normalization if 'image' in group_name: data -= self.norm1 data /= self.norm2 if self.norm_method == 'minmax' or self.norm_method == 'percentile': data = np.clip(data, 1e-5, 1) return data def __getitem__(self, idx): # Get the paths to the image and mask filepath = self.data_list[idx] sample = {} # Load the image patch with h5py.File(filepath[0], 'r') as f_handle: image = f_handle[self.image_group] # Determine the patch position rnd_start = [np.random.randint(0, np.maximum(1,image_dim-patch_dim)) for patch_dim, image_dim in zip(self.patch_size, image.shape)] rnd_end = [start+patch_dim for start, patch_dim in zip(rnd_start, self.patch_size)] slicing = tuple(map(slice, rnd_start, rnd_end)) image = image[slicing].astype(np.float32) # Pad if neccessary pad_width = [(0,np.maximum(0,p-i)) for p,i in zip(self.patch_size,image.shape)] image = np.pad(image, pad_width, mode='reflect') # Normalization image = self._normalize(image, self.image_group) # Apply intensity augmentations if 'image' in self.image_group: image = self.intensity_augmenter.apply(image) # Add channel dimension image = image[np.newaxis,...] image = image.astype(np.float32) if self.norm_method == 'minmax' or self.norm_method == 'percentile': image = np.clip(image, 1e-5, 1) sample['image'] = image # Load the mask patch with h5py.File(filepath[1], 'r') as f_handle: for stride in self.strides: patch_size = [p//stride for p in self.patch_size] ## LOAD THE CENTROID MAP # get slicing patch_start = [r//stride for r in rnd_start] slicing = tuple(map(slice, patch_start, [start+size for start,size in zip(patch_start, patch_size)])) # slice a data patch centroid_tmp = f_handle['data/stride{0}/centroid_map'.format(stride)] centroid_tmp = centroid_tmp[slicing] # pad if necessary pad_width = [(0,np.maximum(0,p-i)) for p,i in zip(patch_size,centroid_tmp.shape)] centroid_tmp = np.pad(centroid_tmp, pad_width, mode='reflect') # save the current mask centroid_tmp = centroid_tmp[np.newaxis,...] centroid_tmp = centroid_tmp.astype(np.float32) sample['stride{0}/centroid_map'.format(stride)] = centroid_tmp ## LOAD THE HARMONIC ENCODING # get slicing slicing = tuple(map(slice, [r//stride for r in rnd_start]+[0,], [r//stride for r in rnd_end]+[self.num_coefficients,])) # slice a data patch encoding_tmp = f_handle['data/stride{0}/encoding_map'.format(stride)] encoding_tmp = encoding_tmp[slicing] # pad if necessary pad_width = [(0,np.maximum(0,p-i)) for p,i in zip(patch_size,encoding_tmp.shape[:-1])] + [(0,0),] encoding_tmp = np.pad(encoding_tmp, pad_width, mode='reflect') # save the current mask encoding_tmp = np.transpose(encoding_tmp, (3,0,1,2)) encoding_tmp = encoding_tmp.astype(np.float32) sample['stride{0}/encoding_map'.format(stride)] = encoding_tmp return sample class MeristemH5Tiler(Dataset): """ Dataset of fluorescently labeled cell membranes """ def __init__(self, list_path, data_root='', patch_size=(64,128,128), overlap=(10,10,10), crop=(10,10,10), norm_method='percentile',\ image_groups=('data/image',), mask_groups=('data/distance', 'data/seeds', 'data/boundary'), \ dist_handling='bool', dist_scaling=(100,100), seed_handling='float', boundary_handling='bool', instance_handling='bool',\ no_mask=False, no_img=False, reduce_dim=False, **kwargs): # Sanity checks assert len(patch_size)==3, 'Patch size must be 3-dimensional.' if reduce_dim: assert np.any([p==1 for p in patch_size]), 'Reduce is only possible, if there is a singleton patch dimension.' # Save parameters self.data_root = data_root self.list_path = os.path.abspath(list_path) self.patch_size = patch_size self.overlap = overlap self.crop = crop self.norm_method = norm_method self.dist_handling = dist_handling self.dist_scaling = dist_scaling self.seed_handling = seed_handling self.boundary_handling = boundary_handling self.instance_handling = instance_handling self.no_mask = no_mask self.no_img = no_img self.reduce_dim = reduce_dim # Read the filelist and construct full paths to each file self.image_groups = image_groups self.mask_groups = mask_groups self.data_list = self._read_list() self.set_data_idx(0) # Get image statistics from up to 10 files if not self.no_img and 'image' in self.image_groups[0]: print('Getting statistics from images...') self.data_statistics = {'min':[], 'max':[], 'mean':[], 'std':[], 'perc02':[], 'perc98':[]} for file_pair in self.data_list[:10]: with h5py.File(file_pair[0], 'r') as f_handle: image = f_handle[self.image_groups[0]][...].astype(np.float32) self.data_statistics['min'].append(np.min(image)) self.data_statistics['max'].append(np.max(image)) self.data_statistics['mean'].append(np.mean(image)) self.data_statistics['std'].append(np.std(image)) perc02, perc98 = np.percentile(image, [2,98]) self.data_statistics['perc02'].append(perc02) self.data_statistics['perc98'].append(perc98) # Construct data set statistics self.data_statistics['min'] = np.min(self.data_statistics['min']) self.data_statistics['max'] = np.max(self.data_statistics['max']) self.data_statistics['mean'] = np.mean(self.data_statistics['mean']) self.data_statistics['std'] = np.mean(self.data_statistics['std']) self.data_statistics['perc02'] = np.mean(self.data_statistics['perc02']) self.data_statistics['perc98'] = np.mean(self.data_statistics['perc98']) if self.norm_method == 'minmax': self.norm1 = self.data_statistics['min'] self.norm2 = self.data_statistics['max']-self.data_statistics['min'] elif self.norm_method == 'meanstd': self.norm1 = self.data_statistics['mean'] self.norm2 = self.data_statistics['std'] elif self.norm_method == 'percentile': self.norm1 = self.data_statistics['perc02'] self.norm2 = self.data_statistics['perc98']-self.data_statistics['perc02'] else: self.norm1 = 0 self.norm2 = 1 def _read_list(self): # Read the filelist and create full paths to each file filelist = [] with open(self.list_path, 'r') as f: reader = csv.reader(f, delimiter=';') for row in reader: if len(row)==0 or np.sum([len(r) for r in row])==0: continue row = [os.path.abspath(os.path.join(self.data_root, r)) for r in row] filelist.append(row) return filelist def get_fading_map(self): fading_map = np.ones(self.patch_size) if all([c==0 for c in self.crop]): self.crop = [1,1,1] # Exclude crop region crop_masking = np.zeros_like(fading_map) crop_masking[self.crop[0]:self.patch_size[0]-self.crop[0],\ self.crop[1]:self.patch_size[1]-self.crop[1],\ self.crop[2]:self.patch_size[2]-self.crop[2]] = 1 fading_map = fading_map * crop_masking fading_map = distance_transform_edt(fading_map).astype(np.float32) # Normalize fading_map = fading_map / fading_map.max() return fading_map def get_whole_image(self): with h5py.File(self.data_list[self.data_idx][0], 'r') as f_handle: image = f_handle[self.image_groups] [:] return image def get_whole_mask(self, mask_groups=None): if mask_groups is None: mask_groups = self.mask_groups if not isinstance(mask_groups, (list,tuple)): mask_groups = [mask_groups] mask = None with h5py.File(self.data_list[self.data_idx][1], 'r') as f_handle: for num_group, group_name in enumerate(mask_groups): mask_tmp = f_handle[group_name] if mask is None: mask = np.zeros((len(mask_groups),)+mask_tmp.shape, dtype=np.float32) mask[num_group,...] = mask_tmp return mask def set_data_idx(self, idx): # Restrict the idx to the amount of data available idx = idx%len(self.data_list) self.data_idx = idx # Get the current data size if not self.no_img: with h5py.File(self.data_list[idx][0], 'r') as f_handle: image = f_handle[self.image_groups[0]] self.data_shape = image.shape[:3] elif not self.no_mask: with h5py.File(self.data_list[idx][1], 'r') as f_handle: mask = f_handle[self.mask_groups[0]] self.data_shape = mask.shape[:3] else: raise ValueError('Can not determine data shape!') # Calculate the position of each tile locations = [] for i,p,o,c in zip(self.data_shape, self.patch_size, self.overlap, self.crop): # get starting coords coords = np.arange(np.ceil((i+o+c)/np.maximum(p-o-2*c,1)), dtype=np.int16)*np.maximum(p-o-2*c,1) -o-c locations.append(coords) self.locations = list(itertools.product(*locations)) self.global_crop_before = np.abs(np.min(np.array(self.locations), axis=0)) self.global_crop_after = np.array(self.data_shape) - np.max(np.array(self.locations), axis=0) - np.array(self.patch_size) def __len__(self): return len(self.locations) def _normalize(self, data, group_name): # Normalization if 'distance' in group_name: if self.dist_handling == 'float': data /= self.dist_scaling[0] elif self.dist_handling == 'bool': data = data<0 elif self.dist_handling == 'bool_inv': data = data>=0 elif self.dist_handling == 'exp': data = (data/self.dist_scaling[0])**3 elif self.dist_handling == 'tanh': foreground = np.float16(data>0) data = np.tanh(data/self.dist_scaling[0])*foreground + np.tanh(data/self.dist_scaling[1])*(1-foreground) elif 'seed' in group_name: if self.seed_handling == 'float': data = data.astype(np.float32) data = filters.gaussian_filter(data, 2) if np.max(data)>1e-4: data /= float(np.max(data)) elif self.seed_handling == 'bool': data = data>0.1 elif 'instance' in group_name or 'nuclei' in group_name: if self.instance_handling == 'bool': data = data>0 elif 'boundary' in group_name: if self.boundary_handling == 'bool': data = data>0 elif 'image' in group_name: data -= self.norm1 data /= self.norm2 if self.norm_method == 'minmax' or self.norm_method == 'percentile': data = np.clip(data, 1e-5, 1) return data def __getitem__(self, idx): self.patch_start = np.array(self.locations[idx]) self.patch_end = self.patch_start + np.array(self.patch_size) pad_before = np.maximum(-self.patch_start, 0) pad_after = np.maximum(self.patch_end-np.array(self.data_shape), 0) pad_width = list(zip(pad_before, pad_after)) slicing = tuple(map(slice, np.maximum(self.patch_start,0), self.patch_end)) sample = {} # Load the mask patch if not self.no_mask: mask = np.zeros((len(self.mask_groups),)+self.patch_size, dtype=np.float32) with h5py.File(self.data_list[self.data_idx][1], 'r') as f_handle: for num_group, group_name in enumerate(self.mask_groups): mask_tmp = f_handle[group_name] mask_tmp = mask_tmp[slicing] # Pad if neccessary mask_tmp = np.pad(mask_tmp, pad_width, mode='reflect') # Normalization mask_tmp = self._normalize(mask_tmp, group_name) # Store current mask mask[num_group,...] = mask_tmp mask = mask.astype(np.float32) if self.reduce_dim: out_shape = [p for i,p in enumerate(mask.shape) if p!=1 or i==0] mask = np.reshape(mask, out_shape) sample['mask'] = mask if not self.no_img: # Load the image patch image = np.zeros((len(self.image_groups),)+self.patch_size, dtype=np.float32) with h5py.File(self.data_list[self.data_idx][0], 'r') as f_handle: for num_group, group_name in enumerate(self.image_groups): image_tmp = f_handle[group_name] image_tmp = image_tmp[slicing] # Pad if neccessary image_tmp = np.pad(image_tmp, pad_width, mode='reflect') # Normalization image_tmp = self._normalize(image_tmp, group_name) # Store current image image[num_group,...] = image_tmp if self.reduce_dim: out_shape = [p for i,p in enumerate(image.shape) if p!=1 or i==0] image = np.reshape(image, out_shape) sample['image'] = image return sample
[ "numpy.maximum", "csv.reader", "numpy.ones", "numpy.clip", "numpy.mean", "dataloader.augmenter.intensity_augmenter", "os.path.join", "numpy.pad", "scipy.ndimage.distance_transform_edt", "os.path.abspath", "numpy.zeros_like", "numpy.std", "numpy.transpose", "numpy.max", "numpy.reshape", ...
[((3069, 3104), 'numpy.min', 'np.min', (["self.data_statistics['min']"], {}), "(self.data_statistics['min'])\n", (3075, 3104), True, 'import numpy as np\n'), ((3143, 3178), 'numpy.max', 'np.max', (["self.data_statistics['max']"], {}), "(self.data_statistics['max'])\n", (3149, 3178), True, 'import numpy as np\n'), ((3218, 3255), 'numpy.mean', 'np.mean', (["self.data_statistics['mean']"], {}), "(self.data_statistics['mean'])\n", (3225, 3255), True, 'import numpy as np\n'), ((3294, 3330), 'numpy.mean', 'np.mean', (["self.data_statistics['std']"], {}), "(self.data_statistics['std'])\n", (3301, 3330), True, 'import numpy as np\n'), ((3372, 3411), 'numpy.mean', 'np.mean', (["self.data_statistics['perc02']"], {}), "(self.data_statistics['perc02'])\n", (3379, 3411), True, 'import numpy as np\n'), ((3453, 3492), 'numpy.mean', 'np.mean', (["self.data_statistics['perc98']"], {}), "(self.data_statistics['perc98'])\n", (3460, 3492), True, 'import numpy as np\n'), ((4382, 4425), 'dataloader.augmenter.intensity_augmenter', 'intensity_augmenter', (['self.augmentation_dict'], {}), '(self.augmentation_dict)\n', (4401, 4425), False, 'from dataloader.augmenter import intensity_augmenter\n'), ((4595, 4634), 'os.makedirs', 'os.makedirs', (['test_folder'], {'exist_ok': '(True)'}), '(test_folder, exist_ok=True)\n', (4606, 4634), False, 'import os\n'), ((10954, 10980), 'os.path.abspath', 'os.path.abspath', (['list_path'], {}), '(list_path)\n', (10969, 10980), False, 'import os\n'), ((14399, 14423), 'numpy.ones', 'np.ones', (['self.patch_size'], {}), '(self.patch_size)\n', (14406, 14423), True, 'import numpy as np\n'), ((14570, 14595), 'numpy.zeros_like', 'np.zeros_like', (['fading_map'], {}), '(fading_map)\n', (14583, 14595), True, 'import numpy as np\n'), ((19049, 19078), 'numpy.array', 'np.array', (['self.locations[idx]'], {}), '(self.locations[idx])\n', (19057, 19078), True, 'import numpy as np\n'), ((19180, 19212), 'numpy.maximum', 'np.maximum', (['(-self.patch_start)', '(0)'], {}), '(-self.patch_start, 0)\n', (19190, 19212), True, 'import numpy as np\n'), ((5462, 5490), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (5472, 5490), False, 'import csv\n'), ((5750, 5777), 'numpy.random.shuffle', 'np.random.shuffle', (['filelist'], {}), '(filelist)\n', (5767, 5777), True, 'import numpy as np\n'), ((6461, 6488), 'h5py.File', 'h5py.File', (['filepath[0]', '"""r"""'], {}), "(filepath[0], 'r')\n", (6470, 6488), False, 'import h5py\n'), ((7148, 7188), 'numpy.pad', 'np.pad', (['image', 'pad_width'], {'mode': '"""reflect"""'}), "(image, pad_width, mode='reflect')\n", (7154, 7188), True, 'import numpy as np\n'), ((7877, 7904), 'h5py.File', 'h5py.File', (['filepath[1]', '"""r"""'], {}), "(filepath[1], 'r')\n", (7886, 7904), False, 'import h5py\n'), ((10755, 10793), 'numpy.any', 'np.any', (['[(p == 1) for p in patch_size]'], {}), '([(p == 1) for p in patch_size])\n', (10761, 10793), True, 'import numpy as np\n'), ((12724, 12759), 'numpy.min', 'np.min', (["self.data_statistics['min']"], {}), "(self.data_statistics['min'])\n", (12730, 12759), True, 'import numpy as np\n'), ((12802, 12837), 'numpy.max', 'np.max', (["self.data_statistics['max']"], {}), "(self.data_statistics['max'])\n", (12808, 12837), True, 'import numpy as np\n'), ((12881, 12918), 'numpy.mean', 'np.mean', (["self.data_statistics['mean']"], {}), "(self.data_statistics['mean'])\n", (12888, 12918), True, 'import numpy as np\n'), ((12961, 12997), 'numpy.mean', 'np.mean', (["self.data_statistics['std']"], {}), "(self.data_statistics['std'])\n", (12968, 12997), True, 'import numpy as np\n'), ((13043, 13082), 'numpy.mean', 'np.mean', (["self.data_statistics['perc02']"], {}), "(self.data_statistics['perc02'])\n", (13050, 13082), True, 'import numpy as np\n'), ((13128, 13167), 'numpy.mean', 'np.mean', (["self.data_statistics['perc98']"], {}), "(self.data_statistics['perc98'])\n", (13135, 13167), True, 'import numpy as np\n'), ((14021, 14049), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (14031, 14049), False, 'import csv\n'), ((15116, 15164), 'h5py.File', 'h5py.File', (['self.data_list[self.data_idx][0]', '"""r"""'], {}), "(self.data_list[self.data_idx][0], 'r')\n", (15125, 15164), False, 'import h5py\n'), ((15538, 15586), 'h5py.File', 'h5py.File', (['self.data_list[self.data_idx][1]', '"""r"""'], {}), "(self.data_list[self.data_idx][1], 'r')\n", (15547, 15586), False, 'import h5py\n'), ((17014, 17043), 'itertools.product', 'itertools.product', (['*locations'], {}), '(*locations)\n', (17031, 17043), False, 'import itertools\n'), ((17232, 17257), 'numpy.array', 'np.array', (['self.patch_size'], {}), '(self.patch_size)\n', (17240, 17257), True, 'import numpy as np\n'), ((19123, 19148), 'numpy.array', 'np.array', (['self.patch_size'], {}), '(self.patch_size)\n', (19131, 19148), True, 'import numpy as np\n'), ((2436, 2464), 'h5py.File', 'h5py.File', (['file_pair[0]', '"""r"""'], {}), "(file_pair[0], 'r')\n", (2445, 2464), False, 'import h5py\n'), ((2829, 2858), 'numpy.percentile', 'np.percentile', (['image', '[2, 98]'], {}), '(image, [2, 98])\n', (2842, 2858), True, 'import numpy as np\n'), ((6183, 6206), 'numpy.clip', 'np.clip', (['data', '(1e-05)', '(1)'], {}), '(data, 1e-05, 1)\n', (6190, 6206), True, 'import numpy as np\n'), ((7716, 7740), 'numpy.clip', 'np.clip', (['image', '(1e-05)', '(1)'], {}), '(image, 1e-05, 1)\n', (7723, 7740), True, 'import numpy as np\n'), ((8706, 8753), 'numpy.pad', 'np.pad', (['centroid_tmp', 'pad_width'], {'mode': '"""reflect"""'}), "(centroid_tmp, pad_width, mode='reflect')\n", (8712, 8753), True, 'import numpy as np\n'), ((9659, 9706), 'numpy.pad', 'np.pad', (['encoding_tmp', 'pad_width'], {'mode': '"""reflect"""'}), "(encoding_tmp, pad_width, mode='reflect')\n", (9665, 9706), True, 'import numpy as np\n'), ((9795, 9835), 'numpy.transpose', 'np.transpose', (['encoding_tmp', '(3, 0, 1, 2)'], {}), '(encoding_tmp, (3, 0, 1, 2))\n', (9807, 9835), True, 'import numpy as np\n'), ((14884, 14918), 'scipy.ndimage.distance_transform_edt', 'distance_transform_edt', (['fading_map'], {}), '(fading_map)\n', (14906, 14918), False, 'from scipy.ndimage import filters, distance_transform_edt\n'), ((16194, 16232), 'h5py.File', 'h5py.File', (['self.data_list[idx][0]', '"""r"""'], {}), "(self.data_list[idx][0], 'r')\n", (16203, 16232), False, 'import h5py\n'), ((17093, 17117), 'numpy.array', 'np.array', (['self.locations'], {}), '(self.locations)\n', (17101, 17117), True, 'import numpy as np\n'), ((17161, 17186), 'numpy.array', 'np.array', (['self.data_shape'], {}), '(self.data_shape)\n', (17169, 17186), True, 'import numpy as np\n'), ((19259, 19284), 'numpy.array', 'np.array', (['self.data_shape'], {}), '(self.data_shape)\n', (19267, 19284), True, 'import numpy as np\n'), ((19387, 19418), 'numpy.maximum', 'np.maximum', (['self.patch_start', '(0)'], {}), '(self.patch_start, 0)\n', (19397, 19418), True, 'import numpy as np\n'), ((19658, 19706), 'h5py.File', 'h5py.File', (['self.data_list[self.data_idx][1]', '"""r"""'], {}), "(self.data_list[self.data_idx][1], 'r')\n", (19667, 19706), False, 'import h5py\n'), ((20484, 20511), 'numpy.reshape', 'np.reshape', (['mask', 'out_shape'], {}), '(mask, out_shape)\n', (20494, 20511), True, 'import numpy as np\n'), ((20755, 20803), 'h5py.File', 'h5py.File', (['self.data_list[self.data_idx][0]', '"""r"""'], {}), "(self.data_list[self.data_idx][0], 'r')\n", (20764, 20803), False, 'import h5py\n'), ((21532, 21560), 'numpy.reshape', 'np.reshape', (['image', 'out_shape'], {}), '(image, out_shape)\n', (21542, 21560), True, 'import numpy as np\n'), ((2581, 2594), 'numpy.min', 'np.min', (['image'], {}), '(image)\n', (2587, 2594), True, 'import numpy as np\n'), ((2647, 2660), 'numpy.max', 'np.max', (['image'], {}), '(image)\n', (2653, 2660), True, 'import numpy as np\n'), ((2714, 2728), 'numpy.mean', 'np.mean', (['image'], {}), '(image)\n', (2721, 2728), True, 'import numpy as np\n'), ((2781, 2794), 'numpy.std', 'np.std', (['image'], {}), '(image)\n', (2787, 2794), True, 'import numpy as np\n'), ((5622, 5652), 'os.path.join', 'os.path.join', (['self.data_dir', 'r'], {}), '(self.data_dir, r)\n', (5634, 5652), False, 'import os\n'), ((6666, 6702), 'numpy.maximum', 'np.maximum', (['(1)', '(image_dim - patch_dim)'], {}), '(1, image_dim - patch_dim)\n', (6676, 6702), True, 'import numpy as np\n'), ((7063, 7083), 'numpy.maximum', 'np.maximum', (['(0)', '(p - i)'], {}), '(0, p - i)\n', (7073, 7083), True, 'import numpy as np\n'), ((12020, 12048), 'h5py.File', 'h5py.File', (['file_pair[0]', '"""r"""'], {}), "(file_pair[0], 'r')\n", (12029, 12048), False, 'import h5py\n'), ((12464, 12493), 'numpy.percentile', 'np.percentile', (['image', '[2, 98]'], {}), '(image, [2, 98])\n', (12477, 12493), True, 'import numpy as np\n'), ((16400, 16438), 'h5py.File', 'h5py.File', (['self.data_list[idx][1]', '"""r"""'], {}), "(self.data_list[idx][1], 'r')\n", (16409, 16438), False, 'import h5py\n'), ((17196, 17220), 'numpy.array', 'np.array', (['self.locations'], {}), '(self.locations)\n', (17204, 17220), True, 'import numpy as np\n'), ((18226, 18258), 'scipy.ndimage.filters.gaussian_filter', 'filters.gaussian_filter', (['data', '(2)'], {}), '(data, 2)\n', (18249, 18258), False, 'from scipy.ndimage import filters, distance_transform_edt\n'), ((19987, 20030), 'numpy.pad', 'np.pad', (['mask_tmp', 'pad_width'], {'mode': '"""reflect"""'}), "(mask_tmp, pad_width, mode='reflect')\n", (19993, 20030), True, 'import numpy as np\n'), ((21092, 21136), 'numpy.pad', 'np.pad', (['image_tmp', 'pad_width'], {'mode': '"""reflect"""'}), "(image_tmp, pad_width, mode='reflect')\n", (21098, 21136), True, 'import numpy as np\n'), ((8608, 8628), 'numpy.maximum', 'np.maximum', (['(0)', '(p - i)'], {}), '(0, p - i)\n', (8618, 8628), True, 'import numpy as np\n'), ((12200, 12213), 'numpy.min', 'np.min', (['image'], {}), '(image)\n', (12206, 12213), True, 'import numpy as np\n'), ((12270, 12283), 'numpy.max', 'np.max', (['image'], {}), '(image)\n', (12276, 12283), True, 'import numpy as np\n'), ((12341, 12355), 'numpy.mean', 'np.mean', (['image'], {}), '(image)\n', (12348, 12355), True, 'import numpy as np\n'), ((12412, 12425), 'numpy.std', 'np.std', (['image'], {}), '(image)\n', (12418, 12425), True, 'import numpy as np\n'), ((14197, 14228), 'os.path.join', 'os.path.join', (['self.data_root', 'r'], {}), '(self.data_root, r)\n', (14209, 14228), False, 'import os\n'), ((16920, 16948), 'numpy.maximum', 'np.maximum', (['(p - o - 2 * c)', '(1)'], {}), '(p - o - 2 * c, 1)\n', (16930, 16948), True, 'import numpy as np\n'), ((18278, 18290), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (18284, 18290), True, 'import numpy as np\n'), ((9545, 9565), 'numpy.maximum', 'np.maximum', (['(0)', '(p - i)'], {}), '(0, p - i)\n', (9555, 9565), True, 'import numpy as np\n'), ((18311, 18323), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (18317, 18323), True, 'import numpy as np\n'), ((17902, 17922), 'numpy.float16', 'np.float16', (['(data > 0)'], {}), '(data > 0)\n', (17912, 17922), True, 'import numpy as np\n'), ((18911, 18934), 'numpy.clip', 'np.clip', (['data', '(1e-05)', '(1)'], {}), '(data, 1e-05, 1)\n', (18918, 18934), True, 'import numpy as np\n'), ((16880, 16908), 'numpy.maximum', 'np.maximum', (['(p - o - 2 * c)', '(1)'], {}), '(p - o - 2 * c, 1)\n', (16890, 16908), True, 'import numpy as np\n'), ((17944, 17980), 'numpy.tanh', 'np.tanh', (['(data / self.dist_scaling[0])'], {}), '(data / self.dist_scaling[0])\n', (17951, 17980), True, 'import numpy as np\n'), ((17992, 18028), 'numpy.tanh', 'np.tanh', (['(data / self.dist_scaling[1])'], {}), '(data / self.dist_scaling[1])\n', (17999, 18028), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ LISTA_cpss_robust.py author: xhchrn <EMAIL> date : 2018-09-07 Implementation of Learned ISTA with support selection and coupled weights like in LAMP. With A and W given, we train a set of step sizes and thresholds that are robust to small turbulence in A. """ import numpy as np import numpy.linalg as la import tensorflow as tf import utils.train # TODO: move shrink functions to utils/shrink.py def shrink_ft( r_, tau_=1.0 ): """ Implement soft thresholding function with input r_ and threshold tau_. """ # tau_ = tf.maximum( tau_, 0.0 ) return tf.sign(r_) * tf.maximum( tf.abs(r_) - tau_, 0.0 ) def special_shrink(inputs_, tau_=1.0, q=1.0): """ Special shrink that does not apply soft shrinkage to entries of top q% magnitudes. :inputs_: TODO :thres_: TODO :q: TODO :returns: TODO """ ### TODO: ### multiplying cindex_ to inputs_ could generate different gradients from ### to tau_, when tau_ is coordinate-wise thresholds; or not. abs_ = tf.abs( inputs_ ) thres_ = tf.contrib.distributions.percentile( abs_, 100.0-q, axis=0, keep_dims=True) # indices of entries with big magnitudes, to which shrinkage should # not be applied to index_ = tf.logical_and (abs_ > tau_, abs_ > thres_) index_ = tf.to_float( index_ ) # stop gradient at index_, considering it as constant index_ = tf.stop_gradient( index_ ) cindex_ = 1.0 - index_ # complementary index return tf.multiply (index_, inputs_) +\ shrink_ft (tf.multiply (cindex_, inputs_), tau_) class LISTA_cpss_robust (object): """ Implementation of deep neural network model. """ def __init__ (self, m, n, T, theta, percent, max_percent, untied, coord, scope): """ :T : Integer. Number of layers (depth) of this LISTA model. :A : numpy.ndarray. Measuring matrix/Dictioanry. :lam : Float. Initial value of thresholds of shrinkage functions. :percent : TODO :max_percent: TODO :untied : Whether weights are shared within layers. :cord : TODO :scope : TODO """ self._m = m self._n = n self._T = T self._theta = theta self._p = percent self._mp = max_percent self._untied = untied self._coord = coord self._scope = scope # theta if self._coord: self._theta = self._theta * np.ones ([self._n, 1], dtype=np.float32) # percentage of support selection ps = np.arange (1, self._T+1) * self._p self._ps = np.clip (ps, 0.0, self._mp) self.setup_layers () def setup_layers (self): """ Implementation of LISTA model proposed by LeCun in 2010. :prob: Problem setting. :T: Number of layers in LISTA. :returns: :layers: List of tuples ( name, xh_, var_list ) :name: description of layers. :xh: estimation of sparse code at current layer. :var_list: list of variables to be trained seperately. """ self._step_sizes = [] self._thetas = [] with tf.variable_scope (self._scope, reuse=False) as vs: for t in range (self._T): ss_ = tf.get_variable ('ss_%d'%(t+1), dtype=tf.float32, initializer=1.0) theta_ = tf.get_variable ('theta_%d'%(t+1), dtype=tf.float32, initializer=self._theta) self._step_sizes.append (ss_) self._thetas.append (theta_) def inference (self, y_, A_, Wt_, x0_, return_recon): xhs_ = [] # collection of the regressed sparse codes if return_recon: yhs_ = [] # collection of the reconstructed signals with tf.variable_scope (self._scope, reuse=True) as vs: # init estimation of sparse vectors if x0_ is None: batch_size = tf.shape (y_) [1] xh_ = tf.zeros (shape=(self._n, batch_size), dtype=tf.float32) else: xh_ = x0_ xhs_.append (xh_) for i in range (self._T): ss_ = self._step_sizes [i] theta_ = self._thetas [i] percent = self._ps [i] yh_ = tf.matmul (A_, xh_) res_ = y_ - yh_ zh_ = xh_ + tf.matmul (ss_ * Wt_, res_) xh_ = special_shrink (zh_, theta_, percent) xhs_.append (xh_) if return_recon: yhs_.append (yh_) if return_recon: yh_ = tf.matmul (A_, xh_) yhs_.append (yh_) return xhs_, yhs_ else: return xhs_ def batch_inference (self, ys_, As_, Wts_, x0_, return_recon): """ Batch inference. Iterate over ys_, As_ and Wts_. The first dimension of list_xhs_ stands for the time/iteration in the model. list_xhs_ [k] is the stacked outputs of all (y_, A_, Wt_) at the step/iteration k. """ list_xhs_ = [[] for i in range (self._T + 1)] if return_recon: list_yhs_ = [[] for i in range (self._T + 1)] # iterate over ys_, As_ and Wts_ batch_size = ys_.shape.as_list () [0] for i in range (batch_size): if return_recon: xhs_, yhs_ = self.inference (ys_ [i], As_ [i], Wts_ [i], x0_, return_recon) # append yhs_ [t] to list_yhs_ [t] for all t for t, yh_ in enumerate (yhs_): list_yhs_ [t].append (yh_) else: xhs_ = self.inference (ys_ [i], As_ [i], Wts_ [i], x0_, return_recon) # append xhs_ [t] to list_xhs_ [t] for all t for t, xh_ in enumerate (xhs_): list_xhs_ [t].append (xh_) # stacking stacked_list_xhs_ = list (map (tf.stack, list_xhs_)) if return_recon: stacked_list_yhs_ = list (map (tf.stack, list_yhs_)) if return_recon: return stacked_list_xhs_, stacked_list_yhs_ else: return stacked_list_xhs_ # def setup_training(self, init_lr=5e-4, decay_rate=0.5, # lr_decay=(0.2, 0.02, )): # """ # Given prob and layers, we set up training stages according to some hyper- # parameters. # :init_lr: Initial learning rate. # :lr_decay: Learning rate decays. # :returns: # :stages: A list of (name, xh_, loss_, nmse_, op_, var_list). # """ # stages = [] # lrs = [init_lr * decay for decay in lr_decay] # x_ = self.prob.x_ # nmse_denom_ = tf.nn.l2_loss( x_ ) # self.decay_rate = decay_rate # # setup self.lr_multiplier dictionary # # learning rate multipliers of each variables # self.lr_multiplier = dict() # for var in tf.trainable_variables(): # self.lr_multiplier[var.op.name] = 1.0 # # initialize self.train_vars list # # variables which will be updated in next training stage # self.train_vars = [] # for l, ( name, xh_, var_list ) in enumerate( self.layers ): # loss_ = tf.nn.l2_loss( xh_ - x_ ) # nmse_ = loss_ / nmse_denom_ # if var_list is None or len(var_list) == 0: # continue # else: # op_ = tf.train.AdamOptimizer(init_lr)\ # .minimize(loss_, var_list=var_list) # stages.append( ( name, xh_, loss_, nmse_, op_, var_list ) ) # for var in var_list: # self.train_vars.append( var ) # for lr in lrs: # op_ = self.get_train_op( loss_, self.train_vars, lr ) # stages.append((name+' lr='+str(lr), # xh_, # loss_, # nmse_, # op_, # tuple(self.train_vars),)) # # decay learning rates for trained variables # for var in self.train_vars: # self.lr_multiplier[var.op.name] *= self.decay_rate # self.stages = stages # def get_train_op(self, loss_, var_list, lrate): # # get training operator # opt = tf.train.AdamOptimizer( lrate ) # grads_vars = opt.compute_gradients( loss_, var_list ) # grads_vars_multiplied = [] # for grad, var in grads_vars: # grad *= self.lr_multiplier[var.op.name] # grads_vars_multiplied.append( (grad, var) ) # return opt.apply_gradients( grads_vars_multiplied ) # def do_training(self, sess, savefn, batch_size=64, val_step=10,\ # maxit=200000, better_wait=4000 ): # """ # Do training actually. Refer to utils/train.py. # :sess : Tensorflow session, # in which session we will run the training. # :batch_size : Batch size. # :val_step : How many steps between two validation. # :maxit : Max number of iterations in each training stage. # :better_wait: Jump to next stage if no better performance after # certain # of iterations. # """ # self.state = utils.train.do_training( # sess, self.stages, self.prob, savefn, self.scope_name, # batch_size, val_step, maxit, better_wait) # def do_cs_training (self, sess, # train_y_, train_f_, train_x_, # val_y_ , val_f_ , val_x_, # savefn, batch_size=64, val_step=10, # maxit=200000, better_wait=4000, norm_patch=False) : # """ # Do training on compressive sensing problem actually. Refer to # utils/train.py. # Param: # :sess : Tensorflow session. # :trainfn : Path of training data tfrecords. # :valfn : Path of validation data tfrecords. # :savefn : Path that trained model to be saved. # Hyperparam: # :batch_size : Batch size. # :val_step : How many steps between two validation. # :maxit : Max number of iterations in each training stage. # :better_wait: Jump to next stage if no better performance after # certain # of iterations. # """ # self.state = utils.train.do_cs_training ( # sess, self.stages, self.prob, # train_y_, train_f_, train_x_, # val_y_ , val_f_ , val_x_, # savefn, self.scope_name, # batch_size, val_step, maxit, better_wait, norm_patch) # def save_trainable_variables( self , sess , savefn ): # """ # Save trainable variables in the model to npz file with current value of each # variable in tf.trainable_variables(). # :sess: Tensorflow session. # :savefn: File name of saved file. # """ # state = getattr ( self , 'state' , {} ) # utils.train.save_trainable_variables( # sess , savefn , self.scope_name , **state ) # def load_trainable_variables( self , sess , savefn ): # """ # Load trainable variables from saved file. # :sess: TODO # :savefn: TODO # :returns: TODO # """ # self.state = utils.train.load_trainable_variables( sess, savefn )
[ "tensorflow.abs", "tensorflow.logical_and", "tensorflow.contrib.distributions.percentile", "tensorflow.stop_gradient", "tensorflow.variable_scope", "tensorflow.sign", "numpy.clip", "numpy.ones", "tensorflow.multiply", "tensorflow.matmul", "tensorflow.zeros", "numpy.arange", "tensorflow.to_fl...
[((1078, 1093), 'tensorflow.abs', 'tf.abs', (['inputs_'], {}), '(inputs_)\n', (1084, 1093), True, 'import tensorflow as tf\n'), ((1109, 1185), 'tensorflow.contrib.distributions.percentile', 'tf.contrib.distributions.percentile', (['abs_', '(100.0 - q)'], {'axis': '(0)', 'keep_dims': '(True)'}), '(abs_, 100.0 - q, axis=0, keep_dims=True)\n', (1144, 1185), True, 'import tensorflow as tf\n'), ((1306, 1348), 'tensorflow.logical_and', 'tf.logical_and', (['(abs_ > tau_)', '(abs_ > thres_)'], {}), '(abs_ > tau_, abs_ > thres_)\n', (1320, 1348), True, 'import tensorflow as tf\n'), ((1363, 1382), 'tensorflow.to_float', 'tf.to_float', (['index_'], {}), '(index_)\n', (1374, 1382), True, 'import tensorflow as tf\n'), ((1456, 1480), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['index_'], {}), '(index_)\n', (1472, 1480), True, 'import tensorflow as tf\n'), ((631, 642), 'tensorflow.sign', 'tf.sign', (['r_'], {}), '(r_)\n', (638, 642), True, 'import tensorflow as tf\n'), ((1544, 1572), 'tensorflow.multiply', 'tf.multiply', (['index_', 'inputs_'], {}), '(index_, inputs_)\n', (1555, 1572), True, 'import tensorflow as tf\n'), ((2735, 2761), 'numpy.clip', 'np.clip', (['ps', '(0.0)', 'self._mp'], {}), '(ps, 0.0, self._mp)\n', (2742, 2761), True, 'import numpy as np\n'), ((1599, 1628), 'tensorflow.multiply', 'tf.multiply', (['cindex_', 'inputs_'], {}), '(cindex_, inputs_)\n', (1610, 1628), True, 'import tensorflow as tf\n'), ((2681, 2706), 'numpy.arange', 'np.arange', (['(1)', '(self._T + 1)'], {}), '(1, self._T + 1)\n', (2690, 2706), True, 'import numpy as np\n'), ((3319, 3362), 'tensorflow.variable_scope', 'tf.variable_scope', (['self._scope'], {'reuse': '(False)'}), '(self._scope, reuse=False)\n', (3336, 3362), True, 'import tensorflow as tf\n'), ((4004, 4046), 'tensorflow.variable_scope', 'tf.variable_scope', (['self._scope'], {'reuse': '(True)'}), '(self._scope, reuse=True)\n', (4021, 4046), True, 'import tensorflow as tf\n'), ((657, 667), 'tensorflow.abs', 'tf.abs', (['r_'], {}), '(r_)\n', (663, 667), True, 'import tensorflow as tf\n'), ((2584, 2623), 'numpy.ones', 'np.ones', (['[self._n, 1]'], {'dtype': 'np.float32'}), '([self._n, 1], dtype=np.float32)\n', (2591, 2623), True, 'import numpy as np\n'), ((3434, 3503), 'tensorflow.get_variable', 'tf.get_variable', (["('ss_%d' % (t + 1))"], {'dtype': 'tf.float32', 'initializer': '(1.0)'}), "('ss_%d' % (t + 1), dtype=tf.float32, initializer=1.0)\n", (3449, 3503), True, 'import tensorflow as tf\n'), ((3568, 3653), 'tensorflow.get_variable', 'tf.get_variable', (["('theta_%d' % (t + 1))"], {'dtype': 'tf.float32', 'initializer': 'self._theta'}), "('theta_%d' % (t + 1), dtype=tf.float32, initializer=self._theta\n )\n", (3583, 3653), True, 'import tensorflow as tf\n'), ((4200, 4255), 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '(self._n, batch_size)', 'dtype': 'tf.float32'}), '(shape=(self._n, batch_size), dtype=tf.float32)\n', (4208, 4255), True, 'import tensorflow as tf\n'), ((4518, 4536), 'tensorflow.matmul', 'tf.matmul', (['A_', 'xh_'], {}), '(A_, xh_)\n', (4527, 4536), True, 'import tensorflow as tf\n'), ((4848, 4866), 'tensorflow.matmul', 'tf.matmul', (['A_', 'xh_'], {}), '(A_, xh_)\n', (4857, 4866), True, 'import tensorflow as tf\n'), ((4160, 4172), 'tensorflow.shape', 'tf.shape', (['y_'], {}), '(y_)\n', (4168, 4172), True, 'import tensorflow as tf\n'), ((4599, 4625), 'tensorflow.matmul', 'tf.matmul', (['(ss_ * Wt_)', 'res_'], {}), '(ss_ * Wt_, res_)\n', (4608, 4625), True, 'import tensorflow as tf\n')]
from torch import random from replay_buffer import ReplayBuffer import torch import torch.optim as optim import torch.nn.functional as F from torch.nn.utils import clip_grad_norm_ import logging import numpy as np import random from dqn import DQN from replay_buffer import ReplayBuffer class TrajectoryPlanner: def __init__( self, state_shape, action_size, buffer_size, batch_size, gamma, lr, freeze_step, her=True, gpu=False, double_dqn=False, ): self.state_shape = state_shape self.action_size = action_size self.buffer_size = buffer_size self.batch_size = batch_size self.gamma = gamma self.lr = lr self.freeze_step = freeze_step self.gpu = gpu self.double_dqn = double_dqn self.n_train_steps = 0 self.device = "cpu" if gpu: self.device = "cuda" self.dqn_local = DQN( action_size, input_shape=state_shape[:2], in_channels=state_shape[2] + 1 ).to(self.device) self.dqn_target = DQN( action_size, input_shape=state_shape[:2], in_channels=state_shape[2] + 1 ).to(self.device) self.optimizer = optim.Adam(self.dqn_local.parameters(), lr=self.lr) self.replay_buffer = ReplayBuffer(buffer_size, gpu=gpu, her=her) logging.info(self.dqn_local) def act(self, state, goal, eps=0.1): _state = np.dstack((state, goal)) state = torch.from_numpy(_state).float().unsqueeze(0).to(self.device) self.dqn_local.eval() with torch.no_grad(): action_values = self.dqn_local(state) if random.random() > eps: action = np.argmax(action_values.cpu().data.numpy()) else: action = random.choice(np.arange(self.action_size)) return action def train_step(self, state, next_state, goal, action, reward, done): # There is a chance that the goal is None when the tetris episode ends, because # there is no valid move anymore if goal is not None: self.replay_buffer.add(state, next_state, goal, action, reward, done) else: self.replay_buffer.current_episode = [] # if there are enough transition in replay buffer, then train the agent if len(self.replay_buffer) < self.batch_size: return None self.n_train_steps += 1 return self._train(self.replay_buffer.sample(self.batch_size)) def _train(self, transitions): """ transitions: (Tuple[torch.Tensor]): tuple of (s, s', a, r, done) tuples """ self.optimizer.zero_grad() states, next_states, goals, actions, rewards, dones = transitions merged_states = torch.cat((next_states, goals.unsqueeze(3)), dim=3) if self.double_dqn: q_target_actions = ( self.dqn_local(merged_states).detach().max(1)[1].unsqueeze(1) ) q_targets_next = self.dqn_target(merged_states).detach() q_targets_next = q_targets_next.gather(1, q_target_actions) else: q_targets_next = ( self.dqn_target(merged_states).detach().max(1)[0].unsqueeze(1) ) q_targets = rewards + self.gamma * q_targets_next * (1 - dones) q_expcteds = self.dqn_local( torch.cat((states, goals.unsqueeze(3)), dim=3) ).gather(1, actions) loss = F.mse_loss(q_expcteds, q_targets) loss.backward() clip_grad_norm_(self.dqn_local.parameters(), 1) self.optimizer.step() if self.n_train_steps % self.freeze_step == 0: self._update_frozen_dqn() return loss.detach().cpu().numpy() def _update_frozen_dqn(self): self.dqn_target.load_state_dict(self.dqn_local.state_dict())
[ "numpy.dstack", "torch.nn.functional.mse_loss", "dqn.DQN", "logging.info", "random.random", "replay_buffer.ReplayBuffer", "numpy.arange", "torch.no_grad", "torch.from_numpy" ]
[((1351, 1394), 'replay_buffer.ReplayBuffer', 'ReplayBuffer', (['buffer_size'], {'gpu': 'gpu', 'her': 'her'}), '(buffer_size, gpu=gpu, her=her)\n', (1363, 1394), False, 'from replay_buffer import ReplayBuffer\n'), ((1404, 1432), 'logging.info', 'logging.info', (['self.dqn_local'], {}), '(self.dqn_local)\n', (1416, 1432), False, 'import logging\n'), ((1492, 1516), 'numpy.dstack', 'np.dstack', (['(state, goal)'], {}), '((state, goal))\n', (1501, 1516), True, 'import numpy as np\n'), ((3516, 3549), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['q_expcteds', 'q_targets'], {}), '(q_expcteds, q_targets)\n', (3526, 3549), True, 'import torch.nn.functional as F\n'), ((1638, 1653), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1651, 1653), False, 'import torch\n'), ((1716, 1731), 'random.random', 'random.random', ([], {}), '()\n', (1729, 1731), False, 'import random\n'), ((985, 1062), 'dqn.DQN', 'DQN', (['action_size'], {'input_shape': 'state_shape[:2]', 'in_channels': '(state_shape[2] + 1)'}), '(action_size, input_shape=state_shape[:2], in_channels=state_shape[2] + 1)\n', (988, 1062), False, 'from dqn import DQN\n'), ((1127, 1204), 'dqn.DQN', 'DQN', (['action_size'], {'input_shape': 'state_shape[:2]', 'in_channels': '(state_shape[2] + 1)'}), '(action_size, input_shape=state_shape[:2], in_channels=state_shape[2] + 1)\n', (1130, 1204), False, 'from dqn import DQN\n'), ((1853, 1880), 'numpy.arange', 'np.arange', (['self.action_size'], {}), '(self.action_size)\n', (1862, 1880), True, 'import numpy as np\n'), ((1533, 1557), 'torch.from_numpy', 'torch.from_numpy', (['_state'], {}), '(_state)\n', (1549, 1557), False, 'import torch\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt from image_processing.processing import denormalize_img from scipy import stats from scipy.signal import convolve2d def get_most_frequent_color(data, return_count=False): ''' Find the most frequent color in the arrays given. The color dimension is assumed to be the last one. Parameters ---------- data : numpy.array Array to find the most common color in. return_count : Boolean, optional Boolean that decides whether to return times the most common color occured in the data. The default is False. Returns ------- tuple The most common color (tuple of length 3). ''' colors = {} greatest_frequency = 0 color_picked = (255, 255, 255) arr = np.array([data[..., i].ravel() for i in range(data.shape[-1])]) arr = np.reshape(arr, (-1, data.shape[-1])) size = arr.shape[0] for i in range(size): color = tuple(arr[i]) if color in colors: colors[color] += 1 if colors[color] > greatest_frequency: greatest_frequency = colors[color] color_picked = color else: colors[color] = 1 if not return_count: return color_picked else: return greatest_frequency, color_picked def get_heatmap(images, method='mean', quantile=0.75): ''' Get heatmap of the given images. Parameters ---------- images : numpy.array Images to use for creating heatmap. method : one of ['mean', 'median', 'quantile'], optional Method to calculate heatmap with. The default is 'mean'. quantile : float, between [0.0 and 1.0], optional Only used when method chosen is quantile. The default is 0.75. Method quantile with quantile=0.5 is the same as method='median'. Returns ------- numpy.array The heatmap array of the images given. ''' if method == 'mean': return np.mean(images, axis=0) if method == 'median': return np.median(images, axis=0) if method == 'quntile': return np.quantile(images, quantile, axis=0) def estimate_character_mask(images, most_frequent_color=None, conv_correction_threshold=8): ''' Estimate masks for the provided images. Estimated masks should True where characters are and False where background is. On the original images it achieved 99.65% accuracy Parameters ---------- images : numpy.array Images to estimate mask on. most_frequent_color : typle, optional The color that is assumed to be background. The default is None. If not provided it will be estimated in the function (costly operation) conv_correction_threshold : int, optional The threshold used in correcting the estimated mask so it doesn't have any obvious holes in it. The default is 8 - the best value for estimating mask on originals. Returns ------- numpy.array (with dtype boolean) Boolean mask estimated for the provided images. ''' if images.shape[-1] == 4: # the 4th channel is usally the alpha channel if images.max() == 1.0: return images[..., -1] == 1.0 else: return images[..., -1] == 255 # Estimate mask from pixel values if not most_frequent_color: most_frequent_color = get_most_frequent_color(images) mask = (images[:, :, :, 0] != most_frequent_color[0]) |\ (images[:, :, :, 1] != most_frequent_color[1]) |\ (images[:, :, :, 2] != most_frequent_color[2]) if conv_correction_threshold > 0: lst = [np.pad(mask[i], 1, 'constant', constant_values=False) for i in range(mask.shape[0])] mask_padded = np.array(lst) filter = np.ones((3, 3)) # Use convolution operations to "repair holes" in the mask for i in range(mask_padded.shape[0]): conv_out = convolve2d(mask_padded[i], filter, mode='valid') m = conv_out >= conv_correction_threshold # if more than threshold neighbours were True then this one also should be True conv_out = conv_out.astype(bool) conv_out[m] = True conv_out[~m] = False mask[i] = mask[i] | conv_out # the logical sum of the initially estimated mask and the correction got from convolution return mask def get_left_offsets(masks): offsets = [] for arr in masks: offset = -1 # -1 is used where there is no character at all for i in range(masks.shape[2]): if arr[:, i].any(): offset = i break offsets.append(offset) return offsets def get_right_offsets(masks): offsets = [] for arr in masks: offset = -1 # -1 is used where there is no character at all for i in range(masks.shape[2]): if arr[:, arr.shape[1] - 1 - i].any(): offset = i break offsets.append(offset) return offsets def get_top_offsets(masks): offsets = [] for arr in masks: offset = -1 # -1 is used where there is no character at all for i in range(masks.shape[1]): if arr[i, :].any(): offset = i break offsets.append(offset) return offsets def get_bottom_offsets(masks): offsets = [] for arr in masks: offset = -1 # -1 is used where there is no character at all for i in range(masks.shape[1]): if arr[arr.shape[0] - 1 - i, :].any(): offset = i break offsets.append(offset) return offsets def calculate_colors_std(images): if images.shape[-1] == 4: images = images[..., :-1] return np.std(images, axis=(1, 2)) def calculate_pixels_number(mask): return mask.sum(axis=(1, 2)) def calculate_colors_histograms(data, mask=None, bins=10): data = data.astype(np.float32) #makes a copy if data.shape[-1] == 4: data = data[..., :-1] if mask is not None: data[~mask] = -1 min_val = data.min() max_val = data.max() step = (max_val - min_val) / bins l = [] for channel in range(data.shape[-1]): channel = data[..., channel] bins_stats = [] for i in range(bins): if i != bins - 1: bin_count = ((channel >= i * step) & (channel < (i + 1) * step)).sum(axis=(1, 2)) else: bin_count = ((channel >= i * step) & (channel <= (i + 1) * step)).sum(axis=(1, 2)) bins_stats.append(bin_count) l.append(bins_stats) return l def calculate_brightness(data, mask=None): if data.shape[-1] == 4: if mask is None: mask = data[..., -1] data = data[..., :-1] if len(data.shape) == 4: brightness_list = [] for i in range(data.shape[0]): img = data[i] if mask is not None: character_pixels = img[mask[i]] if character_pixels.size: brightness = np.mean(character_pixels) else: brightness = -1.0 brightness_list.append(brightness) else: brightness_list = [np.mean(data[mask])] return brightness_list def vertical_direction_change_score(data, mask=None): data = data.copy() if data.shape[-1] == 4: data = data[..., :-1] if mask is not None: data[~mask] = 0 if len(data.shape) == 4: ax = (1, 2, 3) score = np.abs(data[:, :-1, ...] - data[:, 1:, ...]).sum(axis=ax) else: ax = (0, 1, 2) score = np.abs(data[:-1, ...] - data[1:, ...]).sum(axis=ax) if mask is not None: score = score / (mask.sum(axis=ax[:-1]) + data.shape[ax[1]] * 2) / data.shape[-1] else: height = data.shape[1] width = data.shape[2] n_channels = data.shape[-1] score = score / (height - 1) / (width - 1) / n_channels return score def horizontal_direction_change_score(data, mask=None): data = data.copy() if data.shape[-1] == 4: data = data[..., :-1] if mask is not None: data[~mask] = 0 if len(data.shape) == 4: ax = (1, 2, 3) score = np.abs(data[..., :-1, :] - data[..., 1:, :]).sum(axis=ax) else: ax = (0, 1, 2) score = np.abs(data[:, :-1, :] - data[:, 1:, :]).sum(axis=ax) if mask is not None: score = score / (mask.sum(axis=ax[:-1]) + data.shape[ax[0]] * 2) / data.shape[-1] else: height = data.shape[1] width = data.shape[2] n_channels = data.shape[-1] score = score / (height - 1) / (width - 1) / n_channels return score if __name__ == '__main__': images = np.load('dataset.npy') images = denormalize_img(images) im_size = (images.shape[1] * images.shape[2]) df = pd.DataFrame(index=range(len(images))) colors = ['Red', 'Green', 'Blue'] max_value = images.max() masks = estimate_character_mask(images) assert(all(masks.sum(axis=(1, 2)) >= 0) and all(masks.sum(axis=(1, 2)) <= im_size)) df['LeftOffset'] = get_left_offsets(masks) assert(all((df['LeftOffset'] >= -1) | (df['LeftOffset'] < masks.shape[2]))) df['RightOffset'] = get_right_offsets(masks) assert(all((df['RightOffset'] >= -1) | (df['RightOffset'] < masks.shape[2]))) df['TopOffset'] = get_top_offsets(masks) assert(all((df['TopOffset'] >= -1) | (df['TopOffset'] < masks.shape[1]))) df['BottomOffset'] = get_bottom_offsets(masks) assert(all((df['BottomOffset'] >= -1) | (df['BottomOffset'] < masks.shape[1]))) assert(((df['LeftOffset'] == -1) & (df['RightOffset'] == -1) &\ (df['TopOffset'] == -1) & (df['BottomOffset'] == -1)).sum() == \ ((df['LeftOffset'] == -1) | (df['RightOffset'] == -1) |\ (df['TopOffset'] == -1) | (df['BottomOffset'] == -1)).sum()) df['Width'] = masks.shape[2] - df['RightOffset'] - df['LeftOffset'] df.loc[df['RightOffset'] == -1, 'Width'] = 0 assert(all((df['Width'] <= images.shape[2]) & (df['Width'] >= 0))) df['Height'] = masks.shape[1] - df['TopOffset'] - df['BottomOffset'] df.loc[df['RightOffset'] == -1, 'Height'] = 0 assert(all((df['Height'] <= images.shape[1]) & (df['Height'] >= 0))) df['BoundingBoxArea'] = df['Width'] * df['Height'] assert(all(df['BoundingBoxArea'] <= images.shape[1] * images.shape[2])) df['CharacterSize'] = calculate_pixels_number(masks) assert(all(df['CharacterSize'] <= df['BoundingBoxArea'])) df['SizeToImageRatio'] = df['CharacterSize'] / im_size assert(df['SizeToImageRatio'].max() <= 1.0) df['SizeToBoundingBoxRatio'] = df['CharacterSize'] / df['BoundingBoxArea'] df['SizeToBoundingBoxRatio'].fillna(0.0, inplace=True) assert(df['SizeToBoundingBoxRatio'].max() <= 1.0) df['BoundingBoxNonCharacterPixels'] = df['BoundingBoxArea'] - df['CharacterSize'] assert(df['BoundingBoxNonCharacterPixels'].min() >= 0) assert(all((df['BoundingBoxNonCharacterPixels'] < df['BoundingBoxArea']) | (df['BoundingBoxArea'] == 0))) variety = calculate_colors_std(images) assert(np.all((variety >= 0) & (variety <= max_value))) for i in range(variety.shape[1]): df['Variety' + colors[i]] = variety[:, i] del variety df['VerticalDirectionChangeScoreMasked'] = vertical_direction_change_score(images, masks) assert(all(df['VerticalDirectionChangeScoreMasked'] < images[..., :-1].max(axis=(1, 2, 3)))) #df['VerticalDirectionChangeScore'] = vertical_direction_change_score(images) df['HorizontalDirectionChangeScoreMasked'] = horizontal_direction_change_score(images, masks) #df['HorizontalDirectionChangeScore'] = horizontal_direction_change_score(images) assert(all(df['HorizontalDirectionChangeScoreMasked'] < images[..., :-1].max(axis=(1, 2, 3)))) histograms = np.array(calculate_colors_histograms(images, mask=masks)) #histograms2 = np.array(calculate_colors_histograms(images)) for i in range(histograms.shape[0]): for j in range(histograms.shape[1]): df['HistogramMasked' + colors[i] + f'Bin{j+1}'] = histograms[i, j] assert(all((histograms[i, j] >= 0) & (histograms[i, j] <= images.shape[1] * images.shape[2]))) #df['Histogram' + colors[i] + f'Bin{j+1}'] = histograms2[i, j] #del histograms #del histograms2 df['BrightnessMasked'] = calculate_brightness(images, masks) assert(all((df['BrightnessMasked'] >= -1) & (df['BrightnessMasked'] <= max_value))) #brightness2 = calculate_brightness(images)
[ "numpy.pad", "numpy.load", "numpy.quantile", "numpy.abs", "image_processing.processing.denormalize_img", "scipy.signal.convolve2d", "numpy.std", "numpy.median", "numpy.ones", "numpy.mean", "numpy.array", "numpy.reshape", "numpy.all" ]
[((876, 913), 'numpy.reshape', 'np.reshape', (['arr', '(-1, data.shape[-1])'], {}), '(arr, (-1, data.shape[-1]))\n', (886, 913), True, 'import numpy as np\n'), ((5806, 5833), 'numpy.std', 'np.std', (['images'], {'axis': '(1, 2)'}), '(images, axis=(1, 2))\n', (5812, 5833), True, 'import numpy as np\n'), ((8859, 8881), 'numpy.load', 'np.load', (['"""dataset.npy"""'], {}), "('dataset.npy')\n", (8866, 8881), True, 'import numpy as np\n'), ((8895, 8918), 'image_processing.processing.denormalize_img', 'denormalize_img', (['images'], {}), '(images)\n', (8910, 8918), False, 'from image_processing.processing import denormalize_img\n'), ((11288, 11335), 'numpy.all', 'np.all', (['((variety >= 0) & (variety <= max_value))'], {}), '((variety >= 0) & (variety <= max_value))\n', (11294, 11335), True, 'import numpy as np\n'), ((2009, 2032), 'numpy.mean', 'np.mean', (['images'], {'axis': '(0)'}), '(images, axis=0)\n', (2016, 2032), True, 'import numpy as np\n'), ((2075, 2100), 'numpy.median', 'np.median', (['images'], {'axis': '(0)'}), '(images, axis=0)\n', (2084, 2100), True, 'import numpy as np\n'), ((2144, 2181), 'numpy.quantile', 'np.quantile', (['images', 'quantile'], {'axis': '(0)'}), '(images, quantile, axis=0)\n', (2155, 2181), True, 'import numpy as np\n'), ((3789, 3802), 'numpy.array', 'np.array', (['lst'], {}), '(lst)\n', (3797, 3802), True, 'import numpy as np\n'), ((3820, 3835), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (3827, 3835), True, 'import numpy as np\n'), ((3682, 3735), 'numpy.pad', 'np.pad', (['mask[i]', '(1)', '"""constant"""'], {'constant_values': '(False)'}), "(mask[i], 1, 'constant', constant_values=False)\n", (3688, 3735), True, 'import numpy as np\n'), ((3981, 4029), 'scipy.signal.convolve2d', 'convolve2d', (['mask_padded[i]', 'filter'], {'mode': '"""valid"""'}), "(mask_padded[i], filter, mode='valid')\n", (3991, 4029), False, 'from scipy.signal import convolve2d\n'), ((7320, 7339), 'numpy.mean', 'np.mean', (['data[mask]'], {}), '(data[mask])\n', (7327, 7339), True, 'import numpy as np\n'), ((7626, 7670), 'numpy.abs', 'np.abs', (['(data[:, :-1, ...] - data[:, 1:, ...])'], {}), '(data[:, :-1, ...] - data[:, 1:, ...])\n', (7632, 7670), True, 'import numpy as np\n'), ((7733, 7771), 'numpy.abs', 'np.abs', (['(data[:-1, ...] - data[1:, ...])'], {}), '(data[:-1, ...] - data[1:, ...])\n', (7739, 7771), True, 'import numpy as np\n'), ((8349, 8393), 'numpy.abs', 'np.abs', (['(data[..., :-1, :] - data[..., 1:, :])'], {}), '(data[..., :-1, :] - data[..., 1:, :])\n', (8355, 8393), True, 'import numpy as np\n'), ((8456, 8496), 'numpy.abs', 'np.abs', (['(data[:, :-1, :] - data[:, 1:, :])'], {}), '(data[:, :-1, :] - data[:, 1:, :])\n', (8462, 8496), True, 'import numpy as np\n'), ((7129, 7154), 'numpy.mean', 'np.mean', (['character_pixels'], {}), '(character_pixels)\n', (7136, 7154), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import click import logging from pathlib import Path import pandas as pd from src.utils.config import Config from src.features import build_features from dotenv import find_dotenv, load_dotenv from sklearn.manifold import TSNE import umap from sklearn.decomposition import PCA import numpy as np from sklearn.preprocessing import RobustScaler as rs from sklearn.preprocessing import MinMaxScaler as mms from sklearn.preprocessing import StandardScaler as sd project_dir=Config.project_dir def process_data(): labels= pd.read_csv(project_dir / "data/raw/labels.csv") expression_data = pd.read_csv(project_dir / "data/raw/data.csv") #rename and Merge labels and features expression_data.rename({"Unnamed: 0":"sample"}, axis='columns', inplace =True) labels.rename({"Unnamed: 0":"sample"}, axis='columns', inplace =True) labled_expression_merged = pd.merge(labels,expression_data,on="sample") # save expression_data=expression_data.drop("sample",axis=1) expression_data.to_csv(project_dir/ "data/processed/expression_data_original.csv") labels=labels.drop("sample",axis=1) labels.to_csv(project_dir/ "data/processed/labels.csv") labled_expression_merged.to_csv(project_dir/ "data/processed/merged_expression_dataset.csv", index=True) """[Robust scaling ] Robust rescaling the expression levels of each gene, applying the formula : rescaled = (gene_expression - median(gene_expression)) / IQR(gene_expression) where IQR stands for Inter Quartile Range. """ expression_data_centered = rs().fit_transform(expression_data) df_expression_data_centered = pd.DataFrame(expression_data_centered,columns=expression_data.columns) df_expression_data_centered.to_csv(project_dir/ "data/processed/expression_data_centerted.csv") """[standard scaling ] """ expression_data_standardized = sd().fit_transform(expression_data) df_expression_data_standardized = pd.DataFrame(expression_data_standardized,columns=expression_data.columns) df_expression_data_standardized.to_csv(project_dir/ "data/processed/expression_data_standardized.csv") y = labels['Class'].values true_labels = np.array([Config.labels_map[element] for element in y]) df_true_labels = pd.DataFrame(true_labels,columns=["Class"]) df_true_labels.to_csv(project_dir/ "data/processed/true_labels.csv") expression_level_5000_HGV , features_5000_HGV= build_features.top_k_variance( expression_data.values, k=1000, names= expression_data.columns ) #--------------------- data reduction -----------------------# pca_reducer = PCA(n_components=2) pca_reducer.fit(expression_data ) pc = pca_reducer.transform(expression_data ) X_tsne = TSNE(n_components=2).fit_transform(expression_data) UMAP_COMPONENTS_REDUCTION = 2 UMAP_COMPONENTS_FEATURES = 20 UMAP_EPOCHS = 2000 manifold_reducer = umap.UMAP( n_components=UMAP_COMPONENTS_REDUCTION, n_neighbors=200, n_epochs=UMAP_EPOCHS, metric='cosine', min_dist=0.9) manifold = manifold_reducer.fit_transform(expression_data) # saving tranformed data components= ["c1","c2"] df_PCA =pd.DataFrame(pc,columns=components) df_PCA.to_csv(Config.project_dir/ "data/transformed/PCA_reduction.csv") df_PCA =pd.DataFrame(X_tsne,columns=components) df_PCA.to_csv(Config.project_dir/ "data/transformed/TSNA_reduction.csv") df_PCA =pd.DataFrame(manifold,columns=components) df_PCA.to_csv(Config.project_dir/ "data/transformed/UMAP_reduction.csv") # saving hvg df_expression_level_5000_HGV =pd.DataFrame(expression_level_5000_HGV,columns=features_5000_HGV) df_expression_level_5000_HGV.to_csv(Config.project_dir/ "data/transformed/expression_data_HVG_1000.csv") def get_data(data_type:str): """ this function : imports data Args: data_type (str): ["original","centered","standardized"] the type of data you want to import Returns: [tuple]: containing (the merged data , features , labels , true labels ) """ merged_data= pd.read_csv(Config.data / f"processed/merged_expression_dataset.csv",index_col=0) features=pd.read_csv(Config.data / f"processed/expression_data_{data_type}.csv",index_col=0) labels=pd.read_csv(Config.data / f"processed/labels.csv",index_col=0) true_labels=pd.read_csv(Config.data / f"processed/true_labels.csv",index_col=0) return merged_data,features,labels,true_labels def get_transformed_data(): """ this function : import reduced data Args: Returns: [tuple]: containing (the merged data , features , labels , true labels ) """ HGV= pd.read_csv(Config.data / f"transformed/expression_data_HVG_1000.csv",index_col=0) PCA=pd.read_csv(Config.data / f"transformed/PCA_reduction.csv",index_col=0) UMAP=pd.read_csv(Config.data / f"transformed/UMAP_reduction.csv",index_col=0) TSNA=pd.read_csv(Config.data / f"transformed/TSNA_reduction.csv",index_col=0) return HGV,PCA,UMAP,TSNA @click.command() @click.argument('input_filepath', type=click.Path(exists=True)) @click.argument('output_filepath', type=click.Path()) def main(input_filepath, output_filepath): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger = logging.getLogger(__name__) logger.info('making final data set from raw data') if __name__ == '__main__': log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(level=logging.INFO, format=log_fmt) # not used in this stub but often useful for finding various files project_dir = Path(__file__).resolve().parents[2] # find .env automagically by walking up directories until it's found, then # load up the .env entries as environment variables load_dotenv(find_dotenv()) main()
[ "pandas.DataFrame", "sklearn.preprocessing.StandardScaler", "logging.basicConfig", "dotenv.find_dotenv", "pandas.read_csv", "sklearn.preprocessing.RobustScaler", "pandas.merge", "sklearn.manifold.TSNE", "src.features.build_features.top_k_variance", "click.command", "umap.UMAP", "pathlib.Path",...
[((5140, 5155), 'click.command', 'click.command', ([], {}), '()\n', (5153, 5155), False, 'import click\n'), ((549, 597), 'pandas.read_csv', 'pd.read_csv', (["(project_dir / 'data/raw/labels.csv')"], {}), "(project_dir / 'data/raw/labels.csv')\n", (560, 597), True, 'import pandas as pd\n'), ((620, 666), 'pandas.read_csv', 'pd.read_csv', (["(project_dir / 'data/raw/data.csv')"], {}), "(project_dir / 'data/raw/data.csv')\n", (631, 666), True, 'import pandas as pd\n'), ((899, 945), 'pandas.merge', 'pd.merge', (['labels', 'expression_data'], {'on': '"""sample"""'}), "(labels, expression_data, on='sample')\n", (907, 945), True, 'import pandas as pd\n'), ((1657, 1728), 'pandas.DataFrame', 'pd.DataFrame', (['expression_data_centered'], {'columns': 'expression_data.columns'}), '(expression_data_centered, columns=expression_data.columns)\n', (1669, 1728), True, 'import pandas as pd\n'), ((1973, 2048), 'pandas.DataFrame', 'pd.DataFrame', (['expression_data_standardized'], {'columns': 'expression_data.columns'}), '(expression_data_standardized, columns=expression_data.columns)\n', (1985, 2048), True, 'import pandas as pd\n'), ((2206, 2261), 'numpy.array', 'np.array', (['[Config.labels_map[element] for element in y]'], {}), '([Config.labels_map[element] for element in y])\n', (2214, 2261), True, 'import numpy as np\n'), ((2283, 2327), 'pandas.DataFrame', 'pd.DataFrame', (['true_labels'], {'columns': "['Class']"}), "(true_labels, columns=['Class'])\n", (2295, 2327), True, 'import pandas as pd\n'), ((2454, 2551), 'src.features.build_features.top_k_variance', 'build_features.top_k_variance', (['expression_data.values'], {'k': '(1000)', 'names': 'expression_data.columns'}), '(expression_data.values, k=1000, names=\n expression_data.columns)\n', (2483, 2551), False, 'from src.features import build_features\n'), ((2669, 2688), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (2672, 2688), False, 'from sklearn.decomposition import PCA\n'), ((2957, 3081), 'umap.UMAP', 'umap.UMAP', ([], {'n_components': 'UMAP_COMPONENTS_REDUCTION', 'n_neighbors': '(200)', 'n_epochs': 'UMAP_EPOCHS', 'metric': '"""cosine"""', 'min_dist': '(0.9)'}), "(n_components=UMAP_COMPONENTS_REDUCTION, n_neighbors=200, n_epochs\n =UMAP_EPOCHS, metric='cosine', min_dist=0.9)\n", (2966, 3081), False, 'import umap\n'), ((3233, 3269), 'pandas.DataFrame', 'pd.DataFrame', (['pc'], {'columns': 'components'}), '(pc, columns=components)\n', (3245, 3269), True, 'import pandas as pd\n'), ((3358, 3398), 'pandas.DataFrame', 'pd.DataFrame', (['X_tsne'], {'columns': 'components'}), '(X_tsne, columns=components)\n', (3370, 3398), True, 'import pandas as pd\n'), ((3488, 3530), 'pandas.DataFrame', 'pd.DataFrame', (['manifold'], {'columns': 'components'}), '(manifold, columns=components)\n', (3500, 3530), True, 'import pandas as pd\n'), ((3659, 3725), 'pandas.DataFrame', 'pd.DataFrame', (['expression_level_5000_HGV'], {'columns': 'features_5000_HGV'}), '(expression_level_5000_HGV, columns=features_5000_HGV)\n', (3671, 3725), True, 'import pandas as pd\n'), ((4157, 4243), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'processed/merged_expression_dataset.csv')"], {'index_col': '(0)'}), "(Config.data / f'processed/merged_expression_dataset.csv',\n index_col=0)\n", (4168, 4243), True, 'import pandas as pd\n'), ((4252, 4340), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'processed/expression_data_{data_type}.csv')"], {'index_col': '(0)'}), "(Config.data / f'processed/expression_data_{data_type}.csv',\n index_col=0)\n", (4263, 4340), True, 'import pandas as pd\n'), ((4347, 4410), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'processed/labels.csv')"], {'index_col': '(0)'}), "(Config.data / f'processed/labels.csv', index_col=0)\n", (4358, 4410), True, 'import pandas as pd\n'), ((4426, 4494), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'processed/true_labels.csv')"], {'index_col': '(0)'}), "(Config.data / f'processed/true_labels.csv', index_col=0)\n", (4437, 4494), True, 'import pandas as pd\n'), ((4779, 4866), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'transformed/expression_data_HVG_1000.csv')"], {'index_col': '(0)'}), "(Config.data / f'transformed/expression_data_HVG_1000.csv',\n index_col=0)\n", (4790, 4866), True, 'import pandas as pd\n'), ((4870, 4942), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'transformed/PCA_reduction.csv')"], {'index_col': '(0)'}), "(Config.data / f'transformed/PCA_reduction.csv', index_col=0)\n", (4881, 4942), True, 'import pandas as pd\n'), ((4951, 5024), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'transformed/UMAP_reduction.csv')"], {'index_col': '(0)'}), "(Config.data / f'transformed/UMAP_reduction.csv', index_col=0)\n", (4962, 5024), True, 'import pandas as pd\n'), ((5033, 5106), 'pandas.read_csv', 'pd.read_csv', (["(Config.data / f'transformed/TSNA_reduction.csv')"], {'index_col': '(0)'}), "(Config.data / f'transformed/TSNA_reduction.csv', index_col=0)\n", (5044, 5106), True, 'import pandas as pd\n'), ((5478, 5505), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (5495, 5505), False, 'import logging\n'), ((5665, 5720), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': 'log_fmt'}), '(level=logging.INFO, format=log_fmt)\n', (5684, 5720), False, 'import logging\n'), ((5195, 5218), 'click.Path', 'click.Path', ([], {'exists': '(True)'}), '(exists=True)\n', (5205, 5218), False, 'import click\n'), ((5260, 5272), 'click.Path', 'click.Path', ([], {}), '()\n', (5270, 5272), False, 'import click\n'), ((5999, 6012), 'dotenv.find_dotenv', 'find_dotenv', ([], {}), '()\n', (6010, 6012), False, 'from dotenv import find_dotenv, load_dotenv\n'), ((1587, 1591), 'sklearn.preprocessing.RobustScaler', 'rs', ([], {}), '()\n', (1589, 1591), True, 'from sklearn.preprocessing import RobustScaler as rs\n'), ((1899, 1903), 'sklearn.preprocessing.StandardScaler', 'sd', ([], {}), '()\n', (1901, 1903), True, 'from sklearn.preprocessing import StandardScaler as sd\n'), ((2789, 2809), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)'}), '(n_components=2)\n', (2793, 2809), False, 'from sklearn.manifold import TSNE\n'), ((5811, 5825), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (5815, 5825), False, 'from pathlib import Path\n')]
# encoding: utf-8 # # @Author: <NAME>, <NAME> # @Date: Nov 15, 2021 # @Filename: field.py # @License: BSD 3-Clause # @Copyright: <NAME>, <NAME> import astropy.units as u import numpy as np import pyphot import progressbar # import matplotlib.pyplot as plt # from pyphot import unit from astropy.io import fits from astropy.coordinates import SkyCoord from astropy.table import Table, vstack from astroquery.gaia import Gaia from spectres import spectres # from scipy.interpolate import interp1d from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR import os # config parameters Gaia.MAIN_GAIA_TABLE = "gaiadr2.gaia_source" # Select Data Release 2. EDR3 is missing temperatures Gaia.ROW_LIMIT = -1 kms = u.km / u.s c = 299792.458 * kms class StarsList: """ Container of the list of stars for the LVMField object. This class allows to create, modify and store the list of stars needed by the LVMField object to create the datacube that will be feed to the LVM simulator. The class can also open a previously saved fits file with the correct informations. If no filename is provided, the class is initiated with an empty table, and stars can be added manually or by quering gaia on a particolar field. Parameters: ra (float, optional): right ascension of the center of the field. This parameter is expected in degree. Defaults to 0. dec (float, optional): declination of the center of the field. This parameter is expected in degree. Defaults to 0. radius (float, optional): radius of the field to be searched in Gaia. Defaults to 1. filename (str, optional): name of the file to be opened. If it is not provided an empty object is created using the default options or the user provided ones. Defaults to None. dir (str, optional): directory where the file to open is located. Defaults to WORK_DIR unit_ra (astropy.unit, optional): unit associated to the right ascension. Defaults to u.deg unit_dec (astropy.unit, optional): unit associated to the declination. Defaults to u.deg unit_radius (astropy.unit, optional): unit associated to the radius variable. Defaults to u.arcmin colnames (list, optional): list of column names to initiate the table containing the list of stars. types (list, optional): data type to be associated to each column in the table Attributes: TBU colnames (list): list of column names to initiate the table containing the list of stars. stars_table (astropy.table): table containing the list of stars and their parameters """ def __init__(self, ra=0, dec=0, radius=1, filename=None, dir=WORK_DIR, unit_ra=u.deg, unit_dec=u.deg, unit_radius=u.arcmin, colnames=['star_id', 'ra', 'dec', 'phot_g_mean_mag', 'phot_bp_mean_mag', 'phot_rp_mean_mag', 'teff_val', 'a_g_val', 'e_bp_min_rp_val', 'radial_velocity', 'gaia', 'source_id'], types=[int, float, float, float, float, float, float, float, float, float, bool, int], units=[None, u.deg, u.deg, u.mag, u.mag, u.mag, u.K, u.mag, u.mag, kms, None, None] ): # if a filename is given open the file, otherwise create an object with the default # or user provided details if filename is not None: # filename = os.path.join(dir, filename) self._read_from_fits(filename, dir=dir) else: # create an empty table to contain the list of stars self.ra = ra self.dec = dec self.radius = radius # fix the unit of measurements if isinstance(self.ra, (float, int)): self.ra *= unit_ra if isinstance(self.dec, (float, int)): self.dec *= unit_dec if isinstance(self.radius, (float, int)): self.radius *= unit_radius self.center = SkyCoord(self.ra, self.dec) self.colnames = colnames self.colunits = units self.stars_table = Table(names=self.colnames, dtype=types, units=units) self.stars_table.add_index('star_id') self.wave = None # empty for now self.spectra = None # empty for now self.library = None # empty for now def __len__(self): return len(self.stars_table) def add_star(self, ra, dec, gmag, teff, ag, v): """ Manually add a single star to the list. Manually add a star to the list. All the parameters are specified by the user. Temperature and extinction are needed to associate a spectrum to the star in order to build the datacube. The G-band magnitude will be used to normalize the spectra. Parameters: ra (float): right ascension of the star in degrees. dec (float): declination of the star in degrees. gmag (float): gaia G band magnitude of the star teff (float): effective temperature of the star (it is used to look for the correct spectrum) in K. ag (float): extinction on the gaia G band. v (float): radial velocity of the star. """ # check if the star is within the simulated FOV self._check_inside(ra, dec) new_row = {'star_id': len(self.stars_table) + 1, 'ra': ra, 'dec': dec, 'phot_g_mean_mag': gmag, 'teff_val': teff, 'a_g_val': ag, 'radial_velocity': v, 'gaia': False, 'source_id': 0, } log.info('star {} with Teff {}, Gmag {} and velocity {} added at position ({} , {})' .format(new_row['star_id'], new_row['teff_val'], new_row['phot_g_mean_mag'], new_row['radial_velocity'], new_row['ra'], new_row['dec'])) self.stars_table.add_row(new_row) def _check_inside(self, ra, dec): """ Check if the manually added star falls within the required FOV Args: ra (float): ra of the manually added star. dec (float): dec of the manually added star. Raises: ValueError: raise an error if the star is outside the required FOV """ star_coord = SkyCoord(ra, dec, unit=(u.deg, u.deg)) sep = star_coord.separation(self.center) if sep > self.radius: raise ValueError('This star is outside the simulated field of view...') def add_gaia_stars(self, gmag_limit=17): """ Add stars from the Gaia DR2 catalog to the stars list. Query the Gaia DR2 catalog, select the stars brighter than gmag_limit and add the result to the list of stars used to simulated the observed field. Parameters: gmag_limit (float, optional): Maximum magnitude for a star to be included in the list. Defaults to 17. """ try: result = query_gaia(self.center, self.radius.to(u.deg)) except TimeoutError: log.warning('GAIA DR2 server timed out. Continuing without gaia stars') return # select only the relevant columns colnames = [item for item in self.colnames if item not in ['gaia', 'star_id']] result = result[colnames] # apply a filter on the magnitude of the stars mask = result['phot_g_mean_mag'] < gmag_limit result = result[mask] if len(result) == 0: log.warning('All the stars have been rejected!') else: log.info('{} stars are fainter than {} and have been rejected' .format(len(mask) - mask.sum(), gmag_limit)) # adding the star_id idx = range(len(self) + 1, len(result) + 1) result['star_id'] = idx # setting the gaia flag on the table result['gaia'] = np.ones(len(result), dtype=bool) # finally saving the new table self.stars_table = vstack([self.stars_table, result]) def associate_spectra(self, shift=False, append=False, library=STELLAR_LIBS): """ Associate spectra to the identifyied stars. It can both associate spectra to the full list or append them if the first part of the list have already been processed. Args: shift (bool, optional): Shift spectra according to the velocity included in the catalog. Defaults to False. append (bool, optional): If some spectra have been associated to the first part of the stars in the list, it can be used to process only the newly added stars. Defaults to False. library (str, optional): path to the spectral library to use. Defaults to the file defined as stellar_library_name in config (should be stored in data directory). """ self.library = os.path.split(library)[1] log.info(f'Associating spectra to stars using library {self.library}...') if self.spectra is None: self.wave = self._get_wavelength_array(library) if append and self.spectra is not None: log.info('Appending new spectra to existing ones') self._append_spectra(library, shift=False) else: self._associate_spectra(library, shift=False) def _associate_spectra(self, library, shift=False): """ Associate a spectrum from a syntetic library to each one of the stars in the list. Parameters: library (str): path to the spectral library to use. shift (bool, optional): shift the spectra according to the radial velocity of the stars. Defaults to False """ tmp_spectra = np.zeros((len(self), len(self.wave))) bar = progressbar.ProgressBar(max_value=len(self)).start() for i, row in enumerate(self.stars_table): spectrum = get_spectrum(row['teff_val'], library) if shift and row['radial_velocity']: spectrum = shift_spectrum(self.wave, spectrum, row['radial_velocity']) tmp_spectra[i] = spectrum bar.update(i) bar.finish() self.spectra = tmp_spectra def _append_spectra(self, library, shift=False): """ Associate spectra to newly added stars appending the spectra at the end of the list. Parameters: library (str): path to the spectral library to use. shift (bool, optional): shift the spectra according to the radial velocity of the stars. Defaults to False """ nstars = len(self) nspectra = len(self.spectra) if nstars - nspectra == 0: log.info('All stars have an associated spectrum') return tmp_spectra = np.zeros((nstars - nspectra, len(self.wave))) bar = progressbar.ProgressBar(max_value=nstars - nspectra).start() for i, row in enumerate(self.stars_table): if i >= nspectra: spectrum = get_spectrum(row['teff_val'], library) if shift and row['radial_velocity']: spectrum = shift_spectrum(self.wave, spectrum, row['radial_velocity']) tmp_spectra[i - nspectra] = spectrum bar.update(i - nspectra) bar.finish() self.spectra = np.append(self.spectra, tmp_spectra, axis=0) def rescale_spectra(self): """ This function rescales the synthetic spectra in order to match them to the gaia photometry. It works only with the G band of gaia DR2. """ log.info(f'Rescaling {len(self)} synthetic spectra.') passband = pyphot.get_library()['GaiaDR2_G'] # convert gaia magnitudes to fluxes in erg etc # I could do directly with mag, but pyphot has some problems when working on a single # spectra with magnitudes gaia_fluxes = passband.Vega_zero_flux * \ 10**(-0.4 * self.stars_table['phot_g_mean_mag'].data) synth_flux = passband.get_flux(self.wave.value, self.spectra, axis=1) scale_factor = gaia_fluxes / synth_flux # scale factor for the spectra # I don't understand why but it does not work by just multiplying. # I'm not sure I want to keep going with this package for i, factor in enumerate(scale_factor): self.spectra[i] = self.spectra[i] * factor @staticmethod def _get_wavelength_array(filename=STELLAR_LIBS, unit=u.AA): with fits.open(filename) as hdu: wave = hdu['WAVE'].data * unit return wave def apply_extinction(self): """ Apply extinction to a stellar spectrum, to be implemented. """ pass def compute_star_positions(self, wcs): """ Converting world coordinates to pixel coordinates. It can be used to build, in the future, a datacube or a 2D map Args: wcs (astropy.wcs): wcs of the source field that should be produced. """ log.info('Transforming world coordinates to pixel coordinates') x, y = wcs.all_world2pix(self.stars_table['ra'], self.stars_table['dec'], 0) self.stars_table['x'] = x self.stars_table['y'] = y self.stars_table['x'].unit = u.pix self.stars_table['y'].unit = u.pix def save_to_fits(self, outname='starlist.fits.gz', outdir=WORK_DIR, overwrite=True): """ Save the StarList as a fits file. Parameters: outname (str, optional): name of the output file. Defaults to 'starlist.fits.gz'. outdir (str, optional): path to the output directory. Defaults to WORK_DIR. overwrite (bool, optional): overwrite the file if it already exist. Defaults to True. """ # confirming that outfile is a fits or a compressed fits file accepted_types = ('.fits', '.fits.gz') if not outname.endswith(accepted_types): outname += '.fits.gz' log.warning(f'the name of the output file has been updated to {outname}') primary = fits.PrimaryHDU() # creating the primary hdu # adding extension names in the primary header primary.header['EXT1'] = 'TABLE' primary.header['EXT2'] = 'FLUX' primary.header['EXT3'] = 'WAVE' primary.header['LIBRARY'] = (self.library, 'Stellar library') # Add other info in the header primary.header['RA'] = (self.ra.to(u.deg).value, 'Right ascension of the center of the field (deg)') primary.header['DEC'] = (self.dec.to(u.deg).value, 'Declination of the center of the field (deg)') primary.header['RADIUS'] = (self.radius.to(u.deg).value, 'Radius of the field (deg)') table = fits.table_to_hdu(self.stars_table) # creating the table extension table.header['EXTNAME'] = 'TABLE' # add name to the extension spectra = fits.ImageHDU(data=self.spectra, name='FLUX') # creating the fluxes extension wave = fits.ImageHDU(data=self.wave.value, name='WAVE') # creating the wave extension hdul = fits.HDUList([primary, table, spectra, wave]) filename = os.path.join(outdir, outname) if overwrite and os.path.isfile(filename): log.warning(f'The file {filename} already exist and it will be overwritten') hdul.writeto(filename, overwrite=overwrite) def _read_from_fits(self, filename, dir=WORK_DIR): """ Read a starlist object from a fits file. The structure of the file must be the one required by the save_to_fits method and it must contain all the informations required to build a StarList object. It should be used to only open data previously saved by the save_to_fits method Parameters: filename (str): name of the file to open. It must be a .fits or a .fits.gz file dir (str, optional): directory where the file is located. Defaults to WORK_DIR. Raises: ValueError: raises a ValueError when the file is not a .fits or a .fits.gz file. """ accepted_types = ('.fits', '.fits.gz') if not filename.endswith(accepted_types): raise ValueError('Only .fits or .fits.gz files are accepted') filename = os.path.join(dir, filename) if not os.path.isfile(filename): log.error("File with stars is not found: {}".format(filename)) return # reading the file with fits.open(filename) as hdu: # opening the main extensions self.stars_table = Table.read(hdu['TABLE']) self.spectra = hdu['FLUX'].data self.wave = hdu['WAVE'].data * u.AA # recovering main info from primary header self.ra = hdu[0].header['RA'] * u.deg self.dec = hdu[0].header['DEC'] * u.deg self.radius = hdu[0].header['RADIUS'] * u.deg self.center = SkyCoord(self.ra, self.dec) # recovering info on the name of the columns and their units self.colnames = self.stars_table.colnames self.colunits = [] for col in self.colnames: self.colunits.append(self.stars_table[col].unit) self.stars_table.add_index('star_id') def generate_gaia(self, wcs, gmag_limit=17, shift=False): """ Generate the star list and associate the spectra automatically Args: gmag_limit (float, optional): Maximum magnitude for a star to be included in the list. Defaults to 17. shift (bool, optional): shift the spectra according to the radial velocity of the stars. Defaults to False. """ self.add_gaia_stars(gmag_limit=gmag_limit) self.compute_star_positions(wcs) self.associate_spectra(shift=shift) self.rescale_spectra() def generate_stars_manually(self, wcs, parameters, shift=False): ra_list = parameters.get('ra', [0]) dec_list = parameters.get('dec', [0]) gmag_list = parameters.get('gmag', [17]) teff_list = parameters.get('teff', [6000]) ag_list = parameters.get('ag', [0]) v_list = parameters.get('v', [0]) for ra, dec, gmag, teff, ag, v \ in zip(ra_list, dec_list, gmag_list, teff_list, ag_list, v_list): self.add_star(ra, dec, gmag, teff, ag, v) self.compute_star_positions(wcs) self.associate_spectra(shift=shift) self.rescale_spectra() def remove_star(self, id): """ Remove a star with a specific star_id. That is something that breaks the object when it is saved, a star is removed and then re added Args: id (int): star_id of the star to be removed """ # checking if id exist if id not in self.stars_table['star_id']: log.warning(f'There is no star with star_id = {id}') return # if it exists remove the star log.info(f'Removing star (star_id: {id})') mask = self.stars_table['star_id'] == id # mask identifying the correct star self.stars_table = self.stars_table[~mask].copy() # select all the other stars # self.stars_table.remove_row(id) # if spectra where already assigned, remove also the spectrum if self.spectra is not None: self.spectra = self.spectra[~mask].copy() assert len(self.stars_table) == len(self.spectra), \ 'The star and spectrum where not removed correctly' def recover_star_at_position(self, coords, wcs, pixel=True, radius=1): """ Check if there are stars in a certain position, and return the entry and the spectrum Args: coords (tuple): coordinates where to check. It can be both in ra, dec or in pixels wcs (astropy.wcs): wcs object to convert coordinates to pixels pixel (bool, optional): if True the coordinates are in pixel, else are in ra and dec (degrees). Defaults to True. radius (float, optional): radius to check around the central coordinates. Defaults to 1. Returns: (astropy.table or astropy.table.row): row(s) of the table representing the identified stars (array) array containing the spectra of the selected stars """ if not pixel: coords = SkyCoord(coords) coords = wcs.all_world2pix(coords.ra.deg, coords.deg.dec, 0) if 'x' not in self.stars_table['x']: self.compute_star_positions(wcs) distance = np.sqrt((coords[0] - self.stars_table['x']) ** 2 + (coords[1] - self.stars_table['y']) ** 2) mask = distance < radius if mask.sum() == 0: log.warning('No star found at the required position') return None, None stars = self.stars_table[mask] spectra = self.spectra[mask] return stars, spectra ################################################################################ def get_spectrum(temp, library): """ Extract a spectrum from a provided library. The library should have at least two extensions, one called TEMP which includes the physical properties of the associated spectrum, and one called FLUX which contains an array where each column is a spectrum. Args: temp (float): temperature of the star for which the spectrum is needed library (str): path to the desired stellar spectral library Returns: array: simulated stellar spectrum with T ~ temp """ with fits.open(library) as hdu: properties = Table.read(hdu['TEMP']) fluxes = hdu['FLUX'].data delta = np.abs(properties['T'] - temp) idx = np.argmin(delta) spectrum = fluxes[idx] return spectrum ################################################################################ def query_gaia(coord, radius): """ Query Gaia DR2 catalog for sources in a given field. Query the Gaia DR2 catalog around a position given by 'coord' and a radius given by radius. Only the columns included in colnames are selected before returning the query. Parameters: coord (SkyCoord): coordinates of the field as a SkyCoord object. radius (Quantity): Radius of the field to be searched for around the central coordinates. Returns: astropy.Table: astropy table containing the result of the query. """ job = Gaia.cone_search_async(coord, radius) results = job.get_results() if len(results) == 0: log.warning('No star detected!') else: log.info('{} Gaia stars in the field' .format(len(results))) return results ################################################################################ def shift_spectrum(wave, flux, radial_velocity, unit_v=kms): """ Apply a shift to a spectrum based on the radial_velocity of the object. First corrects the wave and flux array, then resample the spectrum using the original wavelength range. Args: wave (array-like): array containing the wavelenght axis of the spectrum. flux (array-like): array with the fluxes radial_velocity (float): radial velocity of the object used for the shift unit_v (astropy.unit): unit of the radial_velocity Returns: array-like: resampled and shifted spectrum """ radial_velocity *= unit_v z = radial_velocity / c new_wave = wave * (1 + z) new_flux = flux / (1 + z) resampled = spectres(wave.value, new_wave.value, new_flux) return resampled # if __name__ == '__main__': # # # wave = np.arange(3000, 10000.1, 0.1) # # # open_gaia_passband(wave, band='G') # starlist = StarsList(0, 0, 2) # # starlist.add_gaia_stars(17) # # print(len(starlist)) # starlist.add_star(0, 0, 7, 10000, 0.4) # # starlist.add_star(0, 0, 15, 20000, 0.4) # starlist.associate_spectra() # starlist.rescale_spectra() # # print(starlist.stars_table)
[ "astropy.coordinates.SkyCoord", "numpy.abs", "astropy.io.fits.PrimaryHDU", "pyphot.get_library", "numpy.argmin", "lvmdatasimulator.log.warning", "os.path.isfile", "lvmdatasimulator.log.info", "astropy.io.fits.HDUList", "os.path.join", "astropy.io.fits.ImageHDU", "numpy.append", "spectres.spe...
[((22804, 22834), 'numpy.abs', 'np.abs', (["(properties['T'] - temp)"], {}), "(properties['T'] - temp)\n", (22810, 22834), True, 'import numpy as np\n'), ((22845, 22861), 'numpy.argmin', 'np.argmin', (['delta'], {}), '(delta)\n', (22854, 22861), True, 'import numpy as np\n'), ((23601, 23638), 'astroquery.gaia.Gaia.cone_search_async', 'Gaia.cone_search_async', (['coord', 'radius'], {}), '(coord, radius)\n', (23623, 23638), False, 'from astroquery.gaia import Gaia\n'), ((24731, 24777), 'spectres.spectres', 'spectres', (['wave.value', 'new_wave.value', 'new_flux'], {}), '(wave.value, new_wave.value, new_flux)\n', (24739, 24777), False, 'from spectres import spectres\n'), ((6800, 6838), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['ra', 'dec'], {'unit': '(u.deg, u.deg)'}), '(ra, dec, unit=(u.deg, u.deg))\n', (6808, 6838), False, 'from astropy.coordinates import SkyCoord\n'), ((8503, 8537), 'astropy.table.vstack', 'vstack', (['[self.stars_table, result]'], {}), '([self.stars_table, result])\n', (8509, 8537), False, 'from astropy.table import Table, vstack\n'), ((9492, 9565), 'lvmdatasimulator.log.info', 'log.info', (['f"""Associating spectra to stars using library {self.library}..."""'], {}), "(f'Associating spectra to stars using library {self.library}...')\n", (9500, 9565), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((11972, 12016), 'numpy.append', 'np.append', (['self.spectra', 'tmp_spectra'], {'axis': '(0)'}), '(self.spectra, tmp_spectra, axis=0)\n', (11981, 12016), True, 'import numpy as np\n'), ((13693, 13756), 'lvmdatasimulator.log.info', 'log.info', (['"""Transforming world coordinates to pixel coordinates"""'], {}), "('Transforming world coordinates to pixel coordinates')\n", (13701, 13756), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((14809, 14826), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', ([], {}), '()\n', (14824, 14826), False, 'from astropy.io import fits\n'), ((15570, 15605), 'astropy.io.fits.table_to_hdu', 'fits.table_to_hdu', (['self.stars_table'], {}), '(self.stars_table)\n', (15587, 15605), False, 'from astropy.io import fits\n'), ((15728, 15773), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', ([], {'data': 'self.spectra', 'name': '"""FLUX"""'}), "(data=self.spectra, name='FLUX')\n", (15741, 15773), False, 'from astropy.io import fits\n'), ((15822, 15870), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', ([], {'data': 'self.wave.value', 'name': '"""WAVE"""'}), "(data=self.wave.value, name='WAVE')\n", (15835, 15870), False, 'from astropy.io import fits\n'), ((15918, 15963), 'astropy.io.fits.HDUList', 'fits.HDUList', (['[primary, table, spectra, wave]'], {}), '([primary, table, spectra, wave])\n', (15930, 15963), False, 'from astropy.io import fits\n'), ((15984, 16013), 'os.path.join', 'os.path.join', (['outdir', 'outname'], {}), '(outdir, outname)\n', (15996, 16013), False, 'import os\n'), ((17153, 17180), 'os.path.join', 'os.path.join', (['dir', 'filename'], {}), '(dir, filename)\n', (17165, 17180), False, 'import os\n'), ((19914, 19956), 'lvmdatasimulator.log.info', 'log.info', (['f"""Removing star (star_id: {id})"""'], {}), "(f'Removing star (star_id: {id})')\n", (19922, 19956), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((21618, 21715), 'numpy.sqrt', 'np.sqrt', (["((coords[0] - self.stars_table['x']) ** 2 + (coords[1] - self.stars_table[\n 'y']) ** 2)"], {}), "((coords[0] - self.stars_table['x']) ** 2 + (coords[1] - self.\n stars_table['y']) ** 2)\n", (21625, 21715), True, 'import numpy as np\n'), ((22684, 22702), 'astropy.io.fits.open', 'fits.open', (['library'], {}), '(library)\n', (22693, 22702), False, 'from astropy.io import fits\n'), ((22733, 22756), 'astropy.table.Table.read', 'Table.read', (["hdu['TEMP']"], {}), "(hdu['TEMP'])\n", (22743, 22756), False, 'from astropy.table import Table, vstack\n'), ((23706, 23738), 'lvmdatasimulator.log.warning', 'log.warning', (['"""No star detected!"""'], {}), "('No star detected!')\n", (23717, 23738), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((4227, 4254), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['self.ra', 'self.dec'], {}), '(self.ra, self.dec)\n', (4235, 4254), False, 'from astropy.coordinates import SkyCoord\n'), ((4357, 4409), 'astropy.table.Table', 'Table', ([], {'names': 'self.colnames', 'dtype': 'types', 'units': 'units'}), '(names=self.colnames, dtype=types, units=units)\n', (4362, 4409), False, 'from astropy.table import Table, vstack\n'), ((8014, 8062), 'lvmdatasimulator.log.warning', 'log.warning', (['"""All the stars have been rejected!"""'], {}), "('All the stars have been rejected!')\n", (8025, 8062), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((9457, 9479), 'os.path.split', 'os.path.split', (['library'], {}), '(library)\n', (9470, 9479), False, 'import os\n'), ((9721, 9771), 'lvmdatasimulator.log.info', 'log.info', (['"""Appending new spectra to existing ones"""'], {}), "('Appending new spectra to existing ones')\n", (9729, 9771), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((11327, 11376), 'lvmdatasimulator.log.info', 'log.info', (['"""All stars have an associated spectrum"""'], {}), "('All stars have an associated spectrum')\n", (11335, 11376), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((12308, 12328), 'pyphot.get_library', 'pyphot.get_library', ([], {}), '()\n', (12326, 12328), False, 'import pyphot\n'), ((13144, 13163), 'astropy.io.fits.open', 'fits.open', (['filename'], {}), '(filename)\n', (13153, 13163), False, 'from astropy.io import fits\n'), ((14716, 14789), 'lvmdatasimulator.log.warning', 'log.warning', (['f"""the name of the output file has been updated to {outname}"""'], {}), "(f'the name of the output file has been updated to {outname}')\n", (14727, 14789), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((16039, 16063), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (16053, 16063), False, 'import os\n'), ((16077, 16153), 'lvmdatasimulator.log.warning', 'log.warning', (['f"""The file {filename} already exist and it will be overwritten"""'], {}), "(f'The file {filename} already exist and it will be overwritten')\n", (16088, 16153), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((17196, 17220), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (17210, 17220), False, 'import os\n'), ((17356, 17375), 'astropy.io.fits.open', 'fits.open', (['filename'], {}), '(filename)\n', (17365, 17375), False, 'from astropy.io import fits\n'), ((17458, 17482), 'astropy.table.Table.read', 'Table.read', (["hdu['TABLE']"], {}), "(hdu['TABLE'])\n", (17468, 17482), False, 'from astropy.table import Table, vstack\n'), ((17817, 17844), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['self.ra', 'self.dec'], {}), '(self.ra, self.dec)\n', (17825, 17844), False, 'from astropy.coordinates import SkyCoord\n'), ((19794, 19846), 'lvmdatasimulator.log.warning', 'log.warning', (['f"""There is no star with star_id = {id}"""'], {}), "(f'There is no star with star_id = {id}')\n", (19805, 19846), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((21417, 21433), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['coords'], {}), '(coords)\n', (21425, 21433), False, 'from astropy.coordinates import SkyCoord\n'), ((21813, 21866), 'lvmdatasimulator.log.warning', 'log.warning', (['"""No star found at the required position"""'], {}), "('No star found at the required position')\n", (21824, 21866), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((7576, 7647), 'lvmdatasimulator.log.warning', 'log.warning', (['"""GAIA DR2 server timed out. Continuing without gaia stars"""'], {}), "('GAIA DR2 server timed out. Continuing without gaia stars')\n", (7587, 7647), False, 'from lvmdatasimulator import log, STELLAR_LIBS, WORK_DIR\n'), ((11480, 11532), 'progressbar.ProgressBar', 'progressbar.ProgressBar', ([], {'max_value': '(nstars - nspectra)'}), '(max_value=nstars - nspectra)\n', (11503, 11532), False, 'import progressbar\n')]
import stk from rdkit.Chem import AllChem as rdkit import numpy as np import itertools as it from typing import List from rdkit_tools import ( get_cavity_size, get_windows, get_max_diameter, set_position, ) from pymongo import MongoClient import random from pymongo.errors import DuplicateKeyError import argparse import pandas as pd from tqdm import tqdm from functools import partial import os from multiprocessing import cpu_count from pathos.pools import _ProcessPool as ProcessPool def collapsed(mol, max_diameter, window_diff, cavity_size): """Determines whether a molecule is collapsed or not using the below criteria. Args: mol: Molecule to identify whether it is collapsed. max_diameter: Maximum distance between two atoms in the molecule. window_diff: Mean difference is window diameters. cavity_size: """ md = max_diameter if window_diff is None: return True elif ((4 * window_diff) / (md * 4)) < 0.035 and cavity_size > 1: return False else: return def get_window_difference(windows): """Calculates the average window difference for all windows detected with pyWindow. Args: windows: Windows of cage detected using pyWindow. Returns: (float): Mean window difference across all windows. """ clusters = [list(windows)] # After this sum the differences in each group and then # sum the group totals. diff_sums = [] for cluster in clusters: diff_sum = sum(abs(w1 - w2) for w1, w2 in it.combinations(cluster, 2)) diff_num = sum(1 for _ in it.combinations(cluster, 2)) diff_sums.append(diff_sum / diff_num) return np.mean(diff_sums) def cavity_size(mol): """Calculates cavity size of a molecule. Args: mol: Molecule to calculate cavity size of. Returns: (float): Cavity size of cage. """ cavity = -get_cavity_size(mol, [0, 0, 0], -1) return cavity if cavity > 0 else 0.0 def make_entry(cage, output_collection, db_url, database): """Gets geometrically properties of the cage. Args: cage: Cage to determine whether it is collasped or not. Returns: (dict): Dictionary containing geometrical properties of the cage. """ # Check if entry already inserted. client = MongoClient(db_url) db = client[database] if db[output_collection].count_documents({"_id": str(cage)}) != 0: return mol = rdkit.Mol(cage.to_rdkit_mol()) mol.RemoveAllConformers() mol.AddConformer(cage.to_rdkit_mol().GetConformer(-1)) windows = get_windows(mol) md = 0.0 if windows is None: wd = window_std = None else: w = sorted(windows, reverse=True)[:4] wd = get_window_difference(w) if len(w) == 4 else None window_std = np.std(w) if len(w) == 4 else None if wd and window_std: md = get_max_diameter(mol) mol = set_position(mol, [0, 0, 0]) cs = cavity_size(mol) record = { "_id": cage._id, "name": str(cage), "collapsed": collapsed(mol, md, wd, cs), "cavity_size": cs, "max_diameter": md, "all_windows": windows, "window_diameter": wd, "window_standard_deviation": window_std, "stk_obj": cage.to_dict(), } try: result = db[output_collection].insert_one(record) print( f"Succesfully inserted {result.inserted_id}.", flush=True ) except DuplicateKeyError as err: print(err) return # Return if all fails. record = { "_id": cage._id, "name": str(cage), "collapsed": True, "cavity_size": 0.0, "max_diameter": 0.0, "all_windows": 0.0, "window_diameter": 0.0, "window_standard_deviation": 0.0, "stk_obj": cage.to_dict(), } try: result = db[output_collection].insert_one(record) print(f"Succesfully inserted {result.inserted_id}.", flush=True) except DuplicateKeyError as err: print(err) return def get_stk_dicts(input_collection, database, db_url): client = MongoClient(db_url) df = pd.DataFrame(list(client[database][input_collection].find({}))) d = {} for row in df.itertuples(): stk_obj = row.stk_obj _id = row._1 d[_id] = stk_obj d[_id]["class"] = "ConstructedMolecule" return d def load_cage(stk_dict): _id, stk_obj = stk_dict cage = stk.ConstructedMolecule.init_from_dict(stk_obj) cage._id = _id return cage def make_database( processes, input_collection, output_collection, database, chunksize, db_url ): print(f"Using {processes} processes for the calculation.") with ProcessPool(processes) as pool: stk_dicts = get_stk_dicts( input_collection=input_collection, database=database, db_url=db_url ) l = list(stk_dicts.items()) random.shuffle(l) stk_dicts = dict(l) chunksize = calculate_chunksize(stk_dicts, processes) print(f"Splitting cages into chunks of size {chunksize}.") print("Loading cages", flush=True) pop = [] for cage in tqdm( pool.imap_unordered( load_cage, stk_dicts.items(), chunksize=chunksize ), desc="Performing property calculations", ): if cage is not None: pop.append(cage) print("Finished loading cages. Performing database calculations.") _make_entry = partial( make_entry, database=database, output_collection=output_collection, db_url=db_url, ) cages = pool.imap(_make_entry, pop, chunksize=chunksize) for _ in tqdm(cages): print( f"Completed calculations for cage.", flush=True, ) pool.close() def calculate_chunksize(iterable, processes): chunksize, extra = divmod(len(iterable), processes * 4) if extra: chunksize += 1 return chunksize if __name__ == "__main__": # CPU count for local calculations. processes = int(os.environ.get("NCPUS")) parser = argparse.ArgumentParser() parser.add_argument( "-i", type=str, help="Name of the collection containing stk cages." ) parser.add_argument( "-o", type=str, help="Name of the collection to store the calculated properties.", ) parser.add_argument( "-c", type=int, help="Chunksize to split the cage iterable into.", default=None, ) parser.add_argument( "-u", type=str, help="URL of the MongoDB client to connect to" ) parser.add_argument( "-d", type=str, help="Name of the MongoDB database containing cages" ) args = parser.parse_args() make_database( processes=processes, input_collection=args.i, output_collection=args.o, database=args.d, chunksize=args.c, db_url=args.u, )
[ "pymongo.MongoClient", "functools.partial", "tqdm.tqdm", "rdkit_tools.set_position", "argparse.ArgumentParser", "numpy.std", "random.shuffle", "os.environ.get", "itertools.combinations", "numpy.mean", "rdkit_tools.get_windows", "rdkit_tools.get_cavity_size", "rdkit_tools.get_max_diameter", ...
[((1714, 1732), 'numpy.mean', 'np.mean', (['diff_sums'], {}), '(diff_sums)\n', (1721, 1732), True, 'import numpy as np\n'), ((2347, 2366), 'pymongo.MongoClient', 'MongoClient', (['db_url'], {}), '(db_url)\n', (2358, 2366), False, 'from pymongo import MongoClient\n'), ((2623, 2639), 'rdkit_tools.get_windows', 'get_windows', (['mol'], {}), '(mol)\n', (2634, 2639), False, 'from rdkit_tools import get_cavity_size, get_windows, get_max_diameter, set_position\n'), ((4336, 4355), 'pymongo.MongoClient', 'MongoClient', (['db_url'], {}), '(db_url)\n', (4347, 4355), False, 'from pymongo import MongoClient\n'), ((4675, 4722), 'stk.ConstructedMolecule.init_from_dict', 'stk.ConstructedMolecule.init_from_dict', (['stk_obj'], {}), '(stk_obj)\n', (4713, 4722), False, 'import stk\n'), ((6410, 6435), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6433, 6435), False, 'import argparse\n'), ((1937, 1972), 'rdkit_tools.get_cavity_size', 'get_cavity_size', (['mol', '[0, 0, 0]', '(-1)'], {}), '(mol, [0, 0, 0], -1)\n', (1952, 1972), False, 'from rdkit_tools import get_cavity_size, get_windows, get_max_diameter, set_position\n'), ((4934, 4956), 'pathos.pools._ProcessPool', 'ProcessPool', (['processes'], {}), '(processes)\n', (4945, 4956), True, 'from pathos.pools import _ProcessPool as ProcessPool\n'), ((5135, 5152), 'random.shuffle', 'random.shuffle', (['l'], {}), '(l)\n', (5149, 5152), False, 'import random\n'), ((5737, 5831), 'functools.partial', 'partial', (['make_entry'], {'database': 'database', 'output_collection': 'output_collection', 'db_url': 'db_url'}), '(make_entry, database=database, output_collection=output_collection,\n db_url=db_url)\n', (5744, 5831), False, 'from functools import partial\n'), ((5969, 5980), 'tqdm.tqdm', 'tqdm', (['cages'], {}), '(cages)\n', (5973, 5980), False, 'from tqdm import tqdm\n'), ((6372, 6395), 'os.environ.get', 'os.environ.get', (['"""NCPUS"""'], {}), "('NCPUS')\n", (6386, 6395), False, 'import os\n'), ((2848, 2857), 'numpy.std', 'np.std', (['w'], {}), '(w)\n', (2854, 2857), True, 'import numpy as np\n'), ((2930, 2951), 'rdkit_tools.get_max_diameter', 'get_max_diameter', (['mol'], {}), '(mol)\n', (2946, 2951), False, 'from rdkit_tools import get_cavity_size, get_windows, get_max_diameter, set_position\n'), ((2970, 2998), 'rdkit_tools.set_position', 'set_position', (['mol', '[0, 0, 0]'], {}), '(mol, [0, 0, 0])\n', (2982, 2998), False, 'from rdkit_tools import get_cavity_size, get_windows, get_max_diameter, set_position\n'), ((1562, 1589), 'itertools.combinations', 'it.combinations', (['cluster', '(2)'], {}), '(cluster, 2)\n', (1577, 1589), True, 'import itertools as it\n'), ((1626, 1653), 'itertools.combinations', 'it.combinations', (['cluster', '(2)'], {}), '(cluster, 2)\n', (1641, 1653), True, 'import itertools as it\n')]
# import unittest from testinfrastructure.InDirTest import InDirTest import numpy as np from sympy import symbols, Matrix from CompartmentalSystems.smooth_reservoir_model import SmoothReservoirModel from CompartmentalSystems.smooth_model_run import SmoothModelRun from CompartmentalSystems.smooth_model_run_14C import SmoothModelRun_14C from CompartmentalSystems.pwc_model_run_fd import PWCModelRunFD from CompartmentalSystems.pwc_model_run_14C import PWCModelRun_14C from CompartmentalSystems.discrete_model_run import DiscreteModelRun from CompartmentalSystems.discrete_model_run_14C import DiscreteModelRun_14C from CompartmentalSystems.model_run import ( plot_stocks_and_fluxes ) class TestModelRun_14C(InDirTest): def setUp(self): x, y, t = symbols("x y t") state_vector = Matrix([x, y]) B = Matrix([[-1, 1.5], [0.5, -2]]) u = Matrix(2, 1, [9, 1]) srm = SmoothReservoirModel.from_B_u(state_vector, t, B, u) start_values = np.array([10, 40]) self.start_values = start_values self.t_0 = 0 self.t_max = 10 self.ntmo = 10 self.fac = 2 self.times = np.linspace(self.t_0, self.t_max, self.ntmo+1) self.smr = SmoothModelRun(srm, {}, start_values, self.times) alpha = 0.5 self.decay_rate = 1.0 self.start_values_14C = alpha * self.start_values def Fa_func(t): return alpha self.Fa_func = Fa_func self.smr_14C = SmoothModelRun_14C( self.smr, self.start_values_14C, self.Fa_func, self.decay_rate ) def test_DiscreteModelRun_14CFromFakeData(self): dmr_from_smr_14C = DiscreteModelRun.from_SmoothModelRun(self.smr_14C,self.ntmo) dmr_14C = DiscreteModelRun_14C( DiscreteModelRun.from_SmoothModelRun(self.smr,self.ntmo), self.start_values_14C, dmr_from_smr_14C.net_Us, self.decay_rate ) meths = [ "solve", "acc_net_external_input_vector", "acc_net_external_output_vector", "acc_net_internal_flux_matrix" ] for meth in meths: with self.subTest(): self.assertTrue( np.allclose( getattr(self.smr_14C, meth)(), getattr(dmr_14C, meth)() ) ) def test_PWCModelRunFD_14C(self): times = self.smr.times xs, gross_Us, gross_Fs, gross_Rs \ = self.smr.fake_gross_discretized_output(times) pwc_mr_fd = PWCModelRunFD.from_gross_fluxes( self.smr.model.time_symbol, times, self.smr.start_values, gross_Us, gross_Fs, gross_Rs ) pwc_mr_fd_14C = PWCModelRun_14C( pwc_mr_fd.pwc_mr, self.start_values_14C, self.Fa_func, self.decay_rate ) meths = [ "solve", "acc_gross_external_input_vector", "acc_net_external_input_vector", "acc_gross_external_output_vector", "acc_net_external_output_vector", "acc_gross_internal_flux_matrix", "acc_net_internal_flux_matrix" ] for meth in meths: with self.subTest(): ref = getattr(self.smr_14C, meth)() res = getattr(pwc_mr_fd_14C, meth)() self.assertTrue( np.allclose( ref, res, rtol=3e-02 ) # For this linear constant model # the error should actually be zero # and is only due to numerical inaccuracy. ) #plot_stocks_and_fluxes( # [ # self.smr_14C, # pwc_mr_fd_14C # ], # 'stocks_and_fluxes.pdf' #)
[ "CompartmentalSystems.pwc_model_run_14C.PWCModelRun_14C", "sympy.symbols", "numpy.allclose", "CompartmentalSystems.pwc_model_run_fd.PWCModelRunFD.from_gross_fluxes", "sympy.Matrix", "CompartmentalSystems.smooth_model_run_14C.SmoothModelRun_14C", "CompartmentalSystems.discrete_model_run.DiscreteModelRun....
[((765, 781), 'sympy.symbols', 'symbols', (['"""x y t"""'], {}), "('x y t')\n", (772, 781), False, 'from sympy import symbols, Matrix\n'), ((805, 819), 'sympy.Matrix', 'Matrix', (['[x, y]'], {}), '([x, y])\n', (811, 819), False, 'from sympy import symbols, Matrix\n'), ((832, 862), 'sympy.Matrix', 'Matrix', (['[[-1, 1.5], [0.5, -2]]'], {}), '([[-1, 1.5], [0.5, -2]])\n', (838, 862), False, 'from sympy import symbols, Matrix\n'), ((895, 915), 'sympy.Matrix', 'Matrix', (['(2)', '(1)', '[9, 1]'], {}), '(2, 1, [9, 1])\n', (901, 915), False, 'from sympy import symbols, Matrix\n'), ((930, 982), 'CompartmentalSystems.smooth_reservoir_model.SmoothReservoirModel.from_B_u', 'SmoothReservoirModel.from_B_u', (['state_vector', 't', 'B', 'u'], {}), '(state_vector, t, B, u)\n', (959, 982), False, 'from CompartmentalSystems.smooth_reservoir_model import SmoothReservoirModel\n'), ((1007, 1025), 'numpy.array', 'np.array', (['[10, 40]'], {}), '([10, 40])\n', (1015, 1025), True, 'import numpy as np\n'), ((1177, 1225), 'numpy.linspace', 'np.linspace', (['self.t_0', 'self.t_max', '(self.ntmo + 1)'], {}), '(self.t_0, self.t_max, self.ntmo + 1)\n', (1188, 1225), True, 'import numpy as np\n'), ((1244, 1293), 'CompartmentalSystems.smooth_model_run.SmoothModelRun', 'SmoothModelRun', (['srm', '{}', 'start_values', 'self.times'], {}), '(srm, {}, start_values, self.times)\n', (1258, 1293), False, 'from CompartmentalSystems.smooth_model_run import SmoothModelRun\n'), ((1496, 1583), 'CompartmentalSystems.smooth_model_run_14C.SmoothModelRun_14C', 'SmoothModelRun_14C', (['self.smr', 'self.start_values_14C', 'self.Fa_func', 'self.decay_rate'], {}), '(self.smr, self.start_values_14C, self.Fa_func, self.\n decay_rate)\n', (1514, 1583), False, 'from CompartmentalSystems.smooth_model_run_14C import SmoothModelRun_14C\n'), ((1718, 1779), 'CompartmentalSystems.discrete_model_run.DiscreteModelRun.from_SmoothModelRun', 'DiscreteModelRun.from_SmoothModelRun', (['self.smr_14C', 'self.ntmo'], {}), '(self.smr_14C, self.ntmo)\n', (1754, 1779), False, 'from CompartmentalSystems.discrete_model_run import DiscreteModelRun\n'), ((2649, 2773), 'CompartmentalSystems.pwc_model_run_fd.PWCModelRunFD.from_gross_fluxes', 'PWCModelRunFD.from_gross_fluxes', (['self.smr.model.time_symbol', 'times', 'self.smr.start_values', 'gross_Us', 'gross_Fs', 'gross_Rs'], {}), '(self.smr.model.time_symbol, times, self.smr\n .start_values, gross_Us, gross_Fs, gross_Rs)\n', (2680, 2773), False, 'from CompartmentalSystems.pwc_model_run_fd import PWCModelRunFD\n'), ((2875, 2967), 'CompartmentalSystems.pwc_model_run_14C.PWCModelRun_14C', 'PWCModelRun_14C', (['pwc_mr_fd.pwc_mr', 'self.start_values_14C', 'self.Fa_func', 'self.decay_rate'], {}), '(pwc_mr_fd.pwc_mr, self.start_values_14C, self.Fa_func, self\n .decay_rate)\n', (2890, 2967), False, 'from CompartmentalSystems.pwc_model_run_14C import PWCModelRun_14C\n'), ((1831, 1888), 'CompartmentalSystems.discrete_model_run.DiscreteModelRun.from_SmoothModelRun', 'DiscreteModelRun.from_SmoothModelRun', (['self.smr', 'self.ntmo'], {}), '(self.smr, self.ntmo)\n', (1867, 1888), False, 'from CompartmentalSystems.discrete_model_run import DiscreteModelRun\n'), ((3564, 3596), 'numpy.allclose', 'np.allclose', (['ref', 'res'], {'rtol': '(0.03)'}), '(ref, res, rtol=0.03)\n', (3575, 3596), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ pysteps.decorators ================== Decorators used to define reusable building blocks that can change or extend the behavior of some functions in pysteps. .. autosummary:: :toctree: ../generated/ postprocess_import check_input_frames prepare_interpolator memoize """ import inspect import uuid from collections import defaultdict from functools import wraps import numpy as np def _add_extra_kwrds_to_docstrings(target_func, extra_kwargs_doc_text): """ Update the functions docstrings by replacing the `{extra_kwargs_doc}` occurences in the docstring by the `extra_kwargs_doc_text` value. """ # Clean up indentation from docstrings for the # docstrings to be merged correctly. extra_kwargs_doc = inspect.cleandoc(extra_kwargs_doc_text) target_func.__doc__ = inspect.cleandoc(target_func.__doc__) # Add extra kwargs docstrings target_func.__doc__ = target_func.__doc__.format_map( defaultdict(str, extra_kwargs_doc=extra_kwargs_doc) ) return target_func def postprocess_import(fillna=np.nan, dtype="double"): """ Postprocess the imported precipitation data. Operations: - Allow type casting (dtype keyword) - Set invalid or missing data to predefined value (fillna keyword) This decorator replaces the text "{extra_kwargs}" in the function's docstring with the documentation of the keywords used in the postprocessing. The additional docstrings are added as "Other Parameters" in the importer function. Parameters ---------- dtype: str Default data type for precipitation. Double precision by default. fillna: float or np.nan Default value used to represent the missing data ("No Coverage"). By default, np.nan is used. If the importer returns a MaskedArray, all the masked values are set to the fillna value. If a numpy array is returned, all the invalid values (nan and inf) are set to the fillna value. """ def _postprocess_import(importer): @wraps(importer) def _import_with_postprocessing(*args, **kwargs): precip, *other_args = importer(*args, **kwargs) _dtype = kwargs.get("dtype", dtype) accepted_precisions = ["float32", "float64", "single", "double"] if _dtype not in accepted_precisions: raise ValueError( "The selected precision does not correspond to a valid value." "The accepted values are: " + str(accepted_precisions) ) if isinstance(precip, np.ma.MaskedArray): invalid_mask = np.ma.getmaskarray(precip) precip.data[invalid_mask] = fillna else: # If plain numpy arrays are used, the importers should indicate # the invalid values with np.nan. _fillna = kwargs.get("fillna", fillna) if _fillna is not np.nan: mask = ~np.isfinite(precip) precip[mask] = _fillna return (precip.astype(_dtype),) + tuple(other_args) extra_kwargs_doc = """ Other Parameters ---------------- dtype: str Data-type to which the array is cast. Valid values: "float32", "float64", "single", and "double". fillna: float or np.nan Value used to represent the missing data ("No Coverage"). By default, np.nan is used. """ _add_extra_kwrds_to_docstrings(_import_with_postprocessing, extra_kwargs_doc) return _import_with_postprocessing return _postprocess_import def check_input_frames( minimum_input_frames=2, maximum_input_frames=np.inf, just_ndim=False ): """ Check that the input_images used as inputs in the optical-flow methods have the correct shape (t, x, y ). """ def _check_input_frames(motion_method_func): @wraps(motion_method_func) def new_function(*args, **kwargs): """ Return new function with the checks prepended to the target motion_method_func function. """ input_images = args[0] if input_images.ndim != 3: raise ValueError( "input_images dimension mismatch.\n" f"input_images.shape: {str(input_images.shape)}\n" "(t, x, y ) dimensions expected" ) if not just_ndim: num_of_frames = input_images.shape[0] if minimum_input_frames < num_of_frames > maximum_input_frames: raise ValueError( f"input_images frames {num_of_frames} mismatch.\n" f"Minimum frames: {minimum_input_frames}\n" f"Maximum frames: {maximum_input_frames}\n" ) return motion_method_func(*args, **kwargs) return new_function return _check_input_frames def prepare_interpolator(nchunks=4): """ Check that all the inputs have the correct shape, and that all values are finite. It also split the destination grid in `nchunks` parts, and process each part independently. """ def _preamble_interpolation(interpolator): @wraps(interpolator) def _interpolator_with_preamble(xy_coord, values, xgrid, ygrid, **kwargs): nonlocal nchunks # https://stackoverflow.com/questions/5630409/ values = values.copy() xy_coord = xy_coord.copy() input_ndims = values.ndim input_nvars = 1 if input_ndims == 1 else values.shape[1] input_nsamples = values.shape[0] coord_ndims = xy_coord.ndim coord_nsamples = xy_coord.shape[0] grid_shape = (ygrid.size, xgrid.size) if np.any(~np.isfinite(values)): raise ValueError("argument 'values' contains non-finite values") if np.any(~np.isfinite(xy_coord)): raise ValueError("argument 'xy_coord' contains non-finite values") if input_ndims > 2: raise ValueError( "argument 'values' must have 1 (n) or 2 dimensions (n, m), " f"but it has {input_ndims}" ) if not coord_ndims == 2: raise ValueError( "argument 'xy_coord' must have 2 dimensions (n, 2), " f"but it has {coord_ndims}" ) if not input_nsamples == coord_nsamples: raise ValueError( "the number of samples in argument 'values' does not match the " f"number of coordinates {input_nsamples}!={coord_nsamples}" ) # only one sample, return uniform output if input_nsamples == 1: output_array = np.ones((input_nvars,) + grid_shape) for n, v in enumerate(values[0, ...]): output_array[n, ...] *= v return output_array.squeeze() # all equal elements, return uniform output if values.max() == values.min(): return np.ones((input_nvars,) + grid_shape) * values.ravel()[0] # split grid in n chunks nchunks = int(kwargs.get("nchunks", nchunks) ** 0.5) if nchunks > 1: subxgrids = np.array_split(xgrid, nchunks) subxgrids = [x for x in subxgrids if x.size > 0] subygrids = np.array_split(ygrid, nchunks) subygrids = [y for y in subygrids if y.size > 0] # generate a unique identifier to be used for caching # intermediate results kwargs["hkey"] = uuid.uuid1().int else: subxgrids = [xgrid] subygrids = [ygrid] interpolated = np.zeros((input_nvars,) + grid_shape) indx = 0 for subxgrid in subxgrids: deltax = subxgrid.size indy = 0 for subygrid in subygrids: deltay = subygrid.size interpolated[ :, indy : (indy + deltay), indx : (indx + deltax) ] = interpolator(xy_coord, values, subxgrid, subygrid, **kwargs) indy += deltay indx += deltax return interpolated.squeeze() extra_kwargs_doc = """ nchunks: int, optional Split and process the destination grid in nchunks. Useful for large grids to limit the memory footprint. """ _add_extra_kwrds_to_docstrings(_interpolator_with_preamble, extra_kwargs_doc) return _interpolator_with_preamble return _preamble_interpolation def memoize(maxsize=10): """ Add a Least Recently Used (LRU) cache to any function. Caching is purely based on the optional keyword argument 'hkey', which needs to be a hashable. Parameters ---------- maxsize: int, optional The maximum number of elements stored in the LRU cache. """ def _memoize(func): cache = dict() hkeys = [] @wraps(func) def _func_with_cache(*args, **kwargs): hkey = kwargs.pop("hkey", None) if hkey in cache: return cache[hkey] result = func(*args, **kwargs) if hkey is not None: cache[hkey] = result hkeys.append(hkey) if len(hkeys) > maxsize: cache.pop(hkeys.pop(0)) return result return _func_with_cache return _memoize
[ "numpy.ma.getmaskarray", "numpy.zeros", "numpy.ones", "numpy.isfinite", "collections.defaultdict", "uuid.uuid1", "functools.wraps", "numpy.array_split", "inspect.cleandoc" ]
[((781, 820), 'inspect.cleandoc', 'inspect.cleandoc', (['extra_kwargs_doc_text'], {}), '(extra_kwargs_doc_text)\n', (797, 820), False, 'import inspect\n'), ((847, 884), 'inspect.cleandoc', 'inspect.cleandoc', (['target_func.__doc__'], {}), '(target_func.__doc__)\n', (863, 884), False, 'import inspect\n'), ((986, 1037), 'collections.defaultdict', 'defaultdict', (['str'], {'extra_kwargs_doc': 'extra_kwargs_doc'}), '(str, extra_kwargs_doc=extra_kwargs_doc)\n', (997, 1037), False, 'from collections import defaultdict\n'), ((2076, 2091), 'functools.wraps', 'wraps', (['importer'], {}), '(importer)\n', (2081, 2091), False, 'from functools import wraps\n'), ((4031, 4056), 'functools.wraps', 'wraps', (['motion_method_func'], {}), '(motion_method_func)\n', (4036, 4056), False, 'from functools import wraps\n'), ((5406, 5425), 'functools.wraps', 'wraps', (['interpolator'], {}), '(interpolator)\n', (5411, 5425), False, 'from functools import wraps\n'), ((9391, 9402), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (9396, 9402), False, 'from functools import wraps\n'), ((8050, 8087), 'numpy.zeros', 'np.zeros', (['((input_nvars,) + grid_shape)'], {}), '((input_nvars,) + grid_shape)\n', (8058, 8087), True, 'import numpy as np\n'), ((2684, 2710), 'numpy.ma.getmaskarray', 'np.ma.getmaskarray', (['precip'], {}), '(precip)\n', (2702, 2710), True, 'import numpy as np\n'), ((7027, 7063), 'numpy.ones', 'np.ones', (['((input_nvars,) + grid_shape)'], {}), '((input_nvars,) + grid_shape)\n', (7034, 7063), True, 'import numpy as np\n'), ((7552, 7582), 'numpy.array_split', 'np.array_split', (['xgrid', 'nchunks'], {}), '(xgrid, nchunks)\n', (7566, 7582), True, 'import numpy as np\n'), ((7676, 7706), 'numpy.array_split', 'np.array_split', (['ygrid', 'nchunks'], {}), '(ygrid, nchunks)\n', (7690, 7706), True, 'import numpy as np\n'), ((5977, 5996), 'numpy.isfinite', 'np.isfinite', (['values'], {}), '(values)\n', (5988, 5996), True, 'import numpy as np\n'), ((6103, 6124), 'numpy.isfinite', 'np.isfinite', (['xy_coord'], {}), '(xy_coord)\n', (6114, 6124), True, 'import numpy as np\n'), ((7336, 7372), 'numpy.ones', 'np.ones', (['((input_nvars,) + grid_shape)'], {}), '((input_nvars,) + grid_shape)\n', (7343, 7372), True, 'import numpy as np\n'), ((7915, 7927), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (7925, 7927), False, 'import uuid\n'), ((3035, 3054), 'numpy.isfinite', 'np.isfinite', (['precip'], {}), '(precip)\n', (3046, 3054), True, 'import numpy as np\n')]
# A class for generating minibatches. Uses sampling without # replacement. Returns batches of indices for each minibatch. import numpy as np class batch_gen(object): def __init__(self, batch_size, num_indices, distribution=None, replace=False, max_batches=-1): self.batch_size = batch_size self.num_indices = num_indices self.indices = np.array(range(num_indices)) self.max_batches = max_batches self.counter = 0 self.distribution = distribution self.replace = replace def __iter__(self): return self def __next__(self): return self.next() def next(self): self.counter += 1 if self.max_batches >= 0 and self.counter > self.max_batches: raise StopIteration() if self.replace: return np.random.choice(self.indices, self.batch_size, replace=True, p=self.distribution) elif self.indices.shape[0] < self.batch_size: acc = np.array(self.indices) self.indices = np.array(range(num_indices)) return np.append(acc, np.random.choice( self.indices, self.batch_size - acc.shape[0], replace=False)) else: return np.random.choice(self.indices, self.batch_size, replace=False)
[ "numpy.array", "numpy.random.choice" ]
[((841, 928), 'numpy.random.choice', 'np.random.choice', (['self.indices', 'self.batch_size'], {'replace': '(True)', 'p': 'self.distribution'}), '(self.indices, self.batch_size, replace=True, p=self.\n distribution)\n', (857, 928), True, 'import numpy as np\n'), ((1032, 1054), 'numpy.array', 'np.array', (['self.indices'], {}), '(self.indices)\n', (1040, 1054), True, 'import numpy as np\n'), ((1274, 1336), 'numpy.random.choice', 'np.random.choice', (['self.indices', 'self.batch_size'], {'replace': '(False)'}), '(self.indices, self.batch_size, replace=False)\n', (1290, 1336), True, 'import numpy as np\n'), ((1145, 1222), 'numpy.random.choice', 'np.random.choice', (['self.indices', '(self.batch_size - acc.shape[0])'], {'replace': '(False)'}), '(self.indices, self.batch_size - acc.shape[0], replace=False)\n', (1161, 1222), True, 'import numpy as np\n')]
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. import unittest, os from unittest.case import skip import numpy as np from pyis.python import ops from pyis.python import save, load # @unittest.skip("local dependencies and already verified") # class TestOrtSessionWithCustomOrtDll(unittest.TestCase): # @classmethod # def setUpClass(self) -> None: # os.makedirs('tmp', exist_ok=True) # # initialize model # self.model_path = os.path.join(os.path.dirname(__file__), 'data', 'a_plus_b.onnx') # custom_dll_path = str(Path(__file__).parent / 'customdll' / 'libonnxruntime.so.1.8.0') # ops.OrtSession.initialize_ort(custom_dll_path) # self.ort_session: ops.OrtSession = ops.OrtSession( # model_path = self.model_path, # input_names = ['x', 'y'], # output_names = ['r1', 'r2'] # ) # def test(self): # i1 = np.array([1], dtype=np.int64) # i2 = np.array([2], dtype=np.int64) # o1, o2 = self.ort_session.run([i1, i2]) # x = o1.tolist() # y = o2.tolist() class TestOrtSessionSimple(unittest.TestCase): @classmethod def setUpClass(self) -> None: ops.OrtSession.initialize_ort() # initialize model self.model_path = os.path.join(os.path.dirname(__file__), 'data', 'a_plus_b.onnx') self.ort_session: ops.OrtSession = ops.OrtSession( model_path = self.model_path, input_names = ['x', 'y'], output_names = ['r1', 'r2'] ) def test_run(self): i1 = np.array([1], dtype=np.int64) i2 = np.array([2], dtype=np.int64) o1, o2 = self.ort_session.run([i1, i2]) x, y = o1.tolist(), o2.tolist() self.assertListEqual(x, [3]) self.assertListEqual(y, [3]) def test_save(self): save(self.ort_session, 'tmp/test_ort_session/model.pkl') loaded_session = load('tmp/test_ort_session/model.pkl') i1 = np.array([1], dtype=np.int64) i2 = np.array([2], dtype=np.int64) o1, o2 = loaded_session.run([i1, i2]) x, y = o1.tolist(), o2.tolist() self.assertListEqual(x, [3]) self.assertListEqual(y, [3]) if __name__ == "__main__": unittest.main()
[ "unittest.main", "pyis.python.load", "pyis.python.save", "os.path.dirname", "pyis.python.ops.OrtSession.initialize_ort", "numpy.array", "pyis.python.ops.OrtSession" ]
[((2298, 2313), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2311, 2313), False, 'import unittest, os\n'), ((1245, 1276), 'pyis.python.ops.OrtSession.initialize_ort', 'ops.OrtSession.initialize_ort', ([], {}), '()\n', (1274, 1276), False, 'from pyis.python import ops\n'), ((1438, 1535), 'pyis.python.ops.OrtSession', 'ops.OrtSession', ([], {'model_path': 'self.model_path', 'input_names': "['x', 'y']", 'output_names': "['r1', 'r2']"}), "(model_path=self.model_path, input_names=['x', 'y'],\n output_names=['r1', 'r2'])\n", (1452, 1535), False, 'from pyis.python import ops\n'), ((1622, 1651), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int64'}), '([1], dtype=np.int64)\n', (1630, 1651), True, 'import numpy as np\n'), ((1665, 1694), 'numpy.array', 'np.array', (['[2]'], {'dtype': 'np.int64'}), '([2], dtype=np.int64)\n', (1673, 1694), True, 'import numpy as np\n'), ((1899, 1955), 'pyis.python.save', 'save', (['self.ort_session', '"""tmp/test_ort_session/model.pkl"""'], {}), "(self.ort_session, 'tmp/test_ort_session/model.pkl')\n", (1903, 1955), False, 'from pyis.python import save, load\n'), ((1981, 2019), 'pyis.python.load', 'load', (['"""tmp/test_ort_session/model.pkl"""'], {}), "('tmp/test_ort_session/model.pkl')\n", (1985, 2019), False, 'from pyis.python import save, load\n'), ((2033, 2062), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int64'}), '([1], dtype=np.int64)\n', (2041, 2062), True, 'import numpy as np\n'), ((2076, 2105), 'numpy.array', 'np.array', (['[2]'], {'dtype': 'np.int64'}), '([2], dtype=np.int64)\n', (2084, 2105), True, 'import numpy as np\n'), ((1343, 1368), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1358, 1368), False, 'import unittest, os\n')]
import numpy as np import torch import torch.distributions as td import torch.nn as nn class ObservationEncoder(nn.Module): def __init__(self, depth=2, stride=2, shape=(3, 64, 64), activation=nn.ReLU, padding=1): super().__init__() self.convolutions = nn.Sequential( nn.Conv2d(shape[0], 1 * depth, 4, stride, padding), activation(), nn.Conv2d(1 * depth, 2 * depth, 4, stride, padding), activation(), ) self.shape = shape self.stride = stride self.depth = depth self.padding = padding def forward(self, obs): batch_shape = obs.shape[:-3] img_shape = obs.shape[-3:] embed = self.convolutions(obs.reshape(-1, *img_shape)) embed = torch.reshape(embed, (*batch_shape, -1)) return embed @property def embed_size(self): conv1_shape = conv_out_shape(self.shape[1:], self.padding, 4, self.stride) conv2_shape = conv_out_shape(conv1_shape, self.padding, 4, self.stride) embed_size = 2 * self.depth * np.prod(conv2_shape).item() return embed_size class ObservationDecoder(nn.Module): def __init__(self, depth=32, stride=2, activation=nn.ReLU, embed_size=1024, shape=(3, 64, 64), distribution=td.Normal): super().__init__() self.depth = depth self.shape = shape self.distribution = distribution c, h, w = shape conv1_kernel_size = 4 conv2_kernel_size = 4 padding = 0 conv1_shape = conv_out_shape((h, w), padding, conv1_kernel_size, stride) conv1_pad = output_padding_shape((h, w), conv1_shape, padding, conv1_kernel_size, stride) conv2_shape = conv_out_shape(conv1_shape, padding, conv2_kernel_size, stride) conv2_pad = output_padding_shape(conv1_shape, conv2_shape, padding, conv2_kernel_size, stride) self.conv_shape = (8 * depth, *conv2_shape) # OR 4 self.linear = nn.Linear(embed_size, 8 * depth * np.prod(conv2_shape).item()) self.decoder = nn.Sequential( nn.ConvTranspose2d(8 * depth, 4 * depth, conv2_kernel_size, stride, output_padding=conv2_pad), activation(), nn.ConvTranspose2d(4 * depth, shape[0], conv1_kernel_size, stride, output_padding=conv1_pad), ) def forward(self, x): """ :param x: size(*batch_shape, embed_size) :return: obs_dist = size(*batch_shape, *self.shape) """ batch_shape = x.shape[:-1] embed_size = x.shape[-1] squeezed_size = np.prod(batch_shape).item() x = x.reshape(squeezed_size, embed_size) x = self.linear(x) x = torch.reshape(x, (squeezed_size, *self.conv_shape)) x = self.decoder(x) mean = torch.reshape(x, (*batch_shape, *self.shape)) obs_dist = self.distribution(mean, 1) return obs_dist def conv_out(h_in, padding, kernel_size, stride): return int((h_in + 2. * padding - (kernel_size - 1.) - 1.) / stride + 1.) def output_padding(h_in, conv_out, padding, kernel_size, stride): return h_in - (conv_out - 1) * stride + 2 * padding - (kernel_size - 1) - 1 def conv_out_shape(h_in, padding, kernel_size, stride): return tuple(conv_out(x, padding, kernel_size, stride) for x in h_in) def output_padding_shape(h_in, conv_out, padding, kernel_size, stride): return tuple(output_padding(h_in[i], conv_out[i], padding, kernel_size, stride) for i in range(len(h_in)))
[ "torch.reshape", "torch.nn.Conv2d", "torch.nn.ConvTranspose2d", "numpy.prod" ]
[((774, 814), 'torch.reshape', 'torch.reshape', (['embed', '(*batch_shape, -1)'], {}), '(embed, (*batch_shape, -1))\n', (787, 814), False, 'import torch\n'), ((2707, 2758), 'torch.reshape', 'torch.reshape', (['x', '(squeezed_size, *self.conv_shape)'], {}), '(x, (squeezed_size, *self.conv_shape))\n', (2720, 2758), False, 'import torch\n'), ((2802, 2847), 'torch.reshape', 'torch.reshape', (['x', '(*batch_shape, *self.shape)'], {}), '(x, (*batch_shape, *self.shape))\n', (2815, 2847), False, 'import torch\n'), ((301, 351), 'torch.nn.Conv2d', 'nn.Conv2d', (['shape[0]', '(1 * depth)', '(4)', 'stride', 'padding'], {}), '(shape[0], 1 * depth, 4, stride, padding)\n', (310, 351), True, 'import torch.nn as nn\n'), ((391, 442), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1 * depth)', '(2 * depth)', '(4)', 'stride', 'padding'], {}), '(1 * depth, 2 * depth, 4, stride, padding)\n', (400, 442), True, 'import torch.nn as nn\n'), ((2102, 2199), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(8 * depth)', '(4 * depth)', 'conv2_kernel_size', 'stride'], {'output_padding': 'conv2_pad'}), '(8 * depth, 4 * depth, conv2_kernel_size, stride,\n output_padding=conv2_pad)\n', (2120, 2199), True, 'import torch.nn as nn\n'), ((2235, 2331), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(4 * depth)', 'shape[0]', 'conv1_kernel_size', 'stride'], {'output_padding': 'conv1_pad'}), '(4 * depth, shape[0], conv1_kernel_size, stride,\n output_padding=conv1_pad)\n', (2253, 2331), True, 'import torch.nn as nn\n'), ((2591, 2611), 'numpy.prod', 'np.prod', (['batch_shape'], {}), '(batch_shape)\n', (2598, 2611), True, 'import numpy as np\n'), ((1078, 1098), 'numpy.prod', 'np.prod', (['conv2_shape'], {}), '(conv2_shape)\n', (1085, 1098), True, 'import numpy as np\n'), ((2023, 2043), 'numpy.prod', 'np.prod', (['conv2_shape'], {}), '(conv2_shape)\n', (2030, 2043), True, 'import numpy as np\n')]
from __future__ import print_function import argparse import os import sys import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import numpy as np import torch.optim as optim import torchvision import torchvision.transforms as transforms from sklearn.linear_model import LogisticRegressionCV import models.densenet as dn import models.wideresnet as wn import utils.svhn_loader as svhn import numpy as np import time from scipy import misc from utils import ConfidenceLinfPGDAttack, MahalanobisLinfPGDAttack, softmax, metric, sample_estimator, get_Mahalanobis_score, TinyImages, CustomDataset parser = argparse.ArgumentParser(description='Pytorch Detecting Out-of-distribution examples in neural networks') parser.add_argument('--in-dataset', default="CIFAR-10", type=str, help='in-distribution dataset') parser.add_argument('--name', required=True, type=str, help='neural network name and training set') parser.add_argument('--model-arch', default='densenet', type=str, help='model architecture') parser.add_argument('--gpu', default = '0', type = str, help='gpu index') parser.add_argument('--epochs', default=100, type=int, help='number of total epochs to run') parser.add_argument('-b', '--batch-size', default=100, type=int, help='mini-batch size') parser.add_argument('--layers', default=100, type=int, help='total number of layers (default: 100)') parser.add_argument('--depth', default=40, type=int, help='depth of resnet') parser.add_argument('--width', default=4, type=int, help='width of resnet') parser.set_defaults(argument=True) args = parser.parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu torch.manual_seed(1) torch.cuda.manual_seed(1) np.random.seed(1) def print_results(results, stypes): mtypes = ['FPR', 'DTERR', 'AUROC', 'AUIN', 'AUOUT'] for stype in stypes: print(' OOD detection method: ' + stype) for mtype in mtypes: print(' {mtype:6s}'.format(mtype=mtype), end='') print('\n{val:6.2f}'.format(val=100.*results[stype]['FPR']), end='') print(' {val:6.2f}'.format(val=100.*results[stype]['DTERR']), end='') print(' {val:6.2f}'.format(val=100.*results[stype]['AUROC']), end='') print(' {val:6.2f}'.format(val=100.*results[stype]['AUIN']), end='') print(' {val:6.2f}\n'.format(val=100.*results[stype]['AUOUT']), end='') print('') def get_odin_score(inputs, model, temper, noiseMagnitude1): criterion = nn.CrossEntropyLoss() inputs = Variable(inputs, requires_grad = True) outputs = model(inputs) maxIndexTemp = np.argmax(outputs.data.cpu().numpy(), axis=1) # Using temperature scaling outputs = outputs / temper labels = Variable(torch.LongTensor(maxIndexTemp).cuda()) loss = criterion(outputs, labels) loss.backward() # Normalizing the gradient to binary in {0, 1} gradient = torch.ge(inputs.grad.data, 0) gradient = (gradient.float() - 0.5) * 2 # Adding small perturbations to images tempInputs = torch.add(inputs.data, -noiseMagnitude1, gradient) outputs = model(Variable(tempInputs)) outputs = outputs / temper # Calculating the confidence after adding perturbations nnOutputs = outputs.data.cpu() nnOutputs = nnOutputs.numpy() nnOutputs = nnOutputs - np.max(nnOutputs, axis=1, keepdims=True) nnOutputs = np.exp(nnOutputs) / np.sum(np.exp(nnOutputs), axis=1, keepdims=True) scores = np.max(nnOutputs, axis=1) return scores def tune_odin_hyperparams(): print('Tuning hyper-parameters...') stypes = ['ODIN'] save_dir = os.path.join('output/odin_hyperparams/', args.in_dataset, args.name, 'tmp') if not os.path.exists(save_dir): os.makedirs(save_dir) transform = transforms.Compose([ transforms.ToTensor(), ]) if args.in_dataset == "CIFAR-10": normalizer = transforms.Normalize((125.3/255, 123.0/255, 113.9/255), (63.0/255, 62.1/255.0, 66.7/255.0)) trainset= torchvision.datasets.CIFAR10('./datasets/cifar10', train=True, download=True, transform=transform) trainloaderIn = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True) testset = torchvision.datasets.CIFAR10(root='./datasets/cifar10', train=False, download=True, transform=transform) testloaderIn = torch.utils.data.DataLoader(testset, batch_size=args.batch_size, shuffle=True) num_classes = 10 elif args.in_dataset == "CIFAR-100": normalizer = transforms.Normalize((125.3/255, 123.0/255, 113.9/255), (63.0/255, 62.1/255.0, 66.7/255.0)) trainset= torchvision.datasets.CIFAR100('./datasets/cifar100', train=True, download=True, transform=transform) trainloaderIn = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True) testset = torchvision.datasets.CIFAR100(root='./datasets/cifar100', train=False, download=True, transform=transform) testloaderIn = torch.utils.data.DataLoader(testset, batch_size=args.batch_size, shuffle=True) num_classes = 100 elif args.in_dataset == "SVHN": normalizer = None trainloaderIn = torch.utils.data.DataLoader( svhn.SVHN('datasets/svhn/', split='train', transform=transforms.ToTensor(), download=False), batch_size=args.batch_size, shuffle=True) testloaderIn = torch.utils.data.DataLoader( svhn.SVHN('datasets/svhn/', split='test', transform=transforms.ToTensor(), download=False), batch_size=args.batch_size, shuffle=True) args.epochs = 20 num_classes = 10 valloaderOut = torch.utils.data.DataLoader(TinyImages(transform=transforms.Compose( [transforms.ToTensor(), transforms.ToPILImage(), transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()])), batch_size=args.batch_size, shuffle=False) valloaderOut.dataset.offset = np.random.randint(len(valloaderOut.dataset)) if args.model_arch == 'densenet': model = dn.DenseNet3(args.layers, num_classes, normalizer=normalizer) elif args.model_arch == 'wideresnet': model = wn.WideResNet(args.depth, num_classes, widen_factor=args.width, normalizer=normalizer) else: assert False, 'Not supported model arch: {}'.format(args.model_arch) checkpoint = torch.load("./checkpoints/{in_dataset}/{name}/checkpoint_{epochs}.pth.tar".format(in_dataset=args.in_dataset, name=args.name, epochs=args.epochs)) model.load_state_dict(checkpoint['state_dict']) model.eval() model.cuda() m = 1000 val_in = [] val_out = [] cnt = 0 for data, target in testloaderIn: for x in data: val_in.append(x.numpy()) cnt += 1 if cnt == m: break if cnt == m: break cnt = 0 for data, target in valloaderOut: for x in data: val_out.append(x.numpy()) cnt += 1 if cnt == m: break if cnt == m: break print('Len of val in: ', len(val_in)) print('Len of val out: ', len(val_out)) best_fpr = 1.1 best_magnitude = 0.0 for magnitude in np.arange(0, 0.0041, 0.004/20): t0 = time.time() f1 = open(os.path.join(save_dir, "confidence_ODIN_In.txt"), 'w') f2 = open(os.path.join(save_dir, "confidence_ODIN_Out.txt"), 'w') ########################################In-distribution########################################### print("Processing in-distribution images") count = 0 for i in range(int(m/args.batch_size) + 1): if i * args.batch_size >= m: break images = torch.tensor(val_in[i * args.batch_size : min((i+1) * args.batch_size, m)]) images = images.cuda() # if j<1000: continue batch_size = images.shape[0] scores = get_odin_score(images, model, temper=1000, noiseMagnitude1=magnitude) for k in range(batch_size): f1.write("{}\n".format(scores[k])) count += batch_size # print("{:4}/{:4} images processed, {:.1f} seconds used.".format(count, m, time.time()-t0)) t0 = time.time() ###################################Out-of-Distributions##################################### t0 = time.time() print("Processing out-of-distribution images") count = 0 for i in range(int(m/args.batch_size) + 1): if i * args.batch_size >= m: break images = torch.tensor(val_out[i * args.batch_size : min((i+1) * args.batch_size, m)]) images = images.cuda() # if j<1000: continue batch_size = images.shape[0] scores = get_odin_score(images, model, temper=1000, noiseMagnitude1=magnitude) for k in range(batch_size): f2.write("{}\n".format(scores[k])) count += batch_size # print("{:4}/{:4} images processed, {:.1f} seconds used.".format(count, m, time.time()-t0)) t0 = time.time() f1.close() f2.close() results = metric(save_dir, stypes) print_results(results, stypes) fpr = results['ODIN']['FPR'] if fpr < best_fpr: best_fpr = fpr best_magnitude = magnitude return best_magnitude if __name__ == '__main__': best_magnitude = tune_odin_hyperparams() print('Best magnitude: ', best_magnitude)
[ "numpy.random.seed", "argparse.ArgumentParser", "torchvision.datasets.CIFAR10", "numpy.arange", "numpy.exp", "models.densenet.DenseNet3", "torchvision.transforms.Normalize", "os.path.join", "torch.utils.data.DataLoader", "utils.metric", "os.path.exists", "torchvision.transforms.ToPILImage", ...
[((653, 762), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Pytorch Detecting Out-of-distribution examples in neural networks"""'}), "(description=\n 'Pytorch Detecting Out-of-distribution examples in neural networks')\n", (676, 762), False, 'import argparse\n'), ((1801, 1821), 'torch.manual_seed', 'torch.manual_seed', (['(1)'], {}), '(1)\n', (1818, 1821), False, 'import torch\n'), ((1822, 1847), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['(1)'], {}), '(1)\n', (1844, 1847), False, 'import torch\n'), ((1848, 1865), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (1862, 1865), True, 'import numpy as np\n'), ((2611, 2632), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2630, 2632), True, 'import torch.nn as nn\n'), ((2646, 2682), 'torch.autograd.Variable', 'Variable', (['inputs'], {'requires_grad': '(True)'}), '(inputs, requires_grad=True)\n', (2654, 2682), False, 'from torch.autograd import Variable\n'), ((3031, 3060), 'torch.ge', 'torch.ge', (['inputs.grad.data', '(0)'], {}), '(inputs.grad.data, 0)\n', (3039, 3060), False, 'import torch\n'), ((3166, 3216), 'torch.add', 'torch.add', (['inputs.data', '(-noiseMagnitude1)', 'gradient'], {}), '(inputs.data, -noiseMagnitude1, gradient)\n', (3175, 3216), False, 'import torch\n'), ((3587, 3612), 'numpy.max', 'np.max', (['nnOutputs'], {'axis': '(1)'}), '(nnOutputs, axis=1)\n', (3593, 3612), True, 'import numpy as np\n'), ((3740, 3815), 'os.path.join', 'os.path.join', (['"""output/odin_hyperparams/"""', 'args.in_dataset', 'args.name', '"""tmp"""'], {}), "('output/odin_hyperparams/', args.in_dataset, args.name, 'tmp')\n", (3752, 3815), False, 'import os\n'), ((7450, 7482), 'numpy.arange', 'np.arange', (['(0)', '(0.0041)', '(0.004 / 20)'], {}), '(0, 0.0041, 0.004 / 20)\n', (7459, 7482), True, 'import numpy as np\n'), ((3238, 3258), 'torch.autograd.Variable', 'Variable', (['tempInputs'], {}), '(tempInputs)\n', (3246, 3258), False, 'from torch.autograd import Variable\n'), ((3448, 3488), 'numpy.max', 'np.max', (['nnOutputs'], {'axis': '(1)', 'keepdims': '(True)'}), '(nnOutputs, axis=1, keepdims=True)\n', (3454, 3488), True, 'import numpy as np\n'), ((3505, 3522), 'numpy.exp', 'np.exp', (['nnOutputs'], {}), '(nnOutputs)\n', (3511, 3522), True, 'import numpy as np\n'), ((3828, 3852), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (3842, 3852), False, 'import os\n'), ((3862, 3883), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n', (3873, 3883), False, 'import os\n'), ((4020, 4128), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(125.3 / 255, 123.0 / 255, 113.9 / 255)', '(63.0 / 255, 62.1 / 255.0, 66.7 / 255.0)'], {}), '((125.3 / 255, 123.0 / 255, 113.9 / 255), (63.0 / 255, \n 62.1 / 255.0, 66.7 / 255.0))\n', (4040, 4128), True, 'import torchvision.transforms as transforms\n'), ((4130, 4233), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', (['"""./datasets/cifar10"""'], {'train': '(True)', 'download': '(True)', 'transform': 'transform'}), "('./datasets/cifar10', train=True, download=\n True, transform=transform)\n", (4158, 4233), False, 'import torchvision\n'), ((4253, 4332), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(trainset, batch_size=args.batch_size, shuffle=True)\n', (4280, 4332), False, 'import torch\n'), ((4352, 4460), 'torchvision.datasets.CIFAR10', 'torchvision.datasets.CIFAR10', ([], {'root': '"""./datasets/cifar10"""', 'train': '(False)', 'download': '(True)', 'transform': 'transform'}), "(root='./datasets/cifar10', train=False,\n download=True, transform=transform)\n", (4380, 4460), False, 'import torchvision\n'), ((4480, 4558), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['testset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(testset, batch_size=args.batch_size, shuffle=True)\n', (4507, 4558), False, 'import torch\n'), ((6267, 6328), 'models.densenet.DenseNet3', 'dn.DenseNet3', (['args.layers', 'num_classes'], {'normalizer': 'normalizer'}), '(args.layers, num_classes, normalizer=normalizer)\n', (6279, 6328), True, 'import models.densenet as dn\n'), ((7496, 7507), 'time.time', 'time.time', ([], {}), '()\n', (7505, 7507), False, 'import time\n'), ((8612, 8623), 'time.time', 'time.time', ([], {}), '()\n', (8621, 8623), False, 'import time\n'), ((9430, 9454), 'utils.metric', 'metric', (['save_dir', 'stypes'], {}), '(save_dir, stypes)\n', (9436, 9454), False, 'from utils import ConfidenceLinfPGDAttack, MahalanobisLinfPGDAttack, softmax, metric, sample_estimator, get_Mahalanobis_score, TinyImages, CustomDataset\n'), ((3532, 3549), 'numpy.exp', 'np.exp', (['nnOutputs'], {}), '(nnOutputs)\n', (3538, 3549), True, 'import numpy as np\n'), ((3930, 3951), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3949, 3951), True, 'import torchvision.transforms as transforms\n'), ((4648, 4756), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(125.3 / 255, 123.0 / 255, 113.9 / 255)', '(63.0 / 255, 62.1 / 255.0, 66.7 / 255.0)'], {}), '((125.3 / 255, 123.0 / 255, 113.9 / 255), (63.0 / 255, \n 62.1 / 255.0, 66.7 / 255.0))\n', (4668, 4756), True, 'import torchvision.transforms as transforms\n'), ((4758, 4863), 'torchvision.datasets.CIFAR100', 'torchvision.datasets.CIFAR100', (['"""./datasets/cifar100"""'], {'train': '(True)', 'download': '(True)', 'transform': 'transform'}), "('./datasets/cifar100', train=True, download=\n True, transform=transform)\n", (4787, 4863), False, 'import torchvision\n'), ((4883, 4962), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(trainset, batch_size=args.batch_size, shuffle=True)\n', (4910, 4962), False, 'import torch\n'), ((4982, 5092), 'torchvision.datasets.CIFAR100', 'torchvision.datasets.CIFAR100', ([], {'root': '"""./datasets/cifar100"""', 'train': '(False)', 'download': '(True)', 'transform': 'transform'}), "(root='./datasets/cifar100', train=False,\n download=True, transform=transform)\n", (5011, 5092), False, 'import torchvision\n'), ((5112, 5190), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['testset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)'}), '(testset, batch_size=args.batch_size, shuffle=True)\n', (5139, 5190), False, 'import torch\n'), ((6387, 6478), 'models.wideresnet.WideResNet', 'wn.WideResNet', (['args.depth', 'num_classes'], {'widen_factor': 'args.width', 'normalizer': 'normalizer'}), '(args.depth, num_classes, widen_factor=args.width, normalizer=\n normalizer)\n', (6400, 6478), True, 'import models.wideresnet as wn\n'), ((7526, 7574), 'os.path.join', 'os.path.join', (['save_dir', '"""confidence_ODIN_In.txt"""'], {}), "(save_dir, 'confidence_ODIN_In.txt')\n", (7538, 7574), False, 'import os\n'), ((7599, 7648), 'os.path.join', 'os.path.join', (['save_dir', '"""confidence_ODIN_Out.txt"""'], {}), "(save_dir, 'confidence_ODIN_Out.txt')\n", (7611, 7648), False, 'import os\n'), ((8489, 8500), 'time.time', 'time.time', ([], {}), '()\n', (8498, 8500), False, 'import time\n'), ((9360, 9371), 'time.time', 'time.time', ([], {}), '()\n', (9369, 9371), False, 'import time\n'), ((2866, 2896), 'torch.LongTensor', 'torch.LongTensor', (['maxIndexTemp'], {}), '(maxIndexTemp)\n', (2882, 2896), False, 'import torch\n'), ((5925, 5946), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5944, 5946), True, 'import torchvision.transforms as transforms\n'), ((5948, 5971), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (5969, 5971), True, 'import torchvision.transforms as transforms\n'), ((5973, 6009), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(32)'], {'padding': '(4)'}), '(32, padding=4)\n', (5994, 6009), True, 'import torchvision.transforms as transforms\n'), ((6020, 6053), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (6051, 6053), True, 'import torchvision.transforms as transforms\n'), ((6055, 6076), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (6074, 6076), True, 'import torchvision.transforms as transforms\n'), ((5438, 5459), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5457, 5459), True, 'import torchvision.transforms as transforms\n'), ((5682, 5703), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5701, 5703), True, 'import torchvision.transforms as transforms\n')]
import numpy as np from sklearn.metrics import pairwise_distances class KMeans: ''' K-Means clustering algorithm using euclidean and mahalanobis distance ''' def __init__(self, n_clusters, max_iterations=200, distance='euclidean', seed=2): ''' Inputs: - n_clusters: number of clusters to find. - max_iterations: maximum number of iterations to run. - distance: type of distance euclidean/mahalanobis ''' self.n_clusters = n_clusters self.max_iterations = max_iterations self.distance = distance self.labels = None self.centroids = None self.seed = seed def initialize_centroids(self, data): ''' Randomly choose n_clusters data points as our initial centroids Inputs: - data: the array of points ''' # Set the seed np.random.seed(self.seed) # Number of points num_points = data.shape[0] # Pick n_cluster indices indices = np.random.randint(0, num_points, self.n_clusters) # Get the centroids centroids = data[indices,:] return centroids def adjust_centroids(self, data, current_labels): ''' One the points are assigned, adjust the centroids Inputs: - data: the array of points - current_labels: list of current labels for the data points ''' new_centroids = [] for x in range(self.n_clusters): # Get the new centroid centroid = data[current_labels == x].mean(axis = 0) # Add it to the list of centroids new_centroids.append(np.ravel(centroid)) return np.array(new_centroids) def mahalanobis(self, data, centroid, vi): ''' Calculate the mahalanobis distance between the points and the centroid Inputs: - data: the array of points - centroid: center point for the distance - vi: inverse of the covaraince matrix ''' mean_difference = data - np.mean(centroid) temp = np.dot(mean_difference, vi) distance = np.dot(temp, mean_difference.transpose()) return np.sqrt(distance.diagonal().reshape(len(data),1)) def calculate_distance(self, data, centroids, covariance): ''' Calculate the distance between the points and the centroids Inputs: - data: the array of points - centroids: center points for the clusters - distance: type of distance euclidean/mahalanobis ''' # Euclidean Distance if self.distance == "euclidean": return pairwise_distances(data, centroids, metric=self.distance) # Malahanobis Distance # if we don't have previous assignments yet if covariance is None: return pairwise_distances(data, centroids, metric=self.distance, VI=np.linalg.inv(np.cov(data.transpose()))) result = [] # Get the distance between each point and each cluster centroid for (cov,centroid) in zip(covariance, centroids): distance = self.mahalanobis(data=data, centroid=centroid, vi=np.linalg.inv(cov)) result = distance if len(result) == 0 else np.concatenate((result, pairwise_distances(data, [centroid], metric=self.distance, VI=np.linalg.inv(cov))), axis=1) return result def assign_clusters(self, data, centroids, covariance): ''' Assign points to a cluster based off their distance Inputs: - data: the array of points - centroids: center points for the clusters - distance: type of distance euclidean/mahalanobis ''' # Compute distances between each data point and the set of centroids, based on the distance selected: distances_from_centroids = self.calculate_distance(data=data, centroids=centroids, covariance=covariance) # Return cluster assignments return np.argmin(distances_from_centroids, axis=1) def get_covariance_matrices(self, data, current_assignments): ''' Get the covarince matrix for each cluster Inputs: - data: the array of points - current_assignments: the current assignments of each point for each cluster ''' cov = [] for x in range(self.n_clusters): temp = np.delete(data, np.where(current_assignments == x), axis = 0) cov.append(np.cov(temp.transpose())) return cov def fit(self, data): ''' Runs k-means on given data Inputs: - data: the array of points ''' # Initialize centroids centroids = self.initialize_centroids(data=data) prev_assignment = None covariance = None for x in range(self.max_iterations): if prev_assignment is not None: covariance = self.get_covariance_matrices(data=data, current_assignments=prev_assignment) # Make cluster assignments current_assignments = self.assign_clusters(data=data, centroids=centroids, covariance=covariance) # Adjust the centroids centroids = self.adjust_centroids(data=data, current_labels=current_assignments) # Check for convergence if prev_assignment is not None and (prev_assignment==current_assignments).all(): break prev_assignment = current_assignments[:] # Set the labels self.labels = current_assignments self.centroids = centroids
[ "numpy.random.seed", "numpy.ravel", "sklearn.metrics.pairwise_distances", "numpy.argmin", "numpy.random.randint", "numpy.array", "numpy.mean", "numpy.where", "numpy.linalg.inv", "numpy.dot" ]
[((931, 956), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (945, 956), True, 'import numpy as np\n'), ((1072, 1121), 'numpy.random.randint', 'np.random.randint', (['(0)', 'num_points', 'self.n_clusters'], {}), '(0, num_points, self.n_clusters)\n', (1089, 1121), True, 'import numpy as np\n'), ((1772, 1795), 'numpy.array', 'np.array', (['new_centroids'], {}), '(new_centroids)\n', (1780, 1795), True, 'import numpy as np\n'), ((2184, 2211), 'numpy.dot', 'np.dot', (['mean_difference', 'vi'], {}), '(mean_difference, vi)\n', (2190, 2211), True, 'import numpy as np\n'), ((4129, 4172), 'numpy.argmin', 'np.argmin', (['distances_from_centroids'], {'axis': '(1)'}), '(distances_from_centroids, axis=1)\n', (4138, 4172), True, 'import numpy as np\n'), ((2151, 2168), 'numpy.mean', 'np.mean', (['centroid'], {}), '(centroid)\n', (2158, 2168), True, 'import numpy as np\n'), ((2772, 2829), 'sklearn.metrics.pairwise_distances', 'pairwise_distances', (['data', 'centroids'], {'metric': 'self.distance'}), '(data, centroids, metric=self.distance)\n', (2790, 2829), False, 'from sklearn.metrics import pairwise_distances\n'), ((1736, 1754), 'numpy.ravel', 'np.ravel', (['centroid'], {}), '(centroid)\n', (1744, 1754), True, 'import numpy as np\n'), ((4563, 4597), 'numpy.where', 'np.where', (['(current_assignments == x)'], {}), '(current_assignments == x)\n', (4571, 4597), True, 'import numpy as np\n'), ((3292, 3310), 'numpy.linalg.inv', 'np.linalg.inv', (['cov'], {}), '(cov)\n', (3305, 3310), True, 'import numpy as np\n'), ((3453, 3471), 'numpy.linalg.inv', 'np.linalg.inv', (['cov'], {}), '(cov)\n', (3466, 3471), True, 'import numpy as np\n')]
import math import collections import numpy as np import pandas as pd import scipy import scipy.stats import remixt.utils import remixt.likelihood import remixt.analysis.experiment import remixt.simulations.balanced MAX_SEED = 2**32 class RearrangedGenome(object): """ Rearranged genome with stored history. Attributes: default_params (dict): dictionary of default simulation parameters chromosomes (list of list of tuple): list of chromosome, each chromosome a list of 'segment copy' wt_adj (set): set of 'breakpoints' representing wild type adjacencies init_params (dict): parameters for initializing chromosome structure. init_seed (int) seed for random initialization of chromosome structure. event_params (list of dict): list of parameters for randomly selected events. event_seeds (list of int): list of seeds used to generate randomly selected events. A 'segment copy' is represented as the tuple (('segment', 'allele'), 'orientation'). A 'breakend' is represented as the tuple (('segment', 'allele'), 'side'). A 'breakpoint' is represented as the frozenset (['breakend_1', 'breakend_2']) """ default_params = { 'genome_length':3e9, 'seg_length_concentration':1.0, 'seg_length_min':50000, 'num_chromosomes':20, 'chrom_length_concentration':5., 'chromosome_lengths':None, 'event_type':['dcj', 'dup', 'del', 'wgd'], 'event_prob':[0.19, 0.3, 0.5, 0.01], 'del_prop_len':0.5, 'dup_prop_len':0.5, 'wgd_prop_dup':0.8, } def __init__(self, N): """ Create an empty genome. Args: N (int): number of segments """ self.N = N self.init_params = None self.init_seed = None self.event_params = list() self.event_seeds = list() def copy(self): """ Create a copy of the genome. Creates a copy such that rearrangement of the copy will not affect the original. """ genome = RearrangedGenome(self.N) # References to fixed attributes of each genome genome.init_params = self.init_params genome.init_seed = self.init_seed genome.segment_start = self.segment_start genome.segment_end = self.segment_end genome.segment_chromosome_id = self.segment_chromosome_id genome.l = self.l genome.wt_adj = self.wt_adj # Copies of mutable attributes of each genome genome.event_params = list(self.event_params) genome.event_seeds = list(self.event_seeds) genome.chromosomes = list(self.chromosomes) return genome def create(self, params): """ Create a new non-rearranged genome. Args: params (dict): parameters for random chromosome creation Sets the seed and updates the init seed and params. """ seed = np.random.randint(MAX_SEED - 1) np.random.seed(seed) self.random_chromosomes(params) self.init_params = params self.init_seed = seed def rewind(self, num_events): """ Rewind event list to more ancestral genome. Args: num_events (int): number of ancestral events from which to create genome """ self.event_params = self.event_params[:num_events] self.event_seeds = self.event_seeds[:num_events] self.recreate() def recreate(self): """ Recreate a genome based on event list. """ np.random.seed(self.init_seed) self.random_chromosomes(self.init_params) for params, seed in zip(self.event_params, self.event_seeds): np.random.seed(seed) self.random_event(params) def random_chromosomes(self, params): """ Create a random set of chromosomes. Args: params (dict): parameters for random chromosome creation """ if params.get('chromosome_lengths', None) is not None: chromosome_ids = list(params['chromosome_lengths'].keys()) chromosome_lengths = np.array(list(params['chromosome_lengths'].values())) else: num_chroms = params['num_chromosomes'] genome_length = params['genome_length'] chrom_length_concentration = params['chrom_length_concentration'] chromosome_ids = [str(a) for a in range(1, num_chroms + 1)] chromosome_lengths = np.random.dirichlet([chrom_length_concentration] * num_chroms) * genome_length chromosome_lengths.sort_values() chromosome_lengths = chromosome_lengths[::-1] chrom_pvals = chromosome_lengths.astype(float) / float(chromosome_lengths.sum()) chrom_num_segments = np.random.multinomial(self.N - len(chromosome_lengths), pvals=chrom_pvals) chrom_num_segments += 1 seg_length_concentration = params['seg_length_concentration'] seg_length_min = params['seg_length_min'] self.l = np.array([]) self.segment_chromosome_id = np.array([], dtype=str) self.segment_start = np.array([], dtype=int) self.segment_end = np.array([], dtype=int) for chrom_id, chrom_length, num_segments in zip(chromosome_ids, chromosome_lengths, chrom_num_segments): length_proportions = np.random.dirichlet([seg_length_concentration] * num_segments) length_proportions = np.maximum(length_proportions, float(seg_length_min) / chrom_length) length_proportions /= length_proportions.sum() lengths = length_proportions * chrom_length lengths = lengths.astype(int) lengths[-1] = chrom_length - lengths[:-1].sum() assert lengths[-1] > 0 chrom_ids = [chrom_id] * num_segments ends = lengths.cumsum() starts = ends - lengths self.l = np.concatenate((self.l, lengths)) self.segment_chromosome_id = np.concatenate((self.segment_chromosome_id, chrom_ids)) self.segment_start = np.concatenate((self.segment_start, starts)) self.segment_end = np.concatenate((self.segment_end, ends)) segment_idx = 0 self.chromosomes = list() for num_seg in chrom_num_segments: for allele in (0, 1): chrom_segs = range(segment_idx, segment_idx+num_seg) chrom_alleles = [allele]*num_seg chrom_orient = [1]*num_seg self.chromosomes.append(tuple(zip(zip(chrom_segs, chrom_alleles), chrom_orient))) segment_idx += num_seg self.wt_adj = set() self.wt_adj = set(self.breakpoints) def generate_cuts(self): """ Generate a list of possible cuts. Cuts are triples of chromosome index, segment index where the segment index is the second in an adjacent pair """ for chromosome_idx, chromosome in enumerate(self.chromosomes): for segment_idx in range(len(chromosome)): next_segment_idx = (segment_idx + 1) % len(chromosome) yield (chromosome_idx, next_segment_idx) def random_cut(self): """ Sample a random cut """ cuts = list(self.generate_cuts()) idx = np.random.choice(range(len(cuts))) return cuts[idx] def random_cut_pair(self): """ Sample a random cut pair without replacement """ cuts = list(self.generate_cuts()) idx1, idx2 = np.random.choice(range(len(cuts)), size=2, replace=False) return (cuts[idx1], cuts[idx2]) def reverse_segment(self, segment): """ Reverse the sign of a segment. """ return (segment[0], segment[1] * -1) def reverse_chromosome(self, chromosome): """ Reverse the order of segments in a chromosome, and the sign of each segment. """ return tuple([self.reverse_segment(a) for a in reversed(chromosome)]) def rearrange(self, params): """ Apply random rearrangement event. Args: params (dict): dictionary of modification params Sets the seed and appends the seed and params to the event lists. """ seed = np.random.randint(MAX_SEED - 1) np.random.seed(seed) self.random_event(params) self.event_params.append(params) self.event_seeds.append(seed) def random_event(self, params): """ Randomly apply rearrangement event. Args: params (dict): dictionary of modification params """ event = np.random.choice(params['event_type'], p=params['event_prob']) if event == 'dcj': self.random_double_cut_join(params) elif event == 'dup': self.random_duplication(params) elif event == 'del': self.random_deletion(params) elif event == 'wgd': self.random_whole_genome_doubling(params) def random_double_cut_join(self, params): """ Randomly break the genome at two locations and rejoin. Args: params (dict): dictionary of modification params """ if len(self.chromosomes) < 2: return breakpoint_1, breakpoint_2 = sorted(self.random_cut_pair()) dcj_flip = np.random.choice([True, False]) if breakpoint_1[0] != breakpoint_2[0]: chromosome_1 = self.chromosomes[breakpoint_1[0]] chromosome_2 = self.chromosomes[breakpoint_2[0]] del self.chromosomes[breakpoint_1[0]] del self.chromosomes[breakpoint_2[0] - 1] if dcj_flip: # Create a new chromosome with chromosome 2 segments reversed new_chromosome = chromosome_1[:breakpoint_1[1]] + \ self.reverse_chromosome(chromosome_2[:breakpoint_2[1]]) + \ self.reverse_chromosome(chromosome_2[breakpoint_2[1]:]) + \ chromosome_1[breakpoint_1[1]:] assert len(new_chromosome) > 0 self.chromosomes.append(new_chromosome) else: # Create a new chromosome with orientation preserved new_chromosome = chromosome_1[:breakpoint_1[1]] + \ chromosome_2[breakpoint_2[1]:] + \ chromosome_2[:breakpoint_2[1]] + \ chromosome_1[breakpoint_1[1]:] assert len(new_chromosome) > 0 self.chromosomes.append(new_chromosome) else: chromosome = self.chromosomes[breakpoint_1[0]] del self.chromosomes[breakpoint_1[0]] if dcj_flip: # Create a new chromosome with an inversion of some segments new_chromosome = chromosome[:breakpoint_1[1]] + \ self.reverse_chromosome(chromosome[breakpoint_1[1]:breakpoint_2[1]]) + \ chromosome[breakpoint_2[1]:] assert len(new_chromosome) > 0 self.chromosomes.append(new_chromosome) else: # Create two new chromosomes with orientation preserved new_chromosome_1 = chromosome[:breakpoint_1[1]] + \ chromosome[breakpoint_2[1]:] new_chromosome_2 = chromosome[breakpoint_1[1]:breakpoint_2[1]] assert len(new_chromosome_1) > 0 assert len(new_chromosome_2) > 0 self.chromosomes.append(new_chromosome_1) self.chromosomes.append(new_chromosome_2) def random_deletion(self, params): """ Randomly delete consecutive segments of a chromosome. Args: params (dict): dictionary of modification params """ if len(self.chromosomes) == 0: return breakpoint_1 = self.random_cut() chromosome = self.chromosomes[breakpoint_1[0]] del self.chromosomes[breakpoint_1[0]] chrom_length = len(chromosome) deletion_length = np.random.randint(0, math.ceil(params['del_prop_len'] * chrom_length)) if deletion_length == 0: return breakpoint_2 = (breakpoint_1[0], (breakpoint_1[1] + deletion_length) % chrom_length) if breakpoint_1[1] < breakpoint_2[1]: new_chromosome = chromosome[:breakpoint_1[1]] + \ chromosome[breakpoint_2[1]:] self.chromosomes.append(new_chromosome) else: new_chromosome = chromosome[breakpoint_2[1]:breakpoint_1[1]] self.chromosomes.append(new_chromosome) def random_duplication(self, params): """ Randomly duplicate consecutive segments of a chromosome. Args: params (dict): dictionary of modification params """ if len(self.chromosomes) == 0: return breakpoint_1 = self.random_cut() chromosome = self.chromosomes[breakpoint_1[0]] del self.chromosomes[breakpoint_1[0]] chrom_length = len(chromosome) duplication_length = np.random.randint(0, math.ceil(params['dup_prop_len'] * chrom_length)) breakpoint_2 = (breakpoint_1[0], (breakpoint_1[1] + duplication_length) % chrom_length) if breakpoint_1[1] < breakpoint_2[1]: new_chromosome = chromosome[:breakpoint_2[1]] + \ chromosome[breakpoint_1[1]:] self.chromosomes.append(new_chromosome) else: new_chromosome = chromosome + \ chromosome[:breakpoint_2[1]] + \ chromosome[breakpoint_1[1]:] self.chromosomes.append(new_chromosome) def random_whole_genome_doubling(self, params): """ Randomly select chromosomes to be duplicated. Args: params (dict): dictionary of modification params """ duplicated_chromosomes = [] for chromosome in self.chromosomes: if np.random.rand() < params['wgd_prop_dup']: duplicated_chromosomes.append(chromosome) self.chromosomes.extend(duplicated_chromosomes) @property def segment_copy_number(self): """ Segment copy number matrix (numpy.array). """ cn_matrix = np.zeros((self.N, 2)) for chromosome in self.chromosomes: for segment in chromosome: cn_matrix[segment[0][0], segment[0][1]] += 1.0 return cn_matrix @property def breakpoint_copy_number(self): """ Breakpoint copy number (dict of breakpoint to integer copy number). """ brk_cn = collections.Counter() for chromosome_idx, segment_idx_2 in self.generate_cuts(): segment_idx_1 = (segment_idx_2 - 1) % len(self.chromosomes[chromosome_idx]) segment_1 = self.chromosomes[chromosome_idx][segment_idx_1] segment_2 = self.chromosomes[chromosome_idx][segment_idx_2] side_1 = (0, 1)[segment_1[1] == 1] side_2 = (1, 0)[segment_2[1] == 1] brkend_1 = (segment_1[0], side_1) brkend_2 = (segment_2[0], side_2) breakpoint = frozenset([brkend_1, brkend_2]) if breakpoint in self.wt_adj: continue brk_cn[breakpoint] += 1 return brk_cn @property def breakpoints(self): """ Breakpoint list. """ return list(self.breakpoint_copy_number.keys()) def length_loh(self): """ Length of the genome with LOH. """ cn = self.segment_copy_number loh = (cn.min(axis=1) == 0) * 1 return (loh * self.l).sum() def proportion_loh(self): """ Proportion of the genome with LOH. """ return self.length_loh() / float(self.l.sum()) def length_hdel(self): """ Length of the genome homozygously deleted. """ cn = self.segment_copy_number hdel = (cn.max(axis=1) == 0) * 1 return (hdel * self.l).sum() def proportion_hdel(self): """ Proportion of the genome homozygously deleted. """ return self.length_hdel() / float(self.l.sum()) def length_hlamp(self, hlamp_min=6): """ Length of the genome with high level amplification. """ cn = self.segment_copy_number hlamp = (cn.sum(axis=1) >= hlamp_min) * 1 return (hlamp * self.l).sum() def proportion_hlamp(self, hlamp_min=6): """ Proportion of the genome with high level amplification. """ return self.length_hlamp(hlamp_min=hlamp_min) / float(self.l.sum()) def length_divergent(self, other): """ Length of the genome divergent from another genome. """ cn = self.segment_copy_number other_cn = other.segment_copy_number divergent = ((cn - other_cn > 0) * 1).sum(axis=1) return (divergent * self.l).sum() def proportion_divergent(self, other): """ Proportion of the genome divergent from another genome. """ return self.length_divergent(other) / float(self.l.sum()) def ploidy(self): """ Average number of copies of each nucleotide. """ cn = self.segment_copy_number cn = cn.sum(axis=1) return (cn * self.l).sum() / self.l.sum() def proportion_minor_state(self, cn_max=6): """ Proportion of the genome with minor in each cn state. """ minor = self.segment_copy_number.min(axis=1) minor[minor > cn_max] = cn_max return np.bincount(minor.flatten().astype(int), weights=self.l, minlength=cn_max+1) / self.l.sum() def proportion_major_state(self, cn_max=6): """ Proportion of the genome with major in each cn state. """ major = self.segment_copy_number.max(axis=1) major[major > cn_max] = cn_max return np.bincount(major.flatten().astype(int), weights=self.l, minlength=cn_max+1) / self.l.sum() def create_chromosome_sequences(self, germline_genome): """ Create sequences of rearranged chromosomes Args: ref_genome (dict): germline chromosome allele sequences keyed by (chromosome, allele_id) Returns: list: rearranged chromosome allele sequences """ rearranged_genome = list() for chrom in self.chromosomes: rearranged_chromosome = list() for ((segment_idx, allele_id), orientation) in chrom: chromosome_id = self.segment_chromosome_id[segment_idx] start = self.segment_start[segment_idx] end = self.segment_end[segment_idx] segment_sequence = germline_genome[(chromosome_id, allele_id)][start:end] if orientation < 0: segment_sequence = remixt.utils.reverse_complement(segment_sequence) rearranged_chromosome.append(segment_sequence) rearranged_genome.append(''.join(rearranged_chromosome)) return rearranged_genome def log_multinomial_likelihood(x, p): return scipy.special.gammaln(np.sum(x+1)) - np.sum(scipy.special.gammaln(x+1)) + np.sum(x * np.log(p)) class RearrangementHistorySampler(object): """ Simulate a random rearrangement history, accounting for relative fitness """ def __init__(self, params): self.N = params.get('N', 1000) self.genome_params = RearrangedGenome.default_params for key in self.genome_params.keys(): if key in params: self.genome_params[key] = params[key] self.proportion_hdel = params.get('proportion_hdel', 0.) self.proportion_hdel_stddev = params.get('proportion_hdel_stddev', 0.001) self.proportion_hlamp = params.get('proportion_hlamp', 0.) self.proportion_hlamp_stddev = params.get('proportion_hlamp_stddev', 0.001) self.ploidy = params.get('ploidy', 2.5) self.ploidy_stddev = params.get('ploidy_stddev', 0.1) self.proportion_loh = params.get('proportion_loh', 0.2) self.proportion_loh_stddev = params.get('proportion_loh_stddev', 0.02) self.num_swarm = 100 def genome_fitness(self, genome, fitness_callback=None): """ Calculate fitness of a genome based on loh, hdel and hlamp proportions. Args: genome (RearrangedGenome): Genome to calculate fitness Kwargs: fitness_callback (callable): modify fitness callback """ hdel_log_p = scipy.stats.norm.logpdf(genome.proportion_hdel(), loc=self.proportion_hdel, scale=self.proportion_hdel_stddev) hlamp_log_p = scipy.stats.norm.logpdf(genome.proportion_hlamp(), loc=self.proportion_hlamp, scale=self.proportion_hlamp_stddev) ploidy_log_p = scipy.stats.norm.logpdf(genome.ploidy(), loc=self.ploidy, scale=self.ploidy_stddev) loh_log_p = scipy.stats.norm.logpdf(genome.proportion_loh(), loc=self.proportion_loh, scale=self.proportion_loh_stddev) fitness = hdel_log_p + hlamp_log_p + ploidy_log_p + loh_log_p if fitness_callback is not None: fitness = fitness_callback(genome, fitness) return fitness def resample_probs(self, genomes, fitness_callback=None): """ Calculate resampling probabilities. Args: genomes (list of RearrangedGenome): list of rearranged genomes to calculate prob from fitnesses Kwargs: fitness_callback (callable): modify fitness callback """ fitnesses = list() for genome in genomes: fitnesses.append(self.genome_fitness(genome, fitness_callback)) fitnesses = np.array(fitnesses) prob = np.exp(fitnesses - scipy.misc.logsumexp(fitnesses)) return prob def sample_wild_type(self): """ Sample a wild type genome. Returns: RearrangedGenome: a wild type genome with no rearrangements """ wt_genome = RearrangedGenome(self.N) wt_genome.create(self.genome_params) return wt_genome def sample_rearrangement_history(self, genome_init, num_events, fitness_callback=None): """ Sample a rearrangement history specified by a random seed, and select based on fitness. Args: genome_init (RearrangedGenome): initial genome to which rearrangements will be applied num_events (int): number of rearrangement events Kwargs: fitness_callback (callable): modify fitness callback Returns: list of RearrangedGenome: a list genome evolved through a series of rearrangements, sorted by the resample probablity of those genomes """ swarm = [genome_init] * self.num_swarm for _ in range(num_events): new_swarm = list() for genome in swarm: genome = genome.copy() genome.rearrange(self.genome_params) new_swarm.append(genome) resample_p = self.resample_probs(new_swarm, fitness_callback=fitness_callback) resampled_swarm = np.random.choice(new_swarm, size=self.num_swarm, p=resample_p) swarm = list(resampled_swarm) prob = self.resample_probs(swarm) swarm = list(np.array(swarm)[np.argsort(prob)[::-1]]) return swarm def _collapse_allele_bp(allele_bp): ((n_1, ell_1), side_1), ((n_2, ell_2), side_2) = allele_bp return frozenset([(n_1, side_1), (n_2, side_2)]) def _sum_brk_cn_alleles(allele_brk_cn): total_brk_cn = {} for allele_bp, cn in allele_brk_cn.items(): total_bp = _collapse_allele_bp(allele_bp) if total_bp not in total_brk_cn: total_brk_cn[total_bp] = cn else: total_brk_cn[total_bp] += cn return total_brk_cn def _collapse_allele_bps(allele_bps): total_bps = set() for allele_bp in allele_bps: total_bps.add(_collapse_allele_bp(allele_bp)) return total_bps class GenomeCollection(object): """ Collection of normal and tumour clone genomes. """ def __init__(self, genomes): self.genomes = genomes self.cn = np.array([genome.segment_copy_number for genome in self.genomes]) self.cn = self.cn.swapaxes(0, 1) self.adjacencies = set() for breakends in self.genomes[0].wt_adj: adj = [None, None] for breakend in breakends: adj[1-breakend[1]] = breakend[0][0] assert None not in adj self.adjacencies.add(tuple(adj)) self.breakpoints = set() for genome in self.genomes[1:]: for brkend_1, brkend_2 in genome.breakpoints: brkend_1 = (brkend_1[0][0], brkend_1[1]) brkend_2 = (brkend_2[0][0], brkend_2[1]) self.breakpoints.add(frozenset([brkend_1, brkend_2])) self.breakpoint_copy_number = collections.defaultdict(lambda: np.zeros(self.M)) for m in range(self.M): for breakpoint, brk_cn in self.genomes[m].breakpoint_copy_number.items(): self.breakpoint_copy_number[breakpoint][m] = brk_cn self.breakpoint_copy_number = dict(self.breakpoint_copy_number) self.balanced_breakpoints = set() for breakpoint, brk_cn in self.breakpoint_copy_number.items(): brk_cn_sum = 0 for (n, ell), side_1 in breakpoint: if side_1 == 1: n_2 = (n + 1) % self.N else: n_2 = (n - 1) % self.N brk_cn_sum += abs((self.cn[n,:,ell] - self.cn[n_2,:,ell]).sum()) if brk_cn_sum == 0: self.balanced_breakpoints.add(breakpoint) @property def N(self): return self.genomes[0].N @property def M(self): return len(self.genomes) @property def l(self): return self.genomes[0].l @property def segment_chromosome_id(self): return self.genomes[0].segment_chromosome_id @property def segment_start(self): return self.genomes[0].segment_start @property def segment_end(self): return self.genomes[0].segment_end def length_divergent(self): return self.genomes[1].length_divergent(self.genomes[2]) def length_loh(self): return [g.length_loh() for g in self.genomes] def length_hdel(self): return [g.length_hdel() for g in self.genomes] def length_hlamp(self, hlamp_min=6): return [g.length_hlamp() for g in self.genomes] def collapsed_breakpoint_copy_number(self): return _sum_brk_cn_alleles(self.breakpoint_copy_number) def collapsed_minimal_breakpoint_copy_number(self): minimal_breakpoint_copy_number = remixt.simulations.balanced.minimize_breakpoint_copies( self.adjacencies, self.breakpoint_copy_number) return _sum_brk_cn_alleles(minimal_breakpoint_copy_number) def collapsed_balanced_breakpoints(self): return _collapse_allele_bps(self.balanced_breakpoints) class GenomeCollectionSampler(object): """ Samples a collection of two genomes with rearrangement histories related by a chain phylogeny. """ def __init__(self, rearrangement_history_sampler, params): self.rh_sampler = rearrangement_history_sampler self.num_ancestral_events = params.get('num_ancestral_events', 25) self.num_descendent_events = params.get('num_descendent_events', 10) self.M = params['M'] self.ploidy = params.get('ploidy', 2.5) self.ploidy_max_error = params.get('ploidy_max_error', 0.2) self.proportion_loh = params.get('proportion_loh', 0.2) self.proportion_loh_max_error = params.get('proportion_loh_max_error', 0.02) self.proportion_subclonal = params.get('proportion_subclonal', 0.3) self.proportion_subclonal_max_error = params.get('proportion_subclonal_max_error', 0.02) self.proportion_subclonal_stddev = params.get('proportion_subclonal_stddev', 0.02) def sample_genome_collection(self): """ Sample a collection of genomes. Returns: GenomeCollection: randomly generated collection of genomes """ wt_genome = self.rh_sampler.sample_wild_type() genomes = [wt_genome] success = False ancestral_genome = None for anc_iter in range(100): ancestral_genomes = self.rh_sampler.sample_rearrangement_history(wt_genome, self.num_ancestral_events) ancestral_genomes = np.array(ancestral_genomes) ploidys = np.array([genome.ploidy() for genome in ancestral_genomes]) ploidy_errors = np.absolute(ploidys - self.ploidy) ancestral_genomes = ancestral_genomes[ploidy_errors < self.ploidy_max_error] if len(ancestral_genomes) == 0: print ('failed ploidy') continue loh_proportions = np.array([genome.proportion_loh() for genome in ancestral_genomes]) loh_errors = np.absolute(loh_proportions - self.proportion_loh) ancestral_genomes = ancestral_genomes[loh_errors < self.proportion_loh_max_error] if len(ancestral_genomes) == 0: print ('failed loh') continue ancestral_genome = ancestral_genomes[0] genomes.append(ancestral_genomes[0]) success = True break if not success: raise ValueError('unable to simulate ancestral genome') def subclone_fitness(genome, fitness): divergent_log_p = scipy.stats.norm.logpdf( genome.proportion_divergent(ancestral_genome), loc=self.proportion_subclonal, scale=self.proportion_subclonal_stddev) return fitness + divergent_log_p for m in range(self.M - 2, self.M): success = False for desc_iter in range(100): descendent_genomes = self.rh_sampler.sample_rearrangement_history( ancestral_genome, self.num_descendent_events, fitness_callback=subclone_fitness) descendent_genomes = np.array(descendent_genomes) subclonal_proportions = np.array([genome.proportion_divergent(ancestral_genome) for genome in descendent_genomes]) subclonal_errors = np.absolute(subclonal_proportions - self.proportion_subclonal) descendent_genomes = descendent_genomes[subclonal_errors < self.proportion_subclonal_max_error] if len(descendent_genomes) == 0: print ('failed subclonal') continue genomes.append(descendent_genomes[0]) success = True break if not success: raise ValueError('unable to simulate descendant genome') return GenomeCollection(genomes) class GenomeMixture(object): """ Mixture of normal and tumour clone genomes. """ def __init__(self, genome_collection, frac, detected_breakpoints): self.genome_collection = genome_collection self.frac = frac self.detected_breakpoints = detected_breakpoints # Table of breakpoint information including chromosome position # info and prediction ids breakpoint_segment_data = list() for prediction_id, breakpoint in self.detected_breakpoints.items(): breakpoint_info = {'prediction_id': prediction_id} for breakend_idx, breakend in enumerate(breakpoint): n, side = breakend if side == 0: strand = '-' position = self.segment_start[n] elif side == 1: strand = '+' position = self.segment_end[n] else: raise Exception('unexpected side value') breakpoint_info['n_{}'.format(breakend_idx + 1)] = n breakpoint_info['side_{}'.format(breakend_idx + 1)] = side breakpoint_info['chromosome_{}'.format(breakend_idx + 1)] = self.segment_chromosome_id[n] breakpoint_info['position_{}'.format(breakend_idx + 1)] = position breakpoint_info['strand_{}'.format(breakend_idx + 1)] = strand breakpoint_segment_data.append(breakpoint_info) self.breakpoint_segment_data = pd.DataFrame(breakpoint_segment_data) @property def N(self): return self.genome_collection.N @property def M(self): return self.genome_collection.M @property def l(self): return self.genome_collection.l @property def segment_chromosome_id(self): return self.genome_collection.segment_chromosome_id @property def segment_start(self): return self.genome_collection.segment_start @property def segment_end(self): return self.genome_collection.segment_end @property def cn(self): return self.genome_collection.cn @property def adjacencies(self): return self.genome_collection.adjacencies @property def breakpoints(self): return self.genome_collection.breakpoints def sample_random_breakpoints(N, num_breakpoints, adjacencies, excluded_breakpoints=None): breakpoints = set() while len(breakpoints) < num_breakpoints: n_1 = np.random.randint(N) n_2 = np.random.randint(N) side_1 = np.random.randint(2) side_2 = np.random.randint(2) # Do not add wild type adjacencies if (n_1, n_2) in adjacencies and side_1 == 1 and side_2 == 0: continue if (n_2, n_1) in adjacencies and side_2 == 1 and side_1 == 0: continue # TODO: fold back inversions if (n_1, side_1) == (n_2, side_2): continue breakpoint = frozenset([(n_1, side_1), (n_2, side_2)]) # Do not add excluded breakpoints if excluded_breakpoints is not None and breakpoint in excluded_breakpoints: continue breakpoints.add(breakpoint) return breakpoints class GenomeMixtureSampler(object): """ Sampler for genome mixtures. """ def __init__(self, params): self.frac_normal = params.get('frac_normal', 0.4) self.frac_clone_concentration = params.get('frac_clone_concentration', 1.) self.frac_clone_1 = params.get('frac_clone_1', None) self.num_false_breakpoints = params.get('num_false_breakpoints', 50) self.proportion_breakpoints_detected = params.get('proportion_breakpoints_detected', 0.9) def sample_genome_mixture(self, genome_collection): """ Sample a genome mixture. Args: genome_collection (GenomeCollection): collection of genomes to mix Returns: GenomeMixture: mixed genomes """ M = genome_collection.M frac = np.zeros((M,)) frac[0] = self.frac_normal if self.frac_clone_1 is None: frac[1:] = np.random.dirichlet([self.frac_clone_concentration] * (M-1)) * (1 - self.frac_normal) elif M == 3: frac[1:] = np.array([self.frac_clone_1, 1. - self.frac_normal - self.frac_clone_1]) elif M == 4: frac_clones_2_3 = 1. - self.frac_normal - self.frac_clone_1 frac_clones_2_3 = np.random.dirichlet([self.frac_clone_concentration] * (M-2)) * frac_clones_2_3 frac[1:] = np.array([self.frac_clone_1] + list(frac_clones_2_3)) else: raise Exception('Case not handled') assert abs(1. - np.sum(frac)) < 1e-8 num_breakpoints_detected = int(self.proportion_breakpoints_detected * len(genome_collection.breakpoints)) detected_breakpoints = list(genome_collection.breakpoints) np.random.shuffle(detected_breakpoints) detected_breakpoints = detected_breakpoints[:num_breakpoints_detected] false_breakpoints = sample_random_breakpoints( genome_collection.N, self.num_false_breakpoints, genome_collection.adjacencies, excluded_breakpoints=genome_collection.breakpoints, ) detected_breakpoints.extend(false_breakpoints) # Create a dictionary of detected breakpoints, keyed by a unique id detected_breakpoints = dict(enumerate(detected_breakpoints)) return GenomeMixture(genome_collection, frac, detected_breakpoints) class Experiment(object): """ Sequencing experiment read counts. """ def __init__(self, genome_mixture, h, phi, x, h_pred, **kwargs): self.genome_mixture = genome_mixture self.h = h self.phi = phi self.x = x self.h_pred = h_pred self.__dict__.update(kwargs) @property def N(self): return self.genome_mixture.N @property def M(self): return self.genome_mixture.M @property def l(self): return self.genome_mixture.l @property def segment_chromosome_id(self): return self.genome_mixture.segment_chromosome_id @property def segment_start(self): return self.genome_mixture.segment_start @property def segment_end(self): return self.genome_mixture.segment_end @property def cn(self): return self.genome_mixture.cn @property def adjacencies(self): return self.genome_mixture.adjacencies @property def chains(self): chain_start = [0] chain_end = [self.N] for idx in range(self.N - 1): if (idx, idx+1) not in self.adjacencies: chain_end.append(idx+1) # Half-open interval indexing [start, end) chain_start.append(idx+1) return zip(sorted(chain_start), sorted(chain_end)) @property def breakpoints(self): return self.genome_mixture.detected_breakpoints @property def breakpoint_segment_data(self): return self.genome_mixture.breakpoint_segment_data def _sample_negbin(mu, r): mu += 1e-16 inv_p = r / (r + mu) x = np.array([np.random.negative_binomial(r, a) for a in inv_p]).reshape(mu.shape) return x def _sample_negbin_mix(mu, r_0, r_1, mix): x_0 = _sample_negbin(mu, r_0) x_1 = _sample_negbin(mu, r_1) is_0 = np.random.random(size=x_0.shape) > mix x = np.where(is_0, x_0, x_1) return x, is_0 def _sample_betabin(n, p, M): p_binom = np.random.beta(M * p, M * (1 - p)) x = np.random.binomial(n, p_binom) return x def _sample_betabin_mix(n, p, M_0, M_1, mix): x_0 = _sample_betabin(n, p, M_0) x_1 = _sample_betabin(n, p, M_1) is_0 = np.random.random(size=x_0.shape) > mix x = np.where(is_0, x_0, x_1) return x, is_0 class ExperimentSampler(object): """ Sampler for sequencing experiments. """ def __init__(self, params): self.h_total = params.get('h_total', 0.1) self.phi_min = params.get('phi_min', 0.05) self.phi_max = params.get('phi_max', 0.2) self.emission_model = params.get('emission_model', 'negbin_betabin') if self.emission_model not in ('poisson', 'negbin', 'normal', 'full', 'negbin_betabin'): raise ValueError('emission_model must be one of "poisson", "negbin", "normal", "full"') self.frac_beta_noise_stddev = params.get('frac_beta_noise_stddev', None) self.params = params.copy() def sample_experiment(self, genome_mixture): """ Sample a sequencing experiment. Args: genome_mixture (GenomeMixture): mixture to sample read counts representing a sequencing experiment Returns: Experiment: sequencing experiment read counts """ N = genome_mixture.N l = genome_mixture.l cn = genome_mixture.cn h = genome_mixture.frac * self.h_total phi = np.random.uniform(low=self.phi_min, high=self.phi_max, size=N) mu = remixt.likelihood.expected_read_count(l, cn, h, phi) extra_params = dict() if self.emission_model == 'poisson': mu_poisson = mu + 1e-16 x = np.array([np.random.poisson(a) for a in mu_poisson]).reshape(mu_poisson.shape) elif self.emission_model == 'negbin': mu_negbin = mu + 1e-16 nb_inv_p = self.negbin_r / (self.negbin_r + mu_negbin) x = np.array([np.random.negative_binomial(self.negbin_r, a) for a in nb_inv_p]).reshape(mu_negbin.shape) extra_params['negbin_r'] = self.negbin_r elif self.emission_model == 'negbin_betabin': x = np.zeros(mu.shape) negbin_r_0 = self.params.get('negbin_r_0', 1000.) negbin_r_1 = self.params.get('negbin_r_1', 10.) negbin_mix = self.params.get('negbin_mix', 0.01) betabin_M_0 = self.params.get('betabin_M_0', 2000.) betabin_M_1 = self.params.get('betabin_M_1', 10.) betabin_mix = self.params.get('betabin_mix', 0.01) x_total, x_total_is_0 = _sample_negbin_mix(mu[:, 2] + 1e-16, negbin_r_0, negbin_r_1, negbin_mix) allele_total = (phi * x_total).astype(int) p_true = mu[:, 0] / (mu[:, 0:2].sum(axis=1) + 1e-16) x_allele_1, x_allele_1_is_0 = _sample_betabin_mix(allele_total, p_true, betabin_M_0, betabin_M_1, betabin_mix) x_allele_2 = allele_total - x_allele_1 x[:, 2] = x_total x[:, 0] = x_allele_1 x[:, 1] = x_allele_2 extra_params['is_outlier_total'] = ~x_total_is_0 extra_params['is_outlier_allele'] = ~x_allele_1_is_0 elif self.emission_model == 'normal': x = np.zeros(mu.shape) mu_total = mu[:, 2] a, b = 0.14514556880927346, 1.3745893696636038 variance = a * mu_total**b variance[variance == 0] = 50. x[:, 2] = np.random.normal(loc=mu_total, scale=variance**0.5) mu_allele = mu[:, 0:2] a, b = 0.040819090849598873, 1.4981089638117262 variance = a * mu_allele**b variance[variance == 0] = 50. x[:, 0:2] = np.random.normal(loc=mu_allele, scale=variance**0.5) x[x < 0] = 0 x = x.round().astype(int) if self.noise_prior is not None: noise_range_total = mu[:, 2].max() noise_range_total *= 1.25 is_outlier_total = np.random.choice( [True, False], size=mu[:, 2].shape, p=[self.noise_prior, 1. - self.noise_prior]) x[is_outlier_total, 2] = (np.random.randint(noise_range_total, size=mu[:, 2].shape))[is_outlier_total] is_outlier_allele = np.random.choice( [True, False], size=mu[:, 0].shape, p=[self.noise_prior, 1. - self.noise_prior]) outlier_allele_ratio = np.random.beta(2, 2, size=mu[:, 0].shape) x[is_outlier_allele, 0] = (outlier_allele_ratio * x[:, 0:2].sum(axis=1))[is_outlier_allele] x[is_outlier_allele, 1] = ((1. - outlier_allele_ratio) * x[:, 0:2].sum(axis=1))[is_outlier_allele] elif self.emission_model == 'full': x = np.zeros(mu.shape) mu_total = mu[:, 2] a, b = 0.14514556880927346, 1.3745893696636038 variance = a * mu_total**b variance[variance == 0] = 50. x[:, 2] = np.random.normal(loc=mu_total, scale=variance**0.5) M = 1200 loh_p = 0.01 noise_prior = 0.03 mu_total = mu[:, 2] p_true = mu[:, 0] / mu[:, 0:2].sum(axis=1) p_true[p_true == 0] = loh_p p_true[p_true == 1] = loh_p p_dispersion = np.random.beta(M * p_true, M * (1 - p_true)) p_noise = np.random.random(size=p_true.shape) p_is_noise = np.random.random(size=p_true.shape) <= noise_prior p_binomial = np.where(p_is_noise, p_noise, p_dispersion) allele_reads = (x[:, 2] * phi).astype(int) x[:, 0] = np.random.binomial(allele_reads, p_binomial) x[:, 1] = allele_reads.astype(float) - x[:, 0] # Reorder x as segment * major/minor/total and record # whether the major allele refers to the first (a) allele # TODO: perhaps easiers to just do minor/major/total major_is_allele_a = x[:, 0] > x[:, 1] for n in range(N): if not major_is_allele_a[n]: x[n, 0], x[n, 1] = x[n, 1], x[n, 0] extra_params['segment_major_is_allele_a'] = major_is_allele_a * 1 def add_beta_noise(mu, var): if np.any(var >= mu * (1. - mu)): raise ValueError('var >= mu * (1. - mu)') nu = mu * (1. - mu) / var - 1. a = mu * nu b = (1 - mu) * nu return np.array([np.random.beta(_a, _b) for _a, _b in zip(a, b)]) if self.frac_beta_noise_stddev is not None: frac = add_beta_noise(genome_mixture.frac, self.frac_beta_noise_stddev**2.) else: frac = genome_mixture.frac h_pred = frac * self.h_total return Experiment(genome_mixture, h, phi, x, h_pred, **extra_params)
[ "numpy.absolute", "numpy.random.seed", "numpy.sum", "numpy.random.negative_binomial", "numpy.argsort", "numpy.random.randint", "numpy.random.normal", "pandas.DataFrame", "scipy.misc.logsumexp", "numpy.random.poisson", "numpy.random.choice", "collections.Counter", "numpy.random.shuffle", "n...
[((39057, 39081), 'numpy.where', 'np.where', (['is_0', 'x_0', 'x_1'], {}), '(is_0, x_0, x_1)\n', (39065, 39081), True, 'import numpy as np\n'), ((39147, 39181), 'numpy.random.beta', 'np.random.beta', (['(M * p)', '(M * (1 - p))'], {}), '(M * p, M * (1 - p))\n', (39161, 39181), True, 'import numpy as np\n'), ((39190, 39220), 'numpy.random.binomial', 'np.random.binomial', (['n', 'p_binom'], {}), '(n, p_binom)\n', (39208, 39220), True, 'import numpy as np\n'), ((39414, 39438), 'numpy.where', 'np.where', (['is_0', 'x_0', 'x_1'], {}), '(is_0, x_0, x_1)\n', (39422, 39438), True, 'import numpy as np\n'), ((2964, 2995), 'numpy.random.randint', 'np.random.randint', (['(MAX_SEED - 1)'], {}), '(MAX_SEED - 1)\n', (2981, 2995), True, 'import numpy as np\n'), ((3005, 3025), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3019, 3025), True, 'import numpy as np\n'), ((3575, 3605), 'numpy.random.seed', 'np.random.seed', (['self.init_seed'], {}), '(self.init_seed)\n', (3589, 3605), True, 'import numpy as np\n'), ((5062, 5074), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5070, 5074), True, 'import numpy as np\n'), ((5113, 5136), 'numpy.array', 'np.array', (['[]'], {'dtype': 'str'}), '([], dtype=str)\n', (5121, 5136), True, 'import numpy as np\n'), ((5166, 5189), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (5174, 5189), True, 'import numpy as np\n'), ((5217, 5240), 'numpy.array', 'np.array', (['[]'], {'dtype': 'int'}), '([], dtype=int)\n', (5225, 5240), True, 'import numpy as np\n'), ((8318, 8349), 'numpy.random.randint', 'np.random.randint', (['(MAX_SEED - 1)'], {}), '(MAX_SEED - 1)\n', (8335, 8349), True, 'import numpy as np\n'), ((8359, 8379), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (8373, 8379), True, 'import numpy as np\n'), ((8686, 8748), 'numpy.random.choice', 'np.random.choice', (["params['event_type']"], {'p': "params['event_prob']"}), "(params['event_type'], p=params['event_prob'])\n", (8702, 8748), True, 'import numpy as np\n'), ((9409, 9440), 'numpy.random.choice', 'np.random.choice', (['[True, False]'], {}), '([True, False])\n', (9425, 9440), True, 'import numpy as np\n'), ((14824, 14845), 'numpy.zeros', 'np.zeros', (['(self.N, 2)'], {}), '((self.N, 2))\n', (14832, 14845), True, 'import numpy as np\n'), ((15198, 15219), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (15217, 15219), False, 'import collections\n'), ((22275, 22294), 'numpy.array', 'np.array', (['fitnesses'], {}), '(fitnesses)\n', (22283, 22294), True, 'import numpy as np\n'), ((24813, 24878), 'numpy.array', 'np.array', (['[genome.segment_copy_number for genome in self.genomes]'], {}), '([genome.segment_copy_number for genome in self.genomes])\n', (24821, 24878), True, 'import numpy as np\n'), ((33080, 33117), 'pandas.DataFrame', 'pd.DataFrame', (['breakpoint_segment_data'], {}), '(breakpoint_segment_data)\n', (33092, 33117), True, 'import pandas as pd\n'), ((34070, 34090), 'numpy.random.randint', 'np.random.randint', (['N'], {}), '(N)\n', (34087, 34090), True, 'import numpy as np\n'), ((34105, 34125), 'numpy.random.randint', 'np.random.randint', (['N'], {}), '(N)\n', (34122, 34125), True, 'import numpy as np\n'), ((34144, 34164), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (34161, 34164), True, 'import numpy as np\n'), ((34182, 34202), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (34199, 34202), True, 'import numpy as np\n'), ((35607, 35621), 'numpy.zeros', 'np.zeros', (['(M,)'], {}), '((M,))\n', (35615, 35621), True, 'import numpy as np\n'), ((36508, 36547), 'numpy.random.shuffle', 'np.random.shuffle', (['detected_breakpoints'], {}), '(detected_breakpoints)\n', (36525, 36547), True, 'import numpy as np\n'), ((39010, 39042), 'numpy.random.random', 'np.random.random', ([], {'size': 'x_0.shape'}), '(size=x_0.shape)\n', (39026, 39042), True, 'import numpy as np\n'), ((39367, 39399), 'numpy.random.random', 'np.random.random', ([], {'size': 'x_0.shape'}), '(size=x_0.shape)\n', (39383, 39399), True, 'import numpy as np\n'), ((40589, 40651), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'self.phi_min', 'high': 'self.phi_max', 'size': 'N'}), '(low=self.phi_min, high=self.phi_max, size=N)\n', (40606, 40651), True, 'import numpy as np\n'), ((3741, 3761), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3755, 3761), True, 'import numpy as np\n'), ((5389, 5451), 'numpy.random.dirichlet', 'np.random.dirichlet', (['([seg_length_concentration] * num_segments)'], {}), '([seg_length_concentration] * num_segments)\n', (5408, 5451), True, 'import numpy as np\n'), ((5952, 5985), 'numpy.concatenate', 'np.concatenate', (['(self.l, lengths)'], {}), '((self.l, lengths))\n', (5966, 5985), True, 'import numpy as np\n'), ((6028, 6083), 'numpy.concatenate', 'np.concatenate', (['(self.segment_chromosome_id, chrom_ids)'], {}), '((self.segment_chromosome_id, chrom_ids))\n', (6042, 6083), True, 'import numpy as np\n'), ((6117, 6161), 'numpy.concatenate', 'np.concatenate', (['(self.segment_start, starts)'], {}), '((self.segment_start, starts))\n', (6131, 6161), True, 'import numpy as np\n'), ((6193, 6233), 'numpy.concatenate', 'np.concatenate', (['(self.segment_end, ends)'], {}), '((self.segment_end, ends))\n', (6207, 6233), True, 'import numpy as np\n'), ((12467, 12515), 'math.ceil', 'math.ceil', (["(params['del_prop_len'] * chrom_length)"], {}), "(params['del_prop_len'] * chrom_length)\n", (12476, 12515), False, 'import math\n'), ((13591, 13639), 'math.ceil', 'math.ceil', (["(params['dup_prop_len'] * chrom_length)"], {}), "(params['dup_prop_len'] * chrom_length)\n", (13600, 13639), False, 'import math\n'), ((23749, 23811), 'numpy.random.choice', 'np.random.choice', (['new_swarm'], {'size': 'self.num_swarm', 'p': 'resample_p'}), '(new_swarm, size=self.num_swarm, p=resample_p)\n', (23765, 23811), True, 'import numpy as np\n'), ((29211, 29238), 'numpy.array', 'np.array', (['ancestral_genomes'], {}), '(ancestral_genomes)\n', (29219, 29238), True, 'import numpy as np\n'), ((29350, 29384), 'numpy.absolute', 'np.absolute', (['(ploidys - self.ploidy)'], {}), '(ploidys - self.ploidy)\n', (29361, 29384), True, 'import numpy as np\n'), ((29708, 29758), 'numpy.absolute', 'np.absolute', (['(loh_proportions - self.proportion_loh)'], {}), '(loh_proportions - self.proportion_loh)\n', (29719, 29758), True, 'import numpy as np\n'), ((45491, 45521), 'numpy.any', 'np.any', (['(var >= mu * (1.0 - mu))'], {}), '(var >= mu * (1.0 - mu))\n', (45497, 45521), True, 'import numpy as np\n'), ((4515, 4577), 'numpy.random.dirichlet', 'np.random.dirichlet', (['([chrom_length_concentration] * num_chroms)'], {}), '([chrom_length_concentration] * num_chroms)\n', (4534, 4577), True, 'import numpy as np\n'), ((14529, 14545), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (14543, 14545), True, 'import numpy as np\n'), ((19707, 19720), 'numpy.sum', 'np.sum', (['(x + 1)'], {}), '(x + 1)\n', (19713, 19720), True, 'import numpy as np\n'), ((19729, 19757), 'scipy.special.gammaln', 'scipy.special.gammaln', (['(x + 1)'], {}), '(x + 1)\n', (19750, 19757), False, 'import scipy\n'), ((19770, 19779), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (19776, 19779), True, 'import numpy as np\n'), ((22330, 22361), 'scipy.misc.logsumexp', 'scipy.misc.logsumexp', (['fitnesses'], {}), '(fitnesses)\n', (22350, 22361), False, 'import scipy\n'), ((23919, 23934), 'numpy.array', 'np.array', (['swarm'], {}), '(swarm)\n', (23927, 23934), True, 'import numpy as np\n'), ((25592, 25608), 'numpy.zeros', 'np.zeros', (['self.M'], {}), '(self.M)\n', (25600, 25608), True, 'import numpy as np\n'), ((30817, 30845), 'numpy.array', 'np.array', (['descendent_genomes'], {}), '(descendent_genomes)\n', (30825, 30845), True, 'import numpy as np\n'), ((31013, 31075), 'numpy.absolute', 'np.absolute', (['(subclonal_proportions - self.proportion_subclonal)'], {}), '(subclonal_proportions - self.proportion_subclonal)\n', (31024, 31075), True, 'import numpy as np\n'), ((35728, 35790), 'numpy.random.dirichlet', 'np.random.dirichlet', (['([self.frac_clone_concentration] * (M - 1))'], {}), '([self.frac_clone_concentration] * (M - 1))\n', (35747, 35790), True, 'import numpy as np\n'), ((35858, 35931), 'numpy.array', 'np.array', (['[self.frac_clone_1, 1.0 - self.frac_normal - self.frac_clone_1]'], {}), '([self.frac_clone_1, 1.0 - self.frac_normal - self.frac_clone_1])\n', (35866, 35931), True, 'import numpy as np\n'), ((23935, 23951), 'numpy.argsort', 'np.argsort', (['prob'], {}), '(prob)\n', (23945, 23951), True, 'import numpy as np\n'), ((36297, 36309), 'numpy.sum', 'np.sum', (['frac'], {}), '(frac)\n', (36303, 36309), True, 'import numpy as np\n'), ((38800, 38833), 'numpy.random.negative_binomial', 'np.random.negative_binomial', (['r', 'a'], {}), '(r, a)\n', (38827, 38833), True, 'import numpy as np\n'), ((41321, 41339), 'numpy.zeros', 'np.zeros', (['mu.shape'], {}), '(mu.shape)\n', (41329, 41339), True, 'import numpy as np\n'), ((45706, 45728), 'numpy.random.beta', 'np.random.beta', (['_a', '_b'], {}), '(_a, _b)\n', (45720, 45728), True, 'import numpy as np\n'), ((36054, 36116), 'numpy.random.dirichlet', 'np.random.dirichlet', (['([self.frac_clone_concentration] * (M - 2))'], {}), '([self.frac_clone_concentration] * (M - 2))\n', (36073, 36116), True, 'import numpy as np\n'), ((42406, 42424), 'numpy.zeros', 'np.zeros', (['mu.shape'], {}), '(mu.shape)\n', (42414, 42424), True, 'import numpy as np\n'), ((42621, 42674), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'mu_total', 'scale': '(variance ** 0.5)'}), '(loc=mu_total, scale=variance ** 0.5)\n', (42637, 42674), True, 'import numpy as np\n'), ((42888, 42942), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'mu_allele', 'scale': '(variance ** 0.5)'}), '(loc=mu_allele, scale=variance ** 0.5)\n', (42904, 42942), True, 'import numpy as np\n'), ((40859, 40879), 'numpy.random.poisson', 'np.random.poisson', (['a'], {}), '(a)\n', (40876, 40879), True, 'import numpy as np\n'), ((43180, 43283), 'numpy.random.choice', 'np.random.choice', (['[True, False]'], {'size': 'mu[:, 2].shape', 'p': '[self.noise_prior, 1.0 - self.noise_prior]'}), '([True, False], size=mu[:, 2].shape, p=[self.noise_prior, \n 1.0 - self.noise_prior])\n', (43196, 43283), True, 'import numpy as np\n'), ((43476, 43579), 'numpy.random.choice', 'np.random.choice', (['[True, False]'], {'size': 'mu[:, 0].shape', 'p': '[self.noise_prior, 1.0 - self.noise_prior]'}), '([True, False], size=mu[:, 0].shape, p=[self.noise_prior, \n 1.0 - self.noise_prior])\n', (43492, 43579), True, 'import numpy as np\n'), ((43655, 43696), 'numpy.random.beta', 'np.random.beta', (['(2)', '(2)'], {'size': 'mu[:, 0].shape'}), '(2, 2, size=mu[:, 0].shape)\n', (43669, 43696), True, 'import numpy as np\n'), ((43998, 44016), 'numpy.zeros', 'np.zeros', (['mu.shape'], {}), '(mu.shape)\n', (44006, 44016), True, 'import numpy as np\n'), ((44213, 44266), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'mu_total', 'scale': '(variance ** 0.5)'}), '(loc=mu_total, scale=variance ** 0.5)\n', (44229, 44266), True, 'import numpy as np\n'), ((44552, 44596), 'numpy.random.beta', 'np.random.beta', (['(M * p_true)', '(M * (1 - p_true))'], {}), '(M * p_true, M * (1 - p_true))\n', (44566, 44596), True, 'import numpy as np\n'), ((44619, 44654), 'numpy.random.random', 'np.random.random', ([], {'size': 'p_true.shape'}), '(size=p_true.shape)\n', (44635, 44654), True, 'import numpy as np\n'), ((44756, 44799), 'numpy.where', 'np.where', (['p_is_noise', 'p_noise', 'p_dispersion'], {}), '(p_is_noise, p_noise, p_dispersion)\n', (44764, 44799), True, 'import numpy as np\n'), ((44903, 44947), 'numpy.random.binomial', 'np.random.binomial', (['allele_reads', 'p_binomial'], {}), '(allele_reads, p_binomial)\n', (44921, 44947), True, 'import numpy as np\n'), ((41105, 41150), 'numpy.random.negative_binomial', 'np.random.negative_binomial', (['self.negbin_r', 'a'], {}), '(self.negbin_r, a)\n', (41132, 41150), True, 'import numpy as np\n'), ((43362, 43419), 'numpy.random.randint', 'np.random.randint', (['noise_range_total'], {'size': 'mu[:, 2].shape'}), '(noise_range_total, size=mu[:, 2].shape)\n', (43379, 43419), True, 'import numpy as np\n'), ((44680, 44715), 'numpy.random.random', 'np.random.random', ([], {'size': 'p_true.shape'}), '(size=p_true.shape)\n', (44696, 44715), True, 'import numpy as np\n')]
import logging import os import numpy as np import pandas as pd import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler from setting import data_path from utils.helper import Scaler class TrafficDataset: def __init__(self, path, train_prop, valid_prop, num_sensors, in_length, out_length, batch_size_per_gpu, num_gpus): logging.info('initialize %s DataWrapper', path) self._path = path self._train_prop = train_prop self._valid_prop = valid_prop self._num_sensors = num_sensors self._in_length = in_length self._out_length = out_length self._batch_size_per_gpu = batch_size_per_gpu self._num_gpus = num_gpus self.build_graph() self.build_data_loader() def build_graph(self): logging.info('initialize graph') # normalize adj_mat self.adj_mats = self.read_adj_mat() for dim in range(self.adj_mats.shape[-1]): values = self.adj_mats[:, :, dim][self.adj_mats[:, :, dim] != np.inf].flatten() self.adj_mats[:, :, dim] = np.exp(-np.square(self.adj_mats[:, :, dim] / (values.std() + 1e-8))) # normalize node_ft self.node_fts = self.read_loc() self.node_fts = (self.node_fts - self.node_fts.mean(axis=0)) / (self.node_fts.std(axis=0) + 1e-8) def build_data_loader(self): logging.info('initialize data loader') train, valid, test = self.read_traffic() self.scaler = Scaler(train.values, missing_value=0) # data for search self.search_train = self.get_data_loader(train, shuffle=True, tag='search train', num_gpus=self._num_gpus) # for weight update self.search_valid = self.get_data_loader(valid, shuffle=True, tag='search valid', num_gpus=self._num_gpus) # for arch update # data for training & evaluation self.train = self.get_data_loader(train, shuffle=True, tag='train', num_gpus=1) self.valid = self.get_data_loader(valid, shuffle=False, tag='valid', num_gpus=1) self.test = self.get_data_loader(test, shuffle=False, tag='test', num_gpus=1) def get_data_loader(self, data, shuffle, tag, num_gpus): logging.info('load %s inputs & labels', tag) num_timestamps = data.shape[0] # fill missing value data_f = self.fill_traffic(data) # transform data distribution data_f = np.expand_dims(self.scaler.transform(data_f.values), axis=-1) # [T, N, 1] # time in day time_ft = (data.index.values - data.index.values.astype('datetime64[D]')) / np.timedelta64(1, 'D') time_ft = np.tile(time_ft, [1, self._num_sensors, 1]).transpose((2, 1, 0)) # [T, N, 1] # day in week # day_ft = np.zeros(shape=(num_timestamps, self._num_sensors, 7)) # [T, N, 7] # day_ft[np.arange(num_timestamps), :, data.index.dayofweek] = 1 # put all input features together in_data = np.concatenate([data_f, time_ft, ], axis=-1) # [T, N, D] out_data = np.expand_dims(data.values, axis=-1) # [T, N, 1] # create inputs & labels inputs, labels = [], [] for i in range(self._in_length): inputs += [in_data[i: num_timestamps + 1 - self._in_length - self._out_length + i]] for i in range(self._out_length): labels += [out_data[self._in_length + i: num_timestamps + 1 - self._out_length + i]] inputs = np.stack(inputs).transpose((1, 3, 2, 0)) labels = np.stack(labels).transpose((1, 3, 2, 0)) # logging info of inputs & labels logging.info('load %s inputs & labels [ok]', tag) logging.info('input shape: %s', inputs.shape) # [num_timestamps, c, n, input_len] logging.info('label shape: %s', labels.shape) # [num_timestamps, c, n, output_len] # create dataset dataset = TensorDataset( torch.from_numpy(inputs).to(dtype=torch.float), torch.from_numpy(labels).to(dtype=torch.float) ) # create sampler sampler = RandomSampler(dataset, replacement=True, num_samples=self._batch_size_per_gpu * num_gpus) if shuffle else SequentialSampler( dataset) # create dataloader data_loader = DataLoader(dataset=dataset, batch_size=self._batch_size_per_gpu * num_gpus, sampler=sampler, num_workers=4, drop_last=False) return data_loader def read_idx(self): with open(os.path.join(data_path, self._path, 'sensor_graph/graph_sensor_ids.txt')) as f: ids = f.read().strip().split(',') idx = {} for i, id in enumerate(ids): idx[id] = i return idx def read_loc(self): idx = self.read_idx() loc = np.loadtxt(os.path.join(data_path, self._path, 'sensor_graph/graph_sensor_locations.csv'), delimiter=',', skiprows=1) loc_ft = np.zeros((self._num_sensors, 2)) for i in range(loc.shape[0]): id = str(int(loc[i, 1])) loc_ft[idx[id], :] = loc[i, 2:4] return loc_ft def read_adj_mat(self): cache_file = os.path.join(data_path, self._path, 'sensor_graph/adjacent_matrix_cached.npz') try: arrays = np.load(cache_file) g = arrays['g'] logging.info('load adj_mat from the cached file [ok]') except: logging.info('load adj_mat from the cached file [fail]') logging.info('load adj_mat from scratch') idx = self.read_idx() graph_csv = pd.read_csv(os.path.join(data_path, self._path, 'sensor_graph/distances.csv'), dtype={'from': 'str', 'to': 'str'}) g = np.zeros((self._num_sensors, self._num_sensors, 2)) g[:] = np.inf for k in range(self._num_sensors): g[k, k] = 0 for row in graph_csv.values: if row[0] in idx and row[1] in idx: g[idx[row[0]], idx[row[1]], 0] = row[2] # distance g[idx[row[0]], idx[row[1]], 1] = 1 # hop g = np.concatenate([g, np.transpose(g, (1, 0, 2))], axis=-1) np.savez_compressed(cache_file, g=g) logging.info('save graph to the cached file [ok]') return g def read_traffic(self): data = pd.read_hdf(os.path.join(data_path, self._path, 'traffic.h5')) num_train = int(data.shape[0] * self._train_prop) num_eval = int(data.shape[0] * self._valid_prop) num_test = data.shape[0] - num_train - num_eval return data[:num_train].copy(), data[num_train: num_train + num_eval].copy(), data[-num_test:].copy() def fill_traffic(self, data): data = data.copy() data[data < 1e-5] = float('nan') data = data.fillna(method='pad') data = data.fillna(method='bfill') return data @property def batch_size_per_gpu(self): return self._batch_size_per_gpu
[ "numpy.stack", "numpy.load", "torch.utils.data.DataLoader", "torch.utils.data.RandomSampler", "numpy.zeros", "numpy.expand_dims", "numpy.transpose", "logging.info", "numpy.savez_compressed", "numpy.timedelta64", "torch.utils.data.SequentialSampler", "numpy.tile", "utils.helper.Scaler", "os...
[((416, 463), 'logging.info', 'logging.info', (['"""initialize %s DataWrapper"""', 'path'], {}), "('initialize %s DataWrapper', path)\n", (428, 463), False, 'import logging\n'), ((865, 897), 'logging.info', 'logging.info', (['"""initialize graph"""'], {}), "('initialize graph')\n", (877, 897), False, 'import logging\n'), ((1439, 1477), 'logging.info', 'logging.info', (['"""initialize data loader"""'], {}), "('initialize data loader')\n", (1451, 1477), False, 'import logging\n'), ((1549, 1586), 'utils.helper.Scaler', 'Scaler', (['train.values'], {'missing_value': '(0)'}), '(train.values, missing_value=0)\n', (1555, 1586), False, 'from utils.helper import Scaler\n'), ((2355, 2399), 'logging.info', 'logging.info', (['"""load %s inputs & labels"""', 'tag'], {}), "('load %s inputs & labels', tag)\n", (2367, 2399), False, 'import logging\n'), ((3111, 3153), 'numpy.concatenate', 'np.concatenate', (['[data_f, time_ft]'], {'axis': '(-1)'}), '([data_f, time_ft], axis=-1)\n', (3125, 3153), True, 'import numpy as np\n'), ((3188, 3224), 'numpy.expand_dims', 'np.expand_dims', (['data.values'], {'axis': '(-1)'}), '(data.values, axis=-1)\n', (3202, 3224), True, 'import numpy as np\n'), ((3747, 3796), 'logging.info', 'logging.info', (['"""load %s inputs & labels [ok]"""', 'tag'], {}), "('load %s inputs & labels [ok]', tag)\n", (3759, 3796), False, 'import logging\n'), ((3805, 3850), 'logging.info', 'logging.info', (['"""input shape: %s"""', 'inputs.shape'], {}), "('input shape: %s', inputs.shape)\n", (3817, 3850), False, 'import logging\n'), ((3896, 3941), 'logging.info', 'logging.info', (['"""label shape: %s"""', 'labels.shape'], {}), "('label shape: %s', labels.shape)\n", (3908, 3941), False, 'import logging\n'), ((4441, 4569), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'dataset', 'batch_size': '(self._batch_size_per_gpu * num_gpus)', 'sampler': 'sampler', 'num_workers': '(4)', 'drop_last': '(False)'}), '(dataset=dataset, batch_size=self._batch_size_per_gpu * num_gpus,\n sampler=sampler, num_workers=4, drop_last=False)\n', (4451, 4569), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler\n'), ((5121, 5153), 'numpy.zeros', 'np.zeros', (['(self._num_sensors, 2)'], {}), '((self._num_sensors, 2))\n', (5129, 5153), True, 'import numpy as np\n'), ((5346, 5424), 'os.path.join', 'os.path.join', (['data_path', 'self._path', '"""sensor_graph/adjacent_matrix_cached.npz"""'], {}), "(data_path, self._path, 'sensor_graph/adjacent_matrix_cached.npz')\n", (5358, 5424), False, 'import os\n'), ((2749, 2771), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""D"""'], {}), "(1, 'D')\n", (2763, 2771), True, 'import numpy as np\n'), ((4212, 4306), 'torch.utils.data.RandomSampler', 'RandomSampler', (['dataset'], {'replacement': '(True)', 'num_samples': '(self._batch_size_per_gpu * num_gpus)'}), '(dataset, replacement=True, num_samples=self.\n _batch_size_per_gpu * num_gpus)\n', (4225, 4306), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler\n'), ((4350, 4376), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['dataset'], {}), '(dataset)\n', (4367, 4376), False, 'from torch.utils.data import TensorDataset, DataLoader, SequentialSampler, RandomSampler\n'), ((4972, 5050), 'os.path.join', 'os.path.join', (['data_path', 'self._path', '"""sensor_graph/graph_sensor_locations.csv"""'], {}), "(data_path, self._path, 'sensor_graph/graph_sensor_locations.csv')\n", (4984, 5050), False, 'import os\n'), ((5459, 5478), 'numpy.load', 'np.load', (['cache_file'], {}), '(cache_file)\n', (5466, 5478), True, 'import numpy as np\n'), ((5519, 5573), 'logging.info', 'logging.info', (['"""load adj_mat from the cached file [ok]"""'], {}), "('load adj_mat from the cached file [ok]')\n", (5531, 5573), False, 'import logging\n'), ((6563, 6612), 'os.path.join', 'os.path.join', (['data_path', 'self._path', '"""traffic.h5"""'], {}), "(data_path, self._path, 'traffic.h5')\n", (6575, 6612), False, 'import os\n'), ((2790, 2833), 'numpy.tile', 'np.tile', (['time_ft', '[1, self._num_sensors, 1]'], {}), '(time_ft, [1, self._num_sensors, 1])\n', (2797, 2833), True, 'import numpy as np\n'), ((3597, 3613), 'numpy.stack', 'np.stack', (['inputs'], {}), '(inputs)\n', (3605, 3613), True, 'import numpy as np\n'), ((3655, 3671), 'numpy.stack', 'np.stack', (['labels'], {}), '(labels)\n', (3663, 3671), True, 'import numpy as np\n'), ((4669, 4741), 'os.path.join', 'os.path.join', (['data_path', 'self._path', '"""sensor_graph/graph_sensor_ids.txt"""'], {}), "(data_path, self._path, 'sensor_graph/graph_sensor_ids.txt')\n", (4681, 4741), False, 'import os\n'), ((5602, 5658), 'logging.info', 'logging.info', (['"""load adj_mat from the cached file [fail]"""'], {}), "('load adj_mat from the cached file [fail]')\n", (5614, 5658), False, 'import logging\n'), ((5671, 5712), 'logging.info', 'logging.info', (['"""load adj_mat from scratch"""'], {}), "('load adj_mat from scratch')\n", (5683, 5712), False, 'import logging\n'), ((5939, 5990), 'numpy.zeros', 'np.zeros', (['(self._num_sensors, self._num_sensors, 2)'], {}), '((self._num_sensors, self._num_sensors, 2))\n', (5947, 5990), True, 'import numpy as np\n'), ((6390, 6426), 'numpy.savez_compressed', 'np.savez_compressed', (['cache_file'], {'g': 'g'}), '(cache_file, g=g)\n', (6409, 6426), True, 'import numpy as np\n'), ((6439, 6489), 'logging.info', 'logging.info', (['"""save graph to the cached file [ok]"""'], {}), "('save graph to the cached file [ok]')\n", (6451, 6489), False, 'import logging\n'), ((4051, 4075), 'torch.from_numpy', 'torch.from_numpy', (['inputs'], {}), '(inputs)\n', (4067, 4075), False, 'import torch\n'), ((4111, 4135), 'torch.from_numpy', 'torch.from_numpy', (['labels'], {}), '(labels)\n', (4127, 4135), False, 'import torch\n'), ((5783, 5848), 'os.path.join', 'os.path.join', (['data_path', 'self._path', '"""sensor_graph/distances.csv"""'], {}), "(data_path, self._path, 'sensor_graph/distances.csv')\n", (5795, 5848), False, 'import os\n'), ((6340, 6366), 'numpy.transpose', 'np.transpose', (['g', '(1, 0, 2)'], {}), '(g, (1, 0, 2))\n', (6352, 6366), True, 'import numpy as np\n')]
import numpy as np from aegis.panconfiguration import pan class Environment: """Modifier of fitness landscape Modifies topology of fitness landscape over time by changing the interpretation of zeros and ones in genomes. """ def __init__(self, gstruc_shape, ENVIRONMENT_CHANGE_RATE): if ENVIRONMENT_CHANGE_RATE == 0: self.dummy = True else: self.dummy = False self.map_ = np.zeros(gstruc_shape, bool) self.ENVIRONMENT_CHANGE_RATE = ENVIRONMENT_CHANGE_RATE def __call__(self, genomes): """Return the genomes reinterpreted in the current environment""" return genomes if self.dummy else np.logical_xor(self.map_, genomes) def evolve(self): """Modify the environmental map""" if self.dummy or pan.skip(self.ENVIRONMENT_CHANGE_RATE): return indices = tuple(pan.rng.integers(self.map_.shape)) self.map_[indices] = ~self.map_[indices]
[ "aegis.panconfiguration.pan.skip", "numpy.logical_xor", "numpy.zeros", "aegis.panconfiguration.pan.rng.integers" ]
[((445, 473), 'numpy.zeros', 'np.zeros', (['gstruc_shape', 'bool'], {}), '(gstruc_shape, bool)\n', (453, 473), True, 'import numpy as np\n'), ((691, 725), 'numpy.logical_xor', 'np.logical_xor', (['self.map_', 'genomes'], {}), '(self.map_, genomes)\n', (705, 725), True, 'import numpy as np\n'), ((817, 855), 'aegis.panconfiguration.pan.skip', 'pan.skip', (['self.ENVIRONMENT_CHANGE_RATE'], {}), '(self.ENVIRONMENT_CHANGE_RATE)\n', (825, 855), False, 'from aegis.panconfiguration import pan\n'), ((901, 934), 'aegis.panconfiguration.pan.rng.integers', 'pan.rng.integers', (['self.map_.shape'], {}), '(self.map_.shape)\n', (917, 934), False, 'from aegis.panconfiguration import pan\n')]
""" cube.py Read a cube file to an array for manipulation. Use the translational symmtry of a supercell to average a cube file into a smaller subsection, eg the unit cell. The number of grid points must be exactly divisible by the folding factors, FX FY FZ. Modified version for faps, provides Cube object. """ import bz2 import gzip from glob import glob from logging import info, debug, error import numpy as np from numpy import array, zeros, matrix from numpy.linalg import norm class Cube(object): """Container for a .cube file. Very specific for folding symmetry.""" def __init__(self, filename=None, fold=None, debug=False): # User defined params self.filename = filename self.fold = fold self.debug = debug # Attributes for internal use self.error = 0.0 self.header_block = [] self.natoms = 0 self.grid = [0, 0, 0] self.rgrid = [0, 0, 0] self.cell = np.eye(3) self.datapoints = np.array([]) # Do we initialise here? if self.filename is not None: self.read_file() def read_file(self, filename=None, fold=None, trim_atoms=True, crop_atoms=False): """Read the gridded cubedata and fold""" if filename is not None: self.filename = filename if fold is not None: self.fold = fold elif self.fold is None: self.fold = (1, 1, 1) fold = self.fold try: cube_temp = compressed_open(self.filename) except IOError: # compressed open will throw an error if the file is not found # it may already be folded, so we can try this cube_temp = compressed_open(self.folded_name) fold = (1, 1, 1) self.fold = fold top_bit = cube_temp.readlines(1024) cube_temp.seek(0) self.natoms = int(top_bit[2].split()[0]) self.grid[0] = abs(int(top_bit[3].split()[0])) self.grid[1] = abs(int(top_bit[4].split()[0])) self.grid[2] = abs(int(top_bit[5].split()[0])) # Abort if we can't divide evenly! if self.grid[0] % fold[0]: raise ValueError("Grid points in x, %i, " "not divisible by fold factor, %i" % (self.grid[0], fold[0])) elif self.grid[1] % fold[1]: raise ValueError("Grid points in y, %i, " "not divisible by fold factor, %i" % (self.grid[1], fold[1])) elif self.grid[2] % fold[2]: raise ValueError("Grid points in z, %i, " "not divisible by fold factor, %i" % (self.grid[2], fold[2])) self.rgrid[0] = self.grid[0]//fold[0] self.rgrid[1] = self.grid[1]//fold[1] self.rgrid[2] = self.grid[2]//fold[2] # read in the top bits -- don't change for now for _lineno in range(self.natoms+6): self.header_block.append(cube_temp.readline()) self.header_block[3:6] = [ "%6i" % (self.rgrid[0]) + self.header_block[3][6:], "%6i" % (self.rgrid[1]) + self.header_block[4][6:], "%6i" % (self.rgrid[2]) + self.header_block[5][6:]] self.cell = np.array( [[float(x) for x in self.header_block[3].split()[1:]], [float(x) for x in self.header_block[4].split()[1:]], [float(x) for x in self.header_block[5].split()[1:]]])*0.529177249 if trim_atoms: self.header_block = extract_atoms(self.header_block, fold) self.natoms = len(self.header_block) - 6 elif crop_atoms: self.header_block = in_cell(self.header_block, self.rgrid, self.cell) self.natoms = len(self.header_block) - 6 # Fromfile might be slower and can't deal with zipped files, # but uses less memory data_start_pos = cube_temp.tell() localdata = zeros([np.prod(fold)] + self.rgrid) stacked_data = True try: cube_data = np.fromstring(cube_temp.read(), sep=' ').reshape(self.grid) except MemoryError: try: cube_temp.seek(data_start_pos) cube_data = np.fromfile(cube_temp, sep=' ').reshape(self.grid) except MemoryError: # Read line by line directly into folded grid, # slowest but with least memory stacked_data = False cube_temp.seek(data_start_pos) localdata = zeros(self.rgrid) xidx, yidx, zidx = 0, 0, 0 for line in cube_temp: for point in line.split(): point = float(point) localdata[xidx % self.rgrid[0], yidx % self.rgrid[1], zidx % self.rgrid[2]] += point zidx += 1 if zidx == self.grid[2]: zidx = 0 yidx += 1 if yidx == self.grid[1]: yidx = 0 xidx += 1 cube_temp.close() if stacked_data: for xidx in range(fold[0]): for yidx in range(fold[1]): for zidx in range(fold[2]): grid_idx = zidx+yidx*fold[2]+xidx*fold[2]*fold[1] localdata[grid_idx] = cube_data[ (xidx*self.grid[0])//fold[0]:((xidx+1)*self.grid[0])//fold[0], (yidx*self.grid[1])//fold[1]:((yidx+1)*self.grid[1])//fold[1], (zidx*self.grid[2])//fold[2]:((zidx+1)*self.grid[2])//fold[2]] del cube_data self.datapoints = np.mean(localdata, axis=0) stdev = np.std(localdata, axis=0) self.error = ((np.sum(stdev)/np.sum(self.datapoints))/ np.flatnonzero(self.datapoints).size) info("Estimated error in cube file: %g" % self.error) else: self.datapoints = localdata/float(fold[0]*fold[1]*fold[2]) def write_cube(self, outname=None): """Write out the data, already folded""" if outname is None: outname = self.folded_name outfile = open(outname, "w") outfile.writelines(self.header_block) for xidx in range(self.rgrid[0]): for yidx in range(self.rgrid[1]): for zidx in range(self.rgrid[2]): outfile.write("%13.5E" % self.datapoints[xidx, yidx, zidx]) if zidx % 6 == 5: outfile.write("\n") outfile.write("\n") outfile.flush() outfile.close() def write_generic(self, data, outname): """Write data to a Gaussian '.cube' file.""" outfile = open(outname, "w") outfile.writelines(self.header_block) for xidx in range(self.rgrid[0]): for yidx in range(self.rgrid[1]): for zidx in range(self.rgrid[2]): outfile.write("%13.5E" % data[xidx, yidx, zidx]) if zidx % 6 == 5: outfile.write("\n") outfile.write("\n") outfile.flush() outfile.close() def maxima(self, sigma=2.0, radius=0.31, cutoff=0.0, write=False): """ Smooth with gaussian blur then use the spacing to determine nearest neighbours to estimate positions of maxima. Return the cartesian positions of maxima in a tuple with their magnitudes from the smoothed data. """ try: from scipy.ndimage.filters import gaussian_filter, maximum_filter from scipy.ndimage.filters import median_filter from scipy.ndimage.morphology import generate_binary_structure from scipy.ndimage.morphology import binary_erosion from scipy.ndimage.morphology import iterate_structure except ImportError: error("Scipy not found, skipping maxima finding") return [] temp_data = self.datapoints normalising_sum = sum(temp_data) spacing = norm(self.cell[0]) debug("Spacing: %f" % spacing) # Median filter removed as testing showed it didn't do much #temp_data = median_filter(temp_data, 4, mode='wrap') # Gaussian filter smoothes out the data # Visual inspection suggests sqrt(2/spacing) sigma = (sigma/spacing)**0.5 info("Smoothing probability with sigma: %f" % sigma) temp_data = gaussian_filter(temp_data, sigma, mode="wrap") # Renormalise to pre-filtered values temp_data *= normalising_sum/sum(temp_data) if write: self.write_cube(self.smoothed_name) # define a connectivity neighborhood neighborhood = generate_binary_structure(np.ndim(temp_data), 2) # expand it to a neighbourhood of ~0.3 A footprint = int(round(radius/spacing, 0)) info("Finding maxima within a radius of %r grid points" % footprint) neighborhood = iterate_structure(neighborhood, footprint) #apply the local maximum filter; all pixel of maximal value #in their neighborhood are set to 1 local_max = maximum_filter(temp_data, footprint=neighborhood, mode='wrap') == temp_data #local_max is a mask that contains the peaks we are #looking for, but also the background. #In order to isolate the peaks we must remove the background from the mask. #we create the mask of the background background = (temp_data == 0) #a little technicality: we must erode the background in order to #successfully subtract it form local_max, otherwise a line will #appear along the background border (artifact of the local maximum filter) eroded_background = binary_erosion(background, structure=neighborhood, border_value=1) #we obtain the final mask, containing only peaks, #by removing the background from the local_max mask detected_peaks = local_max - eroded_background cell = np.array( [[float(x) for x in self.header_block[3].split()[1:]], [float(x) for x in self.header_block[4].split()[1:]], [float(x) for x in self.header_block[5].split()[1:]]])*0.529177249 peaks = np.where(detected_peaks) cartesian_peaks = [] for point in zip(peaks[0], peaks[1], peaks[2]): # Some random peaks with no magnitude were showing up at the PBCs if temp_data[point] > 0.0: cartesian_peaks.append((np.dot(point, cell).tolist(), temp_data[point])) pruned_peaks = [] previous_value = 0.0 maximum_value = max([peak[1] for peak in cartesian_peaks]) # We can cut out the tail end of points where there is a sharp drop for point in sorted(cartesian_peaks, key=lambda k: -k[1]): # All of the points with 0 should be removed already if previous_value/point[1] < 4 and point[1] > cutoff*maximum_value: previous_value = point[1] pruned_peaks.append(point) else: break return pruned_peaks @property def folded_name(self): """File name with _folded inserted for output.""" if ".cube" in self.filename: return self.filename.replace(".cube", "_folded.cube") else: return self.filename + "_folded.cube" @property def smoothed_name(self): """File name with _smooth inserted for output.""" if ".cube" in self.filename: return self.filename.replace(".cube", "_smooth.cube") else: return self.filename + "_smooth.cube" @property def error_name(self): """File name with _folded inserted for output.""" if ".cube" in self.filename: return self.filename.replace(".cube", "_error.cube") else: return self.filename + "_error.cube" def in_cell(header_block, grid, cell): """Cut any atoms that are not in the box from the header block""" rcell = matrix(cell).I newlines = [] for line in header_block[6:]: cpos = [float(x) for x in line.split()[2:]] fpos = array(cpos*rcell)[0] if (fpos[0] < grid[0]) and (fpos[1] < grid[1]) and (fpos[2] < grid[2]): newlines.append(line) header_block[2] = "%6i" % (len(newlines)) + header_block[2][6:] return header_block[:6] + newlines def extract_atoms(header_block, fold): """ Trim the atoms to just the first block. Assumes that subcell are in sequential blocks. """ repeats = fold[0]*fold[1]*fold[2] oldatoms = header_block[6:] newatoms = oldatoms[:len(oldatoms)//repeats] header_block[2] = "%6i" % (len(newatoms)) + header_block[2][6:] return header_block[:6] + newatoms def compressed_open(filename): """Return file objects for either compressed and uncompressed files""" filenames = glob(filename) + glob(filename+".gz") + glob(filename+".bz2") try: filename = filenames[0] except IndexError: raise IOError("File not found: %s" % filename) if filename[-4:] == ".bz2": return bz2.BZ2File(filename) elif filename[-3:] == ".gz": return gzip.open(filename) else: return open(filename, "r")
[ "numpy.sum", "bz2.BZ2File", "numpy.mean", "numpy.linalg.norm", "glob.glob", "numpy.prod", "logging.error", "numpy.std", "numpy.ndim", "numpy.dot", "numpy.matrix", "scipy.ndimage.filters.gaussian_filter", "scipy.ndimage.morphology.binary_erosion", "logging.debug", "scipy.ndimage.filters.m...
[((961, 970), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (967, 970), True, 'import numpy as np\n'), ((997, 1009), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1005, 1009), True, 'import numpy as np\n'), ((8345, 8363), 'numpy.linalg.norm', 'norm', (['self.cell[0]'], {}), '(self.cell[0])\n', (8349, 8363), False, 'from numpy.linalg import norm\n'), ((8372, 8402), 'logging.debug', 'debug', (["('Spacing: %f' % spacing)"], {}), "('Spacing: %f' % spacing)\n", (8377, 8402), False, 'from logging import info, debug, error\n'), ((8680, 8732), 'logging.info', 'info', (["('Smoothing probability with sigma: %f' % sigma)"], {}), "('Smoothing probability with sigma: %f' % sigma)\n", (8684, 8732), False, 'from logging import info, debug, error\n'), ((8753, 8799), 'scipy.ndimage.filters.gaussian_filter', 'gaussian_filter', (['temp_data', 'sigma'], {'mode': '"""wrap"""'}), "(temp_data, sigma, mode='wrap')\n", (8768, 8799), False, 'from scipy.ndimage.filters import gaussian_filter, maximum_filter\n'), ((9189, 9257), 'logging.info', 'info', (["('Finding maxima within a radius of %r grid points' % footprint)"], {}), "('Finding maxima within a radius of %r grid points' % footprint)\n", (9193, 9257), False, 'from logging import info, debug, error\n'), ((9281, 9323), 'scipy.ndimage.morphology.iterate_structure', 'iterate_structure', (['neighborhood', 'footprint'], {}), '(neighborhood, footprint)\n', (9298, 9323), False, 'from scipy.ndimage.morphology import iterate_structure\n'), ((10066, 10132), 'scipy.ndimage.morphology.binary_erosion', 'binary_erosion', (['background'], {'structure': 'neighborhood', 'border_value': '(1)'}), '(background, structure=neighborhood, border_value=1)\n', (10080, 10132), False, 'from scipy.ndimage.morphology import binary_erosion\n'), ((10564, 10588), 'numpy.where', 'np.where', (['detected_peaks'], {}), '(detected_peaks)\n', (10572, 10588), True, 'import numpy as np\n'), ((12407, 12419), 'numpy.matrix', 'matrix', (['cell'], {}), '(cell)\n', (12413, 12419), False, 'from numpy import array, zeros, matrix\n'), ((13327, 13350), 'glob.glob', 'glob', (["(filename + '.bz2')"], {}), "(filename + '.bz2')\n", (13331, 13350), False, 'from glob import glob\n'), ((13515, 13536), 'bz2.BZ2File', 'bz2.BZ2File', (['filename'], {}), '(filename)\n', (13526, 13536), False, 'import bz2\n'), ((5904, 5930), 'numpy.mean', 'np.mean', (['localdata'], {'axis': '(0)'}), '(localdata, axis=0)\n', (5911, 5930), True, 'import numpy as np\n'), ((5951, 5976), 'numpy.std', 'np.std', (['localdata'], {'axis': '(0)'}), '(localdata, axis=0)\n', (5957, 5976), True, 'import numpy as np\n'), ((6120, 6173), 'logging.info', 'info', (["('Estimated error in cube file: %g' % self.error)"], {}), "('Estimated error in cube file: %g' % self.error)\n", (6124, 6173), False, 'from logging import info, debug, error\n'), ((9059, 9077), 'numpy.ndim', 'np.ndim', (['temp_data'], {}), '(temp_data)\n', (9066, 9077), True, 'import numpy as np\n'), ((9457, 9519), 'scipy.ndimage.filters.maximum_filter', 'maximum_filter', (['temp_data'], {'footprint': 'neighborhood', 'mode': '"""wrap"""'}), "(temp_data, footprint=neighborhood, mode='wrap')\n", (9471, 9519), False, 'from scipy.ndimage.filters import gaussian_filter, maximum_filter\n'), ((12541, 12560), 'numpy.array', 'array', (['(cpos * rcell)'], {}), '(cpos * rcell)\n', (12546, 12560), False, 'from numpy import array, zeros, matrix\n'), ((13287, 13301), 'glob.glob', 'glob', (['filename'], {}), '(filename)\n', (13291, 13301), False, 'from glob import glob\n'), ((13304, 13326), 'glob.glob', 'glob', (["(filename + '.gz')"], {}), "(filename + '.gz')\n", (13308, 13326), False, 'from glob import glob\n'), ((13585, 13604), 'gzip.open', 'gzip.open', (['filename'], {}), '(filename)\n', (13594, 13604), False, 'import gzip\n'), ((8177, 8226), 'logging.error', 'error', (['"""Scipy not found, skipping maxima finding"""'], {}), "('Scipy not found, skipping maxima finding')\n", (8182, 8226), False, 'from logging import info, debug, error\n'), ((4019, 4032), 'numpy.prod', 'np.prod', (['fold'], {}), '(fold)\n', (4026, 4032), True, 'import numpy as np\n'), ((6004, 6017), 'numpy.sum', 'np.sum', (['stdev'], {}), '(stdev)\n', (6010, 6017), True, 'import numpy as np\n'), ((6018, 6041), 'numpy.sum', 'np.sum', (['self.datapoints'], {}), '(self.datapoints)\n', (6024, 6041), True, 'import numpy as np\n'), ((6070, 6101), 'numpy.flatnonzero', 'np.flatnonzero', (['self.datapoints'], {}), '(self.datapoints)\n', (6084, 6101), True, 'import numpy as np\n'), ((4599, 4616), 'numpy.zeros', 'zeros', (['self.rgrid'], {}), '(self.rgrid)\n', (4604, 4616), False, 'from numpy import array, zeros, matrix\n'), ((4293, 4324), 'numpy.fromfile', 'np.fromfile', (['cube_temp'], {'sep': '""" """'}), "(cube_temp, sep=' ')\n", (4304, 4324), True, 'import numpy as np\n'), ((10831, 10850), 'numpy.dot', 'np.dot', (['point', 'cell'], {}), '(point, cell)\n', (10837, 10850), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf from tensorflow.keras.models import * from tensorflow.keras.layers import * class SingleAttention(Layer): def __init__(self, d_k, d_v): super(SingleAttention, self).__init__() self.d_k = d_k self.d_v = d_v def build(self, input_shape): self.query = Dense(self.d_k, input_shape=input_shape, kernel_initializer="glorot_uniform", bias_initializer="glorot_uniform") self.key = Dense(self.d_k, input_shape=input_shape, kernel_initializer="glorot_uniform", bias_initializer="glorot_uniform") self.value = Dense(self.d_v, input_shape=input_shape, kernel_initializer="glorot_uniform", bias_initializer="glorot_uniform") def call(self, inputs): q = self.query(inputs[0]) k = self.key(inputs[0]) attn_weights = tf.matmul(q, k, transpose_b=True) attn_weights = tf.map_fn(lambda x: x/np.sqrt(self.d_k), attn_weights) attn_weights = tf.nn.softmax(attn_weights, axis=-1) v = self.value(inputs[2]) attn_out = tf.matmul(attn_weights, v) return attn_out class MultiAttention(Layer): def __init__(self, d_k, d_v, n_heads): super(MultiAttention, self).__init__() self.d_k = d_k self.d_v = d_v self.n_heads = n_heads self.attn_heads = list() def build(self, input_shape): for n in range(self.n_heads): self.attn_heads.append(SingleAttention(self.d_k, self.d_v)) self.linear = Dense(input_shape[0][-1], input_shape=input_shape, kernel_initializer='glorot_uniform', bias_initializer='glorot_uniform') def call(self, inputs): attn = [self.attn_heads[i](inputs) for i in range(self.n_heads)] concat_attn = tf.concat(attn, axis=-1) multi_linear = self.linear(concat_attn) return multi_linear class TransformerEncoder(Layer): def __init__(self, d_k, d_v, n_heads, ff_dim, dropout=0.1, **kwargs): super(TransformerEncoder, self).__init__() self.d_k = d_k self.d_v = d_v self.n_heads = n_heads self.attn_heads = list() self.ff_dim = ff_dim self.dropout_rate = dropout def build(self, input_shape): self.attn_multi = MultiAttention(self.d_k, self.d_v, self.n_heads) self.attn_dropout = Dropout(self.dropout_rate) self.attn_normalize = LayerNormalization(input_shape=input_shape, epsilon=1e-6) self.ff_conv1D_1 = Conv1D(filters=self.ff_dim, kernel_size=1, activation="relu") self.ff_conv1D_2 = Conv1D(filters=input_shape[0][-1], kernel_size=1) self.ff_dropout = Dropout(self.dropout_rate) self.ff_normalize = LayerNormalization(input_shape=input_shape, epsilon=1e-6) def call(self, inputs): attn_layer = self.attn_multi(inputs) attn_layer = self.attn_dropout(attn_layer) attn_layer = self.attn_normalize(inputs[0] + attn_layer) ff_layer = self.ff_conv1D_1(attn_layer) ff_layer = self.ff_conv1D_2(ff_layer) ff_layer = self.ff_dropout(ff_layer) ff_layer = self.ff_normalize(inputs[0] + ff_layer) return ff_layer def get_config(self): config = super().get_config().copy() config.update({'d_k': self.d_k, 'd_v': self.d_v, 'n_heads': self.n_heads, 'ff_dim': self.ff_dim, 'attn_heads': self.attn_heads, 'dropout_rate': self.dropout_rate}) return config
[ "tensorflow.matmul", "tensorflow.nn.softmax", "tensorflow.concat", "numpy.sqrt" ]
[((1005, 1038), 'tensorflow.matmul', 'tf.matmul', (['q', 'k'], {'transpose_b': '(True)'}), '(q, k, transpose_b=True)\n', (1014, 1038), True, 'import tensorflow as tf\n'), ((1132, 1168), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['attn_weights'], {'axis': '(-1)'}), '(attn_weights, axis=-1)\n', (1145, 1168), True, 'import tensorflow as tf\n'), ((1215, 1241), 'tensorflow.matmul', 'tf.matmul', (['attn_weights', 'v'], {}), '(attn_weights, v)\n', (1224, 1241), True, 'import tensorflow as tf\n'), ((1960, 1984), 'tensorflow.concat', 'tf.concat', (['attn'], {'axis': '(-1)'}), '(attn, axis=-1)\n', (1969, 1984), True, 'import tensorflow as tf\n'), ((1080, 1097), 'numpy.sqrt', 'np.sqrt', (['self.d_k'], {}), '(self.d_k)\n', (1087, 1097), True, 'import numpy as np\n')]
from plug_nozzle_angelino import * import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import interpolate from scipy import optimize import numpy as np import gasdynamics as gd from matplotlib import cm import copy #### MOC DESCRIPTION class chr_point(): def __init__(self,gamma,x,y,theta,W,pt_type): self.x = x; self.y = y; self.theta = theta; self.W = W;self.pt_type = pt_type with np.errstate(invalid = 'ignore'): #pt_type = general, jet, contour, or N/A (temp points) self.mu = np.arcsin(np.sqrt((gamma-1)/2*(1/W**2-1))) # print('mu! + ' + str(self.mu)) self.M = 1/np.sin(self.mu) def print_point(self): print('x = ' + str(self.x) + ' y = ' + str(self.y) + ' theta = ' + str(self.theta) + ' W = ' + str(self.W) + ' mu = ' + str(self.mu) + ' M = ' +str(self.M)) def plot_point(self): plt.plot(self.x,self.y,'bx') plt.plot(self.x,self.y*-1,'bx') # will calculate other properties later (p etc.) to vectorize class chr_mesh(): def __init__(self,spike,gamma,altitude,n,downstream_factor=1.1,plot_chr=0,clean_mesh=1): self.spike =copy.copy(spike); self.gamma = gamma; self.altitude =altitude; self.n = n; self.downstream_factor = downstream_factor # percentage down after mesh cross with centre to continue meshing # constants of iteration self.plot_chr = plot_chr self.flip_plug() # flips sign of plug if required self.slope_init = np.arctan(-(self.spike.lip_x-self.spike.x[0])/(self.spike.lip_y-self.spike.y[0])); #print(self.slope_init*180/np.pi) self.tck = interpolate.splrep(self.spike.x,self.spike.y,full_output=0) (self.p_atm,self.T_atm,self.rho_atm) = gd.standard_atmosphere([altitude]) self.gamma = gamma self.PR = self.spike.p_c/(self.p_atm) self.V_l = np.sqrt(2/(self.gamma-1))*self.spike.a_c # Point storage self.chr_array = np.array([]) # array for storing points based on ID # logs characteristics that have not been intercepted self.ID_left_chr = [] self.ID_right_chr = [] self.ID_jet_boundary = [] self.ID_contour_chr = [] #self.ID_next_chr_jet = [] #self.ID_compression_chr = [] self.ID = 0 # ID of next point, not yet computed # COMPUTE EXPANSION FAN POINTS (initial data line) # construction of initial expansion fan self.compute_initial_expansion_fan() # TODO: COMPUTE CHAR. NET DOWN TO NOZZLE BASE (when A.x > spike.x[-1], switch centre point jet boundary) ## after computing initial fan, load all point id's into ordered list showing right and left running characteristics that have not been used to compute a downstream point # TODO: COMPUTE NOZZLE BASE PRESSURE # while (self.chr_array[self.ID_contour_chr[0]].x <= spike.x.max()): # pass # TODO: COMPUTE PLUME DOWNSTREAM OF BASE # TODO: COMPUTE THRUST PRODUCED # for point in self.chr_array: # plt.plot(point.x,point.y,'rX') # print(self.ID_left_chr) # print(self.ID_right_chr) # print(self.ID_jet_boundary) # print(self.ID_contour_chr) # base conditions self.p_b = self.base_pressure() its = 0 self.contour_fan = 1 self.new_fan = 1 self.first_base_intercept = 1 self.centre_line_intercept = 0 self.END_SIM = 0 #while (self.chr_array[self.ID_contour_chr[-1]].x <= spike.x.max()): while self.chr_point_less_zero() and self.contour_converge(): ## TODO: COMPUTE EXPANSION FAN UNTIL POINT IS > spike.length in which case, remove from all tracking lists and do not add to chr_array ## CONTOUR FAN # if (self.contour_fan): # print(its) its += 1 ID_temp = self.ID_right_chr.pop(0) #print(ID_temp) if(self.new_fan): # intersection self.new_fan = 0 if (self.on_nozzle_contour(self.chr_array[ID_temp])): new_point = self.contour_point(self.chr_array[ID_temp],plot_chr=self.plot_chr) self.chr_array = np.append(self.chr_array,new_point) self.ID += 1 # first point ID_temp = self.ID_right_chr.pop(0) new_point = self.general_point(self.chr_array[ID_temp],self.chr_array[self.ID-1],plot_chr=self.plot_chr) self.chr_array = np.append(self.chr_array,new_point) self.ID += 1 else: if (self.first_base_intercept): self.first_base_intercept = 0 first_base_point = self.chr_array[self.ID_contour_chr[-1]] #print(self.spike.p_c/self.p_b) M_b = gd.PR_expansion_mach(self.spike.p_c/self.p_b,self.gamma) #print(M_b) theta_b = gd.prandtl_meyer(M_b,self.gamma) - gd.prandtl_meyer(first_base_point.M,self.gamma) W_b = first_base_point.W first_base_point = chr_point(self.gamma,self.spike.x[-1],self.spike.y[-1],theta_b,W_b,'contour') new_point = self.internal_jet_point(first_base_point,self.chr_array[ID_temp],plot_chr=self.plot_chr) self.chr_array = np.append(self.chr_array,new_point) self.ID += 1 else: new_point = self.internal_jet_point(self.chr_array[self.ID_contour_chr[-1]],self.chr_array[ID_temp],plot_chr=self.plot_chr) self.chr_array = np.append(self.chr_array,new_point) self.ID += 1 elif(ID_temp==-1): # self.ID_next_chr_jet.append(self.ID_left_chr.pop(0)) # plt.plot(self.chr_array[self.ID_jet_boundary[-1]].x,self.chr_array[self.ID_jet_boundary[-1]].y,'gx') new_point = self.general_point(self.chr_array[self.ID_jet_boundary[-1]],self.chr_array[self.ID-1],plot_chr=self.plot_chr) self.chr_array = np.append(self.chr_array,new_point) #self.ID_left_chr.append(self.ID) self.ID += 1 new_point = self.jet_boundary_point(self.chr_array[self.ID_jet_boundary[-1]],self.chr_array[self.ID-1],plot_chr=self.plot_chr) self.chr_array = np.append(self.chr_array,new_point) #plt.plot(new_point.x,new_point.y,'gx') #self.ID_jet_boundary.append(self.ID) self.ID +=1 self.contour_fan = 0 self.add_break_ID() self.new_fan = 1 # if (self.centre_line_intercept): # self.END_SIM = 1 else: if(self.chr_array[ID_temp].pt_type!="same_fam"): temp1 = self.same_fam_point(self.chr_array[self.ID_right_chr[0]],self.chr_array[ID_temp]) temp2 = self.general_point(self.chr_array[ID_temp],self.chr_array[self.ID-1]) if (temp1.x < temp2.x) and (temp1.x>self.chr_array[ID_temp].x) : #self.ID_right_chr.pop(-1); self.ID_left_chr.pop(-1) #self.compression_offset += 1 #self.plot_chr=1 self.ID_left_chr.pop(-1) self.ID_right_chr.pop(-1) #print(temp1.x) if (self.plot_chr): plt.plot(self.chr_array[self.ID_right_chr[0]].x,self.chr_array[self.ID_right_chr[0]].y,'bx',self.chr_array[ID_temp].x,self.chr_array[ID_temp].y,'rx') plt.plot(self.chr_array[self.ID_right_chr[0]].x,self.chr_array[self.ID_right_chr[0]].y*-1,'bx',self.chr_array[ID_temp].x,self.chr_array[ID_temp].y*-1,'rx') plt.plot(temp1.x,temp1.y,'go') plt.plot(temp1.x,temp1.y*-1,'go') #plt.plot([self.chr_array[ID_temp].x, temp1.x],[self.chr_array[ID_temp].y, temp1.y]) self.chr_array = np.append(self.chr_array,temp1) new_point = self.general_point(self.chr_array[-1],self.chr_array[self.ID-1],plot_chr=self.plot_chr) #plt.plot(self.chr_array[self.ID-1].x,self.chr_array[self.ID-1].y,'ro') self.ID += 1 else: new_point = temp2 if (new_point.x<=self.spike.length): pass if (self.plot_chr): plt.plot([self.chr_array[ID_temp].x, temp2.x],[self.chr_array[ID_temp].y*-1, temp2.y*-1],'k',[self.chr_array[self.ID-1].x, temp2.x],[self.chr_array[self.ID-1].y*-1, temp2.y*-1],'k') plt.plot([self.chr_array[ID_temp].x, temp2.x],[self.chr_array[ID_temp].y, temp2.y],'k',[self.chr_array[self.ID-1].x, temp2.x],[self.chr_array[self.ID-1].y, temp2.y],'k') self.ID += 1 self.chr_array = np.append(self.chr_array,new_point) # ## JET BOUNDARY FAN # else: # ID_temp = self.ID_right_chr.pop(0) # if(self.new_fan): # new_point = self.general_point(self.chr_array[ID_temp],self.chr_array[self.ID_contour_chr[-1]]) # self.chr_array = np.append(self.chr_array,new_point) # self.ID += 1 # self.new_fan = 0 # elif (ID_temp == -1): # new_point=self.jet_boundary_point(self.chr_array[self.ID_next_chr_jet[-1]],self.chr_array[ID_temp -1]) # self.chr_array = np.append(self.chr_array, new_point) # self.ID += 1 # self.contour_fan = 1 # self.new_fan = 1 # self.add_break_ID() # else: # new_point = self.general_point(self.chr_array[ID_temp],self.chr_array[ID_temp-1]) # self.chr_array = np.append(self.chr_array,new_point) # self.ID += 1 ## END OF MOC SECTION ##### # function order is important if(clean_mesh): self.clean_data() self.to_arrays() self.calc_flow_properties() #self.compute_thrust() def compute_initial_expansion_fan(self): M_max = gd.PR_expansion_mach(self.PR,self.gamma) # print('M_max: ' + str(M_max)) mach_fan = np.linspace(1.1,M_max,self.n) (T_ratio,p_ratio,rho_ratio,a_ratio) = gd.isentropic_ratios(0,mach_fan,self.gamma) V_fan = a_ratio*self.spike.a_c*mach_fan W_fan = V_fan/self.V_l theta_fan = -gd.prandtl_meyer(mach_fan,self.gamma) + self.slope_init angle_fan = gd.mach_angle(mach_fan) # print(180/np.pi*np.arcsin(np.sqrt((gamma-1)/2*(1/W_fan**2-1)))) # print(W_fan) # print(angle_fan*180/np.pi) x_fan = np.ones(angle_fan.shape)*self.spike.lip_x y_fan = np.ones(angle_fan.shape)*self.spike.lip_y #print(theta_fan*180/np.pi) # print(gd.mach_angle_velocity_ratio(gd.prandtl_meyer(2.3,gamma),0.3,gamma)) initial_point = self.contour_point(chr_point(self.gamma,x_fan[0],y_fan[0],theta_fan[0],W_fan[0],'N/A'),plot_chr=self.plot_chr) self.ID += 1 self.ID_contour_chr.pop(0) self.chr_array = np.append(self.chr_array,initial_point) for point in x_fan[1:-1]: temp_point = chr_point(self.gamma,x_fan[self.ID],y_fan[self.ID],theta_fan[self.ID],W_fan[self.ID],'N/A') new_point = self.general_point(temp_point,self.chr_array[self.ID-1],plot_chr=self.plot_chr) # adding to arrays self.chr_array = np.append(self.chr_array,new_point) self.ID += 1 first_jet = chr_point(self.gamma,x_fan[-1],y_fan[-1],theta_fan[-1],W_fan[-1],'N/A') second_jet = self.jet_boundary_point(first_jet,self.chr_array[self.ID-1],plot_chr=self.plot_chr) self.chr_array = np.append(self.chr_array,second_jet) #self.ID_jet_boundary.append(self.ID) self.ID += 1 self.add_break_ID() def general_point(self,A,B,plot_chr=0): # given points A & B (B.y>A.y) in char mesh, computes 3rd point x_c = (A.x*np.tan(A.theta+A.mu)-A.y+B.y-B.x*np.tan(B.theta-B.mu))/(np.tan(A.theta+A.mu)-np.tan(B.theta-B.mu)) y_c = (x_c-A.x)*np.tan(A.theta+A.mu) + A.y l_A = np.sin(A.mu)*np.sin(A.theta)*np.tan(A.mu)/np.cos(A.theta+A.mu) m_B = np.sin(B.mu)*np.sin(B.theta)*np.tan(B.mu)/np.cos(B.theta-B.mu) if not (self.on_nozzle_contour(A)): theta_c = (-A.W-A.W*(-A.theta*np.tan(A.mu)+l_A*(x_c-A.x)/A.y)+B.W+2*B.W*B.theta*np.tan(B.mu))/(A.W*np.tan(A.mu)+2*B.W*np.tan(B.mu)) else: theta_c = (-A.W-A.W*(-A.theta*np.tan(A.mu)+l_A/A.y*(x_c-A.x))+B.W+B.W*(B.theta*np.tan(B.mu)+m_B/B.y*(x_c-B.x)))/(A.W*np.tan(A.mu)+B.W*np.tan(B.mu)) W_c = A.W + A.W*(np.tan(A.mu*(theta_c-A.theta))+l_A/A.y*(x_c-A.x)) # checking if point is greater than length self.ID_right_chr.append(self.ID) self.ID_left_chr.append(self.ID) if (x_c <= self.spike.length): pass # self.ID_left_chr.append(self.ID) # self.ID_right_chr.append(self.ID) if (plot_chr): plt.plot([A.x,x_c],[A.y,y_c],'k',[B.x,x_c],[B.y,y_c],'k') plt.plot([A.x,x_c],[A.y*-1,y_c*-1],'k',[B.x,x_c],[B.y*-1,y_c*-1],'k') return chr_point(self.gamma,x_c,y_c,theta_c,W_c,'general') def same_fam_point(self,A,B,plot_chr=0): # DEPRECATED, SHOULD BE CHECKED # given points A & B (B.y>A.y) in char mesh, computes 3rd point in the case that the interception is of the same family of points with np.errstate(invalid='ignore',divide='ignore'): x_c = (A.x*np.tan(A.theta+A.mu)-A.y+B.y-B.x*np.tan(B.theta+B.mu))/(np.tan(A.theta+A.mu)-np.tan(B.theta+B.mu)) y_c = (x_c-A.x)*np.tan(A.theta+A.mu) + A.y l_A = np.sin(A.mu)*np.sin(A.theta)*np.tan(A.mu)/np.cos(A.theta+A.mu) m_B = np.sin(B.mu)*np.sin(B.theta)*np.tan(B.mu)/np.cos(B.theta+B.mu) theta_c = (-A.W-A.W*(-A.theta*np.tan(A.mu)+l_A/A.y*(x_c-A.x))+B.W+B.W*(B.theta*np.tan(B.mu)+m_B/B.y*(x_c-B.x)))/(A.W*np.tan(A.mu)+B.W*np.tan(B.mu)) W_c = A.W + A.W*(np.tan(A.mu*(theta_c-A.theta))+l_A/A.y*(x_c-A.x)) # if (self.plot_chr): # plt.plot([A.x,x_c],[A.y,y_c],'r',[B.x,x_c],[B.y,y_c],'r') if (x_c <= self.spike.length): pass if (plot_chr): plt.plot([A.x,x_c],[A.y,y_c],'k',[B.x,x_c],[B.y,y_c],'k') plt.plot([A.x,x_c],[A.y*-1,y_c*-1],'k',[B.x,x_c],[B.y*-1,y_c*-1],'k') return chr_point(self.gamma,x_c,y_c,theta_c,W_c,'same_fam') def contour_point(self,A,plot_chr=0): # Given a chr_point A, computes a chr_point that intersects with the nozzle boundary line = lambda x: np.tan(A.theta+A.mu)*(x-A.x) + A.y # print('line: ' + str((A.theta+A.mu)*180/np.pi)) intercept = lambda x: interpolate.splev(x,self.tck,der=0) - line(x) x_c = optimize.brentq(intercept,self.spike.x[0],self.spike.x[-1]) y_c = line(x_c) theta_c = np.arctan(interpolate.splev(x_c,self.tck,der=1)) l_A = np.sin(A.mu)*np.sin(A.theta)*np.tan(A.mu)/np.cos(A.theta+A.mu) W_c = A.W + A.W*((theta_c-A.theta)*np.tan(A.mu)+l_A/A.y*(x_c-A.x)) #plt.plot(x_c,y_c,'rX') # self.ID_contour_chr.append(self.ID) self.ID_contour_chr.append(self.ID) if (x_c <= self.spike.length): pass if(plot_chr): plt.plot([A.x,x_c],[A.y,y_c],'k') plt.plot([A.x,x_c],[A.y*-1,y_c*-1],'k') return chr_point(self.gamma,x_c,y_c,theta_c,W_c,'contour') def jet_boundary_point(self,A,B,plot_chr=0): # given points A and B (where A is the previous jet boundary point and A.x < B.x) return the next boundary point x_c = (A.x*np.tan(A.theta)-A.y+B.y-B.x*np.tan(B.theta-B.mu))/(np.tan(A.theta)-np.tan(B.theta-B.mu)) y_c = (x_c-A.x)*np.tan(A.theta) + A.y mu_c = A.mu W_c = A.W m_B = np.sin(B.mu)*np.sin(B.theta)*np.tan(B.mu)/np.cos(B.theta-B.mu) theta_c = B.theta + (-(W_c-B.W)/B.W + m_B*(x_c-B.x)/B.y)/np.tan(B.mu) self.ID_jet_boundary.append(self.ID) if (x_c <= self.spike.length): pass # self.ID_jet_boundary.append(self.ID) if (plot_chr): plt.plot([A.x,x_c],[A.y,y_c],'r',[B.x,x_c],[B.y,y_c],'r') plt.plot([A.x,x_c],[A.y*-1,y_c*-1],'r',[B.x,x_c],[B.y*-1,y_c*-1],'r') return chr_point(self.gamma,x_c,y_c,theta_c,W_c,'jet') def internal_jet_point(self,A,B,plot_chr=0): # given points A and B (where A is previous internal jet boundary point) x_c = (A.x*np.tan(A.theta)-A.y+B.y - B.x*np.tan(B.theta + B.mu))/(np.tan(A.theta) - np.tan(B.theta + B.mu)) y_c = (x_c - A.x)*np.tan(A.theta) + A.y if (y_c < 0): W_c = A.W mu_c = A.mu m_B = np.sin(B.mu)*np.sin(B.theta)*np.tan(B.mu)/np.cos(B.theta-B.mu) theta_c = B.theta + (-(W_c -B.W)/B.W + m_B*(x_c - B.x)/B.y)/np.tan(B.mu) else: #centre point self.centre_line_intercept = 1 x_c = A.x - A.y/(np.tan(A.theta)) # + A.theta y_c = 0 theta_c = 0 W_c = A.W # print('W_c = ' + str(W_c)) # x_c = A.x - A.y/(np.tan(A.theta+ A.theta)) # y_c = 0 # theta_c = 0 # #print('W_c = ' + str(W_c)) # l_A = np.sin(A.mu)*np.sin(A.theta)*np.tan(A.mu)/np.cos(A.theta+A.mu) # W_c = A.W + A.W*(np.tan(A.mu*(theta_c-A.theta))+l_A/A.y*(x_c-A.x)) self.ID_contour_chr.append(self.ID) if (x_c <= 2*self.spike.length): pass if (plot_chr): plt.plot([A.x,x_c],[A.y,y_c],'g',[B.x,x_c],[B.y,y_c],'g') plt.plot([A.x,x_c],[A.y*-1,y_c*-1],'g',[B.x,x_c],[B.y*-1,y_c*-1],'g') return chr_point(self.gamma,x_c,y_c,theta_c,W_c,'contour') def add_break_ID(self): #self.ID_left_chr.append(-1) self.ID_right_chr.append(-1) #self.ID_jet_boundary.append(-1) #self.ID_contour_chr.append(-1) def base_pressure(self): ### # UNIVERSITY OF ROME MODEL (2002) ### phi = np.arctan(interpolate.splev(self.spike.x[0], self.tck, der=1)) PHI = (-0.2*phi**4-5.89*phi**2+20179.84)/(phi**4+20179.84) return self.p_atm*(0.05 + 0.967)**PHI def on_nozzle_contour(self,chr_point_obj): line = lambda x: np.tan(chr_point_obj.theta+chr_point_obj.mu)*(x-chr_point_obj.x) + chr_point_obj.y intercept = lambda x: interpolate.splev(x,self.tck,der=0) - line(x) return np.sign(intercept(self.spike.x[0])*intercept(self.spike.x[-1])) <= 0 def chr_point_less_zero(self): if len(self.ID_contour_chr) > 0: return self.chr_array[self.ID_contour_chr[-1]].y < 0 else: return 1 def within_x_bound(self): if len(self.ID_contour_chr) > 0: return self.chr_array[self.ID_contour_chr[-1]].x < spike.x.max()*20 else: return 1 def contour_converge(self): if len(self.ID_contour_chr) > 1: return np.abs(self.chr_array[self.ID_contour_chr[-1]].y) < np.abs(self.chr_array[self.ID_contour_chr[-2]].y) else: return 1 def flip_plug(self): # confirms that the plug y values are negative and flips if required if self.spike.lip_y > 0: self.spike.lip_y = self.spike.lip_y*-1 self.spike.y = self.spike.y*-1 def to_arrays(self): self.x = np.array([]); self.y = np.array([]); self.M = np.array([]); self.mu = np.array([]); self.V = np.array([]); self.theta = np.array([]) for point in self.chr_array: #print(type(point.x)) self.x = np.append(self.x,point.x) self.y = np.append(self.y,point.y) self.M = np.append(self.M,point.M) self.mu = np.append(self.mu,point.mu) self.V = np.append(self.V,point.W*self.V_l) self.theta = np.append(self.theta,point.theta) #takes chr_array obj points to arrays def calc_flow_properties(self): T_ratio,p_ratio,rho_ratio,a_ratio = gd.isentropic_ratios(0,self.M,self.gamma) self.T = self.spike.T_c*T_ratio self.p = self.spike.p_c*p_ratio self.a = self.spike.a_c*a_ratio self.rho = self.spike.rho_c*rho_ratio def clean_data(self): def clean_ID_list(chr_array): contour_ID= [] jet_ID = [] ID = 0 for point in chr_array: if point.pt_type == 'contour': contour_ID.append(ID) elif point.pt_type == 'jet': jet_ID.append(ID) ID += 1 return contour_ID, jet_ID curr_ID = 0 del_ID = [] # creating list of IDs of all points to be deleted from mesh for point in self.chr_array: if point.x < self.chr_array[0].x or point.y > 0 or point.x > self.chr_array[self.ID_contour_chr[-1]].x*self.downstream_factor or np.isnan(point.x): del_ID.append(curr_ID) curr_ID += 1 # deleting IDs from lists self.chr_array = np.delete(self.chr_array,del_ID) #print(len(self.ID_jet_boundary)) self.ID_contour_chr,self.ID_jet_boundary = clean_ID_list(self.chr_array) def compute_thrust(self,approx_method,n): # # constructing spline representation for jet boundary jet_bound_x = np.concatenate((np.array([self.spike.lip_x]),self.x[self.ID_jet_boundary])) jet_bound_y = np.concatenate((np.array([self.spike.lip_y]),self.y[self.ID_jet_boundary])) # filter for uniques jet_bound_x, indices = np.unique(jet_bound_x, return_index=True) jet_bound_y = jet_bound_y[indices] try: #constructing jet boundary spline tck_jet_bound = interpolate.splrep(jet_bound_x,jet_bound_y) except TypeError: print(self.altitude) print(str(jet_bound_x)) print(str(jet_bound_y)) # constructing plane on which to evaluate expanded gas properties x_plane = np.ones(n,)*self.x[self.ID_contour_chr[-1]]; y_points = np.linspace(0,interpolate.splev(self.x[self.ID_contour_chr[-1]],tck_jet_bound),n); #plt.plot(x_plane,y_points,'ro') # constructing rbf functions for interpolation of properties V_grid = interpolate.griddata((self.x,self.y),self.V,(x_plane,y_points),method=approx_method) # nearest and cubic may also work T_grid = interpolate.griddata((self.x,self.y),self.T,(x_plane,y_points),method=approx_method) theta_grid = interpolate.griddata((self.x,self.y),self.theta,(x_plane,y_points),method=approx_method) rho_grid = interpolate.griddata((self.x,self.y),self.rho,(x_plane,y_points),method=approx_method) P_grid = interpolate.griddata((self.x,self.y),self.p,(x_plane,y_points),method=approx_method) #computing thrust Ve_grid = V_grid*np.cos(theta_grid) # V*cos(theta)*r *dr # fig1, (ax1) = plt.subplots(1,1) # vel_plot = ax1.scatter(y_points,Ve_grid) # vel_label = 'Ve ' + str(self.altitude) # print(vel_label) # plt.plot(y_points,Ve_grid,label = vel_label) tck_contour = interpolate.splrep(self.spike.x,self.spike.y) on_nozzle_idx = self.x[self.ID_contour_chr] < self.spike.x.max() on_contour_x = self.x[self.ID_contour_chr][on_nozzle_idx] on_contour_y = self.y[self.ID_contour_chr][on_nozzle_idx] # print('thurst!') # plt.plot(on_contour_x,on_contour_y,'x') # plt.show() contour_der = interpolate.splev(on_contour_x,tck_contour,der=1) contour_angle = np.arctan(contour_der) P_contour = interpolate.griddata((self.x,self.y),self.p,(on_contour_x,on_contour_y),method=approx_method) - self.p_atm P_2D = P_contour*np.sqrt(contour_der**2+1)*2*np.pi*np.sin(contour_angle)*2*np.pi*on_contour_y # p_label = 'P ' + str(self.altitude) + ', patm:' + str(self.p_atm) # plt.plot(y_points,np.cos(theta_grid),label =p_label) # plt.legend() #plt.show() A = y_points*2*np.pi thrust_grid = rho_grid*Ve_grid**2*A ## CHECK THIS!!!!!!! thrust_momentum = np.trapz(thrust_grid,y_points) # check with emerson #thrust_pressure = np.trapz((P_2D),on_contour_x) # check with emerson return thrust_momentum #+ thrust_pressure #FUN PLOTS # print(thrust_momentum) # print(thrust_pressure) # fig1, (ax1,ax2) = plt.subplots(1,2) # vel_plot = ax1.scatter(self.x,self.y,c=(self.V*np.cos(self.theta)),cmap=cm.coolwarm) # ax1.plot(x_plane[-1],y_points[-1],'x') # vel_interp = ax2.plot(y_points,Ve_grid) # ax1.axis('equal') # ax2.set_xlim(y_points.min(),y_points.max()) # plt.colorbar(vel_plot,ax = ax1) # #### NOZZLE INITIAL CONDITIONS # r_e = 0.067/2 #0.034 # likely too large # expansion_ratio = 6.64 #8.1273 # A_t = r_e**2*np.pi/expansion_ratio # max expansion (r_b = 0, r_e**2 >= A_t*expansion_ratio/np.pi) # gamma = 1.2381 #np.mean([1.2534,1.2852]) # T_c = 2833.63 # p_c = 34.474*10**5 # rho_c = 3.3826 # R = (1-1/gamma)*1.8292*1000#1.8292 1.6196 # a_c = np.sqrt(gamma*(1-1/gamma)*200.07*T_c) # n = 1000 # ### DESIGN OF SPIKE # spike = plug_nozzle(expansion_ratio,A_t,r_e,gamma,T_c,p_c,a_c,rho_c,n,truncate_ratio = 1.0) # spike.y = spike.y*-1 # spike.lip_y = spike.lip_y*-1 # line = lambda x: np.tan(-np.pi/3)*(x-spike.lip_x) + spike.lip_y # ## METHOD FOR CALCULATING FUNCTION INTERCEPTS # tck = interpolate.splrep(spike.x,spike.y,full_output=0) # MOC_mesh = chr_mesh(spike,gamma,0,50,downstream_factor=1.2,plot_chr=1) # #plt.plot(MOC_mesh.x,MOC_mesh.y,'ro') # #plt.plot(MOC_mesh.x[MOC_mesh.ID_jet_boundary],MOC_mesh.y[MOC_mesh.ID_jet_boundary],'go-') # MOC_mesh.compute_thrust('nearest',10) # #plt.plot(MOC_mesh.x[MOC_mesh.ID_contour_chr],MOC_mesh.y[MOC_mesh.ID_contour_chr],'bo-') # #plt.plot(MOC_mesh.x[MOC_mesh.ID_contour_chr[-1]],0,'bo') # #plt.plot(spike.x,interpolate.splev(spike.x,tck,der=0),spike.lip_x,spike.lip_y,'X') # #plt.axis('equal') # # fig = plt.figure() # # ax = fig.add_subplot(111) # # ax.scatter(MOC_mesh.x,MOC_mesh.y,c=MOC_mesh.M, cmap = cm.coolwarm) # # #plt.plot(MOC_mesh.x,MOC_mesh.y,'r.') # # # cax = ax.imshow(MOC_mesh,interpolation='nearest',cmap=cm.coolwarm) # # # cbar = fig.colorbar(cax) # # plt.colorbar(ax=ax) # #plt.axis('equal') # plt.show() # M = optimize.brentq(lambda M: gd.expansion_ratio_zero(1,M,gamma,expansion_ratio),1,10)
[ "gasdynamics.prandtl_meyer", "numpy.abs", "numpy.ones", "numpy.isnan", "numpy.sin", "numpy.unique", "gasdynamics.mach_angle", "gasdynamics.PR_expansion_mach", "numpy.append", "numpy.tan", "numpy.linspace", "scipy.interpolate.splrep", "numpy.trapz", "scipy.interpolate.griddata", "gasdynam...
[((916, 946), 'matplotlib.pyplot.plot', 'plt.plot', (['self.x', 'self.y', '"""bx"""'], {}), "(self.x, self.y, 'bx')\n", (924, 946), True, 'import matplotlib.pyplot as plt\n'), ((953, 988), 'matplotlib.pyplot.plot', 'plt.plot', (['self.x', '(self.y * -1)', '"""bx"""'], {}), "(self.x, self.y * -1, 'bx')\n", (961, 988), True, 'import matplotlib.pyplot as plt\n'), ((1188, 1204), 'copy.copy', 'copy.copy', (['spike'], {}), '(spike)\n', (1197, 1204), False, 'import copy\n'), ((1536, 1628), 'numpy.arctan', 'np.arctan', (['(-(self.spike.lip_x - self.spike.x[0]) / (self.spike.lip_y - self.spike.y[0]))'], {}), '(-(self.spike.lip_x - self.spike.x[0]) / (self.spike.lip_y - self.\n spike.y[0]))\n', (1545, 1628), True, 'import numpy as np\n'), ((1682, 1743), 'scipy.interpolate.splrep', 'interpolate.splrep', (['self.spike.x', 'self.spike.y'], {'full_output': '(0)'}), '(self.spike.x, self.spike.y, full_output=0)\n', (1700, 1743), False, 'from scipy import interpolate\n'), ((1789, 1823), 'gasdynamics.standard_atmosphere', 'gd.standard_atmosphere', (['[altitude]'], {}), '([altitude])\n', (1811, 1823), True, 'import gasdynamics as gd\n'), ((2008, 2020), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2016, 2020), True, 'import numpy as np\n'), ((10784, 10825), 'gasdynamics.PR_expansion_mach', 'gd.PR_expansion_mach', (['self.PR', 'self.gamma'], {}), '(self.PR, self.gamma)\n', (10804, 10825), True, 'import gasdynamics as gd\n'), ((10884, 10915), 'numpy.linspace', 'np.linspace', (['(1.1)', 'M_max', 'self.n'], {}), '(1.1, M_max, self.n)\n', (10895, 10915), True, 'import numpy as np\n'), ((10961, 11006), 'gasdynamics.isentropic_ratios', 'gd.isentropic_ratios', (['(0)', 'mach_fan', 'self.gamma'], {}), '(0, mach_fan, self.gamma)\n', (10981, 11006), True, 'import gasdynamics as gd\n'), ((11185, 11208), 'gasdynamics.mach_angle', 'gd.mach_angle', (['mach_fan'], {}), '(mach_fan)\n', (11198, 11208), True, 'import gasdynamics as gd\n'), ((11809, 11849), 'numpy.append', 'np.append', (['self.chr_array', 'initial_point'], {}), '(self.chr_array, initial_point)\n', (11818, 11849), True, 'import numpy as np\n'), ((12449, 12486), 'numpy.append', 'np.append', (['self.chr_array', 'second_jet'], {}), '(self.chr_array, second_jet)\n', (12458, 12486), True, 'import numpy as np\n'), ((15649, 15710), 'scipy.optimize.brentq', 'optimize.brentq', (['intercept', 'self.spike.x[0]', 'self.spike.x[-1]'], {}), '(intercept, self.spike.x[0], self.spike.x[-1])\n', (15664, 15710), False, 'from scipy import optimize\n'), ((20384, 20396), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (20392, 20396), True, 'import numpy as np\n'), ((20407, 20419), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (20415, 20419), True, 'import numpy as np\n'), ((20430, 20442), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (20438, 20442), True, 'import numpy as np\n'), ((20454, 20466), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (20462, 20466), True, 'import numpy as np\n'), ((20477, 20489), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (20485, 20489), True, 'import numpy as np\n'), ((20504, 20516), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (20512, 20516), True, 'import numpy as np\n'), ((21021, 21064), 'gasdynamics.isentropic_ratios', 'gd.isentropic_ratios', (['(0)', 'self.M', 'self.gamma'], {}), '(0, self.M, self.gamma)\n', (21041, 21064), True, 'import gasdynamics as gd\n'), ((22075, 22108), 'numpy.delete', 'np.delete', (['self.chr_array', 'del_ID'], {}), '(self.chr_array, del_ID)\n', (22084, 22108), True, 'import numpy as np\n'), ((22624, 22665), 'numpy.unique', 'np.unique', (['jet_bound_x'], {'return_index': '(True)'}), '(jet_bound_x, return_index=True)\n', (22633, 22665), True, 'import numpy as np\n'), ((23342, 23436), 'scipy.interpolate.griddata', 'interpolate.griddata', (['(self.x, self.y)', 'self.V', '(x_plane, y_points)'], {'method': 'approx_method'}), '((self.x, self.y), self.V, (x_plane, y_points), method=\n approx_method)\n', (23362, 23436), False, 'from scipy import interpolate\n'), ((23479, 23573), 'scipy.interpolate.griddata', 'interpolate.griddata', (['(self.x, self.y)', 'self.T', '(x_plane, y_points)'], {'method': 'approx_method'}), '((self.x, self.y), self.T, (x_plane, y_points), method=\n approx_method)\n', (23499, 23573), False, 'from scipy import interpolate\n'), ((23585, 23682), 'scipy.interpolate.griddata', 'interpolate.griddata', (['(self.x, self.y)', 'self.theta', '(x_plane, y_points)'], {'method': 'approx_method'}), '((self.x, self.y), self.theta, (x_plane, y_points),\n method=approx_method)\n', (23605, 23682), False, 'from scipy import interpolate\n'), ((23693, 23788), 'scipy.interpolate.griddata', 'interpolate.griddata', (['(self.x, self.y)', 'self.rho', '(x_plane, y_points)'], {'method': 'approx_method'}), '((self.x, self.y), self.rho, (x_plane, y_points),\n method=approx_method)\n', (23713, 23788), False, 'from scipy import interpolate\n'), ((23797, 23891), 'scipy.interpolate.griddata', 'interpolate.griddata', (['(self.x, self.y)', 'self.p', '(x_plane, y_points)'], {'method': 'approx_method'}), '((self.x, self.y), self.p, (x_plane, y_points), method=\n approx_method)\n', (23817, 23891), False, 'from scipy import interpolate\n'), ((24221, 24267), 'scipy.interpolate.splrep', 'interpolate.splrep', (['self.spike.x', 'self.spike.y'], {}), '(self.spike.x, self.spike.y)\n', (24239, 24267), False, 'from scipy import interpolate\n'), ((24605, 24656), 'scipy.interpolate.splev', 'interpolate.splev', (['on_contour_x', 'tck_contour'], {'der': '(1)'}), '(on_contour_x, tck_contour, der=1)\n', (24622, 24656), False, 'from scipy import interpolate\n'), ((24680, 24702), 'numpy.arctan', 'np.arctan', (['contour_der'], {}), '(contour_der)\n', (24689, 24702), True, 'import numpy as np\n'), ((25245, 25276), 'numpy.trapz', 'np.trapz', (['thrust_grid', 'y_points'], {}), '(thrust_grid, y_points)\n', (25253, 25276), True, 'import numpy as np\n'), ((439, 468), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (450, 468), True, 'import numpy as np\n'), ((1916, 1945), 'numpy.sqrt', 'np.sqrt', (['(2 / (self.gamma - 1))'], {}), '(2 / (self.gamma - 1))\n', (1923, 1945), True, 'import numpy as np\n'), ((11362, 11386), 'numpy.ones', 'np.ones', (['angle_fan.shape'], {}), '(angle_fan.shape)\n', (11369, 11386), True, 'import numpy as np\n'), ((11421, 11445), 'numpy.ones', 'np.ones', (['angle_fan.shape'], {}), '(angle_fan.shape)\n', (11428, 11445), True, 'import numpy as np\n'), ((12165, 12201), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (12174, 12201), True, 'import numpy as np\n'), ((12924, 12946), 'numpy.cos', 'np.cos', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (12930, 12946), True, 'import numpy as np\n'), ((13001, 13023), 'numpy.cos', 'np.cos', (['(B.theta - B.mu)'], {}), '(B.theta - B.mu)\n', (13007, 13023), True, 'import numpy as np\n'), ((13827, 13893), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y, y_c]', '"""k"""', '[B.x, x_c]', '[B.y, y_c]', '"""k"""'], {}), "([A.x, x_c], [A.y, y_c], 'k', [B.x, x_c], [B.y, y_c], 'k')\n", (13835, 13893), True, 'import matplotlib.pyplot as plt\n'), ((13897, 13987), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y * -1, y_c * -1]', '"""k"""', '[B.x, x_c]', '[B.y * -1, y_c * -1]', '"""k"""'], {}), "([A.x, x_c], [A.y * -1, y_c * -1], 'k', [B.x, x_c], [B.y * -1, y_c *\n -1], 'k')\n", (13905, 13987), True, 'import matplotlib.pyplot as plt\n'), ((14278, 14324), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""', 'divide': '"""ignore"""'}), "(invalid='ignore', divide='ignore')\n", (14289, 14324), True, 'import numpy as np\n'), ((15096, 15162), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y, y_c]', '"""k"""', '[B.x, x_c]', '[B.y, y_c]', '"""k"""'], {}), "([A.x, x_c], [A.y, y_c], 'k', [B.x, x_c], [B.y, y_c], 'k')\n", (15104, 15162), True, 'import matplotlib.pyplot as plt\n'), ((15166, 15256), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y * -1, y_c * -1]', '"""k"""', '[B.x, x_c]', '[B.y * -1, y_c * -1]', '"""k"""'], {}), "([A.x, x_c], [A.y * -1, y_c * -1], 'k', [B.x, x_c], [B.y * -1, y_c *\n -1], 'k')\n", (15174, 15256), True, 'import matplotlib.pyplot as plt\n'), ((15763, 15802), 'scipy.interpolate.splev', 'interpolate.splev', (['x_c', 'self.tck'], {'der': '(1)'}), '(x_c, self.tck, der=1)\n', (15780, 15802), False, 'from scipy import interpolate\n'), ((15859, 15881), 'numpy.cos', 'np.cos', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (15865, 15881), True, 'import numpy as np\n'), ((16175, 16212), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y, y_c]', '"""k"""'], {}), "([A.x, x_c], [A.y, y_c], 'k')\n", (16183, 16212), True, 'import matplotlib.pyplot as plt\n'), ((16221, 16268), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y * -1, y_c * -1]', '"""k"""'], {}), "([A.x, x_c], [A.y * -1, y_c * -1], 'k')\n", (16229, 16268), True, 'import matplotlib.pyplot as plt\n'), ((16748, 16770), 'numpy.cos', 'np.cos', (['(B.theta - B.mu)'], {}), '(B.theta - B.mu)\n', (16754, 16770), True, 'import numpy as np\n'), ((17048, 17114), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y, y_c]', '"""r"""', '[B.x, x_c]', '[B.y, y_c]', '"""r"""'], {}), "([A.x, x_c], [A.y, y_c], 'r', [B.x, x_c], [B.y, y_c], 'r')\n", (17056, 17114), True, 'import matplotlib.pyplot as plt\n'), ((17118, 17208), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y * -1, y_c * -1]', '"""r"""', '[B.x, x_c]', '[B.y * -1, y_c * -1]', '"""r"""'], {}), "([A.x, x_c], [A.y * -1, y_c * -1], 'r', [B.x, x_c], [B.y * -1, y_c *\n -1], 'r')\n", (17126, 17208), True, 'import matplotlib.pyplot as plt\n'), ((18499, 18565), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y, y_c]', '"""g"""', '[B.x, x_c]', '[B.y, y_c]', '"""g"""'], {}), "([A.x, x_c], [A.y, y_c], 'g', [B.x, x_c], [B.y, y_c], 'g')\n", (18507, 18565), True, 'import matplotlib.pyplot as plt\n'), ((18569, 18659), 'matplotlib.pyplot.plot', 'plt.plot', (['[A.x, x_c]', '[A.y * -1, y_c * -1]', '"""g"""', '[B.x, x_c]', '[B.y * -1, y_c * -1]', '"""g"""'], {}), "([A.x, x_c], [A.y * -1, y_c * -1], 'g', [B.x, x_c], [B.y * -1, y_c *\n -1], 'g')\n", (18577, 18659), True, 'import matplotlib.pyplot as plt\n'), ((19033, 19084), 'scipy.interpolate.splev', 'interpolate.splev', (['self.spike.x[0]', 'self.tck'], {'der': '(1)'}), '(self.spike.x[0], self.tck, der=1)\n', (19050, 19084), False, 'from scipy import interpolate\n'), ((20609, 20635), 'numpy.append', 'np.append', (['self.x', 'point.x'], {}), '(self.x, point.x)\n', (20618, 20635), True, 'import numpy as np\n'), ((20656, 20682), 'numpy.append', 'np.append', (['self.y', 'point.y'], {}), '(self.y, point.y)\n', (20665, 20682), True, 'import numpy as np\n'), ((20703, 20729), 'numpy.append', 'np.append', (['self.M', 'point.M'], {}), '(self.M, point.M)\n', (20712, 20729), True, 'import numpy as np\n'), ((20751, 20779), 'numpy.append', 'np.append', (['self.mu', 'point.mu'], {}), '(self.mu, point.mu)\n', (20760, 20779), True, 'import numpy as np\n'), ((20800, 20837), 'numpy.append', 'np.append', (['self.V', '(point.W * self.V_l)'], {}), '(self.V, point.W * self.V_l)\n', (20809, 20837), True, 'import numpy as np\n'), ((20860, 20894), 'numpy.append', 'np.append', (['self.theta', 'point.theta'], {}), '(self.theta, point.theta)\n', (20869, 20894), True, 'import numpy as np\n'), ((22793, 22837), 'scipy.interpolate.splrep', 'interpolate.splrep', (['jet_bound_x', 'jet_bound_y'], {}), '(jet_bound_x, jet_bound_y)\n', (22811, 22837), False, 'from scipy import interpolate\n'), ((23068, 23078), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (23075, 23078), True, 'import numpy as np\n'), ((23146, 23211), 'scipy.interpolate.splev', 'interpolate.splev', (['self.x[self.ID_contour_chr[-1]]', 'tck_jet_bound'], {}), '(self.x[self.ID_contour_chr[-1]], tck_jet_bound)\n', (23163, 23211), False, 'from scipy import interpolate\n'), ((23933, 23951), 'numpy.cos', 'np.cos', (['theta_grid'], {}), '(theta_grid)\n', (23939, 23951), True, 'import numpy as np\n'), ((24733, 24835), 'scipy.interpolate.griddata', 'interpolate.griddata', (['(self.x, self.y)', 'self.p', '(on_contour_x, on_contour_y)'], {'method': 'approx_method'}), '((self.x, self.y), self.p, (on_contour_x, on_contour_y),\n method=approx_method)\n', (24753, 24835), False, 'from scipy import interpolate\n'), ((571, 614), 'numpy.sqrt', 'np.sqrt', (['((gamma - 1) / 2 * (1 / W ** 2 - 1))'], {}), '((gamma - 1) / 2 * (1 / W ** 2 - 1))\n', (578, 614), True, 'import numpy as np\n'), ((672, 687), 'numpy.sin', 'np.sin', (['self.mu'], {}), '(self.mu)\n', (678, 687), True, 'import numpy as np\n'), ((11108, 11146), 'gasdynamics.prandtl_meyer', 'gd.prandtl_meyer', (['mach_fan', 'self.gamma'], {}), '(mach_fan, self.gamma)\n', (11124, 11146), True, 'import gasdynamics as gd\n'), ((12774, 12796), 'numpy.tan', 'np.tan', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (12780, 12796), True, 'import numpy as np\n'), ((12795, 12817), 'numpy.tan', 'np.tan', (['(B.theta - B.mu)'], {}), '(B.theta - B.mu)\n', (12801, 12817), True, 'import numpy as np\n'), ((12841, 12863), 'numpy.tan', 'np.tan', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (12847, 12863), True, 'import numpy as np\n'), ((12911, 12923), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (12917, 12923), True, 'import numpy as np\n'), ((12988, 13000), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (12994, 13000), True, 'import numpy as np\n'), ((14562, 14584), 'numpy.cos', 'np.cos', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (14568, 14584), True, 'import numpy as np\n'), ((14643, 14665), 'numpy.cos', 'np.cos', (['(B.theta + B.mu)'], {}), '(B.theta + B.mu)\n', (14649, 14665), True, 'import numpy as np\n'), ((15589, 15626), 'scipy.interpolate.splev', 'interpolate.splev', (['x', 'self.tck'], {'der': '(0)'}), '(x, self.tck, der=0)\n', (15606, 15626), False, 'from scipy import interpolate\n'), ((15846, 15858), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (15852, 15858), True, 'import numpy as np\n'), ((16570, 16585), 'numpy.tan', 'np.tan', (['A.theta'], {}), '(A.theta)\n', (16576, 16585), True, 'import numpy as np\n'), ((16586, 16608), 'numpy.tan', 'np.tan', (['(B.theta - B.mu)'], {}), '(B.theta - B.mu)\n', (16592, 16608), True, 'import numpy as np\n'), ((16632, 16647), 'numpy.tan', 'np.tan', (['A.theta'], {}), '(A.theta)\n', (16638, 16647), True, 'import numpy as np\n'), ((16735, 16747), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (16741, 16747), True, 'import numpy as np\n'), ((16834, 16846), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (16840, 16846), True, 'import numpy as np\n'), ((17456, 17471), 'numpy.tan', 'np.tan', (['A.theta'], {}), '(A.theta)\n', (17462, 17471), True, 'import numpy as np\n'), ((17474, 17496), 'numpy.tan', 'np.tan', (['(B.theta + B.mu)'], {}), '(B.theta + B.mu)\n', (17480, 17496), True, 'import numpy as np\n'), ((17524, 17539), 'numpy.tan', 'np.tan', (['A.theta'], {}), '(A.theta)\n', (17530, 17539), True, 'import numpy as np\n'), ((17675, 17697), 'numpy.cos', 'np.cos', (['(B.theta - B.mu)'], {}), '(B.theta - B.mu)\n', (17681, 17697), True, 'import numpy as np\n'), ((19386, 19423), 'scipy.interpolate.splev', 'interpolate.splev', (['x', 'self.tck'], {'der': '(0)'}), '(x, self.tck, der=0)\n', (19403, 19423), False, 'from scipy import interpolate\n'), ((19973, 20022), 'numpy.abs', 'np.abs', (['self.chr_array[self.ID_contour_chr[-1]].y'], {}), '(self.chr_array[self.ID_contour_chr[-1]].y)\n', (19979, 20022), True, 'import numpy as np\n'), ((20025, 20074), 'numpy.abs', 'np.abs', (['self.chr_array[self.ID_contour_chr[-2]].y'], {}), '(self.chr_array[self.ID_contour_chr[-2]].y)\n', (20031, 20074), True, 'import numpy as np\n'), ((21931, 21948), 'numpy.isnan', 'np.isnan', (['point.x'], {}), '(point.x)\n', (21939, 21948), True, 'import numpy as np\n'), ((22397, 22425), 'numpy.array', 'np.array', (['[self.spike.lip_x]'], {}), '([self.spike.lip_x])\n', (22405, 22425), True, 'import numpy as np\n'), ((22495, 22523), 'numpy.array', 'np.array', (['[self.spike.lip_y]'], {}), '([self.spike.lip_y])\n', (22503, 22523), True, 'import numpy as np\n'), ((4319, 4355), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (4328, 4355), True, 'import numpy as np\n'), ((4639, 4675), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (4648, 4675), True, 'import numpy as np\n'), ((6319, 6355), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (6328, 6355), True, 'import numpy as np\n'), ((6612, 6648), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (6621, 6648), True, 'import numpy as np\n'), ((12751, 12773), 'numpy.tan', 'np.tan', (['(B.theta - B.mu)'], {}), '(B.theta - B.mu)\n', (12757, 12773), True, 'import numpy as np\n'), ((12882, 12894), 'numpy.sin', 'np.sin', (['A.mu'], {}), '(A.mu)\n', (12888, 12894), True, 'import numpy as np\n'), ((12895, 12910), 'numpy.sin', 'np.sin', (['A.theta'], {}), '(A.theta)\n', (12901, 12910), True, 'import numpy as np\n'), ((12959, 12971), 'numpy.sin', 'np.sin', (['B.mu'], {}), '(B.mu)\n', (12965, 12971), True, 'import numpy as np\n'), ((12972, 12987), 'numpy.sin', 'np.sin', (['B.theta'], {}), '(B.theta)\n', (12978, 12987), True, 'import numpy as np\n'), ((13410, 13444), 'numpy.tan', 'np.tan', (['(A.mu * (theta_c - A.theta))'], {}), '(A.mu * (theta_c - A.theta))\n', (13416, 13444), True, 'import numpy as np\n'), ((14404, 14426), 'numpy.tan', 'np.tan', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (14410, 14426), True, 'import numpy as np\n'), ((14425, 14447), 'numpy.tan', 'np.tan', (['(B.theta + B.mu)'], {}), '(B.theta + B.mu)\n', (14431, 14447), True, 'import numpy as np\n'), ((14475, 14497), 'numpy.tan', 'np.tan', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (14481, 14497), True, 'import numpy as np\n'), ((14549, 14561), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (14555, 14561), True, 'import numpy as np\n'), ((14630, 14642), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (14636, 14642), True, 'import numpy as np\n'), ((15466, 15488), 'numpy.tan', 'np.tan', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (15472, 15488), True, 'import numpy as np\n'), ((15817, 15829), 'numpy.sin', 'np.sin', (['A.mu'], {}), '(A.mu)\n', (15823, 15829), True, 'import numpy as np\n'), ((15830, 15845), 'numpy.sin', 'np.sin', (['A.theta'], {}), '(A.theta)\n', (15836, 15845), True, 'import numpy as np\n'), ((16547, 16569), 'numpy.tan', 'np.tan', (['(B.theta - B.mu)'], {}), '(B.theta - B.mu)\n', (16553, 16569), True, 'import numpy as np\n'), ((16706, 16718), 'numpy.sin', 'np.sin', (['B.mu'], {}), '(B.mu)\n', (16712, 16718), True, 'import numpy as np\n'), ((16719, 16734), 'numpy.sin', 'np.sin', (['B.theta'], {}), '(B.theta)\n', (16725, 16734), True, 'import numpy as np\n'), ((17431, 17453), 'numpy.tan', 'np.tan', (['(B.theta + B.mu)'], {}), '(B.theta + B.mu)\n', (17437, 17453), True, 'import numpy as np\n'), ((17662, 17674), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (17668, 17674), True, 'import numpy as np\n'), ((17768, 17780), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (17774, 17780), True, 'import numpy as np\n'), ((17893, 17908), 'numpy.tan', 'np.tan', (['A.theta'], {}), '(A.theta)\n', (17899, 17908), True, 'import numpy as np\n'), ((19273, 19319), 'numpy.tan', 'np.tan', (['(chr_point_obj.theta + chr_point_obj.mu)'], {}), '(chr_point_obj.theta + chr_point_obj.mu)\n', (19279, 19319), True, 'import numpy as np\n'), ((5011, 5070), 'gasdynamics.PR_expansion_mach', 'gd.PR_expansion_mach', (['(self.spike.p_c / self.p_b)', 'self.gamma'], {}), '(self.spike.p_c / self.p_b, self.gamma)\n', (5031, 5070), True, 'import gasdynamics as gd\n'), ((5558, 5594), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (5567, 5594), True, 'import numpy as np\n'), ((5848, 5884), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (5857, 5884), True, 'import numpy as np\n'), ((9377, 9413), 'numpy.append', 'np.append', (['self.chr_array', 'new_point'], {}), '(self.chr_array, new_point)\n', (9386, 9413), True, 'import numpy as np\n'), ((13159, 13171), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (13165, 13171), True, 'import numpy as np\n'), ((13178, 13190), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (13184, 13190), True, 'import numpy as np\n'), ((13197, 13209), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (13203, 13209), True, 'import numpy as np\n'), ((13354, 13366), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (13360, 13366), True, 'import numpy as np\n'), ((13371, 13383), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (13377, 13383), True, 'import numpy as np\n'), ((14381, 14403), 'numpy.tan', 'np.tan', (['(B.theta + B.mu)'], {}), '(B.theta + B.mu)\n', (14387, 14403), True, 'import numpy as np\n'), ((14520, 14532), 'numpy.sin', 'np.sin', (['A.mu'], {}), '(A.mu)\n', (14526, 14532), True, 'import numpy as np\n'), ((14533, 14548), 'numpy.sin', 'np.sin', (['A.theta'], {}), '(A.theta)\n', (14539, 14548), True, 'import numpy as np\n'), ((14601, 14613), 'numpy.sin', 'np.sin', (['B.mu'], {}), '(B.mu)\n', (14607, 14613), True, 'import numpy as np\n'), ((14614, 14629), 'numpy.sin', 'np.sin', (['B.theta'], {}), '(B.theta)\n', (14620, 14629), True, 'import numpy as np\n'), ((14793, 14805), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (14799, 14805), True, 'import numpy as np\n'), ((14810, 14822), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (14816, 14822), True, 'import numpy as np\n'), ((14853, 14887), 'numpy.tan', 'np.tan', (['(A.mu * (theta_c - A.theta))'], {}), '(A.mu * (theta_c - A.theta))\n', (14859, 14887), True, 'import numpy as np\n'), ((15925, 15937), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (15931, 15937), True, 'import numpy as np\n'), ((17633, 17645), 'numpy.sin', 'np.sin', (['B.mu'], {}), '(B.mu)\n', (17639, 17645), True, 'import numpy as np\n'), ((17646, 17661), 'numpy.sin', 'np.sin', (['B.theta'], {}), '(B.theta)\n', (17652, 17661), True, 'import numpy as np\n'), ((24900, 24921), 'numpy.sin', 'np.sin', (['contour_angle'], {}), '(contour_angle)\n', (24906, 24921), True, 'import numpy as np\n'), ((5138, 5171), 'gasdynamics.prandtl_meyer', 'gd.prandtl_meyer', (['M_b', 'self.gamma'], {}), '(M_b, self.gamma)\n', (5154, 5171), True, 'import gasdynamics as gd\n'), ((5173, 5221), 'gasdynamics.prandtl_meyer', 'gd.prandtl_meyer', (['first_base_point.M', 'self.gamma'], {}), '(first_base_point.M, self.gamma)\n', (5189, 5221), True, 'import gasdynamics as gd\n'), ((8355, 8387), 'numpy.append', 'np.append', (['self.chr_array', 'temp1'], {}), '(self.chr_array, temp1)\n', (8364, 8387), True, 'import numpy as np\n'), ((12718, 12740), 'numpy.tan', 'np.tan', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (12724, 12740), True, 'import numpy as np\n'), ((16519, 16534), 'numpy.tan', 'np.tan', (['A.theta'], {}), '(A.theta)\n', (16525, 16534), True, 'import numpy as np\n'), ((17401, 17416), 'numpy.tan', 'np.tan', (['A.theta'], {}), '(A.theta)\n', (17407, 17416), True, 'import numpy as np\n'), ((7746, 7910), 'matplotlib.pyplot.plot', 'plt.plot', (['self.chr_array[self.ID_right_chr[0]].x', 'self.chr_array[self.ID_right_chr[0]].y', '"""bx"""', 'self.chr_array[ID_temp].x', 'self.chr_array[ID_temp].y', '"""rx"""'], {}), "(self.chr_array[self.ID_right_chr[0]].x, self.chr_array[self.\n ID_right_chr[0]].y, 'bx', self.chr_array[ID_temp].x, self.chr_array[\n ID_temp].y, 'rx')\n", (7754, 7910), True, 'import matplotlib.pyplot as plt\n'), ((7924, 8098), 'matplotlib.pyplot.plot', 'plt.plot', (['self.chr_array[self.ID_right_chr[0]].x', '(self.chr_array[self.ID_right_chr[0]].y * -1)', '"""bx"""', 'self.chr_array[ID_temp].x', '(self.chr_array[ID_temp].y * -1)', '"""rx"""'], {}), "(self.chr_array[self.ID_right_chr[0]].x, self.chr_array[self.\n ID_right_chr[0]].y * -1, 'bx', self.chr_array[ID_temp].x, self.\n chr_array[ID_temp].y * -1, 'rx')\n", (7932, 8098), True, 'import matplotlib.pyplot as plt\n'), ((8108, 8140), 'matplotlib.pyplot.plot', 'plt.plot', (['temp1.x', 'temp1.y', '"""go"""'], {}), "(temp1.x, temp1.y, 'go')\n", (8116, 8140), True, 'import matplotlib.pyplot as plt\n'), ((8167, 8204), 'matplotlib.pyplot.plot', 'plt.plot', (['temp1.x', '(temp1.y * -1)', '"""go"""'], {}), "(temp1.x, temp1.y * -1, 'go')\n", (8175, 8204), True, 'import matplotlib.pyplot as plt\n'), ((8904, 9111), 'matplotlib.pyplot.plot', 'plt.plot', (['[self.chr_array[ID_temp].x, temp2.x]', '[self.chr_array[ID_temp].y * -1, temp2.y * -1]', '"""k"""', '[self.chr_array[self.ID - 1].x, temp2.x]', '[self.chr_array[self.ID - 1].y * -1, temp2.y * -1]', '"""k"""'], {}), "([self.chr_array[ID_temp].x, temp2.x], [self.chr_array[ID_temp].y *\n -1, temp2.y * -1], 'k', [self.chr_array[self.ID - 1].x, temp2.x], [self\n .chr_array[self.ID - 1].y * -1, temp2.y * -1], 'k')\n", (8912, 9111), True, 'import matplotlib.pyplot as plt\n'), ((9116, 9303), 'matplotlib.pyplot.plot', 'plt.plot', (['[self.chr_array[ID_temp].x, temp2.x]', '[self.chr_array[ID_temp].y, temp2.y]', '"""k"""', '[self.chr_array[self.ID - 1].x, temp2.x]', '[self.chr_array[self.ID - 1].y, temp2.y]', '"""k"""'], {}), "([self.chr_array[ID_temp].x, temp2.x], [self.chr_array[ID_temp].y,\n temp2.y], 'k', [self.chr_array[self.ID - 1].x, temp2.x], [self.\n chr_array[self.ID - 1].y, temp2.y], 'k')\n", (9124, 9303), True, 'import matplotlib.pyplot as plt\n'), ((13316, 13328), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (13322, 13328), True, 'import numpy as np\n'), ((14348, 14370), 'numpy.tan', 'np.tan', (['(A.theta + A.mu)'], {}), '(A.theta + A.mu)\n', (14354, 14370), True, 'import numpy as np\n'), ((14755, 14767), 'numpy.tan', 'np.tan', (['B.mu'], {}), '(B.mu)\n', (14761, 14767), True, 'import numpy as np\n'), ((24866, 24895), 'numpy.sqrt', 'np.sqrt', (['(contour_der ** 2 + 1)'], {}), '(contour_der ** 2 + 1)\n', (24873, 24895), True, 'import numpy as np\n'), ((13109, 13121), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (13115, 13121), True, 'import numpy as np\n'), ((13267, 13279), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (13273, 13279), True, 'import numpy as np\n'), ((14706, 14718), 'numpy.tan', 'np.tan', (['A.mu'], {}), '(A.mu)\n', (14712, 14718), True, 'import numpy as np\n')]
#coding:utf-8 import numpy as np from pylab import * """4.1.4 フィッシャーの線形判別(p.185)""" N = 100 # データ数 def f(x, a, b): return a * x + b if __name__ == "__main__": # 訓練データを作成 cls1 = [] cls2 = [] # データは正規分布に従って生成 mean1 = [1, 3] # クラス1の平均 mean2 = [3, 1] # クラス2の平均 cov = [[2.0,0.0], [0.0, 0.1]] # 共分散行列(全クラス共通) # データ作成 cls1.extend(np.random.multivariate_normal(mean1, cov, N / 2)) cls2.extend(np.random.multivariate_normal(mean2, cov, N / 2)) # 各クラスの平均をプロット m1 = np.mean(cls1, axis=0) m2 = np.mean(cls2, axis=0) plot([m1[0]], [m1[1]], 'b+') plot([m2[0]], [m2[1]], 'r+') # 総クラス内共分散行列を計算 Sw = zeros((2, 2)) for n in range(len(cls1)): xn = matrix(cls1[n]).reshape(2, 1) m1 = matrix(m1).reshape(2, 1) Sw += (xn - m1) * transpose(xn - m1) for n in range(len(cls2)): xn = matrix(cls2[n]).reshape(2, 1) m2 = matrix(m2).reshape(2, 1) Sw += (xn - m2) * transpose(xn - m2) Sw_inv = np.linalg.inv(Sw) w = Sw_inv * (m2 - m1) # 訓練データを描画 x1, x2 = np.transpose(np.array(cls1)) plot(x1, x2, 'bo') x1, x2 = np.transpose(np.array(cls2)) plot(x1, x2, 'ro') # 識別境界を描画 # wは識別境界と直交するベクトル a = - (w[0,0] / w[1,0]) # 識別直線の傾き # 傾きがaでmを通る直線のy切片bを求める m = (m1 + m2) / 2 b = -a * m[0,0] + m[1,0] # 識別直線のy切片 x1 = np.linspace(-2, 6, 1000) x2 = [f(x, a, b) for x in x1] plot(x1, x2, 'g-') xlim(-2, 6) ylim(-2, 4) show()
[ "numpy.mean", "numpy.array", "numpy.linalg.inv", "numpy.random.multivariate_normal", "numpy.linspace" ]
[((518, 539), 'numpy.mean', 'np.mean', (['cls1'], {'axis': '(0)'}), '(cls1, axis=0)\n', (525, 539), True, 'import numpy as np\n'), ((549, 570), 'numpy.mean', 'np.mean', (['cls2'], {'axis': '(0)'}), '(cls2, axis=0)\n', (556, 570), True, 'import numpy as np\n'), ((1008, 1025), 'numpy.linalg.inv', 'np.linalg.inv', (['Sw'], {}), '(Sw)\n', (1021, 1025), True, 'import numpy as np\n'), ((1377, 1401), 'numpy.linspace', 'np.linspace', (['(-2)', '(6)', '(1000)'], {}), '(-2, 6, 1000)\n', (1388, 1401), True, 'import numpy as np\n'), ((373, 421), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean1', 'cov', '(N / 2)'], {}), '(mean1, cov, N / 2)\n', (402, 421), True, 'import numpy as np\n'), ((439, 487), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean2', 'cov', '(N / 2)'], {}), '(mean2, cov, N / 2)\n', (468, 487), True, 'import numpy as np\n'), ((1095, 1109), 'numpy.array', 'np.array', (['cls1'], {}), '(cls1)\n', (1103, 1109), True, 'import numpy as np\n'), ((1161, 1175), 'numpy.array', 'np.array', (['cls2'], {}), '(cls2)\n', (1169, 1175), True, 'import numpy as np\n')]
import json import matplotlib.pyplot as plt import numpy as np import seaborn as sns import sys def unistring(s): """Encodes our Unicode string to ASCII, then back to Unicode. In the translation, we ignore all unknown characters, which removes all of the non-ASCII characters that break our string parsing. """ return str(s).encode("ascii", "ignore").decode() def process_data(data_json, key1, renamed1, key2, renamed2, key3, renamed3, key4, renamed4, key5, renamed5, key6="", renamed6=""): """Converts our list of dictionaries to a dictionary of lists, while processing some of the data points (e.g. converting number strings to ints and float, as well as lowercasing strings). Also uses renamed keys instead of the very long default ones. """ val1 = [] val2 = [] val3 = [] val4 = [] val5 = [] val6 = [] for d in data_json: val1.append(d[key1]) val2.append(float(d[key2])) val3.append(int(d[key3])) val4.append(d[key4].lower()) val5.append(d[key5].lower()) if key6 is not "": val6.append(str(d[key6]) == "true" or str(d[key6]) == "True") return {renamed1: val1, renamed2: val2, renamed3: val3, renamed4: val4, renamed5: val5, renamed6: val6} def get_best_fit_poly_coeffs(data_dict, x, y, deg): """Finds the coefficients of the polynomial function for the best fit line. """ coeffs = np.polyfit(x=data_dict[x], y=data_dict[y], deg=deg) return coeffs def scatter_plot(data_dict): """Visualizes account age versus karma on the x and y axes, and whether or not the requester was given a pizza as the green or red point color. """ for i in range(len(data_dict["age"])): formatting = "." + ("g" if data_dict["result"][i] else "r") plt.plot(data_dict["age"][i], data_dict["karma"][i], formatting) coeffs = get_best_fit_poly_coeffs(data_dict, "age", "karma", 1) poly = np.poly1d(coeffs) plt.plot(data_dict["age"], poly(data_dict["age"])) plt.show() def will_reciprocate(data_dict, index): """Searches the text of the request for phrases that suggest a promise to give pizza to someone else. data_dict is a dictionary of lists,and any given index in the lists corresponds to the same post for different keys. """ title = data_dict["title"][index] body = data_dict["body"][index] phrases = ["pay it forward", "return the favor", "reciprocate"] for p in phrases: if p in title or p in body: return True return False def print_data(data_dict): """Prints the data for examining or debugging purposes. """ print("id, age, karma, reciprocal, result") for i in range(len(data_dict["id"])): print(( data_dict["id"][i], data_dict["age"][i], data_dict["karma"][i], will_reciprocate(data_dict, i), data_dict["result"][i] )) def train_acc(data_train, coeffs, multiplier): """Determines the accuracy of a set of coefficients (with a multiplier) on the training data. """ poly = np.poly1d([i*multiplier for i in coeffs]) predictions_train = [(poly(data_train["age"][i]) < data_train["karma"][i]) or will_reciprocate(data_train, i) for i in range(len(data_train["id"]))] correct = 0 for i in range(len(predictions_train)): if predictions_train[i] == data_train["result"][i]: correct += 1 accuracy = correct / len(predictions_train) * 100 return accuracy def sweep_coeff(data_train, coeffs): """Sweep the coefficients to see which multiplier gives the best accuracy. """ best_m = 1 best_a = 0 for m in np.arange(0.0, 100.0, 0.1): acc = train_acc(data_train, coeffs, m) if acc > best_a: best_m = m best_a = acc print(("New best multiplier:", best_m, "with an accuracy of", best_a)) return [i*best_m for i in coeffs] def main(argv): """The main program itself. Imports JSON data as a list of dictionaries, each of which is a data point (a pizza request). Then makes predictions as to whether or not the request would be fulfilled based on whether or not they offered to reciprocate, as well as whether or not they had more karma than the corresponding point on the best-fit line. """ with open("train.json") as open_file: json_train = json.loads(unistring(open_file.read())) print((len(json_train), "training data points")) data_train = process_data(json_train, "request_id", "id", "requester_account_age_in_days_at_request", "age", "requester_upvotes_minus_downvotes_at_request", "karma", "request_title", "title", "request_text_edit_aware", "body", "requester_received_pizza", "result") with open("test.json") as open_file: json_test = json.loads(unistring(open_file.read())) print((len(json_test), "testing data points")) data_test = process_data(json_test, "request_id", "id", "requester_account_age_in_days_at_request", "age", "requester_upvotes_minus_downvotes_at_request", "karma", "request_title", "title", "request_text_edit_aware", "body") # print_data(data_dict) # scatter_plot(data_dict) coeffs = get_best_fit_poly_coeffs(data_train, "age", "karma", 1) print(("Initial coefficients:", coeffs)) best_coeffs = sweep_coeff(data_train, coeffs) poly = np.poly1d(best_coeffs) print(("Best coefficients:", best_coeffs)) predictions_test = [(poly(data_test["age"][i]) < data_test["karma"][i]) or will_reciprocate(data_test, i) for i in range(len(data_test["id"]))] with open("predictions.csv", "w") as output: output.write("request_id,requester_received_pizza\n") for i in range(len(data_test["id"])): output.write("%s,%d\n" % (data_test["id"][i], predictions_test[i])) if __name__ == "__main__": main(sys.argv)
[ "numpy.poly1d", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "numpy.polyfit", "numpy.arange" ]
[((1558, 1609), 'numpy.polyfit', 'np.polyfit', ([], {'x': 'data_dict[x]', 'y': 'data_dict[y]', 'deg': 'deg'}), '(x=data_dict[x], y=data_dict[y], deg=deg)\n', (1568, 1609), True, 'import numpy as np\n'), ((2094, 2111), 'numpy.poly1d', 'np.poly1d', (['coeffs'], {}), '(coeffs)\n', (2103, 2111), True, 'import numpy as np\n'), ((2173, 2183), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2181, 2183), True, 'import matplotlib.pyplot as plt\n'), ((3304, 3349), 'numpy.poly1d', 'np.poly1d', (['[(i * multiplier) for i in coeffs]'], {}), '([(i * multiplier) for i in coeffs])\n', (3313, 3349), True, 'import numpy as np\n'), ((3954, 3980), 'numpy.arange', 'np.arange', (['(0.0)', '(100.0)', '(0.1)'], {}), '(0.0, 100.0, 0.1)\n', (3963, 3980), True, 'import numpy as np\n'), ((6356, 6378), 'numpy.poly1d', 'np.poly1d', (['best_coeffs'], {}), '(best_coeffs)\n', (6365, 6378), True, 'import numpy as np\n'), ((1948, 2012), 'matplotlib.pyplot.plot', 'plt.plot', (["data_dict['age'][i]", "data_dict['karma'][i]", 'formatting'], {}), "(data_dict['age'][i], data_dict['karma'][i], formatting)\n", (1956, 2012), True, 'import matplotlib.pyplot as plt\n')]
import unittest from action.watermark import watermarkImage, watermarkText import cv2 as cv import numpy as np class WatermarkTest((unittest.TestCase)): @classmethod def setUpClass(self): self.testImage = cv.imread('examples/img1.jpg') self.watermarkLogo = cv.imread('examples/wm-logo.png') def setUp(self): pass def test_watermak__image_action(self): wmi = watermarkImage(self.testImage, self.watermarkLogo) self.assertTrue(np.any(self.testImage != wmi)) def test_watarmark_text_action(self): wmi = watermarkText(self.testImage, 'watermarkLogo') self.assertTrue(np.any(self.testImage != wmi))
[ "numpy.any", "cv2.imread", "action.watermark.watermarkText", "action.watermark.watermarkImage" ]
[((223, 253), 'cv2.imread', 'cv.imread', (['"""examples/img1.jpg"""'], {}), "('examples/img1.jpg')\n", (232, 253), True, 'import cv2 as cv\n'), ((283, 316), 'cv2.imread', 'cv.imread', (['"""examples/wm-logo.png"""'], {}), "('examples/wm-logo.png')\n", (292, 316), True, 'import cv2 as cv\n'), ((410, 460), 'action.watermark.watermarkImage', 'watermarkImage', (['self.testImage', 'self.watermarkLogo'], {}), '(self.testImage, self.watermarkLogo)\n', (424, 460), False, 'from action.watermark import watermarkImage, watermarkText\n'), ((574, 620), 'action.watermark.watermarkText', 'watermarkText', (['self.testImage', '"""watermarkLogo"""'], {}), "(self.testImage, 'watermarkLogo')\n", (587, 620), False, 'from action.watermark import watermarkImage, watermarkText\n'), ((486, 515), 'numpy.any', 'np.any', (['(self.testImage != wmi)'], {}), '(self.testImage != wmi)\n', (492, 515), True, 'import numpy as np\n'), ((646, 675), 'numpy.any', 'np.any', (['(self.testImage != wmi)'], {}), '(self.testImage != wmi)\n', (652, 675), True, 'import numpy as np\n')]
import sys, os import numpy as np from .EQ_kernel import * import scipy.linalg as spalg import scipy as scipy import pprint as pp import time from .tools import * from scipy.cluster.vq import vq, kmeans2 from scipy.spatial.distance import cdist class FITC_network: def __init__(self, Ntrain, layer_sizes, no_pseudos, lik, n_classes=None, zu_tied=False): self.lik = lik self.n_classes = n_classes self.no_layers = len(no_pseudos) self.layer_sizes = layer_sizes self.no_pseudos = no_pseudos self.Ntrain = Ntrain self.jitter = 1e-6 self.zu_tied = zu_tied self.no_output_noise = self.lik != 'Gaussian' self.ones_M = [np.ones(Mi) for Mi in no_pseudos] self.ones_D = [np.ones(Di) for Di in layer_sizes[:-1]] self.ones_M_ls = [0 for Di in layer_sizes[:-1]] self.mu = [] self.Su = [] self.Splusmm = [] self.muhat = [] self.Suhat = [] self.Suhatinv = [] self.Splusmmhat = [] self.Kuu = [] self.Kuuinv = [] self.dKuudls = [] self.dKuudsf = [] self.dKuudzu = [] self.ls = [] self.sf = [] self.sn = [] self.zu = [] self.theta_1_R = [] self.theta_2 = [] self.theta_1 = [] self.Ahat = [] self.Bhat = [] self.A = [] self.B = [] for l in range(self.no_layers): Din_l = self.layer_sizes[l] Dout_l = self.layer_sizes[l+1] M_l = self.no_pseudos[l] # variables for the mean and covariance of q(u) self.mu.append([ np.zeros([M_l,]) for _ in range(Dout_l) ]) self.Su.append([ np.zeros([M_l, M_l]) for _ in range(Dout_l) ]) self.Splusmm.append([ np.zeros([M_l, M_l]) for _ in range(Dout_l) ]) # variables for the cavity distribution self.muhat.append([ np.zeros([M_l,]) for _ in range(Dout_l) ]) self.Suhat.append([ np.zeros([M_l, M_l]) for _ in range(Dout_l) ]) self.Suhatinv.append([ np.zeros([M_l, M_l]) for _ in range(Dout_l) ]) self.Splusmmhat.append([ np.zeros([M_l, M_l]) for _ in range(Dout_l) ]) # numpy variable for inducing points, Kuuinv, Kuu and its gradients if not self.zu_tied: self.zu.append([np.zeros([M_l, Din_l]) for _ in range(Dout_l)]) self.Kuu.append([np.zeros([M_l, M_l]) for _ in range(Dout_l)]) self.Kuuinv.append([np.zeros([M_l, M_l]) for _ in range(Dout_l)]) self.dKuudls.append([np.zeros([Din_l, M_l, M_l]) for _ in range(Dout_l)]) self.dKuudsf.append([np.zeros([M_l, M_l]) for _ in range(Dout_l)]) self.dKuudzu.append([np.zeros([Din_l, M_l, M_l]) for _ in range(Dout_l)]) else: self.zu.append(np.zeros([M_l, Din_l])) self.Kuu.append(np.zeros([M_l, M_l])) self.Kuuinv.append(np.zeros([M_l, M_l])) self.dKuudls.append(np.zeros([Din_l, M_l, M_l])) self.dKuudsf.append(np.zeros([M_l, M_l])) self.dKuudzu.append(np.zeros([Din_l, M_l, M_l])) # variables for the hyperparameters self.ls.append(np.zeros([Din_l, ])) self.sf.append(0) if not ( self.no_output_noise and (l == self.no_layers - 1) ): self.sn.append(0) # and natural parameters self.theta_1_R.append([np.zeros([M_l, M_l]) for _ in range(Dout_l)]) self.theta_2.append([np.zeros([M_l,]) for _ in range(Dout_l)]) self.theta_1.append([np.zeros([M_l, M_l]) for _ in range(Dout_l)]) # terms that are common to all datapoints in each minibatch self.Ahat.append([np.zeros([M_l,]) for _ in range(Dout_l)]) self.Bhat.append([np.zeros([M_l, M_l]) for _ in range(Dout_l)]) self.A.append([np.zeros([M_l,]) for _ in range(Dout_l)]) self.B.append([np.zeros([M_l, M_l]) for _ in range(Dout_l)]) def compute_phi_prior(self): logZ_prior = 0 for i in range(self.no_layers): Dout_i = self.layer_sizes[i+1] if not self.zu_tied: for d in range(Dout_i): (sign, logdet) = np.linalg.slogdet(self.Kuu[i][d]) logZ_prior += 0.5 * logdet else: (sign, logdet) = np.linalg.slogdet(self.Kuu[i]) logZ_prior += Dout_i * 0.5 * logdet return logZ_prior def compute_phi_posterior(self): logZ_posterior = 0 for i in range(self.no_layers): Dout_i = self.layer_sizes[i+1] for d in range(Dout_i): mud_val = self.mu[i][d] Sud_val = self.Su[i][d] (sign, logdet) = np.linalg.slogdet(Sud_val) # print 'phi_poste: ', 0.5 * logdet, 0.5 * np.sum(mud_val * spalg.solve(Sud_val, mud_val.T)) logZ_posterior += 0.5 * logdet logZ_posterior += 0.5 * np.sum(mud_val * spalg.solve(Sud_val, mud_val.T)) return logZ_posterior def compute_phi_cavity(self): phi_cavity = 0 for i in range(self.no_layers): Dout_i = self.layer_sizes[i+1] for d in range(Dout_i): muhatd_val = self.muhat[i][d] Suhatd_val = self.Suhat[i][d] (sign, logdet) = np.linalg.slogdet(Suhatd_val) phi_cavity += 0.5 * logdet phi_cavity += 0.5 * np.sum(muhatd_val * spalg.solve(Suhatd_val, muhatd_val.T)) return phi_cavity def output_probabilistic(self, x, inter_layer=None): if inter_layer is None: inter_layer = self.no_layers Dini = self.layer_sizes[0] Douti = self.layer_sizes[1] Mi = self.no_pseudos[0] mx = x.reshape((Dini,)) # Recursively compute output # deal with input layer ls_i = self.ls[0] sf_i = self.sf[0] Dout_i = self.layer_sizes[1] # create place holders mout_i = np.zeros((Douti,)) vout_i = np.zeros((Douti,)) # compute the psi terms psi0 = np.exp(2.0*sf_i) if not (self.no_output_noise and (self.no_layers == 1)): sn2 = np.exp(2.0*self.sn[0]) else: sn2 = 0.0 if self.zu_tied: psi1 = compute_kernel(2*ls_i, 2*sf_i, mx, self.zu[0]) for d in range(Dout_i): if not self.zu_tied: psi1 = compute_kernel(2*ls_i, 2*sf_i, mx, self.zu[0][d]) psi1 = psi1.reshape((Mi, )) Aid = self.A[0][d] Bid = self.B[0][d] moutid = np.sum(np.dot(psi1, Aid)) Bid_psi1 = np.dot(Bid, psi1) sumJ = np.sum(np.dot(psi1.T, Bid_psi1)) voutid = sn2 + psi0 + sumJ mout_i[d] = moutid vout_i[d] = voutid mx_previous = mout_i vx_previous = vout_i # and other layers for i in range(1, self.no_layers, 1): if i == inter_layer: break Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] Mi = self.no_pseudos[i] ls_i = self.ls[i] sf_i = self.sf[i] Dout_i = self.layer_sizes[i+1] # create place holders mout_i = np.zeros((Douti,)) vout_i = np.zeros((Douti,)) # compute the psi terms psi0 = np.exp(2.0*sf_i) if not (self.lik != 'Gaussian' and (i == self.no_layers-1)): sn2 = np.exp(2.0 * self.sn[i]) else: sn2 = 0.0 if self.zu_tied: psi1 = compute_psi1(2*ls_i, 2*sf_i, mx_previous, vx_previous, self.zu[i]) psi2 = compute_psi2(2*ls_i, 2*sf_i, mx_previous, vx_previous, self.zu[i]) for d in range(Dout_i): if not self.zu_tied: psi1 = compute_psi1(2*ls_i, 2*sf_i, mx_previous, vx_previous, self.zu[i][d]) psi2 = compute_psi2(2*ls_i, 2*sf_i, mx_previous, vx_previous, self.zu[i][d]) Aid = self.A[i][d] Bid = self.B[i][d] moutid = np.sum(np.dot(psi1, Aid)) J = Bid * psi2 sumJ = np.sum(J) voutid = sn2 + psi0 + sumJ - moutid**2 mout_i[d] = moutid vout_i[d] = voutid mx_previous = mout_i vx_previous = vout_i mout_i = mout_i.reshape((1, mout_i.shape[0])) vout_i = vout_i.reshape((1, vout_i.shape[0])) return mout_i, vout_i def output_of_a_layer(self, x, layer_no): mx_previous = x i = layer_no - 1 ls_i = self.ls[i] sf_i = self.sf[i] Mi = self.no_pseudos[i] Dout_i = self.layer_sizes[i+1] # create place holders mout_i = np.zeros((1, Dout_i)) vout_i = np.zeros((1, Dout_i)) # compute the psi terms psi0 = np.exp(2.0*sf_i) if not (self.no_output_noise and i == self.no_layers-1): sn2 = np.exp(2.0*self.sn[i]) else: sn2 = 0 if self.zu_tied: psi1 = compute_kernel(2*ls_i, 2*sf_i, mx_previous, self.zu[i]) for d in range(Dout_i): if not self.zu_tied: psi1 = compute_kernel(2*ls_i, 2*sf_i, mx_previous, self.zu[i][d]) psi1 = psi1.reshape((Mi, )) Aid = self.A[i][d] Bid = self.B[i][d] moutid = np.sum(np.dot(psi1, Aid)) Bid_psi1 = np.dot(Bid, psi1) sumJ = np.sum(np.dot(psi1.T, Bid_psi1)) voutid = sn2 + psi0 + sumJ mout_i[0, d] = moutid vout_i[0, d] = voutid return mout_i, vout_i def compute_logZ_and_gradients(self, x, y, epsilon=None): zu_tied = self.zu_tied no_layers = self.no_layers # variables to hold gradients of logZ grad_names = ['ls', 'sf', 'sn', 'zu', 'Ahat', 'Bhat'] grads = {} for name in grad_names: grads[name] = [[] for _ in range(no_layers)] grads[name] = [[] for _ in range(no_layers)] # FORWARD PROPAGATION # variables to hold gradients of output means and variances mout = [[] for _ in range(no_layers)] vout = [[] for _ in range(no_layers)] dmout = {} dvout = {} output_grad_names = ['ls', 'sf', 'sn', 'zu', 'mx', 'vx', 'Ahat', 'Bhat'] for name in output_grad_names: dmout[name] = [[] for _ in range(no_layers)] dvout[name] = [[] for _ in range(no_layers)] # ************************** FIRST LAYER ************************** # deal with the first layer separately since there is no need for psi2 Dini = self.layer_sizes[0] Douti = self.layer_sizes[1] Mi = self.no_pseudos[0] mx = x.reshape((Dini,)) lsi = self.ls[0] sfi = self.sf[0] ls2 = np.exp(2*lsi) psi0 = np.exp(2.0*sfi) mouti = np.zeros((Douti,)) vouti = np.zeros((Douti,)) ones_Di = self.ones_D[0] ones_Mi = self.ones_M[0] # todo: deal with no noise at the last layer for certain liks if self.lik != 'Gaussian' and no_layers == 1: sn2 = 0 else: sn2 = np.exp(2.0*self.sn[0]) if zu_tied: zui = self.zu[0] psi1 = compute_kernel(2*lsi, 2*sfi, mx, zui) for d in range(Douti): if not zu_tied: zuid = self.zu[0][d] psi1 = compute_kernel(2*lsi, 2*sfi, mx, zuid) else: zuid = zui psi1 = psi1.reshape((Mi, )) Ahatid = self.Ahat[0][d] Bhatid = self.Bhat[0][d] moutid = np.sum(np.dot(psi1, Ahatid)) Bhatid_psi1 = np.dot(Bhatid, psi1) sumJ = np.sum(np.dot(psi1.T, Bhatid_psi1)) voutid = sn2 + psi0 + sumJ mouti[d] = moutid vouti[d] = voutid # now compute gradients of output mean # wrt Ahat and Bhat dmout['Ahat'][0].append(psi1.T) dmout['Bhat'][0].append(0) # wrt hypers dmout['sf'][0].append(2*moutid) mx_minus_zuid = np.outer(ones_Mi, mx) - zuid temp1 = np.outer(psi1, ones_Di) * 0.5 * mx_minus_zuid**2 dmoutid_dls = np.dot(Ahatid, temp1) * 1.0 / ls2 dmout['ls'][0].append(2*dmoutid_dls) # temp2 = mx_minus_zuid * np.outer(ones_Mi, 1.0 / ls2 ) temp2 = mx_minus_zuid * self.ones_M_ls[0] dmoutid_dzu = np.outer(psi1 * Ahatid, ones_Di) * temp2 dmout['zu'][0].append(dmoutid_dzu) dmout['sn'][0].append(0) # now compute gradients of the output variance # wrt Ahat and Bhat dvout['Ahat'][0].append(0) dvoutid_dBhat = np.outer(psi1, psi1) dvout['Bhat'][0].append(dvoutid_dBhat) # wrt sf dvoutid_dsf = psi0 + 2*sumJ dvout['sf'][0].append(2*dvoutid_dsf) # wrt ls dvoutid_dls = 2*np.dot(Bhatid_psi1, temp1) * 1.0 / ls2 dvout['ls'][0].append(2*dvoutid_dls) dvoutid_dzu = 2*np.outer(psi1 * Bhatid_psi1, ones_Di) * temp2 dvout['zu'][0].append(dvoutid_dzu) # wrt noise if self.lik != 'Gaussian' and no_layers == 1: dvout['sn'][0].append(0) else: dvout['sn'][0].append(2*sn2) mout[0] = mouti vout[0] = vouti # ************************** END OF FIRST LAYER ********************** # ************************** OTHERS LAYER ************************** for i in range(1, no_layers): Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] Mi = self.no_pseudos[i] mx = mout[i-1] vx = vout[i-1] lsi = self.ls[i] sfi = self.sf[i] psi0 = np.exp(2.0*sfi) mouti = np.zeros((Douti,)) vouti = np.zeros((Douti,)) ones_Di = self.ones_D[i] ones_Mi = self.ones_M[i] # todo: deal with no noise at the last layer for certain liks if self.lik != 'Gaussian' and i == no_layers-1: sn2 = 0 else: sn2 = np.exp(2.0*self.sn[i]) if zu_tied: zui = self.zu[i] psi1 = compute_psi1(2*lsi, 2*sfi, mx, vx, zui) psi2 = compute_psi2(2*lsi, 2*sfi, mx, vx, zui) for d in range(Douti): if not zu_tied: zuid = self.zu[i][d] psi1 = compute_psi1(2*lsi, 2*sfi, mx, vx, zuid) psi2 = compute_psi2(2*lsi, 2*sfi, mx, vx, zuid) Kuuinvid = self.Kuuinv[i][d] Kuuid = self.Kuu[i][d] else: zuid = zui Kuuinvid = self.Kuuinv[i] Kuuid = self.Kuu[i] Ahatid = self.Ahat[i][d] Bhatid = self.Bhat[i][d] muhatid = self.muhat[i][d] Suhatid = self.Suhat[i][d] moutid = np.sum(np.dot(psi1, Ahatid)) J = Bhatid * psi2 sumJ = np.sum(J) voutid = sn2 + psi0 + sumJ - moutid**2 mouti[d] = moutid vouti[d] = voutid # now compute gradients of output mean # wrt Ahat and Bhat dmoutid_dAhat = psi1.T dmout['Ahat'][i].append(dmoutid_dAhat.reshape((Mi, ))) dmout['Bhat'][i].append(0) # wrt xmean ls2 = np.exp(2*lsi) lspxvar = ls2 + vx Ahatid_psi1 = Ahatid * psi1 dmoutid_dmx = (- np.sum(Ahatid_psi1) * mx + np.dot(Ahatid_psi1, zuid)) * 1.0 / lspxvar dmout['mx'][i].append(dmoutid_dmx) # wrt xvar psi1_Kuuinv = np.dot(psi1, Kuuinvid) term1 = np.sum(psi1_Kuuinv * muhatid) * 1.0 / lspxvar * -0.5 term2 = np.dot(Ahatid_psi1, 0.5 * (np.outer(ones_Mi, mx) - zuid)**2) * 1.0 / (lspxvar**2) dmoutid_dvx = term1 + term2 dmout['vx'][i].append(dmoutid_dvx) # wrt hypers dmoutid_dsf = moutid dmout['sf'][i].append(2*moutid) mx_minus_zuid = np.outer(ones_Mi, mx) - zuid temp1 = np.outer(psi1, ones_Di) * 0.5 * mx_minus_zuid**2 dmoutid_dls = moutid * 0.5 * (1 - ls2 / (ls2 + vx)) + \ np.dot(Ahatid, temp1) * 1.0 / ((ls2 + vx)**2) * ls2 dmout['ls'][i].append(2*dmoutid_dls) temp2 = mx_minus_zuid * np.outer(ones_Mi, 1.0 / (ls2 + vx)) dmoutid_dzu = np.outer(psi1 * Ahatid, ones_Di) * temp2 dmout['zu'][i].append(dmoutid_dzu) dmout['sn'][i].append(0) # now compute gradients of the output variance # wrt Ahat and Bhat dvoutid_dAhat = - 2.0 * moutid * dmoutid_dAhat dvout['Ahat'][i].append(dvoutid_dAhat.reshape((Mi, ))) dvout['Bhat'][i].append(psi2) # wrt xmean D = ls2 Dhalf = ls2 / 2.0 Btilde = 1.0 / (Dhalf + vx) H = 0.5 * zuid * np.outer(ones_Mi, Btilde) dvoutid_dmx = 2.0 * np.dot(np.dot(ones_Mi, J), H) - sumJ * Btilde * mx \ - 2.0 * moutid * dmoutid_dmx dvout['mx'][i].append(dvoutid_dmx) # wrt xvar term1 = - sumJ * 1.0 / (Dhalf + vx) * 0.5 dBtilde = -(Btilde**2) dVtilde = dBtilde dQtilde = 0.25 * dVtilde M1 = - 0.5 * np.outer(ones_Mi, dQtilde) * (zuid**2) M2 = + 0.5 * np.outer(ones_Mi, dBtilde * mx) * zuid M3 = - 0.25 * np.outer(ones_Mi, dVtilde) * zuid term2 = 2.0 * np.dot(np.dot(ones_Mi, J), M1) + \ 2.0 * np.dot(np.dot(ones_Mi, J), M2) \ - 0.5 * sumJ * (mx**2) * dBtilde \ + np.dot(ones_Mi, zuid * np.dot(J, M3)) dvoutid_dvx = term1 + term2 - 2.0 * moutid * dmoutid_dvx dvout['vx'][i].append(dvoutid_dvx) # wrt sf dvoutid_dsf = psi0 + 2*np.sum(Bhatid * psi2) - 2.0 * moutid * dmoutid_dsf dvout['sf'][i].append(2*np.sum(dvoutid_dsf)) # wrt to ls Vtilde = Btilde - 1.0 / Dhalf Qtilde = 1.0 / D + 0.25 * Vtilde dBtilde = -(Btilde**2) * Dhalf dVtilde = dBtilde + (Dhalf**(-2)) * Dhalf dQtilde = -(D**(-2)) * D + 0.25 * dVtilde term1 = sumJ * Dhalf * 0.5 * (1.0 / Dhalf - 1.0 / (Dhalf + vx)) M1 = - 0.5 * np.outer(ones_Mi, dQtilde) * (zuid**2) M2 = + 0.5 * np.outer(ones_Mi, dBtilde * mx) * zuid M3 = - 0.25 * np.outer(ones_Mi, dVtilde) * zuid term2 = 2.0 * np.dot(np.dot(ones_Mi, J), M1) + \ 2.0 * np.dot(np.dot(ones_Mi, J), M2) \ - 0.5 * sumJ * (mx**2) * dBtilde \ + np.dot(ones_Mi, zuid * np.dot(J, M3)) dvoutid_dls = term1 + term2 - 2*moutid*dmoutid_dls dvout['ls'][i].append(2*dvoutid_dls) # wrt zu upsilon = np.dot(ones_Mi, J) term1 = 2 * np.outer(upsilon, ones_Di) * -0.5 * zuid * np.outer(ones_Mi, Qtilde) * 2 term2 = 2 * np.outer(upsilon, ones_Di) * +0.5 * np.outer(ones_Mi, mx * Btilde) term3 = 2 * np.dot(J, (zuid * np.outer(np.ones(Mi), Vtilde))) * -0.25 dvoutid_dzu = term1 + term2 + term3 - 2*moutid*dmoutid_dzu dvout['zu'][i].append(dvoutid_dzu) # wrt noise if self.lik != 'Gaussian' and i == no_layers-1: dvout['sn'][i].append(0) else: dvout['sn'][i].append(2*sn2) mout[i] = mouti vout[i] = vouti # ************************** END OF FORWARD PASS ************************** # ************************** COMPUTE LOG Z and DO BACKWARD STEP *********** if self.lik == 'Gaussian': m = mout[-1] v = vout[-1] # print m, v logZ = np.sum( -0.5 * (np.log(v) + (y - m)**2 / v) ) dlogZ_dmlast = (y - m) / v dlogZ_dvlast = -0.5 / v + 0.5 * (y - m)**2 / v**2 dlogZ_dmlast = np.reshape(dlogZ_dmlast, [self.layer_sizes[-1],]) dlogZ_dvlast = np.reshape(dlogZ_dvlast, [self.layer_sizes[-1],]) elif self.lik == 'Probit': # binary classification using probit likelihood m = mout[-1] v = vout[-1] t = y * m / np.sqrt(1 + v) Z = 0.5 * (1 + math.erf(t / np.sqrt(2))) eps = 1e-16 logZ = np.log(Z + eps) dlogZ_dt = 1/(Z + eps) * 1/np.sqrt(2*np.pi) * np.exp(-t**2.0 / 2) dt_dm = y / np.sqrt(1 + v) dt_dv = -0.5 * y * m / (1 + v)**1.5 dlogZ_dmlast = dlogZ_dt * dt_dm dlogZ_dvlast = dlogZ_dt * dt_dv dlogZ_dmlast = np.reshape(dlogZ_dmlast, [1,]) dlogZ_dvlast = np.reshape(dlogZ_dvlast, [1,]) elif self.lik == 'Softmax': # multiclass classification using softmax likelihood m = mout[-1] v = vout[-1] veps = np.sqrt(v) * epsilon samples = m + veps y = np.reshape(y, [1, self.n_classes]) ylabel = np.argmax(y, axis=1) # p_y_given_samples = softmax(samples) # p_y_sum = np.sum(p_y_given_samples[:, ylabel]) / epsilon.shape[0] # p_y_given_samples, dsamples = softmax_onecol(samples, ylabel) # p_y_sum = np.sum(p_y_given_samples) / epsilon.shape[0] # dviam = np.sum(dsamples, axis=0) / epsilon.shape[0] # dsqrtv = np.sum(dsamples * epsilon, axis=0) / epsilon.shape[0] # dviav = 0.5 * dsqrtv / np.sqrt(v) # logZ = np.log(p_y_sum) # dpysum = 1/p_y_sum # dm = dpysum * dviam # dv = dpysum * dviav py, dpy = softmax_given_y(samples, ylabel) logZ = np.log(py) dsamples = 1/py * dpy dm = np.sum(dsamples, axis=0) dv = np.sum(dsamples * epsilon, axis=0) / 2 / np.sqrt(v) dlogZ_dmlast = np.reshape(dm, [self.n_classes,]) dlogZ_dvlast = np.reshape(dv, [self.n_classes,]) dlogZ_dlast = {} dlogZ_dlast['mx'] = dlogZ_dmlast dlogZ_dlast['vx'] = dlogZ_dvlast # deal with layers in reverse order for i in range(self.no_layers-1, -1, -1): Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] dlogZ_din = {} dlogZ_din['mx'] = np.zeros((1, Dini)) dlogZ_din['vx'] = np.zeros((1, Dini)) for d in range(Douti): for name in output_grad_names: if (i > 0) and (name in ['mx', 'vx']): dlogZ_din[name] += dlogZ_dlast['mx'][d] * dmout[name][i][d] + dlogZ_dlast['vx'][d] * dvout[name][i][d] elif name not in ['mx', 'vx']: # print i, d, name grad_name_id = dlogZ_dlast['mx'][d] * dmout[name][i][d] + dlogZ_dlast['vx'][d] * dvout[name][i][d] grads[name][i].append(grad_name_id) if i > 0: dlogZ_din['mx'] = np.reshape(dlogZ_din['mx'], (Dini, )) dlogZ_din['vx'] = np.reshape(dlogZ_din['vx'], (Dini, )) dlogZ_dlast = dlogZ_din return logZ, grads def compute_kuu(self): # compute Kuu for each layer for i in range(self.no_layers): ls_i = self.ls[i] sf_i = self.sf[i] Dout_i = self.layer_sizes[i+1] M_i = self.no_pseudos[i] if not self.zu_tied: for d in range(Dout_i): zu_id = self.zu[i][d] self.Kuu[i][d] = compute_kernel(2*ls_i, 2*sf_i, zu_id, zu_id) self.Kuu[i][d] += np.diag(self.jitter * np.ones((M_i, ))) self.Kuuinv[i][d] = matrixInverse(self.Kuu[i][d]) else: zu_i = self.zu[i] self.Kuu[i] = compute_kernel(2*ls_i, 2*sf_i, zu_i, zu_i) self.Kuu[i] += np.diag(self.jitter * np.ones((M_i, ))) self.Kuuinv[i] = matrixInverse(self.Kuu[i]) def compute_cavity(self): # compute the leave one out moments for each layer beta = (self.Ntrain - 1.0) * 1.0 / self.Ntrain for i in range(self.no_layers): Dout_i = self.layer_sizes[i+1] for d in range(Dout_i): if self.zu_tied: Kuuinvid = self.Kuuinv[i] else: Kuuinvid = self.Kuuinv[i][d] self.Suhatinv[i][d] = Kuuinvid + beta * self.theta_1[i][d] ShatinvMhat = beta * self.theta_2[i][d] # Shat = npalg.inv(self.Suhatinv[i][d]) Shat = matrixInverse(self.Suhatinv[i][d]) self.Suhat[i][d] = Shat mhat = np.dot(Shat, ShatinvMhat) self.muhat[i][d] = mhat self.Ahat[i][d] = np.dot(Kuuinvid, mhat) Smm = Shat + np.outer(mhat, mhat) self.Splusmmhat[i][d] = Smm if i > 0: self.Bhat[i][d] = np.dot(Kuuinvid, np.dot(Smm, Kuuinvid)) - Kuuinvid else: self.Bhat[i][d] = np.dot(Kuuinvid, np.dot(Shat, Kuuinvid)) - Kuuinvid def update_posterior(self): # compute the posterior approximation for i in range(self.no_layers): Dout_i = self.layer_sizes[i+1] for d in range(Dout_i): if self.zu_tied: Kuuinvid = self.Kuuinv[i] else: Kuuinvid = self.Kuuinv[i][d] Sinv = Kuuinvid + self.theta_1[i][d] SinvM = self.theta_2[i][d] # S = npalg.inv(Sinv) S = matrixInverse(Sinv) self.Su[i][d] = S m = np.dot(S, SinvM) self.mu[i][d] = m Smm = S + np.outer(m, m) self.Splusmm[i][d] = Smm self.B[i][d] = np.dot(Kuuinvid, np.dot(Smm, Kuuinvid)) - Kuuinvid def update_posterior_for_prediction(self): # compute the posterior approximation for i in range(self.no_layers): Dout_i = self.layer_sizes[i+1] for d in range(Dout_i): if self.zu_tied: Kuuinvid = self.Kuuinv[i] else: Kuuinvid = self.Kuuinv[i][d] Sinv = Kuuinvid + self.theta_1[i][d] SinvM = self.theta_2[i][d] # S = npalg.inv(Sinv) S = matrixInverse(Sinv) self.Su[i][d] = S m = np.dot(S, SinvM) self.mu[i][d] = m self.A[i][d] = np.dot(Kuuinvid, m) Smm = S + np.outer(m, m) self.Splusmm[i][d] = Smm if i > 0: self.B[i][d] = np.dot(Kuuinvid, np.dot(Smm, Kuuinvid)) - Kuuinvid else: self.B[i][d] = np.dot(Kuuinvid, np.dot(S, Kuuinvid)) - Kuuinvid # Smm = S + np.outer(m, m) # self.Splusmm[i][d] = Smm # self.B[i][d] = np.dot(Kuuinvid, np.dot(Smm, Kuuinvid)) - Kuuinvid def init_hypers_Gaussian(self, x_train, y_train): # dict to hold hypers, inducing points and parameters of q(U) params = {'ls': [], 'sf': [], 'zu': [], 'sn': [], 'eta1_R': [], 'eta2': []} # first layer M1 = self.no_pseudos[0] Dout1 = self.layer_sizes[1] Ntrain = x_train.shape[0] if Ntrain < 20000: centroids, label = kmeans2(x_train, M1, minit='points') else: randind = np.random.permutation(Ntrain) centroids = x_train[randind[0:M1], :] # ls1 = self.estimate_ls(x_train) # ls1[ls1 < -5] = -5 ls1 = self.estimate_ls_temp(x_train) sn1 = np.array([np.log(0.1*np.std(y_train))]) sf1 = np.array([np.log(1*np.std(y_train))]) sf1[sf1 < -5] = 0 sn1[sn1 < -5] = np.log(0.1) # # for maunaloa only # ls1 = ls1 / 20 # sn1 = np.array([np.log(0.001)]) # sf1 = np.array([np.log(0.5)]) params['sf'].append(sf1) params['ls'].append(ls1) params['sn'].append(sn1) eta1_R0 = [] eta20 = [] for d in range(Dout1): eta1_R0.append(np.random.randn(M1*(M1+1)//2, )) eta20.append(np.random.randn(M1, )) params['eta1_R'].append(eta1_R0) params['eta2'].append(eta20) if self.zu_tied: zu0 = centroids else: zu0 = [] for d in range(Dout1): zu0.append(centroids) params['zu'].append(zu0) # other layers for i in range(1, self.no_layers): Mi = self.no_pseudos[i] Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] sfi = np.log(np.array([1])) sni = np.log(np.array([0.1])) lsi = np.ones((Dini, )) params['sf'].append(sfi) params['ls'].append(lsi) params['sn'].append(sni) if self.zu_tied: zui = np.tile(np.linspace(-1, 1, Mi).reshape((Mi, 1)), (1, Dini)) else: zui = [] for d in range(Douti): zuii = np.tile(np.linspace(-1, 1, Mi).reshape((Mi, 1)), (1, Dini)) zui.append(zuii) params['zu'].append(zui) eta1_Ri = [] eta2i = [] for d in range(Douti): eta1_Ri.append(np.random.randn(Mi*(Mi+1)//2, ) / 10) eta2i.append(np.random.randn(Mi, ) / 10) params['eta1_R'].append(eta1_Ri) params['eta2'].append(eta2i) return params def init_hypers_Probit(self, x_train): # dict to hold hypers, inducing points and parameters of q(U) params = {'ls': [], 'sf': [], 'zu': [], 'sn': [], 'eta1_R': [], 'eta2': []} # first layer M1 = self.no_pseudos[0] Dout1 = self.layer_sizes[1] Ntrain = x_train.shape[0] if Ntrain < 20000: centroids, label = kmeans2(x_train, M1, minit='points') else: randind = np.random.permutation(Ntrain) centroids = x_train[randind[0:M1], :] # ls1 = self.estimate_ls(x_train) # ls1[ls1 < -5] = -5 ls1 = self.estimate_ls_temp(x_train) sn1 = np.array([np.log(0.01)]) sf1 = np.array([np.log(1)]) sf1[sf1 < -5] = 0 sn1[sn1 < -5] = np.log(0.1) params['sf'].append(sf1) params['ls'].append(ls1) if self.no_layers > 1: params['sn'].append(sn1) else: # TODO params['sn'].append(0) eta1_R0 = [] eta20 = [] for d in range(Dout1): eta1_R0.append(np.random.randn(M1*(M1+1)//2, )) eta20.append(np.random.randn(M1, )) params['eta1_R'].append(eta1_R0) params['eta2'].append(eta20) if self.zu_tied: zu0 = centroids else: zu0 = [] for d in range(Dout1): zu0.append(centroids) params['zu'].append(zu0) # other layers for i in range(1, self.no_layers): Mi = self.no_pseudos[i] Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] sfi = np.log(np.array([1])) sni = np.log(np.array([0.1])) lsi = np.ones((Dini, )) params['sf'].append(sfi) params['ls'].append(lsi) if i != self.no_layers-1: params['sn'].append(sni) else: # TODO params['sn'].append(0) if self.zu_tied: zui = np.tile(np.linspace(-1, 1, Mi).reshape((Mi, 1)), (1, Dini)) else: zui = [] for d in range(Douti): zuii = np.tile(np.linspace(-1, 1, Mi).reshape((Mi, 1)), (1, Dini)) zui.append(zuii) params['zu'].append(zui) eta1_Ri = [] eta2i = [] for d in range(Douti): eta1_Ri.append(np.random.randn(Mi*(Mi+1)//2, ) / 10) eta2i.append(np.random.randn(Mi, ) / 10) params['eta1_R'].append(eta1_Ri) params['eta2'].append(eta2i) return params def init_hypers_Softmax(self, x_train, y_train): # dict to hold hypers, inducing points and parameters of q(U) params = {'ls': [], 'sf': [], 'zu': [], 'sn': [], 'eta1_R': [], 'eta2': []} # first layer # ls1 = self.estimate_ls(x_train) # ls1[ls1 < -5] = np.log(0.01) ls1 = self.estimate_ls_temp(x_train) sn1 = np.array([np.log(0.01)]) sf1 = np.array([np.log(1)]) sf1[sf1 < -5] = 0 sn1[sn1 < -5] = np.log(0.1) params['sf'].append(sf1) params['ls'].append(ls1) if self.no_layers > 1: params['sn'].append(sn1) else: # TODO params['sn'].append(0) zu0 = [] eta1_R0 = [] eta20 = [] M1 = self.no_pseudos[0] Dout1 = self.layer_sizes[1] Ntrain = x_train.shape[0] if Ntrain < 20000: centroids, label = kmeans2(x_train, M1, minit='points') else: randind = np.random.permutation(Ntrain) centroids = x_train[randind[0:M1], :] eta1_R0 = [] eta20 = [] for d in range(Dout1): eta1_R0.append(np.random.randn(M1*(M1+1)//2, )) eta20.append(np.random.randn(M1, )) params['eta1_R'].append(eta1_R0) params['eta2'].append(eta20) if self.zu_tied: zu0 = centroids else: zu0 = [] for d in range(Dout1): zu0.append(centroids) params['zu'].append(zu0) # other layers for i in range(1, self.no_layers): Mi = self.no_pseudos[i] Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] sfi = np.log(np.array([1])) sni = np.log(np.array([0.1])) lsi = np.ones((Dini, )) params['sf'].append(sfi) params['ls'].append(lsi) if i != self.no_layers-1: params['sn'].append(sni) else: # TODO params['sn'].append(0) if self.zu_tied: zui = np.tile(np.linspace(-1, 1, Mi).reshape((Mi, 1)), (1, Dini)) else: zui = [] for d in range(Douti): zuii = np.tile(np.linspace(-1, 1, Mi).reshape((Mi, 1)), (1, Dini)) zui.append(zuii) params['zu'].append(zui) eta1_Ri = [] eta2i = [] for d in range(Douti): eta1_Ri.append(np.random.randn(Mi*(Mi+1)//2, ) / 10) eta2i.append(np.random.randn(Mi, ) / 10) params['eta1_R'].append(eta1_Ri) params['eta2'].append(eta2i) return params def get_hypers(self): params = {'ls': [], 'sf': [], 'zu': [], 'sn': [], 'eta1_R': [], 'eta2': []} for i in range(self.no_layers): Mi = self.no_pseudos[i] Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] params['ls'].append(self.ls[i]) params['sf'].append(self.sf[i]) if not (self.no_output_noise and (i == self.no_layers-1)): params['sn'].append(self.sn[i]) triu_ind = np.triu_indices(Mi) diag_ind = np.diag_indices(Mi) params_zu_i = [] params_eta2_i = [] params_eta1_Ri = [] if self.zu_tied: params_zu_i = self.zu[i] else: for d in range(Douti): params_zu_i.append(self.zu[i][d]) for d in range(Douti): params_eta2_i.append(self.theta_2[i][d]) Rd = self.theta_1_R[i][d] Rd[diag_ind] = np.log(Rd[diag_ind]) params_eta1_Ri.append(Rd[triu_ind].reshape((Mi*(Mi+1)/2,))) params['zu'].append(params_zu_i) params['eta1_R'].append(params_eta1_Ri) params['eta2'].append(params_eta2_i) return params def estimate_ls(self, X): Ntrain = X.shape[0] if Ntrain < 10000: X1 = np.copy(X) else: randind = np.random.permutation(Ntrain) X1 = X[randind[0:(5*self.no_pseudos[0])], :] # d2 = compute_distance_matrix(X1) D = X1.shape[1] N = X1.shape[0] triu_ind = np.triu_indices(N) ls = np.zeros((D, )) for i in range(D): X1i = np.reshape(X1[:, i], (N, 1)) d2i = cdist(X1i, X1i, 'euclidean') # d2i = d2[:, :, i] d2imed = np.median(d2i[triu_ind]) # d2imed = 0.01 # print d2imed, ls[i] = np.log(d2imed + 1e-16) return ls def estimate_ls_temp(self, X): Ntrain = X.shape[0] if Ntrain < 10000: X1 = np.copy(X) else: randind = np.random.permutation(Ntrain) X1 = X[randind[0:(5*self.no_pseudos[0])], :] dist = cdist(X1, X1, 'euclidean') # diff = X1[:, None, :] - X1[None, :, :] # dist = np.sum(abs(diff), axis=2) D = X1.shape[1] N = X1.shape[0] triu_ind = np.triu_indices(N) ls = np.zeros((D, )) d2imed = np.median(dist[triu_ind]) for i in range(D): ls[i] = np.log(d2imed + 1e-16) return ls def update_hypers(self, params): for i in range(self.no_layers): Mi = self.no_pseudos[i] Dini = self.layer_sizes[i] Douti = self.layer_sizes[i+1] self.ls[i] = params['ls'][i] self.ones_M_ls[i] = np.outer(self.ones_M[i], 1.0 / np.exp(2*self.ls[i])) self.sf[i] = params['sf'][i] if not ((self.no_output_noise) and (i == self.no_layers-1)): self.sn[i] = params['sn'][i] triu_ind = np.triu_indices(Mi) diag_ind = np.diag_indices(Mi) if self.zu_tied: zi = params['zu'][i] self.zu[i] = zi else: for d in range(Douti): zid = params['zu'][i][d] self.zu[i][d] = zid for d in range(Douti): theta_m_d = params['eta2'][i][d] theta_R_d = params['eta1_R'][i][d] R = np.zeros((Mi, Mi)) R[triu_ind] = theta_R_d.reshape(theta_R_d.shape[0], ) R[diag_ind] = np.exp(R[diag_ind]) self.theta_1_R[i][d] = R self.theta_1[i][d] = np.dot(R.T, R) self.theta_2[i][d] = theta_m_d
[ "scipy.linalg.solve", "numpy.sum", "numpy.argmax", "numpy.ones", "numpy.exp", "numpy.copy", "numpy.random.randn", "numpy.std", "numpy.reshape", "numpy.linspace", "scipy.spatial.distance.cdist", "numpy.median", "numpy.triu_indices", "numpy.diag_indices", "scipy.cluster.vq.kmeans2", "num...
[((6165, 6183), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (6173, 6183), True, 'import numpy as np\n'), ((6201, 6219), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (6209, 6219), True, 'import numpy as np\n'), ((6267, 6285), 'numpy.exp', 'np.exp', (['(2.0 * sf_i)'], {}), '(2.0 * sf_i)\n', (6273, 6285), True, 'import numpy as np\n'), ((9035, 9056), 'numpy.zeros', 'np.zeros', (['(1, Dout_i)'], {}), '((1, Dout_i))\n', (9043, 9056), True, 'import numpy as np\n'), ((9074, 9095), 'numpy.zeros', 'np.zeros', (['(1, Dout_i)'], {}), '((1, Dout_i))\n', (9082, 9095), True, 'import numpy as np\n'), ((9143, 9161), 'numpy.exp', 'np.exp', (['(2.0 * sf_i)'], {}), '(2.0 * sf_i)\n', (9149, 9161), True, 'import numpy as np\n'), ((11157, 11172), 'numpy.exp', 'np.exp', (['(2 * lsi)'], {}), '(2 * lsi)\n', (11163, 11172), True, 'import numpy as np\n'), ((11186, 11203), 'numpy.exp', 'np.exp', (['(2.0 * sfi)'], {}), '(2.0 * sfi)\n', (11192, 11203), True, 'import numpy as np\n'), ((11218, 11236), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (11226, 11236), True, 'import numpy as np\n'), ((11253, 11271), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (11261, 11271), True, 'import numpy as np\n'), ((29376, 29387), 'numpy.log', 'np.log', (['(0.1)'], {}), '(0.1)\n', (29382, 29387), True, 'import numpy as np\n'), ((32037, 32048), 'numpy.log', 'np.log', (['(0.1)'], {}), '(0.1)\n', (32043, 32048), True, 'import numpy as np\n'), ((34483, 34494), 'numpy.log', 'np.log', (['(0.1)'], {}), '(0.1)\n', (34489, 34494), True, 'import numpy as np\n'), ((38437, 38455), 'numpy.triu_indices', 'np.triu_indices', (['N'], {}), '(N)\n', (38452, 38455), True, 'import numpy as np\n'), ((38469, 38483), 'numpy.zeros', 'np.zeros', (['(D,)'], {}), '((D,))\n', (38477, 38483), True, 'import numpy as np\n'), ((39060, 39086), 'scipy.spatial.distance.cdist', 'cdist', (['X1', 'X1', '"""euclidean"""'], {}), "(X1, X1, 'euclidean')\n", (39065, 39086), False, 'from scipy.spatial.distance import cdist\n'), ((39247, 39265), 'numpy.triu_indices', 'np.triu_indices', (['N'], {}), '(N)\n', (39262, 39265), True, 'import numpy as np\n'), ((39279, 39293), 'numpy.zeros', 'np.zeros', (['(D,)'], {}), '((D,))\n', (39287, 39293), True, 'import numpy as np\n'), ((39312, 39337), 'numpy.median', 'np.median', (['dist[triu_ind]'], {}), '(dist[triu_ind])\n', (39321, 39337), True, 'import numpy as np\n'), ((702, 713), 'numpy.ones', 'np.ones', (['Mi'], {}), '(Mi)\n', (709, 713), True, 'import numpy as np\n'), ((759, 770), 'numpy.ones', 'np.ones', (['Di'], {}), '(Di)\n', (766, 770), True, 'import numpy as np\n'), ((6367, 6391), 'numpy.exp', 'np.exp', (['(2.0 * self.sn[0])'], {}), '(2.0 * self.sn[0])\n', (6373, 6391), True, 'import numpy as np\n'), ((6829, 6846), 'numpy.dot', 'np.dot', (['Bid', 'psi1'], {}), '(Bid, psi1)\n', (6835, 6846), True, 'import numpy as np\n'), ((7477, 7495), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (7485, 7495), True, 'import numpy as np\n'), ((7517, 7535), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (7525, 7535), True, 'import numpy as np\n'), ((7591, 7609), 'numpy.exp', 'np.exp', (['(2.0 * sf_i)'], {}), '(2.0 * sf_i)\n', (7597, 7609), True, 'import numpy as np\n'), ((9243, 9267), 'numpy.exp', 'np.exp', (['(2.0 * self.sn[i])'], {}), '(2.0 * self.sn[i])\n', (9249, 9267), True, 'import numpy as np\n'), ((9721, 9738), 'numpy.dot', 'np.dot', (['Bid', 'psi1'], {}), '(Bid, psi1)\n', (9727, 9738), True, 'import numpy as np\n'), ((11514, 11538), 'numpy.exp', 'np.exp', (['(2.0 * self.sn[0])'], {}), '(2.0 * self.sn[0])\n', (11520, 11538), True, 'import numpy as np\n'), ((12040, 12060), 'numpy.dot', 'np.dot', (['Bhatid', 'psi1'], {}), '(Bhatid, psi1)\n', (12046, 12060), True, 'import numpy as np\n'), ((13143, 13163), 'numpy.outer', 'np.outer', (['psi1', 'psi1'], {}), '(psi1, psi1)\n', (13151, 13163), True, 'import numpy as np\n'), ((14303, 14320), 'numpy.exp', 'np.exp', (['(2.0 * sfi)'], {}), '(2.0 * sfi)\n', (14309, 14320), True, 'import numpy as np\n'), ((14339, 14357), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (14347, 14357), True, 'import numpy as np\n'), ((14378, 14396), 'numpy.zeros', 'np.zeros', (['(Douti,)'], {}), '((Douti,))\n', (14386, 14396), True, 'import numpy as np\n'), ((21190, 21238), 'numpy.reshape', 'np.reshape', (['dlogZ_dmlast', '[self.layer_sizes[-1]]'], {}), '(dlogZ_dmlast, [self.layer_sizes[-1]])\n', (21200, 21238), True, 'import numpy as np\n'), ((21267, 21315), 'numpy.reshape', 'np.reshape', (['dlogZ_dvlast', '[self.layer_sizes[-1]]'], {}), '(dlogZ_dvlast, [self.layer_sizes[-1]])\n', (21277, 21315), True, 'import numpy as np\n'), ((23623, 23642), 'numpy.zeros', 'np.zeros', (['(1, Dini)'], {}), '((1, Dini))\n', (23631, 23642), True, 'import numpy as np\n'), ((23673, 23692), 'numpy.zeros', 'np.zeros', (['(1, Dini)'], {}), '((1, Dini))\n', (23681, 23692), True, 'import numpy as np\n'), ((28951, 28987), 'scipy.cluster.vq.kmeans2', 'kmeans2', (['x_train', 'M1'], {'minit': '"""points"""'}), "(x_train, M1, minit='points')\n", (28958, 28987), False, 'from scipy.cluster.vq import vq, kmeans2\n'), ((29024, 29053), 'numpy.random.permutation', 'np.random.permutation', (['Ntrain'], {}), '(Ntrain)\n', (29045, 29053), True, 'import numpy as np\n'), ((30362, 30378), 'numpy.ones', 'np.ones', (['(Dini,)'], {}), '((Dini,))\n', (30369, 30378), True, 'import numpy as np\n'), ((31643, 31679), 'scipy.cluster.vq.kmeans2', 'kmeans2', (['x_train', 'M1'], {'minit': '"""points"""'}), "(x_train, M1, minit='points')\n", (31650, 31679), False, 'from scipy.cluster.vq import vq, kmeans2\n'), ((31716, 31745), 'numpy.random.permutation', 'np.random.permutation', (['Ntrain'], {}), '(Ntrain)\n', (31737, 31745), True, 'import numpy as np\n'), ((32987, 33003), 'numpy.ones', 'np.ones', (['(Dini,)'], {}), '((Dini,))\n', (32994, 33003), True, 'import numpy as np\n'), ((34915, 34951), 'scipy.cluster.vq.kmeans2', 'kmeans2', (['x_train', 'M1'], {'minit': '"""points"""'}), "(x_train, M1, minit='points')\n", (34922, 34951), False, 'from scipy.cluster.vq import vq, kmeans2\n'), ((34988, 35017), 'numpy.random.permutation', 'np.random.permutation', (['Ntrain'], {}), '(Ntrain)\n', (35009, 35017), True, 'import numpy as np\n'), ((35805, 35821), 'numpy.ones', 'np.ones', (['(Dini,)'], {}), '((Dini,))\n', (35812, 35821), True, 'import numpy as np\n'), ((37317, 37336), 'numpy.triu_indices', 'np.triu_indices', (['Mi'], {}), '(Mi)\n', (37332, 37336), True, 'import numpy as np\n'), ((37360, 37379), 'numpy.diag_indices', 'np.diag_indices', (['Mi'], {}), '(Mi)\n', (37375, 37379), True, 'import numpy as np\n'), ((38188, 38198), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (38195, 38198), True, 'import numpy as np\n'), ((38235, 38264), 'numpy.random.permutation', 'np.random.permutation', (['Ntrain'], {}), '(Ntrain)\n', (38256, 38264), True, 'import numpy as np\n'), ((38530, 38558), 'numpy.reshape', 'np.reshape', (['X1[:, i]', '(N, 1)'], {}), '(X1[:, i], (N, 1))\n', (38540, 38558), True, 'import numpy as np\n'), ((38577, 38605), 'scipy.spatial.distance.cdist', 'cdist', (['X1i', 'X1i', '"""euclidean"""'], {}), "(X1i, X1i, 'euclidean')\n", (38582, 38605), False, 'from scipy.spatial.distance import cdist\n'), ((38659, 38683), 'numpy.median', 'np.median', (['d2i[triu_ind]'], {}), '(d2i[triu_ind])\n', (38668, 38683), True, 'import numpy as np\n'), ((38761, 38783), 'numpy.log', 'np.log', (['(d2imed + 1e-16)'], {}), '(d2imed + 1e-16)\n', (38767, 38783), True, 'import numpy as np\n'), ((38910, 38920), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (38917, 38920), True, 'import numpy as np\n'), ((38957, 38986), 'numpy.random.permutation', 'np.random.permutation', (['Ntrain'], {}), '(Ntrain)\n', (38978, 38986), True, 'import numpy as np\n'), ((39385, 39407), 'numpy.log', 'np.log', (['(d2imed + 1e-16)'], {}), '(d2imed + 1e-16)\n', (39391, 39407), True, 'import numpy as np\n'), ((39929, 39948), 'numpy.triu_indices', 'np.triu_indices', (['Mi'], {}), '(Mi)\n', (39944, 39948), True, 'import numpy as np\n'), ((39972, 39991), 'numpy.diag_indices', 'np.diag_indices', (['Mi'], {}), '(Mi)\n', (39987, 39991), True, 'import numpy as np\n'), ((3294, 3311), 'numpy.zeros', 'np.zeros', (['[Din_l]'], {}), '([Din_l])\n', (3302, 3311), True, 'import numpy as np\n'), ((4484, 4514), 'numpy.linalg.slogdet', 'np.linalg.slogdet', (['self.Kuu[i]'], {}), '(self.Kuu[i])\n', (4501, 4514), True, 'import numpy as np\n'), ((4892, 4918), 'numpy.linalg.slogdet', 'np.linalg.slogdet', (['Sud_val'], {}), '(Sud_val)\n', (4909, 4918), True, 'import numpy as np\n'), ((5497, 5526), 'numpy.linalg.slogdet', 'np.linalg.slogdet', (['Suhatd_val'], {}), '(Suhatd_val)\n', (5514, 5526), True, 'import numpy as np\n'), ((6787, 6804), 'numpy.dot', 'np.dot', (['psi1', 'Aid'], {}), '(psi1, Aid)\n', (6793, 6804), True, 'import numpy as np\n'), ((6873, 6897), 'numpy.dot', 'np.dot', (['psi1.T', 'Bid_psi1'], {}), '(psi1.T, Bid_psi1)\n', (6879, 6897), True, 'import numpy as np\n'), ((7703, 7727), 'numpy.exp', 'np.exp', (['(2.0 * self.sn[i])'], {}), '(2.0 * self.sn[i])\n', (7709, 7727), True, 'import numpy as np\n'), ((8426, 8435), 'numpy.sum', 'np.sum', (['J'], {}), '(J)\n', (8432, 8435), True, 'import numpy as np\n'), ((9679, 9696), 'numpy.dot', 'np.dot', (['psi1', 'Aid'], {}), '(psi1, Aid)\n', (9685, 9696), True, 'import numpy as np\n'), ((9765, 9789), 'numpy.dot', 'np.dot', (['psi1.T', 'Bid_psi1'], {}), '(psi1.T, Bid_psi1)\n', (9771, 9789), True, 'import numpy as np\n'), ((11992, 12012), 'numpy.dot', 'np.dot', (['psi1', 'Ahatid'], {}), '(psi1, Ahatid)\n', (11998, 12012), True, 'import numpy as np\n'), ((12087, 12114), 'numpy.dot', 'np.dot', (['psi1.T', 'Bhatid_psi1'], {}), '(psi1.T, Bhatid_psi1)\n', (12093, 12114), True, 'import numpy as np\n'), ((12504, 12525), 'numpy.outer', 'np.outer', (['ones_Mi', 'mx'], {}), '(ones_Mi, mx)\n', (12512, 12525), True, 'import numpy as np\n'), ((12859, 12891), 'numpy.outer', 'np.outer', (['(psi1 * Ahatid)', 'ones_Di'], {}), '(psi1 * Ahatid, ones_Di)\n', (12867, 12891), True, 'import numpy as np\n'), ((14669, 14693), 'numpy.exp', 'np.exp', (['(2.0 * self.sn[i])'], {}), '(2.0 * self.sn[i])\n', (14675, 14693), True, 'import numpy as np\n'), ((15649, 15658), 'numpy.sum', 'np.sum', (['J'], {}), '(J)\n', (15655, 15658), True, 'import numpy as np\n'), ((16094, 16109), 'numpy.exp', 'np.exp', (['(2 * lsi)'], {}), '(2 * lsi)\n', (16100, 16109), True, 'import numpy as np\n'), ((16415, 16437), 'numpy.dot', 'np.dot', (['psi1', 'Kuuinvid'], {}), '(psi1, Kuuinvid)\n', (16421, 16437), True, 'import numpy as np\n'), ((19994, 20012), 'numpy.dot', 'np.dot', (['ones_Mi', 'J'], {}), '(ones_Mi, J)\n', (20000, 20012), True, 'import numpy as np\n'), ((21597, 21612), 'numpy.log', 'np.log', (['(Z + eps)'], {}), '(Z + eps)\n', (21603, 21612), True, 'import numpy as np\n'), ((21894, 21923), 'numpy.reshape', 'np.reshape', (['dlogZ_dmlast', '[1]'], {}), '(dlogZ_dmlast, [1])\n', (21904, 21923), True, 'import numpy as np\n'), ((21952, 21981), 'numpy.reshape', 'np.reshape', (['dlogZ_dvlast', '[1]'], {}), '(dlogZ_dvlast, [1])\n', (21962, 21981), True, 'import numpy as np\n'), ((24317, 24353), 'numpy.reshape', 'np.reshape', (["dlogZ_din['mx']", '(Dini,)'], {}), "(dlogZ_din['mx'], (Dini,))\n", (24327, 24353), True, 'import numpy as np\n'), ((24389, 24425), 'numpy.reshape', 'np.reshape', (["dlogZ_din['vx']", '(Dini,)'], {}), "(dlogZ_din['vx'], (Dini,))\n", (24399, 24425), True, 'import numpy as np\n'), ((26066, 26091), 'numpy.dot', 'np.dot', (['Shat', 'ShatinvMhat'], {}), '(Shat, ShatinvMhat)\n', (26072, 26091), True, 'import numpy as np\n'), ((26166, 26188), 'numpy.dot', 'np.dot', (['Kuuinvid', 'mhat'], {}), '(Kuuinvid, mhat)\n', (26172, 26188), True, 'import numpy as np\n'), ((27088, 27104), 'numpy.dot', 'np.dot', (['S', 'SinvM'], {}), '(S, SinvM)\n', (27094, 27104), True, 'import numpy as np\n'), ((27896, 27912), 'numpy.dot', 'np.dot', (['S', 'SinvM'], {}), '(S, SinvM)\n', (27902, 27912), True, 'import numpy as np\n'), ((27979, 27998), 'numpy.dot', 'np.dot', (['Kuuinvid', 'm'], {}), '(Kuuinvid, m)\n', (27985, 27998), True, 'import numpy as np\n'), ((29724, 29759), 'numpy.random.randn', 'np.random.randn', (['(M1 * (M1 + 1) // 2)'], {}), '(M1 * (M1 + 1) // 2)\n', (29739, 29759), True, 'import numpy as np\n'), ((29782, 29801), 'numpy.random.randn', 'np.random.randn', (['M1'], {}), '(M1)\n', (29797, 29801), True, 'import numpy as np\n'), ((30287, 30300), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (30295, 30300), True, 'import numpy as np\n'), ((30327, 30342), 'numpy.array', 'np.array', (['[0.1]'], {}), '([0.1])\n', (30335, 30342), True, 'import numpy as np\n'), ((31936, 31948), 'numpy.log', 'np.log', (['(0.01)'], {}), '(0.01)\n', (31942, 31948), True, 'import numpy as np\n'), ((31975, 31984), 'numpy.log', 'np.log', (['(1)'], {}), '(1)\n', (31981, 31984), True, 'import numpy as np\n'), ((32349, 32384), 'numpy.random.randn', 'np.random.randn', (['(M1 * (M1 + 1) // 2)'], {}), '(M1 * (M1 + 1) // 2)\n', (32364, 32384), True, 'import numpy as np\n'), ((32407, 32426), 'numpy.random.randn', 'np.random.randn', (['M1'], {}), '(M1)\n', (32422, 32426), True, 'import numpy as np\n'), ((32912, 32925), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (32920, 32925), True, 'import numpy as np\n'), ((32952, 32967), 'numpy.array', 'np.array', (['[0.1]'], {}), '([0.1])\n', (32960, 32967), True, 'import numpy as np\n'), ((34382, 34394), 'numpy.log', 'np.log', (['(0.01)'], {}), '(0.01)\n', (34388, 34394), True, 'import numpy as np\n'), ((34421, 34430), 'numpy.log', 'np.log', (['(1)'], {}), '(1)\n', (34427, 34430), True, 'import numpy as np\n'), ((35167, 35202), 'numpy.random.randn', 'np.random.randn', (['(M1 * (M1 + 1) // 2)'], {}), '(M1 * (M1 + 1) // 2)\n', (35182, 35202), True, 'import numpy as np\n'), ((35225, 35244), 'numpy.random.randn', 'np.random.randn', (['M1'], {}), '(M1)\n', (35240, 35244), True, 'import numpy as np\n'), ((35730, 35743), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (35738, 35743), True, 'import numpy as np\n'), ((35770, 35785), 'numpy.array', 'np.array', (['[0.1]'], {}), '([0.1])\n', (35778, 35785), True, 'import numpy as np\n'), ((37819, 37839), 'numpy.log', 'np.log', (['Rd[diag_ind]'], {}), '(Rd[diag_ind])\n', (37825, 37839), True, 'import numpy as np\n'), ((40388, 40406), 'numpy.zeros', 'np.zeros', (['(Mi, Mi)'], {}), '((Mi, Mi))\n', (40396, 40406), True, 'import numpy as np\n'), ((40507, 40526), 'numpy.exp', 'np.exp', (['R[diag_ind]'], {}), '(R[diag_ind])\n', (40513, 40526), True, 'import numpy as np\n'), ((40605, 40619), 'numpy.dot', 'np.dot', (['R.T', 'R'], {}), '(R.T, R)\n', (40611, 40619), True, 'import numpy as np\n'), ((1654, 1669), 'numpy.zeros', 'np.zeros', (['[M_l]'], {}), '([M_l])\n', (1662, 1669), True, 'import numpy as np\n'), ((1726, 1746), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (1734, 1746), True, 'import numpy as np\n'), ((1807, 1827), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (1815, 1827), True, 'import numpy as np\n'), ((1939, 1954), 'numpy.zeros', 'np.zeros', (['[M_l]'], {}), '([M_l])\n', (1947, 1954), True, 'import numpy as np\n'), ((2014, 2034), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (2022, 2034), True, 'import numpy as np\n'), ((2096, 2116), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (2104, 2116), True, 'import numpy as np\n'), ((2180, 2200), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (2188, 2200), True, 'import numpy as np\n'), ((2894, 2916), 'numpy.zeros', 'np.zeros', (['[M_l, Din_l]'], {}), '([M_l, Din_l])\n', (2902, 2916), True, 'import numpy as np\n'), ((2950, 2970), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (2958, 2970), True, 'import numpy as np\n'), ((3007, 3027), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (3015, 3027), True, 'import numpy as np\n'), ((3065, 3092), 'numpy.zeros', 'np.zeros', (['[Din_l, M_l, M_l]'], {}), '([Din_l, M_l, M_l])\n', (3073, 3092), True, 'import numpy as np\n'), ((3130, 3150), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (3138, 3150), True, 'import numpy as np\n'), ((3188, 3215), 'numpy.zeros', 'np.zeros', (['[Din_l, M_l, M_l]'], {}), '([Din_l, M_l, M_l])\n', (3196, 3215), True, 'import numpy as np\n'), ((3539, 3559), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (3547, 3559), True, 'import numpy as np\n'), ((3618, 3633), 'numpy.zeros', 'np.zeros', (['[M_l]'], {}), '([M_l])\n', (3626, 3633), True, 'import numpy as np\n'), ((3693, 3713), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (3701, 3713), True, 'import numpy as np\n'), ((3842, 3857), 'numpy.zeros', 'np.zeros', (['[M_l]'], {}), '([M_l])\n', (3850, 3857), True, 'import numpy as np\n'), ((3914, 3934), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (3922, 3934), True, 'import numpy as np\n'), ((3987, 4002), 'numpy.zeros', 'np.zeros', (['[M_l]'], {}), '([M_l])\n', (3995, 4002), True, 'import numpy as np\n'), ((4056, 4076), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (4064, 4076), True, 'import numpy as np\n'), ((4352, 4385), 'numpy.linalg.slogdet', 'np.linalg.slogdet', (['self.Kuu[i][d]'], {}), '(self.Kuu[i][d])\n', (4369, 4385), True, 'import numpy as np\n'), ((8353, 8370), 'numpy.dot', 'np.dot', (['psi1', 'Aid'], {}), '(psi1, Aid)\n', (8359, 8370), True, 'import numpy as np\n'), ((12553, 12576), 'numpy.outer', 'np.outer', (['psi1', 'ones_Di'], {}), '(psi1, ones_Di)\n', (12561, 12576), True, 'import numpy as np\n'), ((12628, 12649), 'numpy.dot', 'np.dot', (['Ahatid', 'temp1'], {}), '(Ahatid, temp1)\n', (12634, 12649), True, 'import numpy as np\n'), ((13491, 13528), 'numpy.outer', 'np.outer', (['(psi1 * Bhatid_psi1)', 'ones_Di'], {}), '(psi1 * Bhatid_psi1, ones_Di)\n', (13499, 13528), True, 'import numpy as np\n'), ((15570, 15590), 'numpy.dot', 'np.dot', (['psi1', 'Ahatid'], {}), '(psi1, Ahatid)\n', (15576, 15590), True, 'import numpy as np\n'), ((16879, 16900), 'numpy.outer', 'np.outer', (['ones_Mi', 'mx'], {}), '(ones_Mi, mx)\n', (16887, 16900), True, 'import numpy as np\n'), ((17218, 17253), 'numpy.outer', 'np.outer', (['ones_Mi', '(1.0 / (ls2 + vx))'], {}), '(ones_Mi, 1.0 / (ls2 + vx))\n', (17226, 17253), True, 'import numpy as np\n'), ((17284, 17316), 'numpy.outer', 'np.outer', (['(psi1 * Ahatid)', 'ones_Di'], {}), '(psi1 * Ahatid, ones_Di)\n', (17292, 17316), True, 'import numpy as np\n'), ((17861, 17886), 'numpy.outer', 'np.outer', (['ones_Mi', 'Btilde'], {}), '(ones_Mi, Btilde)\n', (17869, 17886), True, 'import numpy as np\n'), ((20179, 20209), 'numpy.outer', 'np.outer', (['ones_Mi', '(mx * Btilde)'], {}), '(ones_Mi, mx * Btilde)\n', (20187, 20209), True, 'import numpy as np\n'), ((21486, 21500), 'numpy.sqrt', 'np.sqrt', (['(1 + v)'], {}), '(1 + v)\n', (21493, 21500), True, 'import numpy as np\n'), ((21672, 21693), 'numpy.exp', 'np.exp', (['(-t ** 2.0 / 2)'], {}), '(-t ** 2.0 / 2)\n', (21678, 21693), True, 'import numpy as np\n'), ((21716, 21730), 'numpy.sqrt', 'np.sqrt', (['(1 + v)'], {}), '(1 + v)\n', (21723, 21730), True, 'import numpy as np\n'), ((22221, 22255), 'numpy.reshape', 'np.reshape', (['y', '[1, self.n_classes]'], {}), '(y, [1, self.n_classes])\n', (22231, 22255), True, 'import numpy as np\n'), ((22277, 22297), 'numpy.argmax', 'np.argmax', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (22286, 22297), True, 'import numpy as np\n'), ((22991, 23001), 'numpy.log', 'np.log', (['py'], {}), '(py)\n', (22997, 23001), True, 'import numpy as np\n'), ((23053, 23077), 'numpy.sum', 'np.sum', (['dsamples'], {'axis': '(0)'}), '(dsamples, axis=0)\n', (23059, 23077), True, 'import numpy as np\n'), ((23187, 23219), 'numpy.reshape', 'np.reshape', (['dm', '[self.n_classes]'], {}), '(dm, [self.n_classes])\n', (23197, 23219), True, 'import numpy as np\n'), ((23248, 23280), 'numpy.reshape', 'np.reshape', (['dv', '[self.n_classes]'], {}), '(dv, [self.n_classes])\n', (23258, 23280), True, 'import numpy as np\n'), ((26218, 26238), 'numpy.outer', 'np.outer', (['mhat', 'mhat'], {}), '(mhat, mhat)\n', (26226, 26238), True, 'import numpy as np\n'), ((27166, 27180), 'numpy.outer', 'np.outer', (['m', 'm'], {}), '(m, m)\n', (27174, 27180), True, 'import numpy as np\n'), ((28025, 28039), 'numpy.outer', 'np.outer', (['m', 'm'], {}), '(m, m)\n', (28033, 28039), True, 'import numpy as np\n'), ((39725, 39747), 'numpy.exp', 'np.exp', (['(2 * self.ls[i])'], {}), '(2 * self.ls[i])\n', (39731, 39747), True, 'import numpy as np\n'), ((2373, 2395), 'numpy.zeros', 'np.zeros', (['[M_l, Din_l]'], {}), '([M_l, Din_l])\n', (2381, 2395), True, 'import numpy as np\n'), ((2454, 2474), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (2462, 2474), True, 'import numpy as np\n'), ((2536, 2556), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (2544, 2556), True, 'import numpy as np\n'), ((2619, 2646), 'numpy.zeros', 'np.zeros', (['[Din_l, M_l, M_l]'], {}), '([Din_l, M_l, M_l])\n', (2627, 2646), True, 'import numpy as np\n'), ((2709, 2729), 'numpy.zeros', 'np.zeros', (['[M_l, M_l]'], {}), '([M_l, M_l])\n', (2717, 2729), True, 'import numpy as np\n'), ((2792, 2819), 'numpy.zeros', 'np.zeros', (['[Din_l, M_l, M_l]'], {}), '([Din_l, M_l, M_l])\n', (2800, 2819), True, 'import numpy as np\n'), ((13375, 13401), 'numpy.dot', 'np.dot', (['Bhatid_psi1', 'temp1'], {}), '(Bhatid_psi1, temp1)\n', (13381, 13401), True, 'import numpy as np\n'), ((16932, 16955), 'numpy.outer', 'np.outer', (['psi1', 'ones_Di'], {}), '(psi1, ones_Di)\n', (16940, 16955), True, 'import numpy as np\n'), ((18305, 18331), 'numpy.outer', 'np.outer', (['ones_Mi', 'dQtilde'], {}), '(ones_Mi, dQtilde)\n', (18313, 18331), True, 'import numpy as np\n'), ((18373, 18404), 'numpy.outer', 'np.outer', (['ones_Mi', '(dBtilde * mx)'], {}), '(ones_Mi, dBtilde * mx)\n', (18381, 18404), True, 'import numpy as np\n'), ((18442, 18468), 'numpy.outer', 'np.outer', (['ones_Mi', 'dVtilde'], {}), '(ones_Mi, dVtilde)\n', (18450, 18468), True, 'import numpy as np\n'), ((18995, 19014), 'numpy.sum', 'np.sum', (['dvoutid_dsf'], {}), '(dvoutid_dsf)\n', (19001, 19014), True, 'import numpy as np\n'), ((19412, 19438), 'numpy.outer', 'np.outer', (['ones_Mi', 'dQtilde'], {}), '(ones_Mi, dQtilde)\n', (19420, 19438), True, 'import numpy as np\n'), ((19480, 19511), 'numpy.outer', 'np.outer', (['ones_Mi', '(dBtilde * mx)'], {}), '(ones_Mi, dBtilde * mx)\n', (19488, 19511), True, 'import numpy as np\n'), ((19549, 19575), 'numpy.outer', 'np.outer', (['ones_Mi', 'dVtilde'], {}), '(ones_Mi, dVtilde)\n', (19557, 19575), True, 'import numpy as np\n'), ((20085, 20110), 'numpy.outer', 'np.outer', (['ones_Mi', 'Qtilde'], {}), '(ones_Mi, Qtilde)\n', (20093, 20110), True, 'import numpy as np\n'), ((21031, 21040), 'numpy.log', 'np.log', (['v'], {}), '(v)\n', (21037, 21040), True, 'import numpy as np\n'), ((21653, 21671), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (21660, 21671), True, 'import numpy as np\n'), ((22153, 22163), 'numpy.sqrt', 'np.sqrt', (['v'], {}), '(v)\n', (22160, 22163), True, 'import numpy as np\n'), ((23136, 23146), 'numpy.sqrt', 'np.sqrt', (['v'], {}), '(v)\n', (23143, 23146), True, 'import numpy as np\n'), ((25265, 25280), 'numpy.ones', 'np.ones', (['(M_i,)'], {}), '((M_i,))\n', (25272, 25280), True, 'import numpy as np\n'), ((27270, 27291), 'numpy.dot', 'np.dot', (['Smm', 'Kuuinvid'], {}), '(Smm, Kuuinvid)\n', (27276, 27291), True, 'import numpy as np\n'), ((29255, 29270), 'numpy.std', 'np.std', (['y_train'], {}), '(y_train)\n', (29261, 29270), True, 'import numpy as np\n'), ((29307, 29322), 'numpy.std', 'np.std', (['y_train'], {}), '(y_train)\n', (29313, 29322), True, 'import numpy as np\n'), ((30960, 30995), 'numpy.random.randn', 'np.random.randn', (['(Mi * (Mi + 1) // 2)'], {}), '(Mi * (Mi + 1) // 2)\n', (30975, 30995), True, 'import numpy as np\n'), ((31027, 31046), 'numpy.random.randn', 'np.random.randn', (['Mi'], {}), '(Mi)\n', (31042, 31046), True, 'import numpy as np\n'), ((33707, 33742), 'numpy.random.randn', 'np.random.randn', (['(Mi * (Mi + 1) // 2)'], {}), '(Mi * (Mi + 1) // 2)\n', (33722, 33742), True, 'import numpy as np\n'), ((33774, 33793), 'numpy.random.randn', 'np.random.randn', (['Mi'], {}), '(Mi)\n', (33789, 33793), True, 'import numpy as np\n'), ((36525, 36560), 'numpy.random.randn', 'np.random.randn', (['(Mi * (Mi + 1) // 2)'], {}), '(Mi * (Mi + 1) // 2)\n', (36540, 36560), True, 'import numpy as np\n'), ((36592, 36611), 'numpy.random.randn', 'np.random.randn', (['Mi'], {}), '(Mi)\n', (36607, 36611), True, 'import numpy as np\n'), ((5132, 5163), 'scipy.linalg.solve', 'spalg.solve', (['Sud_val', 'mud_val.T'], {}), '(Sud_val, mud_val.T)\n', (5143, 5163), True, 'import scipy.linalg as spalg\n'), ((5626, 5663), 'scipy.linalg.solve', 'spalg.solve', (['Suhatd_val', 'muhatd_val.T'], {}), '(Suhatd_val, muhatd_val.T)\n', (5637, 5663), True, 'import scipy.linalg as spalg\n'), ((16247, 16272), 'numpy.dot', 'np.dot', (['Ahatid_psi1', 'zuid'], {}), '(Ahatid_psi1, zuid)\n', (16253, 16272), True, 'import numpy as np\n'), ((16462, 16491), 'numpy.sum', 'np.sum', (['(psi1_Kuuinv * muhatid)'], {}), '(psi1_Kuuinv * muhatid)\n', (16468, 16491), True, 'import numpy as np\n'), ((18700, 18713), 'numpy.dot', 'np.dot', (['J', 'M3'], {}), '(J, M3)\n', (18706, 18713), True, 'import numpy as np\n'), ((18904, 18925), 'numpy.sum', 'np.sum', (['(Bhatid * psi2)'], {}), '(Bhatid * psi2)\n', (18910, 18925), True, 'import numpy as np\n'), ((19807, 19820), 'numpy.dot', 'np.dot', (['J', 'M3'], {}), '(J, M3)\n', (19813, 19820), True, 'import numpy as np\n'), ((20143, 20169), 'numpy.outer', 'np.outer', (['upsilon', 'ones_Di'], {}), '(upsilon, ones_Di)\n', (20151, 20169), True, 'import numpy as np\n'), ((23095, 23129), 'numpy.sum', 'np.sum', (['(dsamples * epsilon)'], {'axis': '(0)'}), '(dsamples * epsilon, axis=0)\n', (23101, 23129), True, 'import numpy as np\n'), ((24999, 25014), 'numpy.ones', 'np.ones', (['(M_i,)'], {}), '((M_i,))\n', (25006, 25014), True, 'import numpy as np\n'), ((26364, 26385), 'numpy.dot', 'np.dot', (['Smm', 'Kuuinvid'], {}), '(Smm, Kuuinvid)\n', (26370, 26385), True, 'import numpy as np\n'), ((26475, 26497), 'numpy.dot', 'np.dot', (['Shat', 'Kuuinvid'], {}), '(Shat, Kuuinvid)\n', (26481, 26497), True, 'import numpy as np\n'), ((28159, 28180), 'numpy.dot', 'np.dot', (['Smm', 'Kuuinvid'], {}), '(Smm, Kuuinvid)\n', (28165, 28180), True, 'import numpy as np\n'), ((28267, 28286), 'numpy.dot', 'np.dot', (['S', 'Kuuinvid'], {}), '(S, Kuuinvid)\n', (28273, 28286), True, 'import numpy as np\n'), ((30550, 30572), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'Mi'], {}), '(-1, 1, Mi)\n', (30561, 30572), True, 'import numpy as np\n'), ((33297, 33319), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'Mi'], {}), '(-1, 1, Mi)\n', (33308, 33319), True, 'import numpy as np\n'), ((36115, 36137), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'Mi'], {}), '(-1, 1, Mi)\n', (36126, 36137), True, 'import numpy as np\n'), ((17073, 17094), 'numpy.dot', 'np.dot', (['Ahatid', 'temp1'], {}), '(Ahatid, temp1)\n', (17079, 17094), True, 'import numpy as np\n'), ((17930, 17948), 'numpy.dot', 'np.dot', (['ones_Mi', 'J'], {}), '(ones_Mi, J)\n', (17936, 17948), True, 'import numpy as np\n'), ((21541, 21551), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (21548, 21551), True, 'import numpy as np\n'), ((30719, 30741), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'Mi'], {}), '(-1, 1, Mi)\n', (30730, 30741), True, 'import numpy as np\n'), ((33466, 33488), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'Mi'], {}), '(-1, 1, Mi)\n', (33477, 33488), True, 'import numpy as np\n'), ((36284, 36306), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'Mi'], {}), '(-1, 1, Mi)\n', (36295, 36306), True, 'import numpy as np\n'), ((16220, 16239), 'numpy.sum', 'np.sum', (['Ahatid_psi1'], {}), '(Ahatid_psi1)\n', (16226, 16239), True, 'import numpy as np\n'), ((18513, 18531), 'numpy.dot', 'np.dot', (['ones_Mi', 'J'], {}), '(ones_Mi, J)\n', (18519, 18531), True, 'import numpy as np\n'), ((18574, 18592), 'numpy.dot', 'np.dot', (['ones_Mi', 'J'], {}), '(ones_Mi, J)\n', (18580, 18592), True, 'import numpy as np\n'), ((19620, 19638), 'numpy.dot', 'np.dot', (['ones_Mi', 'J'], {}), '(ones_Mi, J)\n', (19626, 19638), True, 'import numpy as np\n'), ((19681, 19699), 'numpy.dot', 'np.dot', (['ones_Mi', 'J'], {}), '(ones_Mi, J)\n', (19687, 19699), True, 'import numpy as np\n'), ((20042, 20068), 'numpy.outer', 'np.outer', (['upsilon', 'ones_Di'], {}), '(upsilon, ones_Di)\n', (20050, 20068), True, 'import numpy as np\n'), ((20266, 20277), 'numpy.ones', 'np.ones', (['Mi'], {}), '(Mi)\n', (20273, 20277), True, 'import numpy as np\n'), ((16566, 16587), 'numpy.outer', 'np.outer', (['ones_Mi', 'mx'], {}), '(ones_Mi, mx)\n', (16574, 16587), True, 'import numpy as np\n')]
import torch import numpy as np def create_1toN_adj(n): a = np.zeros((n,n)) a[0].fill(1) a[:,0].fill(1) # a[0,0] = 0.0 return torch.tensor(a, requires_grad=False) def create_fc_adj(n): # return torch.ones(n,n) return torch.ones(n,n)-torch.eye(n)
[ "torch.ones", "torch.eye", "numpy.zeros", "torch.tensor" ]
[((66, 82), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (74, 82), True, 'import numpy as np\n'), ((148, 184), 'torch.tensor', 'torch.tensor', (['a'], {'requires_grad': '(False)'}), '(a, requires_grad=False)\n', (160, 184), False, 'import torch\n'), ((248, 264), 'torch.ones', 'torch.ones', (['n', 'n'], {}), '(n, n)\n', (258, 264), False, 'import torch\n'), ((264, 276), 'torch.eye', 'torch.eye', (['n'], {}), '(n)\n', (273, 276), False, 'import torch\n')]
import numpy as np import json import os import copy import math RANDOM_SEED = 626 np.random.seed(RANDOM_SEED) def demo_postprocess(QAList, selected_video_ids = [], show_shuffle = True): if QAList is None or len(QAList) == 0: print('QA List is null.') return None # select if selected_video_ids is not None and len(selected_video_ids) > 0: QAList = [qa for qa in QAList if qa['video_id'] in selected_video_ids ] # shuffle if show_shuffle: QAList = list(np.random.permutation(QAList)) # default shuffle for showing return QAList def QA_postprocess(QA,thresh,ratio,dtype,qtype,debias_type='action'): #print('{} {} QA num before debiasing: '.format(qtype, dtype),len(QA)) if dtype == 'train': qa_breaked = QA #print('{} {} QA num after debiasing: '.format(qtype, dtype),len(qa_breaked)) else: qa_breaked = debiasing(QA,thresh,ratio, qtype, dtype, debias_type) qa_breaked = debiasing(qa_breaked,0.2, 1.0, qtype, dtype, 'answer') #print('{} {} QA num after debiasing: '.format(qtype, dtype),len(qa_breaked)) #qa_breaked = breaking_shortcuts(QA,mode) #print('QA num after breaking shortcuts: ',len(qa_breaked)) #print('{} {} Down Sampling Ratio: '.format(qtype, dtype), (len(QA)-len(qa_breaked))/len(QA)) return qa_breaked def get_answer_space(QA,save_dir): train_ans_space = {} for qa in QA: qid = qa['question_id'] qtype, qtemp = qid.split('_')[0], qid.split('_')[1] answer = qa['answer'] if qtype not in train_ans_space: train_ans_space[qtype] = {} if qtemp not in train_ans_space[qtype]: train_ans_space[qtype][qtemp] = [] if answer not in train_ans_space[qtype][qtemp]: train_ans_space[qtype][qtemp].append(answer) with open(save_dir,'w') as f: f.write(json.dumps(train_ans_space)) return train_ans_space def get_answer_frequency(QA,save_dir): train_fre_space = {} for qa in QA: qid = qa['question_id'] qtype, qtemp = qid.split('_')[0], qid.split('_')[1] q_key = qa['question_keyword'] a_key = qa['answer_keyword'] if qtype not in train_fre_space: train_fre_space[qtype] = {} if qtemp not in train_fre_space[qtype]: train_fre_space[qtype][qtemp] = {} if q_key not in train_fre_space[qtype][qtemp]: train_fre_space[qtype][qtemp][q_key]={} if a_key not in train_fre_space[qtype][qtemp][q_key]: train_fre_space[qtype][qtemp][q_key][a_key] = 1 else: train_fre_space[qtype][qtemp][q_key][a_key] += 1 with open(save_dir,'w') as f: f.write(json.dumps(train_fre_space)) return train_fre_space def static_distribution(QA): # QA [list] : generated qa pairs Q2A_stat = {} answer_stat = {} action_stat = {} for qa in QA: template = qa['question_id'].split('_')[1] a_keyword = qa['answer_keyword'] q_keyword = qa['question_keyword'] answer = qa['answer'] act_id = qa['answer_action'] # for question-to-answer shortcuts if template not in Q2A_stat: Q2A_stat[template] = {} if q_keyword not in Q2A_stat[template]: Q2A_stat[template][q_keyword] = {} if a_keyword not in Q2A_stat[template][q_keyword]: Q2A_stat[template][q_keyword][a_keyword] = 1 else: Q2A_stat[template][q_keyword][a_keyword] += 1 # for answer biases if template not in answer_stat: answer_stat[template] = {} if answer not in answer_stat[template]: answer_stat[template][answer] = 1 else: answer_stat[template][answer] += 1 if template not in action_stat: action_stat[template] = {} if act_id not in action_stat[template]: action_stat[template][act_id] = 1 else: action_stat[template][act_id] += 1 return Q2A_stat,answer_stat, action_stat def shuffle_option(qa): for q in qa: question_id = int(q['question_id'].split('_')[-1]) np.random.seed(question_id) q['choices'] = list(np.random.permutation(q['choices'])) for i in range(4): q['choices'][i]['choice_id']=i return qa def group_by_vid(QA): qa_by_vid = {} vid = {} for qa in QA: if qa['video_id'] not in qa_by_vid: qa_by_vid[qa['video_id']] = [qa] else: qa_by_vid[qa['video_id']].append(qa) for v in qa_by_vid: vid[v] = len(qa_by_vid[v]) sorted_vid = sorted(vid.items(), key = lambda x:(x[1],x[0]),reverse=True) return qa_by_vid, [ id[0] for id in sorted_vid ] def entropy(statistic): num = [statistic[key] for key in statistic if statistic[key]!=0] total_num = sum(num) c = (np.array(num)/float(total_num)).tolist() result=-1; if(len(c)>0): result=0; for x in c: result+=(-x)*math.log(x,2) return result def variance(statistic): num = np.array([statistic[key] for key in statistic if statistic[key]!=0]) total_num = sum(num) return np.std(num)/total_num def extract_qa_meta(QA): extracted_qas = [] action_answer = ['Interaction_T4','Sequence_T3','Sequence_T4','Prediction_T1','Feasibility_T4','Feasibility_T6'] for qa in QA: temp_qa = {} temp_qa['question_id'] = qa['question_id'] temp_qa['question'] = qa['question'] temp_qa['answer'] = qa['answer'] temp_qa['answer_action'] =qa['answer_action'][0] temp_qa['video_id'] = qa['video_id'] temp_qa['question_keyword']=qa['question_keyword'][0] temp_qa['answer_keyword']=qa['answer_keyword'][0] qtype = qa['question_id'].split('_')[0] qtemp = qa['question_id'].split('_')[1] if qtype=='Interaction': if qtemp=='T4': temp_qa['question_keyword'] = ' '.join(qa['question_keyword']) if qtype=='Sequence': if qtemp=='T1' or qtemp=='T2' or qtemp=='T3' or qtemp=='T4': temp_qa['question_keyword'] = ' '.join(qa['question'].split(' ')[5:]) if qtemp=='T5' or qtemp=='T6': temp_qa['question_keyword'] = ' '.join(qa['question'].split(' ')[7:]) if qtype=='Prediction': if qtemp=='T1': temp_qa['question_keyword'] = 'Prediction_T1' if qtype=='Feasibility' : if qtemp=='T4': temp_qa['question_keyword'] = 'Feasibility_T4' if qtemp=='T5': temp_qa['question_keyword']= qa['question_keyword'][1] if qtemp=='T6': temp_qa['question_keyword'] = ' '.join(qa['question'].split(' ')[9:]) if qtype+'_'+qtemp in action_answer: temp_qa['answer_keyword'] = qa['answer'] extracted_qas.append(temp_qa) return extracted_qas def smooth_sample(ans_stat_, start_filter=0.25, smooth_ratio=0.95, dtype='answer',print_details=False,act_map=None): # do_filter_thred: if the answer ratio do not reach the threshold, do not down-sample to keep variaties ans_stat= copy.deepcopy(ans_stat_) sorted_ans = [item[0] for item in sorted(ans_stat.items(),key=lambda x:(x[1],x[0]))] sorted_ans_num = [item[1] for item in sorted(ans_stat.items(),key=lambda x:(x[1],x[0]))] start_filter_index = int(len(sorted_ans_num)*(1-start_filter)) # print(ans_stat_) sample_record = {} total_num = sum([ans_stat[ans] for ans in sorted_ans]) # print(total_num) sorted_ans_num_ = copy.deepcopy(sorted_ans_num) for i in range(start_filter_index, len(sorted_ans)-1): rest_num = max(int(smooth_ratio*sorted_ans_num[i]),1) sample_num = int(max(0,sorted_ans_num[i+1]-rest_num)) sample_record[sorted_ans[i+1]] = sample_num sorted_ans_num[i+1] = sorted_ans_num[i+1] - sample_num if print_details and act_map is not None: for i in range(len(sorted_ans)): if dtype == 'action': print(act_map[sorted_ans[i]],sorted_ans_num_[i],(sorted_ans_num_[i]/total_num)) else: print(sorted_ans[i],sorted_ans_num_[i],(sorted_ans_num_[i]/total_num)) print('------------------') total_num2 = sum(sorted_ans_num) for i in range(len(sorted_ans)): if dtype == 'action': print(act_map[sorted_ans[i]],sorted_ans_num[i],(sorted_ans_num[i]/total_num2)) else: print(sorted_ans[i],sorted_ans_num[i],(sorted_ans_num[i]/total_num2)) total_num2 = sum(sorted_ans_num) #print('Rest',total_num2/total_num) return sample_record def get_sample_num(QA,thresh,ratio,qtype,dtype,stype='answer'): _, answer_stat, action_stat = static_distribution(QA) #print(action_stat) sample_recorder = {} if stype=='action': sample_stat = action_stat elif stype=='answer': sample_stat = answer_stat for temp in sample_stat: stat = sample_stat[temp] sample_recorder[temp] = smooth_sample(stat,thresh,ratio) return sample_recorder def group_by_act(QA): result = {} for qa in QA: act = qa['answer_action'] ans = qa['answer'] if ans not in result: result[ans] = {} if act not in result[ans]: result[ans][act]=1 else: result[ans][act]+=1 return result # [Template1,Template2,......] # Template1: [Answer1,Answer2,......] # Answer1: [Action1,Action2,......] def sorted_by_temp_ans_act(QA,ans_act_mapping,qtype): sorted_qa = [] TEMPS = {'Interaction':{'T1':[],'T2':[],'T3':[],'T4':[]}, 'Sequence':{'T1':[],'T2':[],'T3':[],'T4':[],'T5':[],'T6':[]}, 'Prediction':{'T1':[],'T2':[],'T3':[],'T4':[]}, 'Feasibility':{'T1':[],'T2':[],'T3':[],'T4':[],'T5':[],'T6':[]}} for qa in QA: temp = qa['question_id'].split('_')[1] TEMPS[qtype][temp].append(qa) for temp in TEMPS[qtype]: split_by_ans = {} for qa in TEMPS[qtype][temp]: ans = qa['answer'] if ans not in split_by_ans: split_by_ans[ans] = [qa] else: split_by_ans[ans].append(qa) #print(split_by_ans) for ans in split_by_ans: qas = split_by_ans[ans] acts = [ [qa['answer_action'],i] for i, qa in enumerate(qas)] #print(acts) if ans in ans_act_mapping: #print('here') sorted_act = copy.deepcopy(sorted(ans_act_mapping[ans].items(), key=lambda x:x[1], reverse=True)) sorted_act_id = [item[0] for item in sorted_act] #print(sorted_act_id) qas_id = [[sorted_act_id.index(act[0]),act[1]] for act in acts] #print('ori',qas_id) sorted_qas_id = sorted(qas_id,key=lambda x:x[0]) #print('sorted',sorted_qas_id) for id in sorted_qas_id: sorted_qa.append(qas[id[1]]) else: sorted_qa.extend(qas) return sorted_qa def debiasing(QA,thresh,ratio,qtype,dtype,stype): filtered_qa = [] sample_recorder = get_sample_num(QA,thresh,ratio,qtype,dtype,stype) ans_act_mapping = group_by_act(QA) qa_by_vid, sorted_vid = group_by_vid(QA) temp_sample_count = 0 #print(sample_recorder) for vid in sorted_vid: qa_in_vid = qa_by_vid[vid] qa_in_vid = sorted_by_temp_ans_act(qa_in_vid,ans_act_mapping,qtype) for qa in qa_in_vid: if stype=='answer': #print('here1') ans = qa['answer'] temp = qa['question_id'].split('_')[1] if ans in sample_recorder[temp]: if sample_recorder[temp][ans]>0: sample_recorder[temp][ans]-=1 temp_sample_count+=1 else: filtered_qa.append(qa) else: filtered_qa.append(qa) elif stype=='action': ans = qa['answer_action'] temp = qa['question_id'].split('_')[1] if ans in sample_recorder[temp]: if sample_recorder[temp][ans]>0: sample_recorder[temp][ans]-=1 temp_sample_count+=1 continue else: filtered_qa.append(qa) else: filtered_qa.append(qa) return filtered_qa def breaking_shortcuts(QA,mode): Q2A_stat, answer_stat, action_stat = static_distribution(QA) filtered_qa = [] sample_recorder = {} #print(len(QA)) for qtemp in Q2A_stat: if qtemp not in sample_recorder: sample_recorder[qtemp] = {} que_ans = Q2A_stat[qtemp] for qkey in que_ans: if qkey not in sample_recorder[qtemp]: sample_recorder[qtemp][qkey] = {} ans = que_ans[qkey] if len(ans.keys())==1: sample_recorder[qtemp][qkey][list(ans.keys())[0]] = ans[list(ans.keys())[0]] else: total_num = sum([item[1] for item in ans.items()]) sorted_ans = sorted(ans.items(),key=lambda x:x[1],reverse=True) qa_by_vid, sorted_vid = group_by_vid(QA) temp_sample_count = 0 for vid in sorted_vid: qa_in_vid = qa_by_vid[vid] for qa in qa_in_vid: qtype = qa['question_id'].split('_')[0] qtemp = qa['question_id'].split('_')[1] q_keyword = qa['question_keyword'] a_keyword = qa['answer_keyword'] if q_keyword in sample_recorder[qtemp]: if a_keyword in sample_recorder[qtemp][q_keyword]: if sample_recorder[qtemp][q_keyword][a_keyword]>0: sample_recorder[qtemp][q_keyword][a_keyword]-=1 continue else: filtered_qa.append(qa) else: filtered_qa.append(qa) else: filtered_qa.append(qa) return filtered_qa
[ "copy.deepcopy", "numpy.random.seed", "numpy.std", "json.dumps", "numpy.array", "numpy.random.permutation", "math.log" ]
[((84, 111), 'numpy.random.seed', 'np.random.seed', (['RANDOM_SEED'], {}), '(RANDOM_SEED)\n', (98, 111), True, 'import numpy as np\n'), ((5182, 5252), 'numpy.array', 'np.array', (['[statistic[key] for key in statistic if statistic[key] != 0]'], {}), '([statistic[key] for key in statistic if statistic[key] != 0])\n', (5190, 5252), True, 'import numpy as np\n'), ((7290, 7314), 'copy.deepcopy', 'copy.deepcopy', (['ans_stat_'], {}), '(ans_stat_)\n', (7303, 7314), False, 'import copy\n'), ((7716, 7745), 'copy.deepcopy', 'copy.deepcopy', (['sorted_ans_num'], {}), '(sorted_ans_num)\n', (7729, 7745), False, 'import copy\n'), ((4251, 4278), 'numpy.random.seed', 'np.random.seed', (['question_id'], {}), '(question_id)\n', (4265, 4278), True, 'import numpy as np\n'), ((5287, 5298), 'numpy.std', 'np.std', (['num'], {}), '(num)\n', (5293, 5298), True, 'import numpy as np\n'), ((508, 537), 'numpy.random.permutation', 'np.random.permutation', (['QAList'], {}), '(QAList)\n', (529, 537), True, 'import numpy as np\n'), ((1897, 1924), 'json.dumps', 'json.dumps', (['train_ans_space'], {}), '(train_ans_space)\n', (1907, 1924), False, 'import json\n'), ((2735, 2762), 'json.dumps', 'json.dumps', (['train_fre_space'], {}), '(train_fre_space)\n', (2745, 2762), False, 'import json\n'), ((4307, 4342), 'numpy.random.permutation', 'np.random.permutation', (["q['choices']"], {}), "(q['choices'])\n", (4328, 4342), True, 'import numpy as np\n'), ((5114, 5128), 'math.log', 'math.log', (['x', '(2)'], {}), '(x, 2)\n', (5122, 5128), False, 'import math\n'), ((4985, 4998), 'numpy.array', 'np.array', (['num'], {}), '(num)\n', (4993, 4998), True, 'import numpy as np\n')]
# Initial crack at an ABM for predicting vaccine strategies for COVID-19 import numpy as np # import pandas as pd # Objects: class universe: def __init__(self, cName = "Untitled", nSize=1000): self.nSize = nSize self.cName = cName self.nDays = 0 self.nAlive = self.nSize self.nDeaths = 0 self.humans = [] i = 0 while i < self.nSize: h1 = human(i,0) self.humans.append(h1) i = i+1 def dump(self): print(f"The name of the universe is: {self.cName}") print(f"The size of our current universe is: {self.nSize}") print(f"It has been running for {self.nDays} day(s).") print(f"There are currently {self.nAlive} individuals alive.") print(f"... and {self.nDeaths} deaths have occurred") def ageReport(self): print(f"Age analysis for universe: {self.cName}:") tmp=[0,0,0,0,0] for i in range(self.nSize): if self.humans[i].age == 1: tmp[0] = tmp[0] + 1 elif self.humans[i].age == 2: tmp[1] = tmp[1] + 1 elif self.humans[i].age == 3: tmp[2] = tmp[2] + 1 elif self.humans[i].age == 4: tmp[3] = tmp[3] + 1 else: tmp[4] = tmp[4] + 1 print(f"Number age < 20: {tmp[0]}") print(f"Number age 20-39: {tmp[1]}") print(f"Number age 40-59: {tmp[2]}") print(f"Number age 60-79: {tmp[3]}") print(f"Number age >80 yr: {tmp[4]}") def updateDeaths(self): tmp = 0 for i in range(self.nSize): if self.humans[i].status == 0: tmp = tmp + 1 self.nDeaths = tmp self.nAlive = self.nSize - self.nDeaths def ageOneDay(self): # for each member of the 'universe', do the update # reset the universe stats not self.nDays = self.nDays + 1 self.updateDeaths() class human: def __init__(self, ID, age = 0, cVaccine = "P" ): self.ID = ID if age == 0: tmp = np.random.randint(12)+1 self.age=tmp if (tmp <= 2): self.age = 1 elif (tmp > 2) and tmp <= (6): self.age = 2 elif (tmp >6) and (tmp <= 9): self.age = 3 elif (tmp > 9) and (tmp <= 11): self.age = 4 else: self.age = 5 self.status = 1 # 1=alive self.dayInf = 0 # Day infected self.dayDis = 0 # Day symptoms show self.dayRecovered = 0 # calc recovery or not - adjust other values self.dayDied = 0 if cVaccine == "P": self.vaccine = vaccine() class vaccine: def __init__(self, cType="P", ): if cType=="P": self.cName = "Pfizer" self.effectiveness = [0,10,20,40,60,80,85,85,70,60,50,45,40,35,30,25,20] elif cType=="M": self.cName = "Moderna" self.effectiveness = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] else: self.cName = "AstraZeneca" self.effectiveness = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] # Test code ... if __name__ == "__main__": print(f"This is some test code for agent based COVID-19 simulation ....") vacc1 = vaccine() uni1 = universe("TestUniverse",100000 ) uni1.dump() uni1.ageOneDay() uni1.dump() uni1.ageReport() print(f"Done.")
[ "numpy.random.randint" ]
[((2137, 2158), 'numpy.random.randint', 'np.random.randint', (['(12)'], {}), '(12)\n', (2154, 2158), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Sat Mar 21 19:31:51 2020 @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import learning_curve from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris def plot_learning_curve(estimator, title, X, y, givenTrainSizes, scoring = 'accuracy', cv = None): """ Generate a simple plot of the test and training learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. title : string Title for the chart. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. scoring : string, callable or None, optional, default: None A string (see model evaluation documentation) or a scorer callable object / function with signature scorer(estimator, X, y). cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold Stratified cross-validation, - integer, to specify the number of folds for Stratified cross-validation - An object to be used as a cross-validation generator. - An iterable yielding train/test splits. givenTrainSizes : list, defines different percentages of whole train data used to evaluate learning capacity For integer/None inputs, if ``y`` is binary or multiclass, :class:`StratifiedKFold` used. If the estimator is not a classifier or if ``y`` is neither binary nor multiclass, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validators that can be used here. """ fig = plt.figure(1, figsize=(6, 6)) ax = fig.add_subplot(111) plt.title(title) plt.xlabel("Training examples") plt.ylabel("Accuracy") # read the help of learning_curve, and call learning_curve with proper paramters train_sizes, train_scores, test_scores = learning_curve(estimator,X,y, scoring=scoring, cv=cv, train_sizes=givenTrainSizes, random_state=0) train_scores_mean = np.mean(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) plt.grid() plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") for xy in zip(train_sizes, test_scores_mean): # <-- ax.annotate('%s' % round(xy[1],2), xy=xy, textcoords='data') plt.legend(loc="best") plt.show() iris = load_iris() # Determine feature matrix X and taget array Y X = iris.data[:,:2] y = iris.target basic_clf = DecisionTreeClassifier(random_state=0) title = "Learning Curves (DecisionTreeClassifier)" givenTrainSizes = np.linspace(.1, 1.0, 5) # 5-fold Stratified CV for train example with percentage of training data from # givenTrainSizes =[0.1 , 0.325, 0.55 , 0.775, 1. ] plot_learning_curve(basic_clf, title, X, y, givenTrainSizes, scoring='accuracy', cv=5)
[ "matplotlib.pyplot.title", "sklearn.datasets.load_iris", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "sklearn.tree.DecisionTreeClassifier", "matplotlib.pyplot.figure", "numpy.mean", "numpy.linspace", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "m...
[((3432, 3443), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (3441, 3443), False, 'from sklearn.datasets import load_iris\n'), ((3545, 3583), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (3567, 3583), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((3657, 3681), 'numpy.linspace', 'np.linspace', (['(0.1)', '(1.0)', '(5)'], {}), '(0.1, 1.0, 5)\n', (3668, 3681), True, 'import numpy as np\n'), ((2236, 2265), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(6, 6)'}), '(1, figsize=(6, 6))\n', (2246, 2265), True, 'import matplotlib.pyplot as plt\n'), ((2304, 2320), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2313, 2320), True, 'import matplotlib.pyplot as plt\n'), ((2326, 2357), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Training examples"""'], {}), "('Training examples')\n", (2336, 2357), True, 'import matplotlib.pyplot as plt\n'), ((2363, 2385), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Accuracy"""'], {}), "('Accuracy')\n", (2373, 2385), True, 'import matplotlib.pyplot as plt\n'), ((2529, 2634), 'sklearn.model_selection.learning_curve', 'learning_curve', (['estimator', 'X', 'y'], {'scoring': 'scoring', 'cv': 'cv', 'train_sizes': 'givenTrainSizes', 'random_state': '(0)'}), '(estimator, X, y, scoring=scoring, cv=cv, train_sizes=\n givenTrainSizes, random_state=0)\n', (2543, 2634), False, 'from sklearn.model_selection import learning_curve\n'), ((2897, 2926), 'numpy.mean', 'np.mean', (['train_scores'], {'axis': '(1)'}), '(train_scores, axis=1)\n', (2904, 2926), True, 'import numpy as np\n'), ((2951, 2979), 'numpy.mean', 'np.mean', (['test_scores'], {'axis': '(1)'}), '(test_scores, axis=1)\n', (2958, 2979), True, 'import numpy as np\n'), ((2985, 2995), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2993, 2995), True, 'import matplotlib.pyplot as plt\n'), ((3009, 3095), 'matplotlib.pyplot.plot', 'plt.plot', (['train_sizes', 'train_scores_mean', '"""o-"""'], {'color': '"""r"""', 'label': '"""Training score"""'}), "(train_sizes, train_scores_mean, 'o-', color='r', label=\n 'Training score')\n", (3017, 3095), True, 'import matplotlib.pyplot as plt\n'), ((3110, 3203), 'matplotlib.pyplot.plot', 'plt.plot', (['train_sizes', 'test_scores_mean', '"""o-"""'], {'color': '"""g"""', 'label': '"""Cross-validation score"""'}), "(train_sizes, test_scores_mean, 'o-', color='g', label=\n 'Cross-validation score')\n", (3118, 3203), True, 'import matplotlib.pyplot as plt\n'), ((3383, 3405), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (3393, 3405), True, 'import matplotlib.pyplot as plt\n'), ((3411, 3421), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3419, 3421), True, 'import matplotlib.pyplot as plt\n')]
import argparse import os import re import sys parser = argparse.ArgumentParser() parser.add_argument( "in_dir" ) parser.add_argument( "out_dir" ) parser.add_argument( "--length", type=int, default=64000 ) parser.add_argument( "--sample_rate", type=int, default=16000 ) parser.add_argument( "--pitch", type=int, default=32 ) args = parser.parse_args() import librosa import numpy as np import soundfile as sf def print_err(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) sys.stderr.flush() def splitext_all(name): m = re.match("^(.*?)((?:\.[^.]*)*)$", name) return (m.group(1), m.group(2)) def main(): try: os.makedirs(args.out_dir) except FileExistsError: # ok pass counts = {} def traverse(in_dir_path, prefix=()): for in_item_name in os.listdir(in_dir_path): in_item_path = os.path.join(in_dir_path, in_item_name) if os.path.isdir(in_item_path): traverse(in_item_path, prefix + (in_item_name,)) continue ext = os.path.splitext(in_item_name)[1].lower() if ext not in [".wav", ".aif", ".aiff", ".mp3"]: continue print_err("/".join(prefix+(in_item_name,))) prefix_str = "-".join(prefix) if prefix else "" out_identifier = re.sub(r"[^a-z0-9]+", "-", prefix_str.lower()) counts[out_identifier] = counts.setdefault(out_identifier, 0) + 1 out_file_name = "{}-{}_{}.wav".format(out_identifier, counts[out_identifier], args.pitch) out_file_path = os.path.join(args.out_dir, out_file_name) audio, sr = librosa.load(in_item_path, sr=args.sample_rate, mono=True) audio_len = len(audio) print_err(" length: {} samples".format(audio_len)) if audio_len > args.length: print_err(" will be truncated") out_audio = np.zeros(args.length, dtype=audio.dtype) copy_stop_i = min(args.length, audio_len) out_audio[:copy_stop_i] = librosa.util.normalize(audio[:copy_stop_i]) # librosa.output.write_wav(out_file_path, out_audio, sr=args.sample_rate, norm=True) sf.write(out_file_path, out_audio, args.sample_rate, subtype="PCM_16") print_err(" -> {}".format(out_file_name)) traverse(args.in_dir) def console_entry_point(): main() if __name__ == '__main__': console_entry_point()
[ "os.makedirs", "argparse.ArgumentParser", "os.path.isdir", "librosa.util.normalize", "numpy.zeros", "re.match", "librosa.load", "os.path.splitext", "soundfile.write", "sys.stderr.flush", "os.path.join", "os.listdir" ]
[((57, 82), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (80, 82), False, 'import argparse\n'), ((513, 531), 'sys.stderr.flush', 'sys.stderr.flush', ([], {}), '()\n', (529, 531), False, 'import sys\n'), ((563, 603), 're.match', 're.match', (['"""^(.*?)((?:\\\\.[^.]*)*)$"""', 'name'], {}), "('^(.*?)((?:\\\\.[^.]*)*)$', name)\n", (571, 603), False, 'import re\n'), ((661, 686), 'os.makedirs', 'os.makedirs', (['args.out_dir'], {}), '(args.out_dir)\n', (672, 686), False, 'import os\n'), ((811, 834), 'os.listdir', 'os.listdir', (['in_dir_path'], {}), '(in_dir_path)\n', (821, 834), False, 'import os\n'), ((857, 896), 'os.path.join', 'os.path.join', (['in_dir_path', 'in_item_name'], {}), '(in_dir_path, in_item_name)\n', (869, 896), False, 'import os\n'), ((907, 934), 'os.path.isdir', 'os.path.isdir', (['in_item_path'], {}), '(in_item_path)\n', (920, 934), False, 'import os\n'), ((1504, 1545), 'os.path.join', 'os.path.join', (['args.out_dir', 'out_file_name'], {}), '(args.out_dir, out_file_name)\n', (1516, 1545), False, 'import os\n'), ((1565, 1623), 'librosa.load', 'librosa.load', (['in_item_path'], {'sr': 'args.sample_rate', 'mono': '(True)'}), '(in_item_path, sr=args.sample_rate, mono=True)\n', (1577, 1623), False, 'import librosa\n'), ((1807, 1847), 'numpy.zeros', 'np.zeros', (['args.length'], {'dtype': 'audio.dtype'}), '(args.length, dtype=audio.dtype)\n', (1815, 1847), True, 'import numpy as np\n'), ((1929, 1972), 'librosa.util.normalize', 'librosa.util.normalize', (['audio[:copy_stop_i]'], {}), '(audio[:copy_stop_i])\n', (1951, 1972), False, 'import librosa\n'), ((2071, 2141), 'soundfile.write', 'sf.write', (['out_file_path', 'out_audio', 'args.sample_rate'], {'subtype': '"""PCM_16"""'}), "(out_file_path, out_audio, args.sample_rate, subtype='PCM_16')\n", (2079, 2141), True, 'import soundfile as sf\n'), ((1023, 1053), 'os.path.splitext', 'os.path.splitext', (['in_item_name'], {}), '(in_item_name)\n', (1039, 1053), False, 'import os\n')]
#!/usr/bin/python # Author: <NAME> # All rights reserved #import calendar; #import fileinput; from makeAzo import *; import math; import numpy; import os; #from pxfuncs import *; import pylab; import re; import scipy; import shutil; import subprocess; #import sys; #import time; def adjustPhase(radar_path, wavelength, width): radar_dir = "."; index = radar_path.rfind("/"); if index > -1: radar_dir = radar_path[ : index]; radar_name = radar_path[index + 1 : ]; new_radar_path = radar_dir + "/new_" + radar_name; infile = open(radar_path, "rb"); radar_unw_data = scipy.matrix(numpy.fromfile(infile,numpy.float32, -1)).reshape(int(width), -1); radar_unw_data = radar_unw_data * float(wavelength) / 4 / numpy.pi; infile.close(); radar_unw_data = scipy.matrix(radar_unw_data,scipy.float32); radar_unw_data.tofile(new_radar_path); radar_unw_data = None; return(new_radar_path); def ampcor(path, rwin, awin, search_x, search_y, wsamp, numproc): cwd = os.getcwd(); import glob; cull_paths = glob.glob(path + "/int*/*_cull.off"); for i in range(0,len(cull_paths)): cull_name = cull_paths[i].strip()[cull_paths[i].rfind("/")+1:]; cull_dir = cull_paths[i][:cull_paths[i].rfind("/")]; if not re.search("\d{6}",cull_name): continue; already_processed=False; contents=os.listdir(cull_dir); for item in contents: if re.search("azo_" + wsamp + "_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y,item) > -1: already_processed=True; break; if already_processed: print("\n***** WARNING, " + cull_dir + " contains \"" + item +"\", \"ampcor\" step already run, exiting...\n"); continue; index1 = re.search("\d{6}",cull_name).start(0); index2 = re.search("\d{6}",cull_name).end(0); index3 = re.search("\d{6}",cull_name[index2:]).start(0)+index2; index4 = re.search("\d{6}",cull_name[index2:]).end(0)+index2; date2 = cull_name[index1:index2]; date1 = cull_name[index3:index4]; slc1 = path + "/" + date1 + "/" + date1 + ".slc"; if not os.path.exists(slc1): print("\n***** ERROR, could not find \"" + date1 + ".slc\" in \"" + path + "/" + date1 + "/\"\n"); break; slc2 = path + "/" + date2 + "/" + date2 + ".slc"; if not os.path.exists(slc2): print("\n***** ERROR, could not find \"" + date2 + ".slc\" in \"" + path + "/" + date2 + "/\"\n"); break; slc1_rsc_file = open(slc1 + ".rsc","r"); while 1: line = slc1_rsc_file.readline(); if not line: break; elif line.find("WIDTH") > -1: width = line.split()[1].strip(); slc1_rsc_file.close(); amp1 = cull_dir + "/" + date1 + ".amp"; amp2 = cull_dir + "/" + date2 + ".amp"; if not os.path.exists(amp1): cmd = "\ncpx2mag_phs " + slc1 + " " + cull_dir + "/" + date1 + ".amp " + cull_dir + "/" + date1 + ".phs " + width + "\n"; cmd += "\ncp -pr " + slc1 + ".rsc " + cull_dir + "/" + date1 + ".amp.rsc\n"; cmd += "\nrm " + cull_dir + "/" + date1 + ".phs\n"; subprocess.call(cmd,shell=True); slc2_rsc_file = open(slc2 + ".rsc","r"); while 1: line = slc2_rsc_file.readline(); if not line: break; elif line.find("WIDTH") > -1: width = line.split()[1].strip(); slc2_rsc_file.close(); if not os.path.exists(amp2): cmd = "\ncpx2mag_phs " + slc2 + " " + cull_dir + "/" + date2 + ".amp " + cull_dir + "/" + date2 + ".phs " + width + "\n"; cmd += "\ncp -pr " + slc2 + ".rsc " + cull_dir + "/" + date2 + ".amp.rsc\n"; cmd += "\nrm " + cull_dir + "/" + date2 + ".phs\n"; subprocess.call(cmd,shell=True); cmd = "\ncp -pr azo_real.pl " + cull_dir + "\n"; subprocess.call(cmd,shell=True); cmd = "\ncd " + cull_dir + "\n"; cmd += "\nperl azo_real.pl " + amp2 + " " + amp1 + " " + cull_name[0:cull_name.rfind(".")] + " " + cull_name[index1:index4] + "_azo_" + wsamp + " " + rwin + " " + awin + " " + search_x + " " + search_y + " " + wsamp + " " + numproc + " &\n"; cmd += "\ncd " + cwd + "\n"; print(cmd); #subprocess.call(cmd,shell=True); return; def makeUNW(path, rwin, awin, search_x, search_y, wsamp, angle, data_type): cmd = "\nfind " + path + " -name \"*azo_" + wsamp + "_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "*.off\" -print\n"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; ampoff_paths = pipe.read().split(); pipe.close(); ampoff_dirs={}; cat_cmds={}; angles = {}; max_inc_angle = ""; min_inc_angle = ""; if data_type.lower().find("tsx") > -1: cmd = "\nfind " + path + " -name \"T*X*.xml\"\n"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; leader_file_paths = pipe.read().split(); pipe.close(); for path in leader_file_paths: date = ""; infile = open(path,"r"); for line in infile: if line.find("timeUTC") > -1: index = re.search("timeUTC>",line).end(0); year = line[index + 2 : index + 4]; month = line[index + 5 : index + 7]; day = line[index + 8 : index + 10]; date = year + month + day; elif line.find("coverageRegionMin incidenceAngle") > -1: min_inc_angle = line[re.search("\">",line).end(0) : re.search("</",line).start(0)]; elif line.find("coverageRegionMax incidenceAngle") > -1: max_inc_angle = line[re.search("\">",line).end(0) : re.search("</",line).start(0)]; infile.close(); angles[date] = str((float(max_inc_angle) + float(min_inc_angle)) / 2.); for i in range(0,len(ampoff_paths)): ampoff_dir = ampoff_paths[i].strip()[0:ampoff_paths[i].strip().rfind("/")]; if ampoff_dir not in ampoff_dirs: ampoff_dirs[ampoff_dir] = ampoff_paths[i]; cat_cmds[ampoff_dir] = "\ncat " + ampoff_paths[i]; else: cat_cmds[ampoff_dir] += " " + ampoff_paths[i]; for ampoff_dir in cat_cmds: cmd = cat_cmds[ampoff_dir]; elements = cmd.split(); if len(elements) < 3: continue; else: if not re.search("_\d\.off",elements[1]): ampoff_dirs[ampoff_dir] = elements[1]; continue; else: composite_ampoff_path = elements[1][:re.search("_\d\.off",elements[1]).start(0)] + ".off"; ampoff_dirs[ampoff_dir]=composite_ampoff_path; if os.path.exists(composite_ampoff_path): continue; cat_cmds[ampoff_dir] += " > " + composite_ampoff_path + "\n"; print("\n***** pixelTrack - step \"make_unw\" - running cat to compose ampcor results into single file...\n"); subprocess.call(cat_cmds[ampoff_dir],shell=True); for ampoff_dir in ampoff_dirs: ampoff_dir_contents = os.listdir(ampoff_dir); already_done = False; item=""; for i in range(0,len(ampoff_dir_contents)): item = ampoff_dir_contents[i]; if re.search(".*azimuth_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + str(int(rwin)/int(wsamp)) + "rlks.unw",item) or \ re.search(".*range_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + str(int(rwin)/int(wsamp)) + "rlks.unw",item): already_done=True; break; if already_done: print("\n****** \"" + item +"\" already exists in \"" + ampoff_dir + "\", make_unw step likely already done for this directory, skipping...\n"); continue; ampoff_path = ampoff_dirs[ampoff_dir]; date = ampoff_path[re.search("/\d{6}[\-_]\d{6}",ampoff_path).start(0) + 1 : re.search("/\d{6}[\-_]\d{6}", ampoff_path).start(0) + 7]; cmd = "\nls " + ampoff_path[0:ampoff_path.rfind("azo")+3]+"*.off.rsc\n"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; ampoff_rsc_paths = pipe.read().split(); pipe.close(); if len(ampoff_rsc_paths) < 1: print("\n***** WARNING, could not find any azo rsc file in \"" + amcporDir + "\", skipping these results\n"); break; ampoff_rsc_path = ampoff_rsc_paths[0]; da_p = ""; r_e = ""; p_h = ""; dr = ""; endRefSample = ""; endRefLine = ""; ampoff_rsc_file = open(ampoff_rsc_path,"r"); while 1: line = ampoff_rsc_file.readline(); if not line: break; elif line.find("RANGE_PIXEL_SIZE") > -1: dr = line.split()[1].strip(); elif line.find("FILE_LENGTH") > -1: endRefLine = line.split()[1].strip(); elif line.find("WIDTH") > -1: endRefSample = line.split()[1].strip(); elif line.find("EARTH_RADIUS") > -1: r_e = line.split()[1].strip(); elif re.search("^HEIGHT\s+",line): p_h = line.split()[1].strip(); elif line.find("AZIMUTH_PIXEL_SIZE") > -1: da_p = line.split()[1].strip(); ampoff_rsc_file.close(); if da_p == "": print("\n***** WARNING, could not find parameter \"FILE_LENGTH\" in \"" + ampoff_rsc_path[0].strip() + "\", skipping these results\n"); break; if da_p == "": print("\n***** WARNING, could not find parameter \"WIDTH\" in \"" + ampoff_rsc_path[0].strip() + "\", skipping these results\n"); break; if da_p == "": print("\n***** WARNING, could not find parameter \"AZIMUTH_PIXEL_SIZE\" in \"" + ampoff_rsc_path[0].strip() + "\", skipping these results\n"); break; if r_e == "": print("\n***** WARNING, could not find parameter \"EARTH_RADIUS\" in \"" + ampoff_rsc_path[0].strip() + "\", skipping these results\n"); break; if p_h == "": print("\n***** WARNING, could not find parameter \"HEIGHT\" in \"" + ampoff_rsc_path[0].strip() + "\", skipping these results\n"); break; if dr == "": print("\n***** WARNING, could not find parameter \"RANGE_PIXEL_SIZE\" in \"" + ampoff_rsc_path[0].strip() + "\", skipping these results\n"); break; input_angle = angle; if data_type.lower().find("tsx") > -1: input_angle = angles[date]; print("\n***** pixelTrack - step \"make_unw\" - running makeAzo in " + ampoff_dir + " to generate azimuth and range unw files ...\n"); makeAzo(ampoff_path, float(da_p), float(r_e), float(p_h), float(dr), float(input_angle), int(wsamp), int(rwin), int(awin), search_x, search_y, int(endRefSample), int(endRefLine)); cwd = os.getcwd(); if not os.path.exists(ampoff_dir+"/azimuth_" + rwin + "x" + awin + "_" + str(int(rwin)/int(wsamp)) + "rlks.unw.rsc"): date = ampoff_path[re.search("/\d{6}[\-_]\d{6}",ampoff_path).start(0)+1:re.search("/\d{6}[\-_]\d{6}",ampoff_path).start(0)+7]; cmd = ""; if not os.path.exists(ampoff_dir + "/" + date + "_" + str(int(rwin)/int(wsamp)) + "rlks.slc.rsc"): cmd += "\nlook.pl " + ampoff_dir + "/" + date + ".slc " + str(int(rwin)/int(wsamp)) + " " + str(int(awin)/int(wsamp)) + "\n"; cmd += "\ncp -p " + ampoff_dir + "/" + date + "_" + str(int(rwin)/int(wsamp)) + "rlks.slc.rsc " + ampoff_dir + "/azimuth_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + str(int(rwin)/int(wsamp)) + "rlks.unw.rsc\n"; cmd += "\ncp -p " + ampoff_dir + "/" + date + "_" + str(int(rwin)/int(wsamp)) + "rlks.slc.rsc " + ampoff_dir + "/range_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + str(int(rwin)/int(wsamp)) + "rlks.unw.rsc\n"; cmd += "\ncp -p " + ampoff_dir + "/" + date + "_" + str(int(rwin)/int(wsamp)) + "rlks.slc.rsc " + ampoff_dir + "/snr_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + str(int(rwin)/int(wsamp)) + "rlks.unw.rsc\n"; subprocess.call(cmd,shell=True); return; def beamTable(): beam_angle["ST1"] = "23.7"; beam_angle["ST2"] = "27.7"; beam_angle["ST3"] = "33.7"; beam_angle["ST4"] = "36.6"; beam_angle["ST5"] = "39.4"; beam_angle["ST6"] = "44.0"; beam_angle["ST7"] = "47.2"; beam_angle["F1"] = "38.5"; beam_angle["F2"] = "40.8"; beam_angle["F3"] = "42.9"; beam_angle["F4"] = "44.8"; beam_angle["F5"] = "46.6"; return; #def densifyAmpmag(path, date): # # if # # return; def findAzimuthPixelSize(path, date, orbit): cwd = os.getcwd(); cmd = "find " + path + " -name \"" + date + ".slc.rsc\" -print"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; slc_rsc_paths = pipe.read().split(); pipe.close(); slc_rsc_path = ""; if len(slc_rsc_paths) < 1: cmd = "find " + path + " -name \"" + date + ".raw\" -print"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; raw_paths = pipe.read().split(); pipe.close(); cmd = "find " + path + " -name \"hdr*"+date+"*.rsc\" -print"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; hdr_paths = pipe.read().split(); pipe.close(); if len(raw_paths) < 1: print("\n***** WARNING, could not find \"" + date + ".raw\", necessary to determine azimuth pixel size\n"); return "-1"; raw_path = raw_paths[0]; if not os.path.exists(raw_path + ".rsc"): print("\n***** WARNING, could not find \"" + date + ".raw.rsc\", necessary to determine azimuth pixel size\n"); return "-1"; if len(hdr_paths) < 1: print("\n***** WARNING, could not find \"hdr*" + date + "*.rsc\", necessary to determine azimuth pixel size\n"); return "-1"; hdr_path = hdr_paths[0]; cmd = "\nmkdir " + path + "/" + date + "_APS\n"; cmd += "\ncd " + path + "/" + date + "_APS\n"; cmd += "\nln -s " + raw_path + " " + raw_path[raw_path.rfind("/") + 1 : ] + "\n"; cmd += "\nln -s " + raw_path + ".rsc " + raw_path[raw_path.rfind("/") + 1 : ] + ".rsc\n"; cmd += "\nln -s " + hdr_path + " " + hdr_path[hdr_path.rfind("/") + 1 : ]+"\n"; cmd += "\ndopav.pl . . " + date + " " + date + " \"\"\n"; cmd += "\nroi_prep.pl " + date + " " + orbit + " " + date + "-" + date + "\n"; cmd += "\ncd " + cwd + "\n"; subprocess.call(cmd,shell=True); slc_rsc_path = path + "/" + date + "_APS/" + date + ".slc.rsc"; else: slc_rsc_path = slc_rsc_paths[0]; slc_rsc_file = open(slc_rsc_path,"r"); while 1: line = slc_rsc_file.readline(); if not line: break; if line.find("AZIMUTH_PIXEL_SIZE") > -1: slc_rsc_file.close(); if os.path.exists(path + "/" + date + "_APS"): shutil.rmtree(path + "/" + date + "_APS"); return line[re.search("\d+\.*\d*",line).start(0) : re.search("\d+\.*\d*",line).end(0)]; slc_rsc_file.close(); print("\n***** WARNING, unable to determine azimuth pixel size, using default value of \"5\"\n"); shutil.rmtree(path + "/" + date + "_APS"); return "-1"; def GCF(num): temp = num[0]; for i in range(len(num)-1): num1 = temp; num2 = num[i+1]; if num1 < num2: num1,num2=num2,num1; while num1 - num2: num3 = num1 - num2; num1 = max(num2,num3); num2 = min(num2,num3); temp = num1; return num1; def has_value(self, value): return value in self.values(); def LCM(num): temp = num[0]; for i in range(len(num)-1): num1 = temp; num2 = num[i+1]; t_gcf = GCF([num1,num2]); temp = t_gcf * num1/t_gcf * num2/t_gcf; return temp; def makeProcFile(path, date2, date1, angle, dem, orbit): proc_file_path = path + "/int_" + date2 + "_" + date1 + ".proc"; print(proc_file_path); if os.path.exists(proc_file_path): print("\n\"" + proc_file_path + "\" already exists, skipping\n"); return; int_path = path + "/int_" + date2 + "_" + date1; proc_file = open(proc_file_path,"w"); proc_file.write("SarDir1=" + path + "/" + date2 + "\n"); proc_file.write("SarDir2=" + path + "/" + date1 + "\n"); proc_file.write("IntDir=" + int_path + "\n"); proc_file.write("SimDir=" + int_path + "/SIM\n"); proc_file.write("GeoDir=" + int_path + "/GEO\n"); proc_file.write("flattening=orbit\n"); proc_file.write("DEM=" + dem + "\n"); proc_file.write("OrbitType=" + orbit + "\n"); proc_file.write("Rlooks_sim=1\n"); proc_file.write("Rlooks_unw=1\n"); proc_file.write("Rlooks_geo=1\n"); proc_file.write("Rlooks_int=1\n"); pixelRatio = "-1"; if re.search("\d+", angle): azimuth_pixel_size = findAzimuthPixelSize(path, date1, orbit); range_pixel_size = "-1"; if azimuth_pixel_size != "-1": cmd = "\nfind " + path + " -name \"" + date1 + ".raw.rsc\" -print\n"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; raw_rsc_paths = pipe.read().split(); pipe.close(); if len(raw_rsc_paths) > 0: raw_rsc_file = open(raw_rsc_paths[0],"r"); while 1: line = raw_rsc_file.readline(); if not line: break; if line.find("RANGE_PIXEL_SIZE") > -1: raw_rsc_file.close(); range_pixel_size = line[re.search("\d+\.*\d*",line).start(0) : re.search("\d+\.*\d*",line).end(0)]; pixel_ratio = str(round(float(range_pixel_size) / math.sin(math.radians(float(angle))) / float(azimuth_pixel_size))); pixel_ratio = pixel_ratio[0 : pixel_ratio.rfind(".")]; break; raw_rsc_file.close(); if pixel_ratio != "-1": proc_file.write("pixel_ratio=" + pixel_ratio + "\n"); proc_file.close(); def getPixelRatios(path): return; def readProcFile(path,date2,date1): procCmd = "find " + path + " -name \"*" + date2 + "*" + date1 + "*.proc\" -print"; procStream = subprocess.Popen(procCmd); procOutput = procStream.read(); procFilePath = procOutput.strip().split(); if len(procFilePath) < 1: print("\n***** ERROR, no proc file found for dates \"" + date2 + ", " + date1 + "\" in \"" + path + "\"\n"); sys.exit(); if len(procFilePath) > 1: print("\n***** WARNING, found more than one proc file for dates \"" + date2 + ", " + date1 + "\", using \"" + procFilePath[0] + "\"\n"); procStream.close(); procFile = open(procFilePath[0],"r"); procHash = {}; while 1: line = procFile.readline(); if not line: break; line = line.strip(); name = ""; value = ""; elements = line.split("="); if len(elements) < 2 or len(elements[0]) < 1 or len(elements[1]) < 1: print("\n***** ERROR, proc file line format is \"varName=varValue\", \"" + line + "\" does not conform to this format\n"); sys.exit(); procHash[elements[0]] = elements[1]; procFile.close(); return procHash; def gausshpfilt(data,kernel): padSize = numpy.size(kernel,axis=0) / 2; temp = numpy.zeros((numpy.size(data,axis=0)+2*padSize,numpy.size(data,axis=1)+2*padSize)); #fill temp with data values for i in range(padSize,numpy.size(temp,axis=0)-padSize): for j in range(padSize,numpy.size(temp,axis=1)-padSize): temp[i,j] = data[i-padSize,j-padSize]; #pad left for i in range(0,padSize): for j in range(padSize,padSize+numpy.size(data,axis=0)): temp[j,padSize-1-i] = data[j-padSize,i]; #pad top for i in range(0,padSize): for j in range(padSize,padSize+numpy.size(data,axis=1)): temp[padSize-1-i,j] = data[i,j-padSize]; #pad right for i in range(0,padSize): for j in range(padSize,padSize+numpy.size(data,axis=0)): temp[j,numpy.size(temp,axis=1)-padSize+i] = data[j-padSize,numpy.size(data,axis=1)-1-i]; #pad bottom for i in range(0,padSize): for j in range(padSize,padSize+numpy.size(data,axis=1)): temp[numpy.size(temp,axis=0)-padSize+i,j] = data[numpy.size(data,axis=0)-1-i,j-padSize]; #fill top-left corner for i in range(0,padSize): for j in range(0, padSize): temp[padSize-i-1,padSize-j-1] = int((temp[padSize-i-1,padSize-j] + temp[padSize-i,padSize-j-1]) / 2); #fill top-right corner for i in range(0,padSize): for j in range(0, padSize): temp[padSize-i-1,numpy.size(temp,axis=1)-padSize+j] = int((temp[padSize-i-1,numpy.size(temp,axis=1)-padSize+j-1] + temp[padSize-i,numpy.size(temp,axis=1)-padSize+j]) / 2); #fill bottom-right corner for i in range(0,padSize): for j in range(0, padSize): temp[numpy.size(temp,axis=0)-padSize+i,numpy.size(temp,axis=1)-padSize+j] = int((temp[numpy.size(temp,axis=0)-padSize+i,numpy.size(temp,axis=1)-padSize+j-1] + temp[numpy.size(temp,axis=0)-padSize+i-1,numpy.size(temp,axis=1)-padSize+j]) / 2); #fill bottom-left corner for i in range(0,padSize): for j in range(0, padSize): temp[numpy.size(temp,axis=0)-padSize+i,padSize-j-1] = (temp[numpy.size(temp,axis=0)-padSize+i,padSize-j] + temp[numpy.size(temp,axis=0)-padSize+i-1,padSize-j-1]) / 2; #perform convolution ghp_data = numpy.zeros((numpy.size(data,axis=0),numpy.size(data,axis=1))); for i in range(numpy.size(ghp_data,axis=0)): for j in range(numpy.size(ghp_data,axis=1)): ghp_data[i,j] = numpy.sum(kernel*temp[i:i+numpy.size(kernel,axis=0),j:j+numpy.size(kernel,axis=1)]); return ghp_data; def geocode(path, rwin, awin, search_x, search_y, wsamp, orbit, dem_path): import fnmatch; cwd = os.getcwd(); azo_unw_paths = []; for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, "*.unw"): if re.search("r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + str(int(rwin) / int(wsamp)), filename): azo_unw_paths.append(root + "/" + filename); ld_range = str(int(rwin) / int(wsamp)); ld_azimuth = str(int(awin) / int(wsamp)); for azo_unw_path in azo_unw_paths: index = re.search("\d{6}_\d{6}", azo_unw_path).start(0); later_date = azo_unw_path[index : index + 6]; early_date = azo_unw_path[index + 7 : index + 13]; print(azo_unw_path); azo_unw_dir = "."; index = azo_unw_path.rfind("/"); if index > -1: azo_unw_dir = azo_unw_path[ : index]; azo_unw_name = azo_unw_path[index + 1 : ]; os.chdir(azo_unw_dir); geo_unw = "geo_" + azo_unw_name[ : azo_unw_name.find("_")] + "_" + later_date + "-" + early_date + "_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + ld_range + "rlks.unw"; if os.path.exists(geo_unw): print("\n**** WARNING, \"" + geo_unw + "\" already exists in \"" + azo_unw_dir + "\", skipping " + azo_unw_name + "...\n"); elif geo_unw.find("range") > -1 and os.path.exists(geo_unw.replace("range", "adj_range")): print("\n**** WARNING, \"" + geo_unw.replace("range", "adj_range") + "\" already exists in \"" + azo_unw_dir + "\", skipping " + azo_unw_name + "...\n"); radar_name = "radar_" + orbit + ".unw"; radar_rsc_name = radar_name + ".rsc"; if not os.path.exists(radar_name): print("\n**** WARNING, \"" + radar_name + "\" not found in \"" + azo_unw_dir + "\", skipping range ramp-removal for this pair...\n"); if not os.path.exists(radar_rsc_name): print("\n***** WARNING, \"" + radar_rsc_name + "\" not found in \"" + azo_unw_dir + "\", skipping range ramp-removal for this pair...\n"); if re.search("^blalbalbrange", azo_unw_name) and os.path.exists(radar_name) and os.path.exists(radar_name + ".rsc"): cmd = "\nlook.pl " + radar_name + " " + ld_range + " " + ld_azimuth + "\n"; subprocess.call(cmd, shell=True); radar_ld_name = "radar_" + orbit + "_" + ld_range + "rlks"; radar_ld_unw = "radar_" + orbit + "_" + ld_range + "rlks.unw"; width = ""; wavelength = ""; radar_rsc_file = open(radar_ld_unw + ".rsc", "r"); while 1: line = radar_rsc_file.readline(); if not line: break; if line.find("WIDTH") > -1: elements = line.split(); width = elements[1]; if line.find("WAVELENGTH") > -1: elements = line.split(); wavelength = elements[1]; radar_rsc_file.close(); if width == "": print("\n***** WARNING, could not find \"WIDTH\" in \"" + radar_ld_unw + ".rsc\", skipping range ramp-removal for \"" + azo_unw_dir + "\"...\n"); continue; if wavelength == "": print("\n***** WARNING, could not find \"WAVELENGTH\" in \"" + radar_ld_unw + ".rsc\", skipping range ramp-removal for \"" + azo_unw_dir + "\"...\n"); continue; cmd = "\nrmg2mag_phs " + radar_ld_unw + " " + radar_ld_name + ".mag " + radar_ld_name + ".phs " + width + "\n"; subprocess.call(cmd, shell=True); adj_radar_ld_phs = adjustPhase(radar_ld_name + ".phs", str(100 * float(wavelength)), width); cmd = "\nmag_phs2rmg " + radar_ld_name + ".mag " + adj_radar_ld_phs + " " + radar_ld_unw + " " + width + "\n"; subprocess.call(cmd, shell=True); adj_range_unw_name = "adj_" + azo_unw_name; cmd = "\nadd_rmg.pl " + azo_unw_name + " " + radar_ld_unw + " " + adj_range_unw_name + " -1 1\n"; subprocess.call(cmd, shell=True); azo_unw_name = adj_range_unw_name; cmd = ""; if not os.path.exists(azo_unw_dir + "/" + later_date + "_" + ld_range + "rlks.slc.rsc"): cmd += "\nlook.pl " + later_date + ".slc " + ld_range + " " + ld_azimuth + "\n"; cmd += "\ncp -pr " + later_date + "_" + ld_range + "rlks.slc.rsc " + azo_unw_path + ".rsc\n"; cmd += "\nmake_geomap.pl ./GEO " + azo_unw_name + " azm.trans " + orbit + " " + dem_path + " " + later_date + "-" + early_date + "_SIM.aff " + ld_range + " " + later_date + " yes ../SIM\n"; cmd += "\ngeocode.pl ./GEO/azm.trans " + azo_unw_name + " geo_" + azo_unw_name[ : azo_unw_name.find("_")] + "_" + later_date + "-" + early_date + "_r" + rwin + "x" + awin + "_s" + search_x + "x" + search_y + "_" + ld_range + "rlks.unw\n"; subprocess.call(cmd,shell=True); os.chdir(cwd); return; def generateProfiles(path): currentDir = os.getcwd(); profilesCmd = "find " + path + " -name \"*.distance\" -print"; profilesStream = subprocess.Popen(profilesCmd); profilesOutput = profilesStream.read(); profilesStream.close(); profiles = profilesOutput.split(); xyzCmd = "find " + path + " -name \"northxyz.txt\" -print"; xyzStream = subprocess.Popen(xyzCmd); xyzOutput = xyzStream.read(); xyzStream.close(); xyzCmd = "find " + path + " -name \"eastxyz.txt\" -print"; xyzStream = subprocess.Popen(xyzCmd); xyzOutput = xyzOutput + xyzStream.read(); xyzStream.close(); xyzCmd = "find " + path + " -name \"magxyz.txt\" -print"; xyzStream = subprocess.Popen(xyzCmd); xyzOutput = xyzOutput + xyzStream.read(); xyzStream.close(); xyzFileList = xyzOutput.split(); for i in range(0,len(xyzFileList)): xyzPath = xyzFileList[i].strip()[0:xyzFileList[i].strip().rfind("/")]; xyzFileName = xyzFileList[i].strip()[xyzFileList[i].strip().rfind("/")+1:]; xyzName = xyzFileName[0:xyzFileName.find(".")]; gridCmd = ""; if not os.path.exists(xyzPath + "/" + xyzName + ".grd"): gridCmd = gridCmd + "\npython grid.py " + xyzFileList[i].strip() + "\n"; gridCmdStream = subprocess.Popen(gridCmd); gridCmdOutput = gridCmdStream.read(); gridCmdStream.close(); #for i in range(0,len(profiles)): # genProfileCmd = "\ncd " + xyzPath + "\ngrdtrack " + profiles[i] + " -G" + xyzName + ".grd > " + profiles[i][profiles[i].rfind("/")+1:profiles[i].find(".")] + "_" + xyzName + ".txt\ncd " + currentDir + "\n"; # print(genProfileCmd); #genProfileStream = subprocess.Popen(genProfileCmd); #genProfileStream.close(); def generatePNGs(path): currentDir = os.getcwd(); findGRDsCmd = "find " + path + " -name \"*.grd\" -print"; findGRDsStream = subprocess.Popen(findGRDsCmd); findGRDsOutput = findGRDsStream.read().split(); findGRDsStream.close(); pngCmd = ""; for i in range(0,len(findGRDsOutput)): psName = findGRDsOutput[i][0:findGRDsOutput[i].rfind(".")] + ".ps"; psPath = findGRDsOutput[i][0:findGRDsOutput[i].rfind("/")]; pngName = findGRDsOutput[i][0:findGRDsOutput[i].rfind(".")] + ".png"; if os.path.exists(psName) and not os.path.exists(pngName): pngCmd += "\ncd " + psPath + "\nps2raster -A -TG " + psName + "\ncd " + currentDir + "\n"; if pngCmd != "": pngStream = subprocess.Popen(pngCmd); pngStream.close(); def getAffineTrans(path): cwd = os.getcwd(); contents = os.listdir(path); proc_paths = [item for item in contents if ".proc" in item]; if len(proc_paths) < 1: print("\n***** WARNING, no *.proc files found in " + path + ", not running \"affine\" step...\n"); return; cmd = ""; for proc_path in proc_paths: int_vars = readIntProcFile(proc_path); date1 = int_vars["SarDir1"]; date2 = int_vars["SarDir2"]; int_dir = int_vars["IntDir"]; rlooks = int_vars["Rlooks_geo"]; aff_path = path + "/" + int_dir + "/" + date1 + "-" + date2 + "_" + rlooks + "rlks_SIM.aff"; if os.path.exists(aff_path): print("\n***** WARNING, " + aff_path + " already exists in " + int_dir + ", skipping...\n"); continue; cmd += "\ncd " + path + "\n"; cmd += "\nprocess_2pass_glac.pl " + proc_path + " offsets done_sim_removal &\n"; cmd += "\ncd " + cwd + "\n"; print(cmd); #subprocess.call(cmd,shell=True); return; def getGRDCorners(path): currentDir = os.getcwd(); findGRDsCmd = "find " + path + " -name \"*.grd\" -print"; findGRDsStream = subprocess.Popen(findGRDsCmd); findGRDsOutput = findGRDsStream.read().split(); findGRDsStream.close(); for i in range(0,len(findGRDsOutput)): grdPath = findGRDsOutput[i][0:findGRDsOutput[i].rfind("/")]; grdName = findGRDsOutput[i][findGRDsOutput[i].rfind("/")+1:findGRDsOutput[i].rfind(".")]; if not os.path.exists(grdPath + "/" + grdName + "_corners.dat"): grdinfoCmd = "\ngrdinfo " + findGRDsOutput[i].strip() + "\n"; grdinfoStream = subprocess.Popen(grdinfoCmd); grdinfoOutput = grdinfoStream.read(); grdinfoStream.close(); x_min = grdinfoOutput[grdinfoOutput.find("x_min:")+6:grdinfoOutput.find("x_max:")].strip(); x_max = grdinfoOutput[grdinfoOutput.find("x_max:")+6:grdinfoOutput.find("x_inc:")].strip(); y_min = grdinfoOutput[grdinfoOutput.find("y_min:")+6:grdinfoOutput.find("y_max:")].strip(); y_max = grdinfoOutput[grdinfoOutput.find("y_max:")+6:grdinfoOutput.find("y_inc:")].strip(); cornersFileName = grdPath + "/" + grdName + "_corners.dat"; cornersFile = open(cornersFileName,"w"); cornersFile.write(x_min + " " + y_min + " LL\n"); cornersFile.write(x_max + " " + y_max + " TR\n"); cornersFile.write(x_min + " " + y_max + " TL\n"); cornersFile.write(x_max + " " + y_min + " LR\n"); cornersFile.close() def generateKML(path): findPNGsCmd = "find " + path + " -name \"*.png\" -print"; findPNGsStream = subprocess.Popen(findPNGsCmd); findPNGsOutput = findPNGsStream.read().split(); findPNGsStream.close(); def createMatlabGetXYZ(matlabPath,ampcorInFilePath): startRefSample = ""; endRefSample = ""; skipRefSample = ""; startRefLine = ""; endRefLine = ""; skipRefLine = ""; ampcorInFile = open(ampcorInFilePath,"r"); ampoff_dir = ampcorInFilePath[0:ampcorInFilePath.rfind("/")]; ampoff_name = ampcorInFilePath[0:ampcorInFilePath.rfind(".")]; cornersFilePath = ampoff_dir + "/corners.dat"; cornersFile = open(cornersFilePath,"r"); ul_long = ""; ul_lat = ""; while 1: line = cornersFile.readline(); if not line: break; line = line.strip(); if line.find("ul_long") > -1: ul_long = line.split("=")[1]; elif line.find("ul_lat") > -1: ul_lat = line.split("=")[1]; cornersFile.close(); while 1: line = ampcorInFile.readline(); if not line: break; if line.find("Start, End and Skip Samples in Reference Image") > -1: line = line.strip().split("="); sampleInfo = line[1].split(); startRefSample = sampleInfo[0]; endRefSample = sampleInfo[1]; skipRefSample = sampleInfo[2]; elif line.find("Start, End and Skip Lines in Reference Image") > -1: line = line.strip().split("="); lineInfo = line[1].split(); startRefLine = lineInfo[0]; endRefLine = lineInfo[1]; skipRefLine = lineInfo[2]; ampcorInFile.close(); matlabFile = open(matlabPath,"r"); outputMatlabFile = open(ampoff_dir + "/getxyzs.m","w"); while 1: line = matlabFile.readline(); if not line: break; elif re.search("rwin\s*=\s*;",line): outputMatlabFile.write(line.replace(";",skipRefSample+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("awin\s*=\s*;",line): outputMatlabFile.write(line.replace(";",skipRefLine+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("load\s*;",line): outputMatlabFile.write(line.replace(";",ampoff_name[ampoff_name.rfind("/")+1:]+".off;")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("indat\s*=\s*;",line): outputMatlabFile.write(line.replace(";",ampoff_name[ampoff_name.rfind("/")+1:]+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("width0\s*=\s*;",line): outputMatlabFile.write(line.replace(";",endRefSample+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("length0\s*=\s*;",line): outputMatlabFile.write(line.replace(";",endRefLine+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("ul_long\s*=\s*;",line): outputMatlabFile.write(line.replace(";",ul_long+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("ul_lat\s*=\s*;",line): outputMatlabFile.write(line.replace(";",ul_lat+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("x_step\s*=\s*;",line): outputMatlabFile.write(line.replace(";",str(15*int(skipRefSample))+";")); break; else: outputMatlabFile.write(line); while 1: line = matlabFile.readline(); if not line: break; elif re.search("y_step\s*=\s*",line): outputMatlabFile.write(line.replace(";",str(15*int(skipRefLine))+";")); else: outputMatlabFile.write(line); outputMatlabFile.close(); matlabFile.close(); currentDir = os.getcwd(); getXYZCmd = "\ncd " + ampoff_dir + "\nmatlab -nodesktop -nosplash -r getxyzs\ncd " + currentDir; getXYZCmdStream = subprocess.Popen(getXYZCmd); getXYZCmdStream.close(); def makeRawALOS(WorkPath): contents = os.listdir(WorkPath); cmd = ""; for i in range(0, len(contents)): if re.search("^\d\d\d\d\d\d$", contents[i]): date_contents = os.listdir(WorkPath + "/" + contents[i]); for item in date_contents: if item.find("LED") > -1: fbd2fbs = "NO"; img_path = item.replace("LED", "IMG-HH"); img_full_path = os.readlink(WorkPath + "/" + contents[i] + "/" + img_path); img_alt_path = img_full_path.replace("HH","HV"); if os.path.exists(img_alt_path): fbd2fbs = "FBD2FBS"; cwd = os.getcwd(); cmd = cmd + "\ncd " + WorkPath + "/" + contents[i] + "\nmake_raw_alos.pl IMG " + contents[i] + " " + fbd2fbs + "\ncd " + cwd + "\n"; break; subprocess.call(cmd,shell=True); return; def makeRawENVISAT(WorkPath, orbit): contents = os.listdir(WorkPath); cmd = ""; for i in range(0, len(contents)): if re.search("^\d\d\d\d\d\d$", contents[i]): date_contents = os.listdir(WorkPath + "/" + contents[i]); for item in date_contents: if item.find("ASA_") > -1: cwd = os.getcwd(); cmd = cmd + "\ncd " + WorkPath + "/" + contents[i] + "\nmake_raw_envi.pl " + item + " " + orbit + " " + contents[i] + "\ncd " + cwd + "\n"; break; subprocess.call(cmd,shell=True); return; def makeRawERS(WorkPath, orbit): contents = os.listdir(WorkPath); cmd = ""; for i in range(0, len(contents)): if re.search("^\d\d\d\d\d\d$", contents[i]): date_contents = os.listdir(WorkPath + "/" + contents[i]); for item in date_contents: if item.find("SARLEADER") > -1: cwd = os.getcwd(); # cmd = cmd + "\ncd " + WorkPath + "/" + contents[i] + "\nmake_raw_ASF.pl " + orbit + " " + item + " " + contents[i] + "\ncd " + cwd + "\n"; cmd = cmd + "\ncd " + WorkPath + "/" + contents[i] + "\nmake_raw.pl " + orbit + " " + item + " " + contents[i] + "\ncd " + cwd + "\n"; break; subprocess.call(cmd,shell=True); return; def makeRawTSX(WorkPath): cwd = os.getcwd(); cmd = "\nfind " + WorkPath + " -name \"TDX*.xml\"\n"; pipe = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout; leader_file_paths = pipe.read().split(); pipe.close(); dates = {}; for path in leader_file_paths: infile = open(path,"r"); for line in infile: if line.find("timeUTC") > -1: index = re.search("timeUTC>",line).end(0); year = line[index + 2 : index + 4]; month = line[index + 5 : index + 7]; day = line[index + 8 : index + 10]; date = year + month + day; dates[date] = path; break; infile.close(); for date in dates: cmd = "\ncd " + WorkPath + "/" + date + "\n"; cmd += "\nmake_slc_tsx.csh " + dates[date] + " " + date + "\n"; cmd += "\ncp -p " + WorkPath + "/" + date + "/" + date + ".slc.rsc " + WorkPath + "/" + date + "/" + date + ".raw.rsc\n"; cmd += "\ntouch " + WorkPath + "/" + date + "/" + date + ".raw\n"; cmd += "\ncd " + cwd + "\n"; subprocess.call(cmd,shell=True); return; def readIntProcFile(proc_path): assert os.path.exists(proc_path), "***** ERROR: " + proc_path + " not found, cannot read proc file\n"; int_vars = {}; proc_file = open(proc_path,"r"); while 1: line = proc_file.readline(); if not line: break; line = line.strip(); if not line: continue; name = ""; value = ""; elements = line.split("="); if len(elements) < 2 or len(elements[0]) < 1 or len(elements[1]) < 1: print("\n***** ERROR, proc file line format is \"name = value\", \"" + line + "\" does not conform to this format\n"); sys.exit(); name = elements[0].strip(); value = elements[1].strip(); int_vars[name] = value; proc_file.close(); return int_vars; def setupALOS(WorkPath, leader_file_paths): for leader_path in leader_file_paths: existingSARLeaderFiles = {}; sarNumber = {}; dateName = ""; extension = leader_path[leader_path.rfind("."):]; leader_name = leader_path[leader_path.rfind("/") + 1 : ]; leaderFile = open(leader_path,"rb"); while 1: line = leaderFile.readline(); if not line: break; searchExp = "\s\d\d\d\d\d\d\d\d"; if re.search(searchExp,line): index = re.search(searchExp,line).start(0); dateName = line[index:index+9].strip(); dateName = dateName[2:8]; if not os.path.isdir(WorkPath + "/" + dateName): cmd = "mkdir " + WorkPath + "/" + dateName; subprocess.call(cmd,shell=True); if not existingSARLeaderFiles.has_key(leader_path): leader_link_path = WorkPath + "/" + dateName + "/" + leader_name; os.symlink(leader_path, leader_link_path); existingSARLeaderFiles[leader_path] = leader_link_path; break; leaderFile.close(); if re.search("LED-A",leader_path): raw_path = leader_path.replace("LED","IMG-HH"); raw_alt_path = leader_path.replace("LED","IMG-HV"); raw_name = raw_path[raw_path.rfind("IMG") : ]; raw_alt_name = raw_alt_path[raw_alt_path.rfind("IMG") : ]; raw_link_path = WorkPath + "/" + dateName + "/" + raw_name; raw_alt_link_path = WorkPath + "/" + dateName + "/" + raw_alt_name; if os.path.exists(raw_path) and not os.path.exists(raw_link_path): os.symlink(raw_path, raw_link_path); # if os.path.exists(raw_alt_path) and not os.path.exists(raw_alt_link_path): # os.symlink(raw_alt_path, raw_alt_link_path); if not os.path.exists(raw_path): print("\n***** WARNING, could not find corresponding raw file for leader file \"" + leader_path + "\"\nPlease make sure the raw file is in the same directory and is named \"IMG-HH*"+leader_path.replace("LED","")+"\"\n"); continue; return; def setupTSX(WorkPath, leader_file_paths): for path in leader_file_paths: infile = open(path,"r"); for path in leader_file_paths: print(path); return; def setupENVISAT(WorkPath, leader_file_paths): for path in leader_file_paths: print(path); return; def setupERS(WorkPath, leader_file_paths): for path in leader_file_paths: existingSARLeaderFiles = {}; sarNumber = {}; dateName = ""; extension = path[path.rfind("."):]; leaderFile = open(path,"rb"); while 1: line = leaderFile.readline(); if not line: break; searchExp = "\s\d\d\d\d\d\d\d\d"; if re.search(searchExp,line): index = re.search(searchExp,line).start(0); dateName = line[index:index+9].strip(); dateName = dateName[2:8]; if not os.path.isdir(WorkPath + "/" + dateName): cmd = "mkdir " + WorkPath + "/" + dateName; subprocess.call(cmd,shell=True); if not existingSARLeaderFiles.has_key(path): if not sarNumber.has_key(dateName): sarNumber[dateName] = 1; else: sarNumber[dateName] = sarNumber[dateName] + 1; sarNumberStr = str(sarNumber[dateName]) if sarNumber[dateName] < 10: sarNumberStr = "0" + sarNumberStr; tempPath = WorkPath + "/" + dateName + "/SARLEADER" + sarNumberStr; while has_value(existingSARLeaderFiles,tempPath): sarNumber[dateName] = sarNumber[dateName] + 1; sarNumberStr = str(sarNumber[dateName]); if sarNumber[dateName] < 10: sarNumberStr = "0" + sarNumberStr; tempPath = WorkPath + "/" + dateName + "/SARLEADER" + sarNumberStr; os.symlink(path,tempPath); existingSARLeaderFiles[path] = tempPath; break; leaderFile.close(); rawFileName = "rawness"; if re.search("LEA.*\.001",path): rawFileName = path.replace("LEA","DAT"); else: rawFileName = path[0:path.find(".ldr")] + ".raw"; if not os.path.exists(rawFileName): rawFileName = rawFileName[0:rawFileName.find(".raw")] + ".RAW"; if not os.path.exists(rawFileName): rawFileName = rawFileName[0:rawFileName.find(".RAW")] + ".Raw"; if not os.path.exists(rawFileName): if DataType.lower().find("alos") > -1: print("\n***** WARNING, could not find corresponding raw file for leader file \"" + path + "\"\nPlease make sure the raw file is in the same directory and is named \"IMG*"+path.replace("LED","")+"\"\n"); else: print("\n***** WARNING, could not find corresponding raw file for leader file \"" + path + "\"\nPlease make sure the raw file is in the same directory and has the extension \".raw\"\n"); continue; tempImagePath = ""; if re.search("SARLEADER", existingSARLeaderFiles[path]): tempImagePath = existingSARLeaderFiles[path].replace("SARLEADER","IMAGERY"); if not os.path.exists(tempImagePath): os.symlink(rawFileName, tempImagePath); return; def setupTSX(WorkPath, leader_file_paths): for path in leader_file_paths: infile = open(path,"r"); for line in infile: if line.find("timeUTC") > -1: index = re.search("timeUTC>",line).end(0); year = line[index + 2 : index + 4]; month = line[index + 5 : index + 7]; day = line[index + 8 : index + 10]; date = year + month + day; if not os.path.exists(date): os.mkdir(WorkPath + "/" + date); break; infile.close(); return;
[ "fnmatch.filter", "subprocess.Popen", "numpy.size", "os.mkdir", "os.readlink", "os.getcwd", "numpy.fromfile", "os.path.isdir", "os.walk", "os.path.exists", "scipy.matrix", "subprocess.call", "os.chdir", "glob.glob", "shutil.rmtree", "os.symlink", "re.search", "os.listdir" ]
[((782, 825), 'scipy.matrix', 'scipy.matrix', (['radar_unw_data', 'scipy.float32'], {}), '(radar_unw_data, scipy.float32)\n', (794, 825), False, 'import scipy\n'), ((993, 1004), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1002, 1004), False, 'import os\n'), ((1036, 1072), 'glob.glob', 'glob.glob', (["(path + '/int*/*_cull.off')"], {}), "(path + '/int*/*_cull.off')\n", (1045, 1072), False, 'import glob\n'), ((11595, 11606), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (11604, 11606), False, 'import os\n'), ((13949, 13990), 'shutil.rmtree', 'shutil.rmtree', (["(path + '/' + date + '_APS')"], {}), "(path + '/' + date + '_APS')\n", (13962, 13990), False, 'import shutil\n'), ((14670, 14700), 'os.path.exists', 'os.path.exists', (['proc_file_path'], {}), '(proc_file_path)\n', (14684, 14700), False, 'import os\n'), ((15431, 15455), 're.search', 're.search', (['"""\\\\d+"""', 'angle'], {}), "('\\\\d+', angle)\n", (15440, 15455), False, 'import re\n'), ((16634, 16659), 'subprocess.Popen', 'subprocess.Popen', (['procCmd'], {}), '(procCmd)\n', (16650, 16659), False, 'import subprocess\n'), ((20074, 20085), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (20083, 20085), False, 'import os\n'), ((20144, 20157), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (20151, 20157), False, 'import os\n'), ((24550, 24561), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (24559, 24561), False, 'import os\n'), ((24645, 24674), 'subprocess.Popen', 'subprocess.Popen', (['profilesCmd'], {}), '(profilesCmd)\n', (24661, 24674), False, 'import subprocess\n'), ((24852, 24876), 'subprocess.Popen', 'subprocess.Popen', (['xyzCmd'], {}), '(xyzCmd)\n', (24868, 24876), False, 'import subprocess\n'), ((25002, 25026), 'subprocess.Popen', 'subprocess.Popen', (['xyzCmd'], {}), '(xyzCmd)\n', (25018, 25026), False, 'import subprocess\n'), ((25163, 25187), 'subprocess.Popen', 'subprocess.Popen', (['xyzCmd'], {}), '(xyzCmd)\n', (25179, 25187), False, 'import subprocess\n'), ((26188, 26199), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (26197, 26199), False, 'import os\n'), ((26278, 26307), 'subprocess.Popen', 'subprocess.Popen', (['findGRDsCmd'], {}), '(findGRDsCmd)\n', (26294, 26307), False, 'import subprocess\n'), ((26912, 26923), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (26921, 26923), False, 'import os\n'), ((26938, 26954), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (26948, 26954), False, 'import os\n'), ((27860, 27871), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (27869, 27871), False, 'import os\n'), ((27950, 27979), 'subprocess.Popen', 'subprocess.Popen', (['findGRDsCmd'], {}), '(findGRDsCmd)\n', (27966, 27979), False, 'import subprocess\n'), ((29323, 29352), 'subprocess.Popen', 'subprocess.Popen', (['findPNGsCmd'], {}), '(findPNGsCmd)\n', (29339, 29352), False, 'import subprocess\n'), ((33122, 33133), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (33131, 33133), False, 'import os\n'), ((33252, 33279), 'subprocess.Popen', 'subprocess.Popen', (['getXYZCmd'], {}), '(getXYZCmd)\n', (33268, 33279), False, 'import subprocess\n'), ((33349, 33369), 'os.listdir', 'os.listdir', (['WorkPath'], {}), '(WorkPath)\n', (33359, 33369), False, 'import os\n'), ((34047, 34079), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (34062, 34079), False, 'import subprocess\n'), ((34142, 34162), 'os.listdir', 'os.listdir', (['WorkPath'], {}), '(WorkPath)\n', (34152, 34162), False, 'import os\n'), ((34571, 34603), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (34586, 34603), False, 'import subprocess\n'), ((34662, 34682), 'os.listdir', 'os.listdir', (['WorkPath'], {}), '(WorkPath)\n', (34672, 34682), False, 'import os\n'), ((35236, 35268), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (35251, 35268), False, 'import subprocess\n'), ((35315, 35326), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (35324, 35326), False, 'import os\n'), ((36357, 36382), 'os.path.exists', 'os.path.exists', (['proc_path'], {}), '(proc_path)\n', (36371, 36382), False, 'import os\n'), ((1326, 1346), 'os.listdir', 'os.listdir', (['cull_dir'], {}), '(cull_dir)\n', (1336, 1346), False, 'import os\n'), ((3601, 3633), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (3616, 3633), False, 'import subprocess\n'), ((4227, 4284), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (4243, 4284), False, 'import subprocess\n'), ((6481, 6503), 'os.listdir', 'os.listdir', (['ampoff_dir'], {}), '(ampoff_dir)\n', (6491, 6503), False, 'import os\n'), ((9847, 9858), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9856, 9858), False, 'import os\n'), ((11683, 11740), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (11699, 11740), False, 'import subprocess\n'), ((13304, 13336), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (13319, 13336), False, 'import subprocess\n'), ((17609, 17635), 'numpy.size', 'numpy.size', (['kernel'], {'axis': '(0)'}), '(kernel, axis=0)\n', (17619, 17635), False, 'import numpy\n'), ((19768, 19796), 'numpy.size', 'numpy.size', (['ghp_data'], {'axis': '(0)'}), '(ghp_data, axis=0)\n', (19778, 19796), False, 'import numpy\n'), ((20178, 20212), 'fnmatch.filter', 'fnmatch.filter', (['filenames', '"""*.unw"""'], {}), "(filenames, '*.unw')\n", (20192, 20212), False, 'import fnmatch\n'), ((20867, 20888), 'os.chdir', 'os.chdir', (['azo_unw_dir'], {}), '(azo_unw_dir)\n', (20875, 20888), False, 'import os\n'), ((21093, 21116), 'os.path.exists', 'os.path.exists', (['geo_unw'], {}), '(geo_unw)\n', (21107, 21116), False, 'import os\n'), ((24444, 24476), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (24459, 24476), False, 'import subprocess\n'), ((24480, 24493), 'os.chdir', 'os.chdir', (['cwd'], {}), '(cwd)\n', (24488, 24493), False, 'import os\n'), ((26828, 26852), 'subprocess.Popen', 'subprocess.Popen', (['pngCmd'], {}), '(pngCmd)\n', (26844, 26852), False, 'import subprocess\n'), ((27477, 27501), 'os.path.exists', 'os.path.exists', (['aff_path'], {}), '(aff_path)\n', (27491, 27501), False, 'import os\n'), ((33425, 33471), 're.search', 're.search', (['"""^\\\\d\\\\d\\\\d\\\\d\\\\d\\\\d$"""', 'contents[i]'], {}), "('^\\\\d\\\\d\\\\d\\\\d\\\\d\\\\d$', contents[i])\n", (33434, 33471), False, 'import re\n'), ((34218, 34264), 're.search', 're.search', (['"""^\\\\d\\\\d\\\\d\\\\d\\\\d\\\\d$"""', 'contents[i]'], {}), "('^\\\\d\\\\d\\\\d\\\\d\\\\d\\\\d$', contents[i])\n", (34227, 34264), False, 'import re\n'), ((34738, 34784), 're.search', 're.search', (['"""^\\\\d\\\\d\\\\d\\\\d\\\\d\\\\d$"""', 'contents[i]'], {}), "('^\\\\d\\\\d\\\\d\\\\d\\\\d\\\\d$', contents[i])\n", (34747, 34784), False, 'import re\n'), ((35392, 35449), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (35408, 35449), False, 'import subprocess\n'), ((36271, 36303), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (36286, 36303), False, 'import subprocess\n'), ((38085, 38116), 're.search', 're.search', (['"""LED-A"""', 'leader_path'], {}), "('LED-A', leader_path)\n", (38094, 38116), False, 'import re\n'), ((40812, 40842), 're.search', 're.search', (['"""LEA.*\\\\.001"""', 'path'], {}), "('LEA.*\\\\.001', path)\n", (40821, 40842), False, 'import re\n'), ((41699, 41751), 're.search', 're.search', (['"""SARLEADER"""', 'existingSARLeaderFiles[path]'], {}), "('SARLEADER', existingSARLeaderFiles[path])\n", (41708, 41751), False, 'import re\n'), ((1243, 1273), 're.search', 're.search', (['"""\\\\d{6}"""', 'cull_name'], {}), "('\\\\d{6}', cull_name)\n", (1252, 1273), False, 'import re\n'), ((2036, 2056), 'os.path.exists', 'os.path.exists', (['slc1'], {}), '(slc1)\n', (2050, 2056), False, 'import os\n'), ((2234, 2254), 'os.path.exists', 'os.path.exists', (['slc2'], {}), '(slc2)\n', (2248, 2254), False, 'import os\n'), ((2682, 2702), 'os.path.exists', 'os.path.exists', (['amp1'], {}), '(amp1)\n', (2696, 2702), False, 'import os\n'), ((2967, 2999), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (2982, 2999), False, 'import subprocess\n'), ((3229, 3249), 'os.path.exists', 'os.path.exists', (['amp2'], {}), '(amp2)\n', (3243, 3249), False, 'import os\n'), ((3514, 3546), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (3529, 3546), False, 'import subprocess\n'), ((4535, 4592), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (4551, 4592), False, 'import subprocess\n'), ((7383, 7440), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (7399, 7440), False, 'import subprocess\n'), ((11063, 11095), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (11078, 11095), False, 'import subprocess\n'), ((11923, 11980), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (11939, 11980), False, 'import subprocess\n'), ((12112, 12169), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (12128, 12169), False, 'import subprocess\n'), ((12418, 12451), 'os.path.exists', 'os.path.exists', (["(raw_path + '.rsc')"], {}), "(raw_path + '.rsc')\n", (12432, 12451), False, 'import os\n'), ((13640, 13682), 'os.path.exists', 'os.path.exists', (["(path + '/' + date + '_APS')"], {}), "(path + '/' + date + '_APS')\n", (13654, 13682), False, 'import os\n'), ((17788, 17812), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (17798, 17812), False, 'import numpy\n'), ((19700, 19724), 'numpy.size', 'numpy.size', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (19710, 19724), False, 'import numpy\n'), ((19724, 19748), 'numpy.size', 'numpy.size', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (19734, 19748), False, 'import numpy\n'), ((19816, 19844), 'numpy.size', 'numpy.size', (['ghp_data'], {'axis': '(1)'}), '(ghp_data, axis=1)\n', (19826, 19844), False, 'import numpy\n'), ((21596, 21622), 'os.path.exists', 'os.path.exists', (['radar_name'], {}), '(radar_name)\n', (21610, 21622), False, 'import os\n'), ((21771, 21801), 'os.path.exists', 'os.path.exists', (['radar_rsc_name'], {}), '(radar_rsc_name)\n', (21785, 21801), False, 'import os\n'), ((21951, 21992), 're.search', 're.search', (['"""^blalbalbrange"""', 'azo_unw_name'], {}), "('^blalbalbrange', azo_unw_name)\n", (21960, 21992), False, 'import re\n'), ((21997, 22023), 'os.path.exists', 'os.path.exists', (['radar_name'], {}), '(radar_name)\n', (22011, 22023), False, 'import os\n'), ((22028, 22063), 'os.path.exists', 'os.path.exists', (["(radar_name + '.rsc')"], {}), "(radar_name + '.rsc')\n", (22042, 22063), False, 'import os\n'), ((22148, 22180), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (22163, 22180), False, 'import subprocess\n'), ((23211, 23243), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (23226, 23243), False, 'import subprocess\n'), ((23460, 23492), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (23475, 23492), False, 'import subprocess\n'), ((23647, 23679), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (23662, 23679), False, 'import subprocess\n'), ((23743, 23828), 'os.path.exists', 'os.path.exists', (["(azo_unw_dir + '/' + later_date + '_' + ld_range + 'rlks.slc.rsc')"], {}), "(azo_unw_dir + '/' + later_date + '_' + ld_range + 'rlks.slc.rsc'\n )\n", (23757, 23828), False, 'import os\n'), ((25549, 25597), 'os.path.exists', 'os.path.exists', (["(xyzPath + '/' + xyzName + '.grd')"], {}), "(xyzPath + '/' + xyzName + '.grd')\n", (25563, 25597), False, 'import os\n'), ((25694, 25719), 'subprocess.Popen', 'subprocess.Popen', (['gridCmd'], {}), '(gridCmd)\n', (25710, 25719), False, 'import subprocess\n'), ((26646, 26668), 'os.path.exists', 'os.path.exists', (['psName'], {}), '(psName)\n', (26660, 26668), False, 'import os\n'), ((28259, 28315), 'os.path.exists', 'os.path.exists', (["(grdPath + '/' + grdName + '_corners.dat')"], {}), "(grdPath + '/' + grdName + '_corners.dat')\n", (28273, 28315), False, 'import os\n'), ((28401, 28429), 'subprocess.Popen', 'subprocess.Popen', (['grdinfoCmd'], {}), '(grdinfoCmd)\n', (28417, 28429), False, 'import subprocess\n'), ((30865, 30898), 're.search', 're.search', (['"""rwin\\\\s*=\\\\s*;"""', 'line'], {}), "('rwin\\\\s*=\\\\s*;', line)\n", (30874, 30898), False, 'import re\n'), ((31086, 31119), 're.search', 're.search', (['"""awin\\\\s*=\\\\s*;"""', 'line'], {}), "('awin\\\\s*=\\\\s*;', line)\n", (31095, 31119), False, 'import re\n'), ((31305, 31333), 're.search', 're.search', (['"""load\\\\s*;"""', 'line'], {}), "('load\\\\s*;', line)\n", (31314, 31333), False, 'import re\n'), ((31551, 31585), 're.search', 're.search', (['"""indat\\\\s*=\\\\s*;"""', 'line'], {}), "('indat\\\\s*=\\\\s*;', line)\n", (31560, 31585), False, 'import re\n'), ((31798, 31833), 're.search', 're.search', (['"""width0\\\\s*=\\\\s*;"""', 'line'], {}), "('width0\\\\s*=\\\\s*;', line)\n", (31807, 31833), False, 'import re\n'), ((32020, 32056), 're.search', 're.search', (['"""length0\\\\s*=\\\\s*;"""', 'line'], {}), "('length0\\\\s*=\\\\s*;', line)\n", (32029, 32056), False, 'import re\n'), ((32241, 32277), 're.search', 're.search', (['"""ul_long\\\\s*=\\\\s*;"""', 'line'], {}), "('ul_long\\\\s*=\\\\s*;', line)\n", (32250, 32277), False, 'import re\n'), ((32459, 32494), 're.search', 're.search', (['"""ul_lat\\\\s*=\\\\s*;"""', 'line'], {}), "('ul_lat\\\\s*=\\\\s*;', line)\n", (32468, 32494), False, 'import re\n'), ((32675, 32710), 're.search', 're.search', (['"""x_step\\\\s*=\\\\s*;"""', 'line'], {}), "('x_step\\\\s*=\\\\s*;', line)\n", (32684, 32710), False, 'import re\n'), ((32911, 32945), 're.search', 're.search', (['"""y_step\\\\s*=\\\\s*"""', 'line'], {}), "('y_step\\\\s*=\\\\s*', line)\n", (32920, 32945), False, 'import re\n'), ((33487, 33527), 'os.listdir', 'os.listdir', (["(WorkPath + '/' + contents[i])"], {}), "(WorkPath + '/' + contents[i])\n", (33497, 33527), False, 'import os\n'), ((34280, 34320), 'os.listdir', 'os.listdir', (["(WorkPath + '/' + contents[i])"], {}), "(WorkPath + '/' + contents[i])\n", (34290, 34320), False, 'import os\n'), ((34800, 34840), 'os.listdir', 'os.listdir', (["(WorkPath + '/' + contents[i])"], {}), "(WorkPath + '/' + contents[i])\n", (34810, 34840), False, 'import os\n'), ((37513, 37539), 're.search', 're.search', (['searchExp', 'line'], {}), '(searchExp, line)\n', (37522, 37539), False, 'import re\n'), ((39679, 39705), 're.search', 're.search', (['searchExp', 'line'], {}), '(searchExp, line)\n', (39688, 39705), False, 'import re\n'), ((41177, 41204), 'os.path.exists', 'os.path.exists', (['rawFileName'], {}), '(rawFileName)\n', (41191, 41204), False, 'import os\n'), ((41843, 41872), 'os.path.exists', 'os.path.exists', (['tempImagePath'], {}), '(tempImagePath)\n', (41857, 41872), False, 'import os\n'), ((41877, 41915), 'os.symlink', 'os.symlink', (['rawFileName', 'tempImagePath'], {}), '(rawFileName, tempImagePath)\n', (41887, 41915), False, 'import os\n'), ((610, 651), 'numpy.fromfile', 'numpy.fromfile', (['infile', 'numpy.float32', '(-1)'], {}), '(infile, numpy.float32, -1)\n', (624, 651), False, 'import numpy\n'), ((1379, 1476), 're.search', 're.search', (["('azo_' + wsamp + '_r' + rwin + 'x' + awin + '_s' + search_x + 'x' + search_y)", 'item'], {}), "('azo_' + wsamp + '_r' + rwin + 'x' + awin + '_s' + search_x + 'x' +\n search_y, item)\n", (1388, 1476), False, 'import re\n'), ((1682, 1712), 're.search', 're.search', (['"""\\\\d{6}"""', 'cull_name'], {}), "('\\\\d{6}', cull_name)\n", (1691, 1712), False, 'import re\n'), ((1732, 1762), 're.search', 're.search', (['"""\\\\d{6}"""', 'cull_name'], {}), "('\\\\d{6}', cull_name)\n", (1741, 1762), False, 'import re\n'), ((5872, 5908), 're.search', 're.search', (['"""_\\\\d\\\\.off"""', 'elements[1]'], {}), "('_\\\\d\\\\.off', elements[1])\n", (5881, 5908), False, 'import re\n'), ((6132, 6169), 'os.path.exists', 'os.path.exists', (['composite_ampoff_path'], {}), '(composite_ampoff_path)\n', (6146, 6169), False, 'import os\n'), ((6372, 6421), 'subprocess.call', 'subprocess.call', (['cat_cmds[ampoff_dir]'], {'shell': '(True)'}), '(cat_cmds[ampoff_dir], shell=True)\n', (6387, 6421), False, 'import subprocess\n'), ((13688, 13729), 'shutil.rmtree', 'shutil.rmtree', (["(path + '/' + date + '_APS')"], {}), "(path + '/' + date + '_APS')\n", (13701, 13729), False, 'import shutil\n'), ((15667, 15724), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE)\n', (15683, 15724), False, 'import subprocess\n'), ((17662, 17686), 'numpy.size', 'numpy.size', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (17672, 17686), False, 'import numpy\n'), ((17696, 17720), 'numpy.size', 'numpy.size', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (17706, 17720), False, 'import numpy\n'), ((17848, 17872), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (17858, 17872), False, 'import numpy\n'), ((18000, 18024), 'numpy.size', 'numpy.size', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (18010, 18024), False, 'import numpy\n'), ((18145, 18169), 'numpy.size', 'numpy.size', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (18155, 18169), False, 'import numpy\n'), ((18293, 18317), 'numpy.size', 'numpy.size', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (18303, 18317), False, 'import numpy\n'), ((18489, 18513), 'numpy.size', 'numpy.size', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (18499, 18513), False, 'import numpy\n'), ((20527, 20567), 're.search', 're.search', (['"""\\\\d{6}_\\\\d{6}"""', 'azo_unw_path'], {}), "('\\\\d{6}_\\\\d{6}', azo_unw_path)\n", (20536, 20567), False, 'import re\n'), ((26677, 26700), 'os.path.exists', 'os.path.exists', (['pngName'], {}), '(pngName)\n', (26691, 26700), False, 'import os\n'), ((38493, 38517), 'os.path.exists', 'os.path.exists', (['raw_path'], {}), '(raw_path)\n', (38507, 38517), False, 'import os\n'), ((38561, 38596), 'os.symlink', 'os.symlink', (['raw_path', 'raw_link_path'], {}), '(raw_path, raw_link_path)\n', (38571, 38596), False, 'import os\n'), ((38739, 38763), 'os.path.exists', 'os.path.exists', (['raw_path'], {}), '(raw_path)\n', (38753, 38763), False, 'import os\n'), ((40960, 40987), 'os.path.exists', 'os.path.exists', (['rawFileName'], {}), '(rawFileName)\n', (40974, 40987), False, 'import os\n'), ((1780, 1819), 're.search', 're.search', (['"""\\\\d{6}"""', 'cull_name[index2:]'], {}), "('\\\\d{6}', cull_name[index2:])\n", (1789, 1819), False, 'import re\n'), ((1846, 1885), 're.search', 're.search', (['"""\\\\d{6}"""', 'cull_name[index2:]'], {}), "('\\\\d{6}', cull_name[index2:])\n", (1855, 1885), False, 'import re\n'), ((33687, 33745), 'os.readlink', 'os.readlink', (["(WorkPath + '/' + contents[i] + '/' + img_path)"], {}), "(WorkPath + '/' + contents[i] + '/' + img_path)\n", (33698, 33745), False, 'import os\n'), ((33811, 33839), 'os.path.exists', 'os.path.exists', (['img_alt_path'], {}), '(img_alt_path)\n', (33825, 33839), False, 'import os\n'), ((33880, 33891), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (33889, 33891), False, 'import os\n'), ((34397, 34408), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (34406, 34408), False, 'import os\n'), ((34922, 34933), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (34931, 34933), False, 'import os\n'), ((37676, 37716), 'os.path.isdir', 'os.path.isdir', (["(WorkPath + '/' + dateName)"], {}), "(WorkPath + '/' + dateName)\n", (37689, 37716), False, 'import os\n'), ((37772, 37804), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (37787, 37804), False, 'import subprocess\n'), ((37940, 37981), 'os.symlink', 'os.symlink', (['leader_path', 'leader_link_path'], {}), '(leader_path, leader_link_path)\n', (37950, 37981), False, 'import os\n'), ((38526, 38555), 'os.path.exists', 'os.path.exists', (['raw_link_path'], {}), '(raw_link_path)\n', (38540, 38555), False, 'import os\n'), ((39842, 39882), 'os.path.isdir', 'os.path.isdir', (["(WorkPath + '/' + dateName)"], {}), "(WorkPath + '/' + dateName)\n", (39855, 39882), False, 'import os\n'), ((39938, 39970), 'subprocess.call', 'subprocess.call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (39953, 39970), False, 'import subprocess\n'), ((40670, 40696), 'os.symlink', 'os.symlink', (['path', 'tempPath'], {}), '(path, tempPath)\n', (40680, 40696), False, 'import os\n'), ((41069, 41096), 'os.path.exists', 'os.path.exists', (['rawFileName'], {}), '(rawFileName)\n', (41083, 41096), False, 'import os\n'), ((42309, 42329), 'os.path.exists', 'os.path.exists', (['date'], {}), '(date)\n', (42323, 42329), False, 'import os\n'), ((42336, 42367), 'os.mkdir', 'os.mkdir', (["(WorkPath + '/' + date)"], {}), "(WorkPath + '/' + date)\n", (42344, 42367), False, 'import os\n'), ((35659, 35686), 're.search', 're.search', (['"""timeUTC>"""', 'line'], {}), "('timeUTC>', line)\n", (35668, 35686), False, 'import re\n'), ((37553, 37579), 're.search', 're.search', (['searchExp', 'line'], {}), '(searchExp, line)\n', (37562, 37579), False, 'import re\n'), ((39719, 39745), 're.search', 're.search', (['searchExp', 'line'], {}), '(searchExp, line)\n', (39728, 39745), False, 'import re\n'), ((42105, 42132), 're.search', 're.search', (['"""timeUTC>"""', 'line'], {}), "('timeUTC>', line)\n", (42114, 42132), False, 'import re\n'), ((4813, 4840), 're.search', 're.search', (['"""timeUTC>"""', 'line'], {}), "('timeUTC>', line)\n", (4822, 4840), False, 'import re\n'), ((7183, 7228), 're.search', 're.search', (['"""/\\\\d{6}[\\\\-_]\\\\d{6}"""', 'ampoff_path'], {}), "('/\\\\d{6}[\\\\-_]\\\\d{6}', ampoff_path)\n", (7192, 7228), False, 'import re\n'), ((7240, 7285), 're.search', 're.search', (['"""/\\\\d{6}[\\\\-_]\\\\d{6}"""', 'ampoff_path'], {}), "('/\\\\d{6}[\\\\-_]\\\\d{6}', ampoff_path)\n", (7249, 7285), False, 'import re\n'), ((13747, 13778), 're.search', 're.search', (['"""\\\\d+\\\\.*\\\\d*"""', 'line'], {}), "('\\\\d+\\\\.*\\\\d*', line)\n", (13756, 13778), False, 'import re\n'), ((13786, 13817), 're.search', 're.search', (['"""\\\\d+\\\\.*\\\\d*"""', 'line'], {}), "('\\\\d+\\\\.*\\\\d*', line)\n", (13795, 13817), False, 'import re\n'), ((18330, 18354), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (18340, 18354), False, 'import numpy\n'), ((18382, 18406), 'numpy.size', 'numpy.size', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (18392, 18406), False, 'import numpy\n'), ((18524, 18548), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (18534, 18548), False, 'import numpy\n'), ((18568, 18592), 'numpy.size', 'numpy.size', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (18578, 18592), False, 'import numpy\n'), ((18904, 18928), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (18914, 18928), False, 'import numpy\n'), ((19156, 19180), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (19166, 19180), False, 'import numpy\n'), ((19190, 19214), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (19200, 19214), False, 'import numpy\n'), ((19489, 19513), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (19499, 19513), False, 'import numpy\n'), ((8244, 8274), 're.search', 're.search', (['"""^HEIGHT\\\\s+"""', 'line'], {}), "('^HEIGHT\\\\s+', line)\n", (8253, 8274), False, 'import re\n'), ((10003, 10048), 're.search', 're.search', (['"""/\\\\d{6}[\\\\-_]\\\\d{6}"""', 'ampoff_path'], {}), "('/\\\\d{6}[\\\\-_]\\\\d{6}', ampoff_path)\n", (10012, 10048), False, 'import re\n'), ((10056, 10101), 're.search', 're.search', (['"""/\\\\d{6}[\\\\-_]\\\\d{6}"""', 'ampoff_path'], {}), "('/\\\\d{6}[\\\\-_]\\\\d{6}', ampoff_path)\n", (10065, 10101), False, 'import re\n'), ((6015, 6051), 're.search', 're.search', (['"""_\\\\d\\\\.off"""', 'elements[1]'], {}), "('_\\\\d\\\\.off', elements[1])\n", (6024, 6051), False, 'import re\n'), ((19544, 19568), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (19554, 19568), False, 'import numpy\n'), ((19892, 19918), 'numpy.size', 'numpy.size', (['kernel'], {'axis': '(0)'}), '(kernel, axis=0)\n', (19902, 19918), False, 'import numpy\n'), ((19922, 19948), 'numpy.size', 'numpy.size', (['kernel'], {'axis': '(1)'}), '(kernel, axis=1)\n', (19932, 19948), False, 'import numpy\n'), ((5097, 5118), 're.search', 're.search', (['"""">"""', 'line'], {}), '(\'">\', line)\n', (5106, 5118), False, 'import re\n'), ((5128, 5149), 're.search', 're.search', (['"""</"""', 'line'], {}), "('</', line)\n", (5137, 5149), False, 'import re\n'), ((16054, 16085), 're.search', 're.search', (['"""\\\\d+\\\\.*\\\\d*"""', 'line'], {}), "('\\\\d+\\\\.*\\\\d*', line)\n", (16063, 16085), False, 'import re\n'), ((16093, 16124), 're.search', 're.search', (['"""\\\\d+\\\\.*\\\\d*"""', 'line'], {}), "('\\\\d+\\\\.*\\\\d*', line)\n", (16102, 16124), False, 'import re\n'), ((19017, 19041), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (19027, 19041), False, 'import numpy\n'), ((19237, 19261), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (19247, 19261), False, 'import numpy\n'), ((19351, 19375), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (19361, 19375), False, 'import numpy\n'), ((19596, 19620), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (19606, 19620), False, 'import numpy\n'), ((5249, 5270), 're.search', 're.search', (['"""">"""', 'line'], {}), '(\'">\', line)\n', (5258, 5270), False, 'import re\n'), ((5280, 5301), 're.search', 're.search', (['"""</"""', 'line'], {}), "('</', line)\n", (5289, 5301), False, 'import re\n'), ((18963, 18987), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (18973, 18987), False, 'import numpy\n'), ((19271, 19295), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(1)'}), '(temp, axis=1)\n', (19281, 19295), False, 'import numpy\n'), ((19315, 19339), 'numpy.size', 'numpy.size', (['temp'], {'axis': '(0)'}), '(temp, axis=0)\n', (19325, 19339), False, 'import numpy\n')]
from __future__ import annotations from typing import Sequence, TYPE_CHECKING from dataclasses import field, dataclass from anndata import AnnData import numpy as np from squidpy.im import ImageContainer # type: ignore[attr-defined] from squidpy._utils import NDArrayA, _unique_order_preserving from squidpy.gr._utils import _assert_spatial_basis, _assert_categorical_obs from squidpy.pl._utils import ALayer from squidpy.im._coords import CropCoords, CropPadding, _NULL_COORDS, _NULL_PADDING from squidpy._constants._constants import Symbol from squidpy._constants._pkg_constants import Key __all__ = ["ImageModel"] @dataclass class ImageModel: """Model which holds the data for interactive visualization.""" adata: AnnData container: ImageContainer spatial_key: str = field(default=Key.obsm.spatial, repr=False) library_key: str | None = None library_id: str | Sequence[str] | None = None spot_diameter_key: str = "spot_diameter_fullres" spot_diameter: NDArrayA | float = field(default=0, init=False) coordinates: NDArrayA = field(init=False, repr=False) alayer: ALayer = field(init=False, repr=True) palette: str | None = field(default=None, repr=False) cmap: str = field(default="viridis", repr=False) blending: str = field(default="opaque", repr=False) key_added: str = "shapes" symbol: Symbol = Symbol.DISC def __post_init__(self) -> None: _assert_spatial_basis(self.adata, self.spatial_key) self.symbol = Symbol(self.symbol) self.adata = self.container.subset(self.adata, spatial_key=self.spatial_key) if not self.adata.n_obs: raise ValueError("Please ensure that the image contains at least 1 spot.") self._set_scale_coords() self._set_library() if TYPE_CHECKING: assert isinstance(self.library_id, Sequence) self.alayer = ALayer( self.adata, self.library_id, is_raw=False, palette=self.palette, ) try: self.container = ImageContainer._from_dataset(self.container.data.sel(z=self.library_id), deep=None) except KeyError: raise KeyError( f"Unable to subset the image container with library ids `{self.library_id}`. " f"Valid container library ids are `{self.container.library_ids}`. Please specify a valid `library_id`." ) from None def _set_scale_coords(self) -> None: self.scale = self.container.data.attrs.get(Key.img.scale, 1) coordinates = self.adata.obsm[self.spatial_key][:, :2] * self.scale c: CropCoords = self.container.data.attrs.get(Key.img.coords, _NULL_COORDS) p: CropPadding = self.container.data.attrs.get(Key.img.padding, _NULL_PADDING) if c != _NULL_COORDS: coordinates -= c.x0 - p.x_pre coordinates -= c.y0 - p.y_pre self.coordinates = coordinates[:, ::-1] def _set_library(self) -> None: if self.library_key is None: if len(self.container.library_ids) > 1: raise KeyError( f"ImageContainer has `{len(self.container.library_ids)}` Z-dimensions. " f"Please specify `library_key` that maps observations to library ids." ) self.coordinates = np.insert(self.coordinates, 0, values=0, axis=1) self.library_id = self.container.library_ids if TYPE_CHECKING: assert isinstance(self.library_id, Sequence) self.spot_diameter = ( Key.uns.spot_diameter(self.adata, self.spatial_key, self.library_id[0], self.spot_diameter_key) * self.scale ) return _assert_categorical_obs(self.adata, self.library_key) if self.library_id is None: self.library_id = self.adata.obs[self.library_key].cat.categories elif isinstance(self.library_id, str): self.library_id = [self.library_id] self.library_id, _ = _unique_order_preserving(self.library_id) # type: ignore[assignment] if not len(self.library_id): raise ValueError("No library ids have been selected.") # invalid library ids from adata are filtered below # invalid library ids from container raise KeyError in `__post_init__` after this call libraries = self.adata.obs[self.library_key] mask = libraries.isin(self.library_id) libraries = libraries[mask].cat.remove_unused_categories() self.library_id = list(libraries.cat.categories) self.coordinates = np.c_[libraries.cat.codes.values, self.coordinates[mask]] self.spot_diameter = np.array( [ np.array([0.0] + [Key.uns.spot_diameter(self.adata, self.spatial_key, lid, self.spot_diameter_key)] * 2) * self.scale for lid in libraries ] ) self.adata = self.adata[mask]
[ "squidpy._constants._constants.Symbol", "squidpy._utils._unique_order_preserving", "squidpy.gr._utils._assert_spatial_basis", "squidpy.pl._utils.ALayer", "squidpy.gr._utils._assert_categorical_obs", "numpy.insert", "dataclasses.field", "squidpy._constants._pkg_constants.Key.uns.spot_diameter" ]
[((795, 838), 'dataclasses.field', 'field', ([], {'default': 'Key.obsm.spatial', 'repr': '(False)'}), '(default=Key.obsm.spatial, repr=False)\n', (800, 838), False, 'from dataclasses import field, dataclass\n'), ((1015, 1043), 'dataclasses.field', 'field', ([], {'default': '(0)', 'init': '(False)'}), '(default=0, init=False)\n', (1020, 1043), False, 'from dataclasses import field, dataclass\n'), ((1072, 1101), 'dataclasses.field', 'field', ([], {'init': '(False)', 'repr': '(False)'}), '(init=False, repr=False)\n', (1077, 1101), False, 'from dataclasses import field, dataclass\n'), ((1123, 1151), 'dataclasses.field', 'field', ([], {'init': '(False)', 'repr': '(True)'}), '(init=False, repr=True)\n', (1128, 1151), False, 'from dataclasses import field, dataclass\n'), ((1179, 1210), 'dataclasses.field', 'field', ([], {'default': 'None', 'repr': '(False)'}), '(default=None, repr=False)\n', (1184, 1210), False, 'from dataclasses import field, dataclass\n'), ((1227, 1263), 'dataclasses.field', 'field', ([], {'default': '"""viridis"""', 'repr': '(False)'}), "(default='viridis', repr=False)\n", (1232, 1263), False, 'from dataclasses import field, dataclass\n'), ((1284, 1319), 'dataclasses.field', 'field', ([], {'default': '"""opaque"""', 'repr': '(False)'}), "(default='opaque', repr=False)\n", (1289, 1319), False, 'from dataclasses import field, dataclass\n'), ((1429, 1480), 'squidpy.gr._utils._assert_spatial_basis', '_assert_spatial_basis', (['self.adata', 'self.spatial_key'], {}), '(self.adata, self.spatial_key)\n', (1450, 1480), False, 'from squidpy.gr._utils import _assert_spatial_basis, _assert_categorical_obs\n'), ((1504, 1523), 'squidpy._constants._constants.Symbol', 'Symbol', (['self.symbol'], {}), '(self.symbol)\n', (1510, 1523), False, 'from squidpy._constants._constants import Symbol\n'), ((1897, 1968), 'squidpy.pl._utils.ALayer', 'ALayer', (['self.adata', 'self.library_id'], {'is_raw': '(False)', 'palette': 'self.palette'}), '(self.adata, self.library_id, is_raw=False, palette=self.palette)\n', (1903, 1968), False, 'from squidpy.pl._utils import ALayer\n'), ((3775, 3828), 'squidpy.gr._utils._assert_categorical_obs', '_assert_categorical_obs', (['self.adata', 'self.library_key'], {}), '(self.adata, self.library_key)\n', (3798, 3828), False, 'from squidpy.gr._utils import _assert_spatial_basis, _assert_categorical_obs\n'), ((4067, 4108), 'squidpy._utils._unique_order_preserving', '_unique_order_preserving', (['self.library_id'], {}), '(self.library_id)\n', (4091, 4108), False, 'from squidpy._utils import NDArrayA, _unique_order_preserving\n'), ((3360, 3408), 'numpy.insert', 'np.insert', (['self.coordinates', '(0)'], {'values': '(0)', 'axis': '(1)'}), '(self.coordinates, 0, values=0, axis=1)\n', (3369, 3408), True, 'import numpy as np\n'), ((3608, 3707), 'squidpy._constants._pkg_constants.Key.uns.spot_diameter', 'Key.uns.spot_diameter', (['self.adata', 'self.spatial_key', 'self.library_id[0]', 'self.spot_diameter_key'], {}), '(self.adata, self.spatial_key, self.library_id[0],\n self.spot_diameter_key)\n', (3629, 3707), False, 'from squidpy._constants._pkg_constants import Key\n'), ((4795, 4880), 'squidpy._constants._pkg_constants.Key.uns.spot_diameter', 'Key.uns.spot_diameter', (['self.adata', 'self.spatial_key', 'lid', 'self.spot_diameter_key'], {}), '(self.adata, self.spatial_key, lid, self.spot_diameter_key\n )\n', (4816, 4880), False, 'from squidpy._constants._pkg_constants import Key\n')]
# this file contains functions required for loading the data for training or evaluation import numpy as np from flags import * from os import listdir import torch import h5py def load_dataset(): # loading data if (DATASET == 'moving_mnist'): dataset = data_moving_mnist(DATA_PATH) elif (DATASET == 'dsprites_color'): dataset = data_dsprites_color(DATA_PATH) else: raise Exception('Invalid Dataset!') return dataset class data_moving_mnist: def __init__(self, DATA_PATH): self.array = [] for f in listdir(DATA_PATH): self.data = np.load(DATA_PATH + f) self.arr = np.reshape(self.data['arr_0'], [10000, 20, 64, 64]) for i in range(10000): self.array.append(np.reshape(self.arr[i, :2*NUM_FRAMES:2, ], [NUM_FRAMES, NUM_INPUT_CHANNELS, H, W])) def __len__(self): return self.array.__len__() def __getitem__(self, index): return self.array[index] class data_dsprites_color(torch.utils.data.Dataset): def __init__(self, file): super(data_dsprites_color, self).__init__() self.file = h5py.File(file, 'r') self.n_videos = np.asarray(self.file.get('data')) def __getitem__(self, index): input = self.n_videos[index] return input.astype('float32') def __len__(self): return self.n_videos.shape[0]
[ "h5py.File", "os.listdir", "numpy.reshape", "numpy.load" ]
[((546, 564), 'os.listdir', 'listdir', (['DATA_PATH'], {}), '(DATA_PATH)\n', (553, 564), False, 'from os import listdir\n'), ((1056, 1076), 'h5py.File', 'h5py.File', (['file', '"""r"""'], {}), "(file, 'r')\n", (1065, 1076), False, 'import h5py\n'), ((581, 603), 'numpy.load', 'np.load', (['(DATA_PATH + f)'], {}), '(DATA_PATH + f)\n', (588, 603), True, 'import numpy as np\n'), ((618, 669), 'numpy.reshape', 'np.reshape', (["self.data['arr_0']", '[10000, 20, 64, 64]'], {}), "(self.data['arr_0'], [10000, 20, 64, 64])\n", (628, 669), True, 'import numpy as np\n'), ((718, 804), 'numpy.reshape', 'np.reshape', (['self.arr[i, :2 * NUM_FRAMES:2]', '[NUM_FRAMES, NUM_INPUT_CHANNELS, H, W]'], {}), '(self.arr[i, :2 * NUM_FRAMES:2], [NUM_FRAMES, NUM_INPUT_CHANNELS,\n H, W])\n', (728, 804), True, 'import numpy as np\n')]
"""The evaluation module of deterior This module provides methods to validate a trained models and cross-validate models on given dataset. """ from itertools import chain from collections import namedtuple import sys import numpy as np from .models import Model from .dataset import Record from .training import prepare_validate, build_simple_model Result = namedtuple('Reulst', ['expect', 'actual', 'var', 'std', 'err']) def validate_model(model: Model, records: [Record]) -> Result: time_states, final_states = prepare_validate(model.n_state, records) expect = model.simulate(time_states) diff = final_states - expect var = np.sum(diff ** 2) std = np.sqrt(var) err = std / np.sum(expect) * 100 np.set_printoptions(precision=2) return Result(expect, final_states, var, std, err) def _split(l, k) -> [[Record]]: """Split list `l` to `k` lists.""" n = int(np.ceil(len(l) / k)) for i in range(0, len(l), n): yield l[i:i + n] def cross_validate(n_state: int, records: [Record], k: int) -> Result: np.random.shuffle(records) folds = list(_split(records, k)) k = len(folds) print('Size of each sub-sample:', len(folds[0])) var, std, err = [], [], [] for i in range(k): print(f'Test on fold {i + 1}...') test = folds[i] train = chain(*folds[:i], *folds[i:]) model, result = build_simple_model(n_state, train) if model is None: print(f'Fail to build model: {result.message}', file=sys.stderr) return result = validate_model(model, test) var.append(result.var) std.append(result.std) err.append(result.err) var = np.sum(var) / k std = np.sum(std) / k err = np.sum(err) / k return Result(None, None, var, std, err)
[ "numpy.set_printoptions", "numpy.sum", "collections.namedtuple", "itertools.chain", "numpy.random.shuffle", "numpy.sqrt" ]
[((362, 425), 'collections.namedtuple', 'namedtuple', (['"""Reulst"""', "['expect', 'actual', 'var', 'std', 'err']"], {}), "('Reulst', ['expect', 'actual', 'var', 'std', 'err'])\n", (372, 425), False, 'from collections import namedtuple\n'), ((647, 664), 'numpy.sum', 'np.sum', (['(diff ** 2)'], {}), '(diff ** 2)\n', (653, 664), True, 'import numpy as np\n'), ((675, 687), 'numpy.sqrt', 'np.sqrt', (['var'], {}), '(var)\n', (682, 687), True, 'import numpy as np\n'), ((729, 761), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (748, 761), True, 'import numpy as np\n'), ((1060, 1086), 'numpy.random.shuffle', 'np.random.shuffle', (['records'], {}), '(records)\n', (1077, 1086), True, 'import numpy as np\n'), ((1332, 1361), 'itertools.chain', 'chain', (['*folds[:i]', '*folds[i:]'], {}), '(*folds[:i], *folds[i:])\n', (1337, 1361), False, 'from itertools import chain\n'), ((1691, 1702), 'numpy.sum', 'np.sum', (['var'], {}), '(var)\n', (1697, 1702), True, 'import numpy as np\n'), ((1717, 1728), 'numpy.sum', 'np.sum', (['std'], {}), '(std)\n', (1723, 1728), True, 'import numpy as np\n'), ((1743, 1754), 'numpy.sum', 'np.sum', (['err'], {}), '(err)\n', (1749, 1754), True, 'import numpy as np\n'), ((704, 718), 'numpy.sum', 'np.sum', (['expect'], {}), '(expect)\n', (710, 718), True, 'import numpy as np\n')]
import numpy as np import pickle import tensorflow as tf from time import time from evaluate import evaluate_model, evaluate_model_recall_precision class MF(): def __init__(self, rating_matrix): #### 參數設定 self.num_u = rating_matrix.shape[0] # 5551 self.num_v = rating_matrix.shape[1] # 16980 self.u_lambda = 100 self.v_lambda = 0.1 self.k = 50 # latent維度 self.a = 1 self.b = 0.01 self.R = np.mat(rating_matrix) self.C = np.mat(np.ones(self.R.shape)) * self.b self.C[np.where(self.R > 0)] = self.a self.I_U = np.mat(np.eye(self.k) * self.u_lambda) self.I_V = np.mat(np.eye(self.k) * self.v_lambda) self.U = np.mat(np.random.normal(0, 1 / self.u_lambda, size=(self.k, self.num_u))) self.V = np.mat(np.random.normal(0, 1 / self.v_lambda, size=(self.k, self.num_v))) def test(self): print(((U_cut * self.R[np.ravel(np.where(self.R[:, j] > 0)[1]), j] + self.v_lambda * self.V_sdae[j])).shape) def ALS(self, V_sdae): self.V_sdae = np.mat(V_sdae) V_sq = self.V * self.V.T * self.b for i in range(self.num_u): idx_a = np.ravel(np.where(self.R[i, :] > 0)[1]) V_cut = self.V[:, idx_a] self.U[:, i] = np.linalg.pinv(V_sq + V_cut * V_cut.T * (self.a - self.b) + self.I_U) * ( V_cut * self.R[i, idx_a].T) # V_sq+V_cut*V_cut.T*a_m_b = VCV^T U_sq = self.U * self.U.T * self.b for j in range(self.num_v): idx_a = np.ravel(np.where(self.R[:, j] > 0)[1]) U_cut = self.U[:, idx_a] self.V[:, j] = np.linalg.pinv(U_sq + U_cut * U_cut.T * (self.a - self.b) + self.I_V) * ( U_cut * self.R[idx_a, j] + self.v_lambda * np.resize(self.V_sdae[j], (self.k, 1))) return self.U, self.V def mask(corruption_level ,size): print("#### masking noise ") mask = np.random.binomial(1, 1 - corruption_level, [size[0],size[1]]) return mask def add_noise(x , corruption_level ): x = x * mask(corruption_level , x.shape) return x class CDL(): def __init__(self, rating_matrix, item_infomation_matrix, topK=10, recallK=300, precisionK=500, use_recall_precision=False): # model參數設定 self.use_recall_precision = use_recall_precision self.topK =topK self.recallK = recallK self.precisionK = precisionK self.n_input = item_infomation_matrix.shape[1] self.n_hidden1 = 200 self.n_hidden2 = 50 self.k = 50 self.lambda_w = 1 self.lambda_n = 1 self.lambda_u = 1 self.lambda_v = 1 self.drop_ratio = 0.01 self.learning_rate = 0.001 self.epochs = 20 self.batch_size = 32 self.num_u = rating_matrix.shape[0] self.num_v = rating_matrix.shape[1] self.Weights = { 'w1': tf.Variable(tf.random_normal([self.n_input, self.n_hidden1], mean=0.0, stddev=1 / self.lambda_w)), 'w2': tf.Variable(tf.random_normal([self.n_hidden1, self.n_hidden2], mean=0.0, stddev=1 / self.lambda_w)), 'w3': tf.Variable(tf.random_normal([self.n_hidden2, self.n_hidden1], mean=0.0, stddev=1 / self.lambda_w)), 'w4': tf.Variable(tf.random_normal([self.n_hidden1, self.n_input], mean=0.0, stddev=1 / self.lambda_w)) } self.Biases = { 'b1': tf.Variable(tf.random_normal([self.n_hidden1], mean=0.0, stddev=1 / self.lambda_w)), 'b2': tf.Variable(tf.random_normal([self.n_hidden2], mean=0.0, stddev=1 / self.lambda_w)), 'b3': tf.Variable(tf.random_normal([self.n_hidden1], mean=0.0, stddev=1 / self.lambda_w)), 'b4': tf.Variable(tf.random_normal([self.n_input], mean=0.0, stddev=1 / self.lambda_w)) } self.item_infomation_matrix = item_infomation_matrix self.build_model() def encoder(self, x, drop_ratio): w1 = self.Weights['w1'] b1 = self.Biases['b1'] L1 = tf.nn.sigmoid(tf.matmul(x, w1) + b1) L1 = tf.nn.dropout(L1, keep_prob=1 - drop_ratio) w2 = self.Weights['w2'] b2 = self.Biases['b2'] L2 = tf.nn.sigmoid(tf.matmul(L1, w2) + b2) L2 = tf.nn.dropout(L2, keep_prob=1 - drop_ratio) return L2 def decoder(self, x, drop_ratio): w3 = self.Weights['w3'] b3 = self.Biases['b3'] L3 = tf.nn.sigmoid(tf.matmul(x, w3) + b3) L3 = tf.nn.dropout(L3, keep_prob=1 - drop_ratio) w4 = self.Weights['w4'] b4 = self.Biases['b4'] L4 = tf.nn.sigmoid(tf.matmul(L3, w4) + b4) L4 = tf.nn.dropout(L4, keep_prob=1 - drop_ratio) return L4 def build_model(self): self.model_X_0 = tf.placeholder(tf.float32, shape=(None, self.n_input)) self.model_X_c = tf.placeholder(tf.float32, shape=(None, self.n_input)) self.model_V = tf.placeholder(tf.float32, shape=(None, self.k)) self.model_drop_ratio = tf.placeholder(tf.float32) self.V_sdae = self.encoder(self.model_X_0, self.model_drop_ratio) self.y_pred = self.decoder(self.V_sdae, self.model_drop_ratio) self.Regularization = tf.reduce_sum( [tf.nn.l2_loss(w) + tf.nn.l2_loss(b) for w, b in zip(self.Weights.values(), self.Biases.values())]) loss_r = 1 / 2 * self.lambda_w * self.Regularization loss_a = 1 / 2 * self.lambda_n * tf.reduce_sum(tf.pow(self.model_X_c - self.y_pred, 2)) loss_v = 1 / 2 * self.lambda_v * tf.reduce_sum(tf.pow(self.model_V - self.V_sdae, 2)) self.Loss = loss_r + loss_a + loss_v self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.Loss) def training(self, rating_matrix, test_ratings, test_negatives): # np.random.shuffle(self.item_infomation_matrix) #random index of train data evaluation_threads = 1 num_items = rating_matrix.shape[1] self.item_infomation_matrix_noise = add_noise(self.item_infomation_matrix, 0.3) #self.item_infomation_matrix_noise = add_noise(self.item_infomation_matrix, 0.05) sess = tf.Session() sess.run(tf.global_variables_initializer()) mf = MF(rating_matrix) V_sdae = sess.run(self.V_sdae, feed_dict={self.model_X_0: self.item_infomation_matrix_noise, self.model_drop_ratio: self.drop_ratio}) U, V = mf.ALS(V_sdae) U=U.T # Init performance t1 = time() if use_recall_precision: (recalls, precisions) = evaluate_model_recall_precision(U @ V, num_items, test_ratings, self.recallK, self.precisionK, evaluation_threads) recall, precision = np.array(recalls).mean(), np.array(precisions).mean() print('Init: Recall = %.4f, Precision = %.4f\t [%.1f s]' % (recall, precision, time() - t1)) else: (hits, ndcgs) = evaluate_model(U @ V, test_ratings, test_negatives, self.topK, evaluation_threads) hr, ndcg = np.array(hits).mean(), np.array(ndcgs).mean() print('Init: HR = %.4f, NDCG = %.4f\t [%.1f s]' % (hr, ndcg, time() - t1)) # Train model if use_recall_precision: best_recall, best_precision, best_iter = recall, precision, -1 else: best_hr, best_ndcg, best_iter = hr, ndcg, -1 for epoch in range(self.epochs): #print("%d / %d" % (epoch + 1, self.epochs)) t1 = time() V = np.resize(V, (num_items, self.k)) for i in range(0, self.item_infomation_matrix.shape[0], self.batch_size): X_train_batch = self.item_infomation_matrix_noise[i:i + self.batch_size] y_train_batch = self.item_infomation_matrix[i:i + self.batch_size] V_batch = V[i:i + self.batch_size] _, my_loss = sess.run([self.optimizer, self.Loss], feed_dict={self.model_X_0: X_train_batch, self.model_X_c: y_train_batch, self.model_V: V_batch, self.model_drop_ratio: self.drop_ratio}) V_sdae = sess.run(self.V_sdae, feed_dict={self.model_X_0: self.item_infomation_matrix_noise, self.model_drop_ratio: self.drop_ratio}) U, V = mf.ALS(V_sdae) U = U.T t2 = time() # Evaluation if use_recall_precision: (recalls, precisions) = evaluate_model_recall_precision(U @ V, num_items, test_ratings, self.recallK, self.precisionK, evaluation_threads) recall, precision = np.array(recalls).mean(), np.array(precisions).mean() print('Iteration %d [%.1f s]: Recall = %.4f, Precision = %.4f, loss = %.4f [%.1f s]' % (epoch, t2 - t1, recall, precision, my_loss, time() - t2)) if recall > best_recall: best_recall, best_precision, best_iter = recall, precision, epoch else: (hits, ndcgs) = evaluate_model(U @ V, test_ratings, test_negatives, self.topK, evaluation_threads) hr, ndcg = np.array(hits).mean(), np.array(ndcgs).mean() print('Iteration %d [%.1f s]: HR = %.4f, NDCG = %.4f, loss = %.4f [%.1f s]' % (epoch, t2 - t1, hr, ndcg, my_loss, time() - t2)) if hr > best_hr: best_hr, best_ndcg, best_iter = hr, ndcg, epoch if use_recall_precision: print( "End. Best Iteration %d: Recall = %.4f, Precision = %.4f. " % (best_iter, best_recall, best_precision)) else: print("End. Best Iteration %d: HR = %.4f, NDCG = %.4f. " % (best_iter, best_hr, best_ndcg)) return U, V #init random seed np.random.seed(5) print(tf.__version__) import argparse parser = argparse.ArgumentParser(description="Run CDL.") parser.add_argument('--db', nargs='?', default='ml-1m', help='Choose a dataset.') parser.add_argument('--recall_precision', action='store_true', default=False, help='use recall_precision eval.') args = parser.parse_args() use_recall_precision = args.recall_precision db = args.db if use_recall_precision: p=-10 else: p=1 print("#### load matrix from pickle") with open(r'{db}/item_infomation_matrix.pickle'.format(db=db), 'rb') as handle: item_infomation_matrix = pickle.load(handle) with open(r'{db}/rating_matrix_p{p}.pickle'.format(db=db,p=p), 'rb') as handle2: rating_matrix = pickle.load(handle2) print("#### build model") print() print("#### matrix factorization model") cdl = CDL(rating_matrix , item_infomation_matrix, use_recall_precision=use_recall_precision) cdl.build_model() from Dataset import Dataset if use_recall_precision: dataset = Dataset("{db}/{db}.precision-recall".format(db=db), use_recall_precision) else: dataset = Dataset("{db}/{db}.hr-ndcg".format(db=db), use_recall_precision) U, V = cdl.training(rating_matrix,dataset.testRatings, dataset.testNegatives) ''' print(rating_matrix.shape) print(U.shape) print(V.shape) np.save("ml-1m/U",U) np.save("ml-1m/V",V) np.save("ml-1m/R",rating_matrix) np.save("ml-1m/R_",U@V) '''
[ "numpy.random.seed", "argparse.ArgumentParser", "numpy.resize", "evaluate.evaluate_model", "numpy.ones", "tensorflow.matmul", "pickle.load", "numpy.random.normal", "numpy.linalg.pinv", "numpy.mat", "tensorflow.placeholder", "tensorflow.nn.l2_loss", "numpy.random.binomial", "tensorflow.glob...
[((10047, 10064), 'numpy.random.seed', 'np.random.seed', (['(5)'], {}), '(5)\n', (10061, 10064), True, 'import numpy as np\n'), ((10113, 10160), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run CDL."""'}), "(description='Run CDL.')\n", (10136, 10160), False, 'import argparse\n'), ((1953, 2016), 'numpy.random.binomial', 'np.random.binomial', (['(1)', '(1 - corruption_level)', '[size[0], size[1]]'], {}), '(1, 1 - corruption_level, [size[0], size[1]])\n', (1971, 2016), True, 'import numpy as np\n'), ((10673, 10692), 'pickle.load', 'pickle.load', (['handle'], {}), '(handle)\n', (10684, 10692), False, 'import pickle\n'), ((10795, 10815), 'pickle.load', 'pickle.load', (['handle2'], {}), '(handle2)\n', (10806, 10815), False, 'import pickle\n'), ((469, 490), 'numpy.mat', 'np.mat', (['rating_matrix'], {}), '(rating_matrix)\n', (475, 490), True, 'import numpy as np\n'), ((1079, 1093), 'numpy.mat', 'np.mat', (['V_sdae'], {}), '(V_sdae)\n', (1085, 1093), True, 'import numpy as np\n'), ((4094, 4137), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L1'], {'keep_prob': '(1 - drop_ratio)'}), '(L1, keep_prob=1 - drop_ratio)\n', (4107, 4137), True, 'import tensorflow as tf\n'), ((4266, 4309), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L2'], {'keep_prob': '(1 - drop_ratio)'}), '(L2, keep_prob=1 - drop_ratio)\n', (4279, 4309), True, 'import tensorflow as tf\n'), ((4494, 4537), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L3'], {'keep_prob': '(1 - drop_ratio)'}), '(L3, keep_prob=1 - drop_ratio)\n', (4507, 4537), True, 'import tensorflow as tf\n'), ((4666, 4709), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['L4'], {'keep_prob': '(1 - drop_ratio)'}), '(L4, keep_prob=1 - drop_ratio)\n', (4679, 4709), True, 'import tensorflow as tf\n'), ((4782, 4836), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.n_input)'}), '(tf.float32, shape=(None, self.n_input))\n', (4796, 4836), True, 'import tensorflow as tf\n'), ((4862, 4916), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.n_input)'}), '(tf.float32, shape=(None, self.n_input))\n', (4876, 4916), True, 'import tensorflow as tf\n'), ((4940, 4988), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.k)'}), '(tf.float32, shape=(None, self.k))\n', (4954, 4988), True, 'import tensorflow as tf\n'), ((5021, 5047), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (5035, 5047), True, 'import tensorflow as tf\n'), ((6161, 6173), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (6171, 6173), True, 'import tensorflow as tf\n'), ((6513, 6519), 'time.time', 'time', ([], {}), '()\n', (6517, 6519), False, 'from time import time\n'), ((562, 582), 'numpy.where', 'np.where', (['(self.R > 0)'], {}), '(self.R > 0)\n', (570, 582), True, 'import numpy as np\n'), ((733, 798), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1 / self.u_lambda)'], {'size': '(self.k, self.num_u)'}), '(0, 1 / self.u_lambda, size=(self.k, self.num_u))\n', (749, 798), True, 'import numpy as np\n'), ((824, 889), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1 / self.v_lambda)'], {'size': '(self.k, self.num_v)'}), '(0, 1 / self.v_lambda, size=(self.k, self.num_v))\n', (840, 889), True, 'import numpy as np\n'), ((6191, 6224), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (6222, 6224), True, 'import tensorflow as tf\n'), ((6589, 6708), 'evaluate.evaluate_model_recall_precision', 'evaluate_model_recall_precision', (['(U @ V)', 'num_items', 'test_ratings', 'self.recallK', 'self.precisionK', 'evaluation_threads'], {}), '(U @ V, num_items, test_ratings, self.\n recallK, self.precisionK, evaluation_threads)\n', (6620, 6708), False, 'from evaluate import evaluate_model, evaluate_model_recall_precision\n'), ((7005, 7091), 'evaluate.evaluate_model', 'evaluate_model', (['(U @ V)', 'test_ratings', 'test_negatives', 'self.topK', 'evaluation_threads'], {}), '(U @ V, test_ratings, test_negatives, self.topK,\n evaluation_threads)\n', (7019, 7091), False, 'from evaluate import evaluate_model, evaluate_model_recall_precision\n'), ((7563, 7569), 'time.time', 'time', ([], {}), '()\n', (7567, 7569), False, 'from time import time\n'), ((7587, 7620), 'numpy.resize', 'np.resize', (['V', '(num_items, self.k)'], {}), '(V, (num_items, self.k))\n', (7596, 7620), True, 'import numpy as np\n'), ((8471, 8477), 'time.time', 'time', ([], {}), '()\n', (8475, 8477), False, 'from time import time\n'), ((515, 536), 'numpy.ones', 'np.ones', (['self.R.shape'], {}), '(self.R.shape)\n', (522, 536), True, 'import numpy as np\n'), ((619, 633), 'numpy.eye', 'np.eye', (['self.k'], {}), '(self.k)\n', (625, 633), True, 'import numpy as np\n'), ((677, 691), 'numpy.eye', 'np.eye', (['self.k'], {}), '(self.k)\n', (683, 691), True, 'import numpy as np\n'), ((1297, 1366), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(V_sq + V_cut * V_cut.T * (self.a - self.b) + self.I_U)'], {}), '(V_sq + V_cut * V_cut.T * (self.a - self.b) + self.I_U)\n', (1311, 1366), True, 'import numpy as np\n'), ((1662, 1731), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(U_sq + U_cut * U_cut.T * (self.a - self.b) + self.I_V)'], {}), '(U_sq + U_cut * U_cut.T * (self.a - self.b) + self.I_V)\n', (1676, 1731), True, 'import numpy as np\n'), ((2945, 3034), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_input, self.n_hidden1]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_input, self.n_hidden1], mean=0.0, stddev=1 / self.\n lambda_w)\n', (2961, 3034), True, 'import tensorflow as tf\n'), ((3062, 3152), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_hidden1, self.n_hidden2]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_hidden1, self.n_hidden2], mean=0.0, stddev=1 /\n self.lambda_w)\n', (3078, 3152), True, 'import tensorflow as tf\n'), ((3181, 3271), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_hidden2, self.n_hidden1]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_hidden2, self.n_hidden1], mean=0.0, stddev=1 /\n self.lambda_w)\n', (3197, 3271), True, 'import tensorflow as tf\n'), ((3300, 3389), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_hidden1, self.n_input]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_hidden1, self.n_input], mean=0.0, stddev=1 / self.\n lambda_w)\n', (3316, 3389), True, 'import tensorflow as tf\n'), ((3450, 3520), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_hidden1]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_hidden1], mean=0.0, stddev=1 / self.lambda_w)\n', (3466, 3520), True, 'import tensorflow as tf\n'), ((3553, 3623), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_hidden2]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_hidden2], mean=0.0, stddev=1 / self.lambda_w)\n', (3569, 3623), True, 'import tensorflow as tf\n'), ((3656, 3726), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_hidden1]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_hidden1], mean=0.0, stddev=1 / self.lambda_w)\n', (3672, 3726), True, 'import tensorflow as tf\n'), ((3759, 3827), 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_input]'], {'mean': '(0.0)', 'stddev': '(1 / self.lambda_w)'}), '([self.n_input], mean=0.0, stddev=1 / self.lambda_w)\n', (3775, 3827), True, 'import tensorflow as tf\n'), ((4058, 4074), 'tensorflow.matmul', 'tf.matmul', (['x', 'w1'], {}), '(x, w1)\n', (4067, 4074), True, 'import tensorflow as tf\n'), ((4229, 4246), 'tensorflow.matmul', 'tf.matmul', (['L1', 'w2'], {}), '(L1, w2)\n', (4238, 4246), True, 'import tensorflow as tf\n'), ((4458, 4474), 'tensorflow.matmul', 'tf.matmul', (['x', 'w3'], {}), '(x, w3)\n', (4467, 4474), True, 'import tensorflow as tf\n'), ((4629, 4646), 'tensorflow.matmul', 'tf.matmul', (['L3', 'w4'], {}), '(L3, w4)\n', (4638, 4646), True, 'import tensorflow as tf\n'), ((5468, 5507), 'tensorflow.pow', 'tf.pow', (['(self.model_X_c - self.y_pred)', '(2)'], {}), '(self.model_X_c - self.y_pred, 2)\n', (5474, 5507), True, 'import tensorflow as tf\n'), ((5564, 5601), 'tensorflow.pow', 'tf.pow', (['(self.model_V - self.V_sdae)', '(2)'], {}), '(self.model_V - self.V_sdae, 2)\n', (5570, 5601), True, 'import tensorflow as tf\n'), ((5674, 5716), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.learning_rate'], {}), '(self.learning_rate)\n', (5696, 5716), True, 'import tensorflow as tf\n'), ((8581, 8700), 'evaluate.evaluate_model_recall_precision', 'evaluate_model_recall_precision', (['(U @ V)', 'num_items', 'test_ratings', 'self.recallK', 'self.precisionK', 'evaluation_threads'], {}), '(U @ V, num_items, test_ratings, self.\n recallK, self.precisionK, evaluation_threads)\n', (8612, 8700), False, 'from evaluate import evaluate_model, evaluate_model_recall_precision\n'), ((9291, 9377), 'evaluate.evaluate_model', 'evaluate_model', (['(U @ V)', 'test_ratings', 'test_negatives', 'self.topK', 'evaluation_threads'], {}), '(U @ V, test_ratings, test_negatives, self.topK,\n evaluation_threads)\n', (9305, 9377), False, 'from evaluate import evaluate_model, evaluate_model_recall_precision\n'), ((1202, 1228), 'numpy.where', 'np.where', (['(self.R[i, :] > 0)'], {}), '(self.R[i, :] > 0)\n', (1210, 1228), True, 'import numpy as np\n'), ((1567, 1593), 'numpy.where', 'np.where', (['(self.R[:, j] > 0)'], {}), '(self.R[:, j] > 0)\n', (1575, 1593), True, 'import numpy as np\n'), ((5253, 5269), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['w'], {}), '(w)\n', (5266, 5269), True, 'import tensorflow as tf\n'), ((5272, 5288), 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['b'], {}), '(b)\n', (5285, 5288), True, 'import tensorflow as tf\n'), ((1803, 1841), 'numpy.resize', 'np.resize', (['self.V_sdae[j]', '(self.k, 1)'], {}), '(self.V_sdae[j], (self.k, 1))\n', (1812, 1841), True, 'import numpy as np\n'), ((6804, 6821), 'numpy.array', 'np.array', (['recalls'], {}), '(recalls)\n', (6812, 6821), True, 'import numpy as np\n'), ((6830, 6850), 'numpy.array', 'np.array', (['precisions'], {}), '(precisions)\n', (6838, 6850), True, 'import numpy as np\n'), ((7111, 7125), 'numpy.array', 'np.array', (['hits'], {}), '(hits)\n', (7119, 7125), True, 'import numpy as np\n'), ((7134, 7149), 'numpy.array', 'np.array', (['ndcgs'], {}), '(ndcgs)\n', (7142, 7149), True, 'import numpy as np\n'), ((6949, 6955), 'time.time', 'time', ([], {}), '()\n', (6953, 6955), False, 'from time import time\n'), ((7230, 7236), 'time.time', 'time', ([], {}), '()\n', (7234, 7236), False, 'from time import time\n'), ((8876, 8893), 'numpy.array', 'np.array', (['recalls'], {}), '(recalls)\n', (8884, 8893), True, 'import numpy as np\n'), ((8902, 8922), 'numpy.array', 'np.array', (['precisions'], {}), '(precisions)\n', (8910, 8922), True, 'import numpy as np\n'), ((9401, 9415), 'numpy.array', 'np.array', (['hits'], {}), '(hits)\n', (9409, 9415), True, 'import numpy as np\n'), ((9424, 9439), 'numpy.array', 'np.array', (['ndcgs'], {}), '(ndcgs)\n', (9432, 9439), True, 'import numpy as np\n'), ((9100, 9106), 'time.time', 'time', ([], {}), '()\n', (9104, 9106), False, 'from time import time\n'), ((9599, 9605), 'time.time', 'time', ([], {}), '()\n', (9603, 9605), False, 'from time import time\n'), ((952, 978), 'numpy.where', 'np.where', (['(self.R[:, j] > 0)'], {}), '(self.R[:, j] > 0)\n', (960, 978), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np import json import soundfile as sf import os import argparse def nsynth_generator(tfrecords): for serialized_example in tf.python_io.tf_record_iterator(tfrecords): example = tf.train.Example() example.ParseFromString(serialized_example) f = example.features.feature audio = np.array(f['audio'].float_list.value) data = { 'note': f['note'].int64_list.value[0], 'note_str': f['note_str'].bytes_list.value[0], 'instrument': f['instrument'].int64_list.value[0], 'instrument_str': f['instrument_str'].bytes_list.value[0], 'pitch': f['pitch'].int64_list.value[0], 'velocity': f['pitch'].int64_list.value[0], 'samplerate': f['sample_rate'].int64_list.value[0], 'qualities': map(int, f['qualities'].int64_list.value), 'qualities_str': map(str, f['qualities_str'].int64_list.value), 'instrument_family': f['instrument_family'].int64_list.value[0], 'instrument_family_str': f['instrument_family_str'].bytes_list.value[0], 'instrument_source': f['instrument_source'].int64_list.value[0], 'instrument_source_str': f['instrument_source_str'].bytes_list.value[0], } yield data, audio if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'input', ) parser.add_argument( 'out_dir', ) args = parser.parse_args() if not os.path.exists(args.out_dir): os.makedirs(args.out_dir) for data, audio in nsynth_generator(args.input): base_file_str = data['note_str'] json_path = os.path.join(args.out_dir, base_file_str + '.json') audio_path = os.path.join(args.out_dir, base_file_str + '.wav') with open(json_path, 'w') as outfile: json.dump(data, outfile, indent=4, sort_keys=False) sf.write(audio_path, audio, data['samplerate'])
[ "json.dump", "argparse.ArgumentParser", "os.makedirs", "tensorflow.train.Example", "os.path.exists", "numpy.array", "soundfile.write", "os.path.join", "tensorflow.python_io.tf_record_iterator" ]
[((169, 211), 'tensorflow.python_io.tf_record_iterator', 'tf.python_io.tf_record_iterator', (['tfrecords'], {}), '(tfrecords)\n', (200, 211), True, 'import tensorflow as tf\n'), ((1583, 1608), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1606, 1608), False, 'import argparse\n'), ((231, 249), 'tensorflow.train.Example', 'tf.train.Example', ([], {}), '()\n', (247, 249), True, 'import tensorflow as tf\n'), ((356, 393), 'numpy.array', 'np.array', (["f['audio'].float_list.value"], {}), "(f['audio'].float_list.value)\n", (364, 393), True, 'import numpy as np\n'), ((1750, 1778), 'os.path.exists', 'os.path.exists', (['args.out_dir'], {}), '(args.out_dir)\n', (1764, 1778), False, 'import os\n'), ((1788, 1813), 'os.makedirs', 'os.makedirs', (['args.out_dir'], {}), '(args.out_dir)\n', (1799, 1813), False, 'import os\n'), ((1930, 1981), 'os.path.join', 'os.path.join', (['args.out_dir', "(base_file_str + '.json')"], {}), "(args.out_dir, base_file_str + '.json')\n", (1942, 1981), False, 'import os\n'), ((2003, 2053), 'os.path.join', 'os.path.join', (['args.out_dir', "(base_file_str + '.wav')"], {}), "(args.out_dir, base_file_str + '.wav')\n", (2015, 2053), False, 'import os\n'), ((2173, 2220), 'soundfile.write', 'sf.write', (['audio_path', 'audio', "data['samplerate']"], {}), "(audio_path, audio, data['samplerate'])\n", (2181, 2220), True, 'import soundfile as sf\n'), ((2112, 2163), 'json.dump', 'json.dump', (['data', 'outfile'], {'indent': '(4)', 'sort_keys': '(False)'}), '(data, outfile, indent=4, sort_keys=False)\n', (2121, 2163), False, 'import json\n')]
# -*- coding: utf-8 -*- # Copyright (c) 2021-2022 the DerivX authors # All rights reserved. # # The project sponsor and lead author is <NAME>. # E-mail: <EMAIL>, QQ: 277195007, WeChat: ustc_xrd # See the contributors file for names of other contributors. # # Commercial use of this code in source and binary forms is # governed by a LGPL v3 license. You may get a copy from the # root directory. Or else you should get a specific written # permission from the project author. # # Individual and educational use of this code in source and # binary forms is governed by a 3-clause BSD license. You may # get a copy from the root directory. Certainly welcome you # to contribute code of all sorts. # # Be sure to retain the above copyright notice and conditions. import numpy as np import matplotlib.pyplot as plt np.set_printoptions(suppress = True) # 不以科学计数法输出 np.set_printoptions(threshold = np.inf) # 指定超过多少使用省略号,np.inf 为无限大 def ShowPlot_Frequency(price, title, xlabel): n, bins, patches = plt.hist(price[:, -1], bins = 50, normed = True, facecolor = "blue", alpha = 0.75) plt.title(title) plt.xlabel(xlabel) plt.ylabel("Frequency") plt.grid(True, alpha = 0.5) plt.show() def ShowPlot_Distribution(price, path, step, title, ylabel): plt.figure() ax = plt.subplot2grid((1, 1), (0, 0), colspan = 1, rowspan = 1) ax.set_xlabel("Steps") ax.set_ylabel(ylabel) for i in range(path): ax.plot(range(step), price[i, :], color = np.random.rand(3), ls = "-", lw = 1.0) #ax.legend(loc = "best") # 不显示图例 ax.margins(0, 0) # 0 ~ 1 ax.set_title(title) plt.subplots_adjust(left = 0.05, bottom = 0.05, right = 0.99, top = 0.98, wspace = 0.0, hspace = 0.0) plt.grid(True, alpha = 0.5) plt.show() # 几何布朗运动 (指数布朗运动) Geometric Brownian Motion # 被Black-Scholes(1973)引入到期权定价文献中,虽然这个过程有一些缺陷,并且与实证研究存在着冲突,但是仍然是一种期权和衍生品估值过程的基础过程。 def SP_GBM(): s = 1.0 # 初始价格 r = 0.03 # 无风险利率,期望收益率 v = 0.24 # 收益率波动率 t = 1.0 # 时间长度 year_days = 252 # 年交易日数 dt = t / year_days # 步长时间 step = int(year_days * t) + 1 path = 10000 # 路径数量 price = np.zeros((path, step)) price[:, 0] = s for i in range(1, step): price[:, i] = price[:, i - 1] * np.exp((r - 0.5 * v ** 2) * dt + v * np.sqrt(dt) * np.random.standard_normal(path)) ShowPlot_Frequency(price, "Final-Price-Frequency", "Final-Price") ShowPlot_Distribution(price, 1000, step, "Price - Steps", "Price") # CIR模型 (平方根扩散过程) Cox–Ingersoll–Ross model (Square-Root Diffusion) # 由Cox、Ingersoll和Ross(1985)所提出,用于对均值回复的数量,例如利率或波动率进行建模,除了均值回复的特性以外,这个过程总是保持为正数。 def SP_CIR(): s = 0.05 # 初始利息率 kappa = 3.0 # 均值回归系数 theta = 0.02 # 长期均值项 sigma = 0.1 # 利息率波动率 t = 2.0 # 时间长度 year_days = 252 # 年交易日数 dt = t / year_days # 步长时间 step = int(year_days * t) + 1 path = 10000 # 路径数量 price = np.zeros((path, step)) price[:, 0] = s for i in range(1, step): d_price = kappa * (theta - np.maximum(price[:, i - 1], 0.0)) * dt + sigma * np.sqrt(np.maximum(price[:, i - 1], 0.0)) * np.sqrt(dt) * np.random.standard_normal(path) price[:, i] = price[:, i - 1] + d_price price = np.maximum(price, 0.0) ShowPlot_Frequency(price, "Final-Interest-Frequency", "Final-Interest") ShowPlot_Distribution(price, 1000, step, "Interest - Steps", "Interest") # 跳跃扩散过程 Jump Diffusion Process # 由Merton(1976)所给出,为几何布朗运动增加了对数正态分布的条约成分,这允许我们考虑,例如,短期虚值(OTM)的期权通常需要在较大条约的可能性下定价。 def SP_JDP(): s = 1.0 # 初始价格 r = 0.05 # 收益率均值,漂移率 v = 0.24 # 收益率波动率 lamb = 0.75 # 跳跃强度 mu = 0.6 # 预期跳跃均值,正负决定跳跃方向,需要改进 delta = 0.25 # 跳跃强度标准差 t = 1.0 # 时间长度 year_days = 252 # 年交易日数 dt = t / year_days # 步长时间 step = int(year_days * t) + 1 path = 10000 # 路径数量 price = np.zeros((path, step)) price[:, 0] = s kappa = lamb * (np.exp(mu + 0.5 * delta ** 2) - 1.0) sn1 = np.random.standard_normal((path, step)) sn2 = np.random.standard_normal((path, step)) poi = np.random.poisson(lamb * dt, (path, step)) for i in range(1, step): price[:, i] = price[:, i - 1] * (np.exp((r - kappa - 0.5 * v ** 2) * dt) + v * np.sqrt(dt) * sn1[:, i] + (np.exp(mu + delta * sn2[:, i]) - 1.0) * poi[:, i]) price[:, i] = np.maximum(price[:, i], 0.0) ShowPlot_Frequency(price, "Final-Price-Frequency", "Final-Price") ShowPlot_Distribution(price, 1000, step, "Price - Steps", "Price") # Heston模型 (随机波动率模型) Heston Model (Stochastic Volatility Model) # 由<NAME>(1993)提出的描述标的资产波动率变化的数学模型,这种模型假设资产收益率的波动率并不恒定,也不确定,而是跟随一个随机过程来运动。 def SP_HEST(): s = 1.0 # 初始价格 r = 0.03 # 收益率均值,漂移率 v = 0.1 # 初始波动率 kappa = 3.0 # 波动率均值回归速度 theta = 0.25 # 波动率长期均值项 sigma = 0.1 # 波动率的波动率 rho = 0.6 # 两个随机过程的相关系数 t = 1.0 # 时间长度 year_days = 252 # 年交易日数 dt = t / year_days # 步长时间 step = int(year_days * t) + 1 path = 10000 # 路径数量 #corr_mat = np.zeros((2, 2)) #corr_mat[0, :] = [1.0, rho] #corr_mat[1, :] = [rho, 1.0] corr_mat = [[1.0, rho], [rho, 1.0]] chol_mat = np.linalg.cholesky(corr_mat) # 两个随机过程的相关系数的 Cholesky 分解 rand_mat = np.random.standard_normal((2, path, step)) # 这里也可以用对偶采样法减少数据生成量 vol = np.zeros((path, step)) vol[:, 0] = v for i in range(1, step): rand = np.dot(chol_mat, rand_mat[:, :, i]) # 也可以用:chol_mat @ rand_mat[:, :, i] d_vol = kappa * (theta - np.maximum(vol[:, i - 1], 0.0)) * dt + sigma * np.sqrt(np.maximum(vol[:, i - 1], 0.0)) * np.sqrt(dt) * rand[1] vol[:, i] = vol[:, i - 1] + d_vol vol = np.maximum(vol, 0.0) ShowPlot_Frequency(vol, "Final-vol-Frequency", "Final-vol") ShowPlot_Distribution(vol, 1000, step, "vol - Steps", "vol") price = np.zeros((path, step)) price[:, 0] = s for i in range(1, step): rand = np.dot(chol_mat, rand_mat[:, :, i]) # 也可以用:chol_mat @ rand_mat[:, :, i] price[:, i] = price[:, i - 1] * np.exp((r - 0.5 * vol[:, i]) * dt + np.sqrt(vol[:, i]) * rand[0] * np.sqrt(dt)) ShowPlot_Frequency(price, "Final-Price-Frequency", "Final-Price") ShowPlot_Distribution(price, 1000, step, "Price - Steps", "Price") # SABR模型 Stochastic Alpha Beta Rho # 由Hagan(2002)提出的一种随机波动率模型,在抛弃了原始的BSM模型中对于波动率为某一常数的假定,假设隐含波动率同样是符合几何布朗运动的, # 并且将隐含波动率设定为标的价格和合约行权价的函数,结合了隐含波动率修正模型的两种思路(随机波动率模型和局部波动率模型),更为准确的动态刻画出吻合市场特征的隐含波动率曲线。 def SP_SABR(): s = 0.06 # 初始远期利率 v = 0.2 # 初始波动率 beta = 0.5 # 远期利率分布的力度 rho = 0.6 # 两个随机过程的相关系数 sigma = 0.2 # 波动率的波动率 t = 1.0 # 时间长度 year_days = 252 # 年交易日数 dt = t / year_days # 步长时间 step = int(year_days * t) + 1 path = 10000 # 路径数量 #corr_mat = np.zeros((2, 2)) #corr_mat[0, :] = [1.0, rho] #corr_mat[1, :] = [rho, 1.0] corr_mat = [[1.0, rho], [rho, 1.0]] chol_mat = np.linalg.cholesky(corr_mat) # 两个相关随机过程的 Cholesky 分解 rand_mat = np.random.standard_normal((2, path, step)) # 这里也可以用对偶采样法减少数据生成量 vol = np.zeros((path, step)) vol[:, 0] = v for i in range(1, step): rand = np.dot(chol_mat, rand_mat[:, :, i]) # 也可以用:chol_mat @ rand_mat[:, :, i] d_vol = sigma * np.maximum(vol[:, i - 1], 0.0) * np.sqrt(dt) * rand[1] vol[:, i] = vol[:, i - 1] + d_vol vol = np.maximum(vol, 0.0) ShowPlot_Frequency(vol, "Final-vol-Frequency", "Final-vol") ShowPlot_Distribution(vol, 1000, step, "vol - Steps", "vol") price = np.zeros((path, step)) price[:, 0] = s for i in range(1, step): rand = np.dot(chol_mat, rand_mat[:, :, i]) # 也可以用:chol_mat @ rand_mat[:, :, i] d_price = vol[:, i - 1] * np.power(np.maximum(price[:, i - 1], 0.0), beta) * np.sqrt(dt) * rand[0] # price 会有小于零的异常值出现的,故增加 np.maximum 判断 price[:, i] = price[:, i - 1] + d_price ShowPlot_Frequency(price, "Final-Price-Frequency", "Final-Price") ShowPlot_Distribution(price, 1000, step, "Price - Steps", "Price") if __name__ == "__main__": #SP_GBM() #SP_CIR() #SP_JDP() #SP_HEST() SP_SABR()
[ "matplotlib.pyplot.title", "numpy.maximum", "matplotlib.pyplot.subplot2grid", "matplotlib.pyplot.figure", "numpy.exp", "numpy.set_printoptions", "numpy.random.poisson", "numpy.linalg.cholesky", "matplotlib.pyplot.show", "numpy.random.standard_normal", "matplotlib.pyplot.subplots_adjust", "nump...
[((816, 850), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (835, 850), True, 'import numpy as np\n'), ((865, 902), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': 'np.inf'}), '(threshold=np.inf)\n', (884, 902), True, 'import numpy as np\n'), ((1001, 1075), 'matplotlib.pyplot.hist', 'plt.hist', (['price[:, -1]'], {'bins': '(50)', 'normed': '(True)', 'facecolor': '"""blue"""', 'alpha': '(0.75)'}), "(price[:, -1], bins=50, normed=True, facecolor='blue', alpha=0.75)\n", (1009, 1075), True, 'import matplotlib.pyplot as plt\n'), ((1088, 1104), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1097, 1104), True, 'import matplotlib.pyplot as plt\n'), ((1109, 1127), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (1119, 1127), True, 'import matplotlib.pyplot as plt\n'), ((1132, 1155), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Frequency"""'], {}), "('Frequency')\n", (1142, 1155), True, 'import matplotlib.pyplot as plt\n'), ((1160, 1185), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'alpha': '(0.5)'}), '(True, alpha=0.5)\n', (1168, 1185), True, 'import matplotlib.pyplot as plt\n'), ((1192, 1202), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1200, 1202), True, 'import matplotlib.pyplot as plt\n'), ((1269, 1281), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1279, 1281), True, 'import matplotlib.pyplot as plt\n'), ((1291, 1345), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(1, 1)', '(0, 0)'], {'colspan': '(1)', 'rowspan': '(1)'}), '((1, 1), (0, 0), colspan=1, rowspan=1)\n', (1307, 1345), True, 'import matplotlib.pyplot as plt\n'), ((1612, 1706), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.05)', 'bottom': '(0.05)', 'right': '(0.99)', 'top': '(0.98)', 'wspace': '(0.0)', 'hspace': '(0.0)'}), '(left=0.05, bottom=0.05, right=0.99, top=0.98, wspace=\n 0.0, hspace=0.0)\n', (1631, 1706), True, 'import matplotlib.pyplot as plt\n'), ((1718, 1743), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'alpha': '(0.5)'}), '(True, alpha=0.5)\n', (1726, 1743), True, 'import matplotlib.pyplot as plt\n'), ((1750, 1760), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1758, 1760), True, 'import matplotlib.pyplot as plt\n'), ((2122, 2144), 'numpy.zeros', 'np.zeros', (['(path, step)'], {}), '((path, step))\n', (2130, 2144), True, 'import numpy as np\n'), ((2874, 2896), 'numpy.zeros', 'np.zeros', (['(path, step)'], {}), '((path, step))\n', (2882, 2896), True, 'import numpy as np\n'), ((3180, 3202), 'numpy.maximum', 'np.maximum', (['price', '(0.0)'], {}), '(price, 0.0)\n', (3190, 3202), True, 'import numpy as np\n'), ((3794, 3816), 'numpy.zeros', 'np.zeros', (['(path, step)'], {}), '((path, step))\n', (3802, 3816), True, 'import numpy as np\n'), ((3904, 3943), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(path, step)'], {}), '((path, step))\n', (3929, 3943), True, 'import numpy as np\n'), ((3954, 3993), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(path, step)'], {}), '((path, step))\n', (3979, 3993), True, 'import numpy as np\n'), ((4004, 4046), 'numpy.random.poisson', 'np.random.poisson', (['(lamb * dt)', '(path, step)'], {}), '(lamb * dt, (path, step))\n', (4021, 4046), True, 'import numpy as np\n'), ((5061, 5089), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['corr_mat'], {}), '(corr_mat)\n', (5079, 5089), True, 'import numpy as np\n'), ((5132, 5174), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(2, path, step)'], {}), '((2, path, step))\n', (5157, 5174), True, 'import numpy as np\n'), ((5211, 5233), 'numpy.zeros', 'np.zeros', (['(path, step)'], {}), '((path, step))\n', (5219, 5233), True, 'import numpy as np\n'), ((5564, 5584), 'numpy.maximum', 'np.maximum', (['vol', '(0.0)'], {}), '(vol, 0.0)\n', (5574, 5584), True, 'import numpy as np\n'), ((5736, 5758), 'numpy.zeros', 'np.zeros', (['(path, step)'], {}), '((path, step))\n', (5744, 5758), True, 'import numpy as np\n'), ((6792, 6820), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['corr_mat'], {}), '(corr_mat)\n', (6810, 6820), True, 'import numpy as np\n'), ((6860, 6902), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(2, path, step)'], {}), '((2, path, step))\n', (6885, 6902), True, 'import numpy as np\n'), ((6939, 6961), 'numpy.zeros', 'np.zeros', (['(path, step)'], {}), '((path, step))\n', (6947, 6961), True, 'import numpy as np\n'), ((7227, 7247), 'numpy.maximum', 'np.maximum', (['vol', '(0.0)'], {}), '(vol, 0.0)\n', (7237, 7247), True, 'import numpy as np\n'), ((7399, 7421), 'numpy.zeros', 'np.zeros', (['(path, step)'], {}), '((path, step))\n', (7407, 7421), True, 'import numpy as np\n'), ((4263, 4291), 'numpy.maximum', 'np.maximum', (['price[:, i]', '(0.0)'], {}), '(price[:, i], 0.0)\n', (4273, 4291), True, 'import numpy as np\n'), ((5296, 5331), 'numpy.dot', 'np.dot', (['chol_mat', 'rand_mat[:, :, i]'], {}), '(chol_mat, rand_mat[:, :, i])\n', (5302, 5331), True, 'import numpy as np\n'), ((5823, 5858), 'numpy.dot', 'np.dot', (['chol_mat', 'rand_mat[:, :, i]'], {}), '(chol_mat, rand_mat[:, :, i])\n', (5829, 5858), True, 'import numpy as np\n'), ((7024, 7059), 'numpy.dot', 'np.dot', (['chol_mat', 'rand_mat[:, :, i]'], {}), '(chol_mat, rand_mat[:, :, i])\n', (7030, 7059), True, 'import numpy as np\n'), ((7486, 7521), 'numpy.dot', 'np.dot', (['chol_mat', 'rand_mat[:, :, i]'], {}), '(chol_mat, rand_mat[:, :, i])\n', (7492, 7521), True, 'import numpy as np\n'), ((3857, 3886), 'numpy.exp', 'np.exp', (['(mu + 0.5 * delta ** 2)'], {}), '(mu + 0.5 * delta ** 2)\n', (3863, 3886), True, 'import numpy as np\n'), ((1479, 1496), 'numpy.random.rand', 'np.random.rand', (['(3)'], {}), '(3)\n', (1493, 1496), True, 'import numpy as np\n'), ((3088, 3119), 'numpy.random.standard_normal', 'np.random.standard_normal', (['path'], {}), '(path)\n', (3113, 3119), True, 'import numpy as np\n'), ((7153, 7164), 'numpy.sqrt', 'np.sqrt', (['dt'], {}), '(dt)\n', (7160, 7164), True, 'import numpy as np\n'), ((7643, 7654), 'numpy.sqrt', 'np.sqrt', (['dt'], {}), '(dt)\n', (7650, 7654), True, 'import numpy as np\n'), ((3074, 3085), 'numpy.sqrt', 'np.sqrt', (['dt'], {}), '(dt)\n', (3081, 3085), True, 'import numpy as np\n'), ((4117, 4156), 'numpy.exp', 'np.exp', (['((r - kappa - 0.5 * v ** 2) * dt)'], {}), '((r - kappa - 0.5 * v ** 2) * dt)\n', (4123, 4156), True, 'import numpy as np\n'), ((5490, 5501), 'numpy.sqrt', 'np.sqrt', (['dt'], {}), '(dt)\n', (5497, 5501), True, 'import numpy as np\n'), ((7120, 7150), 'numpy.maximum', 'np.maximum', (['vol[:, i - 1]', '(0.0)'], {}), '(vol[:, i - 1], 0.0)\n', (7130, 7150), True, 'import numpy as np\n'), ((2285, 2316), 'numpy.random.standard_normal', 'np.random.standard_normal', (['path'], {}), '(path)\n', (2310, 2316), True, 'import numpy as np\n'), ((2981, 3013), 'numpy.maximum', 'np.maximum', (['price[:, i - 1]', '(0.0)'], {}), '(price[:, i - 1], 0.0)\n', (2991, 3013), True, 'import numpy as np\n'), ((4190, 4220), 'numpy.exp', 'np.exp', (['(mu + delta * sn2[:, i])'], {}), '(mu + delta * sn2[:, i])\n', (4196, 4220), True, 'import numpy as np\n'), ((5401, 5431), 'numpy.maximum', 'np.maximum', (['vol[:, i - 1]', '(0.0)'], {}), '(vol[:, i - 1], 0.0)\n', (5411, 5431), True, 'import numpy as np\n'), ((6002, 6013), 'numpy.sqrt', 'np.sqrt', (['dt'], {}), '(dt)\n', (6009, 6013), True, 'import numpy as np\n'), ((7601, 7633), 'numpy.maximum', 'np.maximum', (['price[:, i - 1]', '(0.0)'], {}), '(price[:, i - 1], 0.0)\n', (7611, 7633), True, 'import numpy as np\n'), ((2271, 2282), 'numpy.sqrt', 'np.sqrt', (['dt'], {}), '(dt)\n', (2278, 2282), True, 'import numpy as np\n'), ((3038, 3070), 'numpy.maximum', 'np.maximum', (['price[:, i - 1]', '(0.0)'], {}), '(price[:, i - 1], 0.0)\n', (3048, 3070), True, 'import numpy as np\n'), ((4163, 4174), 'numpy.sqrt', 'np.sqrt', (['dt'], {}), '(dt)\n', (4170, 4174), True, 'import numpy as np\n'), ((5456, 5486), 'numpy.maximum', 'np.maximum', (['vol[:, i - 1]', '(0.0)'], {}), '(vol[:, i - 1], 0.0)\n', (5466, 5486), True, 'import numpy as np\n'), ((5971, 5989), 'numpy.sqrt', 'np.sqrt', (['vol[:, i]'], {}), '(vol[:, i])\n', (5978, 5989), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Sat Mar 28 21:48:04 2020 @author: <NAME> Creates elements of Figs. 5 and 7 (results) from the PPSN 2020 paper. """ import os import csv import numpy as np import matplotlib.pyplot as plt import matplotlib from matplotlib import rcParams import seaborn as sns; sns.set(color_codes=True) import ParetoFrontND as pf import StandardTestFunctions as fn plt.style.use('ggplot') rcParams['font.sans-serif'] = "Segoe UI" rcParams['font.family'] = "sans-serif" plot_size = 10.0 # %% Get function properties FUNCTION_NAME = "DTLZ7" NUM_INPUT_DIMS = 10 NUM_OBJECTIVES = 2 NUM_TOTAL_EVALUATIONS = 300 NUM_SAMPLES = NUM_INPUT_DIMS * 4 d2F1F2_PF = fn.get_M2_pareto_front(FUNCTION_NAME) d1Reference = [max(d2F1F2_PF[:,0]) * 1.1, max(d2F1F2_PF[:,1]) * 1.1] max_hypervolume = pf.calculateHypervolume(d2F1F2_PF, d1Reference) domain, fitnessfunc, _, NUM_INPUT_DIMS, NUM_OBJECTIVES = fn.get_function_definition( FUNCTION_NAME, NUM_INPUT_DIMS, NUM_OBJECTIVES) # %% Load data def load_data(folder: str): filename_hv = 'summary_hv_ref_{0:.2f}_{1:.2f}.csv'.format(d1Reference[0], d1Reference[1]) filename_igd = 'summary_igd.csv' filename_f1 = 'summary_finalset_f{}.csv'.format(1) filename_f2 = 'summary_finalset_f{}.csv'.format(2) all_hv = np.genfromtxt(os.path.join(folder, filename_hv), delimiter=',') all_igd = np.genfromtxt(os.path.join(folder, filename_igd), delimiter=',') d1NumPointsInNds = np.zeros((21, 1)) d2AllNdsPoints = [] with open(os.path.join(folder, filename_f1), 'r') as fid_f1: rdr_f1 = csv.reader(fid_f1) with open(os.path.join(folder, filename_f2), 'r') as fid_f2: rdr_f2 = csv.reader(fid_f2) for o in range(21): opt_f1s = next(rdr_f1) opt_f2s = next(rdr_f2) for p in range(len(opt_f1s)): f1 = float(opt_f1s[p]) f2 = float(opt_f2s[p]) if f1 != 0.0 or f2 != 0.0: d1NumPointsInNds[o] += 1 d2AllNdsPoints.append(np.array([f1, f2])) d2AllNdsPoints = np.array(d2AllNdsPoints) return d1NumPointsInNds, d2AllNdsPoints, all_hv, all_igd # %% xHVI ZETA = 0.0 folder_xhvi = os.path.join("Results_Detailed_Timed", FUNCTION_NAME + "_D{1}_M{2}_Z{0:.2f}_Rnorm".format(ZETA, NUM_INPUT_DIMS, NUM_OBJECTIVES)) d1NumPointsInNds_xhvi, d2AllNdsPoints_xhvi, all_hv_xhvi, all_igd_xhvi = load_data(folder_xhvi) # %% HypI ZETA = 0.0 folder_hypi = os.path.join("Results_Detailed_HypI_Timed", FUNCTION_NAME + "_D{1}_M{2}_Z{0:.2f}_Rnorm".format(ZETA, NUM_INPUT_DIMS, NUM_OBJECTIVES)) d1NumPointsInNds_hypi, d2AllNdsPoints_hypi, all_hv_hypi, all_igd_hypi = load_data(folder_hypi) # %% EHVI folder_ehvi = os.path.join("Results_Detailed_EHVI_Timed", FUNCTION_NAME + "_D{0}_norm_M{1}".format(NUM_INPUT_DIMS, NUM_OBJECTIVES)) d1NumPointsInNds_ehvi, d2AllNdsPoints_ehvi, all_hv_ehvi, all_igd_ehvi = load_data(folder_ehvi) # %% Plot HV and IGD learning traces # def plot_trace(data, ylab, ylim_min, ylim_max): # fig = plt.figure(figsize=[plot_size*1.62, plot_size]) # x_vals = np.arange(NUM_SAMPLES, NUM_TOTAL_EVALUATIONS + 1) # plt.plot(x_vals, # np.median(data[:, NUM_SAMPLES-1:NUM_TOTAL_EVALUATIONS], axis=0), # linewidth=2, color='k', label='Median') # plt.plot(x_vals, # np.percentile(data[:, NUM_SAMPLES-1:NUM_TOTAL_EVALUATIONS], 75, axis=0), # linewidth=1, color='r', label='Upper quartile') # plt.plot(x_vals, # np.percentile(data[:, NUM_SAMPLES-1:NUM_TOTAL_EVALUATIONS], 25, axis=0), # linewidth=1, color='g', label='Lower quartile') # iWorst = np.argmax(data[:,-1]) # plt.plot(x_vals, # data[iWorst, NUM_SAMPLES-1:NUM_TOTAL_EVALUATIONS], # linewidth=1, color='r', linestyle='--', label='Worst') # # plt.plot(range(d2HypervolumeLoss.shape[0]), # # np.max(d2HypervolumeLoss, axis=1), # # linewidth=1, color='r', linestyle='--', label='Worst') # iBest = np.argmin(data[:,-1]) # # plt.plot(range(d2HypervolumeLoss.shape[0]), # # np.min(d2HypervolumeLoss, axis=1), # # linewidth=1, color='g', linestyle='--', label='Best') # plt.plot(x_vals, # data[iBest, NUM_SAMPLES-1:NUM_TOTAL_EVALUATIONS], # linewidth=1, color='g', linestyle='--', label='Best') # plt.ylim(ylim_min, ylim_max) # plt.xlim([0, NUM_TOTAL_EVALUATIONS]) # plt.legend(loc='upper right', fontsize=plot_size*2.0, labelspacing=0.25) # plt.ylabel(ylab, fontsize=plot_size*3.0) # plt.xlabel("Number of evaluations", fontsize=plot_size*3.0) # for tick in fig.get_axes()[0].get_xticklabels(): # tick.set_fontsize(plot_size*2.0) # for tick in fig.get_axes()[0].get_yticklabels(): # tick.set_fontsize(plot_size*2.0) # plot_trace(all_hv_xhvi/max_hypervolume*100, "Hypervolume loss (%)", 0, 100) # plt.savefig(os.path.join(folder_xhvi, FUNCTION_NAME + "_xhvi_hv_progress.svg"), facecolor=None, edgecolor=None) # plot_trace(all_hv_hypi/max_hypervolume*100, "Hypervolume loss (%)", 0, 100) # plt.savefig(os.path.join(folder_hypi, FUNCTION_NAME + "_hypi_hv_progress.svg"), facecolor=None, edgecolor=None) # plot_trace(all_hv_ehvi/max_hypervolume*100, "Hypervolume loss (%)", 0, 100) # plt.savefig(os.path.join(folder_ehvi, FUNCTION_NAME + "_ehvi_hv_progress.svg"), facecolor=None, edgecolor=None) # plot_trace(all_igd_xhvi, "Inter-Generational Distance", 0, np.quantile(all_igd_xhvi, 0.9)*1.25) # plt.savefig(os.path.join(folder_xhvi, FUNCTION_NAME + "_xhvi_igd_progress.svg"), facecolor=None, edgecolor=None) # plot_trace(all_igd_hypi, "Inter-Generational Distance", 0, np.quantile(all_igd_hypi, 0.9)*1.25) # plt.savefig(os.path.join(folder_hypi, FUNCTION_NAME + "_hypi_igd_progress.svg"), facecolor=None, edgecolor=None) # plot_trace(all_igd_ehvi, "Inter-Generational Distance", 0, np.quantile(all_igd_xhvi, 0.9)*1.25) # plt.savefig(os.path.join(folder_ehvi, FUNCTION_NAME + "_ehvi_igd_progress.svg"), facecolor=None, edgecolor=None) # %% Final Non-dominated set hvloss_xhvi = all_hv_xhvi[:, NUM_TOTAL_EVALUATIONS - 1]/max_hypervolume*100 hvloss_hypi = all_hv_hypi[:, NUM_TOTAL_EVALUATIONS - 1]/max_hypervolume*100 hvloss_ehvi = all_hv_ehvi[:, NUM_TOTAL_EVALUATIONS - 1]/max_hypervolume*100 igd_xhvi = all_igd_xhvi[:, NUM_TOTAL_EVALUATIONS - 1] igd_hypi = all_igd_hypi[:, NUM_TOTAL_EVALUATIONS - 1] igd_ehvi = all_igd_ehvi[:, NUM_TOTAL_EVALUATIONS - 1] # def plot_violin(name: str, left_side, left_side_name, right_side, right_side_name, old_size, ymax): # fig = plt.figure(figsize=[plot_size*1.62, plot_size]) # ax = sns.violinplot(old_size * 2 * [0.0], # np.hstack([left_side, right_side]).tolist(), # old_size * [left_side_name] + old_size * [right_side_name], # inner="quartile", split=True, cut=0, scale='area', # palette = ['lightskyblue','lemonchiffon']) # plt.ylim([0, ymax]) # plt.ylabel(name, fontsize=plot_size*3.0) # ax.set_xticks([]) # for tick in fig.get_axes()[0].get_yticklabels(): # tick.set_fontsize(plot_size*2.5) # for child in ax.get_children(): # if type(child) is matplotlib.legend.Legend: # child.remove() # break def plot_box(data, names, old_size, y_label, y_max): fig = plt.figure(figsize=[plot_size*1.62, plot_size]) labels = old_size * [names[0]] for n in range(1, len(names)): labels += old_size * [names[n]] ax1 = sns.violinplot( old_size * len(names) * [0.0], data, labels, cut=0, scale='width', inner='quartile', orient='v', palette = ['lightskyblue','lemonchiffon', 'palegreen'], linewidth=2) plt.ylim([0, y_max]) plt.ylabel(y_label, fontsize=plot_size*3.0) ax1.set_xticks([]) for tick in fig.get_axes()[0].get_yticklabels(): tick.set_fontsize(plot_size*2.5) for child in ax1.get_children(): if type(child) is matplotlib.legend.Legend: child.remove() break plot_box(np.hstack([hvloss_ehvi, hvloss_xhvi, hvloss_hypi]).tolist(), ["EHVI","xHVI","HypI"], all_hv_xhvi.shape[0], "Hypervolume loss (%)", 100) plt.savefig(os.path.join('img', FUNCTION_NAME + "_hv_violin_all.svg"), facecolor=None, edgecolor=None) # plot_violin("Hypervolume loss (%)", hvloss_xhvi, "xHVI", hvloss_ehvi, "EHVI", all_hv_xhvi.shape[0], 100) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_hv_violin_xhvi_vs_ehvi.svg"), facecolor=None, edgecolor=None) # plot_violin("Hypervolume loss (%)", hvloss_hypi, "HypI", hvloss_ehvi, "EHVI", all_hv_xhvi.shape[0], 100) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_hv_violin_hypi_vs_ehvi.svg"), facecolor=None, edgecolor=None) # plot_violin("Hypervolume loss (%)", hvloss_xhvi, "xHVI", hvloss_hypi, "HypI", all_hv_xhvi.shape[0], 100) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_hv_violin_xhvi_vs_hypi.svg"), facecolor=None, edgecolor=None) ymax = max([np.max(igd_xhvi), np.max(igd_hypi), np.max(igd_ehvi)])*1.2 plot_box(np.hstack([igd_ehvi, igd_xhvi, igd_hypi]).tolist(), ["EHVI","xHVI","HypI"], igd_xhvi.shape[0], "Inter-Generational Distance", ymax) plt.savefig(os.path.join('img', FUNCTION_NAME + "_igd_violin_all.svg"), facecolor=None, edgecolor=None) # plot_violin("Inter-Generational Distance", igd_xhvi, "xHVI", igd_ehvi, "EHVI", igd_xhvi.shape[0], ymax) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_igd_violin_xhvi_vs_ehvi.svg"), facecolor=None, edgecolor=None) # plot_violin("Inter-Generational Distance", igd_hypi, "HypI", igd_ehvi, "EHVI", igd_xhvi.shape[0], ymax) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_igd_violin_hypi_vs_ehvi.svg"), facecolor=None, edgecolor=None) # plot_violin("Inter-Generational Distance", igd_xhvi, "xHVI", igd_hypi, "HypI", igd_xhvi.shape[0], ymax) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_igd_violin_xhvi_vs_hypi.svg"), facecolor=None, edgecolor=None) plot_box(np.hstack([d1NumPointsInNds_ehvi[:,0], d1NumPointsInNds_xhvi[:,0], d1NumPointsInNds_hypi[:,0]]).tolist(), ["EHVI","xHVI","HypI"], len(d1NumPointsInNds_xhvi), "Non-Dominated Set Size", 30) plt.savefig(os.path.join('img', FUNCTION_NAME + "_nds_size_violin_all.svg"), facecolor=None, edgecolor=None) # plot_violin("Non-Dominated Set Size", d1NumPointsInNds_xhvi[:,0], "xHVI", d1NumPointsInNds_ehvi[:,0], "EHVI", len(d1NumPointsInNds_xhvi), 30) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_nds_size_violin_xhvi_vs_ehvi.svg"), facecolor=None, edgecolor=None) # plot_violin("Non-Dominated Set Size", d1NumPointsInNds_hypi[:,0], "HypI", d1NumPointsInNds_ehvi[:,0], "EHVI", len(d1NumPointsInNds_xhvi), 30) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_nds_size_violin_hypi_vs_ehvi.svg"), facecolor=None, edgecolor=None) # plot_violin("Non-Dominated Set Size", d1NumPointsInNds_xhvi[:,0], "xHVI", d1NumPointsInNds_hypi[:,0], "HypI", len(d1NumPointsInNds_xhvi), 30) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_nds_size_violin_xhvi_vs_hypi.svg"), facecolor=None, edgecolor=None) # %% Plot Pareto Front itself # def plot_pareto_front(data, xmax, ymax): # fig = plt.figure(figsize=[plot_size*1.62, plot_size]) # plt.hexbin(data[:,0], data[:,1], # gridsize=25, edgecolors='k', cmap='Blues', mincnt=1, bins='log', # extent=(min(d2F1F2_PF[:,0]), xmax, min(d2F1F2_PF[:,1]), ymax), # label = 'Distribution of non-dominated sets') # # ax = sns.kdeplot(d2AllNdsPoints_xhvi[:,0], d2AllNdsPoints_xhvi[:,1], bw=0.1, # # cmap="Blues", shade=True, shade_lowest=False, label = 'KDE of non-dominated sets') # # plt.scatter(d2AllNdsPoints_xhvi[:,0], d2AllNdsPoints_xhvi[:,1], marker='.', color='b', label = 'Non-dominated sets') # plt.scatter(d2F1F2_PF[::10, 0], d2F1F2_PF[::10, 1], c='g', s=plot_size*25.0, # marker='.', label = 'True Pareto Front') # plt.xlabel("$f_1$", fontsize=plot_size*3.0) # plt.ylabel("$f_2$", fontsize=plot_size*3.0) # plt.xlim([min(d2F1F2_PF[:,0]) - 0.1, xmax]) # plt.ylim([min(d2F1F2_PF[:,1]) - 0.1, ymax]) # # plt.legend(loc='upper right', labelspacing=0.25, fontsize=plot_size*2.0) # for tick in fig.get_axes()[0].get_xticklabels(): # tick.set_fontsize(plot_size*2.5) # for tick in fig.get_axes()[0].get_yticklabels(): # tick.set_fontsize(plot_size*2.5) # xmax = max([max(d2AllNdsPoints_xhvi[:,0]), max(d2AllNdsPoints_ehvi[:,0]), max(d2AllNdsPoints_hypi[:,0])]) * 1.01 + 0.1 # ymax = max([max(d2AllNdsPoints_xhvi[:,1]), max(d2AllNdsPoints_ehvi[:,1]), max(d2AllNdsPoints_hypi[:,1])]) * 1.01 + 0.1 # plot_pareto_front(d2AllNdsPoints_xhvi, xmax, ymax) # plt.title('xHVI', fontsize=plot_size*3.0) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_xhvi_nds_kdemap.svg"), facecolor=None, edgecolor=None) # plot_pareto_front(d2AllNdsPoints_hypi, xmax, ymax) # plt.title('HypI', fontsize=plot_size*3.0) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_hypi_nds_kdemap.svg"), facecolor=None, edgecolor=None) # plot_pareto_front(d2AllNdsPoints_ehvi, xmax, ymax) # plt.title('EHVI', fontsize=plot_size*3.0) # plt.savefig(os.path.join('img', FUNCTION_NAME + "_ehvi_nds_kdemap.svg"), facecolor=None, edgecolor=None) # # %% Correlations # plt.figure() # plt.scatter(set_size, d2HypervolumeLoss[-1,:]) # plt.ylabel("Hypervolume loss") # plt.xlabel("Final non-dominated set size") # plt.title("{0} ($D={1}, M={2}$) \n {3}".format( # FUNCTION_NAME, NUM_INPUT_DIMS, NUM_OBJECTIVES, subtitle)) # plt.yscale('log') # plt.grid() # plt.xlim(0,30) # plt.xticks(range(0,31,2)) # plt.savefig(os.path.join(FOLDER, "LossVsSetSize.png"), dpi=400)
[ "csv.reader", "os.path.join", "matplotlib.pyplot.ylim", "numpy.zeros", "numpy.hstack", "StandardTestFunctions.get_M2_pareto_front", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure", "numpy.array", "numpy.max", "StandardTestFunctions.get_function_definition", "matplotlib.pyplot.ylabel"...
[((301, 326), 'seaborn.set', 'sns.set', ([], {'color_codes': '(True)'}), '(color_codes=True)\n', (308, 326), True, 'import seaborn as sns\n'), ((390, 413), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (403, 413), True, 'import matplotlib.pyplot as plt\n'), ((680, 717), 'StandardTestFunctions.get_M2_pareto_front', 'fn.get_M2_pareto_front', (['FUNCTION_NAME'], {}), '(FUNCTION_NAME)\n', (702, 717), True, 'import StandardTestFunctions as fn\n'), ((805, 852), 'ParetoFrontND.calculateHypervolume', 'pf.calculateHypervolume', (['d2F1F2_PF', 'd1Reference'], {}), '(d2F1F2_PF, d1Reference)\n', (828, 852), True, 'import ParetoFrontND as pf\n'), ((911, 984), 'StandardTestFunctions.get_function_definition', 'fn.get_function_definition', (['FUNCTION_NAME', 'NUM_INPUT_DIMS', 'NUM_OBJECTIVES'], {}), '(FUNCTION_NAME, NUM_INPUT_DIMS, NUM_OBJECTIVES)\n', (937, 984), True, 'import StandardTestFunctions as fn\n'), ((1465, 1482), 'numpy.zeros', 'np.zeros', (['(21, 1)'], {}), '((21, 1))\n', (1473, 1482), True, 'import numpy as np\n'), ((2142, 2166), 'numpy.array', 'np.array', (['d2AllNdsPoints'], {}), '(d2AllNdsPoints)\n', (2150, 2166), True, 'import numpy as np\n'), ((7567, 7616), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[plot_size * 1.62, plot_size]'}), '(figsize=[plot_size * 1.62, plot_size])\n', (7577, 7616), True, 'import matplotlib.pyplot as plt\n'), ((7961, 7981), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, y_max]'], {}), '([0, y_max])\n', (7969, 7981), True, 'import matplotlib.pyplot as plt\n'), ((7986, 8031), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {'fontsize': '(plot_size * 3.0)'}), '(y_label, fontsize=plot_size * 3.0)\n', (7996, 8031), True, 'import matplotlib.pyplot as plt\n'), ((8466, 8523), 'os.path.join', 'os.path.join', (['"""img"""', "(FUNCTION_NAME + '_hv_violin_all.svg')"], {}), "('img', FUNCTION_NAME + '_hv_violin_all.svg')\n", (8478, 8523), False, 'import os\n'), ((9476, 9534), 'os.path.join', 'os.path.join', (['"""img"""', "(FUNCTION_NAME + '_igd_violin_all.svg')"], {}), "('img', FUNCTION_NAME + '_igd_violin_all.svg')\n", (9488, 9534), False, 'import os\n'), ((10471, 10534), 'os.path.join', 'os.path.join', (['"""img"""', "(FUNCTION_NAME + '_nds_size_violin_all.svg')"], {}), "('img', FUNCTION_NAME + '_nds_size_violin_all.svg')\n", (10483, 10534), False, 'import os\n'), ((1308, 1341), 'os.path.join', 'os.path.join', (['folder', 'filename_hv'], {}), '(folder, filename_hv)\n', (1320, 1341), False, 'import os\n'), ((1386, 1420), 'os.path.join', 'os.path.join', (['folder', 'filename_igd'], {}), '(folder, filename_igd)\n', (1398, 1420), False, 'import os\n'), ((1589, 1607), 'csv.reader', 'csv.reader', (['fid_f1'], {}), '(fid_f1)\n', (1599, 1607), False, 'import csv\n'), ((1521, 1554), 'os.path.join', 'os.path.join', (['folder', 'filename_f1'], {}), '(folder, filename_f1)\n', (1533, 1554), False, 'import os\n'), ((1698, 1716), 'csv.reader', 'csv.reader', (['fid_f2'], {}), '(fid_f2)\n', (1708, 1716), False, 'import csv\n'), ((8291, 8341), 'numpy.hstack', 'np.hstack', (['[hvloss_ehvi, hvloss_xhvi, hvloss_hypi]'], {}), '([hvloss_ehvi, hvloss_xhvi, hvloss_hypi])\n', (8300, 8341), True, 'import numpy as np\n'), ((9237, 9253), 'numpy.max', 'np.max', (['igd_xhvi'], {}), '(igd_xhvi)\n', (9243, 9253), True, 'import numpy as np\n'), ((9255, 9271), 'numpy.max', 'np.max', (['igd_hypi'], {}), '(igd_hypi)\n', (9261, 9271), True, 'import numpy as np\n'), ((9273, 9289), 'numpy.max', 'np.max', (['igd_ehvi'], {}), '(igd_ehvi)\n', (9279, 9289), True, 'import numpy as np\n'), ((9305, 9346), 'numpy.hstack', 'np.hstack', (['[igd_ehvi, igd_xhvi, igd_hypi]'], {}), '([igd_ehvi, igd_xhvi, igd_hypi])\n', (9314, 9346), True, 'import numpy as np\n'), ((10244, 10346), 'numpy.hstack', 'np.hstack', (['[d1NumPointsInNds_ehvi[:, 0], d1NumPointsInNds_xhvi[:, 0],\n d1NumPointsInNds_hypi[:, 0]]'], {}), '([d1NumPointsInNds_ehvi[:, 0], d1NumPointsInNds_xhvi[:, 0],\n d1NumPointsInNds_hypi[:, 0]])\n', (10253, 10346), True, 'import numpy as np\n'), ((1626, 1659), 'os.path.join', 'os.path.join', (['folder', 'filename_f2'], {}), '(folder, filename_f2)\n', (1638, 1659), False, 'import os\n'), ((2101, 2119), 'numpy.array', 'np.array', (['[f1, f2]'], {}), '([f1, f2])\n', (2109, 2119), True, 'import numpy as np\n')]
#encoding:utf-8 import torch import numpy as np import torch.nn as nn from functools import reduce from torch.nn import Module, Softmax, Parameter from .customize import PyramidPooling __all__ = ['AttGate1', 'AttGate2', 'AttGate3', 'AttGate3a', 'AttGate3b', 'AttGate4c', 'AttGate5c', 'AttGate6', 'AttGate9'] # class AttGate2(Module): # """ Channel attention module""" # def __init__(self, in_ch, reduce_rate=16): # super(AttGate2, self).__init__() # self.global_avg = nn.AdaptiveAvgPool2d(1) # fc_ch = max(in_ch//reduce_rate, 32) # self.fc = nn.Sequential(nn.Conv2d(in_ch, fc_ch, kernel_size=1, stride=1, bias=False), # nn.BatchNorm2d(num_features=fc_ch), # nn.ReLU(inplace=True)) # self.a_linear = nn.Conv2d(fc_ch, in_ch, kernel_size=1, stride=1) # self.b_linear = nn.Conv2d(fc_ch, in_ch, kernel_size=1, stride=1) # self.softmax = Softmax(dim=2) # # def forward(self, x, y): # """ # inputs : x : input feature maps( B X C X H X W); y : input feature maps( B X C X H X W) # returns : out: [B, c, h, w]; attention [B, c, 1, 1] for both x and y # """ # u = self.global_avg(x + y) # [B, c, 1, 1] # z = self.fc(u) # [B, d, 1, 1] # a_att, b_att = self.a_linear(z), self.b_linear(z) # [B, c, 1, 1] # att = torch.cat((a_att, b_att), dim=2) # [B, c, 2, 1] # att = self.softmax(att) # [B, c, 2, 1] # # out = torch.mul(x, att[:, :, 0:1, :]) + torch.mul(y, att[:, :, 1:2, :]) # return out class AttGate1(nn.Module): def __init__(self, in_ch, r=4): """same as the channel attention in SE module""" super(AttGate1, self).__init__() int_ch = max(in_ch//r, 32) self.gap = nn.AdaptiveAvgPool2d((1,1)) self.fc = nn.Sequential(nn.Conv2d(in_ch, int_ch, kernel_size=1, stride=1), nn.BatchNorm2d(int_ch), nn.ReLU(inplace=True), nn.Conv2d(int_ch, in_ch, kernel_size=1, stride=1), nn.Sigmoid()) def forward(self, x): att = self.gap(x) att = self.fc(att) # [B, in_c, 1, 1] out = att*x return out class AttGate2(nn.Module): def __init__(self, in_ch, M=2, r=4, ret_att=False): """ Attention as in SKNet (selective kernel) Args: features/in_ch: input channel dimensionality. M: the number of branches. r: the ratio for compute d, the length of z. L: the minimum dim of the vector z in paper, default 32. """ super(AttGate2, self).__init__() print('Att in_ch {} type {}, r {} type {}'.format(in_ch, type(in_ch), r, type(r))) d = max(int(in_ch / r), 32) self.M = M self.in_ch = in_ch self.ret_att = ret_att self.gap = nn.AdaptiveAvgPool2d((1, 1)) # to calculate Z self.fc = nn.Sequential(nn.Conv2d(in_ch, d, kernel_size=1, stride=1, bias=False), nn.BatchNorm2d(d), nn.ReLU(inplace=True)) # 各个分支 self.fcs = nn.ModuleList([]) for i in range(M): self.fcs.append(nn.Conv2d(d, in_ch, kernel_size=1, stride=1)) self.softmax = nn.Softmax(dim=1) def forward(self, *inputs): U = reduce(lambda x, y: x+y, inputs) batch_size = U.size(0) S = self.gap(U) # [B, c, 1, 1] Z = self.fc(S) # [B, d, 1, 1] attention_vectors = [fc(Z) for fc in self.fcs] # M: [B, c, 1, 1] attention_vectors = torch.cat(attention_vectors, dim=1) # [B, Mc, 1, 1] attention_vectors = attention_vectors.view(batch_size, self.M, self.in_ch, 1, 1) # [B, M, c, 1, 1] attention_vectors = self.softmax(attention_vectors) # [B, M, c, 1, 1] feats = torch.cat(inputs, dim=1) # [B, Mc, h, w] feats = feats.view(batch_size, self.M, self.in_ch, feats.shape[2], feats.shape[3]) # [B, M, c, h, w] feats_V = torch.sum(feats * attention_vectors, dim=1) if self.ret_att: return feats_V, attention_vectors else: return feats_V class AttGate3(nn.Module): def __init__(self, in_ch, M=2, r=4): # 输入特征的通道数, 2个分支,bottle-net layer的 reduction rate super(AttGate3, self).__init__() d = max(int(in_ch*2 / r), 32) self.M = M self.in_ch = in_ch self.gap = nn.AdaptiveAvgPool2d((1, 1)) # to calculate Z self.fc1 = nn.Sequential(nn.Conv2d(in_ch*2, d, kernel_size=1, stride=1, bias=False), nn.BatchNorm2d(d), nn.ReLU(inplace=True)) self.fc2 = nn.Conv2d(d, in_ch*2, kernel_size=1, stride=1, bias=False) # to calculate attention score self.softmax = nn.Softmax(dim=1) def forward(self, *inputs): # Note: before passed to AttentionModule, x,y has already been preprocessed by conv+BN+ReLU x, y = inputs[0], inputs[1] # [B, c, h, w] batch_size = x.size(0) u_x = self.gap(x) # [B, c, 1, 1] u_y = self.gap(y) # [B, c, 1, 1] u = torch.cat((u_x, u_y), dim=1) # [B, 2c, 1, 1] z = self.fc1(u) # [B, d, 1, 1] z = self.fc2(z) # [B, 2c, 1, 1] z = z.view(batch_size, 2, self.in_ch, 1, 1) # [B, 2, c, 1, 1] att_score = self.softmax(z) # [B, 2, c, 1, 1] feats = torch.cat((x,y), dim=1) # [B, 2c, h, w] feats = feats.view(batch_size, 2, self.in_ch, feats.shape[2], feats.shape[3]) # [B, 2, c, h, w] feats_V = torch.sum(feats * att_score, dim=1) # [B, c, h, w] out = feats_V if self.M == 2 else feats_V+inputs[2] return out class AttGate3a(nn.Module): def __init__(self, in_ch, M=2, r=4): # 输入特征的通道数, 2个分支,bottle-net layer的 reduction rate super().__init__() self.gap = nn.AdaptiveAvgPool2d((1, 1)) # to calculate Z self.fc = nn.Sequential(nn.Conv1d(4, 1, kernel_size=1, bias=False), # [B, 1, c] nn.BatchNorm1d(1), nn.Sigmoid()) def forward(self, x, y): # Note: before passed to AttentionModule, x,y has already been preprocessed by conv+BN+ReLU u_x = self.gap(x).squeeze(-1) # [B, c, 1] u_y = self.gap(y).squeeze(-1) # [B, c, 1] g_x = torch.mean(u_x, 1).unsqueeze(1).expand_as(u_x) # [B, c, 1] g_y = torch.mean(u_y, 1).unsqueeze(1).expand_as(u_y) # [B, c, 1] m = torch.cat((u_x, u_y, g_x, g_y), dim=2) # [B, c, 4] m = m.permute(0, 2, 1).contiguous() # [B, 4, c] att = self.fc(m) # [B, 1, c] att = att.permute(0, 2, 1).unsqueeze(-1) # [B, c, 1, 1] return x*att+y*(1-att) class AttGate3b(nn.Module): def __init__(self, in_ch, M=2, r=4): # 输入特征的通道数, 2个分支,bottle-net layer的 reduction rate super().__init__() self.gap = nn.AdaptiveAvgPool2d((1, 1)) # to calculate Z self.fc = nn.Sequential(nn.Conv1d(4, 8, kernel_size=1, bias=False), # [B, 8, c] nn.BatchNorm1d(8), nn.ReLU(inplace=True), nn.Conv1d(8, 1, kernel_size=1, bias=False), # [B, 1, c] nn.Sigmoid()) def forward(self, x, y): # Note: before passed to AttentionModule, x,y has already been preprocessed by conv+BN+ReLU u_x = self.gap(x).squeeze(-1) # [B, c, 1] u_y = self.gap(y).squeeze(-1) # [B, c, 1] g_x = torch.mean(u_x, 1).unsqueeze(1).expand_as(u_x) # [B, c, 1] g_y = torch.mean(u_y, 1).unsqueeze(1).expand_as(u_y) # [B, c, 1] m = torch.cat((u_x, u_y, g_x, g_y), dim =2) # [B, c, 4] m = m.permute(0, 2, 1).contiguous() # [B, 4, c] att = self.fc(m) # [B, 1, c] att = att.permute(0, 2, 1).unsqueeze(-1) # [B, c, 1, 1] return x*att+y*(1-att) class AttGate4(nn.Module): def __init__(self, hw, in_ch, r=4): super().__init__() d = max(in_ch//4, 32) # self.conv1 = nn.Sequential(nn.Conv1d(hw, 32, kernel_size=1, stride=1, bias=True), # [B, 32, 2c] nn.BatchNorm1d(32), nn.ReLU(inplace=True)) self.conv2 = nn.Conv1d(32, 1, kernel_size=1, stride=1, bias=True) # [B, 1, 2c] self.fc1 = nn.Sequential(nn.Conv2d(in_ch * 2, d, kernel_size=1, stride=1, bias=False), nn.BatchNorm2d(d), nn.ReLU(inplace=True)) self.fc2 = nn.Conv2d(d, in_ch * 2, kernel_size=1, stride=1, bias=False) def forward(self, x, y): batch_size, ch, h, w = x.shape # [B, c, h, w] m = torch.cat((x,y), dim=1) # [B, 2c, h, w] m = m.view(batch_size, 2*ch, -1).permute(0, 2, 1) # [B, hw, 2ch] gap = self.conv2(self.conv1(m)) # [B, 1, 2c] gap = gap.view(batch_size, 2*ch, 1, 1) # [B, 2c, 1, 1] att = self.fc2(self.fc1(gap)) # [B, 2c, 1, 1] att = att.view() class AttGate4c(nn.Module): def __init__(self, in_ch, shape=None): super().__init__() self.h, self.w = shape d = max(in_ch//4, 32) if self.w > 30: self.conv0 = nn.Sequential() for i in range(int(np.log2(self.w//30))): self.conv0.add_module('conv'+str(i),nn.Conv2d(1, 1, kernel_size=2, stride=2)) hw = min(30*30, self.h*self.w ) self.conv1 = nn.Sequential(nn.Conv1d(hw, 8, kernel_size=1, stride=1, bias=True), # [B, 32, 2c] nn.BatchNorm1d(8), nn.ReLU(inplace=True)) self.conv2 = nn.Conv1d(8, 1, kernel_size=1, stride=1, bias=True) # [B, 1, 2c] self.fc = nn.Sequential(nn.Conv2d(in_ch, d, kernel_size=1, stride=1, bias=False), nn.BatchNorm2d(d), nn.ReLU(inplace=True), nn.Conv2d(d, in_ch, kernel_size=1, stride=1, bias=False), nn.Sigmoid()) def forward(self, inputs): batch_size, ch, h, w = inputs.shape # [B, c, h, w] if self.w > 30: x = inputs.view(batch_size*ch, 1, h, w) # [Bc, 1, h, w] x = self.conv0(x) # [Bc, 1, 30, 30] x = x.view(batch_size, ch, -1) # [B, c, 30*30] else: x = inputs.view(batch_size, ch, -1) # [B, c, hw] x = x.permute(0, 2, 1).contiguous() # [B, hw, c] z = self.conv1(x) # [B, 8, c] z = self.conv2(z) # [B, 1, c] z = z.view(batch_size, ch, 1, -1) # [B, c, 1, 1] att = self.fc(z) # [B, c, 1, 1] return att*inputs class PSPSE(nn.Module): def __init__(self, in_ch, r=16, d=None): super().__init__() int_ch = max(in_ch // r, 8) self.pool = nn.AdaptiveAvgPool2d(d) self.fc = nn.Sequential(nn.Linear(in_ch*d*d, int_ch, bias=False), nn.ReLU(inplace=True), nn.Linear(int_ch, in_ch, bias=True), nn.Sigmoid()) def forward(self, x): batch_size, ch, h, w = x.size() z = self.pool(x) # [B, c, d, d] z = z.view(batch_size, -1) # [B, c*d*d] z = self.fc(z) # [B, c] z = z.view(batch_size, ch, 1, 1) # [B, c, 1, 1] return x*z class AttGate5c(nn.Module): def __init__(self, in_ch, r=None): super().__init__() for d in [1, 2, 4]: r = 32 if d == 4 else 16 self.add_module('att_d{}'.format(d), PSPSE(in_ch=in_ch, r=r, d=d)) def forward(self, x): y1 = self.att_d1(x) y2 = self.att_d2(x) y4 = self.att_d4(x) return y1+y2+y4 class AttGate6(nn.Module): def __init__(self, in_ch, r=None): super().__init__() # 参考PAN x 为浅层网络,y为深层网络 self.x_conv = nn.Sequential(nn.Conv2d(in_ch, in_ch, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(in_ch)) self.y_gap = nn.AdaptiveAvgPool2d(1) self.y_conv = nn.Sequential(nn.Conv2d(in_ch, in_ch, kernel_size=1, padding=0, bias=False), nn.BatchNorm2d(in_ch), nn.ReLU(inplace=True)) def forward(self, y, x): x1 = self.x_conv(x) # [B, c, h, w] y1 = self.y_gap(y) # [B, c, 1, 1] y1 = self.y_conv(y1) # [B, c, 1, 1] out = y1*x1 + y return out class AttGate9(nn.Module): # 简单的线性变换 def __init__(self, in_ch): super().__init__() self.conv = nn.Conv2d(in_ch*2, in_ch, kernel_size=1, stride=1, groups=in_ch, bias=False) self.conv.weight.data.fill_(0.5) def forward(self, x, y): batch_size, ch, h, w = x.size() x1 = x.view(batch_size, ch, -1) # [B, c, hw] y1 = y.view(batch_size, ch, -1) # [B, c, hw] m = torch.cat((x1, y1), dim=-1) # [B, c, 2hw] m = m.view(batch_size, 2*ch, h, -1).contiguous() # [B, 2c, h, w] out = self.conv(m) # [B, c, h, w] return out
[ "torch.mean", "torch.nn.AdaptiveAvgPool2d", "torch.nn.ReLU", "torch.nn.ModuleList", "torch.nn.Sequential", "numpy.log2", "torch.nn.Conv2d", "torch.nn.Conv1d", "torch.cat", "torch.nn.BatchNorm1d", "torch.nn.BatchNorm2d", "torch.nn.Softmax", "torch.nn.Linear", "functools.reduce", "torch.su...
[((1921, 1949), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (1941, 1949), True, 'import torch.nn as nn\n'), ((3061, 3089), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (3081, 3089), True, 'import torch.nn as nn\n'), ((3345, 3362), 'torch.nn.ModuleList', 'nn.ModuleList', (['[]'], {}), '([])\n', (3358, 3362), True, 'import torch.nn as nn\n'), ((3487, 3504), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (3497, 3504), True, 'import torch.nn as nn\n'), ((3551, 3585), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'inputs'], {}), '(lambda x, y: x + y, inputs)\n', (3557, 3585), False, 'from functools import reduce\n'), ((3808, 3843), 'torch.cat', 'torch.cat', (['attention_vectors'], {'dim': '(1)'}), '(attention_vectors, dim=1)\n', (3817, 3843), False, 'import torch\n'), ((4069, 4093), 'torch.cat', 'torch.cat', (['inputs'], {'dim': '(1)'}), '(inputs, dim=1)\n', (4078, 4093), False, 'import torch\n'), ((4239, 4282), 'torch.sum', 'torch.sum', (['(feats * attention_vectors)'], {'dim': '(1)'}), '(feats * attention_vectors, dim=1)\n', (4248, 4282), False, 'import torch\n'), ((4668, 4696), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (4688, 4696), True, 'import torch.nn as nn\n'), ((4941, 5001), 'torch.nn.Conv2d', 'nn.Conv2d', (['d', '(in_ch * 2)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(d, in_ch * 2, kernel_size=1, stride=1, bias=False)\n', (4950, 5001), True, 'import torch.nn as nn\n'), ((5063, 5080), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (5073, 5080), True, 'import torch.nn as nn\n'), ((5396, 5424), 'torch.cat', 'torch.cat', (['(u_x, u_y)'], {'dim': '(1)'}), '((u_x, u_y), dim=1)\n', (5405, 5424), False, 'import torch\n'), ((5683, 5707), 'torch.cat', 'torch.cat', (['(x, y)'], {'dim': '(1)'}), '((x, y), dim=1)\n', (5692, 5707), False, 'import torch\n'), ((5847, 5882), 'torch.sum', 'torch.sum', (['(feats * att_score)'], {'dim': '(1)'}), '(feats * att_score, dim=1)\n', (5856, 5882), False, 'import torch\n'), ((6154, 6182), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (6174, 6182), True, 'import torch.nn as nn\n'), ((6801, 6839), 'torch.cat', 'torch.cat', (['(u_x, u_y, g_x, g_y)'], {'dim': '(2)'}), '((u_x, u_y, g_x, g_y), dim=2)\n', (6810, 6839), False, 'import torch\n'), ((7290, 7318), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (7310, 7318), True, 'import torch.nn as nn\n'), ((8081, 8119), 'torch.cat', 'torch.cat', (['(u_x, u_y, g_x, g_y)'], {'dim': '(2)'}), '((u_x, u_y, g_x, g_y), dim=2)\n', (8090, 8119), False, 'import torch\n'), ((8770, 8822), 'torch.nn.Conv1d', 'nn.Conv1d', (['(32)', '(1)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(True)'}), '(32, 1, kernel_size=1, stride=1, bias=True)\n', (8779, 8822), True, 'import torch.nn as nn\n'), ((9060, 9120), 'torch.nn.Conv2d', 'nn.Conv2d', (['d', '(in_ch * 2)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(d, in_ch * 2, kernel_size=1, stride=1, bias=False)\n', (9069, 9120), True, 'import torch.nn as nn\n'), ((9220, 9244), 'torch.cat', 'torch.cat', (['(x, y)'], {'dim': '(1)'}), '((x, y), dim=1)\n', (9229, 9244), False, 'import torch\n'), ((10212, 10263), 'torch.nn.Conv1d', 'nn.Conv1d', (['(8)', '(1)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(True)'}), '(8, 1, kernel_size=1, stride=1, bias=True)\n', (10221, 10263), True, 'import torch.nn as nn\n'), ((11518, 11541), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['d'], {}), '(d)\n', (11538, 11541), True, 'import torch.nn as nn\n'), ((12775, 12798), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1)'], {}), '(1)\n', (12795, 12798), True, 'import torch.nn as nn\n'), ((13357, 13435), 'torch.nn.Conv2d', 'nn.Conv2d', (['(in_ch * 2)', 'in_ch'], {'kernel_size': '(1)', 'stride': '(1)', 'groups': 'in_ch', 'bias': '(False)'}), '(in_ch * 2, in_ch, kernel_size=1, stride=1, groups=in_ch, bias=False)\n', (13366, 13435), True, 'import torch.nn as nn\n'), ((13699, 13726), 'torch.cat', 'torch.cat', (['(x1, y1)'], {'dim': '(-1)'}), '((x1, y1), dim=-1)\n', (13708, 13726), False, 'import torch\n'), ((1981, 2030), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_ch', 'int_ch'], {'kernel_size': '(1)', 'stride': '(1)'}), '(in_ch, int_ch, kernel_size=1, stride=1)\n', (1990, 2030), True, 'import torch.nn as nn\n'), ((2064, 2086), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['int_ch'], {}), '(int_ch)\n', (2078, 2086), True, 'import torch.nn as nn\n'), ((2120, 2141), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (2127, 2141), True, 'import torch.nn as nn\n'), ((2175, 2224), 'torch.nn.Conv2d', 'nn.Conv2d', (['int_ch', 'in_ch'], {'kernel_size': '(1)', 'stride': '(1)'}), '(int_ch, in_ch, kernel_size=1, stride=1)\n', (2184, 2224), True, 'import torch.nn as nn\n'), ((2258, 2270), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (2268, 2270), True, 'import torch.nn as nn\n'), ((3147, 3203), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_ch', 'd'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(in_ch, d, kernel_size=1, stride=1, bias=False)\n', (3156, 3203), True, 'import torch.nn as nn\n'), ((3237, 3254), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['d'], {}), '(d)\n', (3251, 3254), True, 'import torch.nn as nn\n'), ((3288, 3309), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3295, 3309), True, 'import torch.nn as nn\n'), ((4756, 4816), 'torch.nn.Conv2d', 'nn.Conv2d', (['(in_ch * 2)', 'd'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(in_ch * 2, d, kernel_size=1, stride=1, bias=False)\n', (4765, 4816), True, 'import torch.nn as nn\n'), ((4848, 4865), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['d'], {}), '(d)\n', (4862, 4865), True, 'import torch.nn as nn\n'), ((4899, 4920), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4906, 4920), True, 'import torch.nn as nn\n'), ((6241, 6283), 'torch.nn.Conv1d', 'nn.Conv1d', (['(4)', '(1)'], {'kernel_size': '(1)', 'bias': '(False)'}), '(4, 1, kernel_size=1, bias=False)\n', (6250, 6283), True, 'import torch.nn as nn\n'), ((6330, 6347), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['(1)'], {}), '(1)\n', (6344, 6347), True, 'import torch.nn as nn\n'), ((6381, 6393), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (6391, 6393), True, 'import torch.nn as nn\n'), ((7377, 7419), 'torch.nn.Conv1d', 'nn.Conv1d', (['(4)', '(8)'], {'kernel_size': '(1)', 'bias': '(False)'}), '(4, 8, kernel_size=1, bias=False)\n', (7386, 7419), True, 'import torch.nn as nn\n'), ((7466, 7483), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['(8)'], {}), '(8)\n', (7480, 7483), True, 'import torch.nn as nn\n'), ((7517, 7538), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (7524, 7538), True, 'import torch.nn as nn\n'), ((7572, 7614), 'torch.nn.Conv1d', 'nn.Conv1d', (['(8)', '(1)'], {'kernel_size': '(1)', 'bias': '(False)'}), '(8, 1, kernel_size=1, bias=False)\n', (7581, 7614), True, 'import torch.nn as nn\n'), ((7661, 7673), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (7671, 7673), True, 'import torch.nn as nn\n'), ((8566, 8619), 'torch.nn.Conv1d', 'nn.Conv1d', (['hw', '(32)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(True)'}), '(hw, 32, kernel_size=1, stride=1, bias=True)\n', (8575, 8619), True, 'import torch.nn as nn\n'), ((8671, 8689), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['(32)'], {}), '(32)\n', (8685, 8689), True, 'import torch.nn as nn\n'), ((8726, 8747), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (8733, 8747), True, 'import torch.nn as nn\n'), ((8871, 8931), 'torch.nn.Conv2d', 'nn.Conv2d', (['(in_ch * 2)', 'd'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(in_ch * 2, d, kernel_size=1, stride=1, bias=False)\n', (8880, 8931), True, 'import torch.nn as nn\n'), ((8966, 8983), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['d'], {}), '(d)\n', (8980, 8983), True, 'import torch.nn as nn\n'), ((9018, 9039), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (9025, 9039), True, 'import torch.nn as nn\n'), ((9770, 9785), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (9783, 9785), True, 'import torch.nn as nn\n'), ((10010, 10062), 'torch.nn.Conv1d', 'nn.Conv1d', (['hw', '(8)'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(True)'}), '(hw, 8, kernel_size=1, stride=1, bias=True)\n', (10019, 10062), True, 'import torch.nn as nn\n'), ((10114, 10131), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['(8)'], {}), '(8)\n', (10128, 10131), True, 'import torch.nn as nn\n'), ((10168, 10189), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (10175, 10189), True, 'import torch.nn as nn\n'), ((10311, 10367), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_ch', 'd'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(in_ch, d, kernel_size=1, stride=1, bias=False)\n', (10320, 10367), True, 'import torch.nn as nn\n'), ((10401, 10418), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['d'], {}), '(d)\n', (10415, 10418), True, 'import torch.nn as nn\n'), ((10452, 10473), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (10459, 10473), True, 'import torch.nn as nn\n'), ((10507, 10563), 'torch.nn.Conv2d', 'nn.Conv2d', (['d', 'in_ch'], {'kernel_size': '(1)', 'stride': '(1)', 'bias': '(False)'}), '(d, in_ch, kernel_size=1, stride=1, bias=False)\n', (10516, 10563), True, 'import torch.nn as nn\n'), ((10597, 10609), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (10607, 10609), True, 'import torch.nn as nn\n'), ((11574, 11618), 'torch.nn.Linear', 'nn.Linear', (['(in_ch * d * d)', 'int_ch'], {'bias': '(False)'}), '(in_ch * d * d, int_ch, bias=False)\n', (11583, 11618), True, 'import torch.nn as nn\n'), ((11648, 11669), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (11655, 11669), True, 'import torch.nn as nn\n'), ((11703, 11738), 'torch.nn.Linear', 'nn.Linear', (['int_ch', 'in_ch'], {'bias': '(True)'}), '(int_ch, in_ch, bias=True)\n', (11712, 11738), True, 'import torch.nn as nn\n'), ((11772, 11784), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (11782, 11784), True, 'import torch.nn as nn\n'), ((12631, 12692), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_ch', 'in_ch'], {'kernel_size': '(3)', 'padding': '(1)', 'bias': '(False)'}), '(in_ch, in_ch, kernel_size=3, padding=1, bias=False)\n', (12640, 12692), True, 'import torch.nn as nn\n'), ((12730, 12751), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['in_ch'], {}), '(in_ch)\n', (12744, 12751), True, 'import torch.nn as nn\n'), ((12835, 12896), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_ch', 'in_ch'], {'kernel_size': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(in_ch, in_ch, kernel_size=1, padding=0, bias=False)\n', (12844, 12896), True, 'import torch.nn as nn\n'), ((12934, 12955), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['in_ch'], {}), '(in_ch)\n', (12948, 12955), True, 'import torch.nn as nn\n'), ((12993, 13014), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (13000, 13014), True, 'import torch.nn as nn\n'), ((3418, 3462), 'torch.nn.Conv2d', 'nn.Conv2d', (['d', 'in_ch'], {'kernel_size': '(1)', 'stride': '(1)'}), '(d, in_ch, kernel_size=1, stride=1)\n', (3427, 3462), True, 'import torch.nn as nn\n'), ((9817, 9838), 'numpy.log2', 'np.log2', (['(self.w // 30)'], {}), '(self.w // 30)\n', (9824, 9838), True, 'import numpy as np\n'), ((9892, 9932), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(1)'], {'kernel_size': '(2)', 'stride': '(2)'}), '(1, 1, kernel_size=2, stride=2)\n', (9901, 9932), True, 'import torch.nn as nn\n'), ((6656, 6674), 'torch.mean', 'torch.mean', (['u_x', '(1)'], {}), '(u_x, 1)\n', (6666, 6674), False, 'import torch\n'), ((6729, 6747), 'torch.mean', 'torch.mean', (['u_y', '(1)'], {}), '(u_y, 1)\n', (6739, 6747), False, 'import torch\n'), ((7936, 7954), 'torch.mean', 'torch.mean', (['u_x', '(1)'], {}), '(u_x, 1)\n', (7946, 7954), False, 'import torch\n'), ((8009, 8027), 'torch.mean', 'torch.mean', (['u_y', '(1)'], {}), '(u_y, 1)\n', (8019, 8027), False, 'import torch\n')]
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Pauli tomography preparation and measurement basis """ # Needed for functions import numpy as np # Import QISKit classes from qiskit import QuantumCircuit from .tomographybasis import TomographyBasis ########################################################################### # Built-in circuit functions ########################################################################### def pauli_measurement_circuit(op, qubit, clbit): """ Return a qubit Pauli operator measurement circuit. Params: op (str): Pauli operator 'X', 'Y', 'Z'. qubit (QuantumRegister tuple): qubit to be measured. clbit (ClassicalRegister tuple): clbit for measurement outcome. Returns: A QuantumCircuit object. """ circ = QuantumCircuit(qubit.register, clbit.register) if op == 'X': circ.h(qubit) circ.measure(qubit, clbit) if op == 'Y': circ.sdg(qubit) circ.h(qubit) circ.measure(qubit, clbit) if op == 'Z': circ.measure(qubit, clbit) return circ def pauli_preparation_circuit(op, qubit): """ Return a qubit Pauli eigenstate preparation circuit. This circuit assumes the qubit is initialized in the Zp eigenstate [1, 0]. Params: op (str): Pauli eigenstate 'Zp', 'Zm', 'Xp', 'Xm', 'Yp', or 'Ym'. qubit (QuantumRegister tuple): qubit to be prepared. Returns: A QuantumCircuit object. """ circ = QuantumCircuit(qubit.register) if op == 'Xp': circ.h(qubit) if op == 'Xm': circ.x(qubit) circ.h(qubit) if op == 'Yp': circ.h(qubit) circ.s(qubit) if op == 'Ym': circ.x(qubit) circ.h(qubit) circ.s(qubit) if op == 'Zm': circ.x(qubit) return circ ########################################################################### # Matrix functions for built-in bases ########################################################################### def pauli_preparation_matrix(label): """ Return the matrix corresponding to a Pauli eigenstate preparation. Args: label (str): single-qubit Pauli eigenstate operator label. Returns: numpy.array: A Numpy array for the Pauli eigenstate. Allowed inputs and corresponding returned matrices are: 'Xp' : [[1, 1], [1, 1]] / sqrt(2) 'Xm' : [[1, -1], [1, -1]] / sqrt(2) 'Yp' : [[1, -1j], [1j, 1]] / sqrt(2) 'Ym' : [[1, 1j], [-1j, 1]] / sqrt(2) 'Zp' : [[1, 0], [0, 0]] 'Zm' : [[0, 0], [0, 1]] """ res = np.array([]) # Return matrix for allowed label if label == 'Xp': res = np.array([[0.5, 0.5], [0.5, 0.5]], dtype=complex) if label == 'Xm': res = np.array([[0.5, -0.5], [-0.5, 0.5]], dtype=complex) if label == 'Yp': res = np.array([[0.5, -0.5j], [0.5j, 0.5]], dtype=complex) if label == 'Ym': res = np.array([[0.5, 0.5j], [-0.5j, 0.5]], dtype=complex) if label == 'Zp': res = np.array([[1, 0], [0, 0]], dtype=complex) if label == 'Zm': res = np.array([[0, 0], [0, 1]], dtype=complex) return res def pauli_measurement_matrix(label, outcome): """ Return the matrix corresonding to a Pauli measurement outcome. Args: label (str): single-qubit Pauli measurement operator label. outcome (int): measurement outcome. Returns: numpy.array: A Numpy array for measurement outcome operator. Allowed inputs and corresponding returned matrices are: 'X', 0 : [[1, 1], [1, 1]] / sqrt(2) 'X', 1 : [[1, -1], [1, -1]] / sqrt(2) 'Y', 0 : [[1, -1j], [1j, 1]] / sqrt(2) 'Y', 1 : [[1, 1j], [-1j, 1]] / sqrt(2) 'Z', 0 : [[1, 0], [0, 0]] 'Z', 1 : [[0, 0], [0, 1]] """ res = np.array([]) # Return matrix if label == 'X': if outcome in ['0', 0]: res = pauli_preparation_matrix('Xp') if outcome in ['1', 1]: res = pauli_preparation_matrix('Xm') if label == 'Y': if outcome in ['0', 0]: res = pauli_preparation_matrix('Yp') if outcome in ['1', 1]: res = pauli_preparation_matrix('Ym') if label == 'Z': if outcome in ['0', 0]: res = pauli_preparation_matrix('Zp') if outcome in ['1', 1]: res = pauli_preparation_matrix('Zm') return res ########################################################################### # PauliBasis Object ########################################################################### PauliBasis = TomographyBasis('Pauli', measurement=(('X', 'Y', 'Z'), pauli_measurement_circuit, pauli_measurement_matrix), preparation=(('Xp', 'Xm', 'Yp', 'Ym', 'Zp', 'Zm'), pauli_preparation_circuit, pauli_preparation_matrix))
[ "numpy.array", "qiskit.QuantumCircuit" ]
[((1266, 1312), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qubit.register', 'clbit.register'], {}), '(qubit.register, clbit.register)\n', (1280, 1312), False, 'from qiskit import QuantumCircuit\n'), ((1960, 1990), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qubit.register'], {}), '(qubit.register)\n', (1974, 1990), False, 'from qiskit import QuantumCircuit\n'), ((3112, 3124), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3120, 3124), True, 'import numpy as np\n'), ((4378, 4390), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4386, 4390), True, 'import numpy as np\n'), ((3199, 3248), 'numpy.array', 'np.array', (['[[0.5, 0.5], [0.5, 0.5]]'], {'dtype': 'complex'}), '([[0.5, 0.5], [0.5, 0.5]], dtype=complex)\n', (3207, 3248), True, 'import numpy as np\n'), ((3285, 3336), 'numpy.array', 'np.array', (['[[0.5, -0.5], [-0.5, 0.5]]'], {'dtype': 'complex'}), '([[0.5, -0.5], [-0.5, 0.5]], dtype=complex)\n', (3293, 3336), True, 'import numpy as np\n'), ((3373, 3425), 'numpy.array', 'np.array', (['[[0.5, -0.5j], [0.5j, 0.5]]'], {'dtype': 'complex'}), '([[0.5, -0.5j], [0.5j, 0.5]], dtype=complex)\n', (3381, 3425), True, 'import numpy as np\n'), ((3462, 3514), 'numpy.array', 'np.array', (['[[0.5, 0.5j], [-0.5j, 0.5]]'], {'dtype': 'complex'}), '([[0.5, 0.5j], [-0.5j, 0.5]], dtype=complex)\n', (3470, 3514), True, 'import numpy as np\n'), ((3551, 3592), 'numpy.array', 'np.array', (['[[1, 0], [0, 0]]'], {'dtype': 'complex'}), '([[1, 0], [0, 0]], dtype=complex)\n', (3559, 3592), True, 'import numpy as np\n'), ((3629, 3670), 'numpy.array', 'np.array', (['[[0, 0], [0, 1]]'], {'dtype': 'complex'}), '([[0, 0], [0, 1]], dtype=complex)\n', (3637, 3670), True, 'import numpy as np\n')]
from argparse import ArgumentParser from typing import Any, Dict from typing import Tuple import os import numpy as np from sklearn.datasets import dump_svmlight_file def generate_dummy_data( num_queries: int, results_len: int, num_labels: int, num_features: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Generate dummy dataset to be dumped in libsvm format. """ X = np.random.rand(num_queries * results_len, num_features) y = np.random.randint(0, num_labels-1, num_queries * results_len) qid = np.repeat(np.arange(0, num_queries), results_len) return X, y, qid def parse_args() -> Dict[str, Any]: parser = ArgumentParser("Dummy data") parser.add_argument("--num_queries", help="Number of queries.", default=6) parser.add_argument("--results_len", help="Length of results list for a single query.", default=20) parser.add_argument("--num_labels", help="Number of relevance levels.", default=5) parser.add_argument("--num_features", help="Number of features of a single item", default=20) return vars(parser.parse_args()) if __name__ == '__main__': args = parse_args() X_train, y_train, qid_train = generate_dummy_data(**args) X_val, y_val, qid_val = generate_dummy_data(**args) os.makedirs("dummy_data", exist_ok=True) dump_svmlight_file(X_train, y_train, os.path.join("dummy_data", "train.txt"), query_id=qid_train) dump_svmlight_file(X_val, y_val, os.path.join("dummy_data", "vali.txt"), query_id=qid_val)
[ "os.makedirs", "argparse.ArgumentParser", "numpy.random.randint", "numpy.arange", "numpy.random.rand", "os.path.join" ]
[((403, 458), 'numpy.random.rand', 'np.random.rand', (['(num_queries * results_len)', 'num_features'], {}), '(num_queries * results_len, num_features)\n', (417, 458), True, 'import numpy as np\n'), ((467, 530), 'numpy.random.randint', 'np.random.randint', (['(0)', '(num_labels - 1)', '(num_queries * results_len)'], {}), '(0, num_labels - 1, num_queries * results_len)\n', (484, 530), True, 'import numpy as np\n'), ((661, 689), 'argparse.ArgumentParser', 'ArgumentParser', (['"""Dummy data"""'], {}), "('Dummy data')\n", (675, 689), False, 'from argparse import ArgumentParser\n'), ((1272, 1312), 'os.makedirs', 'os.makedirs', (['"""dummy_data"""'], {'exist_ok': '(True)'}), "('dummy_data', exist_ok=True)\n", (1283, 1312), False, 'import os\n'), ((549, 574), 'numpy.arange', 'np.arange', (['(0)', 'num_queries'], {}), '(0, num_queries)\n', (558, 574), True, 'import numpy as np\n'), ((1354, 1393), 'os.path.join', 'os.path.join', (['"""dummy_data"""', '"""train.txt"""'], {}), "('dummy_data', 'train.txt')\n", (1366, 1393), False, 'import os\n'), ((1452, 1490), 'os.path.join', 'os.path.join', (['"""dummy_data"""', '"""vali.txt"""'], {}), "('dummy_data', 'vali.txt')\n", (1464, 1490), False, 'import os\n')]
#!/usr/bin/env python3 # Copyright (c) 2015-2020 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. """Invert a block diagonal covariance matrix. """ import os import re import sys import argparse import traceback import numpy as np import healpy as hp from toast.mpi import get_world from toast.utils import Logger from toast.dist import distribute_uniform from toast.map import DistPixels, covariance_invert def main(): log = Logger.get() parser = argparse.ArgumentParser( description="Read a toast covariance matrix and invert it." ) parser.add_argument( "--input", required=True, default=None, help="The input covariance FITS file" ) parser.add_argument( "--output", required=False, default=None, help="The output inverse covariance FITS file.", ) parser.add_argument( "--rcond", required=False, default=None, help="Optionally write the inverse condition number map to this file.", ) parser.add_argument( "--single", required=False, default=False, action="store_true", help="Write the output in single precision.", ) parser.add_argument( "--threshold", required=False, default=1e-3, type=np.float, help="Reciprocal condition number threshold", ) try: args = parser.parse_args() except SystemExit: return # get options infile = args.input outfile = None if args.output is not None: outfile = args.output else: inmat = re.match(r"(.*)\.fits", infile) if inmat is None: log.error("input file should have .fits extension") return inroot = inmat.group(1) outfile = "{}_inv.fits".format(inroot) # Get the default communicator mpiworld, procs, rank = get_world() # We need to read the header to get the size of the matrix. # This would be a trivial function call in astropy.fits or # fitsio, but we don't want to bring in a whole new dependency # just for that. Instead, we open the file with healpy in memmap # mode so that nothing is actually read except the header. nside = 0 ncovnz = 0 if rank == 0: fake, head = hp.read_map(infile, h=True, memmap=True) for key, val in head: if key == "NSIDE": nside = int(val) if key == "TFIELDS": ncovnz = int(val) if mpiworld is not None: nside = mpiworld.bcast(nside, root=0) ncovnz = mpiworld.bcast(ncovnz, root=0) nnz = int(((np.sqrt(8.0 * ncovnz) - 1.0) / 2.0) + 0.5) npix = 12 * nside ** 2 subnside = int(nside / 16) if subnside == 0: subnside = 1 subnpix = 12 * subnside ** 2 nsubmap = int(npix / subnpix) # divide the submaps as evenly as possible among processes dist = distribute_uniform(nsubmap, procs) local = np.arange(dist[rank][0], dist[rank][0] + dist[rank][1]) if rank == 0: if os.path.isfile(outfile): os.remove(outfile) if mpiworld is not None: mpiworld.barrier() # create the covariance and inverse condition number map cov = None invcov = None rcond = None cov = DistPixels( comm=mpiworld, dtype=np.float64, size=npix, nnz=ncovnz, submap=subnpix, local=local, ) if args.single: invcov = DistPixels( comm=mpiworld, dtype=np.float32, size=npix, nnz=ncovnz, submap=subnpix, local=local, ) else: invcov = cov if args.rcond is not None: rcond = DistPixels( comm=mpiworld, dtype=np.float64, size=npix, nnz=nnz, submap=subnpix, local=local, ) # read the covariance if rank == 0: log.info("Reading covariance from {}".format(infile)) cov.read_healpix_fits(infile) # every process computes its local piece if rank == 0: log.info("Inverting covariance") covariance_invert(cov, args.threshold, rcond=rcond) if args.single: invcov.data[:] = cov.data.astype(np.float32) # write the inverted covariance if rank == 0: log.info("Writing inverted covariance to {}".format(outfile)) invcov.write_healpix_fits(outfile) # write the condition number if args.rcond is not None: if rank == 0: log.info("Writing condition number map") rcond.write_healpix_fits(args.rcond) return if __name__ == "__main__": try: main() except: # We have an unhandled exception on at least one process. Print a stack # trace for this process and then abort so that all processes terminate. mpiworld, procs, rank = get_world() exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) lines = ["Proc {}: {}".format(rank, x) for x in lines] print("".join(lines), flush=True) if mpiworld is not None: mpiworld.Abort(6)
[ "os.remove", "traceback.format_exception", "toast.mpi.get_world", "argparse.ArgumentParser", "toast.map.covariance_invert", "toast.map.DistPixels", "re.match", "os.path.isfile", "numpy.arange", "sys.exc_info", "healpy.read_map", "toast.dist.distribute_uniform", "toast.utils.Logger.get", "n...
[((558, 570), 'toast.utils.Logger.get', 'Logger.get', ([], {}), '()\n', (568, 570), False, 'from toast.utils import Logger\n'), ((585, 674), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Read a toast covariance matrix and invert it."""'}), "(description=\n 'Read a toast covariance matrix and invert it.')\n", (608, 674), False, 'import argparse\n'), ((2012, 2023), 'toast.mpi.get_world', 'get_world', ([], {}), '()\n', (2021, 2023), False, 'from toast.mpi import get_world\n'), ((3051, 3085), 'toast.dist.distribute_uniform', 'distribute_uniform', (['nsubmap', 'procs'], {}), '(nsubmap, procs)\n', (3069, 3085), False, 'from toast.dist import distribute_uniform\n'), ((3098, 3153), 'numpy.arange', 'np.arange', (['dist[rank][0]', '(dist[rank][0] + dist[rank][1])'], {}), '(dist[rank][0], dist[rank][0] + dist[rank][1])\n', (3107, 3153), True, 'import numpy as np\n'), ((3421, 3521), 'toast.map.DistPixels', 'DistPixels', ([], {'comm': 'mpiworld', 'dtype': 'np.float64', 'size': 'npix', 'nnz': 'ncovnz', 'submap': 'subnpix', 'local': 'local'}), '(comm=mpiworld, dtype=np.float64, size=npix, nnz=ncovnz, submap=\n subnpix, local=local)\n', (3431, 3521), False, 'from toast.map import DistPixels, covariance_invert\n'), ((4294, 4345), 'toast.map.covariance_invert', 'covariance_invert', (['cov', 'args.threshold'], {'rcond': 'rcond'}), '(cov, args.threshold, rcond=rcond)\n', (4311, 4345), False, 'from toast.map import DistPixels, covariance_invert\n'), ((1728, 1759), 're.match', 're.match', (['"""(.*)\\\\.fits"""', 'infile'], {}), "('(.*)\\\\.fits', infile)\n", (1736, 1759), False, 'import re\n'), ((2421, 2461), 'healpy.read_map', 'hp.read_map', (['infile'], {'h': '(True)', 'memmap': '(True)'}), '(infile, h=True, memmap=True)\n', (2432, 2461), True, 'import healpy as hp\n'), ((3184, 3207), 'os.path.isfile', 'os.path.isfile', (['outfile'], {}), '(outfile)\n', (3198, 3207), False, 'import os\n'), ((3610, 3710), 'toast.map.DistPixels', 'DistPixels', ([], {'comm': 'mpiworld', 'dtype': 'np.float32', 'size': 'npix', 'nnz': 'ncovnz', 'submap': 'subnpix', 'local': 'local'}), '(comm=mpiworld, dtype=np.float32, size=npix, nnz=ncovnz, submap=\n subnpix, local=local)\n', (3620, 3710), False, 'from toast.map import DistPixels, covariance_invert\n'), ((3868, 3965), 'toast.map.DistPixels', 'DistPixels', ([], {'comm': 'mpiworld', 'dtype': 'np.float64', 'size': 'npix', 'nnz': 'nnz', 'submap': 'subnpix', 'local': 'local'}), '(comm=mpiworld, dtype=np.float64, size=npix, nnz=nnz, submap=\n subnpix, local=local)\n', (3878, 3965), False, 'from toast.map import DistPixels, covariance_invert\n'), ((3221, 3239), 'os.remove', 'os.remove', (['outfile'], {}), '(outfile)\n', (3230, 3239), False, 'import os\n'), ((5041, 5052), 'toast.mpi.get_world', 'get_world', ([], {}), '()\n', (5050, 5052), False, 'from toast.mpi import get_world\n'), ((5098, 5112), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (5110, 5112), False, 'import sys\n'), ((5129, 5191), 'traceback.format_exception', 'traceback.format_exception', (['exc_type', 'exc_value', 'exc_traceback'], {}), '(exc_type, exc_value, exc_traceback)\n', (5155, 5191), False, 'import traceback\n'), ((2763, 2784), 'numpy.sqrt', 'np.sqrt', (['(8.0 * ncovnz)'], {}), '(8.0 * ncovnz)\n', (2770, 2784), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 15 17:32:44 2020 @author: pengning """ import numpy as np import mpmath from mpmath import mp import sys sys.path.append('../') from dualbound.Arnoldi.spherical_multiRegion_Green_Arnoldi import spherical_multiRegion_Green_Arnoldi_Mmn_Uconverge, spherical_multiRegion_Green_Arnoldi_Nmn_Uconverge from dualbound.Lagrangian.spatialProjopt_Zops_numpy import get_ZTT_mineig, get_inc_ZTT_mineig from dualbound.Lagrangian.spatialProjopt_feasiblept import spatialProjopt_find_feasiblept from dualbound.Lagrangian.spatialProjopt_dualgradHess_fullSvec_numpy import get_inc_spatialProj_dualgradHess_fullS from dualbound.Optimization.modSource_opt import modS_opt from dualbound.Arnoldi.eqconstraint_xdipole_spherical_domain import get_real_RgNM_l_coeffs_for_xdipole_field def get_xdipole_sphere_multiRegion_S1list_Ulists_Projlists_numpy(k,RPlist,dist,chi, S1list, Plistlist, UPlistlist, Rgnormlistlist, subbasis_indlistlist, wig_1llp1_000,wig_1llm1_000, wig_1llp1_1m10,wig_1llm1_1m10, mpdps=60, normtol = 1e-4, gridpts=1000, maxveclim=40, Minitklim=22, Ninitklim=22, Taylor_tol=1e-12, Unormtol=1e-6, includeI=True): #along with the old xdipole data, this method generates the block diagonals of spatial shell projection operators #RPlist stores the boundaries between the different projection regions; RPlist[-1] is the radius of the entire bounding sphere #length of Ulist is the number of different modes involved, for xdipoles there are RgM_l1o and RgN_l1e waves #Plistlist and UPlistlist are organized such that the first index is mode, and second index is projection operator number #subbasis_ind_listlist is a list for all the mode's lists of the starting indices of each projection region's subbasis #if includeI==True, then we include the original constraints with P0=I sumnorm = 0 mp.dps=mpdps #we are going to modify the list arguments in place l=1 invchi = 1.0/chi while True: print('at mode number', l) if 2*l>len(Plistlist): #extend the Plistlists and UPlistlists if necessary, factor of 2 to account for both M and N waves if l==1: Mklim = Minitklim; Nklim = Ninitklim else: #the first subregion is the inner sphere; its Arnoldi process uses the old Taylor Arnoldi code Mklim = 2*(subbasis_indlistlist[-2][1]-subbasis_indlistlist[-2][0])+5 Nklim = 2*(subbasis_indlistlist[-1][1]-subbasis_indlistlist[-1][0])+5 print(Nklim) #################first do the M wave################################################### Gmat, Uconj, RgMnormlist, subbasis_indlist, fullrgrid, All_fullr_unitMvecs = spherical_multiRegion_Green_Arnoldi_Mmn_Uconverge(l,k,RPlist, invchi, gridpts=gridpts, mpdps=mpdps, maxveclim=maxveclim, klim=Mklim, Taylor_tol=Taylor_tol, Unormtol=Unormtol) U = Uconj.conjugate() if includeI: #now extend Plistlist and UPlistlist Plist = [np.eye(U.shape[0])] UPlist = [U] else: Plist = [] UPlist = [] for i in range(len(RPlist)): Proj = np.zeros_like(U) subbasis_head = subbasis_indlist[i]; subbasis_tail = subbasis_indlist[i+1] Proj[subbasis_head:subbasis_tail,subbasis_head:subbasis_tail] = np.eye(subbasis_tail-subbasis_head) UProj = U @ Proj Plist.append(Proj) UPlist.append(UProj) Plistlist.append(Plist) UPlistlist.append(UPlist) Rgnormlistlist.append(RgMnormlist) subbasis_indlistlist.append(subbasis_indlist) #the do N wave Gmat, Uconj, RgNnormlist, subbasis_indlist, fullrgrid, All_fullr_unitBvecs,All_fullr_unitPvecs = spherical_multiRegion_Green_Arnoldi_Nmn_Uconverge(l,k,RPlist, invchi, gridpts=gridpts, mpdps=mpdps, maxveclim=maxveclim, klim=Nklim, Taylor_tol=Taylor_tol, Unormtol=Unormtol) U = Uconj.conjugate() #the U generated in Green_Taylor_Arnoldi is an older definition that corresponds to U^\dagger in our current notation if includeI: #now extend Plistlist and UPlistlist Plist = [np.eye(U.shape[0])] UPlist = [U] else: Plist = [] UPlist = [] for i in range(len(RPlist)): Proj = np.zeros_like(U) subbasis_head = subbasis_indlist[i]; subbasis_tail = subbasis_indlist[i+1] Proj[subbasis_head:subbasis_tail,subbasis_head:subbasis_tail] = np.eye(subbasis_tail-subbasis_head) UProj = U @ Proj Plist.append(Proj) UPlist.append(UProj) Plistlist.append(Plist) UPlistlist.append(UPlist) Rgnormlistlist.append(RgNnormlist) subbasis_indlistlist.append(subbasis_indlist) np.seterr(under='warn') #the coeffs of the source in terms of the non-normalized regular waves with real azimuthal angle dependence coeffs = get_real_RgNM_l_coeffs_for_xdipole_field(l,k,RPlist[-1]+dist, wig_1llp1_000, wig_1llm1_000, wig_1llp1_1m10, wig_1llm1_1m10) #the coefficients in coeffs are stored in the order of [RgM_l,1,e RgM_l,1,o RgN_l,1,e RgN_l,1,o] #construct the M source vector M_S1vec = np.zeros(UPlistlist[2*l-2][0].shape[0], dtype=np.complex) for i in range(len(subbasis_indlistlist[2*l-2])-1): #-1 because last index of subbasis_indlist is total number of basis vectors M_S1vec[subbasis_indlistlist[2*l-2][i]] = np.complex(coeffs[1]*Rgnormlistlist[2*l-2][i])/np.sqrt(2) #factor of 1/sqrt(2) comes from normalizing the real azimuthal vector spherical harmonics S1list.append(M_S1vec) #construct the N source vector N_S1vec = np.zeros(UPlistlist[2*l-1][0].shape[0], dtype=np.complex) for i in range(len(subbasis_indlistlist[2*l-1])-1): #-1 because last index of subbasis_indlist is total number of basis vectors N_S1vec[subbasis_indlistlist[2*l-1][i]] = np.complex(coeffs[2]*Rgnormlistlist[2*l-1][i])/np.sqrt(2) S1list.append(N_S1vec) sosqr = np.real(np.vdot(M_S1vec,M_S1vec)+np.vdot(N_S1vec,N_S1vec)) sumnorm += sosqr #check with old code and see the sumnorms are the same print('sumnorm,', sumnorm) if l>2 and sosqr<sumnorm*normtol: break l+=1 def get_ext_Prad_ZTS_Slist(Lags, S1list, Plistlist): ZTS_Slist = [] for mode in range(len(S1list)): Plist = Plistlist[mode] ZTS = np.zeros_like(Plist[0], dtype=np.complex) for i in range(len(Plist)): ZTS += (Lags[2*i]+1j*Lags[2*i+1])*Plist[i].conj().T/2 ZTS_S = ZTS @ S1list[mode] + (1j/2)*np.conj(S1list[mode]) #for external dipoles, S2 = S1* ZTS_Slist.append(ZTS_S) return ZTS_Slist def get_ext_Prad_gradZTS_Slist(Lags, S1list, Plistlist): gradZTS_Slist = [] for mode in range(len(S1list)): Plist = Plistlist[mode] gradZTS_S = [] for i in range(len(Plist)): P_S = Plist[i] @ S1list[mode] gradZTS_S.append(P_S/2) gradZTS_S.append(1j*P_S/2) gradZTS_Slist.append(gradZTS_S) return gradZTS_Slist def get_xdipole_spherical_multiRegion_shellProj_Psca_numpy(k,RPlist,dist,chi, S1list, Plistlist, UPlistlist, Rgnormlistlist, subbasis_indlistlist, wig_1llp1_000,wig_1llm1_000, wig_1llp1_1m10,wig_1llm1_1m10, initLags=None, incPIm=False, incRegions=None, mpdps=60, maxveclim=40, normtol=1e-4, gridpts=1000, Minitklim=25, Ninitklim=25, Taylor_tol=1e-12, Unormtol=1e-6, opttol=1e-2, modSratio=1e-2, check_iter_period=20): mp.dps = mpdps get_xdipole_sphere_multiRegion_S1list_Ulists_Projlists_numpy(k,RPlist,dist,chi, S1list, Plistlist, UPlistlist, Rgnormlistlist, subbasis_indlistlist, wig_1llp1_000,wig_1llm1_000, wig_1llp1_1m10,wig_1llm1_1m10, mpdps=mpdps, normtol = normtol, gridpts=gridpts, maxveclim=maxveclim, Minitklim=Minitklim, Ninitklim=Ninitklim, Taylor_tol=Taylor_tol, Unormtol=Unormtol, includeI=True) modenum = len(S1list) zinv = np.imag(1/np.conj(chi)) Olist = [] for mode in range(modenum): Olist.append(np.eye(Plistlist[mode][0].shape[0])*zinv) Lagnum = 2 + 2*len(RPlist) """ 2 is for the original Re+Im global constraint; then there's the projection versions because we always include the original global constraints over the entire region, can't include all regional constraints because that would cause the constraints to be linearly dependent default is to include all regional constraints except that of the inner shell """ include=[True]*Lagnum if incRegions is None: #use default region inclusion: every region except the innermost include[2] = False; include[3] = False else: for i in range(len(incRegions)): include[2+2*i] = incRegions[i]; include[3+2*i] = incRegions[i] if not incPIm: for i in range(1,len(RPlist)+1): #i starts from 1 because we always want to keep the original Im constraint include[2*i+1] = False if initLags is None: Lags = spatialProjopt_find_feasiblept(Lagnum, include, Olist, UPlistlist) else: Lags = initLags.copy() Lags[1] = np.abs(Lags[1])+0.01 validLagsfunc = lambda L: get_ZTT_mineig(L, Olist, UPlistlist, eigvals_only=True)[1] #[1] because we only need the minimum eigenvalue part of the returned values while validLagsfunc(Lags)<0: print('zeta', Lags[1]) Lags[1] *= 1.5 #enlarge zeta until we enter domain of validity print('initial Lags', Lags) ZTS_Slistfunc = lambda L, Slist: get_ext_Prad_ZTS_Slist(L, Slist, Plistlist) gradZTS_Slistfunc = lambda L, Slist: get_ext_Prad_gradZTS_Slist(L, Slist, Plistlist) dgHfunc = lambda dof, dofgrad, dofHess, Slist, get_grad=True, get_Hess=True: get_inc_spatialProj_dualgradHess_fullS(dof, dofgrad, dofHess, include, Olist, Plistlist, UPlistlist, Slist, ZTS_Slistfunc, gradZTS_Slistfunc, get_grad=get_grad, get_Hess=get_Hess) mineigfunc = lambda dof, eigvals_only=False: get_inc_ZTT_mineig(dof, include, Olist, UPlistlist, eigvals_only=eigvals_only) opt_incLags, opt_incgrad, opt_dual, opt_obj = modS_opt(Lags[include], S1list, dgHfunc, mineigfunc, opttol=opttol, modSratio=modSratio, check_iter_period=check_iter_period) optLags = np.zeros(Lagnum) optgrad = np.zeros(Lagnum) optLags[include] = opt_incLags optgrad[include] = opt_incgrad print('the remaining constraint violations') print(optgrad) #prefactors from physics Z=1 return optLags, k*opt_dual/2/Z, k*opt_obj/2/Z, 2*(subbasis_indlistlist[0][1]-subbasis_indlistlist[0][0])+5 #final returned value is useful for certain sweeps to determine polynomial order for the Arnoldi process def sweep_Psca_xdipole_multipleRegion_shellProj_varydist_np(k, RPlist, distlist, chi, incPIm=False, incRegions=None, normtol = 1e-4, mpdps=60, maxveclim=40, gridpts=1000, Minitklim=25, Ninitklim=25, Taylor_tol=1e-12, Unormtol=1e-6, opttol=1e-2, check_iter_period=20, filename=None, feedforward=True): #for now let the external calling script set the domains flag = False if not (filename is None): flag = True outdist = open(filename+'_distlist.txt','w'); outdual = open(filename+'_duallist.txt','w') outobj = open(filename+'_objlist.txt','w'); outnPrad = open(filename+'_nPradlist.txt','w') wig_1llp1_000=[]; wig_1llm1_000=[]; wig_1llp1_1m10=[]; wig_1llm1_1m10=[] Plistlist=[] UPlistlist=[] Rgnormlistlist=[] subbasis_indlistlist=[] #these lists will be gradually filled up as sweep progresses #since we fix R, the U matrices and Proj matrices only need to be computed once duallist=[]; objlist=[]; nPradlist=[]; currentdistlist=[] dRad = 1.0/(12*np.pi) #vacuum dipole radiation contribution, for calculating normalized Prad Lags = None klim=Minitklim for i in range(len(distlist)): dist = distlist[i] if flag: outdist.write(str(dist)+'\n') outdist.flush() try: if (not feedforward) or (Lags is None): if not (Lags is None): Minitklim = max(Minitklim, klim+3); Ninitklim = max(Ninitklim,klim+3) #change Ninitklim based on required size from previous iteration print('new Minitklim is', Minitklim, 'new Ninitklim is', Ninitklim) Lags, dualval, objval, klim = get_xdipole_spherical_multiRegion_shellProj_Psca_numpy(k,RPlist,dist,chi, [], Plistlist, UPlistlist, Rgnormlistlist, subbasis_indlistlist, wig_1llp1_000,wig_1llm1_000, wig_1llp1_1m10,wig_1llm1_1m10, initLags=None, incPIm=incPIm, incRegions=incRegions, mpdps=mpdps, normtol=normtol, gridpts=gridpts, maxveclim=maxveclim, Minitklim=Minitklim, Ninitklim=Ninitklim, Taylor_tol=Taylor_tol, Unormtol=Unormtol, opttol=opttol, check_iter_period=check_iter_period) #we may lose strong duality so never start from rand init else: #feed previous optimal parameters as starting point for next optimization Minitklim = max(Minitklim, klim+3); Ninitklim = max(Ninitklim,klim+3) #change Minitklim based on required size from previous iteration print('new Minitklim is', Minitklim, 'new Ninitklim is', Ninitklim) if Minitklim > mp.dps: mp.dps = Minitklim Lags, dualval, objval, klim = get_xdipole_spherical_multiRegion_shellProj_Psca_numpy(k,RPlist,dist,chi, [], Plistlist, UPlistlist, Rgnormlistlist, subbasis_indlistlist, wig_1llp1_000,wig_1llm1_000, wig_1llp1_1m10,wig_1llm1_1m10, initLags=Lags, incPIm=incPIm, incRegions=incRegions, mpdps=mpdps, normtol=normtol, gridpts=gridpts, maxveclim=maxveclim, Minitklim=Minitklim, Ninitklim=Ninitklim, Taylor_tol=Taylor_tol, Unormtol=Unormtol, opttol=opttol, check_iter_period=check_iter_period) #we may lose strong duality so never start from rand init except (KeyboardInterrupt, SystemExit): #in case I am interrupting by hand raise nPrad = (dualval+dRad)/dRad duallist.append(dualval); objlist.append(objval); currentdistlist.append(dist) nPradlist.append(nPrad) if flag: outdual.write(str(dualval)+'\n') outobj.write(str(objval)+'\n') outnPrad.write(str(nPrad)+'\n') np.save(filename+'_distlist.npy', np.array(currentdistlist)) #save as npy after each data point is calculated for easy plotting on-the-fly np.save(filename+'_duallist.npy', np.array(duallist)) np.save(filename+'_objlist.npy', np.array(objlist)) np.save(filename+'_nPradlist.npy', np.array(nPradlist)) outdual.flush() outobj.flush() outnPrad.flush() print(len(UPlistlist), len(wig_1llp1_000), len(wig_1llm1_000)) if flag: outdist.close() outdual.close() outobj.close() outnPrad.close() return currentdistlist, duallist, objlist, nPradlist
[ "dualbound.Lagrangian.spatialProjopt_Zops_numpy.get_ZTT_mineig", "numpy.abs", "dualbound.Lagrangian.spatialProjopt_dualgradHess_fullSvec_numpy.get_inc_spatialProj_dualgradHess_fullS", "sys.path.append", "numpy.zeros_like", "dualbound.Lagrangian.spatialProjopt_feasiblept.spatialProjopt_find_feasiblept", ...
[((178, 200), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (193, 200), False, 'import sys\n'), ((10902, 11031), 'dualbound.Optimization.modSource_opt.modS_opt', 'modS_opt', (['Lags[include]', 'S1list', 'dgHfunc', 'mineigfunc'], {'opttol': 'opttol', 'modSratio': 'modSratio', 'check_iter_period': 'check_iter_period'}), '(Lags[include], S1list, dgHfunc, mineigfunc, opttol=opttol,\n modSratio=modSratio, check_iter_period=check_iter_period)\n', (10910, 11031), False, 'from dualbound.Optimization.modSource_opt import modS_opt\n'), ((11042, 11058), 'numpy.zeros', 'np.zeros', (['Lagnum'], {}), '(Lagnum)\n', (11050, 11058), True, 'import numpy as np\n'), ((11073, 11089), 'numpy.zeros', 'np.zeros', (['Lagnum'], {}), '(Lagnum)\n', (11081, 11089), True, 'import numpy as np\n'), ((5263, 5286), 'numpy.seterr', 'np.seterr', ([], {'under': '"""warn"""'}), "(under='warn')\n", (5272, 5286), True, 'import numpy as np\n'), ((5420, 5551), 'dualbound.Arnoldi.eqconstraint_xdipole_spherical_domain.get_real_RgNM_l_coeffs_for_xdipole_field', 'get_real_RgNM_l_coeffs_for_xdipole_field', (['l', 'k', '(RPlist[-1] + dist)', 'wig_1llp1_000', 'wig_1llm1_000', 'wig_1llp1_1m10', 'wig_1llm1_1m10'], {}), '(l, k, RPlist[-1] + dist,\n wig_1llp1_000, wig_1llm1_000, wig_1llp1_1m10, wig_1llm1_1m10)\n', (5460, 5551), False, 'from dualbound.Arnoldi.eqconstraint_xdipole_spherical_domain import get_real_RgNM_l_coeffs_for_xdipole_field\n'), ((5719, 5780), 'numpy.zeros', 'np.zeros', (['UPlistlist[2 * l - 2][0].shape[0]'], {'dtype': 'np.complex'}), '(UPlistlist[2 * l - 2][0].shape[0], dtype=np.complex)\n', (5727, 5780), True, 'import numpy as np\n'), ((6204, 6265), 'numpy.zeros', 'np.zeros', (['UPlistlist[2 * l - 1][0].shape[0]'], {'dtype': 'np.complex'}), '(UPlistlist[2 * l - 1][0].shape[0], dtype=np.complex)\n', (6212, 6265), True, 'import numpy as np\n'), ((6977, 7018), 'numpy.zeros_like', 'np.zeros_like', (['Plist[0]'], {'dtype': 'np.complex'}), '(Plist[0], dtype=np.complex)\n', (6990, 7018), True, 'import numpy as np\n'), ((9802, 9868), 'dualbound.Lagrangian.spatialProjopt_feasiblept.spatialProjopt_find_feasiblept', 'spatialProjopt_find_feasiblept', (['Lagnum', 'include', 'Olist', 'UPlistlist'], {}), '(Lagnum, include, Olist, UPlistlist)\n', (9832, 9868), False, 'from dualbound.Lagrangian.spatialProjopt_feasiblept import spatialProjopt_find_feasiblept\n'), ((10543, 10730), 'dualbound.Lagrangian.spatialProjopt_dualgradHess_fullSvec_numpy.get_inc_spatialProj_dualgradHess_fullS', 'get_inc_spatialProj_dualgradHess_fullS', (['dof', 'dofgrad', 'dofHess', 'include', 'Olist', 'Plistlist', 'UPlistlist', 'Slist', 'ZTS_Slistfunc', 'gradZTS_Slistfunc'], {'get_grad': 'get_grad', 'get_Hess': 'get_Hess'}), '(dof, dofgrad, dofHess, include,\n Olist, Plistlist, UPlistlist, Slist, ZTS_Slistfunc, gradZTS_Slistfunc,\n get_grad=get_grad, get_Hess=get_Hess)\n', (10581, 10730), False, 'from dualbound.Lagrangian.spatialProjopt_dualgradHess_fullSvec_numpy import get_inc_spatialProj_dualgradHess_fullS\n'), ((10772, 10850), 'dualbound.Lagrangian.spatialProjopt_Zops_numpy.get_inc_ZTT_mineig', 'get_inc_ZTT_mineig', (['dof', 'include', 'Olist', 'UPlistlist'], {'eigvals_only': 'eigvals_only'}), '(dof, include, Olist, UPlistlist, eigvals_only=eigvals_only)\n', (10790, 10850), False, 'from dualbound.Lagrangian.spatialProjopt_Zops_numpy import get_ZTT_mineig, get_inc_ZTT_mineig\n'), ((2904, 3088), 'dualbound.Arnoldi.spherical_multiRegion_Green_Arnoldi.spherical_multiRegion_Green_Arnoldi_Mmn_Uconverge', 'spherical_multiRegion_Green_Arnoldi_Mmn_Uconverge', (['l', 'k', 'RPlist', 'invchi'], {'gridpts': 'gridpts', 'mpdps': 'mpdps', 'maxveclim': 'maxveclim', 'klim': 'Mklim', 'Taylor_tol': 'Taylor_tol', 'Unormtol': 'Unormtol'}), '(l, k, RPlist, invchi,\n gridpts=gridpts, mpdps=mpdps, maxveclim=maxveclim, klim=Mklim,\n Taylor_tol=Taylor_tol, Unormtol=Unormtol)\n', (2953, 3088), False, 'from dualbound.Arnoldi.spherical_multiRegion_Green_Arnoldi import spherical_multiRegion_Green_Arnoldi_Mmn_Uconverge, spherical_multiRegion_Green_Arnoldi_Nmn_Uconverge\n'), ((4082, 4266), 'dualbound.Arnoldi.spherical_multiRegion_Green_Arnoldi.spherical_multiRegion_Green_Arnoldi_Nmn_Uconverge', 'spherical_multiRegion_Green_Arnoldi_Nmn_Uconverge', (['l', 'k', 'RPlist', 'invchi'], {'gridpts': 'gridpts', 'mpdps': 'mpdps', 'maxveclim': 'maxveclim', 'klim': 'Nklim', 'Taylor_tol': 'Taylor_tol', 'Unormtol': 'Unormtol'}), '(l, k, RPlist, invchi,\n gridpts=gridpts, mpdps=mpdps, maxveclim=maxveclim, klim=Nklim,\n Taylor_tol=Taylor_tol, Unormtol=Unormtol)\n', (4131, 4266), False, 'from dualbound.Arnoldi.spherical_multiRegion_Green_Arnoldi import spherical_multiRegion_Green_Arnoldi_Mmn_Uconverge, spherical_multiRegion_Green_Arnoldi_Nmn_Uconverge\n'), ((8745, 8757), 'numpy.conj', 'np.conj', (['chi'], {}), '(chi)\n', (8752, 8757), True, 'import numpy as np\n'), ((9928, 9943), 'numpy.abs', 'np.abs', (['Lags[1]'], {}), '(Lags[1])\n', (9934, 9943), True, 'import numpy as np\n'), ((9984, 10039), 'dualbound.Lagrangian.spatialProjopt_Zops_numpy.get_ZTT_mineig', 'get_ZTT_mineig', (['L', 'Olist', 'UPlistlist'], {'eigvals_only': '(True)'}), '(L, Olist, UPlistlist, eigvals_only=True)\n', (9998, 10039), False, 'from dualbound.Lagrangian.spatialProjopt_Zops_numpy import get_ZTT_mineig, get_inc_ZTT_mineig\n'), ((3416, 3432), 'numpy.zeros_like', 'np.zeros_like', (['U'], {}), '(U)\n', (3429, 3432), True, 'import numpy as np\n'), ((3604, 3641), 'numpy.eye', 'np.eye', (['(subbasis_tail - subbasis_head)'], {}), '(subbasis_tail - subbasis_head)\n', (3610, 3641), True, 'import numpy as np\n'), ((4716, 4732), 'numpy.zeros_like', 'np.zeros_like', (['U'], {}), '(U)\n', (4729, 4732), True, 'import numpy as np\n'), ((4904, 4941), 'numpy.eye', 'np.eye', (['(subbasis_tail - subbasis_head)'], {}), '(subbasis_tail - subbasis_head)\n', (4910, 4941), True, 'import numpy as np\n'), ((5967, 6019), 'numpy.complex', 'np.complex', (['(coeffs[1] * Rgnormlistlist[2 * l - 2][i])'], {}), '(coeffs[1] * Rgnormlistlist[2 * l - 2][i])\n', (5977, 6019), True, 'import numpy as np\n'), ((6014, 6024), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6021, 6024), True, 'import numpy as np\n'), ((6452, 6504), 'numpy.complex', 'np.complex', (['(coeffs[2] * Rgnormlistlist[2 * l - 1][i])'], {}), '(coeffs[2] * Rgnormlistlist[2 * l - 1][i])\n', (6462, 6504), True, 'import numpy as np\n'), ((6499, 6509), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6506, 6509), True, 'import numpy as np\n'), ((6574, 6599), 'numpy.vdot', 'np.vdot', (['M_S1vec', 'M_S1vec'], {}), '(M_S1vec, M_S1vec)\n', (6581, 6599), True, 'import numpy as np\n'), ((6599, 6624), 'numpy.vdot', 'np.vdot', (['N_S1vec', 'N_S1vec'], {}), '(N_S1vec, N_S1vec)\n', (6606, 6624), True, 'import numpy as np\n'), ((7178, 7199), 'numpy.conj', 'np.conj', (['S1list[mode]'], {}), '(S1list[mode])\n', (7185, 7199), True, 'import numpy as np\n'), ((8832, 8867), 'numpy.eye', 'np.eye', (['Plistlist[mode][0].shape[0]'], {}), '(Plistlist[mode][0].shape[0])\n', (8838, 8867), True, 'import numpy as np\n'), ((15495, 15520), 'numpy.array', 'np.array', (['currentdistlist'], {}), '(currentdistlist)\n', (15503, 15520), True, 'import numpy as np\n'), ((15651, 15669), 'numpy.array', 'np.array', (['duallist'], {}), '(duallist)\n', (15659, 15669), True, 'import numpy as np\n'), ((15716, 15733), 'numpy.array', 'np.array', (['objlist'], {}), '(objlist)\n', (15724, 15733), True, 'import numpy as np\n'), ((15782, 15801), 'numpy.array', 'np.array', (['nPradlist'], {}), '(nPradlist)\n', (15790, 15801), True, 'import numpy as np\n'), ((3213, 3231), 'numpy.eye', 'np.eye', (['U.shape[0]'], {}), '(U.shape[0])\n', (3219, 3231), True, 'import numpy as np\n'), ((4513, 4531), 'numpy.eye', 'np.eye', (['U.shape[0]'], {}), '(U.shape[0])\n', (4519, 4531), True, 'import numpy as np\n')]
""" Script to make training dataset for 6*6 """ # %% import os,sys from numpy.lib.npyio import save import vtk,vtktools import u2r import numpy as np import matplotlib.pyplot as plt import random from nirom_dd_tools import * import copy ### MY version of nirom_dd_orig.py for Buildings Case Time Dependent Data # some functions of tools.io copied in def write_sing_values(s_values): f= open('singular_values.dat',"w+") f.write('# index, s_values, normalised s_values, cumulative energy \n' ) for k in range(len(s_values)): #f.write('# field: %s\n' % field[k]) total = 0.0 s_values = s_values[k] for i in range(len(s_values)): total = total + s_values[i]*s_values[i] running_total = 0.0 for i in range(len(s_values)): running_total = running_total + s_values[i]*s_values[i] f.write ('%d %g %g %18.10g \n' % (i, s_values[i], s_values[i]/s_values[0], running_total/total) ) f.close() return def get_clean_vtk_file(filename): "Removes fields and arrays from a vtk file, leaving the coordinates/connectivity information." vtu_data = vtktools.vtu(filename) clean_vtu = vtktools.vtu() clean_vtu.ugrid.DeepCopy(vtu_data.ugrid) fieldNames = clean_vtu.GetFieldNames() # remove all fields and arrays from this vtu for field in fieldNames: clean_vtu.RemoveField(field) fieldNames = clean_vtu.GetFieldNames() vtkdata=clean_vtu.ugrid.GetCellData() arrayNames = [vtkdata.GetArrayName(i) for i in range(vtkdata.GetNumberOfArrays())] for array in arrayNames: vtkdata.RemoveArray(array) return clean_vtu #(nNodes, reconstruction_on_mesh[iTime*nScalar:(iTime+1)*nScalar,:], template_vtu, original_data[0][iTime*nDim:(iTime+1)*nDim], iTime) def create_vtu_file(path, nNodes, value_mesh_twice_interp, filename, orig_vel, iTime): velocity_field = np.zeros((nNodes,3)) velocity_field[:,0:nDim] = np.transpose(value_mesh_twice_interp[0:nDim,:]) # streamwise component only difference = np.zeros((nNodes,3)) difference[:,0:nDim] = np.transpose(value_mesh_twice_interp[0:nDim,:]) - orig_vel # streamwise component only difference = difference / np.max(velocity_field) clean_vtk = get_clean_vtk_file(filename) new_vtu = vtktools.vtu() new_vtu.ugrid.DeepCopy(clean_vtk.ugrid) new_vtu.filename = path + 'recon_' + str(iTime) + '.vtu' new_vtu.AddField('Velocity',velocity_field) new_vtu.AddField('Original',orig_vel) new_vtu.AddField('Velocity_diff',difference) new_vtu.Write() return def create_vtu_file_timelevel(nNodes, value_mesh_twice_interp, template_vtu, iTime): velocity_field = np.zeros((nNodes,3)) velocity_field[:,0:nDim] = np.transpose(value_mesh_twice_interp[0:nDim,:]) # streamwise component only # difference = np.zeros((nNodes,3)) # difference[:,0:nDim] = np.transpose(value_mesh_twice_interp[0:nDim,:]) - orig_vel # streamwise component only clean_vtk = get_clean_vtk_file(template_vtu) new_vtu = vtktools.vtu() new_vtu.ugrid.DeepCopy(clean_vtk.ugrid) new_vtu.filename = 'reconstructed_' + str(iTime) + '.vtu' new_vtu.AddField('Velocity',velocity_field) #new_vtu.AddField('Velocity_diff',difference) new_vtu.Write() return #code for full domain case # def get_grid_end_points(grid_origin,grid_width,iGrid ): # return np.array(( grid_origin[0]+iGrid*grid_width[0], grid_origin[1] +iGrid*grid_width[1]))# def get_grid_end_points(grid_origin,grid_width): return np.array((grid_origin[0]+grid_width[0], grid_origin[1] +grid_width[1])) def plot_grid(grid_origin, grid_width, nx, ny): # include plot of entire coordinates with grid plt.figure(figsize=(9,9)) plt.plot(coordinates[:,0], coordinates[:,1], 'g.', ms = 0.3, label = 'angle = {}˚'.format(rangle)) # corrdinates # code for just the edges # plt.plot([grid_origin[0], grid_origin[0]+grid_width[0]], [grid_origin[1], grid_origin[1]], 'ko-') #1 # plt.plot([grid_origin[0], grid_origin[0]], [grid_origin[1], grid_origin[1]+grid_width[1]], 'ko-') #2 # plt.plot([grid_origin[0], grid_origin[0]+grid_width[0]], [grid_origin[1]+grid_width[1], grid_origin[1]+grid_width[1]], 'ko-') #3 # plt.plot([grid_origin[0]+grid_width[0], grid_origin[0]+grid_width[0]], [grid_origin[1], grid_origin[1]+grid_width[1]], 'ko-') #4 for d in range(ny + 1): if d%4 == 0: plt.plot([grid_origin[0], grid_origin[0]+grid_width[0]], [grid_origin[1]+d*ddx[1], grid_origin[1]+d*ddx[1]], 'k-', lw = 1.2) #horizontal if ny == nx: plt.plot([grid_origin[0]+d*ddx[1], grid_origin[0]+d*ddx[1]], [grid_origin[1], grid_origin[1]+grid_width[1]], 'k-', lw = 1.2) #vertical if ny != nx: for d in range (nx + 1): #vertical if d%4 == 0: plt.plot([grid_origin[0]+d*ddx[0], grid_origin[0]+d*ddx[0]], [grid_origin[1], grid_origin[1]+grid_width[1]], 'k-', lw = 1.2) #vertical plt.grid(':') plt.tight_layout() plt.legend(loc = 'best') # plt.show() def rotate_mesh(angle): theta = np.radians(angle) #shift coordinates so that they are centred at (0,0) # for i in range(coordinates.shape[0]): # coordinates[i][0] -= 1.5 # coordinates[i][1] -= 1.5 new_mesh = np.zeros(coordinates.shape) for i in range(coordinates.shape[0]): new_mesh[i][0] = (coordinates[i][0]-(xlength/2))*np.cos(theta) - (coordinates[i][1]-(xlength/2))*np.sin(theta) new_mesh[i][1] = (coordinates[i][0]-(xlength/2))*np.sin(theta) + (coordinates[i][1]-(xlength/2))*np.cos(theta) #rotate the velocity field as well return new_mesh def rotate_vel(angle, velocity_field): theta = np.radians(angle) new_mesh = np.zeros(velocity_field.shape) for i in range(coordinates.shape[0]): new_mesh[i][0] = (velocity_field[i][0])*np.cos(theta) - (velocity_field[i][1])*np.sin(theta) new_mesh[i][1] = (velocity_field[i][0])*np.sin(theta) + (velocity_field[i][1])*np.cos(theta) return new_mesh def select_gridpoint(): min_x = min(coordinates[:,0]) max_x = max(coordinates[:,0]) min_y = min(coordinates[:,1]) max_y = max(coordinates[:,1]) grid_origin = [9,9] while np.sqrt(grid_origin[0]**2+grid_origin[1]**2) >= 2.75: # print("finding point - ", np.sqrt(grid_origin[0]**2+grid_origin[1]**2)) grid_origin = [random.uniform(min_x+0.8, max_x-1.3), random.uniform(min_y+0.8, max_y-1.3)] return grid_origin def sample_starshape(mesh, grid_origin): """ Returns a snapshot matrix of shape (5,nx*ny) and snapshot_ae of shape (5,nx,ny) with given mesh and central grid origin for the starshape grid formation """ grid_point_0 = [grid_origin[0], grid_origin[1]+grid_width[1]] grid_point_1 = [grid_origin[0]-grid_width[0], grid_origin[1]] grid_point_2 = [grid_origin[0]+grid_width[0], grid_origin[1]] grid_point_3 = [grid_origin[0], grid_origin[1]-grid_width[1]] #grid_point_4 = grid_origin grid_list = [grid_point_0,grid_point_1, grid_point_2, grid_point_3, grid_origin] s_matrix = np.zeros((nx*ny, 5)) s_ae = np.zeros((5,nx,ny)) for iloc in range(5): value_grid = u2r.simple_interpolate_from_mesh_to_grid(mesh, x_all, x_ndgln, ddx, grid_list[iloc], nx, ny, nz, zeros_beyond_mesh, nEl, nloc, nNodes, nScalar, nDim,1) s_matrix[:,iloc] = value_grid.reshape(-1) s_ae[iloc,:,:] = value_grid.reshape((nx,ny)) return s_matrix, s_ae def plot_starshape(nSGrids, iTime, iField = 0): plt.figure(figsize=(8,8)) plt.subplot(3,3,2) plt.imshow(np.rot90(Ssnapshot_ae[iTime,5*nSGrids,:,:,iField])) plt.subplot(3,3,4) plt.imshow(np.rot90(Ssnapshot_ae[iTime,5*nSGrids+1,:,:,iField])) plt.subplot(3,3,5) plt.imshow(np.rot90(Ssnapshot_ae[iTime,5*nSGrids+4,:,:,iField])) plt.subplot(3,3,6) plt.imshow(np.rot90(Ssnapshot_ae[iTime,5*nSGrids+2,:,:,iField])) plt.subplot(3,3,8) plt.imshow(np.rot90(Ssnapshot_ae[iTime,5*nSGrids+3,:,:,iField])) plt.tight_layout() # plt.show() ## settings snapshot_data_location = '../data/' snapshot_file_base = 'Flow_past_buildings_' nTime = 475 offset = 25 t_step = 1 field_names = ['Velocity', 'VelocityAbsorption'] nFields = len(field_names) assert nTime <= (500 - offset), "Time range nTime is larger than what comprises full dataset" # nSnapshots = nTime // t_step # print("Number of time level Snapshots = ", nSnapshots) xlength = 6.0 ylength = 6.0 grid_width = [0.5,0.5] # spacing inside small grid nx = int(grid_width[0]*100) ny = nx nz = 1 ddx = np.array((0.01,0.01)) # set number of grids - samples/snapshots to take # nGrids = 3000 # Turn on/off snapshots matrix save_snapshots = False save_stargrid = True # Turn on/off save first 20 images save_imgs = True # get a vtu file (any will do as the mesh is not adapted) filename = snapshot_data_location + snapshot_file_base + '84.vtu' representative_vtu = vtktools.vtu(filename) coordinates_org = representative_vtu.GetLocations() #coordinates of the nodes coordinates = coordinates_org nNodes = coordinates.shape[0] # vtu_data.ugrid.GetNumberOfPoints() nEl = representative_vtu.ugrid.GetNumberOfCells() # print('nEl', nEl, type(nEl), 'nNodes', nNodes) #nNodes = 375627 #nEl = 125209 nloc = 3 # number of local nodes, ie three nodes per element (in 2D) # nScalar = 2 # dimension of fields , 2 = u and v nScalar = 1 #because I calculate u and v separately nDim = 2 # dimension of problem (no need to interpolate in the third dimension) # x_all = np.transpose(coordinates[:,0:nDim]) ### coords n,3 x_all 2,n # get global node numbers x_ndgln = np.zeros((nEl*nloc), dtype=int) for iEl in range(nEl): n = representative_vtu.GetCellPoints(iEl) + 1 x_ndgln[iEl*nloc:(iEl+1)*nloc] = n # %% print("Generating starshape grids") zeros_beyond_mesh = 0 #load central grids and angles # origin_save = np.load("grid_origins.npy") # rangle_save = np.load("rotation_angles.npy") #set number of starshape grids to use nSGrids = 2000 # print("Number of available central grids: ", len(origin_save)) # assert nSGrids <= nGrids, "Cannot make more starshape grids than number of central grids we have" # Ssnapshots_matrix = np.zeros((nx*ny*3, nSGrids*5)) Ssnapshot_ae = np.zeros((nSGrids*2*5,nx,ny,3)) for iGrid in range(nSGrids): rand_t = random.randint(offset, nTime+offset-1) print("Sampling at starshape grid ", iGrid+1, " out of ", nSGrids) # call saved values for grid origin and random angle # grid_origin = origin_save[iGrid] #have offset of 50 # rangle = rangle_save[iGrid] #find new random location and location grid_origin = select_gridpoint() rangle = random.randint(0,360) # print("grid origin", grid_origin[0], grid_origin[1], ", angle = ", rangle) for i in range(2): iTime = rand_t+(i*t_step) print("Sampling at Timestep ", iTime) filename = snapshot_data_location + snapshot_file_base + str(iTime) + '.vtu' vtu_data = vtktools.vtu(filename) iSnapshot = iTime // t_step # print("rangle ", rangle, "grid_origin", grid_origin[0], grid_origin[1]) coordinates_org = vtu_data.GetLocations() #coordinates of the nodes nEl = vtu_data.ugrid.GetNumberOfCells() x_ndgln = np.zeros((nEl*nloc), dtype=int) for iEl in range(nEl): n = vtu_data.GetCellPoints(iEl) + 1 x_ndgln[iEl*nloc:(iEl+1)*nloc] = n # print("nEl for time level ", iTime, " = ", nEl) # rotate mesh and velocity coordinates = coordinates_org coordinates = rotate_mesh(rangle) if iGrid <= 50 and i == 0: plot_grid(grid_origin, grid_width, nx, ny) plt.savefig("imgs/grid_" + str(iGrid) + ".png") plt.close() nNodes = coordinates.shape[0] # vtu_data.ugrid.GetNumberOfPoints() x_all = np.transpose(coordinates[:,0:nDim]) velocity_field = vtu_data.GetField(field_names[0])[:,:nDim] #field name 0 is velocity field velocity_field = rotate_vel(rangle, velocity_field) #rotate velocity va_field = vtu_data.GetField(field_names[1])[:,0] index = (iGrid*2)+ i # print("Snapshot index: ", index) #starshape for u_vel u_mesh = np.zeros((1,nNodes,1)) u_mesh[:,:,0] = np.transpose(velocity_field[:,0]) _, u_sae = sample_starshape(u_mesh, grid_origin) # Ssnapshots_matrix[:nx*ny,5*iGrid:5*iGrid+5] = u_smatrix Ssnapshot_ae[5*index:5*index+5,:,:,0] = u_sae #starshape for v_vel v_mesh = np.zeros((1,nNodes,1)) v_mesh[:,:,0] = np.transpose(velocity_field[:,1]) _, v_sae = sample_starshape(v_mesh, grid_origin) # Ssnapshots_matrix[nx*ny:nx*ny*2,5*iGrid:5*iGrid+5] = v_smatrix Ssnapshot_ae[5*index:5*index+5,:,:,1] = v_sae #starshape for va va_mesh = np.zeros((1,nNodes,1)) va_mesh[:,:,0] = np.transpose(va_field) va_smatrix, va_sae = sample_starshape(va_mesh, grid_origin) # Ssnapshots_matrix[nx*ny*2:nx*ny*3,5*iGrid:5*iGrid+5] = va_smatrix Ssnapshot_ae[5*index:5*index+5,:,:,2] = va_sae #Scale values # min_vel = np.amin(Ssnapshots_matrix[:nx*ny*2,:]) #minimum among u and v velocity # max_vel = np.amax(Ssnapshots_matrix[:nx*ny*2,:]) min_vel = np.amin(Ssnapshot_ae[:,:,:,:2]) max_vel = np.amax(Ssnapshot_ae[:,:,:,:2]) # min_vel = -6.545574188232422 # max_vel = 6.623080253601074 vel_scaling = 1/(max_vel-min_vel) min_va = np.amin(Ssnapshot_ae[:,:,:,2]) max_va = np.amax(Ssnapshot_ae[:,:,:,2]) va_scaling = 1/(max_va - min_va) #scale snapshots for ae # Ssnapshot_ae = vel_scaling*(Ssnapshot_ae-min_vel) Ssnapshot_ae[:,:,:,:2] = vel_scaling*(Ssnapshot_ae[:,:,:,:2]-min_vel) Ssnapshot_ae[:,:,:,2] = va_scaling*Ssnapshot_ae[:,:,:,2] # print("Scaled minimum = ", np.amin(Ssnapshot_ae[:,:,:,:2])) # print("Scaled maximum = ", np.amax(Ssnapshot_ae[:,:,:,:2])) np.save("training_set_8.npy",Ssnapshot_ae) textfile = open("training_set_8.txt", 'w') textfile.write("min_vel = "+str(min_vel) +" , max_vel = "+ str(max_vel)+ " , vel_scaling = "+ str(vel_scaling)) textfile.close() print("min_vel = ", min_vel, " , max_vel = ", max_vel, " , vel_scaling = ", vel_scaling) # %%
[ "numpy.amin", "matplotlib.pyplot.figure", "numpy.rot90", "numpy.sin", "matplotlib.pyplot.tight_layout", "random.randint", "matplotlib.pyplot.close", "numpy.transpose", "numpy.max", "numpy.radians", "numpy.save", "matplotlib.pyplot.legend", "vtktools.vtu", "numpy.cos", "matplotlib.pyplot....
[((8647, 8669), 'numpy.array', 'np.array', (['(0.01, 0.01)'], {}), '((0.01, 0.01))\n', (8655, 8669), True, 'import numpy as np\n'), ((9010, 9032), 'vtktools.vtu', 'vtktools.vtu', (['filename'], {}), '(filename)\n', (9022, 9032), False, 'import vtk, vtktools\n'), ((9701, 9732), 'numpy.zeros', 'np.zeros', (['(nEl * nloc)'], {'dtype': 'int'}), '(nEl * nloc, dtype=int)\n', (9709, 9732), True, 'import numpy as np\n'), ((10321, 10359), 'numpy.zeros', 'np.zeros', (['(nSGrids * 2 * 5, nx, ny, 3)'], {}), '((nSGrids * 2 * 5, nx, ny, 3))\n', (10329, 10359), True, 'import numpy as np\n'), ((13380, 13414), 'numpy.amin', 'np.amin', (['Ssnapshot_ae[:, :, :, :2]'], {}), '(Ssnapshot_ae[:, :, :, :2])\n', (13387, 13414), True, 'import numpy as np\n'), ((13422, 13456), 'numpy.amax', 'np.amax', (['Ssnapshot_ae[:, :, :, :2]'], {}), '(Ssnapshot_ae[:, :, :, :2])\n', (13429, 13456), True, 'import numpy as np\n'), ((13559, 13592), 'numpy.amin', 'np.amin', (['Ssnapshot_ae[:, :, :, 2]'], {}), '(Ssnapshot_ae[:, :, :, 2])\n', (13566, 13592), True, 'import numpy as np\n'), ((13599, 13632), 'numpy.amax', 'np.amax', (['Ssnapshot_ae[:, :, :, 2]'], {}), '(Ssnapshot_ae[:, :, :, 2])\n', (13606, 13632), True, 'import numpy as np\n'), ((13993, 14036), 'numpy.save', 'np.save', (['"""training_set_8.npy"""', 'Ssnapshot_ae'], {}), "('training_set_8.npy', Ssnapshot_ae)\n", (14000, 14036), True, 'import numpy as np\n'), ((1147, 1169), 'vtktools.vtu', 'vtktools.vtu', (['filename'], {}), '(filename)\n', (1159, 1169), False, 'import vtk, vtktools\n'), ((1186, 1200), 'vtktools.vtu', 'vtktools.vtu', ([], {}), '()\n', (1198, 1200), False, 'import vtk, vtktools\n'), ((1913, 1934), 'numpy.zeros', 'np.zeros', (['(nNodes, 3)'], {}), '((nNodes, 3))\n', (1921, 1934), True, 'import numpy as np\n'), ((1965, 2013), 'numpy.transpose', 'np.transpose', (['value_mesh_twice_interp[0:nDim, :]'], {}), '(value_mesh_twice_interp[0:nDim, :])\n', (1977, 2013), True, 'import numpy as np\n'), ((2059, 2080), 'numpy.zeros', 'np.zeros', (['(nNodes, 3)'], {}), '((nNodes, 3))\n', (2067, 2080), True, 'import numpy as np\n'), ((2307, 2321), 'vtktools.vtu', 'vtktools.vtu', ([], {}), '()\n', (2319, 2321), False, 'import vtk, vtktools\n'), ((2704, 2725), 'numpy.zeros', 'np.zeros', (['(nNodes, 3)'], {}), '((nNodes, 3))\n', (2712, 2725), True, 'import numpy as np\n'), ((2756, 2804), 'numpy.transpose', 'np.transpose', (['value_mesh_twice_interp[0:nDim, :]'], {}), '(value_mesh_twice_interp[0:nDim, :])\n', (2768, 2804), True, 'import numpy as np\n'), ((3051, 3065), 'vtktools.vtu', 'vtktools.vtu', ([], {}), '()\n', (3063, 3065), False, 'import vtk, vtktools\n'), ((3547, 3621), 'numpy.array', 'np.array', (['(grid_origin[0] + grid_width[0], grid_origin[1] + grid_width[1])'], {}), '((grid_origin[0] + grid_width[0], grid_origin[1] + grid_width[1]))\n', (3555, 3621), True, 'import numpy as np\n'), ((3723, 3749), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 9)'}), '(figsize=(9, 9))\n', (3733, 3749), True, 'import matplotlib.pyplot as plt\n'), ((5001, 5014), 'matplotlib.pyplot.grid', 'plt.grid', (['""":"""'], {}), "(':')\n", (5009, 5014), True, 'import matplotlib.pyplot as plt\n'), ((5019, 5037), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5035, 5037), True, 'import matplotlib.pyplot as plt\n'), ((5042, 5064), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (5052, 5064), True, 'import matplotlib.pyplot as plt\n'), ((5121, 5138), 'numpy.radians', 'np.radians', (['angle'], {}), '(angle)\n', (5131, 5138), True, 'import numpy as np\n'), ((5327, 5354), 'numpy.zeros', 'np.zeros', (['coordinates.shape'], {}), '(coordinates.shape)\n', (5335, 5354), True, 'import numpy as np\n'), ((5749, 5766), 'numpy.radians', 'np.radians', (['angle'], {}), '(angle)\n', (5759, 5766), True, 'import numpy as np\n'), ((5782, 5812), 'numpy.zeros', 'np.zeros', (['velocity_field.shape'], {}), '(velocity_field.shape)\n', (5790, 5812), True, 'import numpy as np\n'), ((7160, 7182), 'numpy.zeros', 'np.zeros', (['(nx * ny, 5)'], {}), '((nx * ny, 5))\n', (7168, 7182), True, 'import numpy as np\n'), ((7192, 7213), 'numpy.zeros', 'np.zeros', (['(5, nx, ny)'], {}), '((5, nx, ny))\n', (7200, 7213), True, 'import numpy as np\n'), ((7595, 7621), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (7605, 7621), True, 'import matplotlib.pyplot as plt\n'), ((7625, 7645), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(3)', '(2)'], {}), '(3, 3, 2)\n', (7636, 7645), True, 'import matplotlib.pyplot as plt\n'), ((7716, 7736), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(3)', '(4)'], {}), '(3, 3, 4)\n', (7727, 7736), True, 'import matplotlib.pyplot as plt\n'), ((7809, 7829), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(3)', '(5)'], {}), '(3, 3, 5)\n', (7820, 7829), True, 'import matplotlib.pyplot as plt\n'), ((7902, 7922), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(3)', '(6)'], {}), '(3, 3, 6)\n', (7913, 7922), True, 'import matplotlib.pyplot as plt\n'), ((7995, 8015), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(3)', '(8)'], {}), '(3, 3, 8)\n', (8006, 8015), True, 'import matplotlib.pyplot as plt\n'), ((8088, 8106), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8104, 8106), True, 'import matplotlib.pyplot as plt\n'), ((10396, 10438), 'random.randint', 'random.randint', (['offset', '(nTime + offset - 1)'], {}), '(offset, nTime + offset - 1)\n', (10410, 10438), False, 'import random\n'), ((10750, 10772), 'random.randint', 'random.randint', (['(0)', '(360)'], {}), '(0, 360)\n', (10764, 10772), False, 'import random\n'), ((2107, 2155), 'numpy.transpose', 'np.transpose', (['value_mesh_twice_interp[0:nDim, :]'], {}), '(value_mesh_twice_interp[0:nDim, :])\n', (2119, 2155), True, 'import numpy as np\n'), ((2224, 2246), 'numpy.max', 'np.max', (['velocity_field'], {}), '(velocity_field)\n', (2230, 2246), True, 'import numpy as np\n'), ((6275, 6325), 'numpy.sqrt', 'np.sqrt', (['(grid_origin[0] ** 2 + grid_origin[1] ** 2)'], {}), '(grid_origin[0] ** 2 + grid_origin[1] ** 2)\n', (6282, 6325), True, 'import numpy as np\n'), ((7260, 7420), 'u2r.simple_interpolate_from_mesh_to_grid', 'u2r.simple_interpolate_from_mesh_to_grid', (['mesh', 'x_all', 'x_ndgln', 'ddx', 'grid_list[iloc]', 'nx', 'ny', 'nz', 'zeros_beyond_mesh', 'nEl', 'nloc', 'nNodes', 'nScalar', 'nDim', '(1)'], {}), '(mesh, x_all, x_ndgln, ddx,\n grid_list[iloc], nx, ny, nz, zeros_beyond_mesh, nEl, nloc, nNodes,\n nScalar, nDim, 1)\n', (7300, 7420), False, 'import u2r\n'), ((7659, 7715), 'numpy.rot90', 'np.rot90', (['Ssnapshot_ae[iTime, 5 * nSGrids, :, :, iField]'], {}), '(Ssnapshot_ae[iTime, 5 * nSGrids, :, :, iField])\n', (7667, 7715), True, 'import numpy as np\n'), ((7750, 7810), 'numpy.rot90', 'np.rot90', (['Ssnapshot_ae[iTime, 5 * nSGrids + 1, :, :, iField]'], {}), '(Ssnapshot_ae[iTime, 5 * nSGrids + 1, :, :, iField])\n', (7758, 7810), True, 'import numpy as np\n'), ((7843, 7903), 'numpy.rot90', 'np.rot90', (['Ssnapshot_ae[iTime, 5 * nSGrids + 4, :, :, iField]'], {}), '(Ssnapshot_ae[iTime, 5 * nSGrids + 4, :, :, iField])\n', (7851, 7903), True, 'import numpy as np\n'), ((7936, 7996), 'numpy.rot90', 'np.rot90', (['Ssnapshot_ae[iTime, 5 * nSGrids + 2, :, :, iField]'], {}), '(Ssnapshot_ae[iTime, 5 * nSGrids + 2, :, :, iField])\n', (7944, 7996), True, 'import numpy as np\n'), ((8029, 8089), 'numpy.rot90', 'np.rot90', (['Ssnapshot_ae[iTime, 5 * nSGrids + 3, :, :, iField]'], {}), '(Ssnapshot_ae[iTime, 5 * nSGrids + 3, :, :, iField])\n', (8037, 8089), True, 'import numpy as np\n'), ((11061, 11083), 'vtktools.vtu', 'vtktools.vtu', (['filename'], {}), '(filename)\n', (11073, 11083), False, 'import vtk, vtktools\n'), ((11346, 11377), 'numpy.zeros', 'np.zeros', (['(nEl * nloc)'], {'dtype': 'int'}), '(nEl * nloc, dtype=int)\n', (11354, 11377), True, 'import numpy as np\n'), ((11945, 11981), 'numpy.transpose', 'np.transpose', (['coordinates[:, 0:nDim]'], {}), '(coordinates[:, 0:nDim])\n', (11957, 11981), True, 'import numpy as np\n'), ((12336, 12360), 'numpy.zeros', 'np.zeros', (['(1, nNodes, 1)'], {}), '((1, nNodes, 1))\n', (12344, 12360), True, 'import numpy as np\n'), ((12383, 12417), 'numpy.transpose', 'np.transpose', (['velocity_field[:, 0]'], {}), '(velocity_field[:, 0])\n', (12395, 12417), True, 'import numpy as np\n'), ((12641, 12665), 'numpy.zeros', 'np.zeros', (['(1, nNodes, 1)'], {}), '((1, nNodes, 1))\n', (12649, 12665), True, 'import numpy as np\n'), ((12688, 12722), 'numpy.transpose', 'np.transpose', (['velocity_field[:, 1]'], {}), '(velocity_field[:, 1])\n', (12700, 12722), True, 'import numpy as np\n'), ((12951, 12975), 'numpy.zeros', 'np.zeros', (['(1, nNodes, 1)'], {}), '((1, nNodes, 1))\n', (12959, 12975), True, 'import numpy as np\n'), ((12999, 13021), 'numpy.transpose', 'np.transpose', (['va_field'], {}), '(va_field)\n', (13011, 13021), True, 'import numpy as np\n'), ((4443, 4579), 'matplotlib.pyplot.plot', 'plt.plot', (['[grid_origin[0], grid_origin[0] + grid_width[0]]', '[grid_origin[1] + d * ddx[1], grid_origin[1] + d * ddx[1]]', '"""k-"""'], {'lw': '(1.2)'}), "([grid_origin[0], grid_origin[0] + grid_width[0]], [grid_origin[1] +\n d * ddx[1], grid_origin[1] + d * ddx[1]], 'k-', lw=1.2)\n", (4451, 4579), True, 'import matplotlib.pyplot as plt\n'), ((6434, 6474), 'random.uniform', 'random.uniform', (['(min_x + 0.8)', '(max_x - 1.3)'], {}), '(min_x + 0.8, max_x - 1.3)\n', (6448, 6474), False, 'import random\n'), ((6472, 6512), 'random.uniform', 'random.uniform', (['(min_y + 0.8)', '(max_y - 1.3)'], {}), '(min_y + 0.8, max_y - 1.3)\n', (6486, 6512), False, 'import random\n'), ((11841, 11852), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (11850, 11852), True, 'import matplotlib.pyplot as plt\n'), ((4623, 4760), 'matplotlib.pyplot.plot', 'plt.plot', (['[grid_origin[0] + d * ddx[1], grid_origin[0] + d * ddx[1]]', '[grid_origin[1], grid_origin[1] + grid_width[1]]', '"""k-"""'], {'lw': '(1.2)'}), "([grid_origin[0] + d * ddx[1], grid_origin[0] + d * ddx[1]], [\n grid_origin[1], grid_origin[1] + grid_width[1]], 'k-', lw=1.2)\n", (4631, 4760), True, 'import matplotlib.pyplot as plt\n'), ((4860, 4997), 'matplotlib.pyplot.plot', 'plt.plot', (['[grid_origin[0] + d * ddx[0], grid_origin[0] + d * ddx[0]]', '[grid_origin[1], grid_origin[1] + grid_width[1]]', '"""k-"""'], {'lw': '(1.2)'}), "([grid_origin[0] + d * ddx[0], grid_origin[0] + d * ddx[0]], [\n grid_origin[1], grid_origin[1] + grid_width[1]], 'k-', lw=1.2)\n", (4868, 4997), True, 'import matplotlib.pyplot as plt\n'), ((5455, 5468), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (5461, 5468), True, 'import numpy as np\n'), ((5503, 5516), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (5509, 5516), True, 'import numpy as np\n'), ((5574, 5587), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (5580, 5587), True, 'import numpy as np\n'), ((5622, 5635), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (5628, 5635), True, 'import numpy as np\n'), ((5904, 5917), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (5910, 5917), True, 'import numpy as np\n'), ((5943, 5956), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (5949, 5956), True, 'import numpy as np\n'), ((6005, 6018), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6011, 6018), True, 'import numpy as np\n'), ((6044, 6057), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6050, 6057), True, 'import numpy as np\n')]
# Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import pyeparse as pp fname = '../pyeparse/tests/data/test_raw.edf' raw = pp.read_raw(fname) # visualize initial calibration raw.plot_calibration(title='5-Point Calibration') # create heatmap raw.plot_heatmap(start=3., stop=60.) # find events and epoch data events = raw.find_events('SYNCTIME', event_id=1) tmin, tmax, event_id = -0.5, 1.5, 1 epochs = pp.Epochs(raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax) # access pandas data frame and plot single epoch fig, ax = plt.subplots() ax.plot(epochs[3].get_data('xpos')[0], epochs[3].get_data('ypos')[0]) # iterate over and access numpy arrays. # find epochs withouth loss of tracking / blinks print(len([e for e in epochs if not np.isnan(e).any()])) fig, ax = plt.subplots() ax.set_title('Superimposed saccade responses') n_trials = 12 # first 12 trials for epoch in epochs[:n_trials]: ax.plot(epochs.times * 1e3, epoch[0].T) time_mask = epochs.times > 0 times = epochs.times * 1e3 fig, ax = plt.subplots() ax.plot(times[time_mask], epochs.data[0, 0, time_mask]) ax.set_title('Post baseline saccade (X, pos)') # plot single trials epochs.plot(picks=['xpos'], draw_discrete='saccades') plt.show()
[ "matplotlib.pyplot.show", "pyeparse.read_raw", "pyeparse.Epochs", "numpy.isnan", "matplotlib.pyplot.subplots" ]
[((185, 203), 'pyeparse.read_raw', 'pp.read_raw', (['fname'], {}), '(fname)\n', (196, 203), True, 'import pyeparse as pp\n'), ((466, 536), 'pyeparse.Epochs', 'pp.Epochs', (['raw'], {'events': 'events', 'event_id': 'event_id', 'tmin': 'tmin', 'tmax': 'tmax'}), '(raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax)\n', (475, 536), True, 'import pyeparse as pp\n'), ((616, 630), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (628, 630), True, 'import matplotlib.pyplot as plt\n'), ((859, 873), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (871, 873), True, 'import matplotlib.pyplot as plt\n'), ((1098, 1112), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1110, 1112), True, 'import matplotlib.pyplot as plt\n'), ((1292, 1302), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1300, 1302), True, 'import matplotlib.pyplot as plt\n'), ((827, 838), 'numpy.isnan', 'np.isnan', (['e'], {}), '(e)\n', (835, 838), True, 'import numpy as np\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import scipy.io import torch import torch.nn as nn import numpy as np from glob import glob import scipy.misc as sic import subprocess import models.network as net import argparse import random import imageio from vgg import VGG19 parser = argparse.ArgumentParser() parser.add_argument("--model", default='Test', type=str, help="Name of model") parser.add_argument("--save_freq", default=5, type=int, help="save frequency of epochs") parser.add_argument("--use_gpu", default=1, type=int, help="use gpu or not") parser.add_argument("--with_IRT", default=0, type=int, help="use IRT or not") parser.add_argument("--IRT_initialization", default=0, type=int, help="use initialization for IRT or not") parser.add_argument("--max_epoch", default=25, type=int, help="The max number of epochs for training") parser.add_argument("--input", default='./demo/colorization/goat_input', type=str, help="dir of input video") parser.add_argument("--processed", default='./demo/colorization/goat_processed', type=str, help="dir of processed video") parser.add_argument("--output", default='None', type=str, help="dir of output video") # set random seed seed = 2020 np.random.seed(seed) torch.manual_seed(seed) random.seed(seed) # process arguments ARGS = parser.parse_args() print(ARGS) save_freq = ARGS.save_freq input_folder = ARGS.input processed_folder = ARGS.processed with_IRT = ARGS.with_IRT maxepoch = ARGS.max_epoch + 1 model= ARGS.model task = "/{}_IRT{}_initial{}".format(model, with_IRT, ARGS.IRT_initialization) #Colorization, HDR, StyleTransfer, Dehazing # set gpu if ARGS.use_gpu: os.environ["CUDA_VISIBLE_DEVICES"]=str(np.argmax([int(x.split()[2]) for x in subprocess.Popen("nvidia-smi -q -d Memory | grep -A4 GPU | grep Free", shell=True, stdout=subprocess.PIPE).stdout.readlines()])) else: os.environ["CUDA_VISIBLE_DEVICES"] = '' device = torch.device("cuda:0" if ARGS.use_gpu else "cpu") # clear cuda cache torch.cuda.empty_cache() # define loss function def compute_error(real,fake): # return tf.reduce_mean(tf.abs(fake-real)) return torch.mean(torch.abs(fake-real)) def Lp_loss(x, y): vgg_real = VGG_19(normalize_batch(x)) vgg_fake = VGG_19(normalize_batch(y)) p0 = compute_error(normalize_batch(x), normalize_batch(y)) content_loss_list = [] content_loss_list.append(p0) feat_layers = {'conv1_2' : 1.0/2.6, 'conv2_2' : 1.0/4.8, 'conv3_2': 1.0/3.7, 'conv4_2':1.0/5.6, 'conv5_2':10.0/1.5} for layer, w in feat_layers.items(): pi = compute_error(vgg_real[layer], vgg_fake[layer]) content_loss_list.append(w * pi) content_loss = torch.sum(torch.stack(content_loss_list)) return content_loss loss_L2 = torch.nn.MSELoss() loss_L1 = torch.nn.L1Loss() # Define model . out_channels = 6 if with_IRT else 3 net = net.UNet(in_channels=3, out_channels=out_channels, init_features=32) net.to(device) optimizer = torch.optim.Adam(net.parameters(), lr=0.0001) # scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[3000,8000], gamma=0.5) VGG_19 = VGG19(requires_grad=False).to(device) # prepare data input_folders = [input_folder] processed_folders = [processed_folder] def prepare_paired_input(task, id, input_names, processed_names, is_train=0): net_in = np.float32(imageio.imread(input_names[id]))/255.0 if len(net_in.shape) == 2: net_in = np.tile(net_in[:,:,np.newaxis], [1,1,3]) net_gt = np.float32(imageio.imread(processed_names[id]))/255.0 org_h,org_w = net_in.shape[:2] h = org_h // 32 * 32 w = org_w // 32 * 32 print(net_in.shape, net_gt.shape) return net_in[np.newaxis, :h, :w, :], net_gt[np.newaxis, :h, :w, :] # some functions def initialize_weights(model): for module in model.modules(): if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear): # nn.init.kaiming_normal_(module.weight) nn.init.xavier_normal_(module.weight) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.BatchNorm2d): module.weight.data.fill_(1) module.bias.data.zero_() def normalize_batch(batch): # Normalize batch using ImageNet mean and std mean = batch.new_tensor([0.485, 0.456, 0.406]).view(1, -1, 1, 1) std = batch.new_tensor([0.229, 0.224, 0.225]).view(1, -1, 1, 1) return (batch - mean) / std # start to train for folder_idx, input_folder in enumerate(input_folders): # -----------load data------------- input_names = sorted(glob(input_folders[folder_idx] + "/*")) processed_names = sorted(glob(processed_folders[folder_idx] + "/*")) if ARGS.output == "None": output_folder = "./result/{}".format(task + '/' + input_folder.split("/")[-2] + '/' + input_folder.split("/")[-1]) else: output_folder = ARGS.output + "/" + task + '/' + input_folder.split("/")[-1] print(output_folder, input_folders[folder_idx], processed_folders[folder_idx] ) num_of_sample = min(len(input_names), len(processed_names)) data_in_memory = [None] * num_of_sample #Speedup for id in range(min(len(input_names), len(processed_names))): #Speedup net_in,net_gt = prepare_paired_input(task, id, input_names, processed_names) #Speedup net_in = torch.from_numpy(net_in).permute(0,3,1,2).float().to(device) net_gt = torch.from_numpy(net_gt).permute(0,3,1,2).float().to(device) data_in_memory[id] = [net_in,net_gt] #Speedup # model re-initialization initialize_weights(net) step = 0 for epoch in range(1,maxepoch): # -----------start to train------------- print("Processing epoch {}".format(epoch)) frame_id = 0 if os.path.isdir("{}/{:04d}".format(output_folder, epoch)): continue else: os.makedirs("{}/{:04d}".format(output_folder, epoch)) if not os.path.isdir("{}/training".format(output_folder)): os.makedirs("{}/training".format(output_folder)) print(len(input_names), len(processed_names)) for id in range(num_of_sample): if with_IRT: if epoch < 6 and ARGS.IRT_initialization: net_in,net_gt = data_in_memory[0] #Option: prediction = net(net_in) crt_loss = loss_L1(prediction[:,:3,:,:], net_gt) + 0.9*loss_L1(prediction[:,3:,:,:], net_gt) else: net_in,net_gt = data_in_memory[id] prediction = net(net_in) prediction_main = prediction[:,:3,:,:] prediction_minor = prediction[:,3:,:,:] diff_map_main,_ = torch.max(torch.abs(prediction_main - net_gt) / (net_in+1e-1), dim=1, keepdim=True) diff_map_minor,_ = torch.max(torch.abs(prediction_minor - net_gt) / (net_in+1e-1), dim=1, keepdim=True) confidence_map = torch.lt(diff_map_main, diff_map_minor).repeat(1,3,1,1).float() crt_loss = loss_L1(prediction_main*confidence_map, net_gt*confidence_map) \ + loss_L1(prediction_minor*(1-confidence_map), net_gt*(1-confidence_map)) else: net_in,net_gt = data_in_memory[id] prediction = net(net_in) crt_loss = Lp_loss(prediction, net_gt) optimizer.zero_grad() crt_loss.backward() optimizer.step() frame_id+=1 step+=1 if step % 10 == 0: print("Image iter: {} {} {} || Loss: {:.4f} ".format(epoch, frame_id, step, crt_loss)) if step % 100 == 0 : net_in = net_in.permute(0,2,3,1).cpu().numpy() net_gt = net_gt.permute(0,2,3,1).cpu().numpy() prediction = prediction.detach().permute(0,2,3,1).cpu().numpy() if with_IRT: prediction = prediction[...,:3] imageio.imsave("{}/training/step{:06d}_{:06d}.jpg".format(output_folder, step, id), np.uint8(np.concatenate([net_in[0], prediction[0], net_gt[0]], axis=1).clip(0,1) * 255.0)) # # -----------save intermidiate results------------- if epoch % save_freq == 0: for id in range(num_of_sample): st=time.time() net_in,net_gt = data_in_memory[id] print("Test: {}-{} \r".format(id, num_of_sample)) with torch.no_grad(): prediction = net(net_in) net_in = net_in.permute(0,2,3,1).cpu().numpy() net_gt = net_gt.permute(0,2,3,1).cpu().numpy() prediction = prediction.detach().permute(0,2,3,1).cpu().numpy() if with_IRT: prediction_main = prediction[...,:3] prediction_minor = prediction[...,3:] diff_map_main = np.amax(np.absolute(prediction_main - net_gt) / (net_in+1e-1), axis=3, keepdims=True) diff_map_minor = np.amax(np.absolute(prediction_minor - net_gt) / (net_in+1e-1), axis=3, keepdims=True) confidence_map = np.tile(np.less(diff_map_main, diff_map_minor), (1,1,1,3)).astype('float32') imageio.imsave("{}/{:04d}/predictions_{:05d}.jpg".format(output_folder, epoch, id), np.uint8(np.concatenate([net_in[0,:,:,:3],prediction_main[0], prediction_minor[0],net_gt[0], confidence_map[0]], axis=1).clip(0,1) * 255.0)) imageio.imsave("{}/{:04d}/out_main_{:05d}.jpg".format(output_folder, epoch, id),np.uint8(prediction_main[0].clip(0,1) * 255.0)) imageio.imsave("{}/{:04d}/out_minor_{:05d}.jpg".format(output_folder, epoch, id),np.uint8(prediction_minor[0].clip(0,1) * 255.0)) else: imageio.imsave("{}/{:04d}/predictions_{:05d}.jpg".format(output_folder, epoch, id), np.uint8(np.concatenate([net_in[0,:,:,:3], prediction[0], net_gt[0]],axis=1).clip(0,1) * 255.0)) imageio.imsave("{}/{:04d}/out_main_{:05d}.jpg".format(output_folder, epoch, id), np.uint8(prediction[0].clip(0,1) * 255.0))
[ "numpy.absolute", "numpy.random.seed", "argparse.ArgumentParser", "models.network.UNet", "numpy.tile", "torch.device", "glob.glob", "torch.no_grad", "torch.nn.MSELoss", "models.network", "vgg.VGG19", "random.seed", "numpy.less", "subprocess.Popen", "torch.manual_seed", "imageio.imread"...
[((372, 397), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (395, 397), False, 'import argparse\n'), ((1280, 1300), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1294, 1300), True, 'import numpy as np\n'), ((1301, 1324), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1318, 1324), False, 'import torch\n'), ((1325, 1342), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1336, 1342), False, 'import random\n'), ((1997, 2046), 'torch.device', 'torch.device', (["('cuda:0' if ARGS.use_gpu else 'cpu')"], {}), "('cuda:0' if ARGS.use_gpu else 'cpu')\n", (2009, 2046), False, 'import torch\n'), ((2067, 2091), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (2089, 2091), False, 'import torch\n'), ((2836, 2854), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (2852, 2854), False, 'import torch\n'), ((2865, 2882), 'torch.nn.L1Loss', 'torch.nn.L1Loss', ([], {}), '()\n', (2880, 2882), False, 'import torch\n'), ((2944, 3012), 'models.network.UNet', 'net.UNet', ([], {'in_channels': '(3)', 'out_channels': 'out_channels', 'init_features': '(32)'}), '(in_channels=3, out_channels=out_channels, init_features=32)\n', (2952, 3012), True, 'import models.network as net\n'), ((3013, 3027), 'models.network.to', 'net.to', (['device'], {}), '(device)\n', (3019, 3027), True, 'import models.network as net\n'), ((3057, 3073), 'models.network.parameters', 'net.parameters', ([], {}), '()\n', (3071, 3073), True, 'import models.network as net\n'), ((2216, 2238), 'torch.abs', 'torch.abs', (['(fake - real)'], {}), '(fake - real)\n', (2225, 2238), False, 'import torch\n'), ((2768, 2798), 'torch.stack', 'torch.stack', (['content_loss_list'], {}), '(content_loss_list)\n', (2779, 2798), False, 'import torch\n'), ((3193, 3219), 'vgg.VGG19', 'VGG19', ([], {'requires_grad': '(False)'}), '(requires_grad=False)\n', (3198, 3219), False, 'from vgg import VGG19\n'), ((3509, 3553), 'numpy.tile', 'np.tile', (['net_in[:, :, np.newaxis]', '[1, 1, 3]'], {}), '(net_in[:, :, np.newaxis], [1, 1, 3])\n', (3516, 3553), True, 'import numpy as np\n'), ((4687, 4725), 'glob.glob', 'glob', (["(input_folders[folder_idx] + '/*')"], {}), "(input_folders[folder_idx] + '/*')\n", (4691, 4725), False, 'from glob import glob\n'), ((4756, 4798), 'glob.glob', 'glob', (["(processed_folders[folder_idx] + '/*')"], {}), "(processed_folders[folder_idx] + '/*')\n", (4760, 4798), False, 'from glob import glob\n'), ((3422, 3453), 'imageio.imread', 'imageio.imread', (['input_names[id]'], {}), '(input_names[id])\n', (3436, 3453), False, 'import imageio\n'), ((3574, 3609), 'imageio.imread', 'imageio.imread', (['processed_names[id]'], {}), '(processed_names[id])\n', (3588, 3609), False, 'import imageio\n'), ((4048, 4085), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['module.weight'], {}), '(module.weight)\n', (4070, 4085), True, 'import torch.nn as nn\n'), ((7635, 7646), 'models.network', 'net', (['net_in'], {}), '(net_in)\n', (7638, 7646), True, 'import models.network as net\n'), ((8683, 8694), 'time.time', 'time.time', ([], {}), '()\n', (8692, 8694), False, 'import time\n'), ((6582, 6593), 'models.network', 'net', (['net_in'], {}), '(net_in)\n', (6585, 6593), True, 'import models.network as net\n'), ((6839, 6850), 'models.network', 'net', (['net_in'], {}), '(net_in)\n', (6842, 6850), True, 'import models.network as net\n'), ((8834, 8849), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8847, 8849), False, 'import torch\n'), ((8884, 8895), 'models.network', 'net', (['net_in'], {}), '(net_in)\n', (8887, 8895), True, 'import models.network as net\n'), ((7039, 7074), 'torch.abs', 'torch.abs', (['(prediction_main - net_gt)'], {}), '(prediction_main - net_gt)\n', (7048, 7074), False, 'import torch\n'), ((7162, 7198), 'torch.abs', 'torch.abs', (['(prediction_minor - net_gt)'], {}), '(prediction_minor - net_gt)\n', (7171, 7198), False, 'import torch\n'), ((9323, 9360), 'numpy.absolute', 'np.absolute', (['(prediction_main - net_gt)'], {}), '(prediction_main - net_gt)\n', (9334, 9360), True, 'import numpy as np\n'), ((9446, 9484), 'numpy.absolute', 'np.absolute', (['(prediction_minor - net_gt)'], {}), '(prediction_minor - net_gt)\n', (9457, 9484), True, 'import numpy as np\n'), ((1804, 1914), 'subprocess.Popen', 'subprocess.Popen', (['"""nvidia-smi -q -d Memory | grep -A4 GPU | grep Free"""'], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), "('nvidia-smi -q -d Memory | grep -A4 GPU | grep Free',\n shell=True, stdout=subprocess.PIPE)\n", (1820, 1914), False, 'import subprocess\n'), ((5523, 5547), 'torch.from_numpy', 'torch.from_numpy', (['net_in'], {}), '(net_in)\n', (5539, 5547), False, 'import torch\n'), ((5601, 5625), 'torch.from_numpy', 'torch.from_numpy', (['net_gt'], {}), '(net_gt)\n', (5617, 5625), False, 'import torch\n'), ((9590, 9628), 'numpy.less', 'np.less', (['diff_map_main', 'diff_map_minor'], {}), '(diff_map_main, diff_map_minor)\n', (9597, 9628), True, 'import numpy as np\n'), ((7274, 7313), 'torch.lt', 'torch.lt', (['diff_map_main', 'diff_map_minor'], {}), '(diff_map_main, diff_map_minor)\n', (7282, 7313), False, 'import torch\n'), ((8434, 8495), 'numpy.concatenate', 'np.concatenate', (['[net_in[0], prediction[0], net_gt[0]]'], {'axis': '(1)'}), '([net_in[0], prediction[0], net_gt[0]], axis=1)\n', (8448, 8495), True, 'import numpy as np\n'), ((9797, 9918), 'numpy.concatenate', 'np.concatenate', (['[net_in[0, :, :, :3], prediction_main[0], prediction_minor[0], net_gt[0],\n confidence_map[0]]'], {'axis': '(1)'}), '([net_in[0, :, :, :3], prediction_main[0], prediction_minor[0\n ], net_gt[0], confidence_map[0]], axis=1)\n', (9811, 9918), True, 'import numpy as np\n'), ((10407, 10478), 'numpy.concatenate', 'np.concatenate', (['[net_in[0, :, :, :3], prediction[0], net_gt[0]]'], {'axis': '(1)'}), '([net_in[0, :, :, :3], prediction[0], net_gt[0]], axis=1)\n', (10421, 10478), True, 'import numpy as np\n')]
# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """ Preprocess data obtained for training Cora and Citeseer datasets are supported by our example, the original versions of these datasets are as follows: @inproceedings{nr, title={The Network Data Repository with Interactive Graph Analytics and Visualization}, author={<NAME> and <NAME>}, booktitle={AAAI}, url={http://networkrepository.com}, year={2015} } In this example, we use dataset splits provided by https://github.com/kimiyoung/planetoid (<NAME>, <NAME>, <NAME>, [Revisiting Semi-Supervised Learning with Graph Embeddings](https://arxiv.org/abs/1603.08861), ICML 2016). """ import numpy as np import mindspore.dataset as ds def adj_to_bias(adj): """Add self loop to adj and make sure only one hop neighbors are engaged in computing""" num_graphs = adj.shape[0] adj_temp = np.empty(adj.shape) for i in range(num_graphs): adj_temp[i] = adj[i] + np.eye(adj.shape[1]) return -1e9 * (1.0 - adj_temp) def get_biases_features_labels(data_dir): """Get biases, features, labels from Dataset""" g = ds.GraphData(data_dir) nodes = g.get_all_nodes(0) nodes_list = nodes.tolist() row_tensor = g.get_node_feature(nodes_list, [1, 2]) features = row_tensor[0] features = features[np.newaxis] labels = row_tensor[1] nodes_num = labels.shape[0] class_num = labels.max() + 1 labels_onehot = np.eye(nodes_num, class_num)[labels].astype(np.float32) neighbor = g.get_all_neighbors(nodes_list, 0) node_map = {node_id: index for index, node_id in enumerate(nodes_list)} adj = np.zeros([nodes_num, nodes_num], dtype=np.float32) for index, value in np.ndenumerate(neighbor): if value >= 0 and index[1] > 0: adj[node_map[neighbor[index[0], 0]], node_map[value]] = 1 adj = adj[np.newaxis] biases = adj_to_bias(adj) return biases, features, labels_onehot def get_mask(total, begin, end): """Generate mask according to begin and end position""" mask = np.zeros([total]).astype(np.float32) mask[begin:end] = 1 return np.array(mask, dtype=np.bool) def load_and_process(data_dir, train_node_num, eval_node_num, test_node_num): """Load cora dataset and preprocessing""" biases, feature, label = get_biases_features_labels(data_dir) # split training, validation and testing set nodes_num = label.shape[0] train_mask = get_mask(nodes_num, 0, train_node_num) eval_mask = get_mask(nodes_num, train_node_num, train_node_num + eval_node_num) test_mask = get_mask(nodes_num, nodes_num - test_node_num, nodes_num) y_train = np.zeros(label.shape) y_val = np.zeros(label.shape) y_test = np.zeros(label.shape) y_train[train_mask, :] = label[train_mask, :] y_val[eval_mask, :] = label[eval_mask, :] y_test[test_mask, :] = label[test_mask, :] y_train = y_train[np.newaxis] y_val = y_val[np.newaxis] y_test = y_test[np.newaxis] train_mask = train_mask[np.newaxis] eval_mask = eval_mask[np.newaxis] test_mask = test_mask[np.newaxis] return feature, biases, y_train, train_mask, y_val, eval_mask, y_test, test_mask
[ "numpy.ndenumerate", "numpy.empty", "numpy.zeros", "numpy.array", "numpy.eye", "mindspore.dataset.GraphData" ]
[((1483, 1502), 'numpy.empty', 'np.empty', (['adj.shape'], {}), '(adj.shape)\n', (1491, 1502), True, 'import numpy as np\n'), ((1726, 1748), 'mindspore.dataset.GraphData', 'ds.GraphData', (['data_dir'], {}), '(data_dir)\n', (1738, 1748), True, 'import mindspore.dataset as ds\n'), ((2240, 2290), 'numpy.zeros', 'np.zeros', (['[nodes_num, nodes_num]'], {'dtype': 'np.float32'}), '([nodes_num, nodes_num], dtype=np.float32)\n', (2248, 2290), True, 'import numpy as np\n'), ((2315, 2339), 'numpy.ndenumerate', 'np.ndenumerate', (['neighbor'], {}), '(neighbor)\n', (2329, 2339), True, 'import numpy as np\n'), ((2729, 2758), 'numpy.array', 'np.array', (['mask'], {'dtype': 'np.bool'}), '(mask, dtype=np.bool)\n', (2737, 2758), True, 'import numpy as np\n'), ((3260, 3281), 'numpy.zeros', 'np.zeros', (['label.shape'], {}), '(label.shape)\n', (3268, 3281), True, 'import numpy as np\n'), ((3294, 3315), 'numpy.zeros', 'np.zeros', (['label.shape'], {}), '(label.shape)\n', (3302, 3315), True, 'import numpy as np\n'), ((3329, 3350), 'numpy.zeros', 'np.zeros', (['label.shape'], {}), '(label.shape)\n', (3337, 3350), True, 'import numpy as np\n'), ((1566, 1586), 'numpy.eye', 'np.eye', (['adj.shape[1]'], {}), '(adj.shape[1])\n', (1572, 1586), True, 'import numpy as np\n'), ((2657, 2674), 'numpy.zeros', 'np.zeros', (['[total]'], {}), '([total])\n', (2665, 2674), True, 'import numpy as np\n'), ((2047, 2075), 'numpy.eye', 'np.eye', (['nodes_num', 'class_num'], {}), '(nodes_num, class_num)\n', (2053, 2075), True, 'import numpy as np\n')]
import cv2 import numpy as np o = cv2.imread(r"..\lena.jpg", cv2.IMREAD_UNCHANGED) kernel = np.ones((9, 9), np.uint8) erosion = cv2.erode(o, kernel, iterations=5) cv2.imshow("original", o) cv2.imshow("erosion", erosion) cv2.waitKey() cv2.destroyAllWindows()
[ "cv2.waitKey", "cv2.destroyAllWindows", "numpy.ones", "cv2.imread", "cv2.erode", "cv2.imshow" ]
[((35, 83), 'cv2.imread', 'cv2.imread', (['"""..\\\\lena.jpg"""', 'cv2.IMREAD_UNCHANGED'], {}), "('..\\\\lena.jpg', cv2.IMREAD_UNCHANGED)\n", (45, 83), False, 'import cv2\n'), ((93, 118), 'numpy.ones', 'np.ones', (['(9, 9)', 'np.uint8'], {}), '((9, 9), np.uint8)\n', (100, 118), True, 'import numpy as np\n'), ((129, 163), 'cv2.erode', 'cv2.erode', (['o', 'kernel'], {'iterations': '(5)'}), '(o, kernel, iterations=5)\n', (138, 163), False, 'import cv2\n'), ((164, 189), 'cv2.imshow', 'cv2.imshow', (['"""original"""', 'o'], {}), "('original', o)\n", (174, 189), False, 'import cv2\n'), ((190, 220), 'cv2.imshow', 'cv2.imshow', (['"""erosion"""', 'erosion'], {}), "('erosion', erosion)\n", (200, 220), False, 'import cv2\n'), ((221, 234), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (232, 234), False, 'import cv2\n'), ((235, 258), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (256, 258), False, 'import cv2\n')]
# # import numpy as np def read_eigenbody (filename): eigenbody = [] f_eigen = open(filename,'r') for line in f_eigen: eigenbody.append(float(line)) return np.array(eigenbody) def compose_vertices_eigenmat (eigenmat): eigenvertices = [] for i in range(0,len(eigenmat),3): eigenvertices.append([eigenmat[i],-eigenmat[i+2],eigenmat[i+1]]) return np.array(eigenvertices)
[ "numpy.array" ]
[((183, 202), 'numpy.array', 'np.array', (['eigenbody'], {}), '(eigenbody)\n', (191, 202), True, 'import numpy as np\n'), ((393, 416), 'numpy.array', 'np.array', (['eigenvertices'], {}), '(eigenvertices)\n', (401, 416), True, 'import numpy as np\n')]
import numpy as np class ReplayBuffer(object): ''' Standard FIFO Replay Buffer implementation using NumPy Arguments obs_dim - int The dimensionality of observations action_dim - int The dimension of action vectors max_size - int The maximum number of time steps of data the replay buffer can hold. Stale data is overwritten ''' def __init__(self, obs_dim, action_dim, max_size): '''Initialisation of replay buffer''' # Separate storage for each variable to track. # Stored in private attributes self._obs = np.zeros((max_size, obs_dim), dtype=np.float32) self._actions = np.zeros((max_size, action_dim), dtype=np.float32) self._next_obs = np.zeros((max_size, obs_dim), dtype=np.float32) self._rewards = np.zeros((max_size,), dtype=np.float32) self._terminals = np.zeros((max_size,), dtype=np.float32) # Track the amount of data stored in the replay buffer self._size = 0 # Track where to insert each new item self._insert_index = 0 # Keep the capacity as an attribute self.max_size = max_size def __len__(self): '''Compatibility with the built-in len function''' return self._size def add(self, obs, act, rew, next_obs, terminal): ''' Add a new time step of experience to the buffer. Arguments obs - np.array The agent's observation act - np.array The action the agent chose based on the current observation rew - float The reward received from the environment after action executed next_obs - np.array The subsequent observation terminal - float or bool The end of episode flag ''' # Store each piece of experience provided in the relevant array self._obs[self._insert_index] = obs self._actions[self._insert_index] = act self._rewards[self._insert_index] = rew self._next_obs[self._insert_index] = next_obs self._terminals[self._insert_index] = terminal # Update the size of the replay buffer self._size = min(self._size + 1, self.max_size) # Increment the insertion index modulo buffer capacity self._insert_index = (self._insert_index + 1) % self.max_size def sample(self, batch_size): ''' Sample a minibatch of experience from the replay buffer. Arguments batch_size - int The number of time steps of experience to sample Returns obs - np.array Array of size (batch_size, obs_dim) of observations actions - np.array Array of size (batch_size, action_dim) of actions rewards - np.array Array of size (batch_size, ) of reward scalars next_obs - np.array Array of size (batch_size, obs_dim) of subsequent observations terminals - np.array Array of size (batch_size, ) of termination flags ''' # First sample the indices of the experience to return indices = np.random.randint(0, self._size, size=batch_size) # Use the sampled indices to get the relevant data and return it return (self._obs[indices], self._actions[indices], self._rewards[indices], self._next_obs[indices], self._terminals[indices])
[ "numpy.random.randint", "numpy.zeros" ]
[((607, 654), 'numpy.zeros', 'np.zeros', (['(max_size, obs_dim)'], {'dtype': 'np.float32'}), '((max_size, obs_dim), dtype=np.float32)\n', (615, 654), True, 'import numpy as np\n'), ((679, 729), 'numpy.zeros', 'np.zeros', (['(max_size, action_dim)'], {'dtype': 'np.float32'}), '((max_size, action_dim), dtype=np.float32)\n', (687, 729), True, 'import numpy as np\n'), ((755, 802), 'numpy.zeros', 'np.zeros', (['(max_size, obs_dim)'], {'dtype': 'np.float32'}), '((max_size, obs_dim), dtype=np.float32)\n', (763, 802), True, 'import numpy as np\n'), ((827, 866), 'numpy.zeros', 'np.zeros', (['(max_size,)'], {'dtype': 'np.float32'}), '((max_size,), dtype=np.float32)\n', (835, 866), True, 'import numpy as np\n'), ((893, 932), 'numpy.zeros', 'np.zeros', (['(max_size,)'], {'dtype': 'np.float32'}), '((max_size,), dtype=np.float32)\n', (901, 932), True, 'import numpy as np\n'), ((3174, 3223), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self._size'], {'size': 'batch_size'}), '(0, self._size, size=batch_size)\n', (3191, 3223), True, 'import numpy as np\n')]
import numpy as np import cv2 import scipy import scipy.signal def createGaussianPyramid(im, sigma0=1, k=np.sqrt(2), levels=[-1,0,1,2,3,4]): if len(im.shape)==3: im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) if im.max()>10: im = np.float32(im)/255 im_pyramid = [] for i in levels: sigma_ = sigma0*k**i im_pyramid.append(cv2.GaussianBlur(im, (0,0), sigma_)) im_pyramid = np.stack(im_pyramid, axis=-1) return im_pyramid def displayPyramid(im_pyramid): im_pyramid = np.split(im_pyramid, im_pyramid.shape[2], axis=2) im_pyramid = np.concatenate(im_pyramid, axis=1) im_pyramid = cv2.normalize(im_pyramid, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) cv2.imshow('Pyramid of image', im_pyramid) cv2.waitKey(0) # press any key to exit cv2.destroyAllWindows() def createDoGPyramid(gaussian_pyramid, levels=[-1,0,1,2,3,4]): ''' Produces DoG Pyramid Inputs Gaussian Pyramid - A matrix of grayscale images of size [imH, imW, len(levels)] levels - the levels of the pyramid where the blur at each level is outputs DoG Pyramid - size (imH, imW, len(levels) - 1) matrix of the DoG pyramid created by differencing the Gaussian Pyramid input ''' DoG_pyramid = np.ndarray((gaussian_pyramid.shape[0], gaussian_pyramid.shape[1], gaussian_pyramid.shape[2] - 1)) for i in range(1, len(levels)): DoG_pyramid[:, :, i - 1] = (gaussian_pyramid[:, :, i] - gaussian_pyramid[:, :, i - 1]) DoG_levels = levels[1:] return DoG_pyramid, DoG_levels def computePrincipalCurvature(DoG_pyramid): ''' Takes in DoGPyramid generated in createDoGPyramid and returns PrincipalCurvature,a matrix of the same size where each point contains the curvature ratio R for the corre-sponding point in the DoG pyramid INPUTS DoG Pyramid - size (imH, imW, len(levels) - 1) matrix of the DoG pyramid OUTPUTS principal_curvature - size (imH, imW, len(levels) - 1) matrix where each point contains the curvature ratio R for the corresponding point in the DoG pyramid ''' principal_curvature = np.ndarray(DoG_pyramid.shape) for i in range(DoG_pyramid.shape[2]): DoG_image = DoG_pyramid[:, :, i] dxx = cv2.Sobel(DoG_image, ddepth=-1, dx=2, dy=0) dxy = cv2.Sobel(DoG_image, ddepth=-1, dx=1, dy=1) dyy = cv2.Sobel(DoG_image, ddepth=-1, dx=0, dy=2) principal_curvature[:, :, i] = (((dxx + dyy) ** 2) / (dxx * dyy - dxy * dxy)) return principal_curvature def getLocalExtrema(DoG_pyramid, DoG_levels, principal_curvature, th_contrast=0.03, th_r=12): ''' Returns local extrema points in both scale and space using the DoGPyramid INPUTS DoG_pyramid - size (imH, imW, len(levels) - 1) matrix of the DoG pyramid DoG_levels - The levels of the pyramid where the blur at each level is outputs principal_curvature - size (imH, imW, len(levels) - 1) matrix contains the curvature ratio R th_contrast - remove any point that is a local extremum but does not have a DoG response magnitude above this threshold th_r - remove any edge-like points that have too large a principal curvature ratio OUTPUTS locsDoG - N x 3 matrix where the DoG pyramid achieves a local extrema in both scale and space, and also satisfies the two thresholds. ''' # filter based on 8 spatial and 2 level neighbors: # x == 0 or x == imH or y == 0 or y == imW or # principal_curvature[x][y][level] < th_r or # abs(DoG_pyramid[x][y][level]) > th_contrast # If missing spatial neighbors, mark as invalid local extremum matches = (principal_curvature < th_r) & (abs(DoG_pyramid) > th_contrast) matches[0, :, :] = False matches[DoG_pyramid.shape[0] - 1, :, :] = False matches[:, 0, :] = False matches[:, DoG_pyramid.shape[1] - 1, :] = False locsDoG = np.argwhere(matches) locsDoG_final = [] # Filter out based on neighbors for loc in locsDoG: x, y, level = loc loc_value = DoG_pyramid[x][y][level] # Get neighborhood neighborhood = DoG_pyramid[x - 1:x + 2, y - 1:y + 2, level].reshape((9)) if level > 0: neighborhood = np.append(neighborhood, DoG_pyramid[x][y][level - 1]) if level < DoG_pyramid.shape[2] - 1: neighborhood = np.append(neighborhood, DoG_pyramid[x][y][level + 1]) if (neighborhood.max() == loc_value or neighborhood.min() == loc_value): # Swap coordinates locsDoG_final.append([loc[1], loc[0], loc[2]]) locsDoG_final = np.asarray(locsDoG_final) return locsDoG_final def DoGdetector(im, sigma0=1, k=np.sqrt(2), levels=[-1,0,1,2,3,4], th_contrast=0.03, th_r=12): ''' Putting it all together Inputs Description -------------------------------------------------------------------------- im Grayscale image with range [0,1]. sigma0 Scale of the 0th image pyramid. k Pyramid Factor. Suggest sqrt(2). levels Levels of pyramid to construct. Suggest -1:4. th_contrast DoG contrast threshold. Suggest 0.03. th_r Principal Ratio threshold. Suggest 12. Outputs Description -------------------------------------------------------------------------- locsDoG N x 3 matrix where the DoG pyramid achieves a local extrema in both scale and space, and satisfies the two thresholds. gauss_pyramid A matrix of grayscale images of size (imH,imW,len(levels)) ''' gauss_pyramid = createGaussianPyramid(im, sigma0=sigma0, k=k, levels=levels) DoG_pyramid, DoG_levels = createDoGPyramid(gauss_pyramid, levels=levels) principal_curvature = computePrincipalCurvature(DoG_pyramid) locsDoG = getLocalExtrema(DoG_pyramid, DoG_levels, principal_curvature, th_contrast=th_contrast, th_r=th_r) return locsDoG, gauss_pyramid if __name__ == '__main__': # test gaussian pyramid levels = [-1,0,1,2,3,4] im = cv2.imread('../data/model_chickenbroth.jpg') im_pyr = createGaussianPyramid(im) displayPyramid(im_pyr) # test DoG pyramid DoG_pyr, DoG_levels = createDoGPyramid(im_pyr, levels) displayPyramid(DoG_pyr) # test compute principal curvature pc_curvature = computePrincipalCurvature(DoG_pyr) displayPyramid(pc_curvature) # test get local extrema th_contrast = 0.03 th_r = 12 locsDoG = getLocalExtrema(DoG_pyr, DoG_levels, pc_curvature, th_contrast, th_r) # test DoG detector locsDoG, gaussian_pyramid = DoGdetector(im) # im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) for loc in locsDoG: cv2.circle(im, (loc[0], loc[1]), 1, (0, 255, 0), -1) cv2.imshow('Keypoint Detector', im) cv2.waitKey(0) # press any key to exit cv2.destroyAllWindows()
[ "numpy.stack", "cv2.GaussianBlur", "cv2.circle", "cv2.waitKey", "cv2.destroyAllWindows", "numpy.asarray", "cv2.cvtColor", "numpy.float32", "numpy.split", "numpy.argwhere", "cv2.imread", "numpy.append", "cv2.normalize", "cv2.imshow", "numpy.ndarray", "cv2.Sobel", "numpy.concatenate", ...
[((106, 116), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (113, 116), True, 'import numpy as np\n'), ((419, 448), 'numpy.stack', 'np.stack', (['im_pyramid'], {'axis': '(-1)'}), '(im_pyramid, axis=-1)\n', (427, 448), True, 'import numpy as np\n'), ((521, 570), 'numpy.split', 'np.split', (['im_pyramid', 'im_pyramid.shape[2]'], {'axis': '(2)'}), '(im_pyramid, im_pyramid.shape[2], axis=2)\n', (529, 570), True, 'import numpy as np\n'), ((588, 622), 'numpy.concatenate', 'np.concatenate', (['im_pyramid'], {'axis': '(1)'}), '(im_pyramid, axis=1)\n', (602, 622), True, 'import numpy as np\n'), ((640, 737), 'cv2.normalize', 'cv2.normalize', (['im_pyramid', 'None'], {'alpha': '(0)', 'beta': '(1)', 'norm_type': 'cv2.NORM_MINMAX', 'dtype': 'cv2.CV_32F'}), '(im_pyramid, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX,\n dtype=cv2.CV_32F)\n', (653, 737), False, 'import cv2\n'), ((738, 780), 'cv2.imshow', 'cv2.imshow', (['"""Pyramid of image"""', 'im_pyramid'], {}), "('Pyramid of image', im_pyramid)\n", (748, 780), False, 'import cv2\n'), ((785, 799), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (796, 799), False, 'import cv2\n'), ((828, 851), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (849, 851), False, 'import cv2\n'), ((1344, 1446), 'numpy.ndarray', 'np.ndarray', (['(gaussian_pyramid.shape[0], gaussian_pyramid.shape[1], gaussian_pyramid.\n shape[2] - 1)'], {}), '((gaussian_pyramid.shape[0], gaussian_pyramid.shape[1], \n gaussian_pyramid.shape[2] - 1))\n', (1354, 1446), True, 'import numpy as np\n'), ((2262, 2291), 'numpy.ndarray', 'np.ndarray', (['DoG_pyramid.shape'], {}), '(DoG_pyramid.shape)\n', (2272, 2291), True, 'import numpy as np\n'), ((4155, 4175), 'numpy.argwhere', 'np.argwhere', (['matches'], {}), '(matches)\n', (4166, 4175), True, 'import numpy as np\n'), ((4858, 4883), 'numpy.asarray', 'np.asarray', (['locsDoG_final'], {}), '(locsDoG_final)\n', (4868, 4883), True, 'import numpy as np\n'), ((4943, 4953), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (4950, 4953), True, 'import numpy as np\n'), ((6327, 6371), 'cv2.imread', 'cv2.imread', (['"""../data/model_chickenbroth.jpg"""'], {}), "('../data/model_chickenbroth.jpg')\n", (6337, 6371), False, 'import cv2\n'), ((7033, 7068), 'cv2.imshow', 'cv2.imshow', (['"""Keypoint Detector"""', 'im'], {}), "('Keypoint Detector', im)\n", (7043, 7068), False, 'import cv2\n'), ((7073, 7087), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (7084, 7087), False, 'import cv2\n'), ((7116, 7139), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7137, 7139), False, 'import cv2\n'), ((180, 216), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GRAY'], {}), '(im, cv2.COLOR_BGR2GRAY)\n', (192, 216), False, 'import cv2\n'), ((2389, 2432), 'cv2.Sobel', 'cv2.Sobel', (['DoG_image'], {'ddepth': '(-1)', 'dx': '(2)', 'dy': '(0)'}), '(DoG_image, ddepth=-1, dx=2, dy=0)\n', (2398, 2432), False, 'import cv2\n'), ((2447, 2490), 'cv2.Sobel', 'cv2.Sobel', (['DoG_image'], {'ddepth': '(-1)', 'dx': '(1)', 'dy': '(1)'}), '(DoG_image, ddepth=-1, dx=1, dy=1)\n', (2456, 2490), False, 'import cv2\n'), ((2505, 2548), 'cv2.Sobel', 'cv2.Sobel', (['DoG_image'], {'ddepth': '(-1)', 'dx': '(0)', 'dy': '(2)'}), '(DoG_image, ddepth=-1, dx=0, dy=2)\n', (2514, 2548), False, 'import cv2\n'), ((6976, 7028), 'cv2.circle', 'cv2.circle', (['im', '(loc[0], loc[1])', '(1)', '(0, 255, 0)', '(-1)'], {}), '(im, (loc[0], loc[1]), 1, (0, 255, 0), -1)\n', (6986, 7028), False, 'import cv2\n'), ((250, 264), 'numpy.float32', 'np.float32', (['im'], {}), '(im)\n', (260, 264), True, 'import numpy as np\n'), ((365, 401), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['im', '(0, 0)', 'sigma_'], {}), '(im, (0, 0), sigma_)\n', (381, 401), False, 'import cv2\n'), ((4487, 4540), 'numpy.append', 'np.append', (['neighborhood', 'DoG_pyramid[x][y][level - 1]'], {}), '(neighborhood, DoG_pyramid[x][y][level - 1])\n', (4496, 4540), True, 'import numpy as np\n'), ((4613, 4666), 'numpy.append', 'np.append', (['neighborhood', 'DoG_pyramid[x][y][level + 1]'], {}), '(neighborhood, DoG_pyramid[x][y][level + 1])\n', (4622, 4666), True, 'import numpy as np\n')]
""" Providing an abstraction of input block for pwscf in control of ATOMIC_SPECIES, ATOMIC_POSITIONS, KPOINTS, CELL_PARAMETERS, CONSTRAINTS, OCCUPATIONS, ATOMIC_FORCES """ import numpy as np import os import sys import re import pymatflow.base as base from pymatflow.base.xyz import BaseXyz from pymatflow.qe.group import QeVariableGroup from . import qe_variable_to_string """ usage: """ class QePseudo: def __init__(self): self.dir = os.path.abspath("./") # default dir to put pseudo files def to_in(self, fout, xyz): fout.write(self.to_string(xyz)) def to_string(self, xyz): out = "" out += "ATOMIC_SPECIES\n" all_file = os.listdir(self.dir) for element in xyz.specie_labels: for item in all_file: if re.match("(%s)(.*)(upf)" % (element), item, re.IGNORECASE): out += "%s %f %s\n" % (element, base.element[element].mass, item) break return out class QeArts(QeVariableGroup): """ an abstraction of part of input block for pwscf """ def __init__(self): super().__init__() self.xyz = BaseXyz() self.pseudo = QePseudo() self.cell_params = { "cell_dynamics": None, "press": None, "wmass": None, "cell_factor": None, "press_conv_thr": None, "cell_dofree": None, } self.kpoints_option = "automatic" self.kpoints_mp = [1, 1, 1, 0, 0, 0] self.ifstatic = True # used to determine how to put atomic coordinates to input file self.atomic_forces_status = False # default is no force acting on system def to_in(self, fout, coordtype="angstrom"): """ :param fout: a file stream for writing :param coordtype: specify coordinate format, can eigher be 'angstrom' or 'crystal' """ fout.write(self.to_string(coordtype=coordtype)) def to_string(self, coordtype="angstrom"): out = "" out += self.pseudo.to_string(xyz=self.xyz) out += "\n" cell = self.xyz.cell out += "CELL_PARAMETERS angstrom\n" #fout.write("%.9f %.9f %.9f\n" % (cell[0], cell[1], cell[2])) #fout.write("%.9f %.9f %.9f\n" % (cell[3], cell[4], cell[5])) #fout.write("%.9f %.9f %.9f\n" % (cell[6], cell[7], cell[8])) for i in range(3): out += "%.9f %.9f %.9f\n" % (cell[i][0], cell[i][1], cell[i][2]) out += "\n" if coordtype == "angstrom": out += "ATOMIC_POSITIONS angstrom\n" if self.ifstatic == True: for atom in self.xyz.atoms: out += "%s\t%.9f\t%.9f\t%.9f\n" % (atom.name, atom.x, atom.y, atom.z) elif self.ifstatic == False: for atom in self.xyz.atoms: out += "%s\t%.9f\t%.9f\t%.9f" % (atom.name, atom.x, atom.y, atom.z) for fix in atom.fix: if fix == True: out += "\t0" elif fix == False: out += "\t1" out += "\n" else: print("===============================================\n") print("warning: qe.base.arts.to_in():\n") print("arts.ifstatic could only be True or False\n") sys.exit(1) out += "\n" elif coordtype == "crystal": # crystal namely fractional coordinate can be convert from cartesian coordinates # the conversion process is like transformation of presentation in quantum mechanics # the convmat is bulid to do the conversion #latcell = np.array(self.xyz.cell) #latcell = latcell.reshape(3, 3) latcell = np.array(self.xyz.cell) convmat = np.linalg.inv(latcell.T) crystal_coord = np.zeros([self.xyz.natom, 3]) for i in range(self.xyz.natom): crystal_coord[i] = convmat.dot(np.array([self.xyz.atoms[i].x, self.xyz.atoms[i].y, self.xyz.atoms[i].z])) # out += "ATOMIC_POSITIONS crystal\n" if self.ifstatic == True: for k in range(self.xyz.natom): out += "%s\t%.9f\t%.9f\t%.9f\n" % (self.xyz.atoms[k].name, crystal_coord[k, 0], crystal_coord[k, 1], crystal_coord[k, 2]) elif self.ifstatic == False: for k in range(self.xyz.natom): out += "%s\t%.9f\t%.9f\t%.9f" % (self.xyz.atoms[k].name, crystal_coord[k, 0], crystal_coord[k, 1], crystal_coord[k, 2]) for fix in self.xyz.atoms[k].fix: if fix == True: out += "\t0" elif fix == False: out += "\t1" out += "\n" else: print("===============================================\n") print("warning: qe.base.arts.to_in():\n") print("arts.ifstatic could only be True or False\n") sys.exit(1) out += "\n" # end crystal type ATOMIC_POSITIONS # writing KPOINTS to the fout out += self.to_string_kpoints() # ========================= # # writing forces act on atoms if self.atomic_forces_status == True: out += self.to_string_atomic_forces() # ========================= return out def write_kpoints(self, fout): """ :param fout: a file stream for writing """ fout.write(self.to_string_kpionts()) def to_string_kpoints(self): out = "" if self.kpoints_option == "automatic": out += "K_POINTS %s\n" % self.kpoints_option out += "%d %d %d %d %d %d\n" % ( self.kpoints_mp[0], self.kpoints_mp[1], self.kpoints_mp[2], self.kpoints_mp[3], self.kpoints_mp[4], self.kpoints_mp[5] ) elif self.kpoints_option == "gamma": out += "K_POINTS gamma\n" elif self.kpoints_option == "crystal_b": # there is a trick: # when self.crystal_b[i][4] == "|" # we set the number of k point to connect to the next high symmetry kpoint to 0 # then after the pw.x calculation and bands.x calculation, we can see from the # output of bands.x, the two nieghbor high symmetry kpoints # have the same x coordinates, and that can be processed by qe.post.bands and # the corresponding post-qe-bands.py, and the label in the processed band strucutre # image would be in format of 'label|label', for example 'K|U' # this is very fantastic !!! out += "K_POINTS %s\n" % self.kpoints_option out += "%d\n" % len(self.crystal_b) for i in range(len(self.crystal_b)): out += "%f %f %f %d #%s\n" % ( self.crystal_b[i][0], self.crystal_b[i][1], self.crystal_b[i][2], self.crystal_b[i][4] if self.crystal_b[i][4] != "|" else 0, # 0 is for the disconnected k point self.crystal_b[i][3], ) elif self.kpoints_option == "tpiba_b": pass return out def set_kpoints(self, kpoints_mp=[1, 1, 1, 0, 0, 0], option="automatic", crystal_b=None): """ :param crystal_b: the high symmetry k point path used in bands structure calculation in format like this: [[kx, ky, kz, label, connect_indicator], ...] like [[0.0, 0.0, 0.0, 'GAMMA', 15], ...] if connect_indicator in a kpoint is an integer, then it will connect to the following point through the number of kpoints defined by connect_indicator. if connect_indicator in a kpoint is '|', then it will not connect to the following point, TODO: Note: "automatic" was controlled by kpoints_mp "gamma" was also handled internally "crystal_b" as controlled by crystal_b """ if option == "automatic": self.kpoints_option = option self.kpoints_mp = kpoints_mp return if option == "gamma": self.kpoints_option = option return if option == "crystal_b": self.kpoints_option = option self.crystal_b = crystal_b return def write_atomic_forces(self, fout): fout.write(self.to_string_atomic_forces) def to_string_atomic_forces(self): out = "" out += "ATOMIC_FORCES\n" for i in range(len(self.xyz.atoms)): out += "%s\t%.9f\t%.9f\t%.9f\n" % (self.xyz.atoms[i].name, self.atomic_forces[i][0], self.atomic_forces[i][1] , self.atomic_forces[i][2]) out += '\n' return out def set_atomic_forces(self, pressure=None, direction=None): """set ATOMIC_FORCES :param pressure: in unit of Pa :param direction: x | y | z Note: currently only support unidirectional forces acting on all atoms of the cubic system. and the user provide pressure and direction of force, this function will calculate the corresponding force accordign to the cell. """ if pressure == None or direction == None: self.atomic_forces_status = False return else: self.atomic_forces_status = True if direction == "x": area = np.sqrt(self.xyz.cell[1][0]**2 + self.xyz.cell[1][1]**2 + self.xyz.cell[1][2]**2) * np.sqrt(self.xyz.cell[2][0]**2 + self.xyz.cell[2][1]**2 + self.xyz.cell[2][2]**2) # in unit of Anstrom^2 # 1 Hartree/Bohr = 8.238 7225(14)×10^8 N # 1 Ry/Bohr = 4.119358925x10^8 N # force is in unit of Ry/a.u. force = area * 1.0e-20 * pressure / (4.119358925e8) self.atomic_forces = np.zeros((len(self.xyz.atoms), 3)) self.atomic_forces[:, 0] = force def basic_setting(self, ifstatic=True): self.ifstatic = ifstatic #
[ "os.path.abspath", "numpy.zeros", "re.match", "numpy.array", "numpy.linalg.inv", "pymatflow.base.xyz.BaseXyz", "os.listdir", "sys.exit", "numpy.sqrt" ]
[((473, 494), 'os.path.abspath', 'os.path.abspath', (['"""./"""'], {}), "('./')\n", (488, 494), False, 'import os\n'), ((711, 731), 'os.listdir', 'os.listdir', (['self.dir'], {}), '(self.dir)\n', (721, 731), False, 'import os\n'), ((1206, 1215), 'pymatflow.base.xyz.BaseXyz', 'BaseXyz', ([], {}), '()\n', (1213, 1215), False, 'from pymatflow.base.xyz import BaseXyz\n'), ((830, 886), 're.match', 're.match', (["('(%s)(.*)(upf)' % element)", 'item', 're.IGNORECASE'], {}), "('(%s)(.*)(upf)' % element, item, re.IGNORECASE)\n", (838, 886), False, 'import re\n'), ((3986, 4009), 'numpy.array', 'np.array', (['self.xyz.cell'], {}), '(self.xyz.cell)\n', (3994, 4009), True, 'import numpy as np\n'), ((4033, 4057), 'numpy.linalg.inv', 'np.linalg.inv', (['latcell.T'], {}), '(latcell.T)\n', (4046, 4057), True, 'import numpy as np\n'), ((4087, 4116), 'numpy.zeros', 'np.zeros', (['[self.xyz.natom, 3]'], {}), '([self.xyz.natom, 3])\n', (4095, 4116), True, 'import numpy as np\n'), ((10050, 10142), 'numpy.sqrt', 'np.sqrt', (['(self.xyz.cell[1][0] ** 2 + self.xyz.cell[1][1] ** 2 + self.xyz.cell[1][2] ** 2\n )'], {}), '(self.xyz.cell[1][0] ** 2 + self.xyz.cell[1][1] ** 2 + self.xyz.cell\n [1][2] ** 2)\n', (10057, 10142), True, 'import numpy as np\n'), ((10134, 10226), 'numpy.sqrt', 'np.sqrt', (['(self.xyz.cell[2][0] ** 2 + self.xyz.cell[2][1] ** 2 + self.xyz.cell[2][2] ** 2\n )'], {}), '(self.xyz.cell[2][0] ** 2 + self.xyz.cell[2][1] ** 2 + self.xyz.cell\n [2][2] ** 2)\n', (10141, 10226), True, 'import numpy as np\n'), ((3545, 3556), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3553, 3556), False, 'import sys\n'), ((4210, 4283), 'numpy.array', 'np.array', (['[self.xyz.atoms[i].x, self.xyz.atoms[i].y, self.xyz.atoms[i].z]'], {}), '([self.xyz.atoms[i].x, self.xyz.atoms[i].y, self.xyz.atoms[i].z])\n', (4218, 4283), True, 'import numpy as np\n'), ((5310, 5321), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5318, 5321), False, 'import sys\n')]
import numpy as np import pandas as pd import staircase as sc def _not_arithmetic_op(series_op): return series_op not in ( pd.Series.add, pd.Series.sub, pd.Series.mul, pd.Series.div, ) def _reindex_deltas(new_index, deltas, initial_value): mask = deltas.where(np.isnan(deltas.values), 0) deltas_reindexed = deltas.reindex(new_index, fill_value=0) mask_initial_value = np.nan if np.isnan(initial_value) else 0 mask_reindexed = _reindex_values(new_index, mask, mask_initial_value) return deltas_reindexed + mask_reindexed def _reindex_values(new_index, values, initial_value): """ Conform values to new index Parameters ---------- new_index : pandas.Index values : pandas.Series initial_value : float Returns ------- pandas.Series """ first_step = values.index[0] new_values = values.reindex(new_index, method="ffill") new_values.loc[new_values.index < first_step] = initial_value return new_values def _combine_step_series( series_1, series_2, initial_value_1, initial_value_2, series_op, kind ): # kind = "values" or "deltas" new_index = series_1.index.union(series_2.index) reindex_method = _reindex_values if kind == "values" else _reindex_deltas reindexed_series_1 = reindex_method(new_index, series_1, initial_value_1) reindexed_series_2 = reindex_method(new_index, series_2, initial_value_2) new_series = series_op( reindexed_series_1, reindexed_series_2, ).astype(float) if series_op == pd.Series.divide: new_series.replace(np.inf, np.nan, inplace=True) return new_series def _combine_stairs_via_values(stairs1, stairs2, series_op, float_op): # self.values and other._values should be able to be created values = _combine_step_series( stairs1._get_values(), stairs2._get_values(), stairs1.initial_value, stairs2.initial_value, series_op, "values", ) requires_manual_masking = _not_arithmetic_op(series_op) if requires_manual_masking and (stairs1._has_na() or stairs2._has_na()): mask = _combine_step_series( stairs1._get_values().isnull(), stairs2._get_values().isnull(), np.isnan(stairs1.initial_value), np.isnan(stairs2.initial_value), np.logical_or, "values", ).astype(bool) values.loc[mask] = np.nan if requires_manual_masking and ( np.isnan(stairs1.initial_value) or np.isnan(stairs2.initial_value) ): initial_value = np.nan elif series_op == pd.Series.divide and stairs2.initial_value == 0: initial_value = np.nan else: initial_value = float_op(stairs1.initial_value, stairs2.initial_value) * 1 if series_op == pd.Series.divide: values = values.replace(np.inf, np.nan).replace(-np.inf, np.nan) new_instance = sc.Stairs._new( initial_value=initial_value, data=pd.DataFrame({"value": values}), ) new_instance._remove_redundant_step_points() return new_instance
[ "pandas.DataFrame", "numpy.isnan" ]
[((309, 332), 'numpy.isnan', 'np.isnan', (['deltas.values'], {}), '(deltas.values)\n', (317, 332), True, 'import numpy as np\n'), ((435, 458), 'numpy.isnan', 'np.isnan', (['initial_value'], {}), '(initial_value)\n', (443, 458), True, 'import numpy as np\n'), ((2523, 2554), 'numpy.isnan', 'np.isnan', (['stairs1.initial_value'], {}), '(stairs1.initial_value)\n', (2531, 2554), True, 'import numpy as np\n'), ((2558, 2589), 'numpy.isnan', 'np.isnan', (['stairs2.initial_value'], {}), '(stairs2.initial_value)\n', (2566, 2589), True, 'import numpy as np\n'), ((3021, 3052), 'pandas.DataFrame', 'pd.DataFrame', (["{'value': values}"], {}), "({'value': values})\n", (3033, 3052), True, 'import pandas as pd\n'), ((2293, 2324), 'numpy.isnan', 'np.isnan', (['stairs1.initial_value'], {}), '(stairs1.initial_value)\n', (2301, 2324), True, 'import numpy as np\n'), ((2338, 2369), 'numpy.isnan', 'np.isnan', (['stairs2.initial_value'], {}), '(stairs2.initial_value)\n', (2346, 2369), True, 'import numpy as np\n')]
""" '########:'##::::'##::::'##::: ##.....::. ##::'##:::'####::: ##::::::::. ##'##::::.. ##::: ######:::::. ###::::::: ##::: ##...:::::: ## ##:::::: ##::: ##:::::::: ##:. ##::::: ##::: ########: ##:::. ##::'######: ........::..:::::..:::......:: """ from typing import List import cv2 import numpy as np import matplotlib.pyplot as plt LOAD_GRAY_SCALE = 1 LOAD_RGB = 2 NUM_OF_PIXELS_255 = 255 NUM_OF_PIXELS_256 = 256 EPSILON = 0.001 MY_ID = 12345789 def myID() -> np.int: """ Return my ID (not the friend's ID I copied from) :return: int """ return MY_ID def normalize_image(img): return (img - np.min(img)) / (np.max(img) - np.min(img)) def imReadAndConvert(filename: str, representation: int) -> np.ndarray: """ Reads an image, and returns the image converted as requested :param filename: The path to the image :param representation: GRAY_SCALE or RGB :return: The image object """ if representation == LOAD_GRAY_SCALE: img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) return normalize_image(img=img) elif representation == LOAD_RGB: img = cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2RGB) return normalize_image(img=img) def imDisplay(filename: str, representation: int): """ Reads an image as RGB or GRAY_SCALE and displays it :param filename: The path to the image :param representation: GRAY_SCALE or RGB :return: None """ img = imReadAndConvert(filename, representation) if representation == LOAD_GRAY_SCALE: plt.imshow(img, cmap='gray') else: plt.imshow(img) plt.show() def split_to_channels(img: np.ndarray): return img[:, :, 0], img[:, :, 1], img[:, :, 2] def assign_channels(img: np.ndarray, x: int, y: int, z: int): img[:, :, 0], img[:, :, 1], img[:, :, 2] = x, y, z def transformRGB2YIQ(imgRGB: np.ndarray) -> np.ndarray: """ Converts an RGB image to YIQ color space :param imgRGB: An Image in RGB :return: A YIQ in image color space """ imgRGB = normalize_image(imgRGB) r, g, b = split_to_channels(imgRGB) y, i, q = r * 0.299 + g * 0.587 + b * 0.114, r * 0.596 + g * -0.275 + b * -0.321, r * 0.212 + g * -0.523 + b * 0.311 yiq_img = imgRGB assign_channels(yiq_img, y, i, q) return normalize_image(yiq_img) def transformYIQ2RGB(imgYIQ: np.ndarray) -> np.ndarray: """ Converts an YIQ image to RGB color space :param imgYIQ: An Image in YIQ :return: A RGB in image color space """ imgYIQ = normalize_image(imgYIQ) y, i, q = split_to_channels(imgYIQ) r, g, b = y + i * 0.956 + q * 0.619, y + i * -0.272 + q * -0.647, y + i * -1.106 + q * 1.703 r, g, b = normalize_image(r), normalize_image(g), normalize_image(b) rgb_img = imgYIQ assign_channels(rgb_img, r, g, b) return rgb_img def hsitogram_norm(norm_255, num_of_pixels): hist_origin, edges = np.histogram(norm_255, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256]) cum_sum_origin = np.cumsum(hist_origin) return np.ceil(cum_sum_origin * NUM_OF_PIXELS_255 / num_of_pixels), hist_origin def hsitogramEqualize(imgOrig: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray): """ Equalizes the histogram of an image :param imgOrig: Original Histogram :return """ num_of_pixels = imgOrig.shape[0] * imgOrig.shape[1] if len(imgOrig.shape) == 2: norm_255 = normalize_image(imgOrig) * NUM_OF_PIXELS_255 lut, hist_origin = hsitogram_norm(norm_255, num_of_pixels) img_eq = norm_255 for i in range(imgOrig.shape[0]): for j in range(imgOrig.shape[1]): img_eq[i][j] = lut[int(norm_255[i][j])] hist_eq, edges = np.histogram(img_eq, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256]) return normalize_image(img_eq), hist_origin, hist_eq else: yiq = transformRGB2YIQ(imgOrig) norm_255 = normalize_image(yiq[:, :, 0]) * NUM_OF_PIXELS_255 lut, hist_origin = hsitogram_norm(norm_255, num_of_pixels) norm_255_new = norm_255 for i in range(imgOrig.shape[0]): for j in range(imgOrig.shape[1]): norm_255_new[i][j] = lut[int(norm_255[i][j])] hist_eq, edges = np.histogram(norm_255_new, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256]) yiq[:, :, 0] = normalize_image(norm_255_new) img_eq = normalize_image(transformYIQ2RGB(yiq)) return img_eq, hist_origin, hist_eq def next_z(z, q): i = 0 while i < len(q) - 1: z[i + 1] = (q[i] + q[i + 1]) / 2 i += 1 return z def find_new_q(z, q, hist, num_pixel): ans, new_q, t = 1, q, 0 i = 0 while i < len(z) - 1: res1 = res2 = 0 j = z[i] while j < z[i + 1]: res1 += hist[j] / num_pixel * j res2 += hist[j] / num_pixel j += 1 if res2 != 0: qi = int(res1 / res2) q[t] = qi t += 1 else: return q, 0 i += 1 return np.ceil(new_q), ans def new_pic(imOrig255, nQuant, z, q): shape, new_img = imOrig255.shape, imOrig255 for i in range(shape[0]): for j in range(shape[1]): x = int(imOrig255[i][j]) for t in range(nQuant): if z[t] <= x <= z[t + 1]: new_img[i][j] = q[t] return new_img def calc_mse(nQuant, z, q, hist, pixel_num): mse = i = 0 while i < nQuant: temp_mse = 0 j = z[i] while j < z[i + 1]: temp_mse += (q[i] - j) * (q[i] - j) * hist[j] / pixel_num j += 1 mse += temp_mse i += 1 return mse def origin_z(pixel_num, nQuant, cumsum, z): temp_bound = pixel_num / nQuant bound = temp_bound t, i = 1, 0 while i < NUM_OF_PIXELS_256: if cumsum[i] >= bound: z[t] = i t += 1 bound = bound + temp_bound i += 1 return z.astype(int) def quantizeImage(imOrig: np.ndarray, nQuant: int, nIter: int) -> (List[np.ndarray], List[float]): """ Quantized an image in to **nQuant** colors :param imOrig: The original image (RGB or Gray scale) :param nQuant: Number of colors to quantize the image to :param nIter: Number of optimization loops :return: (List[qImage_i],List[error_i]) """ z, q = np.zeros(nQuant + 1), np.zeros(nQuant) list_of_pic, list_of_mse = [], [] pixel_num = imOrig.shape[0] * imOrig.shape[1] if len(imOrig.shape) == 2: imOrig255 = normalize_image(imOrig) * NUM_OF_PIXELS_255 hist, edges = np.histogram(imOrig255, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256]) cum_sum = np.cumsum(hist) z = origin_z(pixel_num, nQuant, cum_sum, z) q, ans = find_new_q(z, q, hist, pixel_num) new_img = new_pic(imOrig255, nQuant, z, q) list_of_pic.append(new_img) temp_mse = calc_mse(nQuant, z, q, hist, pixel_num) list_of_mse.append(temp_mse) old_mse, old_q = temp_mse, q for k in range(1, nIter): z = next_z(z, q) q, ans = find_new_q(z, q, hist, pixel_num) if np.array_equal(q, old_q) and ans == 0: break new_img = new_pic(imOrig255, nQuant, z, q) mse = calc_mse(nQuant, z, q, hist, pixel_num) if abs(old_mse - mse) < EPSILON or mse > old_mse: break list_of_mse.append(mse) list_of_pic.append(new_img) old_mse, old_q = mse, q return list_of_pic, list_of_mse else: yiq = transformRGB2YIQ(imOrig) y = yiq[:, :, 0] y255 = normalize_image(y) * NUM_OF_PIXELS_255 hist, edges = np.histogram(y255, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256]) cum_sum = np.cumsum(hist) z = origin_z(pixel_num, nQuant, cum_sum, z) q, ans = find_new_q(z, q, hist, pixel_num) new_img = new_pic(y255, nQuant, z, q) yiq[:, :, 0] = normalize_image(new_img) new_image = normalize_image(transformYIQ2RGB(yiq)) temp_mse = calc_mse(nQuant, z, q, hist, pixel_num) list_of_pic.append(new_image) list_of_mse.append(temp_mse) old_mse, old_img, old_q = temp_mse, new_img, q i = 1 while i < nIter: z = next_z(z, q) q, ans = find_new_q(z, q, hist, pixel_num) if np.array_equal(q, old_q) and ans == 0: break new_img = new_pic(y255, nQuant, z, q) mse = calc_mse(nQuant, z, q, hist, pixel_num) if abs(old_mse - mse) < EPSILON: break if mse > old_mse: new_img = old_img print("mse got bigger") break list_of_mse.append(mse) yiq[:, :, 0] = normalize_image(new_img) new_image = normalize_image(transformYIQ2RGB(yiq)) list_of_pic.append(new_image) old_mse, old_img, old_q = mse, new_img, q i += 1 return list_of_pic, list_of_mse
[ "matplotlib.pyplot.show", "numpy.ceil", "matplotlib.pyplot.imshow", "numpy.zeros", "numpy.cumsum", "numpy.histogram", "cv2.imread", "numpy.min", "numpy.max", "numpy.array_equal" ]
[((1696, 1706), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1704, 1706), True, 'import matplotlib.pyplot as plt\n'), ((2999, 3064), 'numpy.histogram', 'np.histogram', (['norm_255', 'NUM_OF_PIXELS_256', '[0, NUM_OF_PIXELS_256]'], {}), '(norm_255, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256])\n', (3011, 3064), True, 'import numpy as np\n'), ((3086, 3108), 'numpy.cumsum', 'np.cumsum', (['hist_origin'], {}), '(hist_origin)\n', (3095, 3108), True, 'import numpy as np\n'), ((1066, 1108), 'cv2.imread', 'cv2.imread', (['filename', 'cv2.IMREAD_GRAYSCALE'], {}), '(filename, cv2.IMREAD_GRAYSCALE)\n', (1076, 1108), False, 'import cv2\n'), ((1629, 1657), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (1639, 1657), True, 'import matplotlib.pyplot as plt\n'), ((1676, 1691), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (1686, 1691), True, 'import matplotlib.pyplot as plt\n'), ((3120, 3179), 'numpy.ceil', 'np.ceil', (['(cum_sum_origin * NUM_OF_PIXELS_255 / num_of_pixels)'], {}), '(cum_sum_origin * NUM_OF_PIXELS_255 / num_of_pixels)\n', (3127, 3179), True, 'import numpy as np\n'), ((3801, 3864), 'numpy.histogram', 'np.histogram', (['img_eq', 'NUM_OF_PIXELS_256', '[0, NUM_OF_PIXELS_256]'], {}), '(img_eq, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256])\n', (3813, 3864), True, 'import numpy as np\n'), ((4320, 4389), 'numpy.histogram', 'np.histogram', (['norm_255_new', 'NUM_OF_PIXELS_256', '[0, NUM_OF_PIXELS_256]'], {}), '(norm_255_new, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256])\n', (4332, 4389), True, 'import numpy as np\n'), ((5107, 5121), 'numpy.ceil', 'np.ceil', (['new_q'], {}), '(new_q)\n', (5114, 5121), True, 'import numpy as np\n'), ((6457, 6477), 'numpy.zeros', 'np.zeros', (['(nQuant + 1)'], {}), '(nQuant + 1)\n', (6465, 6477), True, 'import numpy as np\n'), ((6479, 6495), 'numpy.zeros', 'np.zeros', (['nQuant'], {}), '(nQuant)\n', (6487, 6495), True, 'import numpy as np\n'), ((6702, 6768), 'numpy.histogram', 'np.histogram', (['imOrig255', 'NUM_OF_PIXELS_256', '[0, NUM_OF_PIXELS_256]'], {}), '(imOrig255, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256])\n', (6714, 6768), True, 'import numpy as np\n'), ((6788, 6803), 'numpy.cumsum', 'np.cumsum', (['hist'], {}), '(hist)\n', (6797, 6803), True, 'import numpy as np\n'), ((7825, 7886), 'numpy.histogram', 'np.histogram', (['y255', 'NUM_OF_PIXELS_256', '[0, NUM_OF_PIXELS_256]'], {}), '(y255, NUM_OF_PIXELS_256, [0, NUM_OF_PIXELS_256])\n', (7837, 7886), True, 'import numpy as np\n'), ((7905, 7920), 'numpy.cumsum', 'np.cumsum', (['hist'], {}), '(hist)\n', (7914, 7920), True, 'import numpy as np\n'), ((694, 705), 'numpy.min', 'np.min', (['img'], {}), '(img)\n', (700, 705), True, 'import numpy as np\n'), ((710, 721), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (716, 721), True, 'import numpy as np\n'), ((724, 735), 'numpy.min', 'np.min', (['img'], {}), '(img)\n', (730, 735), True, 'import numpy as np\n'), ((1214, 1234), 'cv2.imread', 'cv2.imread', (['filename'], {}), '(filename)\n', (1224, 1234), False, 'import cv2\n'), ((7263, 7287), 'numpy.array_equal', 'np.array_equal', (['q', 'old_q'], {}), '(q, old_q)\n', (7277, 7287), True, 'import numpy as np\n'), ((8505, 8529), 'numpy.array_equal', 'np.array_equal', (['q', 'old_q'], {}), '(q, old_q)\n', (8519, 8529), True, 'import numpy as np\n')]
import sys import torch from uuid import uuid4 import numpy as np from glove import Corpus from ..task.nlp import GloveDataset from ..utils import infer_model_device, defaultdict, check_numpy, JobServer from . import GloveModel JOB_TYPE_REGULAR, JOB_TYPE_NORMS = "JOB_TYPE_REGULAR", "JOB_TYPE_NORMS" class DistributedGloveDataset(GloveDataset): def __init__(self, *, corpora: Corpus, job_server: JobServer, verbose=True, **kwargs): super().__init__(corpora, **kwargs) self.job_server = job_server self.verbose = verbose def iterate_minibatches(self, *, batch_size, buffer_size, job_chunk_size=None, total_batches=float('inf'), model: GloveModel, **kwargs): """ Generate minibatches of data points using worker pool Each batch contains a few unique rows and potentially many columns per row (see GloveDataset) :param batch_size: number of COOC rows in batch :param buffer_size: number of unfinished batches that can exist simultaneously. Smaller buffer = less that paths found by workers are no longer optimal for trainer (due to sgd updates) :param job_chunk_size: if specified, dispatches worker jobs in chunks of this size (default to batch_size) :param total_batches: if specified, terminates after this many batches :type model: GloveModel """ ids = dict() # registry of created jobs. A job is put into registry at birth and removed at completion null_vertex = model.null_vertex num_vertices = model.graph_embedding.num_vertices device = infer_model_device(model) def create_norms_job(): sample_id = uuid4().int job_inputs = { 'row_indices': np.array([null_vertex], dtype='int32'), 'col_matrix': np.arange(num_vertices, dtype='int32')[None], 'sample_id': sample_id, **kwargs, } ids[job_inputs['sample_id']] = {"sample_id": sample_id, "type": JOB_TYPE_NORMS} return job_inputs # (1) create a job for initial norms and wait for it to complete paths_from_v0 = None self.job_server.add_jobs(create_norms_job()) while paths_from_v0 is None: job_result = self.job_server.get_result() if ids[job_result['sample_id']].get("type") == JOB_TYPE_NORMS: paths_from_v0 = job_result elif self.verbose: print(f'Found unknown sample_id {job_result.get("sample_id")}', file=sys.stderr) # (2) generate regular jobs, with occasional norm jobs inbetween def job_generator(): total_samples = 0 while True: batch = self.form_batch(batch_size=batch_size) keys_to_send = ('row_indices', 'col_matrix') keys_to_keep = [key for key in batch.keys() if key not in keys_to_send] for elem in range(batch_size): # submit normal jobs sample_id = uuid4().int data_to_send = {key: check_numpy(batch[key][[elem]]) for key in keys_to_send} data_to_keep = {key: batch[key][[elem]] for key in keys_to_keep} ids[sample_id] = {'sample_id': sample_id, "type": JOB_TYPE_REGULAR, **data_to_keep} yield {'sample_id': sample_id, **data_to_send, **kwargs} total_samples += 1 if total_samples >= total_batches: break # submit job to compute norms yield create_norms_job() # (3) assemble regular job results into batches, update norms as they appear def postprocess_batch(batch): agg_results = defaultdict(list) for result in batch: sample_id = result['sample_id'] for key, value in result.items(): if isinstance(value, (torch.Tensor, np.ndarray)): agg_results[key].append(torch.from_numpy(check_numpy(value))) for key, value in ids[sample_id].items(): if isinstance(value, (torch.Tensor, np.ndarray)): agg_results[key].append(value) del ids[sample_id] concat_result = {key: torch.cat(value).to(device) for key, value in agg_results.items()} concat_result['vertex_norms_output'] = paths_from_v0 return concat_result current_batch = [] for results_chunk in self.job_server.iterate_minibatches( job_generator(), job_chunk_size or batch_size, buffer_size=buffer_size): for job_result in results_chunk: sample_id = job_result['sample_id'] if sample_id not in ids: print(f'Found unknown sample_id {sample_id}', file=sys.stderr) continue elif ids[sample_id]['type'] == JOB_TYPE_NORMS: paths_from_v0 = job_result del ids[sample_id] elif ids[sample_id]['type'] == JOB_TYPE_REGULAR: current_batch.append(job_result) if len(current_batch) >= batch_size: yield [postprocess_batch(current_batch)] # note: we use list to make sure batch isn't *unpacked current_batch = [] else: print(f'Found unknown job type {ids[sample_id]["type"]}', file=sys.stderr)
[ "torch.cat", "uuid.uuid4", "numpy.array", "numpy.arange" ]
[((1711, 1718), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (1716, 1718), False, 'from uuid import uuid4\n'), ((1781, 1819), 'numpy.array', 'np.array', (['[null_vertex]'], {'dtype': '"""int32"""'}), "([null_vertex], dtype='int32')\n", (1789, 1819), True, 'import numpy as np\n'), ((1851, 1889), 'numpy.arange', 'np.arange', (['num_vertices'], {'dtype': '"""int32"""'}), "(num_vertices, dtype='int32')\n", (1860, 1889), True, 'import numpy as np\n'), ((3065, 3072), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (3070, 3072), False, 'from uuid import uuid4\n'), ((4362, 4378), 'torch.cat', 'torch.cat', (['value'], {}), '(value)\n', (4371, 4378), False, 'import torch\n')]
import os import glob import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, CSVLogger from tensorflow.keras.applications.inception_v3 import preprocess_input from tensorflow.keras.preprocessing.image import ImageDataGenerator IM_WIDTH, IM_HEIGHT = 100, 100 # fixed size for InceptionV3 INPUT_SHAPE = (IM_WIDTH, IM_HEIGHT, 3) NB_EPOCHS = 50 BATCH_SIZE = 64 FC_SIZE = 512 NB_IV3_LAYERS_TO_FREEZE = 172 TRAIN_DIR = "../dataset/segmentedspecies/train" VAL_DIR = "../dataset/segmentedspecies/val" MODEL_STORE_TEMPLATE = "../Models/InceptionV3-{}.h5" MODEL_LOG_TEMPLATE = "{}_iv3_log.csv" nb_classes = len(glob.glob(TRAIN_DIR + "/*")) def train_model(model, plot=False): identifier = input('Enter model name to identify log and saved model: ') CSV_LOG_FILE = MODEL_LOG_TEMPLATE.format(identifier) nb_train_samples = get_nb_files(TRAIN_DIR) nb_val_samples = get_nb_files(VAL_DIR) nb_epoch = int(NB_EPOCHS) batch_size = int(BATCH_SIZE) output_model_file = MODEL_STORE_TEMPLATE.format(identifier) train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input) val_datagen = ImageDataGenerator(preprocessing_function=preprocess_input) train_generator = train_datagen.flow_from_directory(TRAIN_DIR, target_size=(IM_WIDTH, IM_HEIGHT), batch_size=batch_size) validation_generator = val_datagen.flow_from_directory(VAL_DIR, target_size=(IM_WIDTH, IM_HEIGHT), batch_size=batch_size) callbacks = [ ReduceLROnPlateau(factor=np.sqrt(0.1), cooldown=0, patience=5, min_lr=0.5e-6), EarlyStopping(min_delta=0.001, patience=10), CSVLogger(CSV_LOG_FILE) ] history_ft = model.fit_generator(train_generator, epochs=nb_epoch, steps_per_epoch=nb_train_samples // batch_size, validation_data=validation_generator, validation_steps=nb_val_samples // batch_size, callbacks=callbacks) model.save(output_model_file) if plot: plot_training(history_ft) def get_nb_files(directory): """Get number of files by searching directory recursively""" if not os.path.exists(directory): return 0 cnt = 0 for r, dirs, files in os.walk(directory): for dr in dirs: cnt += len(glob.glob(os.path.join(r, dr + "/*"))) return cnt def plot_training(history): acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'r.') plt.plot(epochs, val_acc, 'r') plt.title('Training and validation accuracy') plt.figure() plt.plot(epochs, loss, 'r.') plt.plot(epochs, val_loss, 'r-') plt.title('Training and validation loss') plt.show()
[ "matplotlib.pyplot.title", "tensorflow.keras.preprocessing.image.ImageDataGenerator", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "os.walk", "os.path.exists", "tensorflow.keras.callbacks.CSVLogger", "matplotlib.pyplot.figure", "glob.glob", "os.path.join", "tensorflow.keras.callbacks.Earl...
[((676, 703), 'glob.glob', 'glob.glob', (["(TRAIN_DIR + '/*')"], {}), "(TRAIN_DIR + '/*')\n", (685, 703), False, 'import glob\n'), ((1115, 1174), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'preprocessing_function': 'preprocess_input'}), '(preprocessing_function=preprocess_input)\n', (1133, 1174), False, 'from tensorflow.keras.preprocessing.image import ImageDataGenerator\n'), ((1193, 1252), 'tensorflow.keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'preprocessing_function': 'preprocess_input'}), '(preprocessing_function=preprocess_input)\n', (1211, 1252), False, 'from tensorflow.keras.preprocessing.image import ImageDataGenerator\n'), ((2421, 2439), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (2428, 2439), False, 'import os\n'), ((2758, 2785), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'acc', '"""r."""'], {}), "(epochs, acc, 'r.')\n", (2766, 2785), True, 'import matplotlib.pyplot as plt\n'), ((2790, 2820), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'val_acc', '"""r"""'], {}), "(epochs, val_acc, 'r')\n", (2798, 2820), True, 'import matplotlib.pyplot as plt\n'), ((2825, 2870), 'matplotlib.pyplot.title', 'plt.title', (['"""Training and validation accuracy"""'], {}), "('Training and validation accuracy')\n", (2834, 2870), True, 'import matplotlib.pyplot as plt\n'), ((2876, 2888), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2886, 2888), True, 'import matplotlib.pyplot as plt\n'), ((2893, 2921), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'loss', '"""r."""'], {}), "(epochs, loss, 'r.')\n", (2901, 2921), True, 'import matplotlib.pyplot as plt\n'), ((2926, 2958), 'matplotlib.pyplot.plot', 'plt.plot', (['epochs', 'val_loss', '"""r-"""'], {}), "(epochs, val_loss, 'r-')\n", (2934, 2958), True, 'import matplotlib.pyplot as plt\n'), ((2963, 3004), 'matplotlib.pyplot.title', 'plt.title', (['"""Training and validation loss"""'], {}), "('Training and validation loss')\n", (2972, 3004), True, 'import matplotlib.pyplot as plt\n'), ((3009, 3019), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3017, 3019), True, 'import matplotlib.pyplot as plt\n'), ((1735, 1778), 'tensorflow.keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'min_delta': '(0.001)', 'patience': '(10)'}), '(min_delta=0.001, patience=10)\n', (1748, 1778), False, 'from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, CSVLogger\n'), ((1788, 1811), 'tensorflow.keras.callbacks.CSVLogger', 'CSVLogger', (['CSV_LOG_FILE'], {}), '(CSV_LOG_FILE)\n', (1797, 1811), False, 'from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, CSVLogger\n'), ((2339, 2364), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (2353, 2364), False, 'import os\n'), ((1673, 1685), 'numpy.sqrt', 'np.sqrt', (['(0.1)'], {}), '(0.1)\n', (1680, 1685), True, 'import numpy as np\n'), ((2498, 2524), 'os.path.join', 'os.path.join', (['r', "(dr + '/*')"], {}), "(r, dr + '/*')\n", (2510, 2524), False, 'import os\n')]
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for base_utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numpy as np import tensorflow as tf from coltran.utils import base_utils class UtilsTest(tf.test.TestCase): def test_quantize(self): x = tf.range(0, 256, dtype=tf.int32) actual = base_utils.convert_bits(x, n_bits_in=8, n_bits_out=5).numpy() expected = np.repeat(np.arange(0, 32), 8) self.assertTrue(np.allclose(expected, actual)) def test_dequantize(self): x = tf.range(0, 32, dtype=tf.int32) actual = base_utils.convert_bits(x, n_bits_in=5, n_bits_out=8).numpy() expected = np.arange(0, 256, 8) self.assertTrue(np.allclose(expected, actual)) def test_rgb_to_ycbcr(self): x = tf.random.uniform(shape=(2, 32, 32, 3)) ycbcr = base_utils.rgb_to_ycbcr(x) self.assertEqual(ycbcr.shape, (2, 32, 32, 3)) def test_image_hist_to_bit(self): x = tf.random.uniform(shape=(2, 32, 32, 3), minval=0, maxval=256, dtype=tf.int32) hist = base_utils.image_to_hist(x, num_symbols=256) self.assertEqual(hist.shape, (2, 3, 256)) def test_labels_to_bins(self): n_bits = 3 bins = np.arange(2**n_bits) triplets = itertools.product(bins, bins, bins) labels = np.array(list(triplets)) labels_t = tf.convert_to_tensor(labels, dtype=tf.float32) bins_t = base_utils.labels_to_bins(labels_t, num_symbols_per_channel=8) bins_np = bins_t.numpy() self.assertTrue(np.allclose(bins_np, np.arange(512))) inv_labels_t = base_utils.bins_to_labels(bins_t, num_symbols_per_channel=8) inv_labels_np = inv_labels_t.numpy() self.assertTrue(np.allclose(labels, inv_labels_np)) def test_bins_to_labels_random(self): labels_t = tf.random.uniform(shape=(1, 64, 64, 3), minval=0, maxval=8, dtype=tf.int32) labels_np = labels_t.numpy() bins_t = base_utils.labels_to_bins(labels_t, num_symbols_per_channel=8) inv_labels_t = base_utils.bins_to_labels(bins_t, num_symbols_per_channel=8) inv_labels_np = inv_labels_t.numpy() self.assertTrue(np.allclose(inv_labels_np, labels_np)) if __name__ == '__main__': tf.test.main()
[ "tensorflow.test.main", "coltran.utils.base_utils.rgb_to_ycbcr", "tensorflow.range", "coltran.utils.base_utils.convert_bits", "tensorflow.random.uniform", "coltran.utils.base_utils.labels_to_bins", "tensorflow.convert_to_tensor", "numpy.allclose", "coltran.utils.base_utils.bins_to_labels", "numpy....
[((2834, 2848), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (2846, 2848), True, 'import tensorflow as tf\n'), ((917, 949), 'tensorflow.range', 'tf.range', (['(0)', '(256)'], {'dtype': 'tf.int32'}), '(0, 256, dtype=tf.int32)\n', (925, 949), True, 'import tensorflow as tf\n'), ((1160, 1191), 'tensorflow.range', 'tf.range', (['(0)', '(32)'], {'dtype': 'tf.int32'}), '(0, 32, dtype=tf.int32)\n', (1168, 1191), True, 'import tensorflow as tf\n'), ((1282, 1302), 'numpy.arange', 'np.arange', (['(0)', '(256)', '(8)'], {}), '(0, 256, 8)\n', (1291, 1302), True, 'import numpy as np\n'), ((1394, 1433), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '(2, 32, 32, 3)'}), '(shape=(2, 32, 32, 3))\n', (1411, 1433), True, 'import tensorflow as tf\n'), ((1446, 1472), 'coltran.utils.base_utils.rgb_to_ycbcr', 'base_utils.rgb_to_ycbcr', (['x'], {}), '(x)\n', (1469, 1472), False, 'from coltran.utils import base_utils\n'), ((1568, 1645), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '(2, 32, 32, 3)', 'minval': '(0)', 'maxval': '(256)', 'dtype': 'tf.int32'}), '(shape=(2, 32, 32, 3), minval=0, maxval=256, dtype=tf.int32)\n', (1585, 1645), True, 'import tensorflow as tf\n'), ((1683, 1727), 'coltran.utils.base_utils.image_to_hist', 'base_utils.image_to_hist', (['x'], {'num_symbols': '(256)'}), '(x, num_symbols=256)\n', (1707, 1727), False, 'from coltran.utils import base_utils\n'), ((1834, 1856), 'numpy.arange', 'np.arange', (['(2 ** n_bits)'], {}), '(2 ** n_bits)\n', (1843, 1856), True, 'import numpy as np\n'), ((1870, 1905), 'itertools.product', 'itertools.product', (['bins', 'bins', 'bins'], {}), '(bins, bins, bins)\n', (1887, 1905), False, 'import itertools\n'), ((1960, 2006), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['labels'], {'dtype': 'tf.float32'}), '(labels, dtype=tf.float32)\n', (1980, 2006), True, 'import tensorflow as tf\n'), ((2020, 2082), 'coltran.utils.base_utils.labels_to_bins', 'base_utils.labels_to_bins', (['labels_t'], {'num_symbols_per_channel': '(8)'}), '(labels_t, num_symbols_per_channel=8)\n', (2045, 2082), False, 'from coltran.utils import base_utils\n'), ((2190, 2250), 'coltran.utils.base_utils.bins_to_labels', 'base_utils.bins_to_labels', (['bins_t'], {'num_symbols_per_channel': '(8)'}), '(bins_t, num_symbols_per_channel=8)\n', (2215, 2250), False, 'from coltran.utils import base_utils\n'), ((2404, 2479), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '(1, 64, 64, 3)', 'minval': '(0)', 'maxval': '(8)', 'dtype': 'tf.int32'}), '(shape=(1, 64, 64, 3), minval=0, maxval=8, dtype=tf.int32)\n', (2421, 2479), True, 'import tensorflow as tf\n'), ((2559, 2621), 'coltran.utils.base_utils.labels_to_bins', 'base_utils.labels_to_bins', (['labels_t'], {'num_symbols_per_channel': '(8)'}), '(labels_t, num_symbols_per_channel=8)\n', (2584, 2621), False, 'from coltran.utils import base_utils\n'), ((2642, 2702), 'coltran.utils.base_utils.bins_to_labels', 'base_utils.bins_to_labels', (['bins_t'], {'num_symbols_per_channel': '(8)'}), '(bins_t, num_symbols_per_channel=8)\n', (2667, 2702), False, 'from coltran.utils import base_utils\n'), ((1050, 1066), 'numpy.arange', 'np.arange', (['(0)', '(32)'], {}), '(0, 32)\n', (1059, 1066), True, 'import numpy as np\n'), ((1091, 1120), 'numpy.allclose', 'np.allclose', (['expected', 'actual'], {}), '(expected, actual)\n', (1102, 1120), True, 'import numpy as np\n'), ((1323, 1352), 'numpy.allclose', 'np.allclose', (['expected', 'actual'], {}), '(expected, actual)\n', (1334, 1352), True, 'import numpy as np\n'), ((2312, 2346), 'numpy.allclose', 'np.allclose', (['labels', 'inv_labels_np'], {}), '(labels, inv_labels_np)\n', (2323, 2346), True, 'import numpy as np\n'), ((2764, 2801), 'numpy.allclose', 'np.allclose', (['inv_labels_np', 'labels_np'], {}), '(inv_labels_np, labels_np)\n', (2775, 2801), True, 'import numpy as np\n'), ((963, 1016), 'coltran.utils.base_utils.convert_bits', 'base_utils.convert_bits', (['x'], {'n_bits_in': '(8)', 'n_bits_out': '(5)'}), '(x, n_bits_in=8, n_bits_out=5)\n', (986, 1016), False, 'from coltran.utils import base_utils\n'), ((1205, 1258), 'coltran.utils.base_utils.convert_bits', 'base_utils.convert_bits', (['x'], {'n_bits_in': '(5)', 'n_bits_out': '(8)'}), '(x, n_bits_in=5, n_bits_out=8)\n', (1228, 1258), False, 'from coltran.utils import base_utils\n'), ((2153, 2167), 'numpy.arange', 'np.arange', (['(512)'], {}), '(512)\n', (2162, 2167), True, 'import numpy as np\n')]
""" This file defines an "energy balance" snowmelt component and related functions. It inherits from the snowmelt "base class" in "snow_base.py". """ #----------------------------------------------------------------------- # # Copyright (c) 2001-2014, <NAME> # # Sep 2014. Cleanup and testing. # Own versions of input file routines, at end. # Aug 2014. Customized initialize_computed_vars(), which calls # initialize_cold_content(). # Updates to standard names and BMI. # Nov 2013. Converted TopoFlow to Python package. # Jan 2013. Revised handling of input/output names. # Oct 2012. CSDMS Standard Names and BMI. # May 2010. Changes to unit_test() and read_cfg_file(). # Aug 2009. Updates. # Jul 2009. Updates. # Jan 2009. Converted from IDL. # #----------------------------------------------------------------------- # # class snow_energy_balance # # get_component_name() # get_attribute() # (10/26/11) # get_input_var_names() # (5/14/12) # get_output_var_names() # (5/14/12) # get_var_name() # (5/16/12, Bolton) # get_var_units() # (5/16/12, Bolton) # ---------------------- # check_input_types() # initialize_input_file_vars() # (7/3/20) # initialize_cold_content() # (9/13/14, from snow_base.py) # initialize_computed_vars() # (9/13/14, from snow_base.py) # update_meltrate() # ---------------------- # open_input_files() # read_input_files() # close_input_files() # #----------------------------------------------------------------------- import numpy as np from topoflow.utils import model_input from topoflow.components import snow_base #----------------------------------------------------------------------- class snow_component( snow_base.snow_component ): #------------------------------------------------------------------- _att_map = { 'model_name': 'TopoFlow_Snowmelt_Energy_Balance', 'version': '3.1', 'author_name': '<NAME>', 'grid_type': 'uniform', 'time_step_type': 'fixed', 'step_method': 'explicit', #------------------------------------------------------------- 'comp_name': 'SnowEnergyBalance', 'model_family': 'TopoFlow', 'cfg_template_file': 'Snow_Energy_Balance.cfg.in', 'cfg_extension': '_snow_energy_balance.cfg', 'cmt_var_prefix': '/SnowEnergyBalance/Input/Var/', 'gui_xml_file': '/home/csdms/cca/topoflow/3.1/src/share/cmt/gui/Snow_Energy_Balance.xml', 'dialog_title': 'Snowmelt: Energy Balance Parameters', # (Snowmelt ?) 'time_units': 'seconds' } #---------------------------------------------------------- # The Energy-Balance method needs several vars from the # Met component, such as T_air, Q_sum. The others # are used for consistent use of scalars vs. grids; # see "check_input_types()" below. (e.g. p0 and RH) #---------------------------------------------------------- # Some input vars, like ****** are read from the CFG # file and not from other components. They are therefore # included with the output_vars. #------------------------------------------------------------ # Note: snowfall_leq-volume_flux *must* be nonliquid precip. #------------------------------------------------------------ _input_var_names = [ 'atmosphere_bottom_air__mass-per-volume_density', 'atmosphere_bottom_air__mass-specific_isobaric_heat_capacity', 'atmosphere_bottom_air__temperature', 'atmosphere_water__snowfall_leq-volume_flux', 'land_surface__temperature', # (used to initialize Ecc) 'land_surface_net-total-energy__energy_flux', 'water-liquid__mass-per-volume_density' ] #------------------------------------------------------------ # These are used by Meteorology component to compute Q_sum. # but are not needed directly by this component. (9/14/14) #------------------------------------------------------------ # 'atmosphere_bottom_air__pressure', # 'atmosphere_bottom_air_flow__log_law_roughness_length', # 'atmosphere_bottom_air_flow__speed_reference_height', # 'atmosphere_bottom_air_flow__reference-height_speed', # 'atmosphere_bottom_air_water-vapor__relative_saturation', # 'land_surface_net-longwave-radiation__energy_flux', # 'land_surface_net-shortwave-radiation__energy_flux', #------------------------------------------------------------ # Note: The main output of the Energy-Balance method is SM. # Functions in snow_base.py compute additional output # vars, such as: # update_SM_integral(), update_depth(), update_swe(). # They need things like: rho_H2O and rho_snow. #------------------------------------------------------------ # Note: Cp_snow is a constant set in the "set_constants()" # function in snow_base.py. #------------------------------------------------------------ # vol_SM was "basin_cumulative_snow_meltwater_volume" #------------------------------------------------------------ _output_var_names = [ 'model__time_step', # dt 'snowpack__domain_time_integral_of_melt_volume_flux', # vol_SM 'snowpack__domain_time_integral_of_liquid-equivalent_depth', # vol_swe 'snowpack__energy-per-area_cold_content', # Ecc 'snowpack__depth', # h_snow 'snowpack__initial_depth', # h0_snow 'snowpack__initial_liquid-equivalent_depth', # h0_swe 'snowpack__liquid-equivalent_depth', # h_swe 'snowpack__melt_volume_flux', # SM 'snowpack__z_mean_of_mass-per-volume_density', # rho_snow 'snowpack__z_mean_of_mass-specific_isobaric_heat_capacity' ] # Cp_snow _var_name_map = { 'atmosphere_bottom_air__mass-per-volume_density': 'rho_air', 'atmosphere_bottom_air__mass-specific_isobaric_heat_capacity': 'Cp_air', 'atmosphere_bottom_air__temperature': 'T_air', 'atmosphere_water__snowfall_leq-volume_flux': 'P_snow', 'land_surface_net-total-energy__energy_flux': 'Q_sum', 'land_surface__temperature': 'T_surf', 'water-liquid__mass-per-volume_density': 'rho_H2O', #------------------------------------------------------------ # These are used by Meteorology component to compute Q_sum. # but are not needed directly by this component. (9/14/14) #------------------------------------------------------------ #'atmosphere_bottom_air__pressure': 'p0', #'atmosphere_bottom_air_flow__log_law_roughness_length': 'z0_air', #'atmosphere_bottom_air_flow__speed_reference_height': 'z', #'atmosphere_bottom_air_flow__reference-height_speed': 'uz', #'atmosphere_bottom_air_water-vapor__relative_saturation': 'RH', #'land_surface_net-longwave-radiation__energy_flux': 'Qn_LW', #'land_surface_net-shortwave-radiation__energy_flux': 'Qn_SW', #---------------------------------------------------------- 'model__time_step': 'dt', 'snowpack__domain_time_integral_of_melt_volume_flux': 'vol_SM', 'snowpack__domain_time_integral_of_liquid-equivalent_depth': 'vol_swe', 'snowpack__depth': 'h_snow', 'snowpack__energy-per-area_cold_content': 'Ecc', 'snowpack__initial_depth': 'h0_snow', 'snowpack__initial_liquid-equivalent_depth': 'h0_swe', 'snowpack__liquid-equivalent_depth': 'h_swe', 'snowpack__melt_volume_flux': 'SM', 'snowpack__z_mean_of_mass-per-volume_density': 'rho_snow', 'snowpack__z_mean_of_mass-specific_isobaric_heat_capacity': 'Cp_snow' } #----------------------------------------------------------------- # Note: We need to be careful with whether units are C or K, # for all "thermal" quantities (e.g. thermal_capacity). #----------------------------------------------------------------- _var_units_map = { 'atmosphere_bottom_air__mass-per-volume_density': 'kg m-3', 'atmosphere_bottom_air__mass-specific_isobaric_heat_capacity': 'J kg-1 K-1 ', # (see Notes above) 'atmosphere_bottom_air__temperature': 'deg_C', # (see Notes above) 'atmosphere_water__snowfall_leq-volume_flux': 'm s-1', 'land_surface_net-total-energy__energy_flux': 'W m-2', 'land_surface__temperature': 'deg_C', 'water-liquid__mass-per-volume_density': 'kg m-3', #------------------------------------------------------------ # These are used by Meteorology component to compute Q_sum. # but are not needed directly by this component. (9/14/14) #------------------------------------------------------------ # 'atmosphere_bottom_air__pressure': 'mbar', # 'atmosphere_bottom_air_flow__log_law_roughness_length': 'm', # 'atmosphere_bottom_air_flow__speed_reference_height': 'm', # 'atmosphere_bottom_air_flow__reference-height_speed': 'm s-1', # 'atmosphere_bottom_air_water-vapor__relative_saturation': '1', # 'land_surface_net-longwave-radiation__energy_flux': 'W m-2', # 'land_surface_net-shortwave-radiation__energy_flux': 'W m-2', #-------------------------------------------------------------- 'model__time_step': 's', 'snowpack__domain_time_integral_of_melt_volume_flux': 'm3', 'snowpack__domain_time_integral_of_liquid-equivalent_depth': 'm3', 'snowpack__depth': 'm', 'snowpack__energy-per-area_cold_content': 'J m-2', 'snowpack__initial_depth': 'm', 'snowpack__initial_liquid-equivalent_depth': 'm', 'snowpack__liquid-equivalent_depth': 'm', 'snowpack__melt_volume_flux': 'm s-1', 'snowpack__z_mean_of_mass-per-volume_density': 'kg m-3', 'snowpack__z_mean_of_mass-specific_isobaric_heat_capacity': 'J kg-1 K-1' } #------------------------------------------------ # Return NumPy string arrays vs. Python lists ? #------------------------------------------------ ## _input_var_names = np.array( _input_var_names ) ## _output_var_names = np.array( _output_var_names ) #------------------------------------------------------------------- def get_component_name(self): return 'TopoFlow_Snow_Energy_Balance' # get_component_name() #------------------------------------------------------------------- def get_attribute(self, att_name): try: return self._att_map[ att_name.lower() ] except: print('###################################################') print(' ERROR: Could not find attribute: ' + att_name) print('###################################################') print(' ') # get_attribute() #------------------------------------------------------------------- def get_input_var_names(self): #-------------------------------------------------------- # Note: These are currently variables needed from other # components vs. those read from files or GUI. #-------------------------------------------------------- return self._input_var_names # get_input_var_names() #------------------------------------------------------------------- def get_output_var_names(self): return self._output_var_names # get_output_var_names() #------------------------------------------------------------------- def get_var_name(self, long_var_name): return self._var_name_map[ long_var_name ] # get_var_name() #------------------------------------------------------------------- def get_var_units(self, long_var_name): return self._var_units_map[ long_var_name ] # get_var_units() #------------------------------------------------------------------- ## def get_var_type(self, long_var_name): ## ## #--------------------------------------- ## # So far, all vars have type "double", ## # but use the one in BMI_base instead. ## #--------------------------------------- ## return 'float64' ## ## # get_var_type() #------------------------------------------------------------------- def check_input_types(self): #-------------------------------------------------- # Notes: rho_H2O, Cp_snow, rho_air and Cp_air are # currently always scalars. #-------------------------------------------------- are_scalars = np.array([ self.is_scalar('P_snow'), self.is_scalar('rho_H2O'), self.is_scalar('rho_air'), self.is_scalar('Cp_air'), self.is_scalar('T_air'), ##### CHECK THIS ONE. self.is_scalar('T_surf'), self.is_scalar('Q_sum'), #-------------------------------- # self.is_scalar('RH'), # self.is_scalar('p0'), # self.is_scalar('uz'), # self.is_scalar('z'), # self.is_scalar('z0_air'), # self.is_scalar('Qn_SW'), # self.is_scalar('Qn_LW'), #-------------------------------- self.is_scalar('rho_snow'), self.is_scalar('Cp_snow'), self.is_scalar('h0_snow'), self.is_scalar('h0_swe') ]) self.ALL_SCALARS = np.all(are_scalars) # check_input_types() #------------------------------------------------------------------- def initialize_input_file_vars(self): #--------------------------------------------------- # Initialize vars to be read from files (11/16/16) #--------------------------------------------------- # Need this in order to use "bmi.update_var()". #---------------------------------------------------------- # NOTE: read_config_file() sets these to '0.0' if they # are not type "Scalar", so self has the attribute. #---------------------------------------------------------- dtype = 'float64' if (self.Cp_snow_type.lower() != 'scalar'): self.Cp_snow = self.initialize_var(self.Cp_snow_type, dtype=dtype) if (self.rho_snow_type.lower() != 'scalar'): self.rho_snow = self.initialize_var(self.rho_snow_type, dtype=dtype) if (self.T0_type.lower() != 'scalar'): self.T0 = self.initialize_var(self.T0_type, dtype=dtype) if (self.h0_snow_type.lower() != 'scalar'): self.h0_snow = self.initialize_var(self.h0_snow_type, dtype=dtype) if (self.h0_swe_type.lower() != 'scalar'): self.h0_swe = self.initialize_var(self.h0_swe_type, dtype=dtype) # initialize_input_file_vars() #------------------------------------------------------------------- def initialize_computed_vars(self): #------------------------------------------ # If T_air or precip are grids, then make # sure that h_snow and h_swe are grids #------------------------------------------ T_IS_GRID = self.is_grid('T_air') P_IS_GRID = self.is_grid('P_snow') H0_SNOW_IS_SCALAR = self.is_scalar('h0_snow') H0_SWE_IS_SCALAR = self.is_scalar('h0_swe') #------------------------------------------------------ # If h0_snow or h0_swe are scalars, the use of copy() # here requires they were converted to numpy scalars. # Using copy() may not be necessary for scalars. #------------------------------------------------------ h_snow = self.h0_snow.copy() # [meters] h_swe = self.h0_swe.copy() # [meters] #------------------------------------------------------ # For the Energy Balance method, SM, h_snow and h_swe # are always grids because Q_sum is always a grid. #-------------------------------------------------------------- # Convert both h_snow and h_swe to grids if not already grids #-------------------------------------------------------------- if (H0_SNOW_IS_SCALAR): self.h_snow = h_snow + np.zeros([self.ny, self.nx], dtype='float64') else: self.h_snow = h_snow # (is already a grid) if (H0_SWE_IS_SCALAR): self.h_swe = h_swe + np.zeros([self.ny, self.nx], dtype='float64') else: self.h_swe = h_swe # (is already a grid) self.SM = np.zeros([self.ny, self.nx], dtype='float64') self.vol_SM = self.initialize_scalar( 0, dtype='float64') # (m3) #---------------------------------------------------- # Compute density ratio for water to snow. # rho_H2O is for liquid water close to 0 degrees C. # Water is denser than snow, so density_ratio > 1. #---------------------------------------------------- self.density_ratio = (self.rho_H2O / self.rho_snow) #---------------------------------------------------- # Initialize the cold content of snowpack (2/21/07) #------------------------------------------------------------- # This is the only difference from initialize_computed_vars() # method in snow_base.py. #------------------------------------------------------------- self.initialize_cold_content() # initialize_computed_vars() #--------------------------------------------------------------------- def initialize_cold_content( self ): #---------------------------------------------------------------- # NOTES: This function is used to initialize the cold content # of a snowpack. # The cold content has units of [J m-2] (_NOT_ [W m-2]). # It is an energy (per unit area) threshold (or deficit) # that must be overcome before melting of snow can occur. # Cold content changes over time as the snowpack warms or # cools, but must always be non-negative. # # K_snow is between 0.063 and 0.71 [W m-1 K-1] # All of the Q's have units of W m-2 = J s-1 m-2). # # T0 is read from the config file. This is a different # T0 from the one used by the Degree-Day method. #--------------------------------------------------------------- #-------------------------------------------- # Compute initial cold content of snowpack #-------------------------------------------- T_snow = self.T_surf del_T = (self.T0 - T_snow) self.Ecc = (self.rho_snow * self.Cp_snow) * self.h0_snow * del_T #------------------------------------ # Cold content must be nonnegative. #---------------------------------------------- # Ecc > 0 if (T_snow < T0). i.e. T_snow < 0. #---------------------------------------------- self.Ecc = np.maximum( self.Ecc, np.float64(0)) ### np.maximum( self.Ecc, np.float64(0), self.Ecc) # (in place) # initialize_cold_content() #------------------------------------------------------------------- def update_meltrate(self): #------------------------------------------------------------ # Notes: This computes a "potential" meltrate, which can't # be realized unless there is enough snow. # See snow_base.enforce_max_meltrate(). #------------------------------------------------------------ # Notes: See notes in "met_base.py" for the method called # "update_net_energy_flux()". # This version uses "Q_sum" which is computed as a # state variable for a meteorology component # (e.g. met_base.py). # Arguments are assumed to be references to a scalar # or grid so that: # M = water equivalent of snowmelt [m/s] # M_max = max possible meltrate if all snow melts # T_air = air temperature [deg_C] # Model must start when snow is isothermal. (CHECK) # Cooling of the snowpack is not considered. # 86400000d = 1000 [mm/m] * 60 [sec/min] * # 60 [min/sec] * 24 [hrs/day] # rho_snow is not needed in formula here, but is # needed to convert snowmelt to water equivalent? #------------------------------------------------------------- #---------------------------------- # Compute energy-balance meltrate #------------------------------------------------------ # Ecc is initialized by initialize_cold_content(). #------------------------------------------------------ # The following pseudocode only works for scalars but # is otherwise equivalent to that given below and # clarifies the logic: #------------------------------------------------------ # if (Q_sum gt 0) then begin # if ((Q_sum * dt) gt Ecc) then begin # ;------------------------------------------- # ; Snow is melting. Use some of Q_sum to # ; overcome Ecc, and remainder to melt snow # ;------------------------------------------- # Qm = Q_sum - (Ecc/dt) # Ecc = 0 # M = (Qm / (rho_w * Lf)) # endif else begin # ;------------------------------ # ; Snow is warming; reduce Ecc # ;------------------------------ # Ecc = (Ecc - (Q_sum * dt)) # M = 0d # endelse # endif else begin # ;-------------------------------- # ; Snow is cooling; increase Ecc # ;-------------------------------- # Ecc = Ecc - (Q_sum * dt) # M = 0d # endelse #--------------------------------------------------------- # Q_sum = Qn_SW + Qn_LW + Qh + Qe + Qa + Qc # [W m-2] #--------------------------------------------------------- #----------------------------------------------- # New approach; easier to understand (9/14/14) #----------------------------------------------- # E_in = energy input over one time step # E_rem = energy remaining in excess of Ecc #----------------------------------------------- E_in = (self.Q_sum * self.dt) E_rem = np.maximum( E_in - self.Ecc, np.float64(0) ) Qm = (E_rem / self.dt) # [W m-2] ################################## # Used before 9/14/14/. ################################## # Q_sum = self.Q_sum # (2/3/13, new framework) # Qcc = (self.Ecc / self.dt) # [W m-2] # Qm = np.maximum((Q_sum - Qcc), float64(0)) # [W m-2] #------------------------------------- # Convert melt energy to a melt rate #------------------------------------------ # Lf = latent heat of fusion [J/kg] # Lv = latent heat of vaporization [J/kg] # M = (Qm / (rho_w * Lf)) #------------------------------------------ # rho_w = 1000d ;[kg/m^3] # Lf = 334000d ;[J/kg = W*s/kg] # So (rho_w * Lf) = 3.34e+8 [J/m^3] #------------------------------------------ M = (Qm / np.float64(3.34E+8)) #[m/s] self.SM = np.maximum(M, np.float64(0)) #-------------------------------------------------- # Update the cold content of the snowpack [J m-2] # If this is positive, there was no melt so far. #-------------------------------------------------- # (9/13/14) Bug fix: Ecc wasn't stored into self. #-------------------------------------------------- self.Ecc = np.maximum((self.Ecc - E_in), np.float64(0)) #------------------------------------------------------- # Note: enforce_max_meltrate() method is always called # by the base class to make sure that meltrate # does not exceed the max possible. #------------------------------------------------------- # self.enforce_max_meltrate() # update_meltrate() #--------------------------------------------------------------------- def open_input_files(self): self.Cp_snow_file = self.in_directory + self.Cp_snow_file self.rho_snow_file = self.in_directory + self.rho_snow_file self.T0_file = self.in_directory + self.T0_file self.h0_snow_file = self.in_directory + self.h0_snow_file self.h0_swe_file = self.in_directory + self.h0_swe_file self.Cp_snow_unit = model_input.open_file(self.Cp_snow_type, self.Cp_snow_file) self.rho_snow_unit = model_input.open_file(self.rho_snow_type, self.rho_snow_file) self.T0_unit = model_input.open_file(self.T0_type, self.T0_file) self.h0_snow_unit = model_input.open_file(self.h0_snow_type, self.h0_snow_file) self.h0_swe_unit = model_input.open_file(self.h0_swe_type, self.h0_swe_file) # open_input_files() #------------------------------------------------------------------- def read_input_files(self): rti = self.rti #-------------------------------------------------------- # All grids are assumed to have a data type of float32. #-------------------------------------------------------- Cp_snow = model_input.read_next(self.Cp_snow_unit, self.Cp_snow_type, rti) if (Cp_snow is not None): self.update_var( 'Cp_snow', Cp_snow ) rho_snow = model_input.read_next(self.rho_snow_unit, self.rho_snow_type, rti) if (rho_snow is not None): self.update_var( 'rho_snow', rho_snow ) T0 = model_input.read_next(self.T0_unit, self.T0_type, rti) if (T0 is not None): self.update_var( 'T0', T0 ) h0_snow = model_input.read_next(self.h0_snow_unit, self.h0_snow_type, rti) if (h0_snow is not None): self.update_var( 'h0_snow', h0_snow ) h0_swe = model_input.read_next(self.h0_swe_unit, self.h0_swe_type, rti) if (h0_swe is not None): self.update_var( 'h0_swe', h0_swe ) # read_input_files() #------------------------------------------------------------------- def close_input_files(self): if (self.Cp_snow_type != 'Scalar'): self.Cp_snow_unit.close() if (self.rho_snow_type != 'Scalar'): self.rho_snow_unit.close() if (self.T0_type != 'Scalar'): self.T0_unit.close() if (self.h0_snow_type != 'Scalar'): self.h0_snow_unit.close() if (self.h0_swe_type != 'Scalar'): self.h0_swe_unit.close() ## if (self.T0_file != ''): self.T0_unit.close() ## if (self.rho_snow_file != ''): self.rho_snow_unit.close() ## if (self.h0_snow_file != ''): self.h0_snow_unit.close() ## if (self.h0_swe_file != ''): self.h0_swe_unit.close() # close_input_files() #------------------------------------------------------------------- #------------------------------------------------------------------------- ###------------------------------------------------------------------------- ##def Energy_Balance_Meltrate(Qn_SW, Qn_LW, T_air, T_surf, RH, p0, \ ## uz, z, z0_air, rho_air, Cp_air, Ecc, \ ## h_snow, rho_snow, Cp_snow, dt, \ ## e_air, e_surf): #(returned) ## ## #----------------------------------------------------------------- ## # Notes: 3/13/07. This function used to have vapor pressure ## # arguments e_air and e_surf. However, e_air is always ## # computed as a function of T_air and RH and e_surf is ## # computed as a function of T_surf (saturated vap. press.) ## # So it makes sense to remove these two arguments and add ## # RH (relative humidity). This change only affects the ## # Latent_Heat_Flux function call, which calls a new ## # function called Vapor_Pressure. ## #----------------------------------------------------------------- ## # Qm = energy used to melt snowpack (if > 0) ## # Qn_SW = net shortwave radiation flux (solar) ## # Qn_LW = net longwave radiation flux (air, surface) ## # Qh = sensible heat flux from turbulent convection ## # between snow surface and air ## # Qe = latent heat flux from evaporation, sublimation, ## # and condensation ## # Qa = energy advected by moving water (i.e. rainfall) ## # (ARHYTHM assumes this to be negligible; Qa=0.) ## # Qc = energy flux via conduction from snow to soil ## # (ARHYTHM assumes this to be negligible; Qc=0.) ## # Ecc = cold content of snowpack = amount of energy ## # needed before snow can begin to melt [J/m^2] ## ## # All Q's here have units of [W/m^2]. ## # Are they all treated as positive quantities ? ## ## # rho_air = density of air [kg/m^3] ## # rho_snow = density of snow [kg/m^3] ## # Cp_air = specific heat of air [Jkg-1 K-1] ## # Cp_snow = heat capacity of snow [Jkg-1 K-1] ## # = ???????? = specific heat of snow ## # Kh = eddy diffusivity for heat [m^2/s] ## # Ke = eddy diffusivity for water vapor [m^2/s] ## # Lv = latent heat of vaporization [J/kg] ## # Lf = latent heat of fusion [J/kg] ## # ------------------------------------------------------ ## # Dn = bulk exchange coeff for the conditions of ## # neutral atmospheric stability [m/s] ## # Dh = bulk exchange coeff for heat ## # De = bulk exchange coeff for vapor ## # ------------------------------------------------------ ## # T_air = air temperature [deg_C] ## # T_surf = surface temperature [deg_C] ## # T_snow = average snow temperature [deg_C] ## # RH = relative humidity [none] (in [0,1]) ## # e_air = air vapor pressure at height z [mbar] ## # e_surf = surface vapor pressure [mbar] ## # ------------------------------------------------------ ## # h_snow = snow depth [m] ## # z = height where wind speed is uz [m] ## # uz = wind speed at height z [m/s] ## # P0 = atmospheric pressure [mbar] ## # T0 = snow temperature when isothermal [deg_C] ## # (This is usually 0.) ## # z0_air = surface roughness length scale [m] ## # (includes vegetation not covered by snow) ## # (Values from page 1033: 0.0013, 0.02 [m]) ## # kappa = von Karman's constant [unitless] = 0.41 ## # dt = snowmelt timestep [seconds] ## #---------------------------------------------------------------- ## ## # FORWARD_FUNCTION Richardson_Number ## ## #--------------------------------- ## #Some required physical constants ## #are defined in the functions: ## #e.g. Lv, Lf ## #--------------------------------- ## ## #------------------------------ ## #Compute the Richardson number ## #------------------------------ ## Ri = Richardson_Number(z, uz, T_air, T_surf) ## ## #------------------------------------------------- ## #Compute bulk exchange coeffs (neutral stability) ## #------------------------------------------------- ## Dn = Bulk_Exchange_Coeff(uz, z, h_snow, z0_air, T_air, T_surf) ## Dh = Dn ## De = Dn ## ## #--------------------------- ## #Compute sensible heat flux ## #--------------------------- ## Qh = Sensible_Heat_Flux(rho_air, Cp_air, Dh, T_air, T_surf) ## #Formula: Qh = rho_air * Cp_air * Dh * (T_air - T_surf) ## #print,'Dh = ', Dh ## #print,'Qh = ', Qh ## ## #------------------------- ## #Compute latent heat flux ## #------------------------- ## Qe = Latent_Heat_Flux(rho_air, De, T_air, T_surf, RH, p0, ## e_air, e_surf) #(these 2 returned) ## #Formula: Qe = rho_air * Lv * De * (0.662/p0) * (e_air - e_surf) ## ## #print,'Qe = ', Qe ## ## #----------------------------- ## #Compute conduction heat flux ## #----------------------------- ## Qc = Conduction_Heat_Flux() ## #Formula: Qc = 0d ## ## #----------------------------- ## #Compute advective heat flux ## #----------------------------- ## Qa = Advection_Heat_Flux() ## #Formula: Qa = 0d ## ## #--------------------------------- ## #Qn_SW, Qn_SW & Ecc are pointers, ## #others are local variables ## #---------------------------------------------------- ## #Ecc is initialized with the Initial_Cold_Content ## #function by Initialize_Snow_Vars function (2/21/07) ## #---------------------------------------------------- ## #The following pseudocode only works for scalars but ## #is otherwise equivalent to that given below and ## #clarifies the logic: ## #---------------------------------------------------- ## # if (Q_sum gt 0) then begin ## # if ((Q_sum * dt) gt Ecc) then begin ## # ;----------------------------------------- ## # ;Snow is melting. Use some of Q_sum to ## # ;overcome Ecc, and remainder to melt snow ## # ;----------------------------------------- ## # Qm = Q_sum - (Ecc/dt) ## # Ecc = 0 ## # M = (Qm / (rho_w * Lf)) ## # endif else begin ## # ;---------------------------- ## # ;Snow is warming; reduce Ecc ## # ;---------------------------- ## # Ecc = (Ecc - (Q_sum * dt)) ## # M = 0d ## # endelse ## # endif else begin ## # ;------------------------------ ## # ;Snow is cooling; increase Ecc ## # ;------------------------------ ## # Ecc = Ecc - (Q_sum * dt) ## # M = 0d ## # endelse ## #------------------------------------------------------- ## Q_sum = Qn_SW + Qn_LW + Qh + Qe + Qa + Qc #[W/m^2] ## Qcc = (Ecc / dt) #[W/m^2] ## Qm = maximum((Q_sum - Qcc), float64(0)) #[W/m^2] ## Ecc = maximum((Ecc - (Q_sum * dt)), float64(0)) #[J/m^2] ## #print,'Qm = ', Qm ## #print,' ' ## ## #----------------------------------- ## #Convert melt energy to a melt rate ## #---------------------------------------- ## #Lf = latent heat of fusion [J/kg] ## #Lv = latent heat of vaporization [J/kg] ## #M = (Qm/ (rho_w * Lf)) ## #---------------------------------------- ## #rho_w = 1000d ;[kg/m^3] ## #Lf = 334000d ;[J/kg = W*s/kg] ## #So (rho_w * Lf) = 3.34e+8 [J/m^3] ## #------------------------------------- ## M = (Qm / float32(3.34E+8)) #[m/s] ## ## return maximum(M, float32(0.0)) ## ### Energy_Balance_Meltrate ###-------------------------------------------------------------------------
[ "topoflow.utils.model_input.open_file", "numpy.zeros", "topoflow.utils.model_input.read_next", "numpy.float64", "numpy.all" ]
[((14220, 14239), 'numpy.all', 'np.all', (['are_scalars'], {}), '(are_scalars)\n', (14226, 14239), True, 'import numpy as np\n'), ((17344, 17389), 'numpy.zeros', 'np.zeros', (['[self.ny, self.nx]'], {'dtype': '"""float64"""'}), "([self.ny, self.nx], dtype='float64')\n", (17352, 17389), True, 'import numpy as np\n'), ((25895, 25954), 'topoflow.utils.model_input.open_file', 'model_input.open_file', (['self.Cp_snow_type', 'self.Cp_snow_file'], {}), '(self.Cp_snow_type, self.Cp_snow_file)\n', (25916, 25954), False, 'from topoflow.utils import model_input\n'), ((25985, 26046), 'topoflow.utils.model_input.open_file', 'model_input.open_file', (['self.rho_snow_type', 'self.rho_snow_file'], {}), '(self.rho_snow_type, self.rho_snow_file)\n', (26006, 26046), False, 'from topoflow.utils import model_input\n'), ((26076, 26125), 'topoflow.utils.model_input.open_file', 'model_input.open_file', (['self.T0_type', 'self.T0_file'], {}), '(self.T0_type, self.T0_file)\n', (26097, 26125), False, 'from topoflow.utils import model_input\n'), ((26161, 26220), 'topoflow.utils.model_input.open_file', 'model_input.open_file', (['self.h0_snow_type', 'self.h0_snow_file'], {}), '(self.h0_snow_type, self.h0_snow_file)\n', (26182, 26220), False, 'from topoflow.utils import model_input\n'), ((26251, 26308), 'topoflow.utils.model_input.open_file', 'model_input.open_file', (['self.h0_swe_type', 'self.h0_swe_file'], {}), '(self.h0_swe_type, self.h0_swe_file)\n', (26272, 26308), False, 'from topoflow.utils import model_input\n'), ((26685, 26749), 'topoflow.utils.model_input.read_next', 'model_input.read_next', (['self.Cp_snow_unit', 'self.Cp_snow_type', 'rti'], {}), '(self.Cp_snow_unit, self.Cp_snow_type, rti)\n', (26706, 26749), False, 'from topoflow.utils import model_input\n'), ((26862, 26928), 'topoflow.utils.model_input.read_next', 'model_input.read_next', (['self.rho_snow_unit', 'self.rho_snow_type', 'rti'], {}), '(self.rho_snow_unit, self.rho_snow_type, rti)\n', (26883, 26928), False, 'from topoflow.utils import model_input\n'), ((27030, 27084), 'topoflow.utils.model_input.read_next', 'model_input.read_next', (['self.T0_unit', 'self.T0_type', 'rti'], {}), '(self.T0_unit, self.T0_type, rti)\n', (27051, 27084), False, 'from topoflow.utils import model_input\n'), ((27181, 27245), 'topoflow.utils.model_input.read_next', 'model_input.read_next', (['self.h0_snow_unit', 'self.h0_snow_type', 'rti'], {}), '(self.h0_snow_unit, self.h0_snow_type, rti)\n', (27202, 27245), False, 'from topoflow.utils import model_input\n'), ((27356, 27418), 'topoflow.utils.model_input.read_next', 'model_input.read_next', (['self.h0_swe_unit', 'self.h0_swe_type', 'rti'], {}), '(self.h0_swe_unit, self.h0_swe_type, rti)\n', (27377, 27418), False, 'from topoflow.utils import model_input\n'), ((19933, 19946), 'numpy.float64', 'np.float64', (['(0)'], {}), '(0)\n', (19943, 19946), True, 'import numpy as np\n'), ((23613, 23626), 'numpy.float64', 'np.float64', (['(0)'], {}), '(0)\n', (23623, 23626), True, 'import numpy as np\n'), ((24541, 24564), 'numpy.float64', 'np.float64', (['(334000000.0)'], {}), '(334000000.0)\n', (24551, 24564), True, 'import numpy as np\n'), ((24603, 24616), 'numpy.float64', 'np.float64', (['(0)'], {}), '(0)\n', (24613, 24616), True, 'import numpy as np\n'), ((25029, 25042), 'numpy.float64', 'np.float64', (['(0)'], {}), '(0)\n', (25039, 25042), True, 'import numpy as np\n'), ((17015, 17060), 'numpy.zeros', 'np.zeros', (['[self.ny, self.nx]'], {'dtype': '"""float64"""'}), "([self.ny, self.nx], dtype='float64')\n", (17023, 17060), True, 'import numpy as np\n'), ((17195, 17240), 'numpy.zeros', 'np.zeros', (['[self.ny, self.nx]'], {'dtype': '"""float64"""'}), "([self.ny, self.nx], dtype='float64')\n", (17203, 17240), True, 'import numpy as np\n')]
import numpy as np import matplotlib import matplotlib.pyplot as plt import tensorflow as tf from setup_cifar import CIFAR, CIFARModel from neuromask import NeuroMask flags = tf.app.flags flags.DEFINE_integer('test_idx', 1, help='Index for test example.') flags.DEFINE_integer('num_iters', 2000, help='Number of iterations') flags.DEFINE_float('smooth_lambda', 0.15, help='Weight of smoothness loss coefficient') def display_img(img, mask): fig, ax = plt.subplots(1, 2, figsize=(10, 4)) ax[0].imshow(img) ax[0].axis('off') ax[1].imshow(img) mask_min = mask.min() mask_max = mask.max() mask_vis = (mask - mask_min) / (mask_max - mask_min) ax[1].imshow(mask_vis, cmap='jet', alpha=0.6) ax[1].axis('off') return fig FLAGS = flags.FLAGS cifar_data = CIFAR() test_idx = FLAGS.test_idx test_img = cifar_data.test_data[test_idx]+0.5 tf.reset_default_graph() with tf.Session() as sess: model = CIFARModel('cifar10_model', sess, False) input_holder = tf.placeholder(tf.float32, [1, 32, 32, 3], name='x') model_out = model(input_holder) mask_net = NeuroMask(model, coeffs=( 0.4, 0.35, FLAGS.smooth_lambda), temp=1, is_cifar=True) mask_net.init_model(sess) pred_ = sess.run(model_out, feed_dict={input_holder: [test_img]}) print('correct label = ', np.argmax( cifar_data.test_labels[test_idx], axis=0)) mask_result = mask_net.explain( sess, test_img, target_label=None, iters=FLAGS.num_iters) final_mask = mask_result[-1][:, :, 0] display_img(test_img, final_mask) plt.show() fig, axes = plt.subplots(6, 10) axes = axes.ravel() for i in range(60): axes[i].imshow(cifar_data.test_data[i]+0.5) axes[i].set_title('idx = {}'.format(i)) plt.show()
[ "setup_cifar.CIFARModel", "matplotlib.pyplot.show", "numpy.argmax", "tensorflow.reset_default_graph", "tensorflow.Session", "setup_cifar.CIFAR", "neuromask.NeuroMask", "tensorflow.placeholder", "matplotlib.pyplot.subplots" ]
[((813, 820), 'setup_cifar.CIFAR', 'CIFAR', ([], {}), '()\n', (818, 820), False, 'from setup_cifar import CIFAR, CIFARModel\n'), ((893, 917), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (915, 917), True, 'import tensorflow as tf\n'), ((1615, 1634), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(6)', '(10)'], {}), '(6, 10)\n', (1627, 1634), True, 'import matplotlib.pyplot as plt\n'), ((1767, 1777), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1775, 1777), True, 'import matplotlib.pyplot as plt\n'), ((480, 515), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(10, 4)'}), '(1, 2, figsize=(10, 4))\n', (492, 515), True, 'import matplotlib.pyplot as plt\n'), ((924, 936), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (934, 936), True, 'import tensorflow as tf\n'), ((958, 998), 'setup_cifar.CIFARModel', 'CIFARModel', (['"""cifar10_model"""', 'sess', '(False)'], {}), "('cifar10_model', sess, False)\n", (968, 998), False, 'from setup_cifar import CIFAR, CIFARModel\n'), ((1018, 1070), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, 32, 32, 3]'], {'name': '"""x"""'}), "(tf.float32, [1, 32, 32, 3], name='x')\n", (1032, 1070), True, 'import tensorflow as tf\n'), ((1123, 1208), 'neuromask.NeuroMask', 'NeuroMask', (['model'], {'coeffs': '(0.4, 0.35, FLAGS.smooth_lambda)', 'temp': '(1)', 'is_cifar': '(True)'}), '(model, coeffs=(0.4, 0.35, FLAGS.smooth_lambda), temp=1, is_cifar=True\n )\n', (1132, 1208), False, 'from neuromask import NeuroMask\n'), ((1591, 1601), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1599, 1601), True, 'import matplotlib.pyplot as plt\n'), ((1343, 1394), 'numpy.argmax', 'np.argmax', (['cifar_data.test_labels[test_idx]'], {'axis': '(0)'}), '(cifar_data.test_labels[test_idx], axis=0)\n', (1352, 1394), True, 'import numpy as np\n')]
import tensorflow as tf import numpy as np import tflearn def running_mean(net, sizes, penalties, out_classes, name=None): """ Args: net -> (max_len, batch_size, num_classes) sizes -> sizes of running mean window penalties -> penalty per size out_classes -> number of output classes """ with tf.name_scope("running_mean"): net = tf.transpose(net, [1, 0, 2]) net = tf.nn.log_softmax(net) # net.set_shape([4, 2, 5]) # (batch_size, max_len, num_classes) out = [] for size, penalty in zip(sizes, penalties): with tf.name_scope("size_%d" % size): filters = np.zeros([size, out_classes, out_classes], dtype=np.float32) for i in range(out_classes): filters[:, i, i] = 1 reg = tf.nn.conv1d(net, filters, 1, 'VALID') reg = tf.exp( reg ) # Likelihood of having size consecutive symbols on output reg = tf.reduce_sum(reg, axis=[2]) # Sum over all symbols reg = tf.reduce_mean( reg ) # and find mean per sequence per batch out.append(penalty * reg) return tf.reduce_sum(out) def read_model_vars(model, *args, **kwargs): try: model.init_session() model.restore(*args, **kwargs) sol = {} with model.g.as_default(): vars = tf.trainable_variables() for var, val in zip(vars, model.sess.run(vars)): sol[var.name] = val return sol finally: model.close_session() def __running_mean_test(): with tf.Session() as sess: x = tf.placeholder(tf.float32) net = running_mean(x, [1], [1], 5) # batch_size = 2 # max_len = 4 # num_classes = 5 tin = np.arange(4 * 2 * 5).reshape([4, 2, 5]) print(tin) print(sess.run(net, feed_dict={x: tin})) def central_cut(net, block_size, shrink_factor): output_shape = net.get_shape().as_list() output_shape[1] = None cut_size = tf.shape(net)[1] - tf.div(block_size, shrink_factor) with tf.control_dependencies([ tf.cond( tflearn.get_training_mode(), lambda: tf.assert_equal( tf.mod(cut_size, 2), 0, name="cut_size_assert"), lambda: tf.no_op() ), tf.assert_non_negative(cut_size) ] ): cut_size = tf.div(cut_size, 2) net = tf.slice( net, [0, cut_size, 0], [-1, tf.div(block_size, shrink_factor), -1], name="Cutting" ) net.set_shape(output_shape) return net def atrous_conv1d(value, filters, rate, padding="SAME", name=None): with tf.name_scope(name, "atrous_conv1d", [value, filters]) as name: value = tf.convert_to_tensor(value, name="value") filters = tf.convert_to_tensor(filters, name="filters") if rate == 1: return tf.nn.conv1d(value, filters, 1, padding) if value.get_shape().is_fully_defined(): value_shape = value.get_shape().as_list() else: value_shape = tf.shape(value) add = (-value_shape[1] % rate + rate) % rate pad = [[0, add]] crop = [[0, add]] value = tf.space_to_batch_nd( input=value, paddings=pad, block_shape=[rate] ) value = tf.nn.conv1d(value, filters, 1, padding, name=name) value = tf.batch_to_space_nd( input=value, crops=crop, block_shape=[rate] ) return value def dense2d_to_sparse(dense_input, length, name=None, dtype=None): with tf.name_scope(name, "dense2d_to_sparse"): num_batches = dense_input.get_shape()[0] indices = [ tf.stack([tf.fill([length[x]], x), tf.range(length[x])], axis=1) for x in range(num_batches) ] indices = tf.concat(axis=0, values=indices) indices = tf.to_int64(indices) values = [ tf.squeeze(tf.slice(dense_input, [x, 0], [1, length[x]]), axis=[0]) for x in range(num_batches) ] values = tf.concat(axis=0, values=values) if dtype is not None: values = tf.cast(values, dtype) return tf.SparseTensor( indices, values, tf.to_int64(tf.shape(dense_input)) ) # (2) use SELUs def selu(x): with tf.name_scope('selu'): alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 return scale * tf.where(x >= 0.0, x, alpha * tf.nn.elu(x)) # (3) initialize weights with stddev sqrt(1/n) # e.g. use: # selu_initializer = tf.layers.variance_scaling_initializer(factor=1.0, mode='FAN_IN') if __name__ == '__main__': from model_small import model print(read_model_vars(model)) X = tf.constant( np.array([1, 2, 3, 4, 5, 6, 7]).reshape(1, 7, 1), dtype=tf.float32 ) kernel = tf.constant( np.array([100, 10, 1]).reshape(3, 1, 1), dtype=tf.float32 ) y = atrous_conv1d(X, kernel, 2, "SAME") sess = tf.Session() sess.run(tf.global_variables_initializer()) gg = sess.run(y) print(gg, gg.shape)
[ "tensorflow.batch_to_space_nd", "tensorflow.reduce_sum", "tensorflow.space_to_batch_nd", "tensorflow.trainable_variables", "model_small.model.restore", "numpy.arange", "tensorflow.nn.conv1d", "tflearn.get_training_mode", "tensorflow.nn.elu", "tensorflow.nn.log_softmax", "tensorflow.to_int64", ...
[((5194, 5206), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (5204, 5206), True, 'import tensorflow as tf\n'), ((346, 375), 'tensorflow.name_scope', 'tf.name_scope', (['"""running_mean"""'], {}), "('running_mean')\n", (359, 375), True, 'import tensorflow as tf\n'), ((391, 419), 'tensorflow.transpose', 'tf.transpose', (['net', '[1, 0, 2]'], {}), '(net, [1, 0, 2])\n', (403, 419), True, 'import tensorflow as tf\n'), ((434, 456), 'tensorflow.nn.log_softmax', 'tf.nn.log_softmax', (['net'], {}), '(net)\n', (451, 456), True, 'import tensorflow as tf\n'), ((1312, 1330), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['out'], {}), '(out)\n', (1325, 1330), True, 'import tensorflow as tf\n'), ((1395, 1415), 'model_small.model.init_session', 'model.init_session', ([], {}), '()\n', (1413, 1415), False, 'from model_small import model\n'), ((1424, 1454), 'model_small.model.restore', 'model.restore', (['*args'], {}), '(*args, **kwargs)\n', (1437, 1454), False, 'from model_small import model\n'), ((1692, 1713), 'model_small.model.close_session', 'model.close_session', ([], {}), '()\n', (1711, 1713), False, 'from model_small import model\n'), ((1752, 1764), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1762, 1764), True, 'import tensorflow as tf\n'), ((1786, 1812), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (1800, 1812), True, 'import tensorflow as tf\n'), ((2210, 2243), 'tensorflow.div', 'tf.div', (['block_size', 'shrink_factor'], {}), '(block_size, shrink_factor)\n', (2216, 2243), True, 'import tensorflow as tf\n'), ((2554, 2573), 'tensorflow.div', 'tf.div', (['cut_size', '(2)'], {}), '(cut_size, 2)\n', (2560, 2573), True, 'import tensorflow as tf\n'), ((2827, 2881), 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""atrous_conv1d"""', '[value, filters]'], {}), "(name, 'atrous_conv1d', [value, filters])\n", (2840, 2881), True, 'import tensorflow as tf\n'), ((2907, 2948), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['value'], {'name': '"""value"""'}), "(value, name='value')\n", (2927, 2948), True, 'import tensorflow as tf\n'), ((2967, 3012), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['filters'], {'name': '"""filters"""'}), "(filters, name='filters')\n", (2987, 3012), True, 'import tensorflow as tf\n'), ((3378, 3445), 'tensorflow.space_to_batch_nd', 'tf.space_to_batch_nd', ([], {'input': 'value', 'paddings': 'pad', 'block_shape': '[rate]'}), '(input=value, paddings=pad, block_shape=[rate])\n', (3398, 3445), True, 'import tensorflow as tf\n'), ((3485, 3536), 'tensorflow.nn.conv1d', 'tf.nn.conv1d', (['value', 'filters', '(1)', 'padding'], {'name': 'name'}), '(value, filters, 1, padding, name=name)\n', (3497, 3536), True, 'import tensorflow as tf\n'), ((3554, 3619), 'tensorflow.batch_to_space_nd', 'tf.batch_to_space_nd', ([], {'input': 'value', 'crops': 'crop', 'block_shape': '[rate]'}), '(input=value, crops=crop, block_shape=[rate])\n', (3574, 3619), True, 'import tensorflow as tf\n'), ((3742, 3782), 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""dense2d_to_sparse"""'], {}), "(name, 'dense2d_to_sparse')\n", (3755, 3782), True, 'import tensorflow as tf\n'), ((4009, 4042), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(0)', 'values': 'indices'}), '(axis=0, values=indices)\n', (4018, 4042), True, 'import tensorflow as tf\n'), ((4061, 4081), 'tensorflow.to_int64', 'tf.to_int64', (['indices'], {}), '(indices)\n', (4072, 4081), True, 'import tensorflow as tf\n'), ((4249, 4281), 'tensorflow.concat', 'tf.concat', ([], {'axis': '(0)', 'values': 'values'}), '(axis=0, values=values)\n', (4258, 4281), True, 'import tensorflow as tf\n'), ((4504, 4525), 'tensorflow.name_scope', 'tf.name_scope', (['"""selu"""'], {}), "('selu')\n", (4517, 4525), True, 'import tensorflow as tf\n'), ((5220, 5253), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (5251, 5253), True, 'import tensorflow as tf\n'), ((1485, 1505), 'model_small.model.g.as_default', 'model.g.as_default', ([], {}), '()\n', (1503, 1505), False, 'from model_small import model\n'), ((1526, 1550), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (1548, 1550), True, 'import tensorflow as tf\n'), ((2191, 2204), 'tensorflow.shape', 'tf.shape', (['net'], {}), '(net)\n', (2199, 2204), True, 'import tensorflow as tf\n'), ((2631, 2664), 'tensorflow.div', 'tf.div', (['block_size', 'shrink_factor'], {}), '(block_size, shrink_factor)\n', (2637, 2664), True, 'import tensorflow as tf\n'), ((3055, 3095), 'tensorflow.nn.conv1d', 'tf.nn.conv1d', (['value', 'filters', '(1)', 'padding'], {}), '(value, filters, 1, padding)\n', (3067, 3095), True, 'import tensorflow as tf\n'), ((3240, 3255), 'tensorflow.shape', 'tf.shape', (['value'], {}), '(value)\n', (3248, 3255), True, 'import tensorflow as tf\n'), ((4334, 4356), 'tensorflow.cast', 'tf.cast', (['values', 'dtype'], {}), '(values, dtype)\n', (4341, 4356), True, 'import tensorflow as tf\n'), ((624, 655), 'tensorflow.name_scope', 'tf.name_scope', (["('size_%d' % size)"], {}), "('size_%d' % size)\n", (637, 655), True, 'import tensorflow as tf\n'), ((684, 744), 'numpy.zeros', 'np.zeros', (['[size, out_classes, out_classes]'], {'dtype': 'np.float32'}), '([size, out_classes, out_classes], dtype=np.float32)\n', (692, 744), True, 'import numpy as np\n'), ((889, 927), 'tensorflow.nn.conv1d', 'tf.nn.conv1d', (['net', 'filters', '(1)', '"""VALID"""'], {}), "(net, filters, 1, 'VALID')\n", (901, 927), True, 'import tensorflow as tf\n'), ((950, 961), 'tensorflow.exp', 'tf.exp', (['reg'], {}), '(reg)\n', (956, 961), True, 'import tensorflow as tf\n'), ((1081, 1109), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['reg'], {'axis': '[2]'}), '(reg, axis=[2])\n', (1094, 1109), True, 'import tensorflow as tf\n'), ((1156, 1175), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['reg'], {}), '(reg)\n', (1170, 1175), True, 'import tensorflow as tf\n'), ((1589, 1609), 'model_small.model.sess.run', 'model.sess.run', (['vars'], {}), '(vars)\n', (1603, 1609), False, 'from model_small import model\n'), ((1945, 1965), 'numpy.arange', 'np.arange', (['(4 * 2 * 5)'], {}), '(4 * 2 * 5)\n', (1954, 1965), True, 'import numpy as np\n'), ((2489, 2521), 'tensorflow.assert_non_negative', 'tf.assert_non_negative', (['cut_size'], {}), '(cut_size)\n', (2511, 2521), True, 'import tensorflow as tf\n'), ((4125, 4170), 'tensorflow.slice', 'tf.slice', (['dense_input', '[x, 0]', '[1, length[x]]'], {}), '(dense_input, [x, 0], [1, length[x]])\n', (4133, 4170), True, 'import tensorflow as tf\n'), ((4431, 4452), 'tensorflow.shape', 'tf.shape', (['dense_input'], {}), '(dense_input)\n', (4439, 4452), True, 'import tensorflow as tf\n'), ((4968, 4999), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7]'], {}), '([1, 2, 3, 4, 5, 6, 7])\n', (4976, 4999), True, 'import numpy as np\n'), ((5075, 5097), 'numpy.array', 'np.array', (['[100, 10, 1]'], {}), '([100, 10, 1])\n', (5083, 5097), True, 'import numpy as np\n'), ((2308, 2335), 'tflearn.get_training_mode', 'tflearn.get_training_mode', ([], {}), '()\n', (2333, 2335), False, 'import tflearn\n'), ((3876, 3899), 'tensorflow.fill', 'tf.fill', (['[length[x]]', 'x'], {}), '([length[x]], x)\n', (3883, 3899), True, 'import tensorflow as tf\n'), ((3923, 3942), 'tensorflow.range', 'tf.range', (['length[x]'], {}), '(length[x])\n', (3931, 3942), True, 'import tensorflow as tf\n'), ((4680, 4692), 'tensorflow.nn.elu', 'tf.nn.elu', (['x'], {}), '(x)\n', (4689, 4692), True, 'import tensorflow as tf\n'), ((2459, 2469), 'tensorflow.no_op', 'tf.no_op', ([], {}), '()\n', (2467, 2469), True, 'import tensorflow as tf\n'), ((2390, 2409), 'tensorflow.mod', 'tf.mod', (['cut_size', '(2)'], {}), '(cut_size, 2)\n', (2396, 2409), True, 'import tensorflow as tf\n')]
"""Read, write, create Brainvoyager SSM file format.""" import struct import numpy as np # ============================================================================= def read_ssm(filename): """Read Brainvoyager SSM (surface to surface mapping) file. Parameters ---------- filename : string Path to file. Returns ------- header : dictionary TODO. data : 3D numpy.array TODO. """ header = dict() with open(filename, 'rb') as f: # --------------------------------------------------------------------- # Header # --------------------------------------------------------------------- # Expected binary data: short int (2 bytes) data, = struct.unpack('<h', f.read(2)) header["File version"] = data # Expected binary data: int (4 bytes) data, = struct.unpack('<i', f.read(4)) header["Nr vertices 1"] = data data, = struct.unpack('<i', f.read(4)) header["Nr vertices 2"] = data # Referenced mesh number of vertices # --------------------------------------------------------------------- # Data # --------------------------------------------------------------------- data_ssm = np.zeros(header["Nr vertices 1"]) for i in range(header["Nr vertices 1"]): data_ssm[i], = struct.unpack('<f', f.read(4)) return header, data_ssm
[ "numpy.zeros" ]
[((1269, 1302), 'numpy.zeros', 'np.zeros', (["header['Nr vertices 1']"], {}), "(header['Nr vertices 1'])\n", (1277, 1302), True, 'import numpy as np\n')]
# %% Integer opcode computer from __future__ import annotations from collections import defaultdict from itertools import tee, islice from typing import Iterable, List from dataclasses import dataclass import matplotlib.pyplot as plt import numpy as np @dataclass class Point: x: int y: int def distance_to(self, p: Point) -> int: return abs(p.x - self.x) + abs(p.y - self.y) def __iter__(self): yield self.y yield self.x def __add__(self, other: Point) -> Point: return self.__class__(self.x + other.x, self.y + other.y) def __hash__(self): return hash((self.x, self.y)) def get_parameters(seq, pointer, opmodes, number, base): result = [] for i in range(number): if opmodes[i] == 0: result.append(seq[seq[pointer + i + 1]]) elif opmodes[i] == 1: result.append(seq[pointer + i + 1]) elif opmodes[i] == 2: result.append(seq[seq[pointer + i + 1] + base]) else: print("invalid opmode") return result def run_program(program_code: List[int], program_input: Iterable[int]) -> Iterable[int]: increments = {1: 4, 2: 4, 3: 2, 4: 2, 5: 3, 6: 3, 7: 4, 8: 4, 9: 2} input_iter = iter(program_input) pointer = 0 base = 0 while (opcode := program_code[pointer] % 100) != 99: opmodes = [program_code[pointer] // 10 ** n % 10 for n in range(2, 5)] if opcode == 1 or opcode == 2: op1, op2 = get_parameters(program_code, pointer, opmodes, 2, base) idx = program_code[pointer + 3] + (base if opmodes[2] else 0) program_code[idx] = op1 + op2 if opcode == 1 else op1 * op2 elif opcode == 3: idx = program_code[pointer + 1] + (base if opmodes[0] else 0) program_code[idx] = next(input_iter) elif opcode == 4: out = get_parameters(program_code, pointer, opmodes, 1, base)[0] yield out elif opcode == 5 or opcode == 6: op1, op2 = get_parameters(program_code, pointer, opmodes, 2, base) switch = bool(op1) if opcode == 5 else not bool(op1) if switch: pointer = op2 continue elif opcode == 7 or opcode == 8: op1, op2 = get_parameters(program_code, pointer, opmodes, 2, base) switch = op1 < op2 if opcode == 7 else op1 == op2 idx = program_code[pointer + 3] + (base if opmodes[2] else 0) program_code[idx] = 1 if switch else 0 elif opcode == 9: op = get_parameters(program_code, pointer, opmodes, 1, base)[0] base += op else: print("Unknown opcode") pointer += increments[opcode] with open("day_11.input", "r") as input_data: program = defaultdict( int, {i: int(x) for i, x in enumerate(input_data.readline().split(","))} ) def run_robot(robot_program, init): def input_generator(region, init_value): yield init_value while True: yield region.get(pos, 0) direction = "U" pos = Point(0, 0) region_map = {} directions = { ("U", 0): "L", ("U", 1): "R", ("L", 0): "D", ("R", 1): "D", ("D", 0): "R", ("D", 1): "L", ("R", 0): "U", ("L", 1): "U", } delta_move = { "U": Point(0, -1), "L": Point(-1, 0), "D": Point(0, 1), "R": Point(1, 0), } a, b = tee(run_program(robot_program, input_generator(region_map, init))) next(b, None) for color, move in islice(zip(a, b), None, None, 2): region_map[pos] = color direction = directions[(direction, move)] pos += delta_move[direction] points = np.array([list(p) for p, value in region_map.items() if value]) points -= np.min(points, axis=0) reg = np.zeros(np.max(points, axis=0) + 1) reg[points[:, 0], points[:, 1]] = 1 return len(region_map), reg num_paints, registration = run_robot(program.copy(), 0) print(f"Part 1: Number of painted fields is {num_paints}") plt.imshow(registration) plt.show() num_paints, registration = run_robot(program.copy(), 1) print(f"Part 2: Number of painted fields is {num_paints}") plt.imshow(registration) plt.show()
[ "matplotlib.pyplot.imshow", "numpy.min", "numpy.max", "matplotlib.pyplot.show" ]
[((4104, 4128), 'matplotlib.pyplot.imshow', 'plt.imshow', (['registration'], {}), '(registration)\n', (4114, 4128), True, 'import matplotlib.pyplot as plt\n'), ((4129, 4139), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4137, 4139), True, 'import matplotlib.pyplot as plt\n'), ((4256, 4280), 'matplotlib.pyplot.imshow', 'plt.imshow', (['registration'], {}), '(registration)\n', (4266, 4280), True, 'import matplotlib.pyplot as plt\n'), ((4281, 4291), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4289, 4291), True, 'import matplotlib.pyplot as plt\n'), ((3844, 3866), 'numpy.min', 'np.min', (['points'], {'axis': '(0)'}), '(points, axis=0)\n', (3850, 3866), True, 'import numpy as np\n'), ((3886, 3908), 'numpy.max', 'np.max', (['points'], {'axis': '(0)'}), '(points, axis=0)\n', (3892, 3908), True, 'import numpy as np\n')]
# 3rd party import neurokit2 as nk from neurokit2 import signal_period import datetime import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from tqdm import tqdm plt.rcParams['figure.figsize'] = [30, 25] # Bigger images pd.set_option('display.width', 400) pd.set_option('display.max_columns', 25) np.set_printoptions(linewidth=400) # local from preprocess_mit import read_mit_bit_files from preprocess_ludb import read_ludb_files def pantompkins1985(ecg, sampling_rate): signal, info = nk.ecg_peaks(ecg, sampling_rate=sampling_rate, method="pantompkins1985") return info["ECG_R_Peaks"] def engzeemod2012(ecg, sampling_rate): signal, info = nk.ecg_peaks(ecg, sampling_rate=sampling_rate, method="engzeemod2012") return info["ECG_R_Peaks"] def christov2004(ecg, sampling_rate): signal, info = nk.ecg_peaks(ecg, sampling_rate=sampling_rate, method="christov2004") return info["ECG_R_Peaks"] def pantompkins1985_correction(ecg, sampling_rate): signal, info = nk.ecg_peaks(ecg, sampling_rate=sampling_rate, method="pantompkins1985", correct_artifacts=True) return info["ECG_R_Peaks"] def engzeemod2012_correction(ecg, sampling_rate): signal, info = nk.ecg_peaks(ecg, sampling_rate=sampling_rate, method="engzeemod2012", correct_artifacts=True) return info["ECG_R_Peaks"] def christov2004_correction(ecg, sampling_rate): signal, info = nk.ecg_peaks(ecg, sampling_rate=sampling_rate, method="christov2004", correct_artifacts=True) return info["ECG_R_Peaks"] def benchmark_ecg_preprocessing(function, ecg, rpeaks=None, sampling_rate=1000, error_correction=False): """Benchmark ECG preprocessing pipelines. Parameters ---------- function : function Must be a Python function which first argument is the ECG signal and which has a ``sampling_rate`` argument. ecg : pd.DataFrame or str The path to a folder where you have an `ECGs.csv` file or directly its loaded DataFrame. Such file can be obtained by running THIS SCRIPT (TO COMPLETE). rpeaks : pd.DataFrame or str The path to a folder where you have an `Rpeaks.csv` fils or directly its loaded DataFrame. Such file can be obtained by running THIS SCRIPT (TO COMPLETE). sampling_rate : int The sampling frequency of `ecg_signal` (in Hz, i.e., samples/second). Only used if ``ecgs`` and ``rpeaks`` are single vectors. Returns -------- pd.DataFrame A DataFrame containing the results of the benchmarking Examples -------- >>> import neurokit2 as nk >>> >>> # Define a preprocessing routine >>> def function(ecg, sampling_rate): >>> signal, info = nk.ecg_peaks(ecg, method='engzeemod2012', sampling_rate=sampling_rate) >>> return info["ECG_R_Peaks"] >>> >>> # Synthetic example >>> ecg = nk.ecg_simulate(duration=20, sampling_rate=200) >>> true_rpeaks = nk.ecg_peaks(ecg, sampling_rate=200)[1]["ECG_R_Peaks"] >>> >>> nk.benchmark_ecg_preprocessing(function, ecg, true_rpeaks, sampling_rate=200) >>> >>> # Example using database (commented-out) >>> # nk.benchmark_ecg_preprocessing(function, r'path/to/GUDB_database') """ # find data if rpeaks is None: rpeaks = ecg if isinstance(ecg, str): ecg = pd.read_csv(ecg + "/ECGs.csv") if isinstance(rpeaks, str): rpeaks = pd.read_csv(rpeaks + "/Rpeaks.csv") if isinstance(ecg, pd.DataFrame): results, evaluations = _benchmark_ecg_preprocessing_databases(function, ecg, rpeaks, error_correction=error_correction) else: results, evaluations = _benchmark_ecg_preprocessing(function, ecg, rpeaks, sampling_rate=sampling_rate, error_correction=error_correction) return results, evaluations # ============================================================================= # Utils # ============================================================================= def _benchmark_ecg_preprocessing_databases(function, ecgs, rpeaks, error_correction): """A wrapper over _benchmark_ecg_preprocessing when the input is a database.""" # Run algorithms results = [] evaluations = [] for participant in ecgs["Participant"].unique(): for database in ecgs[ecgs["Participant"] == participant]["Database"].unique(): # Extract the right slice of data ecg_slice = ecgs[(ecgs["Participant"] == participant) & (ecgs["Database"] == database)] rpeaks_slice = rpeaks[(rpeaks["Participant"] == participant) & (rpeaks["Database"] == database)] sampling_rate = ecg_slice["Sampling_Rate"].unique()[0] # Extract values ecg = ecg_slice["ECG"].values rpeak = rpeaks_slice["Rpeaks"].values # Run benchmark result, evaluation = _benchmark_ecg_preprocessing(function, ecg, rpeak, sampling_rate, error_correction) # Add info result["Participant"] = participant result["Database"] = database evaluation["Participant"] = participant evaluation["Database"] = database results.append(result) evaluations.append(evaluation) return pd.concat(results), pd.concat(evaluations) def _benchmark_ecg_preprocessing(function, ecg, rpeak, sampling_rate=1000, error_correction=False): # Apply function t0 = datetime.datetime.now() try: if not error_correction: found_rpeaks = function(ecg, sampling_rate=sampling_rate) else: found_rpeaks = function(ecg, sampling_rate=sampling_rate) duration = (datetime.datetime.now() - t0).total_seconds() # In case of failure except Exception as error: # pylint: disable=broad-except return pd.DataFrame( { "Sampling_Rate": [sampling_rate], "Duration": [np.nan], "Score": [np.nan], "Recording_Length": [len(ecg) / sampling_rate / 60], "Error": str(error), } ) # Compare R peaks score, error = benchmark_ecg_compareRpeaks(rpeak, found_rpeaks, sampling_rate=sampling_rate) evaluation = evaluate_qrs_detectors(ecg, rpeak, found_rpeaks, sampling_rate, tolerance=0.05, show_plot=False) return pd.DataFrame( { "Sampling_Rate": [sampling_rate], "Duration": [duration], "Score": [score], "Recording_Length": [len(ecg) / sampling_rate / 60], "Error": error, }, ), evaluation # ============================================================================= # Comparison methods # ============================================================================= def benchmark_ecg_compareRpeaks(true_rpeaks, found_rpeaks, sampling_rate=250): # Failure to find sufficient R-peaks if len(found_rpeaks) <= 3: return np.nan, "R-peaks detected <= 3" length = np.max(np.concatenate([true_rpeaks, found_rpeaks])) true_interpolated = signal_period( true_rpeaks, sampling_rate=sampling_rate, desired_length=length, interpolation_method="linear" ) found_interpolated = signal_period( found_rpeaks, sampling_rate=sampling_rate, desired_length=length, interpolation_method="linear" ) return np.mean(np.abs(found_interpolated - true_interpolated)), "None" def evaluate_qrs_detectors(signal, reference_rpeaks, detected_rpeaks, sampling_frequency, tolerance, show_plot=False): # Threshold for 100ms # tol = 0.1 # 100 ms # Fs_mit = mit_metadata["Sampling Frequency"] # Fs_ludb = ludb_metadata["Sampling Frequency"] # N_mit = int((tol * int(Fs_mit)) + 1) # Number of samples for given time of 100ms and frequency # N_ludb = int((tol * int(Fs_ludb)) + 1) # Number of samples for given time of 100ms and frequency def compute_confusion_matrix_and_delays(frames_detections, frames_annotations, tolerance_frames): """ compute the confusion matrix of the evaluation. For each annotation, consider a interval of tolerance around it, and check if there is a detection. If Yes : correct detection (TP) and the delays between the corresponding annotation and it is measured, if No : missed complex (FN). Every detections which were not in a tolerance interval around an annotation is a false detection (FP). :param frames_detections: list of QRS detections (localisations) of the chosen algorithm :type frames_detections: list(int) :param frames_annotations: list of beat annotations (localisations) :type frames_annotations: list(int) :param tolerance_frames: number of frames corresponding to the value of the tolerance in milliseconds :type tolerance_frames: int :return: list of calculated criteria and the list of delays between annotations and their corresponding correct detections :rtype: tuple(list(int),list(int)) """ true_pos = 0 false_neg = 0 delays = [] for fr in frames_annotations: interval = range(fr - tolerance_frames, fr + tolerance_frames + 1) corresponding_detections_frame = list(set(interval).intersection(frames_detections)) if len(corresponding_detections_frame) > 0: true_pos += 1 delays.append(corresponding_detections_frame[0] - fr) else: false_neg += 1 false_pos = len(frames_detections) - true_pos return [true_pos, false_pos, false_neg], delays tolerance = int(tolerance * sampling_frequency) + 1 # Number of samples for given time of 0.05s (50ms) and frequency [TP, FP, FN], delays = compute_confusion_matrix_and_delays(reference_rpeaks, detected_rpeaks, tolerance) TN = len(signal) - (TP + FP + FN) # output metrics performance = float(TP) / len(reference_rpeaks) # Test performance = TP / len(reference r-peaks) accuracy = float(TP) / (TP + FP) # Positive Predictive Value (PPV) = TP / TP + FP error = float(FP) / (TP + FP) # Error rate = FP / (TP + FP) if TP and FN != 0: sensitivity = float(TP) / (TP + FN) # Sensitivity (Sens) = TP / TP + FN else: sensitivity = 1. if TN and FP != 0: specificity = float(TN) / (TN + FP) # Specificity (Spec) = TN / TN + FP else: specificity = 1. # calculate mean and std. delay from detected to reference peaks delays = np.array(delays, dtype='float') if len(delays) == 0: mdev = np.nan sdev = np.nan elif len(delays) == 1: mdev = np.mean(delays) sdev = 0. else: mdev = np.mean(delays) sdev = np.std(delays, ddof=1) evaluation = pd.DataFrame({"TP": TP, "FN": FN, "FP": FP, "TN": TN, "Positive Prediction Value": [accuracy], "Sensitivity": [sensitivity], "Specificity": [specificity], "Mean Error (ms)": [mdev], "Std. Mean Error (ms)": [sdev]}) if show_plot: # Confusion matrix cf_matrix = np.array([[TP, FN], [FP, TN]]) group_names = ['True Pos', 'False Neg', 'False Pos', 'True Neg'] group_counts = ["{0:0.0f}".format(value) for value in cf_matrix.flatten()] group_percentages = ["{0:.2%}".format(value) for value in cf_matrix.flatten() / np.sum(cf_matrix)] labels = [f"{v1}\n{v2}\n{v3}" for v1, v2, v3 in zip(group_names, group_counts, group_percentages)] labels = np.asarray(labels).reshape(2, 2) sns.heatmap(cf_matrix, annot=labels, fmt='', cmap='Blues') plt.show() # PPV, Sens, Sec, mean error boxplot #sns.barplot(x="Algorithms", y="", data=evaluation[["Positive Prediction Value", "Sensitivity", "Specificity"]]) #sns.barplot(x="Algorithms", y="", data=evaluation[["Mean Error (s)", "Std. Mean Error"]]) #plt.show() return evaluation def distort_signal(signal): # Distort the signal (add noise, linear trend, artifacts etc.) return nk.signal_distort(signal=signal.to_numpy(), noise_amplitude=0.1, noise_frequency=[5, 10, 20], powerline_amplitude=0.05, artifacts_amplitude=0.3, artifacts_number=3, linear_drift=0.5) ### Run the Benchmarking ## Note: This takes a long time (several hours). # load ECG data and annotations from mit-bih database into pandas dataframes mit_data, mit_anno, mit_metadata = read_mit_bit_files() # load ECG data and annotationsfrom ludb database into pandas dataframes ludb_data, ludb_anno, ludb_metadata = read_ludb_files() # Concatenate them together ecgs = [mit_data, ludb_data] rpeaks = [mit_anno, ludb_anno] metadatas = [mit_metadata, ludb_metadata] functions = [pantompkins1985, engzeemod2012, christov2004] correction_functions = [pantompkins1985_correction, engzeemod2012_correction, christov2004_correction] results = [] evaluations = [] for method in correction_functions: for i in range(1,len(ecgs)): if False: ecgs[i].loc[:, "ECG"] = distort_signal(ecgs[i]["ECG"]) ecgs[i].loc[:, "ECG"] = nk.ecg_clean(ecgs[i]["ECG"], sampling_rate=int(metadatas[i]["Sampling Frequency"]), method=method.__name__.replace("_correction", "")) result, evaluation = benchmark_ecg_preprocessing(method, ecgs[i], rpeaks[i]) result["Method"] = method.__name__ evaluation["Method"] = method.__name__ results.append(result) evaluations.append(evaluation) results = pd.concat(results).reset_index(drop=True) evaluations = pd.concat(evaluations).reset_index(drop=True) print(results) print(evaluations) print(results.describe()) print(evaluations.describe()) plt.rcParams['figure.figsize'] = [15, 9] # Bigger images # Errors and bugs # Plot a bar chart #sns.set_style("dark") plot = sns.barplot(data=results, x="Method", y="Score", hue="Database", ci=None) # result[["Duration", "Score", "Error"]] plt.show() plot = sns.barplot(data=results, x="Method", y="Duration", hue="Database", ci=None) # result[["Duration", "Score", "Error"]] plt.show() # Confusion matrix cf_matrix cf_matrix = np.array([[evaluations["TP"].sum(), evaluations["FN"].sum()], [evaluations["FP"].sum(), evaluations["TN"].sum()]]) group_names = ['True Pos', 'False Neg', 'False Pos', 'True Neg'] group_counts = ["{0:0.0f}".format(value) for value in cf_matrix.flatten()] group_percentages = ["{0:.2%}".format(value) for value in cf_matrix.flatten() / np.sum(cf_matrix)] labels = [f"{v1}\n{v2}\n{v3}" for v1, v2, v3 in zip(group_names, group_counts, group_percentages)] labels = np.asarray(labels).reshape(2, 2) sns.heatmap(cf_matrix, annot=labels, fmt='', cmap='Blues') plt.show() plot = sns.barplot(data=evaluations, x="Method", y="Positive Prediction Value", hue="Database", ci=None) # result[["Duration", "Score", "Error"]] plt.show() plot = sns.barplot(data=evaluations, x="Method", y="Sensitivity", hue="Database", ci=None) # result[["Duration", "Score", "Error"]] plt.show() plot = sns.barplot(data=evaluations, x="Method", y="Specificity", hue="Database", ci=None) # result[["Duration", "Score", "Error"]] plt.show() plot = sns.barplot(data=evaluations, x="Method", y="Mean Error (ms)", hue="Database", ci=None) # result[["Duration", "Score", "Error"]] plt.show() plot = sns.barplot(data=evaluations, x="Method", y="Std. Mean Error (ms)", hue="Database", ci=None) # result[["Duration", "Score", "Error"]] plt.show() # Results methods = ["pantompkins1985", "engzeemod2012", "christov2004"] color = {"pantompkins1985": "#E91E63", "engzeemod2012": "#4CAF50", "christov2004": "#2196F3"} # Errors and bugs #sns.barplot(x=results["Method"], y="Evaluation", hue="Detector", # data=[results["Duration"][:199], results["Score"][:199], results["Error"][:199]])
[ "preprocess_mit.read_mit_bit_files", "seaborn.heatmap", "numpy.abs", "numpy.sum", "pandas.read_csv", "neurokit2.ecg_peaks", "numpy.mean", "pandas.set_option", "pandas.DataFrame", "numpy.set_printoptions", "neurokit2.signal_period", "numpy.std", "preprocess_ludb.read_ludb_files", "datetime....
[((273, 308), 'pandas.set_option', 'pd.set_option', (['"""display.width"""', '(400)'], {}), "('display.width', 400)\n", (286, 308), True, 'import pandas as pd\n'), ((310, 350), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(25)'], {}), "('display.max_columns', 25)\n", (323, 350), True, 'import pandas as pd\n'), ((352, 386), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'linewidth': '(400)'}), '(linewidth=400)\n', (371, 386), True, 'import numpy as np\n'), ((13010, 13030), 'preprocess_mit.read_mit_bit_files', 'read_mit_bit_files', ([], {}), '()\n', (13028, 13030), False, 'from preprocess_mit import read_mit_bit_files\n'), ((13146, 13163), 'preprocess_ludb.read_ludb_files', 'read_ludb_files', ([], {}), '()\n', (13161, 13163), False, 'from preprocess_ludb import read_ludb_files\n'), ((14416, 14489), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'results', 'x': '"""Method"""', 'y': '"""Score"""', 'hue': '"""Database"""', 'ci': 'None'}), "(data=results, x='Method', y='Score', hue='Database', ci=None)\n", (14427, 14489), True, 'import seaborn as sns\n'), ((14533, 14543), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14541, 14543), True, 'import matplotlib.pyplot as plt\n'), ((14552, 14628), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'results', 'x': '"""Method"""', 'y': '"""Duration"""', 'hue': '"""Database"""', 'ci': 'None'}), "(data=results, x='Method', y='Duration', hue='Database', ci=None)\n", (14563, 14628), True, 'import seaborn as sns\n'), ((14672, 14682), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14680, 14682), True, 'import matplotlib.pyplot as plt\n'), ((15229, 15287), 'seaborn.heatmap', 'sns.heatmap', (['cf_matrix'], {'annot': 'labels', 'fmt': '""""""', 'cmap': '"""Blues"""'}), "(cf_matrix, annot=labels, fmt='', cmap='Blues')\n", (15240, 15287), True, 'import seaborn as sns\n'), ((15289, 15299), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15297, 15299), True, 'import matplotlib.pyplot as plt\n'), ((15310, 15411), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'evaluations', 'x': '"""Method"""', 'y': '"""Positive Prediction Value"""', 'hue': '"""Database"""', 'ci': 'None'}), "(data=evaluations, x='Method', y='Positive Prediction Value',\n hue='Database', ci=None)\n", (15321, 15411), True, 'import seaborn as sns\n'), ((15451, 15461), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15459, 15461), True, 'import matplotlib.pyplot as plt\n'), ((15472, 15559), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'evaluations', 'x': '"""Method"""', 'y': '"""Sensitivity"""', 'hue': '"""Database"""', 'ci': 'None'}), "(data=evaluations, x='Method', y='Sensitivity', hue='Database',\n ci=None)\n", (15483, 15559), True, 'import seaborn as sns\n'), ((15599, 15609), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15607, 15609), True, 'import matplotlib.pyplot as plt\n'), ((15620, 15707), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'evaluations', 'x': '"""Method"""', 'y': '"""Specificity"""', 'hue': '"""Database"""', 'ci': 'None'}), "(data=evaluations, x='Method', y='Specificity', hue='Database',\n ci=None)\n", (15631, 15707), True, 'import seaborn as sns\n'), ((15747, 15757), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15755, 15757), True, 'import matplotlib.pyplot as plt\n'), ((15768, 15860), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'evaluations', 'x': '"""Method"""', 'y': '"""Mean Error (ms)"""', 'hue': '"""Database"""', 'ci': 'None'}), "(data=evaluations, x='Method', y='Mean Error (ms)', hue=\n 'Database', ci=None)\n", (15779, 15860), True, 'import seaborn as sns\n'), ((15899, 15909), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15907, 15909), True, 'import matplotlib.pyplot as plt\n'), ((15920, 16017), 'seaborn.barplot', 'sns.barplot', ([], {'data': 'evaluations', 'x': '"""Method"""', 'y': '"""Std. Mean Error (ms)"""', 'hue': '"""Database"""', 'ci': 'None'}), "(data=evaluations, x='Method', y='Std. Mean Error (ms)', hue=\n 'Database', ci=None)\n", (15931, 16017), True, 'import seaborn as sns\n'), ((16056, 16066), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16064, 16066), True, 'import matplotlib.pyplot as plt\n'), ((556, 628), 'neurokit2.ecg_peaks', 'nk.ecg_peaks', (['ecg'], {'sampling_rate': 'sampling_rate', 'method': '"""pantompkins1985"""'}), "(ecg, sampling_rate=sampling_rate, method='pantompkins1985')\n", (568, 628), True, 'import neurokit2 as nk\n'), ((723, 793), 'neurokit2.ecg_peaks', 'nk.ecg_peaks', (['ecg'], {'sampling_rate': 'sampling_rate', 'method': '"""engzeemod2012"""'}), "(ecg, sampling_rate=sampling_rate, method='engzeemod2012')\n", (735, 793), True, 'import neurokit2 as nk\n'), ((887, 956), 'neurokit2.ecg_peaks', 'nk.ecg_peaks', (['ecg'], {'sampling_rate': 'sampling_rate', 'method': '"""christov2004"""'}), "(ecg, sampling_rate=sampling_rate, method='christov2004')\n", (899, 956), True, 'import neurokit2 as nk\n'), ((1064, 1164), 'neurokit2.ecg_peaks', 'nk.ecg_peaks', (['ecg'], {'sampling_rate': 'sampling_rate', 'method': '"""pantompkins1985"""', 'correct_artifacts': '(True)'}), "(ecg, sampling_rate=sampling_rate, method='pantompkins1985',\n correct_artifacts=True)\n", (1076, 1164), True, 'import neurokit2 as nk\n'), ((1266, 1364), 'neurokit2.ecg_peaks', 'nk.ecg_peaks', (['ecg'], {'sampling_rate': 'sampling_rate', 'method': '"""engzeemod2012"""', 'correct_artifacts': '(True)'}), "(ecg, sampling_rate=sampling_rate, method='engzeemod2012',\n correct_artifacts=True)\n", (1278, 1364), True, 'import neurokit2 as nk\n'), ((1465, 1562), 'neurokit2.ecg_peaks', 'nk.ecg_peaks', (['ecg'], {'sampling_rate': 'sampling_rate', 'method': '"""christov2004"""', 'correct_artifacts': '(True)'}), "(ecg, sampling_rate=sampling_rate, method='christov2004',\n correct_artifacts=True)\n", (1477, 1562), True, 'import neurokit2 as nk\n'), ((5584, 5607), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (5605, 5607), False, 'import datetime\n'), ((7274, 7388), 'neurokit2.signal_period', 'signal_period', (['true_rpeaks'], {'sampling_rate': 'sampling_rate', 'desired_length': 'length', 'interpolation_method': '"""linear"""'}), "(true_rpeaks, sampling_rate=sampling_rate, desired_length=\n length, interpolation_method='linear')\n", (7287, 7388), False, 'from neurokit2 import signal_period\n'), ((7426, 7541), 'neurokit2.signal_period', 'signal_period', (['found_rpeaks'], {'sampling_rate': 'sampling_rate', 'desired_length': 'length', 'interpolation_method': '"""linear"""'}), "(found_rpeaks, sampling_rate=sampling_rate, desired_length=\n length, interpolation_method='linear')\n", (7439, 7541), False, 'from neurokit2 import signal_period\n'), ((10818, 10849), 'numpy.array', 'np.array', (['delays'], {'dtype': '"""float"""'}), "(delays, dtype='float')\n", (10826, 10849), True, 'import numpy as np\n'), ((11103, 11329), 'pandas.DataFrame', 'pd.DataFrame', (["{'TP': TP, 'FN': FN, 'FP': FP, 'TN': TN, 'Positive Prediction Value': [\n accuracy], 'Sensitivity': [sensitivity], 'Specificity': [specificity],\n 'Mean Error (ms)': [mdev], 'Std. Mean Error (ms)': [sdev]}"], {}), "({'TP': TP, 'FN': FN, 'FP': FP, 'TN': TN,\n 'Positive Prediction Value': [accuracy], 'Sensitivity': [sensitivity],\n 'Specificity': [specificity], 'Mean Error (ms)': [mdev],\n 'Std. Mean Error (ms)': [sdev]})\n", (11115, 11329), True, 'import pandas as pd\n'), ((3454, 3484), 'pandas.read_csv', 'pd.read_csv', (["(ecg + '/ECGs.csv')"], {}), "(ecg + '/ECGs.csv')\n", (3465, 3484), True, 'import pandas as pd\n'), ((3538, 3573), 'pandas.read_csv', 'pd.read_csv', (["(rpeaks + '/Rpeaks.csv')"], {}), "(rpeaks + '/Rpeaks.csv')\n", (3549, 3573), True, 'import pandas as pd\n'), ((5406, 5424), 'pandas.concat', 'pd.concat', (['results'], {}), '(results)\n', (5415, 5424), True, 'import pandas as pd\n'), ((5426, 5448), 'pandas.concat', 'pd.concat', (['evaluations'], {}), '(evaluations)\n', (5435, 5448), True, 'import pandas as pd\n'), ((7202, 7245), 'numpy.concatenate', 'np.concatenate', (['[true_rpeaks, found_rpeaks]'], {}), '([true_rpeaks, found_rpeaks])\n', (7216, 7245), True, 'import numpy as np\n'), ((11452, 11482), 'numpy.array', 'np.array', (['[[TP, FN], [FP, TN]]'], {}), '([[TP, FN], [FP, TN]])\n', (11460, 11482), True, 'import numpy as np\n'), ((11917, 11975), 'seaborn.heatmap', 'sns.heatmap', (['cf_matrix'], {'annot': 'labels', 'fmt': '""""""', 'cmap': '"""Blues"""'}), "(cf_matrix, annot=labels, fmt='', cmap='Blues')\n", (11928, 11975), True, 'import seaborn as sns\n'), ((11985, 11995), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11993, 11995), True, 'import matplotlib.pyplot as plt\n'), ((14087, 14105), 'pandas.concat', 'pd.concat', (['results'], {}), '(results)\n', (14096, 14105), True, 'import pandas as pd\n'), ((14144, 14166), 'pandas.concat', 'pd.concat', (['evaluations'], {}), '(evaluations)\n', (14153, 14166), True, 'import pandas as pd\n'), ((15195, 15213), 'numpy.asarray', 'np.asarray', (['labels'], {}), '(labels)\n', (15205, 15213), True, 'import numpy as np\n'), ((7575, 7621), 'numpy.abs', 'np.abs', (['(found_interpolated - true_interpolated)'], {}), '(found_interpolated - true_interpolated)\n', (7581, 7621), True, 'import numpy as np\n'), ((10966, 10981), 'numpy.mean', 'np.mean', (['delays'], {}), '(delays)\n', (10973, 10981), True, 'import numpy as np\n'), ((11028, 11043), 'numpy.mean', 'np.mean', (['delays'], {}), '(delays)\n', (11035, 11043), True, 'import numpy as np\n'), ((11060, 11082), 'numpy.std', 'np.std', (['delays'], {'ddof': '(1)'}), '(delays, ddof=1)\n', (11066, 11082), True, 'import numpy as np\n'), ((15066, 15083), 'numpy.sum', 'np.sum', (['cf_matrix'], {}), '(cf_matrix)\n', (15072, 15083), True, 'import numpy as np\n'), ((11875, 11893), 'numpy.asarray', 'np.asarray', (['labels'], {}), '(labels)\n', (11885, 11893), True, 'import numpy as np\n'), ((5830, 5853), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (5851, 5853), False, 'import datetime\n'), ((11730, 11747), 'numpy.sum', 'np.sum', (['cf_matrix'], {}), '(cf_matrix)\n', (11736, 11747), True, 'import numpy as np\n')]
from __future__ import print_function import tensorflow as tf import numpy as np import pytest import sys import argparse funcs = { 'tanh': 'np.tanh(a)', 'neg': 'np.negative(a)', 'exp': 'np.exp(a)', 'sigmoid': '1/(1+np.exp(-a))', 'sqrt': 'np.sqrt(a)', 'log': 'np.log(a)', 'abs': 'np.abs(a)', 'floor': 'np.floor(a)', 'ceil': 'np.ceil(a)', 'square': 'np.square(a)', 'argmax': 'np.argmax(a, 1)', 'argmin': 'np.argmin(a, 1)', } def nop(val): return val def get_test_params(): tests = [] for dtype in ['uint8', 'float32', 'int32']: for tf_func, py_func in funcs.items(): if 'int' in dtype and tf_func in [ 'ceil', 'floor', 'exp', 'sigmoid', 'log', 'sqrt', 'tanh', 'argmax', 'argmin']: continue if dtype == 'uint8' and tf_func in ['abs', 'square', 'neg']: continue mark = nop tests.append({'mark': mark, 'dtype': dtype, 'tf_func': tf_func, 'py_func': py_func}) return tests @pytest.mark.parametrize( 'dtype, tf_func, py_func', [d['mark']((d['dtype'], d['tf_func'], d['py_func'])) for d in get_test_params()]) def test(tf_func, py_func, dtype): print('func', tf_func, dtype) np_dtype = eval('np.%s' % dtype) tf_dtype = eval('tf.%s' % dtype) with tf.Graph().as_default(): with tf.device('/gpu:0'): tf_a = tf.placeholder(tf_dtype, [None, None], 'a') if tf_func in ['argmax', 'argmin']: tf_c = tf.__dict__[tf_func](tf_a, 1, name="c") else: tf_c = tf.__dict__[tf_func](tf_a, name="c") print('tf_c', tf_c) with tf.Session(config=tf.ConfigProto(log_device_placement=False)) as sess: np.random.seed(123) shape = (3, 10) a = np.random.choice(50, shape) / 50 if 'sqrt' not in tf_func and 'log' not in tf_func: a -= 0.5 if 'int' in dtype: a *= 10 a = a.astype(np_dtype) ar, cr = sess.run((tf_a, tf_c), {tf_a: a}) print('original ', ar) c_py = eval(py_func) diff = np.abs(c_py - cr).max() print('expected ', c_py) print('gpu ', cr) print('diff', diff) assert diff < 1e-4, 'failed for %s' % tf_func if __name__ == '__main__': if len(sys.argv) == 1: print('Please run using py.test, ie: py.test -v') sys.exit(0) else: parser = argparse.ArgumentParser() parser.add_argument('--dtype', type=str, default='float32') parser.add_argument('--tf-func', type=str, default='sqrt') args = parser.parse_args() args.py_func = funcs[args.tf_func] test(**args.__dict__)
[ "numpy.random.seed", "argparse.ArgumentParser", "numpy.abs", "tensorflow.device", "tensorflow.placeholder", "tensorflow.ConfigProto", "tensorflow.Graph", "numpy.random.choice", "sys.exit" ]
[((2572, 2583), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2580, 2583), False, 'import sys\n'), ((2611, 2636), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2634, 2636), False, 'import argparse\n'), ((1381, 1400), 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (1390, 1400), True, 'import tensorflow as tf\n'), ((1421, 1464), 'tensorflow.placeholder', 'tf.placeholder', (['tf_dtype', '[None, None]', '"""a"""'], {}), "(tf_dtype, [None, None], 'a')\n", (1435, 1464), True, 'import tensorflow as tf\n'), ((1343, 1353), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1351, 1353), True, 'import tensorflow as tf\n'), ((1791, 1810), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (1805, 1810), True, 'import numpy as np\n'), ((1863, 1890), 'numpy.random.choice', 'np.random.choice', (['(50)', 'shape'], {}), '(50, shape)\n', (1879, 1890), True, 'import numpy as np\n'), ((1721, 1763), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'log_device_placement': '(False)'}), '(log_device_placement=False)\n', (1735, 1763), True, 'import tensorflow as tf\n'), ((2253, 2270), 'numpy.abs', 'np.abs', (['(c_py - cr)'], {}), '(c_py - cr)\n', (2259, 2270), True, 'import numpy as np\n')]
from setuptools import Extension, setup, find_packages from Cython.Build import cythonize import numpy setup( name='pyjpegls', version='0.0.1', description='Encode and decode jpeg-ls files from and to numpy arrays.', install_requires = [ 'numpy' ], packages=find_packages('src'), package_dir={'':'src'}, ext_modules=cythonize( Extension('jpegls', sources=[ 'src/jpegls.pyx', 'thirdparty/charls/src/charls_jpegls_decoder.cpp', 'thirdparty/charls/src/charls_jpegls_encoder.cpp', 'thirdparty/charls/src/jpegls_error.cpp', 'thirdparty/charls/src/jpegls.cpp', 'thirdparty/charls/src/jpeg_stream_reader.cpp', 'thirdparty/charls/src/jpeg_stream_writer.cpp', 'thirdparty/charls/src/version.cpp' ], include_dirs=[ numpy.get_include(), 'thirdparty/charls/include' ], define_macros =[ ('CHARLS_STATIC', 1), ('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION') ] ), build_dir='build', language_level = "3" ) )
[ "numpy.get_include", "setuptools.find_packages" ]
[((267, 287), 'setuptools.find_packages', 'find_packages', (['"""src"""'], {}), "('src')\n", (280, 287), False, 'from setuptools import Extension, setup, find_packages\n'), ((763, 782), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (780, 782), False, 'import numpy\n')]
import unittest import numpy as np from functools import partial from scipy import stats import sympy as sp from pyapprox.univariate_polynomials.quadrature import \ gauss_jacobi_pts_wts_1D, gauss_hermite_pts_wts_1D, \ clenshaw_curtis_pts_wts_1D, leja_growth_rule, \ constant_increment_growth_rule from pyapprox.utilities import beta_pdf_on_ab, gaussian_pdf from pyapprox.variables import float_rv_discrete, get_probability_masses from pyapprox.univariate_polynomials.leja_quadrature import \ get_univariate_leja_quadrature_rule from pyapprox.variables import transform_scale_parameters class TestQuadrature(unittest.TestCase): def setUp(self): np.random.seed(1) def test_gauss_jacobi_quadrature(self): """ integrate x^2 x^a (1-x)^b/B(a+1,b+1) dx from x=0..1 """ alpha_poly = 0 beta_poly = 0 a = beta_poly+1 b = alpha_poly+1 true_mean = a/float(a+b) true_variance = a*b/float((a+b)**2*(a+b+1)) x, w = gauss_jacobi_pts_wts_1D(2, alpha_poly, beta_poly) x = (x+1)/2. def function(x): return x**2 assert np.allclose(np.dot(function(x), w)-true_mean**2, true_variance) def test_clenshaw_curtis_quadrature(self): a = 1 b = 1 true_mean = a/float(a+b) true_variance = a*b/float((a+b)**2*(a+b+1)) x, w = clenshaw_curtis_pts_wts_1D(2) x = (x+1)/2. def function(x): return x**2 assert np.allclose(np.dot(function(x), w)-true_mean**2, true_variance) def test_gauss_hermite_quadrature(self): """ integrate x^2 1/sqrt(2*pi)exp(-x**2/2) dx from x=-inf..inf """ true_mean = 0. true_variance = 1. x, w = gauss_hermite_pts_wts_1D(2) def function(x): return x**2 assert np.allclose(np.dot(function(x), w)-true_mean**2, true_variance) def test_gaussian_leja_quadrature(self): level = 20 quad_rule = get_univariate_leja_quadrature_rule( stats.norm(0, 1), leja_growth_rule, return_weights_for_all_levels=False) x_quad, w_quad = quad_rule(level) x = sp.Symbol('x') weight_function = gaussian_pdf(0, 1, x, sp) ranges = [-sp.oo, sp.oo] exact_integral = float( sp.integrate(weight_function*x**3, (x, ranges[0], ranges[1]))) # print(exact_integral, x_quad, w_quad) assert np.allclose(exact_integral, np.dot(x_quad**3, w_quad)) def test_beta_leja_quadrature(self): level = 12 alpha_stat, beta_stat = 2, 10 quad_rule = get_univariate_leja_quadrature_rule( stats.beta(alpha_stat, beta_stat), leja_growth_rule, return_weights_for_all_levels=False) x_quad, w_quad = quad_rule(level) x = sp.Symbol('x') weight_function = beta_pdf_on_ab(alpha_stat, beta_stat, -1, 1, x) ranges = [-1, 1] exact_integral = float( sp.integrate(weight_function*x**3, (x, ranges[0], ranges[1]))) assert np.allclose(exact_integral, np.dot(x_quad**3, w_quad)) level = 12 alpha_stat, beta_stat = 2, 10 x_quad, w_quad = quad_rule(level) x_quad = (x_quad+1)/2 x = sp.Symbol('x') weight_function = beta_pdf_on_ab(alpha_stat, beta_stat, 0, 1, x) ranges = [0, 1] exact_integral = float( sp.integrate(weight_function*x**3, (x, ranges[0], ranges[1]))) assert np.allclose(exact_integral, np.dot(x_quad**3, w_quad)) def test_get_univariate_leja_rule_float_rv_discrete(self): nmasses = 20 xk = np.array(range(1, nmasses+1), dtype='float') pk = np.ones(nmasses)/nmasses variable = float_rv_discrete( name='float_rv_discrete', values=(xk, pk))() growth_rule = partial(constant_increment_growth_rule, 2) quad_rule = get_univariate_leja_quadrature_rule( variable, growth_rule, orthonormality_tol=1e-10, return_weights_for_all_levels=False) level = 3 x, w = quad_rule(level) loc, scale = transform_scale_parameters(variable) x = x*scale+loc degree = x.shape[0]-1 true_moment = (xk**degree).dot(pk) moment = (x**degree).dot(w) # print(moment, true_moment) assert np.allclose(moment, true_moment) def test_get_univariate_leja_rule_bounded_discrete(self): growth_rule = partial(constant_increment_growth_rule, 2) level = 3 nmasses = 20 xk = np.array(range(0, nmasses), dtype='float') pk = np.ones(nmasses)/nmasses var_cheb = float_rv_discrete( name='discrete_chebyshev', values=(xk, pk))() for variable in [var_cheb, stats.binom(17, 0.5), stats.hypergeom(10+10, 10, 9)]: quad_rule = get_univariate_leja_quadrature_rule( variable, growth_rule) x, w = quad_rule(level) loc, scale = transform_scale_parameters(variable) x = x*scale+loc xk, pk = get_probability_masses(variable) print(x, xk, loc, scale) degree = (x.shape[0]-1) true_moment = (xk**degree).dot(pk) moment = (x**degree).dot(w[-1]) print(moment, true_moment, variable.dist.name) assert np.allclose(moment, true_moment) # Note: # currently get_univariate_leja_quadrature_rule with christoffel # does not produce nested sequences without using initial_points def test_hermite_christoffel_leja_quadrature_rule(self): variable = stats.norm(2, 3) growth_rule = partial(constant_increment_growth_rule, 2) quad_rule = get_univariate_leja_quadrature_rule( variable, growth_rule, method='christoffel') level = 5 samples, weights = quad_rule(level) # samples returned by quadrature rule will be on canonical domain # check first point was chosen correctly assert np.allclose(samples[0], (variable.ppf(0.75)-2)/3) # so integral is computed with resepect to standard normal assert np.allclose((samples**2).dot(weights[-1]), 1) # check samples are nested. samples1, weights1 = quad_rule(level+3) assert np.allclose(samples1[:samples.shape[0]], samples) def test_uniform_christoffel_leja_quadrature_rule(self): import warnings warnings.filterwarnings('error') variable = stats.uniform(-2, 3) growth_rule = partial(constant_increment_growth_rule, 2) quad_rule = get_univariate_leja_quadrature_rule( variable, growth_rule, method='christoffel') level = 5 samples, weights = quad_rule(level) # samples returned by quadrature rule will be on canonical domain # check first point was chosen correctly assert np.allclose(samples[0], 2*(variable.ppf(0.5)+2)/3-1) # so integral is computed with resepect to uniform on [-1, 1] assert np.allclose((samples**2).dot(weights[-1]), 1/3) def test_hermite_pdf_weighted_leja_quadrature_rule(self): variable = stats.norm(2, 3) growth_rule = partial(constant_increment_growth_rule, 2) quad_rule = get_univariate_leja_quadrature_rule( variable, growth_rule, method='pdf') level = 5 samples, weights = quad_rule(level) assert np.allclose(samples[0], (variable.ppf(0.75)-2)/3) assert np.allclose((samples**2).dot(weights[-1]), 1) def test_legendre_pdf_weighted_leja_quadrature_rule(self): variable = stats.uniform(-2, 3) growth_rule = partial(constant_increment_growth_rule, 2) quad_rule = get_univariate_leja_quadrature_rule( variable, growth_rule, method='pdf') level = 5 samples, weights = quad_rule(level) assert np.allclose(samples[0], 2*(variable.ppf(0.5)+2)/3-1) assert np.allclose((samples**2).dot(weights[-1]), 1/3) def test_sampled_based_christoffel_leja_quadrature_rule(self): nsamples = int(1e6) samples = np.random.normal(0, 1, (1, nsamples)) variable = float_rv_discrete( name='continuous_rv_sample', values=(samples[0, :], np.ones(nsamples)/nsamples))() growth_rule = partial(constant_increment_growth_rule, 2) quad_rule = get_univariate_leja_quadrature_rule( variable, growth_rule, method='christoffel', orthonormality_tol=1e-8) level = 5 quad_samples, weights = quad_rule(level) # print(quad_samples) print((quad_samples**2).dot(weights[-1])) print((samples**2).mean()) assert np.allclose( (quad_samples**2).dot(weights[-1]), (samples**2).mean()) if __name__ == "__main__": univariate_quadrature_test_suite = \ unittest.TestLoader().loadTestsFromTestCase(TestQuadrature) unittest.TextTestRunner(verbosity=2).run(univariate_quadrature_test_suite)
[ "numpy.random.seed", "pyapprox.variables.float_rv_discrete", "numpy.allclose", "numpy.ones", "unittest.TestLoader", "numpy.random.normal", "pyapprox.utilities.gaussian_pdf", "scipy.stats.norm", "pyapprox.variables.transform_scale_parameters", "scipy.stats.hypergeom", "functools.partial", "pyap...
[((675, 692), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (689, 692), True, 'import numpy as np\n'), ((1019, 1068), 'pyapprox.univariate_polynomials.quadrature.gauss_jacobi_pts_wts_1D', 'gauss_jacobi_pts_wts_1D', (['(2)', 'alpha_poly', 'beta_poly'], {}), '(2, alpha_poly, beta_poly)\n', (1042, 1068), False, 'from pyapprox.univariate_polynomials.quadrature import gauss_jacobi_pts_wts_1D, gauss_hermite_pts_wts_1D, clenshaw_curtis_pts_wts_1D, leja_growth_rule, constant_increment_growth_rule\n'), ((1385, 1414), 'pyapprox.univariate_polynomials.quadrature.clenshaw_curtis_pts_wts_1D', 'clenshaw_curtis_pts_wts_1D', (['(2)'], {}), '(2)\n', (1411, 1414), False, 'from pyapprox.univariate_polynomials.quadrature import gauss_jacobi_pts_wts_1D, gauss_hermite_pts_wts_1D, clenshaw_curtis_pts_wts_1D, leja_growth_rule, constant_increment_growth_rule\n'), ((1757, 1784), 'pyapprox.univariate_polynomials.quadrature.gauss_hermite_pts_wts_1D', 'gauss_hermite_pts_wts_1D', (['(2)'], {}), '(2)\n', (1781, 1784), False, 'from pyapprox.univariate_polynomials.quadrature import gauss_jacobi_pts_wts_1D, gauss_hermite_pts_wts_1D, clenshaw_curtis_pts_wts_1D, leja_growth_rule, constant_increment_growth_rule\n'), ((2176, 2190), 'sympy.Symbol', 'sp.Symbol', (['"""x"""'], {}), "('x')\n", (2185, 2190), True, 'import sympy as sp\n'), ((2217, 2242), 'pyapprox.utilities.gaussian_pdf', 'gaussian_pdf', (['(0)', '(1)', 'x', 'sp'], {}), '(0, 1, x, sp)\n', (2229, 2242), False, 'from pyapprox.utilities import beta_pdf_on_ab, gaussian_pdf\n'), ((2826, 2840), 'sympy.Symbol', 'sp.Symbol', (['"""x"""'], {}), "('x')\n", (2835, 2840), True, 'import sympy as sp\n'), ((2867, 2914), 'pyapprox.utilities.beta_pdf_on_ab', 'beta_pdf_on_ab', (['alpha_stat', 'beta_stat', '(-1)', '(1)', 'x'], {}), '(alpha_stat, beta_stat, -1, 1, x)\n', (2881, 2914), False, 'from pyapprox.utilities import beta_pdf_on_ab, gaussian_pdf\n'), ((3260, 3274), 'sympy.Symbol', 'sp.Symbol', (['"""x"""'], {}), "('x')\n", (3269, 3274), True, 'import sympy as sp\n'), ((3301, 3347), 'pyapprox.utilities.beta_pdf_on_ab', 'beta_pdf_on_ab', (['alpha_stat', 'beta_stat', '(0)', '(1)', 'x'], {}), '(alpha_stat, beta_stat, 0, 1, x)\n', (3315, 3347), False, 'from pyapprox.utilities import beta_pdf_on_ab, gaussian_pdf\n'), ((3848, 3890), 'functools.partial', 'partial', (['constant_increment_growth_rule', '(2)'], {}), '(constant_increment_growth_rule, 2)\n', (3855, 3890), False, 'from functools import partial\n'), ((3911, 4036), 'pyapprox.univariate_polynomials.leja_quadrature.get_univariate_leja_quadrature_rule', 'get_univariate_leja_quadrature_rule', (['variable', 'growth_rule'], {'orthonormality_tol': '(1e-10)', 'return_weights_for_all_levels': '(False)'}), '(variable, growth_rule,\n orthonormality_tol=1e-10, return_weights_for_all_levels=False)\n', (3946, 4036), False, 'from pyapprox.univariate_polynomials.leja_quadrature import get_univariate_leja_quadrature_rule\n'), ((4142, 4178), 'pyapprox.variables.transform_scale_parameters', 'transform_scale_parameters', (['variable'], {}), '(variable)\n', (4168, 4178), False, 'from pyapprox.variables import transform_scale_parameters\n'), ((4366, 4398), 'numpy.allclose', 'np.allclose', (['moment', 'true_moment'], {}), '(moment, true_moment)\n', (4377, 4398), True, 'import numpy as np\n'), ((4484, 4526), 'functools.partial', 'partial', (['constant_increment_growth_rule', '(2)'], {}), '(constant_increment_growth_rule, 2)\n', (4491, 4526), False, 'from functools import partial\n'), ((5687, 5703), 'scipy.stats.norm', 'stats.norm', (['(2)', '(3)'], {}), '(2, 3)\n', (5697, 5703), False, 'from scipy import stats\n'), ((5726, 5768), 'functools.partial', 'partial', (['constant_increment_growth_rule', '(2)'], {}), '(constant_increment_growth_rule, 2)\n', (5733, 5768), False, 'from functools import partial\n'), ((5789, 5874), 'pyapprox.univariate_polynomials.leja_quadrature.get_univariate_leja_quadrature_rule', 'get_univariate_leja_quadrature_rule', (['variable', 'growth_rule'], {'method': '"""christoffel"""'}), "(variable, growth_rule, method='christoffel'\n )\n", (5824, 5874), False, 'from pyapprox.univariate_polynomials.leja_quadrature import get_univariate_leja_quadrature_rule\n'), ((6361, 6410), 'numpy.allclose', 'np.allclose', (['samples1[:samples.shape[0]]', 'samples'], {}), '(samples1[:samples.shape[0]], samples)\n', (6372, 6410), True, 'import numpy as np\n'), ((6505, 6537), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""error"""'], {}), "('error')\n", (6528, 6537), False, 'import warnings\n'), ((6557, 6577), 'scipy.stats.uniform', 'stats.uniform', (['(-2)', '(3)'], {}), '(-2, 3)\n', (6570, 6577), False, 'from scipy import stats\n'), ((6600, 6642), 'functools.partial', 'partial', (['constant_increment_growth_rule', '(2)'], {}), '(constant_increment_growth_rule, 2)\n', (6607, 6642), False, 'from functools import partial\n'), ((6663, 6748), 'pyapprox.univariate_polynomials.leja_quadrature.get_univariate_leja_quadrature_rule', 'get_univariate_leja_quadrature_rule', (['variable', 'growth_rule'], {'method': '"""christoffel"""'}), "(variable, growth_rule, method='christoffel'\n )\n", (6698, 6748), False, 'from pyapprox.univariate_polynomials.leja_quadrature import get_univariate_leja_quadrature_rule\n'), ((7225, 7241), 'scipy.stats.norm', 'stats.norm', (['(2)', '(3)'], {}), '(2, 3)\n', (7235, 7241), False, 'from scipy import stats\n'), ((7264, 7306), 'functools.partial', 'partial', (['constant_increment_growth_rule', '(2)'], {}), '(constant_increment_growth_rule, 2)\n', (7271, 7306), False, 'from functools import partial\n'), ((7327, 7399), 'pyapprox.univariate_polynomials.leja_quadrature.get_univariate_leja_quadrature_rule', 'get_univariate_leja_quadrature_rule', (['variable', 'growth_rule'], {'method': '"""pdf"""'}), "(variable, growth_rule, method='pdf')\n", (7362, 7399), False, 'from pyapprox.univariate_polynomials.leja_quadrature import get_univariate_leja_quadrature_rule\n'), ((7684, 7704), 'scipy.stats.uniform', 'stats.uniform', (['(-2)', '(3)'], {}), '(-2, 3)\n', (7697, 7704), False, 'from scipy import stats\n'), ((7727, 7769), 'functools.partial', 'partial', (['constant_increment_growth_rule', '(2)'], {}), '(constant_increment_growth_rule, 2)\n', (7734, 7769), False, 'from functools import partial\n'), ((7790, 7862), 'pyapprox.univariate_polynomials.leja_quadrature.get_univariate_leja_quadrature_rule', 'get_univariate_leja_quadrature_rule', (['variable', 'growth_rule'], {'method': '"""pdf"""'}), "(variable, growth_rule, method='pdf')\n", (7825, 7862), False, 'from pyapprox.univariate_polynomials.leja_quadrature import get_univariate_leja_quadrature_rule\n'), ((8183, 8220), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(1, nsamples)'], {}), '(0, 1, (1, nsamples))\n', (8199, 8220), True, 'import numpy as np\n'), ((8388, 8430), 'functools.partial', 'partial', (['constant_increment_growth_rule', '(2)'], {}), '(constant_increment_growth_rule, 2)\n', (8395, 8430), False, 'from functools import partial\n'), ((8451, 8562), 'pyapprox.univariate_polynomials.leja_quadrature.get_univariate_leja_quadrature_rule', 'get_univariate_leja_quadrature_rule', (['variable', 'growth_rule'], {'method': '"""christoffel"""', 'orthonormality_tol': '(1e-08)'}), "(variable, growth_rule, method=\n 'christoffel', orthonormality_tol=1e-08)\n", (8486, 8562), False, 'from pyapprox.univariate_polynomials.leja_quadrature import get_univariate_leja_quadrature_rule\n'), ((2036, 2052), 'scipy.stats.norm', 'stats.norm', (['(0)', '(1)'], {}), '(0, 1)\n', (2046, 2052), False, 'from scipy import stats\n'), ((2320, 2385), 'sympy.integrate', 'sp.integrate', (['(weight_function * x ** 3)', '(x, ranges[0], ranges[1])'], {}), '(weight_function * x ** 3, (x, ranges[0], ranges[1]))\n', (2332, 2385), True, 'import sympy as sp\n'), ((2474, 2501), 'numpy.dot', 'np.dot', (['(x_quad ** 3)', 'w_quad'], {}), '(x_quad ** 3, w_quad)\n', (2480, 2501), True, 'import numpy as np\n'), ((2669, 2702), 'scipy.stats.beta', 'stats.beta', (['alpha_stat', 'beta_stat'], {}), '(alpha_stat, beta_stat)\n', (2679, 2702), False, 'from scipy import stats\n'), ((2984, 3049), 'sympy.integrate', 'sp.integrate', (['(weight_function * x ** 3)', '(x, ranges[0], ranges[1])'], {}), '(weight_function * x ** 3, (x, ranges[0], ranges[1]))\n', (2996, 3049), True, 'import sympy as sp\n'), ((3090, 3117), 'numpy.dot', 'np.dot', (['(x_quad ** 3)', 'w_quad'], {}), '(x_quad ** 3, w_quad)\n', (3096, 3117), True, 'import numpy as np\n'), ((3416, 3481), 'sympy.integrate', 'sp.integrate', (['(weight_function * x ** 3)', '(x, ranges[0], ranges[1])'], {}), '(weight_function * x ** 3, (x, ranges[0], ranges[1]))\n', (3428, 3481), True, 'import sympy as sp\n'), ((3522, 3549), 'numpy.dot', 'np.dot', (['(x_quad ** 3)', 'w_quad'], {}), '(x_quad ** 3, w_quad)\n', (3528, 3549), True, 'import numpy as np\n'), ((3705, 3721), 'numpy.ones', 'np.ones', (['nmasses'], {}), '(nmasses)\n', (3712, 3721), True, 'import numpy as np\n'), ((3749, 3809), 'pyapprox.variables.float_rv_discrete', 'float_rv_discrete', ([], {'name': '"""float_rv_discrete"""', 'values': '(xk, pk)'}), "(name='float_rv_discrete', values=(xk, pk))\n", (3766, 3809), False, 'from pyapprox.variables import float_rv_discrete, get_probability_masses\n'), ((4636, 4652), 'numpy.ones', 'np.ones', (['nmasses'], {}), '(nmasses)\n', (4643, 4652), True, 'import numpy as np\n'), ((4680, 4741), 'pyapprox.variables.float_rv_discrete', 'float_rv_discrete', ([], {'name': '"""discrete_chebyshev"""', 'values': '(xk, pk)'}), "(name='discrete_chebyshev', values=(xk, pk))\n", (4697, 4741), False, 'from pyapprox.variables import float_rv_discrete, get_probability_masses\n'), ((4793, 4813), 'scipy.stats.binom', 'stats.binom', (['(17)', '(0.5)'], {}), '(17, 0.5)\n', (4804, 4813), False, 'from scipy import stats\n'), ((4840, 4871), 'scipy.stats.hypergeom', 'stats.hypergeom', (['(10 + 10)', '(10)', '(9)'], {}), '(10 + 10, 10, 9)\n', (4855, 4871), False, 'from scipy import stats\n'), ((4896, 4954), 'pyapprox.univariate_polynomials.leja_quadrature.get_univariate_leja_quadrature_rule', 'get_univariate_leja_quadrature_rule', (['variable', 'growth_rule'], {}), '(variable, growth_rule)\n', (4931, 4954), False, 'from pyapprox.univariate_polynomials.leja_quadrature import get_univariate_leja_quadrature_rule\n'), ((5034, 5070), 'pyapprox.variables.transform_scale_parameters', 'transform_scale_parameters', (['variable'], {}), '(variable)\n', (5060, 5070), False, 'from pyapprox.variables import transform_scale_parameters\n'), ((5121, 5153), 'pyapprox.variables.get_probability_masses', 'get_probability_masses', (['variable'], {}), '(variable)\n', (5143, 5153), False, 'from pyapprox.variables import float_rv_discrete, get_probability_masses\n'), ((5398, 5430), 'numpy.allclose', 'np.allclose', (['moment', 'true_moment'], {}), '(moment, true_moment)\n', (5409, 5430), True, 'import numpy as np\n'), ((8940, 8961), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (8959, 8961), False, 'import unittest\n'), ((9004, 9040), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (9027, 9040), False, 'import unittest\n'), ((8335, 8352), 'numpy.ones', 'np.ones', (['nsamples'], {}), '(nsamples)\n', (8342, 8352), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression # # Download and convert the MNIST data set # see the program: mnist2csv.py (converts idx3 data to csv) # Load the dataset df = pd.read_csv('data/mnist_train.csv') #print( df.head() ) # Plot a couple of images pixel_colnames = df.columns[1:] # Get all columns except the label column for the first image image_values = df.loc[0, pixel_colnames].values # Plot up the first two images just for fun: plt.figure(figsize=(8,4)) for index in range(0, 2): plt.subplot(1, 2, 1 + index ) image_values = df.loc[index, pixel_colnames].values image_label = df.loc[index, 'label'] plt.imshow(image_values.reshape(28,28), cmap ='gray') plt.title('Label: ' + str(image_label), fontsize = 18) # Split data into Training and Test Sets X_train, X_test, y_train, y_test = train_test_split(df[pixel_colnames], df['label'], random_state=0) # Standardize the data: # PCA and logisitic regression are sensitive to the scale of your features. # set the data onto unit scale (mean = 0 and variance = 1) by using StandardScaler scaler = StandardScaler() # Fit on training set only. scaler.fit(X_train) # Apply transform to both the training set and the test set. X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) # for the plot at the bottom scaledTrainImages = X_train.copy() # Perform PCA # n_components = .90 means that scikit-learn will choose the minimum number # of principal components such that 90% of the variance is retained. pca = PCA(n_components = .90) # Fit PCA on training set only pca.fit(X_train) # Apply the mapping (transform) to both the training set and the test set. X_train = pca.transform(X_train) X_test = pca.transform(X_test) # Logistic Regression # - If you turn PCA off, you obtain a very similar accuracy as to using the # complete data set clf = LogisticRegression() clf.fit(X_train, y_train) print('Number of dimensions before PCA: ' + str(len(pixel_colnames))) print('Number of dimensions after PCA: ' + str(pca.n_components_)) print('Classification accuracy: ' + str(clf.score(X_test, y_test))) #========================================================================== # A Plot to demonstrate the cumulative explained variance and the # number of principal components # if n_components is not set, all components are kept (784 in this case) pca = PCA() pca.fit(scaledTrainImages) # Summing explained variance tot = sum(pca.explained_variance_) var_exp = [(i/tot)*100 for i in sorted(pca.explained_variance_, reverse=True)] # Cumulative explained variance cum_var_exp = np.cumsum(var_exp) # PLOT OUT THE EXPLAINED VARIANCES SUPERIMPOSED fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (10,7)); ax.tick_params(labelsize = 18) ax.plot(range(1, 785), cum_var_exp, label='cumulative explained variance') ax.set_ylabel('Cumulative Explained variance', fontsize = 16) ax.set_xlabel('Principal components', fontsize = 16) ax.axhline(y = 95, color='k', linestyle='--', label = '95% Explained Variance') ax.axhline(y = 90, color='c', linestyle='--', label = '90% Explained Variance') ax.axhline(y = 85, color='r', linestyle='--', label = '85% Explained Variance') ax.legend(loc='best', markerscale = 1.0, fontsize = 12) plt.show()
[ "matplotlib.pyplot.subplot", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.show", "pandas.read_csv", "sklearn.model_selection.train_test_split", "numpy.cumsum", "matplotlib.pyplot.figure", "sklearn.linear_model.LogisticRegression", "sklearn.decomposition.PCA", "matplotlib.pyplot.subpl...
[((396, 431), 'pandas.read_csv', 'pd.read_csv', (['"""data/mnist_train.csv"""'], {}), "('data/mnist_train.csv')\n", (407, 431), True, 'import pandas as pd\n'), ((671, 697), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (681, 697), True, 'import matplotlib.pyplot as plt\n'), ((1051, 1116), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df[pixel_colnames]', "df['label']"], {'random_state': '(0)'}), "(df[pixel_colnames], df['label'], random_state=0)\n", (1067, 1116), False, 'from sklearn.model_selection import train_test_split\n'), ((1312, 1328), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1326, 1328), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1745, 1766), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(0.9)'}), '(n_components=0.9)\n', (1748, 1766), False, 'from sklearn.decomposition import PCA\n'), ((2090, 2110), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (2108, 2110), False, 'from sklearn.linear_model import LogisticRegression\n'), ((2599, 2604), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (2602, 2604), False, 'from sklearn.decomposition import PCA\n'), ((2825, 2843), 'numpy.cumsum', 'np.cumsum', (['var_exp'], {}), '(var_exp)\n', (2834, 2843), True, 'import numpy as np\n'), ((2903, 2950), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(1)', 'figsize': '(10, 7)'}), '(nrows=1, ncols=1, figsize=(10, 7))\n', (2915, 2950), True, 'import matplotlib.pyplot as plt\n'), ((3476, 3486), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3484, 3486), True, 'import matplotlib.pyplot as plt\n'), ((729, 757), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1 + index)'], {}), '(1, 2, 1 + index)\n', (740, 757), True, 'import matplotlib.pyplot as plt\n')]
from keras.models import Sequential, Model from keras.layers import Conv2D, Lambda, Input, Flatten import numpy as np import math import sys from keras.models import load_model import os import keras.backend as K GRID_LENGTH = 9 GRID_SIZE = (GRID_LENGTH, GRID_LENGTH) RIM_SIZE = 2 SAMPLE_SIZE = 10 * 1000 EPOCHS = 100 def in_between(value, tuple): return tuple[0] <= value <= tuple[1] def build_random_grid(): treshkhold = (RIM_SIZE, GRID_LENGTH - RIM_SIZE -1) return np.array([ np.array([np.random.uniform(-100, 200) if in_between(i, treshkhold) and in_between(j, treshkhold) else 0 for i in range(0, GRID_LENGTH)]) for j in range(0, GRID_LENGTH)]) def score_neighbourhood(nn): """ :type nn: ndarray :return: """ flat = nn.flatten() enemies = filter(lambda x: x < 0, flat) if nn[1][1] <= 0: return 0 if min(flat) >= 0: # no enemy return 0 if -max(enemies) > nn[1][1]+2: # can't attack return min(enemies) return nn[1][1] * (nn[1][1] + max(enemies)) / math.log(-sum(enemies) + 1, 5) def score_neighbourhood_xx(nn): """ :type nn: ndarray :return: """ flat = nn.flatten() enemies = filter(lambda x: x < 0, flat) if nn[1][1] <= 0: return 0 if min(flat) >= 0: # no enemy return 0 if -max(enemies) > nn[1][1]+2: # can't attack return min(enemies) return nn[1][1] * (nn[1][1] + max(enemies)) / (-sum(enemies) + 1) def score_neighbourhood_x(nn): """ :type nn: ndarray :return: """ flat = nn.flatten() enemies = filter(lambda x: x < 0, flat) if nn[1][1] <= 0: return nn[1][1] if min(flat) >= 0: # no enemy return 0 if -max(enemies) > nn[1][1]+2: # can't attack return min(enemies) return nn[1][1] def score_neighbourhood_simple(nn): """ :type nn: ndarray :return: """ flat = nn.flatten() enemies = filter(lambda x: x < 0, flat) maxEnemies = max(enemies) if any(enemies) else 0 return nn[1][1] + maxEnemies def score_neighbourhood_simplest(nn): """ :type nn: ndarray :return: """ return nn[1][1] def score_victor(victor): res = np.zeros(GRID_SIZE) for j in range(RIM_SIZE, GRID_LENGTH-RIM_SIZE): for i in range(RIM_SIZE, GRID_LENGTH-RIM_SIZE): res[i][j] = score_neighbourhood_xx(victor[i-1:i+2, j-1:j+2]) return res class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return '{},{}'.format(self.x, self.y) def __repr__(self): return self.__str__() def build_model(): model = Sequential() model.add(Conv2D(128, (3, 3), padding='same', activation='relu', input_shape=(GRID_SIZE[0], GRID_SIZE[1], 1))) model.add(Conv2D(16, (3, 3), padding='same', activation='relu')) model.add(Conv2D(4, (3, 3), padding='same', activation='relu')) model.add(Conv2D(1, (1, 1), padding='same', activation='relu')) return model def chuz_top(input): """ :type input: ndarray :return: """ return K.argmax(input, 1) if __name__ == '__main__': fname = 'scratch_conv.h5f' if len(sys.argv) < 2: print('use with TRAIN or SCORE') elif sys.argv[1] == 'TRAIN': model = build_model() X = [] Y = [] for i in range(0, SAMPLE_SIZE): x = build_random_grid() y = score_victor(x) X.append(x) Y.append(y) X = np.array(X) Y = np.array(Y) X = X.reshape(X.shape[0], GRID_SIZE[0], GRID_SIZE[1], 1) Y = Y.reshape(X.shape[0], GRID_SIZE[0], GRID_SIZE[1], 1) if os.path.exists(fname): model.load_weights(fname) model.compile(loss='mean_squared_logarithmic_error', optimizer='adam') model.fit(X, Y, batch_size=100, verbose=1, epochs=EPOCHS) model.save(fname) elif sys.argv[1] == 'SCORE': model = load_model(fname) xxx = build_random_grid() xx = np.array([xxx]) x = xx.reshape(xx.shape[0], GRID_SIZE[0], GRID_SIZE[1], 1) y_hat = model.predict(x) #y_hat = y_hat.reshape(GRID_SIZE[0], GRID_SIZE[1]) print('____________________________') y_hat = y_hat.reshape(GRID_SIZE[0], GRID_SIZE[1]) y_hat_scores = {} y = score_victor(xxx) y_scores = {} for j in range(0, GRID_SIZE[0]): for i in range(0, GRID_SIZE[1]): y_hat_scores[Point(i, j)] = round(y_hat[i][j]) y_scores[Point(i, j)] = round(y[i][j]) print('{} ({}|{})\t'.format(round(xxx[i][j]), round(y[i][j]), round(y_hat[i][j]))) sorted_y_hat = sorted(y_hat_scores, key=lambda p: y_hat_scores[p], reverse=True) sorted_y = sorted(y_scores, key=lambda p: y_scores[p], reverse=True) print('TOP 5:') for i in range(0, 5): print('{} ({}) - {} ({})'.format(sorted_y[i], y_scores[sorted_y[i]], sorted_y_hat[i], y_hat_scores[sorted_y_hat[i]])) ''' input_1 = Input(shape=(GRID_SIZE[0], GRID_SIZE[1], 1)) conv_1 = Conv2D(128, (3, 3), padding='same', activation='relu') conv_2 = Conv2D(16, (3, 3), padding='same', activation='relu') conv_3 = Conv2D(4, (3, 3), padding='same', activation='relu') conv_4 = Conv2D(1, (1, 1), padding='same', activation='relu') flat_1 = Flatten() lamma = Lambda(chuz_top) stack = conv_1(input_1) stack = conv_2(stack) stack = conv_3(stack) stack = conv_4(stack) stack = flat_1(stack) stack = lamma(stack) m2 = Model(inputs=input_1, outputs=stack) m2.load_weights(fname) print m2.predict(x) '''
[ "keras.models.load_model", "numpy.random.uniform", "numpy.zeros", "os.path.exists", "numpy.array", "keras.layers.Conv2D", "keras.models.Sequential", "keras.backend.argmax" ]
[((2079, 2098), 'numpy.zeros', 'np.zeros', (['GRID_SIZE'], {}), '(GRID_SIZE)\n', (2087, 2098), True, 'import numpy as np\n'), ((2497, 2509), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2507, 2509), False, 'from keras.models import Sequential, Model\n'), ((2915, 2933), 'keras.backend.argmax', 'K.argmax', (['input', '(1)'], {}), '(input, 1)\n', (2923, 2933), True, 'import keras.backend as K\n'), ((2522, 2626), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(3, 3)'], {'padding': '"""same"""', 'activation': '"""relu"""', 'input_shape': '(GRID_SIZE[0], GRID_SIZE[1], 1)'}), "(128, (3, 3), padding='same', activation='relu', input_shape=(\n GRID_SIZE[0], GRID_SIZE[1], 1))\n", (2528, 2626), False, 'from keras.layers import Conv2D, Lambda, Input, Flatten\n'), ((2635, 2688), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(3, 3)'], {'padding': '"""same"""', 'activation': '"""relu"""'}), "(16, (3, 3), padding='same', activation='relu')\n", (2641, 2688), False, 'from keras.layers import Conv2D, Lambda, Input, Flatten\n'), ((2702, 2754), 'keras.layers.Conv2D', 'Conv2D', (['(4)', '(3, 3)'], {'padding': '"""same"""', 'activation': '"""relu"""'}), "(4, (3, 3), padding='same', activation='relu')\n", (2708, 2754), False, 'from keras.layers import Conv2D, Lambda, Input, Flatten\n'), ((2768, 2820), 'keras.layers.Conv2D', 'Conv2D', (['(1)', '(1, 1)'], {'padding': '"""same"""', 'activation': '"""relu"""'}), "(1, (1, 1), padding='same', activation='relu')\n", (2774, 2820), False, 'from keras.layers import Conv2D, Lambda, Input, Flatten\n'), ((3270, 3281), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (3278, 3281), True, 'import numpy as np\n'), ((3290, 3301), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (3298, 3301), True, 'import numpy as np\n'), ((3431, 3452), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (3445, 3452), False, 'import os\n'), ((3688, 3705), 'keras.models.load_model', 'load_model', (['fname'], {}), '(fname)\n', (3698, 3705), False, 'from keras.models import load_model\n'), ((3745, 3760), 'numpy.array', 'np.array', (['[xxx]'], {}), '([xxx])\n', (3753, 3760), True, 'import numpy as np\n'), ((502, 530), 'numpy.random.uniform', 'np.random.uniform', (['(-100)', '(200)'], {}), '(-100, 200)\n', (519, 530), True, 'import numpy as np\n')]
#! /usr/bin/python # -*- coding: utf-8 -*- """ MobileNetV1 for ImageNet using TL models - mobilenetv2 : https://github.com/tensorflow/models/tree/master/research/slim/nets/mobilenet - tf.slim : https://github.com/tensorflow/models/tree/master/research/slim#pre-trained-models """ import time import numpy as np import tensorflow as tf import tensorlayer as tl from tensorlayer.models.imagenet_classes import class_names tf.logging.set_verbosity(tf.logging.DEBUG) tl.logging.set_verbosity(tl.logging.DEBUG) x = tf.placeholder(tf.float32, [None, 224, 224, 3]) # get the whole model mobilenetv1 = tl.models.MobileNetV1(x) # restore pre-trained parameters sess = tf.InteractiveSession() mobilenetv1.restore_params(sess) probs = tf.nn.softmax(mobilenetv1.outputs) mobilenetv1.print_params(False) mobilenetv1.print_layers() img1 = tl.vis.read_image('data/tiger.jpeg') img1 = tl.prepro.imresize(img1, (224, 224)) / 255 _ = sess.run(probs, feed_dict={x: [img1]})[0] # 1st time takes time to compile start_time = time.time() prob = sess.run(probs, feed_dict={x: [img1]})[0] print(" End time : %.5ss" % (time.time() - start_time)) preds = (np.argsort(prob)[::-1])[0:5] for p in preds: print(class_names[p], prob[p])
[ "tensorflow.nn.softmax", "tensorlayer.vis.read_image", "tensorlayer.logging.set_verbosity", "tensorlayer.models.MobileNetV1", "tensorflow.logging.set_verbosity", "time.time", "numpy.argsort", "tensorflow.placeholder", "tensorlayer.prepro.imresize", "tensorflow.InteractiveSession" ]
[((427, 469), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.DEBUG'], {}), '(tf.logging.DEBUG)\n', (451, 469), True, 'import tensorflow as tf\n'), ((470, 512), 'tensorlayer.logging.set_verbosity', 'tl.logging.set_verbosity', (['tl.logging.DEBUG'], {}), '(tl.logging.DEBUG)\n', (494, 512), True, 'import tensorlayer as tl\n'), ((518, 565), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 224, 224, 3]'], {}), '(tf.float32, [None, 224, 224, 3])\n', (532, 565), True, 'import tensorflow as tf\n'), ((603, 627), 'tensorlayer.models.MobileNetV1', 'tl.models.MobileNetV1', (['x'], {}), '(x)\n', (624, 627), True, 'import tensorlayer as tl\n'), ((669, 692), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (690, 692), True, 'import tensorflow as tf\n'), ((736, 770), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['mobilenetv1.outputs'], {}), '(mobilenetv1.outputs)\n', (749, 770), True, 'import tensorflow as tf\n'), ((840, 876), 'tensorlayer.vis.read_image', 'tl.vis.read_image', (['"""data/tiger.jpeg"""'], {}), "('data/tiger.jpeg')\n", (857, 876), True, 'import tensorlayer as tl\n'), ((1021, 1032), 'time.time', 'time.time', ([], {}), '()\n', (1030, 1032), False, 'import time\n'), ((884, 920), 'tensorlayer.prepro.imresize', 'tl.prepro.imresize', (['img1', '(224, 224)'], {}), '(img1, (224, 224))\n', (902, 920), True, 'import tensorlayer as tl\n'), ((1148, 1164), 'numpy.argsort', 'np.argsort', (['prob'], {}), '(prob)\n', (1158, 1164), True, 'import numpy as np\n'), ((1112, 1123), 'time.time', 'time.time', ([], {}), '()\n', (1121, 1123), False, 'import time\n')]
import numpy as np from sklearn.linear_model import Ridge from sklearn.pipeline import make_pipeline from sklearn.preprocessing import PolynomialFeatures from pysurrogate.surrogate import Surrogate class PolynomialRegression(Surrogate): def __init__(self, n_degree): Surrogate.__init__(self) self.model = None self.n_degree = n_degree def _predict(self, X): F = self.model.predict(X) return F, np.zeros(X.shape[0]) def _fit(self, X, F): clf = make_pipeline(PolynomialFeatures(self.n_degree), Ridge()) clf.fit(X, F) self.model = clf return self @staticmethod def get_params(): val = [] for n_degree in [1, 2, 3, 5]: val.append({'n_degree': n_degree}) return val
[ "pysurrogate.surrogate.Surrogate.__init__", "sklearn.preprocessing.PolynomialFeatures", "numpy.zeros", "sklearn.linear_model.Ridge" ]
[((282, 306), 'pysurrogate.surrogate.Surrogate.__init__', 'Surrogate.__init__', (['self'], {}), '(self)\n', (300, 306), False, 'from pysurrogate.surrogate import Surrogate\n'), ((446, 466), 'numpy.zeros', 'np.zeros', (['X.shape[0]'], {}), '(X.shape[0])\n', (454, 466), True, 'import numpy as np\n'), ((522, 555), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', (['self.n_degree'], {}), '(self.n_degree)\n', (540, 555), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((557, 564), 'sklearn.linear_model.Ridge', 'Ridge', ([], {}), '()\n', (562, 564), False, 'from sklearn.linear_model import Ridge\n')]
#TSOPOURIDIS GRIGORIOS, AM:3358 import numpy as np import sys from PIL import Image import matplotlib.pyplot as plt #FIX TRACES OF OLD REMAINS #affine transformation function def affineTransformation(inputPath, outputPath, a1 ,a2 , a3, a4, a5, a6): inImage = np.array(Image.open(inputPath)) #affine transformation matrix #changed due to numpy axes being opposite from the usual, starting from 0,0 #affine = [[a1,a2,a3], [a1,a2,a3], [0,0,1]] #changed a? variables due to numpy coordinate system and transposed affine multiplication affine = [[a5,a2,a6], [a4,a1,a3], [0,0,1]] affine = np.array(affine) #print(affine) centeredCoord = [] #x image coordinates centered to the center of the image for i in range((int((-1)*np.floor(len(inImage)/2))),int(np.ceil(len(inImage)/2))): for j in range((int((-1)*np.floor(len(inImage[0])/2))),int(np.ceil(len(inImage[0])/2))): centeredCoord.append([i,j,1]) #application of affine transformation on the image #move image center to upper left corner again. centeredCoord = np.array(centeredCoord) x = int((-1)*np.floor(len(inImage)/2)) y = int(np.ceil(len(inImage[0])/2)) - 1 centeredCoord = centeredCoord + [-x,y,0] #centeredCoord * affine (transposed) centeredCoordAffine = np.matmul(centeredCoord, affine.T) tempIm = inImage.copy() inImage.fill(0) for (p1,p2) in zip(centeredCoord,centeredCoordAffine): if(p2[0] >= len(inImage) or p2[1] >= len(inImage[0]) or p2[0] < 0 or p2[1] < 0): #convert negative(inversed) coordinates to (image with negative scale) #0-imagesize-1 if(a5<0 or a1 < 0): if(not(p2[1] >= len(inImage[0])) and not(p2[0] >= len(inImage))): x1 = p2[0] y1 = p2[1] #x axis if(a5<0): x1 = len(inImage)+ p2[0]-1 #y axis if(a1<0): y1 = len(inImage)+p2[1]-1 #prevent image wrapping over the edges if(x1<0 or y1<0): continue #print((x1,y1)) inImage[x1][y1] = tempIm[p1[0]][p1[1]] else: inImage[p2[0]][p2[1]] = tempIm[p1[0]][p1[1]] #nearest neighbor interpolation #adjuct y due to inversed axis for x in range(0,len(inImage)): for y in range(0,len(inImage[0])): if(inImage[x][y] == 0 and x-1 < len(inImage)and x+1 < len(inImage) and y-1 < len(inImage[0])and y+1 < len(inImage[0])): if(inImage[x][y+1] != 0): inImage[x][y] = inImage[x][y+1] elif(inImage[x+1][y] != 0): inImage[x][y] = inImage[x+1][y] #edo #elif(inImage[x-1][y] != 0): # inImage[x][y] = inImage[x-1][y] elif(inImage[x][y-1] != 0 and y+2 < len(inImage[0])): if(inImage[x][y+2] != 0): inImage[x][y] = inImage[x][y-1] elif(inImage[x+1][y+1] != 0): inImage[x][y] = inImage[x+1][y+1] elif(inImage[x+1][y-1] != 0): inImage[x][y] = inImage[x+1][y-1] elif(inImage[x+1][y] != 0): inImage[x][y] = inImage[x+1][y] elif(inImage[x-1][y] != 0 and x+2 < len(inImage)): if(inImage[x+2][y] != 0): inImage[x][y] = inImage[x-1][y] elif(inImage[x-1][y+1] != 0): inImage[x][y] = inImage[x-1][y+1] elif(inImage[x-1][y-1] != 0): inImage[x][y] = inImage[x-1][y-1] #save the output image to the given file path plt.imshow(inImage, cmap="gray") plt.imsave(outputPath,inImage, cmap='gray') #main if __name__ == "__main__": if(not(len(sys.argv) == 9)): print("Incorrect format.") print("python3 ask2.py <input filename> <output filename> <a1> <a2> <a3> <a4> <a5> <a6>") else: affineTransformation(sys.argv[1],sys.argv[2],int(sys.argv[3]),int(sys.argv[4]),int(sys.argv[5]),int(sys.argv[6]),int(sys.argv[7]),int(sys.argv[8]))
[ "matplotlib.pyplot.imshow", "PIL.Image.open", "numpy.array", "matplotlib.pyplot.imsave", "numpy.matmul" ]
[((616, 632), 'numpy.array', 'np.array', (['affine'], {}), '(affine)\n', (624, 632), True, 'import numpy as np\n'), ((1092, 1115), 'numpy.array', 'np.array', (['centeredCoord'], {}), '(centeredCoord)\n', (1100, 1115), True, 'import numpy as np\n'), ((1321, 1355), 'numpy.matmul', 'np.matmul', (['centeredCoord', 'affine.T'], {}), '(centeredCoord, affine.T)\n', (1330, 1355), True, 'import numpy as np\n'), ((3964, 3996), 'matplotlib.pyplot.imshow', 'plt.imshow', (['inImage'], {'cmap': '"""gray"""'}), "(inImage, cmap='gray')\n", (3974, 3996), True, 'import matplotlib.pyplot as plt\n'), ((4001, 4045), 'matplotlib.pyplot.imsave', 'plt.imsave', (['outputPath', 'inImage'], {'cmap': '"""gray"""'}), "(outputPath, inImage, cmap='gray')\n", (4011, 4045), True, 'import matplotlib.pyplot as plt\n'), ((275, 296), 'PIL.Image.open', 'Image.open', (['inputPath'], {}), '(inputPath)\n', (285, 296), False, 'from PIL import Image\n')]
import os import sys from os.path import join as opj import base64 import struct import copy import numpy as np from scipy.spatial.distance import cdist import cv2 def parse_pt(pt_file): with open(pt_file) as f: lines = f.readlines() img_rects = dict() for line in lines: line = line.strip().split(',') fid, tid = int(float(line[0])), int(float(line[1])) rect = map(lambda x:int(float(x)), line[2:6]) rect[2] += rect[0] rect[3] += rect[1] fea = base64.b64decode(line[-1]) fea = struct.unpack('{}f'.format(len(fea)/4), fea) if tid not in img_rects: img_rects[tid] = list() rect.insert(0, fid) rect.append(fea) img_rects[tid].append(rect) return img_rects def parse_bias(timestamp_dir, scene_name): cid_bias = dict() for sname in scene_name: with open(opj(timestamp_dir, sname + '.txt')) as f: lines = f.readlines() for line in lines: line = line.strip().split(' ') cid = int(line[0][2:]) bias = float(line[1]) if cid not in cid_bias: cid_bias[cid] = bias return cid_bias def homography(data_dir): cid_arr = dict() for cid_name in os.listdir(data_dir): if '.' in cid_name: continue cid = int(cid_name[1:]) cal_path = opj(data_dir, cid_name, 'calibration.txt') with open(cal_path) as f: lines = f.readlines() datas = lines[0].strip().split(':')[-1].strip().split(';') arr = list() for data in datas: arr.append(map(float, data.split(' '))) arr = np.array(arr) cid_arr[cid] = arr return cid_arr if __name__ == '__main__': data_dir = '../data/feature/' roi_dir = '../data/roi/' save_dir = '../data/trajectory/' scene_name = ['S02', 'S05'] cid_bias = parse_bias('../data/Track1/cam_timestamp', scene_name) cid_arr = homography('../data/Track1/calibration/') txt_paths = os.listdir(data_dir) txt_paths = filter(lambda x: '.txt' in x, sorted(txt_paths, key=lambda x: int(x.split('.')[0][-3:]))) for txt_path in txt_paths: print('processing {}...'.format(txt_path)) cid = int(txt_path.split('.')[0][-3:]) f_w = open(opj(save_dir, txt_path), 'wb') cur_bias = cid_bias[cid] roi = cv2.imread(opj(roi_dir, '{}.jpg'.format(txt_path.split('.')[0])), 0) img_rects = parse_pt(opj(data_dir, txt_path)) tid_data = dict() for tid in img_rects: rects = img_rects[tid] if len(rects) == 0: continue tid_data[tid] = [cid] rects = sorted(rects, key=lambda x: x[0]) if cid != 15: tid_data[tid] += [cur_bias + rects[0][0] / 10., cur_bias + rects[-1][0] / 10.] # [enter, leave] else: tid_data[tid] += [cur_bias + rects[0][0] / 8., cur_bias + rects[-1][0] / 8.] # [enter, leave] all_fea = np.array([rect[-1] for rect in rects[int(0.3*len(rects)):int(0.7*len(rects)) + 1]]) mean_fea = np.mean(all_fea, axis=0) tid_data[tid] += mean_fea.tolist() for tid in tid_data: data = tid_data[tid] data.insert(1, tid) f_w.write(' '.join(map(str, data)) + '\n') f_w.close()
[ "base64.b64decode", "numpy.mean", "numpy.array", "os.path.join", "os.listdir" ]
[((1277, 1297), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (1287, 1297), False, 'import os\n'), ((2043, 2063), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (2053, 2063), False, 'import os\n'), ((514, 540), 'base64.b64decode', 'base64.b64decode', (['line[-1]'], {}), '(line[-1])\n', (530, 540), False, 'import base64\n'), ((1387, 1429), 'os.path.join', 'opj', (['data_dir', 'cid_name', '"""calibration.txt"""'], {}), "(data_dir, cid_name, 'calibration.txt')\n", (1390, 1429), True, 'from os.path import join as opj\n'), ((1679, 1692), 'numpy.array', 'np.array', (['arr'], {}), '(arr)\n', (1687, 1692), True, 'import numpy as np\n'), ((2318, 2341), 'os.path.join', 'opj', (['save_dir', 'txt_path'], {}), '(save_dir, txt_path)\n', (2321, 2341), True, 'from os.path import join as opj\n'), ((2494, 2517), 'os.path.join', 'opj', (['data_dir', 'txt_path'], {}), '(data_dir, txt_path)\n', (2497, 2517), True, 'from os.path import join as opj\n'), ((3135, 3159), 'numpy.mean', 'np.mean', (['all_fea'], {'axis': '(0)'}), '(all_fea, axis=0)\n', (3142, 3159), True, 'import numpy as np\n'), ((892, 926), 'os.path.join', 'opj', (['timestamp_dir', "(sname + '.txt')"], {}), "(timestamp_dir, sname + '.txt')\n", (895, 926), True, 'from os.path import join as opj\n')]
import numpy as np import pymc3 as pm class LinearModel: def __init__(self, name): self.name = name self.gmm = None def fit(self, y, yerr, x, gmm_params, sample_kwargs={}): """ yerr : The uncertainties (standard deviations) in measured y. """ x = np.asarray(x) y = np.asarray(y) yerr = np.asarray(yerr) # Left merge dictionary default_sample_kwargs = dict(draws=1000, tune=1000, chains=2) sample_kwargs = {**default_sample_kwargs, **sample_kwargs} nsamples = y.shape[0] assert gmm_params.shape[1] % 3 == 0, "GMM params shape 1 must multiple of 3." k = gmm_params.shape[1] // 3 mu_x = gmm_params[:, :k] sigma_x = gmm_params[:, k:2*k] weights_x = gmm_params[:, 2*k:3*k] with pm.Model() as model: # noqa # Priors intercept = pm.Uniform("intercept", -1, 1) slope = pm.Uniform("slope", -1, 0) scatter_sigma = pm.HalfNormal("scatter", 2) components = [] for i in range(k): component = pm.Normal.dist(mu=mu_x[:, i], sigma=sigma_x[:, i], shape=nsamples) components.append(component) x = pm.Mixture("x", w=weights_x, comp_dists=components, shape=nsamples) # Likelihoods # Constant value for true y which served as the mean value of the observed y y_true = pm.Deterministic("y_true", slope * x + intercept) # Standard deviation of observed y as Gaussian errors y_sigma = pm.Deterministic("sigma", pm.math.sqrt(yerr**2 + scatter_sigma**2)) # Altogether, observed y is normally distributed y_ = pm.Normal("y", mu=y_true, sigma=y_sigma, observed=y) trace = pm.sample(**sample_kwargs) return trace, model def run_model(self, *args, **kwargs): return self.fit(*args, **kwargs)
[ "pymc3.sample", "pymc3.Model", "pymc3.HalfNormal", "numpy.asarray", "pymc3.Deterministic", "pymc3.Normal", "pymc3.Normal.dist", "pymc3.math.sqrt", "pymc3.Uniform", "pymc3.Mixture" ]
[((318, 331), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (328, 331), True, 'import numpy as np\n'), ((344, 357), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (354, 357), True, 'import numpy as np\n'), ((373, 389), 'numpy.asarray', 'np.asarray', (['yerr'], {}), '(yerr)\n', (383, 389), True, 'import numpy as np\n'), ((844, 854), 'pymc3.Model', 'pm.Model', ([], {}), '()\n', (852, 854), True, 'import pymc3 as pm\n'), ((918, 948), 'pymc3.Uniform', 'pm.Uniform', (['"""intercept"""', '(-1)', '(1)'], {}), "('intercept', -1, 1)\n", (928, 948), True, 'import pymc3 as pm\n'), ((969, 995), 'pymc3.Uniform', 'pm.Uniform', (['"""slope"""', '(-1)', '(0)'], {}), "('slope', -1, 0)\n", (979, 995), True, 'import pymc3 as pm\n'), ((1024, 1051), 'pymc3.HalfNormal', 'pm.HalfNormal', (['"""scatter"""', '(2)'], {}), "('scatter', 2)\n", (1037, 1051), True, 'import pymc3 as pm\n'), ((1268, 1335), 'pymc3.Mixture', 'pm.Mixture', (['"""x"""'], {'w': 'weights_x', 'comp_dists': 'components', 'shape': 'nsamples'}), "('x', w=weights_x, comp_dists=components, shape=nsamples)\n", (1278, 1335), True, 'import pymc3 as pm\n'), ((1473, 1522), 'pymc3.Deterministic', 'pm.Deterministic', (['"""y_true"""', '(slope * x + intercept)'], {}), "('y_true', slope * x + intercept)\n", (1489, 1522), True, 'import pymc3 as pm\n'), ((1757, 1809), 'pymc3.Normal', 'pm.Normal', (['"""y"""'], {'mu': 'y_true', 'sigma': 'y_sigma', 'observed': 'y'}), "('y', mu=y_true, sigma=y_sigma, observed=y)\n", (1766, 1809), True, 'import pymc3 as pm\n'), ((1831, 1857), 'pymc3.sample', 'pm.sample', ([], {}), '(**sample_kwargs)\n', (1840, 1857), True, 'import pymc3 as pm\n'), ((1140, 1206), 'pymc3.Normal.dist', 'pm.Normal.dist', ([], {'mu': 'mu_x[:, i]', 'sigma': 'sigma_x[:, i]', 'shape': 'nsamples'}), '(mu=mu_x[:, i], sigma=sigma_x[:, i], shape=nsamples)\n', (1154, 1206), True, 'import pymc3 as pm\n'), ((1637, 1681), 'pymc3.math.sqrt', 'pm.math.sqrt', (['(yerr ** 2 + scatter_sigma ** 2)'], {}), '(yerr ** 2 + scatter_sigma ** 2)\n', (1649, 1681), True, 'import pymc3 as pm\n')]
""" detects cards using a web cam. needs a bit of hand-calibration. calibrate: - MIN_CARD_AREA, set to be minimum area for detecting a card - THRESHOLD, for thresholding dark/light values of the image - FILTER, for smoothing the image """ import cv2 import pygame import imutils import numpy as np import pygame.camera from pygame.locals import KEYDOWN, K_q, K_s, K_SPACE from . import util import argparse import glob DEBUG = False # calibrate this for camera position MIN_CARD_AREA = 250000.0 / 3 # calibrate these THRESHOLD = (100, 255) FILTER = (11, 17, 17) ROTATION = 0 # noinspection PyUnresolvedReferences def scan(img): # preprocess image gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.bilateralFilter(gray, FILTER[0], FILTER[1], FILTER[2]) ret, gray = cv2.threshold(gray, THRESHOLD[0], THRESHOLD[1], cv2.THRESH_BINARY) edges = imutils.auto_canny(gray) # extract contours cnts, _ = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = [c for c in cnts if cv2.contourArea(c) >= MIN_CARD_AREA] card, c = None, None if cnts: # get largest contour c = sorted(cnts, key=cv2.contourArea, reverse=True)[0] # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.05 * peri, True) pts = np.float32(approx) x, y, w, h = cv2.boundingRect(c) # Find center point of card by taking x and y average of the four corners. # average = np.sum(pts, axis=0)/len(pts) # cent_x = int(average[0][0]) # cent_y = int(average[0][1]) # center = [cent_x, cent_y] # Warp card into 200x300 flattened image using perspective transform card = util.flattener(img, pts, w, h) card = util.cv2_to_pil(card).rotate(ROTATION) return card, c, gray, edges # noinspection PyUnresolvedReferences def detect(on_detect): dim = (800, 600) pygame.init() pygame.camera.init() cams = pygame.camera.list_cameras() # print(cams) display = pygame.display.set_mode(dim, 0) cam = pygame.camera.Camera(cams[-1], dim) cam.start() capture = True while capture: img = cam.get_image() img = pygame.transform.scale(img, dim) img = util.pygame_to_cv2(img) card, c, gray, edges = scan(img) # q to quit for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_q: capture = False elif event.key == K_s or event.key == K_SPACE: if card is None: print('nothing found') else: on_detect(card) # display if c is not None: cv2.drawContours(img, [c], -1, (0, 0, 255), 3) img = util.cv2_to_pygame(img) display.blit(img, (0, 0)) pygame.display.update() if card is not None: card_img = util.pil_to_pygame(card) display.blit(card_img, (0, 0)) if DEBUG: for layer in [gray, edges]: layer = cv2.cvtColor(layer, cv2.COLOR_GRAY2RGB) layer = util.cv2_to_pygame(layer) layer.set_alpha(100) display.blit(layer, (0, 0)) pygame.display.flip() cam.stop() pygame.quit()
[ "cv2.approxPolyDP", "cv2.arcLength", "pygame.event.get", "cv2.bilateralFilter", "pygame.display.update", "pygame.camera.init", "cv2.contourArea", "cv2.cvtColor", "pygame.display.set_mode", "pygame.camera.list_cameras", "pygame.transform.scale", "cv2.drawContours", "cv2.boundingRect", "pyga...
[((670, 707), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (682, 707), False, 'import cv2\n'), ((719, 777), 'cv2.bilateralFilter', 'cv2.bilateralFilter', (['gray', 'FILTER[0]', 'FILTER[1]', 'FILTER[2]'], {}), '(gray, FILTER[0], FILTER[1], FILTER[2])\n', (738, 777), False, 'import cv2\n'), ((794, 860), 'cv2.threshold', 'cv2.threshold', (['gray', 'THRESHOLD[0]', 'THRESHOLD[1]', 'cv2.THRESH_BINARY'], {}), '(gray, THRESHOLD[0], THRESHOLD[1], cv2.THRESH_BINARY)\n', (807, 860), False, 'import cv2\n'), ((873, 897), 'imutils.auto_canny', 'imutils.auto_canny', (['gray'], {}), '(gray)\n', (891, 897), False, 'import imutils\n'), ((1954, 1967), 'pygame.init', 'pygame.init', ([], {}), '()\n', (1965, 1967), False, 'import pygame\n'), ((1972, 1992), 'pygame.camera.init', 'pygame.camera.init', ([], {}), '()\n', (1990, 1992), False, 'import pygame\n'), ((2004, 2032), 'pygame.camera.list_cameras', 'pygame.camera.list_cameras', ([], {}), '()\n', (2030, 2032), False, 'import pygame\n'), ((2065, 2096), 'pygame.display.set_mode', 'pygame.display.set_mode', (['dim', '(0)'], {}), '(dim, 0)\n', (2088, 2096), False, 'import pygame\n'), ((2107, 2142), 'pygame.camera.Camera', 'pygame.camera.Camera', (['cams[-1]', 'dim'], {}), '(cams[-1], dim)\n', (2127, 2142), False, 'import pygame\n'), ((3371, 3384), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (3382, 3384), False, 'import pygame\n'), ((1257, 1279), 'cv2.arcLength', 'cv2.arcLength', (['c', '(True)'], {}), '(c, True)\n', (1270, 1279), False, 'import cv2\n'), ((1297, 1335), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['c', '(0.05 * peri)', '(True)'], {}), '(c, 0.05 * peri, True)\n', (1313, 1335), False, 'import cv2\n'), ((1350, 1368), 'numpy.float32', 'np.float32', (['approx'], {}), '(approx)\n', (1360, 1368), True, 'import numpy as np\n'), ((1391, 1410), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (1407, 1410), False, 'import cv2\n'), ((2243, 2275), 'pygame.transform.scale', 'pygame.transform.scale', (['img', 'dim'], {}), '(img, dim)\n', (2265, 2275), False, 'import pygame\n'), ((2398, 2416), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (2414, 2416), False, 'import pygame\n'), ((2925, 2948), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (2946, 2948), False, 'import pygame\n'), ((3329, 3350), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (3348, 3350), False, 'import pygame\n'), ((2798, 2844), 'cv2.drawContours', 'cv2.drawContours', (['img', '[c]', '(-1)', '(0, 0, 255)', '(3)'], {}), '(img, [c], -1, (0, 0, 255), 3)\n', (2814, 2844), False, 'import cv2\n'), ((1038, 1056), 'cv2.contourArea', 'cv2.contourArea', (['c'], {}), '(c)\n', (1053, 1056), False, 'import cv2\n'), ((3153, 3192), 'cv2.cvtColor', 'cv2.cvtColor', (['layer', 'cv2.COLOR_GRAY2RGB'], {}), '(layer, cv2.COLOR_GRAY2RGB)\n', (3165, 3192), False, 'import cv2\n')]
#!/usr/bin/python3 # -*- coding: utf-8 -*- from warnings import warn from itertools import count import symengine import numpy as np from jitcdde.past import Past, Anchor import jitcdde._python_core as python_core from jitcxde_common import jitcxde, checker from jitcxde_common.helpers import sort_helpers, sympify_helpers, find_dependent_helpers from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function from jitcxde_common.transversal import GroupHandler import chspy _default_min_step = 1e-10 #sigmoid = lambda x: 1/(1+np.exp(-x)) #sigmoid = lambda x: 1 if x>0 else 0 sigmoid = lambda x: (np.tanh(x)+1)/2 #: the symbol for time for defining the differential equation. You may just as well define the an analogous symbol directly with SymEngine or SymPy, but using this function is the best way to get the most of future versions of JiTCDDE, in particular avoiding incompatibilities. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). t = symengine.Symbol("t", real=True) def y(index,time=t): """ the function representing the DDE’s past and present states used for defining the differential equation. The first integer argument denotes the component. The second, optional argument is a symbolic expression denoting the time. This automatically expands to using `current_y`, `past_y`, and `anchors`; so do not be surprised when you look at the output and it is different than what you entered or expected. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). """ if time == t: return current_y(index) else: return past_y(time, index, anchors(time)) def dy(index,time): """ This is the function representing the DDE’s past derivative used for defining the differential equation. The first integer argument denotes the component. The second, argument denotes the time. If you use this, you get a neutral DDE which may make addressing initial discontinuities more difficult. Do not use this to get the current derivative. Instead compute it using your dynamical equations. This will not work with tangential Lyapunov exponents. **This feature is experimental.** This automatically expands to using `current_y`, `past_y`, and `anchors`; so do not be surprised when you look at the output and it is different than what you entered or expected. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). """ if time == t: raise ValueError("Do not use `dy` to compute the current derivative. Use your dynamical equations instead.") else: return past_dy(time, index, anchors(time)) #: the symbol for the current state for defining the differential equation. It is a function and the integer argument denotes the component. This is only needed for specific optimisations of large DDEs; in all other cases use `y` instead. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). current_y = symengine.Function("current_y") #: the symbol for DDE’s past state for defining differential equation. It is a function with the first integer argument denoting the component and the second argument being a pair of past points (as being returned by `anchors`) from which the past state is interpolated (or, in rare cases, extrapolated). This is only needed for specific optimisations of large DDEs; in all other cases use `y` instead. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). past_y = symengine.Function("past_y") #: the symbol for DDE’s past derivative for defining differential equation. It is a function with the first integer argument denoting the component and the second argument being a pair of past points (as being returned by `anchors`) from which the past state is interpolated (or, in rare cases, extrapolated). This is only needed for specific optimisations of large DDEs; in all other cases use `dy` instead. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). past_dy = symengine.Function("past_dy") #: the symbol representing two anchors for defining the differential equation. It is a function and the float argument denotes the time point to which the anchors pertain. This is only needed for specific optimisations of large DDEs; in all other cases use `y` instead. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). anchors = symengine.Function("anchors") def _get_delays(f, helpers=()): delay_terms = set().union(*(collect_arguments(entry, anchors) for entry in f())) delay_terms.update(*(collect_arguments(helper[1], anchors) for helper in helpers)) delays = [ (t-delay_term[0]).simplify() for delay_term in delay_terms ] return [0]+delays def _find_max_delay(delays): if all(symengine.sympify(delay).is_Number for delay in delays): return float(symengine.sympify(max(delays)).n(real=True)) else: raise ValueError("Delay depends on time or dynamics; cannot determine max_delay automatically. You have to pass it as an argument to jitcdde.") def _propagate_delays(delays, p, threshold=1e-5): result = [0] if p!=0: for delay in _propagate_delays(delays, p-1, threshold): for other_delay in delays: new_entry = delay + other_delay for old_entry in result: if abs(new_entry-old_entry) < threshold: break else: result.append(new_entry) return result def quadrature(integrand,variable,lower,upper,nsteps=20,method="gauss"): """ If your DDE contains an integral over past points, this utility function helps you to implement it. It returns an estimator of the integral from evaluations of the past at discrete points, employing a numerical quadrature. You probably want to disable automatic simplifications when using this. Parameters ---------- integrand : symbolic expression variable : symbol variable of integration lower, upper : expressions lower and upper limit of integration nsteps : integer number of sampling steps. This should be chosen sufficiently high to capture all relevant aspects of your dynamics. method : `"midpoint"` or `"gauss"` which method to use for numerical integration. So far Gauß–Legendre quadrature (`"gauss"`; needs SymPy) and the midpoint rule (`"midpoint"`) are available. Use the midpoint rule if you expect your integrand to exhibit structure on a time scale smaller than (`upper` − `lower`)/`nsteps`. Otherwise or when in doubt, use `"gauss"`. """ sample = lambda pos: integrand.subs(variable,pos) if method == "midpoint": half_step = (symengine.sympify(upper-lower)/symengine.sympify(nsteps)/2).simplify() return 2*half_step*sum( sample(lower+(1+2*i)*half_step) for i in range(nsteps) ) elif method == "gauss": from sympy.integrals.quadrature import gauss_legendre factor = (symengine.sympify(upper-lower)/2).simplify() return factor*sum( weight*sample(lower+(1+pos)*factor) for pos,weight in zip(*gauss_legendre(nsteps,20)) ) else: raise NotImplementedError("I know no integration method named %s."%method) class UnsuccessfulIntegration(Exception): """ This exception is raised when the integrator cannot meet the accuracy and step-size requirements. If you want to know the exact state of your system before the integration fails or similar, catch this exception. """ pass class jitcdde(jitcxde): """ Parameters ---------- f_sym : iterable of symbolic expressions or generator function yielding symbolic expressions or dictionary If an iterable or generator function, the `i`-th element is the `i`-th component of the value of the DDE’s derivative :math:`f(t,y)`. If a dictionary, it has to map the dynamical variables to its derivatives and the dynamical variables must be `y(0), y(1), …`. helpers : list of length-two iterables, each containing a symbol and an expression Each helper is a variable that will be calculated before evaluating the derivative and can be used in the latter’s computation. The first component of the tuple is the helper’s symbol as referenced in the derivative or other helpers, the second component describes how to compute it from `t`, `y` and other helpers. This is for example useful to realise a mean-field coupling, where the helper could look like `(mean, sum(y(i) for i an range(100))/100)`. (See `the JiTCODE documentation <http://jitcode.readthedocs.io/#module-SW_of_Roesslers>`_ for an example.) n : integer Length of `f_sym`. While JiTCDDE can easily determine this itself (and will, if necessary), this may take some time if `f_sym` is a generator function and `n` is large. Take care that this value is correct – if it isn’t, you will not get a helpful error message. delays : iterable of expressions or floats The delays of the dynamics. If not given, JiTCDDE will determine these itself if needed. However, this may take some time if `f_sym` is large. Take care that these are correct – if they aren’t, you won’t get a helpful error message. max_delay : number Maximum delay. In case of constant delays and if not given, JiTCDDE will determine this itself. However, this may take some time if `f_sym` is large and `delays` is not given. Take care that this value is not too small – if it is, you will not get a helpful error message. If this value is too large, you may run into memory issues for long integration times and calculating Lyapunov exponents (with `jitcdde_lyap`) may take forever. control_pars : list of symbols Each symbol corresponds to a control parameter that can be used when defining the equations and set after compilation with `set_parameters`. Using this makes sense if you need to do a parameter scan with short integrations for each parameter and you are spending a considerable amount of time compiling. callback_functions : iterable Python functions that should be called at integration time (callback) when evaluating the derivative. Each element of the iterable represents one callback function as a tuple containing (in that order): * A SymEngine function object used in `f_sym` to represent the function call. If you want to use any JiTCDDE features that need the derivative, this must have a properly defined `f_diff` method with the derivative being another callback function (or constant). * The Python function to be called. This function will receive the state array (`y`) as the first argument. All further arguments are whatever you use as arguments of the SymEngine function in `f_sym`. These can be any expression that you might use in the definition of the derivative and contain, e.g., dynamical variables (current or delayed), time, control parameters, and helpers. The only restriction is that the arguments are floats (and not vectors, anchors or similar). The return value must also be a float (or something castable to float). It is your responsibility to ensure that this function adheres to these criteria, is deterministic and sufficiently smooth with respect its arguments; expect nasty errors otherwise. * The number of arguments, **excluding** the state array as mandatory first argument. This means if you have a variadic Python function, you cannot just call it with different numbers of arguments in `f_sym`, but you have to define separate callbacks for each of numer of arguments. See `this example <https://github.com/neurophysik/jitcdde/blob/master/examples/sunflower_callback.py>`_ for how to use this. verbose : boolean Whether JiTCDDE shall give progress reports on the processing steps. module_location : string location of a module file from which functions are to be loaded (see `save_compiled`). If you use this, you need not give `f_sym` as an argument, but then you must give `n` and `max_delay`. If you used `control_pars` or `callback_functions`, you have to provide them again. Also note that the integrator may lack some functionalities, depending on the arguments you provide. """ dynvar = current_y def __init__( self, f_sym = (), *, helpers = None, n = None, delays = None, max_delay = None, control_pars = (), callback_functions = (), verbose = True, module_location = None ): super(jitcdde,self).__init__(n,verbose,module_location) self.f_sym = self._handle_input(f_sym) if not hasattr(self,"n_basic"): self.n_basic = self.n self.helpers = sort_helpers(sympify_helpers(helpers or [])) self.control_pars = control_pars self.callback_functions = callback_functions self.initiate_past() self.integration_parameters_set = False self.DDE = None self.verbose = verbose self.delays = delays self.max_delay = max_delay self.initial_discontinuities_handled = False def initiate_past(self): self.past = Past( n=self.n, n_basic=self.n_basic ) @property def delays(self): if self._delays is None: self.delays = _get_delays(self.f_sym, self.helpers) return self._delays @delays.setter def delays(self, new_delays): self._delays = new_delays if (self._delays is not None) and (0 not in self._delays): self._delays.append(0) @property def max_delay(self): if self._max_delay is None: self._max_delay = _find_max_delay(self.delays) assert self._max_delay >= 0.0, "Negative maximum delay." return self._max_delay @max_delay.setter def max_delay(self, new_max_delay): if new_max_delay is not None: assert new_max_delay >= 0.0, "Negative maximum delay." self._max_delay = new_max_delay @checker def _check_non_empty(self): self._check_assert( self.f_sym(), "f_sym is empty." ) @checker def _check_valid_arguments(self): for i,entry in enumerate(self.f_sym()): indizes = [argument[0] for argument in collect_arguments(entry,current_y)] indizes += [argument[1] for argument in collect_arguments(entry,past_y )] indizes += [argument[1] for argument in collect_arguments(entry,past_dy )] for index in indizes: self._check_assert( index >= 0, "y is called with a negative argument (%i) in equation %i." % (index,i), ) self._check_assert( index < self.n, "y is called with an argument (%i) higher than the system’s dimension (%i) in equation %i." % (index,self.n,i), ) @checker def _check_valid_symbols(self): valid_symbols = [t] + [helper[0] for helper in self.helpers] + list(self.control_pars) for i,entry in enumerate(self.f_sym()): for symbol in entry.atoms(symengine.Symbol): self._check_assert( symbol in valid_symbols, "Invalid symbol (%s) in equation %i." % (symbol.name,i), ) def add_past_point(self, time, state, derivative): """ adds an anchor from which the initial past of the DDE is interpolated. Parameters ---------- time : float the temporal position of the anchor. state : iterable of floats the state of the anchor. The dimension of the array must match the dimension of the differential equation (`n`). derivative : iterable of floats the derivative at the anchor. The dimension of the array must match the dimension of the differential equation (`n`). """ self.reset_integrator(idc_unhandled=True) self.past.add((time,state,derivative)) def add_past_points(self, anchors): """ adds multiple anchors from which the past of the DDE is interpolated. Parameters ---------- anchors : iterable of tuples Each tuple must have components corresponding to the arguments of `add_past_point`. """ self.reset_integrator(idc_unhandled=True) for anchor in anchors: self.past.add(anchor) def constant_past(self,state,time=0): """ initialises the past with a constant state. Parameters ---------- state : iterable of floats The length must match the dimension of the differential equation (`n`). time : float The time at which the integration starts. """ self.reset_integrator(idc_unhandled=True) self.past.constant(state,time) def past_from_function(self,function,times_of_interest=None,max_anchors=100,tol=5): """ automatically determines anchors describing the past of the DDE from a given function, i.e., a piecewise cubic Hermite interpolation of the function at automatically selected time points will be the initial past. As this process involves heuristics, it is not perfect. For a better control of the initial conditions, use `add_past_point`. Parameters ---------- function : callable or iterable of symbolic expressions If callable, this takes the time as an argument and returns an iterable of floats that is the initial state of the past at that time. If an iterable of expressions, each expression represents how the initial past of the respective component depends on `t` (requires SymPy). In both cases, the lengths of the iterable must match the dimension of the differential equation (`n`). times_of_interest : iterable of numbers or `None` Initial set of time points considered for the interpolation. The highest value will be the starting point of the integration. Further interpolation anchors may be added in between the given anchors depending on heuristic criteria. If `None`, these will be automatically chosen depending on the maximum delay and the integration will start at :math:`t=0`. max_anchors : positive integer The maximum number of anchors that this routine will create (including those for the times_of_interest). tol : integer This is a parameter for the heuristics, more precisely the number of digits considered for precision in several places. The higher this value, the more likely it is that the heuristic adds anchors. """ self.reset_integrator(idc_unhandled=True) if times_of_interest is None: times_of_interest = np.linspace(-self.max_delay,0,10) else: times_of_interest = sorted(times_of_interest) self.past.from_function(function,times_of_interest,max_anchors,tol) def get_state(self): """ Returns an object that represents all anchors currently used by the integrator, which compeletely define the current state. The object is a `CubicHermiteSpline <https://chspy.readthedocs.io>`_ instance (with a few special extensions for JiTCDDE), which allows you to extract all sorts of information from it if you want. The format can also be used as an argument for `add_past_points`. An example where this is useful is when you want to switch between plain integration and one that also obtains Lyapunov exponents. You can also use this to implement time-dependent equations, however, you need to be careful to truncate the result properly. Moreover, if your delay changes, you may need to set the `max_delay` accordingly to avoid too much past being discarded before you call this method. If you reinitialise this integrator after calling this, this past will be used. """ self._initiate() self.DDE.forget(self.max_delay) self.past.clear() self.past.extend(self.DDE.get_full_state()) return self.past def purge_past(self): """ Clears the past and resets the integrator. You need to define a new past (using `add_past_point`) after this. """ self.past.clear() self.reset_integrator(idc_unhandled=True) def reset_integrator(self,idc_unhandled=False): """ Resets the integrator, forgetting all integration progress and forcing re-initiation when it is needed next. """ if idc_unhandled: self.initial_discontinuities_handled = False self.DDE = None def generate_lambdas(self,simplify=None): """ Explicitly initiates a purely Python-based integrator. Parameter --------- simplify : boolean Whether the derivative should be `simplified <http://docs.sympy.org/dev/modules/simplify/simplify.html>`_ (with `ratio=1.0`). The main reason why you could want to disable this is if your derivative is already optimised and so large that simplifying takes a considerable amount of time. If `None`, this will be automatically disabled for `n>10`. """ if simplify is None: simplify = self.n<=10 if self.callback_functions: raise NotImplementedError("Callbacks do not work with lambdification. You must use the C backend.") assert len(self.past)>1, "You need to add at least two past points first. Usually this means that you did not set an initial past at all." self.DDE = python_core.dde_integrator( self.f_sym, self.past, self.helpers, self.control_pars, simplify=simplify, ) self.compile_attempt = False def _compile_C(self, *args, **kwargs): self.compile_C(*args, **kwargs) def compile_C( self, simplify = None, do_cse = False, chunk_size = 100, extra_compile_args = None, extra_link_args = None, verbose = False, modulename = None, omp = False, ): """ translates the derivative to C code using SymEngine’s `C-code printer <https://github.com/symengine/symengine/pull/1054>`_. For detailed information many of the arguments and other ways to tweak the compilation, read `these notes <jitcde-common.readthedocs.io>`_. Parameters ---------- simplify : boolean Whether the derivative should be `simplified <http://docs.sympy.org/dev/modules/simplify/simplify.html>`_ (with `ratio=1.0`) before translating to C code. The main reason why you could want to disable this is if your derivative is already optimised and so large that simplifying takes a considerable amount of time. If `None`, this will be automatically disabled for `n>10`. do_cse : boolean Whether SymPy’s `common-subexpression detection <http://docs.sympy.org/dev/modules/rewriting.html#module-sympy.simplify.cse_main>`_ should be applied before translating to C code. This is worthwile if your DDE contains the same delay more than once. Otherwise it is almost always better to let the compiler do this (unless you want to set the compiler optimisation to `-O2` or lower). As this requires all entries of `f` at once, it may void advantages gained from using generator functions as an input. Also, this feature uses SymPy and not SymEngine. chunk_size : integer If the number of instructions in the final C code exceeds this number, it will be split into chunks of this size. See `Handling very large differential equations <http://jitcde-common.readthedocs.io/#handling-very-large-differential-equations>`_ on why this is useful and how to best choose this value. If smaller than 1, no chunking will happen. extra_compile_args : iterable of strings extra_link_args : iterable of strings Arguments to be handed to the C compiler or linker, respectively. verbose : boolean Whether the compiler commands shall be shown. This is the same as Setuptools’ `verbose` setting. modulename : string or `None` The name used for the compiled module. omp : pair of iterables of strings or boolean What compiler arguments shall be used for multiprocessing (using OpenMP). If `True`, they will be selected automatically. If empty or `False`, no compilation for multiprocessing will happen (unless you supply the relevant compiler arguments otherwise). """ self.compile_attempt = False f_sym_wc = self.f_sym() helpers_wc = list(self.helpers) # list is here for copying if simplify is None: simplify = self.n<=10 if simplify: f_sym_wc = (entry.simplify(ratio=1.0) for entry in f_sym_wc) if do_cse: import sympy additional_helper = sympy.Function("additional_helper") _cse = sympy.cse( sympy.Matrix(sympy.sympify(list(f_sym_wc))), symbols = (additional_helper(i) for i in count()) ) helpers_wc.extend(symengine.sympify(_cse[0])) f_sym_wc = symengine.sympify(_cse[1][0]) arguments = [ ("self", "dde_integrator * const"), ("t", "double const"), ("y", "double", self.n), ] helper_i = 0 anchor_i = 0 converted_helpers = [] self.past_calls = 0 self.substitutions = { control_par: symengine.Symbol("self->parameter_"+control_par.name) for control_par in self.control_pars } def finalise(expression): expression = expression.subs(self.substitutions) self.past_calls += count_calls(expression,anchors) return expression if helpers_wc: get_helper = symengine.Function("get_f_helper") set_helper = symengine.Function("set_f_helper") get_anchor = symengine.Function("get_f_anchor_helper") set_anchor = symengine.Function("set_f_anchor_helper") for helper in helpers_wc: if ( type(helper[1]) == type(anchors(0)) and helper[1].get_name() == anchors.name ): converted_helpers.append(set_anchor(anchor_i, finalise(helper[1]))) self.substitutions[helper[0]] = get_anchor(anchor_i) anchor_i += 1 else: converted_helpers.append(set_helper(helper_i, finalise(helper[1]))) self.substitutions[helper[0]] = get_helper(helper_i) helper_i += 1 if helper_i: arguments.append(("f_helper","double", helper_i)) if anchor_i: arguments.append(("f_anchor_helper","anchor", anchor_i)) self.render_and_write_code( converted_helpers, name = "helpers", chunk_size = chunk_size, arguments = arguments, omp = False, ) set_dy = symengine.Function("set_dy") self.render_and_write_code( (set_dy(i,finalise(entry)) for i,entry in enumerate(f_sym_wc)), name = "f", chunk_size = chunk_size, arguments = arguments + [("dY", "double", self.n)] ) if not self.past_calls: warn("Differential equation does not include a delay term.") self._process_modulename(modulename) self._render_template( n = self.n, number_of_helpers = helper_i, number_of_anchor_helpers = anchor_i, has_any_helpers = anchor_i or helper_i, anchor_mem_length = self.past_calls, n_basic = self.n_basic, control_pars = [par.name for par in self.control_pars], tangent_indices = self.tangent_indices if hasattr(self,"tangent_indices") else [], chunk_size = chunk_size, # only for OMP callbacks = [(fun.name,n_args) for fun,_,n_args in self.callback_functions], ) self._compile_and_load(verbose,extra_compile_args,extra_link_args,omp) def _initiate(self): if self.compile_attempt is None: self._attempt_compilation() if self.DDE is None: assert len(self.past)>1, "You need to add at least two past points first. Usually this means that you did not set an initial past at all." if self.compile_attempt: self.DDE = self.jitced.dde_integrator( self.past, *[callback for _,callback,_ in self.callback_functions], ) else: self.generate_lambdas() self._set_integration_parameters() def set_parameters(self, *parameters): """ Set the control parameters defined by the `control_pars` argument of the `jitcdde`. Note that you probably want to use `purge_past` and address initial discontinuities every time after you do this. Parameters ---------- parameters : floats Values of the control parameters. You can also use a single iterable containing these. Either way, the order must be the same as in the `control_pars` argument of the `jitcdde`. """ self._initiate() self.initial_discontinuities_handled = False try: self.DDE.set_parameters(*parameters[0]) except TypeError: self.DDE.set_parameters(*parameters) else: if len(parameters)>1: raise TypeError("Argument must either be a single sequence or multiple numbers.") def _set_integration_parameters(self): if not self.integration_parameters_set: self.report("Using default integration parameters.") self.set_integration_parameters() def set_integration_parameters(self, atol = 1e-10, rtol = 1e-5, first_step = 1.0, min_step = _default_min_step, max_step = 10.0, decrease_threshold = 1.1, increase_threshold = 0.5, safety_factor = 0.9, max_factor = 5.0, min_factor = 0.2, pws_factor = 3, pws_atol = 0.0, pws_rtol = 1e-5, pws_max_iterations = 10, pws_base_increase_chance = 0.1, pws_fuzzy_increase = False, ): """ Sets the parameters for the step-size adaption. Arguments starting with `pws` (past within step) are only relevant if the delay is shorter than the step size. Parameters ---------- atol : float rtol : float The tolerance of the estimated integration error is determined as :math:`\\texttt{atol} + \\texttt{rtol}·|y|`. The step-size adaption algorithm is the same as for the GSL. For details see `its documentation <http://www.gnu.org/software/gsl/manual/html_node/Adaptive-Step_002dsize-Control.html>`_. first_step : float The step-size adaption starts with this value. min_step : float Should the step-size have to be adapted below this value, the integration is aborted and `UnsuccessfulIntegration` is raised. max_step : float The step size will be capped at this value. decrease_threshold : float If the estimated error divided by the tolerance exceeds this, the step size is decreased. increase_threshold : float If the estimated error divided by the tolerance is smaller than this, the step size is increased. safety_factor : float To avoid frequent adaption, all freshly adapted step sizes are multiplied with this factor. max_factor : float min_factor : float The maximum and minimum factor by which the step size can be adapted in one adaption step. pws_factor : float Factor of step-size adaptions due to a delay shorter than the time step. If dividing the step size by `pws_factor` moves the delay out of the time step, it is done. If this is not possible, if the iterative algorithm does not converge within `pws_max_iterations`, or if it converges within fewer iterations than `pws_factor`, the step size is decreased or increased, respectively, by this factor. pws_atol : float pws_rtol : float If the difference between two successive iterations is below the tolerance determined with these parameters, the iterations are considered to have converged. pws_max_iterations : integer The maximum number of iterations before the step size is decreased. pws_base_increase_chance : float If the normal step-size adaption calls for an increase and the step size was adapted due to the past lying within the step, there is at least this chance that the step size is increased. pws_fuzzy_increase : boolean Whether the decision to try to increase the step size shall depend on chance. The upside of this is that it is less likely that the step size gets locked at a unnecessarily low value. The downside is that the integration is not deterministic anymore. If False, increase probabilities will be added up until they exceed 0.9, in which case an increase happens. """ if first_step > max_step: first_step = max_step warn("Decreasing first_step to match max_step") if min_step > first_step: min_step = first_step warn("Decreasing min_step to match first_step") assert decrease_threshold>=1.0, "decrease_threshold smaller than 1" assert increase_threshold<=1.0, "increase_threshold larger than 1" assert max_factor>=1.0, "max_factor smaller than 1" assert min_factor<=1.0, "min_factor larger than 1" assert safety_factor<=1.0, "safety_factor larger than 1" assert atol>=0.0, "negative atol" assert rtol>=0.0, "negative rtol" if atol==0 and rtol==0: warn("atol and rtol are both 0. You probably do not want this.") assert pws_atol>=0.0, "negative pws_atol" assert pws_rtol>=0.0, "negative pws_rtol" assert 0<pws_max_iterations, "non-positive pws_max_iterations" assert 2<=pws_factor, "pws_factor smaller than 2" assert pws_base_increase_chance>=0, "negative pws_base_increase_chance" self.atol = atol self.rtol = rtol self.dt = first_step self.min_step = min_step self.max_step = max_step self.decrease_threshold = decrease_threshold self.increase_threshold = increase_threshold self.safety_factor = safety_factor self.max_factor = max_factor self.min_factor = min_factor self.pws_atol = pws_atol self.pws_rtol = pws_rtol self.pws_max_iterations = pws_max_iterations self.pws_factor = pws_factor self.pws_base_increase_chance = pws_base_increase_chance self.q = 3. self.last_pws = False self.count = 0 if pws_fuzzy_increase: self.do_increase = lambda p: np.random.random() < p else: self.increase_credit = 0.0 def do_increase(p): self.increase_credit += p if self.increase_credit >= 0.9: self.increase_credit = 0.0 return True else: return False self.do_increase = do_increase self.integration_parameters_set = True def _control_for_min_step(self): if self.dt < self.min_step: message = (["", "Could not integrate with the given tolerance parameters:\n", "atol: %e" % self.atol, "rtol: %e" % self.rtol, "min_step: %e\n" % self.min_step, "The most likely reasons for this are:", ]) if not self.initial_discontinuities_handled: message.append("• You did not sufficiently address initial discontinuities. See https://jitcdde.rtfd.io/#discontinuities for details.") message.append("• The DDE is ill-posed or stiff.") if self.initial_discontinuities_handled: message.append("• You used `integrate_blindly` and did not adjust the maximum step or you used `adjust_diff` and did not pay attention to the extrema.") if self.atol==0: message.append("• You did not allow for an absolute error tolerance (atol) though your DDE calls for it. Even a very small absolute tolerance (1e-16) may sometimes help.") raise UnsuccessfulIntegration("\n".join(message)) def _increase_chance(self, new_dt): q = new_dt/self.last_pws is_explicit = sigmoid(1-q) far_from_explicit = sigmoid(q-self.pws_factor) few_iterations = sigmoid(1-self.count/self.pws_factor) profile = is_explicit+far_from_explicit*few_iterations return profile + self.pws_base_increase_chance*(1-profile) def _adjust_step_size(self): p = self.DDE.get_p(self.atol, self.rtol) if p > self.decrease_threshold: self.dt *= max(self.safety_factor*p**(-1/self.q), self.min_factor) self._control_for_min_step() return False else: if p <= self.increase_threshold: factor = self.safety_factor*p**(-1/(self.q+1)) if p else self.max_factor new_dt = min( self.dt*min(factor, self.max_factor), self.max_step ) if (not self.last_pws) or self.do_increase(self._increase_chance(new_dt)): self.dt = new_dt self.count = 0 self.last_pws = False return True @property def t(self): """ Returns ------- time : float The current time of the integrator. """ self._initiate() return self.DDE.get_t() def integrate(self, target_time): """ Tries to evolve the dynamics. Parameters ---------- target_time : float time until which the dynamics is evolved Returns ------- state : NumPy array the computed state of the system at `target_time`. """ self._initiate() if self.DDE.get_t() > target_time: warn("The target time is smaller than the current time. No integration step will happen. The returned state will be extrapolated from the interpolating Hermite polynomial for the last integration step. You may see this because you try to integrate backwards in time, in which case you did something wrong. You may see this just because your sampling step is small, in which case there is no need to worry.") if not self.initial_discontinuities_handled: warn("You did not explicitly handle initial discontinuities. Proceed only if you know what you are doing. This is only fine if you somehow chose your initial past such that the derivative of the last anchor complies with the DDE. In this case, you can set the attribute `initial_discontinuities_handled` to `True` to suppress this warning. See https://jitcdde.rtfd.io/#discontinuities for details.") while self.DDE.get_t() < target_time: if self.try_single_step(self.dt): self.DDE.accept_step() result = self.DDE.get_recent_state(target_time) self.DDE.forget(self.max_delay) return result def try_single_step(self,length): self.DDE.get_next_step(length) if self.DDE.past_within_step: self.last_pws = self.DDE.past_within_step # If possible, adjust step size to make integration explicit: if self.dt > self.pws_factor*self.DDE.past_within_step: self.dt /= self.pws_factor self._control_for_min_step() return False # Try to come within an acceptable error within pws_max_iterations iterations; otherwise adjust step size: for self.count in range(1,self.pws_max_iterations+1): self.DDE.get_next_step(self.dt) if self.DDE.check_new_y_diff(self.pws_atol, self.pws_rtol): break else: self.dt /= self.pws_factor self._control_for_min_step() return False return self._adjust_step_size() def adjust_diff(self,shift_ratio=1e-4): """ Performs a zero-amplitude (backwards) `jump` whose `width` is `shift_ratio` times the distance to the previous anchor into the past. See the documentation of `jump` for the caveats of this and see `discontinuities` for more information on why you almost certainly need to use this or an alternative way to address initial discontinuities. Returns ------- minima : NumPy array of floats maxima : NumPy array of floats The minima or maxima, respectively, of each component during the jump interval. See the documentation of `jump` on why you may want these. """ self._initiate() past = self.get_state() width = shift_ratio*(past[-1][0]-past[-2][0]) time = past[-1][0] self.initial_discontinuities_handled = True return self.jump(0,time,width,forward=False) def _prepare_blind_int(self, target_time, step): self._initiate() step = step or self.max_step assert step>0, "step must be positive" total_integration_time = target_time-self.DDE.get_t() if total_integration_time>0: if total_integration_time < step: step = total_integration_time number = int(round(total_integration_time/step)) dt = total_integration_time/number elif total_integration_time==0: number = 0 dt = 0 else: raise ValueError("Can’t integrate backwards in time.") assert abs(number*dt-total_integration_time)<1e-10 return dt, number, total_integration_time def integrate_blindly(self, target_time, step=None): """ Evolves the dynamics with a fixed step size ignoring any accuracy concerns. If a delay is smaller than the time step, the state is extrapolated from the previous step. See `discontinuities` for more information on why you almost certainly need to use this or an alternative way to address initial discontinuities. If the target time equals the current time, `adjust_diff` is called automatically. Parameters ---------- target_time : float time until which the dynamics is evolved. In most cases, this should be larger than the maximum delay. step : float aspired step size. The actual step size may be slightly adapted to make it divide the integration time. If `None`, `0`, or otherwise falsy, the maximum step size as set with `max_step` of `set_integration_parameters` is used. Returns ------- state : NumPy array the computed state of the system at `target_time`. """ self.initial_discontinuities_handled = True dt,number,_ = self._prepare_blind_int(target_time, step) if number == 0: self.adjust_diff() else: for _ in range(number): self.DDE.get_next_step(dt) self.DDE.accept_step() self.DDE.forget(self.max_delay) return self.DDE.get_current_state() def step_on_discontinuities( self, *, propagations = 1, min_distance = 1e-5, max_step = None, ): """ Assumes that the derivative is discontinuous at the start of the integration and chooses steps such that propagations of this point via the delays always fall on integration steps (or very close). Between these, adaptive steps are taken if necessary to keep the error within the bounds set by `set_integration_parameters`. If the discontinuity was propagated sufficiently often, it is considered to be smoothed and the integration is stopped. See `discontinuities` for more information on why you almost certainly need to use this or an alternative way to address initial discontinuities. This only makes sense if you just defined the past (via `add_past_point`) and start integrating, just reset the integrator, or changed control parameters. In case of an ODE, `adjust_diff` is used automatically. Parameters ---------- propagations : integer how often the discontinuity has to propagate to before it’s considered smoothed min_distance : float If two required steps are closer than this, they will be treated as one. max_step : float Retired parameter. Steps are now automatically adapted. Returns ------- state : NumPy array the computed state of the system after integration """ self._initiate() self.initial_discontinuities_handled = True assert min_distance > 0, "min_distance must be positive." assert isinstance(propagations,int), "Non-integer number of propagations." if max_step is not None: warn("The max_step parameter is retired and does not need to be used anymore. Instead, step_on_discontinuities now adapts the step size. This will raise an error in the future.") if not all(symengine.sympify(delay).is_number for delay in self.delays): raise ValueError("At least one delay depends on time or dynamics; cannot automatically determine steps.") self.delays = [ # This conversion is due to SymEngine.py issue #227 float(symengine.sympify(delay).n(real=True)) for delay in self.delays ] steps = _propagate_delays(self.delays, propagations, min_distance) steps.sort() steps.remove(0) if steps: for step in steps: target_time = self.t + step while True: current_time = self.DDE.get_t() if current_time >= target_time: break if self.try_single_step( min(self.dt,target_time-current_time) ): self.DDE.accept_step() result = self.DDE.get_recent_state(target_time) self.DDE.forget(self.max_delay) return result else: self.adjust_diff() return self.DDE.get_current_state()[:self.n_basic] def jump( self, amplitude, time, width=1e-5, forward=True ): """ Applies a jump to the state. Since this naturally introduces a discontinuity to the state, it can only be approximated. This is done by adding two anchors in a short temporal distance `width`. With other words, the jump is not instantaneous but just a strong change of the state over a small interval of length `width`. The slope after the jump is computed using the derivative `f`. A potential source of numerical issues is that the Hermite interpolant becomes extreme during the jump (due to Runge’s phenomenon). Whether this is a problem primarily depends on how these extrema influence delayed dependencies of your derivative. To allow you to estimate the magnitude of this, this function returns the extrema during the jump interval. There are two ways to address this: * Integrate with steps such that past values from the jump interval are avoided. You can use `integrate_blindly` to do this. * Increase the `width`. Note that due to the adapted derivative, there are no initial discontinuities after this. Parameters ---------- amplitude : NumPy array of floats The amplitude of the jump. time : float The time at which the jump shall happen. Usually this would be the last time to which you integrated. width : float The size of the jump interval (see above). The smaller you choose this, the sharper the jump, but the more likely are numerical problems in its wake. This should be smaller than all delays in the system. forward : boolean Whether the jump interval should begin after `time`. Otherwise it will end at `time` (equivalent to a forward jump starting at `time`−`width`). Returns ------- minima : NumPy array of floats maxima : NumPy array of floats The minima or maxima, respectively, of each component during the jump interval. See above on why you may want these. """ self._initiate() self.initial_discontinuities_handled = True assert width>=0 if np.ndim(amplitude)==0: amplitude = np.full(self.n,amplitude,dtype=float) amplitude = np.atleast_1d(np.array(amplitude,dtype=float)) assert amplitude.shape == (self.n,) if forward: return self.DDE.apply_jump( amplitude, time , width ) else: return self.DDE.apply_jump( amplitude, time-width, width ) def _jac(f, helpers, delay, n): dependent_helpers = [ find_dependent_helpers(helpers,y(i,t-delay)) for i in range(n) ] def line(f_entry): for j in range(n): entry = f_entry.diff(y(j,t-delay)) for helper in dependent_helpers[j]: entry += f_entry.diff(helper[0]) * helper[1] yield entry for f_entry in f(): yield line(f_entry) def tangent_vector_f(f, helpers, n, n_lyap, delays, zero_padding=0, simplify=True): if f: def f_lyap(): yield from f() for i in range(n_lyap): jacs = [_jac(f, helpers, delay, n) for delay in delays] for _ in range(n): expression = 0 for delay,jac in zip(delays,jacs): for k,entry in enumerate(next(jac)): expression += entry * y(k+(i+1)*n,t-delay) if simplify: expression = expression.simplify(ratio=1.0) yield expression for _ in range(zero_padding): yield symengine.sympify(0) else: return [] return f_lyap class jitcdde_lyap(jitcdde): """Calculates the Lyapunov exponents of the dynamics (see the documentation for more details). The handling is the same as that for `jitcdde` except for: Parameters ---------- n_lyap : integer Number of Lyapunov exponents to calculate. simplify : boolean Whether the differential equations for the separation function shall be `simplified <http://docs.sympy.org/dev/modules/simplify/simplify.html>`_ (with `ratio=1.0`). Doing so may speed up the time evolution but may slow down the generation of the code (considerably for large differential equations). If `None`, this will be automatically disabled for `n>10`. """ def __init__( self, f_sym=(), n_lyap=1, simplify=None, **kwargs ): self.n_basic = kwargs.pop("n",None) kwargs.setdefault("helpers",()) kwargs["helpers"] = sort_helpers(sympify_helpers(kwargs["helpers"] or [])) f_basic = self._handle_input(f_sym,n_basic=True) if simplify is None: simplify = self.n_basic<=10 if "delays" not in kwargs.keys() or not kwargs["delays"]: kwargs["delays"] = _get_delays(f_basic,kwargs["helpers"]) assert n_lyap>=0, "n_lyap negative" self._n_lyap = n_lyap f_lyap = tangent_vector_f( f = f_basic, helpers = kwargs["helpers"], n = self.n_basic, n_lyap = self._n_lyap, delays = kwargs["delays"], zero_padding = 0, simplify = simplify ) super(jitcdde_lyap, self).__init__( f_lyap, n = self.n_basic*(self._n_lyap+1), **kwargs ) assert self.max_delay>0, "Maximum delay must be positive for calculating Lyapunov exponents." def integrate(self, target_time): """ Like `jitcdde`’s `integrate`, except for orthonormalising the separation functions and: Returns ------- y : one-dimensional NumPy array The state of the system. Same as the output of `jitcdde`’s `integrate`. lyaps : one-dimensional NumPy array The “local” Lyapunov exponents as estimated from the growth or shrinking of the separation function during the integration time of this very `integrate` command. integration time : float The actual integration time during to which the local Lyapunov exponents apply. Note that this is not necessarily the difference between `target_time` and the previous `target_time` as JiTCDDE usually integrates a bit ahead and estimates the output via interpolation. When averaging the Lyapunov exponents, you almost always want to weigh them with the integration time. If the size of the advance by `integrate` (the sampling step) is smaller than the actual integration step, it may also happen that `integrate` does not integrate at all and the integration time is zero. In this case, the local Lyapunov exponents are returned as `0`, which is as nonsensical as any other result (except perhaps `nan`) but should not matter with a proper weighted averaging. It is essential that you choose `target_time` properly such that orthonormalisation does not happen too rarely. If you want to control the maximum step size, use the parameter `max_step` of `set_integration_parameters` instead. """ self._initiate() old_t = self.DDE.get_t() result = super(jitcdde_lyap, self).integrate(target_time)[:self.n_basic] delta_t = self.DDE.get_t()-old_t if delta_t!=0: norms = self.DDE.orthonormalise(self._n_lyap, self.max_delay) lyaps = np.log(norms) / delta_t else: lyaps = np.zeros(self._n_lyap) return result, lyaps, delta_t def set_integration_parameters(self, **kwargs): if self._n_lyap/self.n_basic > 2: required_max_step = self.max_delay/(np.ceil(self._n_lyap/self.n_basic/2)-1) if "max_step" in kwargs.keys(): if kwargs["max_step"] > required_max_step: kwargs["max_step"] = required_max_step warn("Decreased max_step to %f to ensure sufficient dimensionality for Lyapunov exponents." % required_max_step) else: kwargs["max_step"] = required_max_step kwargs.setdefault("min_step",_default_min_step) if kwargs["min_step"] > required_max_step: warn("Given the number of desired Lyapunov exponents and the maximum delay in the system, the highest possible step size is lower than the default min_step or the min_step set by you. This is almost certainly a very bad thing. Nonetheless I will lower min_step accordingly.") super(jitcdde_lyap, self).set_integration_parameters(**kwargs) def integrate_blindly(self, target_time, step=None): """ Like `jitcdde`’s `integrate_blindly`, except for orthonormalising the separation functions after each step and the output being analogous to `jitcdde_lyap`’s `integrate`. """ dt,number,total_integration_time = self._prepare_blind_int(target_time, step) instantaneous_lyaps = [] for _ in range(number): self.DDE.get_next_step(dt) self.DDE.accept_step() self.DDE.forget(self.max_delay) norms = self.DDE.orthonormalise(self._n_lyap, self.max_delay) instantaneous_lyaps.append(np.log(norms)/dt) lyaps = np.average(instantaneous_lyaps, axis=0) return self.DDE.get_current_state()[:self.n_basic], lyaps, total_integration_time class jitcdde_restricted_lyap(jitcdde): """ Calculates the largest Lyapunov exponent in orthogonal direction to a predefined plane, i.e. the projection of the separation function onto that plane vanishes. See `this test <https://github.com/neurophysik/jitcdde/blob/master/tests/test_restricted_lyap.py>`_ for an example of usage. Note that coordinate planes (i.e., planes orthogonal to vectors with only one non-zero component) are handled considerably faster. Consider transforming your differential equation to achieve this. The handling is the same as that for `jitcdde_lyap` except for: Parameters ---------- vectors : iterable of pairs of NumPy arrays A basis of the plane, whose projection shall be removed. The first vector in each pair is the component coresponding to the the state, the second vector corresponds to the derivative. """ def __init__(self, f_sym=(), vectors=(), **kwargs): self.n_basic = kwargs.pop("n",None) kwargs.setdefault("helpers",()) kwargs["helpers"] = sort_helpers(sympify_helpers(kwargs["helpers"] or [])) f_basic = self._handle_input(f_sym,n_basic=True) if kwargs.pop("simplify",None) is None: simplify = self.n_basic<=10 if "delays" not in kwargs.keys() or not kwargs["delays"]: kwargs["delays"] = _get_delays(f_basic,kwargs["helpers"]) self.vectors = [] self.state_components = [] self.diff_components = [] for vector in vectors: assert len(vector[0]) == self.n_basic assert len(vector[1]) == self.n_basic if np.count_nonzero(vector[0])+np.count_nonzero(vector[1]) > 1: state = np.array(vector[0], dtype=float, copy=True) diff = np.array(vector[1], dtype=float, copy=True) self.vectors.append((state,diff)) elif np.count_nonzero(vector[0])==1 and np.count_nonzero(vector[1])==0: self.state_components.append(vector[0].nonzero()[0][0]) elif np.count_nonzero(vector[1])==1 and np.count_nonzero(vector[0])==0: self.diff_components.append(vector[1].nonzero()[0][0]) else: raise ValueError("One vector contains only zeros.") f_lyap = tangent_vector_f( f = f_basic, helpers = kwargs["helpers"], n = self.n_basic, n_lyap = 1, delays = kwargs["delays"], zero_padding = 2*self.n_basic*len(self.vectors), simplify = simplify ) super(jitcdde_restricted_lyap, self).__init__( f_lyap, n = self.n_basic*(2+2*len(self.vectors)), **kwargs ) assert self.max_delay>0, "Maximum delay must be positive for calculating Lyapunov exponents." def remove_projections(self): for state_component in self.state_components: self.DDE.remove_state_component(state_component) for diff_component in self.diff_components: self.DDE.remove_diff_component(diff_component) norm = self.DDE.remove_projections(self.max_delay, self.vectors) return norm def set_integration_parameters(self, *args, **kwargs): super(jitcdde_restricted_lyap, self).set_integration_parameters(*args, **kwargs) if (self.state_components or self.diff_components) and not self.atol: warn("At least one of your vectors has only one component while your absolute error (atol) is 0. This may cause problems due to spuriously high relative errors. Consider setting atol to some small, non-zero value (e.g., 1e-10) to avoid this.") def integrate(self, target_time): """ Like `jitcdde`’s `integrate`, except for normalising and aligning the separation function and: Returns ------- y : one-dimensional NumPy array The state of the system. Same as the output of `jitcdde`’s `integrate`. lyap : float The “local” largest transversal Lyapunov exponent as estimated from the growth or shrinking of the separation function during the integration time of this very `integrate` command. integration time : float The actual integration time during to which the local Lyapunov exponents apply. Note that this is not necessarily difference between `target_time` and the previous `target_time`, as JiTCDDE usually integrates a bit ahead and estimates the output via interpolation. When averaging the Lyapunov exponents, you almost always want to weigh them with the integration time. If the size of the advance by `integrate` (the sampling step) is smaller than the actual integration step, it may also happen that `integrate` does not integrate at all and the integration time is zero. In this case, the local Lyapunov exponents are returned as `0`, which is as nonsensical as any other result (except perhaps `nan`) but should not matter with a proper weighted averaging. It is essential that you choose `target_time` properly such that orthonormalisation does not happen too rarely. If you want to control the maximum step size, use the parameter `max_step` of `set_integration_parameters` instead. """ self._initiate() old_t = self.DDE.get_t() result = super(jitcdde_restricted_lyap, self).integrate(target_time)[:self.n_basic] delta_t = self.DDE.get_t()-old_t if delta_t==0: warn("No actual integration happened in this call of integrate. This happens because the sampling step became smaller than the actual integration step. While this is not a problem per se, I cannot return a meaningful local Lyapunov exponent; therefore I return 0 instead.") lyap = 0 else: norm = self.remove_projections() lyap = np.log(norm) / delta_t return result, lyap, delta_t def integrate_blindly(self, target_time, step=None): """ Like `jitcdde`’s `integrate_blindly`, except for normalising and aligning the separation function after each step and the output being analogous to `jitcdde_restricted_lyap`’s `integrate`. """ self._initiate() self.initial_discontinuities_handled = True dt,number,total_integration_time = self._prepare_blind_int(target_time, step) instantaneous_lyaps = [] for _ in range(number): self.DDE.get_next_step(dt) self.DDE.accept_step() self.DDE.forget(self.max_delay) norm = self.remove_projections() instantaneous_lyaps.append(np.log(norm)/dt) lyap = np.average(instantaneous_lyaps) state = self.DDE.get_current_state()[:self.n_basic] return state, lyap, total_integration_time class jitcdde_transversal_lyap(jitcdde,GroupHandler): """ Calculates the largest Lyapunov exponent in orthogonal direction to a predefined synchronisation manifold, i.e. the projection of the tangent vector onto that manifold vanishes. In contrast to `jitcdde_restricted_lyap`, this performs some transformations tailored to this specific application that may strongly reduce the number of differential equations and ensure a dynamics on the synchronisation manifold. Note that all functions for defining the past differ from their analoga from `jitcdde` by having the dimensions of the arguments reduced to the number of groups. This means that only one initial value (of the state or derivative) per group of synchronised components has to be provided (in the same order as the `groups` argument of the constructor). The handling is the same as that for `jitcdde` except for: Parameters ---------- groups : iterable of iterables of integers each group is an iterable of indices that identify dynamical variables that are synchronised on the synchronisation manifold. simplify : boolean Whether the transformed differential equations shall be subjected to SymEngine’s `simplify`. Doing so may speed up the time evolution but may slow down the generation of the code (considerably for large differential equations). If `None`, this will be automatically disabled for `n>10`. """ def __init__( self, f_sym=(), groups=(), simplify=None, **kwargs ): GroupHandler.__init__(self,groups) self.n = kwargs.pop("n",None) f_basic,extracted = self.extract_main(self._handle_input(f_sym)) if simplify is None: simplify = self.n<=10 helpers = sort_helpers(sympify_helpers( kwargs.pop("helpers",[]) )) delays = kwargs.pop("delays",()) or _get_delays(f_basic,helpers) past_z = symengine.Function("past_z") current_z = symengine.Function("current_z") def z(index,time=t): if time == t: return current_z(index) else: return past_z(time, index, anchors(time)) tangent_vectors = {} for d in delays: z_vector = [z(i,(t-d)) for i in range(self.n)] tangent_vectors[d] = self.back_transform(z_vector) def tangent_vector_f(): jacs = [ _jac( f_basic, helpers, delay, self.n ) for delay in delays ] for _ in range(self.n): expression = 0 for delay,jac in zip(delays,jacs): try: for k,entry in enumerate(next(jac)): expression += entry * tangent_vectors[delay][k] except StopIteration: raise AssertionError("Something got horribly wrong") yield expression current_z_conflate = lambda i: current_z(self.map_to_main(i)) past_z_conflate = lambda t,i,a: past_z(t,self.map_to_main(i),a) def finalise(entry): entry = replace_function(entry,current_y,current_z_conflate) entry = replace_function(entry,past_y,past_z_conflate) if simplify: entry = entry.simplify(ratio=1) entry = replace_function(entry,current_z,current_y) entry = replace_function(entry,past_z,past_y) return entry def f_lyap(): for entry in self.iterate(tangent_vector_f()): if type(entry)==int: yield finalise(extracted[self.main_indices[entry]]) else: yield finalise(entry[0]-entry[1]) helpers = ((helper[0],finalise(helper[1])) for helper in helpers) super(jitcdde_transversal_lyap, self).__init__( f_lyap, n = self.n, delays = delays, helpers = helpers, **kwargs ) def initiate_past(self): self.past = Past( n=self.n, n_basic=self.n_basic, tangent_indices = self.tangent_indices ) def norm(self): tangent_vector = self._y[self.tangent_indices] norm = np.linalg.norm(tangent_vector) tangent_vector /= norm if not np.isfinite(norm): warn("Norm of perturbation vector for Lyapunov exponent out of numerical bounds. You probably waited too long before renormalising and should call integrate with smaller intervals between steps (as renormalisations happen once with every call of integrate).") self._y[self.tangent_indices] = tangent_vector return norm def integrate(self, target_time): """ Like `jitcdde`’s `integrate`, except for normalising and aligning the separation function and: Returns ------- y : one-dimensional NumPy array The state of the system. Only one initial value per group of synchronised components is returned (in the same order as the `groups` argument of the constructor). lyap : float The “local” largest transversal Lyapunov exponent as estimated from the growth or shrinking of the separation function during the integration time of this very `integrate` command. integration time : float The actual integration time during to which the local Lyapunov exponents apply. Note that this is not necessarily difference between `target_time` and the previous `target_time`, as JiTCDDE usually integrates a bit ahead and estimates the output via interpolation. When averaging the Lyapunov exponents, you almost always want to weigh them with the integration time. If the size of the advance by `integrate` (the sampling step) is smaller than the actual integration step, it may also happen that `integrate` does not integrate at all and the integration time is zero. In this case, the local Lyapunov exponents are returned as `0`, which is as nonsensical as any other result (except perhaps `nan`) but should not matter with a proper weighted averaging. It is essential that you choose `target_time` properly such that orthonormalisation does not happen too rarely. If you want to control the maximum step size, use the parameter `max_step` of `set_integration_parameters` instead. """ self._initiate() old_t = self.DDE.get_t() result = super(jitcdde_transversal_lyap, self).integrate(target_time)[self.main_indices] delta_t = self.DDE.get_t()-old_t if delta_t==0: warn("No actual integration happened in this call of integrate. This happens because the sampling step became smaller than the actual integration step. While this is not a problem per se, I cannot return a meaningful local Lyapunov exponent; therefore I return 0 instead.") lyap = 0 else: norm = self.DDE.normalise_indices(self.max_delay) lyap = np.log(norm) / delta_t return result, lyap, delta_t def integrate_blindly(self, target_time, step=None): """ Like `jitcdde`’s `integrate_blindly`, except for normalising and aligning the separation function after each step and the output being analogous to `jitcdde_transversal_lyap`’s `integrate`. """ self.initial_discontinuities_handled = True dt,number,total_integration_time = self._prepare_blind_int(target_time, step) instantaneous_lyaps = [] for _ in range(number): self.DDE.get_next_step(dt) self.DDE.accept_step() self.DDE.forget(self.max_delay) norm = self.DDE.normalise_indices(self.max_delay) instantaneous_lyaps.append(np.log(norm)/dt) lyap = np.average(instantaneous_lyaps) state = self.DDE.get_current_state()[self.main_indices] return state, lyap, total_integration_time input_shift = symengine.Symbol("external_input",real=True,negative=False) input_base_n = symengine.Symbol("input_base_n",integer=True,negative=False) def input(index,time=t): """ Function representing an external input (for `jitcdde_input`). The first integer argument denotes the component. The second, optional argument is a symbolic expression denoting the time. This automatically expands to using `current_y`, `past_y`, `anchors`, `input_base_n`, and `input_shift`; so do not be surprised when you look at the output and it is different than what you entered or expected. You can import a SymPy variant from the submodule `sympy_symbols` instead (see `SymPy vs. SymEngine`_ for details). """ if time!=t: warn("Do not use delayed inputs unless you also have undelayed inputs (otherwise you can just shift your time frame). If you use delayed and undelayed inputs, you have to rely on automatic delay detection or explicitly add `input[-1].time+delay` to the delays (and consider it as a max_delay) for each delayed input.") return y(index+input_base_n,time-input_shift) class jitcdde_input(jitcdde): """ Allows to integrate the DDE (or an ODE) with input. Under the hood, this is handled by adding dummy dynamical variables, in whose past state the input is stored. In contrast to other variants of JiTCDDE, the integration must start at :math:`t=0`. All parameters and methods are as for `jitcdde`, except: Parameters ---------- input : CHSPy CubicHermiteSpline The input. This has to be a CubicHermiteSpline (specifying the values and derivatives at certain anchor points). Be sure to plot the input to check whether it conforms with your expectations. """ def __init__( self, f_sym=(), input=None, **kwargs ): if input is None: raise ValueError("You must define an input; otherwise just use plain jitcdde.") if input[0].time > 0: warn(f"Your input past does not begin at t=0 but at t={input[0].time}. Values before the beginning of the past will be extrapolated. You very likely do not want this.") self.n = kwargs.pop("n",None) f_basic = self._handle_input(f_sym) self.input_base_n = self.n self.n += input.n self.input_duration = input[-1].time substitutions = { input_base_n: self.input_base_n, input_shift: self.input_duration, } self.regular_past = chspy.CubicHermiteSpline(n=self.input_base_n) self.input_past = chspy.CubicHermiteSpline(n=input.n) for anchor in input: self.input_past.add(( anchor.time-self.input_duration, anchor.state, anchor.diff, )) def f_full(): for expression in f_basic(): yield expression.subs(substitutions) # Dummy dynamical variables having constant diff of the last input point to avoid adjustment and to provide the best extrapolation, if required. yield from input[-1].diff if kwargs.setdefault("delays",None) is not None: kwargs["delays"] = [ *kwargs["delays"], self.input_duration ] if kwargs.setdefault("max_delay",None) is not None: kwargs["max_delay"] = max( kwargs["max_delay"], self.input_duration ) super().__init__( f_full, n=self.n, **kwargs ) self._past = None def initiate_past(self): pass @property def past(self): if self._past is None: assert len(self.regular_past)>1, "You need to add at least two past points first. Usually this means that you did not set an initial past at all." if self.regular_past[-1].time != 0: raise ValueError("For jitcdde_input, the initial past must end at t=0.") self._past = chspy.join(self.regular_past,self.input_past) return self._past @past.setter def past(self,value): raise AssertionError("For jitcdde_input, the past attribute should not be directly set.") def add_past_point(self, time, state, derivative): self._past = None self.reset_integrator(idc_unhandled=True) self.regular_past.add((time,state,derivative)) def add_past_points(self, anchors): self._past = None self.reset_integrator(idc_unhandled=True) for anchor in anchors: self.regular_past.add(anchor) def constant_past(self,state,time=0): self._past = None self.regular_past.constant(state,time) def past_from_function(self,function,times_of_interest=None,max_anchors=100,tol=5): self._past = None if times_of_interest is None: times_of_interest = np.linspace(-self.max_delay,0,10) else: times_of_interest = sorted(times_of_interest) self.regular_past.from_function(function,times_of_interest,max_anchors,tol) def get_state(self): self._initiate() self.DDE.forget(self.max_delay) self._past = None self.regular_past.clear() for anchor in self.DDE.get_full_state(): self.regular_past.append(( anchor[0], anchor[1][:self.input_base_n], anchor[2][:self.input_base_n], )) return self.regular_past def purge_past(self): self._past = None self.regular_past.clear() self.reset_integrator(idc_unhandled=True) def integrate(self,target_time): if target_time>self.input_duration: warn("Integrating beyond duration of input. From now on, the input will be extrapolated. You very likely do not want this. Instead define a longer input or stop integrating.") return super().integrate(target_time)[:self.input_base_n] def integrate_blindly(self,*args,**kwargs): return super().integrate_blindly(*args,**kwargs)[:self.input_base_n] def step_on_discontinuities(self,*args,**kwargs): raise NotImplementedError("Stepping on discontinuities is not implemented for input yet. Use integrate_blindly or adjust_diff instead.") def jump(self,amplitude,*args,**kwargs): if np.ndim(amplitude)==0: amplitude = np.full(self.input_base_n,amplitude,dtype=float) assert amplitude.shape == (self.input_base_n,) extended_amplitude = np.hstack((amplitude,np.zeros(self.input_past.n))) minima,maxima = super().jump(extended_amplitude,*args,**kwargs) return minima[:self.input_base_n], maxima[:self.input_base_n] def test(omp=True,sympy=True): """ Runs a quick simulation to test whether: * a compiler is available and can be interfaced by Setuptools, * OMP libraries are available and can be assessed, * SymPy is available. The latter two tests can be deactivated with the respective argument. This is not a full software test but rather a quick sanity check of your installation. If successful, this function just finishes without any message. """ if sympy: import sympy DDE = jitcdde( [y(1,t-1),-y(0,t-2)], verbose=False ) DDE.compile_C(chunk_size=1,omp=omp) DDE.constant_past([1,2]) DDE.step_on_discontinuities() DDE.integrate(DDE.t+1)
[ "jitcxde_common.symbolic.count_calls", "symengine.Symbol", "numpy.linalg.norm", "symengine.sympify", "chspy.CubicHermiteSpline", "numpy.full", "numpy.ndim", "numpy.isfinite", "jitcdde._python_core.dde_integrator", "numpy.linspace", "jitcxde_common.symbolic.collect_arguments", "sympy.Function",...
[((1038, 1070), 'symengine.Symbol', 'symengine.Symbol', (['"""t"""'], {'real': '(True)'}), "('t', real=True)\n", (1054, 1070), False, 'import symengine\n'), ((3086, 3117), 'symengine.Function', 'symengine.Function', (['"""current_y"""'], {}), "('current_y')\n", (3104, 3117), False, 'import symengine\n'), ((3647, 3675), 'symengine.Function', 'symengine.Function', (['"""past_y"""'], {}), "('past_y')\n", (3665, 3675), False, 'import symengine\n'), ((4212, 4241), 'symengine.Function', 'symengine.Function', (['"""past_dy"""'], {}), "('past_dy')\n", (4230, 4241), False, 'import symengine\n'), ((4639, 4668), 'symengine.Function', 'symengine.Function', (['"""anchors"""'], {}), "('anchors')\n", (4657, 4668), False, 'import symengine\n'), ((64154, 64215), 'symengine.Symbol', 'symengine.Symbol', (['"""external_input"""'], {'real': '(True)', 'negative': '(False)'}), "('external_input', real=True, negative=False)\n", (64170, 64215), False, 'import symengine\n'), ((64229, 64291), 'symengine.Symbol', 'symengine.Symbol', (['"""input_base_n"""'], {'integer': '(True)', 'negative': '(False)'}), "('input_base_n', integer=True, negative=False)\n", (64245, 64291), False, 'import symengine\n'), ((12947, 12983), 'jitcdde.past.Past', 'Past', ([], {'n': 'self.n', 'n_basic': 'self.n_basic'}), '(n=self.n, n_basic=self.n_basic)\n', (12951, 12983), False, 'from jitcdde.past import Past, Anchor\n'), ((20471, 20577), 'jitcdde._python_core.dde_integrator', 'python_core.dde_integrator', (['self.f_sym', 'self.past', 'self.helpers', 'self.control_pars'], {'simplify': 'simplify'}), '(self.f_sym, self.past, self.helpers, self.\n control_pars, simplify=simplify)\n', (20497, 20577), True, 'import jitcdde._python_core as python_core\n'), ((25324, 25352), 'symengine.Function', 'symengine.Function', (['"""set_dy"""'], {}), "('set_dy')\n", (25342, 25352), False, 'import symengine\n'), ((50759, 50798), 'numpy.average', 'np.average', (['instantaneous_lyaps'], {'axis': '(0)'}), '(instantaneous_lyaps, axis=0)\n', (50769, 50798), True, 'import numpy as np\n'), ((56937, 56968), 'numpy.average', 'np.average', (['instantaneous_lyaps'], {}), '(instantaneous_lyaps)\n', (56947, 56968), True, 'import numpy as np\n'), ((58545, 58580), 'jitcxde_common.transversal.GroupHandler.__init__', 'GroupHandler.__init__', (['self', 'groups'], {}), '(self, groups)\n', (58566, 58580), False, 'from jitcxde_common.transversal import GroupHandler\n'), ((58881, 58909), 'symengine.Function', 'symengine.Function', (['"""past_z"""'], {}), "('past_z')\n", (58899, 58909), False, 'import symengine\n'), ((58924, 58955), 'symengine.Function', 'symengine.Function', (['"""current_z"""'], {}), "('current_z')\n", (58942, 58955), False, 'import symengine\n'), ((60558, 60632), 'jitcdde.past.Past', 'Past', ([], {'n': 'self.n', 'n_basic': 'self.n_basic', 'tangent_indices': 'self.tangent_indices'}), '(n=self.n, n_basic=self.n_basic, tangent_indices=self.tangent_indices)\n', (60562, 60632), False, 'from jitcdde.past import Past, Anchor\n'), ((60729, 60759), 'numpy.linalg.norm', 'np.linalg.norm', (['tangent_vector'], {}), '(tangent_vector)\n', (60743, 60759), True, 'import numpy as np\n'), ((64001, 64032), 'numpy.average', 'np.average', (['instantaneous_lyaps'], {}), '(instantaneous_lyaps)\n', (64011, 64032), True, 'import numpy as np\n'), ((64855, 65183), 'warnings.warn', 'warn', (['"""Do not use delayed inputs unless you also have undelayed inputs (otherwise you can just shift your time frame). If you use delayed and undelayed inputs, you have to rely on automatic delay detection or explicitly add `input[-1].time+delay` to the delays (and consider it as a max_delay) for each delayed input."""'], {}), "(\n 'Do not use delayed inputs unless you also have undelayed inputs (otherwise you can just shift your time frame). If you use delayed and undelayed inputs, you have to rely on automatic delay detection or explicitly add `input[-1].time+delay` to the delays (and consider it as a max_delay) for each delayed input.'\n )\n", (64859, 65183), False, 'from warnings import warn\n'), ((66474, 66519), 'chspy.CubicHermiteSpline', 'chspy.CubicHermiteSpline', ([], {'n': 'self.input_base_n'}), '(n=self.input_base_n)\n', (66498, 66519), False, 'import chspy\n'), ((66540, 66575), 'chspy.CubicHermiteSpline', 'chspy.CubicHermiteSpline', ([], {'n': 'input.n'}), '(n=input.n)\n', (66564, 66575), False, 'import chspy\n'), ((623, 633), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (630, 633), True, 'import numpy as np\n'), ((12578, 12608), 'jitcxde_common.helpers.sympify_helpers', 'sympify_helpers', (['(helpers or [])'], {}), '(helpers or [])\n', (12593, 12608), False, 'from jitcxde_common.helpers import sort_helpers, sympify_helpers, find_dependent_helpers\n'), ((17911, 17946), 'numpy.linspace', 'np.linspace', (['(-self.max_delay)', '(0)', '(10)'], {}), '(-self.max_delay, 0, 10)\n', (17922, 17946), True, 'import numpy as np\n'), ((23550, 23585), 'sympy.Function', 'sympy.Function', (['"""additional_helper"""'], {}), "('additional_helper')\n", (23564, 23585), False, 'import sympy\n'), ((23785, 23814), 'symengine.sympify', 'symengine.sympify', (['_cse[1][0]'], {}), '(_cse[1][0])\n', (23802, 23814), False, 'import symengine\n'), ((24051, 24106), 'symengine.Symbol', 'symengine.Symbol', (["('self->parameter_' + control_par.name)"], {}), "('self->parameter_' + control_par.name)\n", (24067, 24106), False, 'import symengine\n'), ((24256, 24288), 'jitcxde_common.symbolic.count_calls', 'count_calls', (['expression', 'anchors'], {}), '(expression, anchors)\n', (24267, 24288), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((24345, 24379), 'symengine.Function', 'symengine.Function', (['"""get_f_helper"""'], {}), "('get_f_helper')\n", (24363, 24379), False, 'import symengine\n'), ((24396, 24430), 'symengine.Function', 'symengine.Function', (['"""set_f_helper"""'], {}), "('set_f_helper')\n", (24414, 24430), False, 'import symengine\n'), ((24451, 24492), 'symengine.Function', 'symengine.Function', (['"""get_f_anchor_helper"""'], {}), "('get_f_anchor_helper')\n", (24469, 24492), False, 'import symengine\n'), ((24509, 24550), 'symengine.Function', 'symengine.Function', (['"""set_f_anchor_helper"""'], {}), "('set_f_anchor_helper')\n", (24527, 24550), False, 'import symengine\n'), ((25584, 25644), 'warnings.warn', 'warn', (['"""Differential equation does not include a delay term."""'], {}), "('Differential equation does not include a delay term.')\n", (25588, 25644), False, 'from warnings import warn\n'), ((30928, 30975), 'warnings.warn', 'warn', (['"""Decreasing first_step to match max_step"""'], {}), "('Decreasing first_step to match max_step')\n", (30932, 30975), False, 'from warnings import warn\n'), ((31032, 31079), 'warnings.warn', 'warn', (['"""Decreasing min_step to match first_step"""'], {}), "('Decreasing min_step to match first_step')\n", (31036, 31079), False, 'from warnings import warn\n'), ((31489, 31553), 'warnings.warn', 'warn', (['"""atol and rtol are both 0. You probably do not want this."""'], {}), "('atol and rtol are both 0. You probably do not want this.')\n", (31493, 31553), False, 'from warnings import warn\n'), ((35189, 35606), 'warnings.warn', 'warn', (['"""The target time is smaller than the current time. No integration step will happen. The returned state will be extrapolated from the interpolating Hermite polynomial for the last integration step. You may see this because you try to integrate backwards in time, in which case you did something wrong. You may see this just because your sampling step is small, in which case there is no need to worry."""'], {}), "(\n 'The target time is smaller than the current time. No integration step will happen. The returned state will be extrapolated from the interpolating Hermite polynomial for the last integration step. You may see this because you try to integrate backwards in time, in which case you did something wrong. You may see this just because your sampling step is small, in which case there is no need to worry.'\n )\n", (35193, 35606), False, 'from warnings import warn\n'), ((35650, 36059), 'warnings.warn', 'warn', (['"""You did not explicitly handle initial discontinuities. Proceed only if you know what you are doing. This is only fine if you somehow chose your initial past such that the derivative of the last anchor complies with the DDE. In this case, you can set the attribute `initial_discontinuities_handled` to `True` to suppress this warning. See https://jitcdde.rtfd.io/#discontinuities for details."""'], {}), "(\n 'You did not explicitly handle initial discontinuities. Proceed only if you know what you are doing. This is only fine if you somehow chose your initial past such that the derivative of the last anchor complies with the DDE. In this case, you can set the attribute `initial_discontinuities_handled` to `True` to suppress this warning. See https://jitcdde.rtfd.io/#discontinuities for details.'\n )\n", (35654, 36059), False, 'from warnings import warn\n'), ((41381, 41569), 'warnings.warn', 'warn', (['"""The max_step parameter is retired and does not need to be used anymore. Instead, step_on_discontinuities now adapts the step size. This will raise an error in the future."""'], {}), "(\n 'The max_step parameter is retired and does not need to be used anymore. Instead, step_on_discontinuities now adapts the step size. This will raise an error in the future.'\n )\n", (41385, 41569), False, 'from warnings import warn\n'), ((44486, 44504), 'numpy.ndim', 'np.ndim', (['amplitude'], {}), '(amplitude)\n', (44493, 44504), True, 'import numpy as np\n'), ((44524, 44563), 'numpy.full', 'np.full', (['self.n', 'amplitude'], {'dtype': 'float'}), '(self.n, amplitude, dtype=float)\n', (44531, 44563), True, 'import numpy as np\n'), ((44590, 44622), 'numpy.array', 'np.array', (['amplitude'], {'dtype': 'float'}), '(amplitude, dtype=float)\n', (44598, 44622), True, 'import numpy as np\n'), ((46612, 46652), 'jitcxde_common.helpers.sympify_helpers', 'sympify_helpers', (["(kwargs['helpers'] or [])"], {}), "(kwargs['helpers'] or [])\n", (46627, 46652), False, 'from jitcxde_common.helpers import sort_helpers, sympify_helpers, find_dependent_helpers\n'), ((49185, 49207), 'numpy.zeros', 'np.zeros', (['self._n_lyap'], {}), '(self._n_lyap)\n', (49193, 49207), True, 'import numpy as np\n'), ((51912, 51952), 'jitcxde_common.helpers.sympify_helpers', 'sympify_helpers', (["(kwargs['helpers'] or [])"], {}), "(kwargs['helpers'] or [])\n", (51927, 51952), False, 'from jitcxde_common.helpers import sort_helpers, sympify_helpers, find_dependent_helpers\n'), ((53939, 54192), 'warnings.warn', 'warn', (['"""At least one of your vectors has only one component while your absolute error (atol) is 0. This may cause problems due to spuriously high relative errors. Consider setting atol to some small, non-zero value (e.g., 1e-10) to avoid this."""'], {}), "(\n 'At least one of your vectors has only one component while your absolute error (atol) is 0. This may cause problems due to spuriously high relative errors. Consider setting atol to some small, non-zero value (e.g., 1e-10) to avoid this.'\n )\n", (53943, 54192), False, 'from warnings import warn\n'), ((55888, 56171), 'warnings.warn', 'warn', (['"""No actual integration happened in this call of integrate. This happens because the sampling step became smaller than the actual integration step. While this is not a problem per se, I cannot return a meaningful local Lyapunov exponent; therefore I return 0 instead."""'], {}), "(\n 'No actual integration happened in this call of integrate. This happens because the sampling step became smaller than the actual integration step. While this is not a problem per se, I cannot return a meaningful local Lyapunov exponent; therefore I return 0 instead.'\n )\n", (55892, 56171), False, 'from warnings import warn\n'), ((59819, 59873), 'jitcxde_common.symbolic.replace_function', 'replace_function', (['entry', 'current_y', 'current_z_conflate'], {}), '(entry, current_y, current_z_conflate)\n', (59835, 59873), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((59883, 59931), 'jitcxde_common.symbolic.replace_function', 'replace_function', (['entry', 'past_y', 'past_z_conflate'], {}), '(entry, past_y, past_z_conflate)\n', (59899, 59931), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((59993, 60038), 'jitcxde_common.symbolic.replace_function', 'replace_function', (['entry', 'current_z', 'current_y'], {}), '(entry, current_z, current_y)\n', (60009, 60038), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((60048, 60087), 'jitcxde_common.symbolic.replace_function', 'replace_function', (['entry', 'past_z', 'past_y'], {}), '(entry, past_z, past_y)\n', (60064, 60087), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((60794, 60811), 'numpy.isfinite', 'np.isfinite', (['norm'], {}), '(norm)\n', (60805, 60811), True, 'import numpy as np\n'), ((60816, 61085), 'warnings.warn', 'warn', (['"""Norm of perturbation vector for Lyapunov exponent out of numerical bounds. You probably waited too long before renormalising and should call integrate with smaller intervals between steps (as renormalisations happen once with every call of integrate)."""'], {}), "(\n 'Norm of perturbation vector for Lyapunov exponent out of numerical bounds. You probably waited too long before renormalising and should call integrate with smaller intervals between steps (as renormalisations happen once with every call of integrate).'\n )\n", (60820, 61085), False, 'from warnings import warn\n'), ((62939, 63222), 'warnings.warn', 'warn', (['"""No actual integration happened in this call of integrate. This happens because the sampling step became smaller than the actual integration step. While this is not a problem per se, I cannot return a meaningful local Lyapunov exponent; therefore I return 0 instead."""'], {}), "(\n 'No actual integration happened in this call of integrate. This happens because the sampling step became smaller than the actual integration step. While this is not a problem per se, I cannot return a meaningful local Lyapunov exponent; therefore I return 0 instead.'\n )\n", (62943, 63222), False, 'from warnings import warn\n'), ((66016, 66194), 'warnings.warn', 'warn', (['f"""Your input past does not begin at t=0 but at t={input[0].time}. Values before the beginning of the past will be extrapolated. You very likely do not want this."""'], {}), "(\n f'Your input past does not begin at t=0 but at t={input[0].time}. Values before the beginning of the past will be extrapolated. You very likely do not want this.'\n )\n", (66020, 66194), False, 'from warnings import warn\n'), ((67671, 67717), 'chspy.join', 'chspy.join', (['self.regular_past', 'self.input_past'], {}), '(self.regular_past, self.input_past)\n', (67681, 67717), False, 'import chspy\n'), ((68459, 68494), 'numpy.linspace', 'np.linspace', (['(-self.max_delay)', '(0)', '(10)'], {}), '(-self.max_delay, 0, 10)\n', (68470, 68494), True, 'import numpy as np\n'), ((69145, 69330), 'warnings.warn', 'warn', (['"""Integrating beyond duration of input. From now on, the input will be extrapolated. You very likely do not want this. Instead define a longer input or stop integrating."""'], {}), "(\n 'Integrating beyond duration of input. From now on, the input will be extrapolated. You very likely do not want this. Instead define a longer input or stop integrating.'\n )\n", (69149, 69330), False, 'from warnings import warn\n'), ((69740, 69758), 'numpy.ndim', 'np.ndim', (['amplitude'], {}), '(amplitude)\n', (69747, 69758), True, 'import numpy as np\n'), ((69778, 69828), 'numpy.full', 'np.full', (['self.input_base_n', 'amplitude'], {'dtype': 'float'}), '(self.input_base_n, amplitude, dtype=float)\n', (69785, 69828), True, 'import numpy as np\n'), ((4731, 4764), 'jitcxde_common.symbolic.collect_arguments', 'collect_arguments', (['entry', 'anchors'], {}), '(entry, anchors)\n', (4748, 4764), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((4806, 4843), 'jitcxde_common.symbolic.collect_arguments', 'collect_arguments', (['helper[1]', 'anchors'], {}), '(helper[1], anchors)\n', (4823, 4843), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((5006, 5030), 'symengine.sympify', 'symengine.sympify', (['delay'], {}), '(delay)\n', (5023, 5030), False, 'import symengine\n'), ((23743, 23769), 'symengine.sympify', 'symengine.sympify', (['_cse[0]'], {}), '(_cse[0])\n', (23760, 23769), False, 'import symengine\n'), ((49142, 49155), 'numpy.log', 'np.log', (['norms'], {}), '(norms)\n', (49148, 49155), True, 'import numpy as np\n'), ((49814, 50099), 'warnings.warn', 'warn', (['"""Given the number of desired Lyapunov exponents and the maximum delay in the system, the highest possible step size is lower than the default min_step or the min_step set by you. This is almost certainly a very bad thing. Nonetheless I will lower min_step accordingly."""'], {}), "(\n 'Given the number of desired Lyapunov exponents and the maximum delay in the system, the highest possible step size is lower than the default min_step or the min_step set by you. This is almost certainly a very bad thing. Nonetheless I will lower min_step accordingly.'\n )\n", (49818, 50099), False, 'from warnings import warn\n'), ((52481, 52524), 'numpy.array', 'np.array', (['vector[0]'], {'dtype': 'float', 'copy': '(True)'}), '(vector[0], dtype=float, copy=True)\n', (52489, 52524), True, 'import numpy as np\n'), ((52537, 52580), 'numpy.array', 'np.array', (['vector[1]'], {'dtype': 'float', 'copy': '(True)'}), '(vector[1], dtype=float, copy=True)\n', (52545, 52580), True, 'import numpy as np\n'), ((56228, 56240), 'numpy.log', 'np.log', (['norm'], {}), '(norm)\n', (56234, 56240), True, 'import numpy as np\n'), ((63296, 63308), 'numpy.log', 'np.log', (['norm'], {}), '(norm)\n', (63302, 63308), True, 'import numpy as np\n'), ((69920, 69947), 'numpy.zeros', 'np.zeros', (['self.input_past.n'], {}), '(self.input_past.n)\n', (69928, 69947), True, 'import numpy as np\n'), ((13897, 13932), 'jitcxde_common.symbolic.collect_arguments', 'collect_arguments', (['entry', 'current_y'], {}), '(entry, current_y)\n', (13914, 13932), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((13976, 14008), 'jitcxde_common.symbolic.collect_arguments', 'collect_arguments', (['entry', 'past_y'], {}), '(entry, past_y)\n', (13993, 14008), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((14055, 14088), 'jitcxde_common.symbolic.collect_arguments', 'collect_arguments', (['entry', 'past_dy'], {}), '(entry, past_dy)\n', (14072, 14088), False, 'from jitcxde_common.symbolic import collect_arguments, count_calls, replace_function\n'), ((32453, 32471), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (32469, 32471), True, 'import numpy as np\n'), ((45710, 45730), 'symengine.sympify', 'symengine.sympify', (['(0)'], {}), '(0)\n', (45727, 45730), False, 'import symengine\n'), ((49369, 49409), 'numpy.ceil', 'np.ceil', (['(self._n_lyap / self.n_basic / 2)'], {}), '(self._n_lyap / self.n_basic / 2)\n', (49376, 49409), True, 'import numpy as np\n'), ((49540, 49662), 'warnings.warn', 'warn', (["('Decreased max_step to %f to ensure sufficient dimensionality for Lyapunov exponents.'\n % required_max_step)"], {}), "(\n 'Decreased max_step to %f to ensure sufficient dimensionality for Lyapunov exponents.'\n % required_max_step)\n", (49544, 49662), False, 'from warnings import warn\n'), ((50728, 50741), 'numpy.log', 'np.log', (['norms'], {}), '(norms)\n', (50734, 50741), True, 'import numpy as np\n'), ((52408, 52435), 'numpy.count_nonzero', 'np.count_nonzero', (['vector[0]'], {}), '(vector[0])\n', (52424, 52435), True, 'import numpy as np\n'), ((52436, 52463), 'numpy.count_nonzero', 'np.count_nonzero', (['vector[1]'], {}), '(vector[1])\n', (52452, 52463), True, 'import numpy as np\n'), ((56908, 56920), 'numpy.log', 'np.log', (['norm'], {}), '(norm)\n', (56914, 56920), True, 'import numpy as np\n'), ((63972, 63984), 'numpy.log', 'np.log', (['norm'], {}), '(norm)\n', (63978, 63984), True, 'import numpy as np\n'), ((6778, 6810), 'symengine.sympify', 'symengine.sympify', (['(upper - lower)'], {}), '(upper - lower)\n', (6795, 6810), False, 'import symengine\n'), ((6809, 6834), 'symengine.sympify', 'symengine.sympify', (['nsteps'], {}), '(nsteps)\n', (6826, 6834), False, 'import symengine\n'), ((7036, 7068), 'symengine.sympify', 'symengine.sympify', (['(upper - lower)'], {}), '(upper - lower)\n', (7053, 7068), False, 'import symengine\n'), ((41576, 41600), 'symengine.sympify', 'symengine.sympify', (['delay'], {}), '(delay)\n', (41593, 41600), False, 'import symengine\n'), ((41831, 41855), 'symengine.sympify', 'symengine.sympify', (['delay'], {}), '(delay)\n', (41848, 41855), False, 'import symengine\n'), ((52627, 52654), 'numpy.count_nonzero', 'np.count_nonzero', (['vector[0]'], {}), '(vector[0])\n', (52643, 52654), True, 'import numpy as np\n'), ((52662, 52689), 'numpy.count_nonzero', 'np.count_nonzero', (['vector[1]'], {}), '(vector[1])\n', (52678, 52689), True, 'import numpy as np\n'), ((23707, 23714), 'itertools.count', 'count', ([], {}), '()\n', (23712, 23714), False, 'from itertools import count\n'), ((52762, 52789), 'numpy.count_nonzero', 'np.count_nonzero', (['vector[1]'], {}), '(vector[1])\n', (52778, 52789), True, 'import numpy as np\n'), ((52797, 52824), 'numpy.count_nonzero', 'np.count_nonzero', (['vector[0]'], {}), '(vector[0])\n', (52813, 52824), True, 'import numpy as np\n'), ((7169, 7195), 'sympy.integrals.quadrature.gauss_legendre', 'gauss_legendre', (['nsteps', '(20)'], {}), '(nsteps, 20)\n', (7183, 7195), False, 'from sympy.integrals.quadrature import gauss_legendre\n')]
from datetime import datetime import numpy as np import pandas as pd from nwbext_ecog.ecog_manual import CorticalSurfaces, ECoGSubject from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager from pynwb.ecephys import ElectricalSeries from pytz import timezone from scipy.io.wavfile import read as wavread # get_manager must come after dynamic imports manager = get_manager() external_subject = True nwbfile = NWBFile('session description', 'session identifier', datetime.now().astimezone(), institution='UCSF', lab='Chang Lab') # electrodes devices = ['a', 'a', 'a', 'b', 'b', 'b'] locations = ['a location', 'b location'] udevices, inds = np.unique(devices, return_inverse=True) groups = [] for device_name, location in zip(udevices, locations): # Create devices device = nwbfile.create_device(device_name) # Create electrode groups electrode_group = nwbfile.create_electrode_group( name=device_name + '_electrodes', description=device_name, location=location, device=device) groups.append(electrode_group) nwbfile.add_electrode_column('bad', 'whether the electrode is too noisy to use') electrodes_df = pd.DataFrame( {'location': ['c', 'c', 'c', 'd', 'd', 'd'], 'group': np.array(groups)[inds], 'x': [np.nan] * 6, 'y': [np.nan] * 6, 'z': [np.nan] * 6, 'imp': [np.nan] * 6, 'filtering': ['none'] * 6, 'bad': [False] * 5 + [True]} ) for _, row in electrodes_df.iterrows(): nwbfile.add_electrode(**{label: row[label] for label in electrodes_df}) all_elecs = nwbfile.create_electrode_table_region( list(range(len(electrodes_df))), 'all electrodes') # ECoG signal ecog_signal = np.random.randn(1000, 64) ecog_ts = ElectricalSeries('ECoG', ecog_signal, all_elecs, rate=3000., description='ecog_signal', conversion=0.001) nwbfile.add_acquisition(ecog_ts) # Trials # optional columns nwbfile.add_trial_column('condition', 'condition of task') nwbfile.add_trial_column('response_latency', 'in seconds') nwbfile.add_trial_column('response', 'y is yes, n is no') nwbfile.add_trial_column('bad', 'whether a trial is bad either because of ' 'artifact or bad performance') trials_df = pd.DataFrame({'start_time': [1., 2., 3.], 'stop_time': [1.5, 2.5, 3.5], 'condition': ['a', 'b', 'c'], 'response_latency': [.3, .26, .31], 'response': ['y', 'n', 'y'], 'bad': [False, False, True]}) for _, row in trials_df.iterrows(): nwbfile.add_trial(**{label: row[label] for label in trials_df}) # print(nwbfile.trials.to_dataframe()) # bad times bad_times_data = [[5.4, 6.], [10.4, 11.]] # in seconds for start, stop in bad_times_data: nwbfile.add_invalid_time_interval(start_time=start, stop_time=stop, tags=('ECoG artifact',), timeseries=ecog_ts) # Create units table for neurons from micro-array recordings single_electrode_regions = [ nwbfile.create_electrode_table_region([i], 'electrode i') for i in range(len(electrodes_df))] all_spike_times = [[1., 2., 3., 4.], [2., 3., 4.], [0.5, 1., 4., 10., 15.]] all_electrodes = ((0,), (0,), (1,)) waveform_means = [np.random.randn(30, 1) for _ in range(3)] for spike_times, electrodes, waveform_mean in \ zip(all_spike_times, all_electrodes, waveform_means): nwbfile.add_unit(spike_times=spike_times, electrodes=electrodes, waveform_mean=waveform_mean) # analog data # microphone data # Be careful! This might contain identifying information mic_path = '/Users/bendichter/Desktop/Chang/video_abstract/word_emphasis.wav' mic_fs, mic_data = wavread(mic_path) nwbfile.add_acquisition( TimeSeries('microphone', mic_data, 'audio unit', rate=float(mic_fs), description="audio recording from microphone in room") ) # all analog data can be added like the microphone example (speaker, button press, etc.) spk_path = '/Users/bendichter/Desktop/Chang/video_abstract/word_emphasis.wav' spk_fs, spk_data = wavread(spk_path) nwbfile.add_stimulus( TimeSeries('speaker1', spk_data, 'audio unit', rate=float(spk_fs), description="speaker recording") ) subject = ECoGSubject(species='homo sapiens', age='PY21', sex='M') cortical_surfaces = CorticalSurfaces() for name in ('a', 'b', 'c'): vertices = np.random.randn(10, 3) faces = np.random.randint(0, 9, (15, 3)) cortical_surfaces.create_surface(name=name, faces=faces, vertices=vertices) subject.cortical_surfaces = cortical_surfaces # cortical surfaces if external_subject: subject_fpath = 'S1.nwbaux' subject_nwbfile = NWBFile( session_description='session description', identifier='S1', subject=subject, session_start_time=datetime(1900, 1, 1).astimezone(timezone('UTC'))) with NWBHDF5IO(subject_fpath, manager=manager, mode='w') as subject_io: subject_io.write(subject_nwbfile) subject_read_io = NWBHDF5IO(subject_fpath, manager=manager, mode='r') subject_nwbfile = subject_read_io.read() subject = subject_nwbfile.subject nwbfile.subject = subject fout_path = 'ecog_example.nwb' with NWBHDF5IO(fout_path, manager=manager, mode='w') as io: io.write(nwbfile) # test read with NWBHDF5IO(fout_path, 'r') as io: io.read() if external_subject: subject_read_io.close()
[ "pandas.DataFrame", "pynwb.NWBHDF5IO", "pynwb.ecephys.ElectricalSeries", "numpy.random.randn", "scipy.io.wavfile.read", "nwbext_ecog.ecog_manual.CorticalSurfaces", "datetime.datetime", "numpy.random.randint", "nwbext_ecog.ecog_manual.ECoGSubject", "numpy.array", "pytz.timezone", "pynwb.get_man...
[((369, 382), 'pynwb.get_manager', 'get_manager', ([], {}), '()\n', (380, 382), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((687, 726), 'numpy.unique', 'np.unique', (['devices'], {'return_inverse': '(True)'}), '(devices, return_inverse=True)\n', (696, 726), True, 'import numpy as np\n'), ((1732, 1757), 'numpy.random.randn', 'np.random.randn', (['(1000)', '(64)'], {}), '(1000, 64)\n', (1747, 1757), True, 'import numpy as np\n'), ((1768, 1879), 'pynwb.ecephys.ElectricalSeries', 'ElectricalSeries', (['"""ECoG"""', 'ecog_signal', 'all_elecs'], {'rate': '(3000.0)', 'description': '"""ecog_signal"""', 'conversion': '(0.001)'}), "('ECoG', ecog_signal, all_elecs, rate=3000.0, description=\n 'ecog_signal', conversion=0.001)\n", (1784, 1879), False, 'from pynwb.ecephys import ElectricalSeries\n'), ((2293, 2503), 'pandas.DataFrame', 'pd.DataFrame', (["{'start_time': [1.0, 2.0, 3.0], 'stop_time': [1.5, 2.5, 3.5], 'condition':\n ['a', 'b', 'c'], 'response_latency': [0.3, 0.26, 0.31], 'response': [\n 'y', 'n', 'y'], 'bad': [False, False, True]}"], {}), "({'start_time': [1.0, 2.0, 3.0], 'stop_time': [1.5, 2.5, 3.5],\n 'condition': ['a', 'b', 'c'], 'response_latency': [0.3, 0.26, 0.31],\n 'response': ['y', 'n', 'y'], 'bad': [False, False, True]})\n", (2305, 2503), True, 'import pandas as pd\n'), ((3962, 3979), 'scipy.io.wavfile.read', 'wavread', (['mic_path'], {}), '(mic_path)\n', (3969, 3979), True, 'from scipy.io.wavfile import read as wavread\n'), ((4336, 4353), 'scipy.io.wavfile.read', 'wavread', (['spk_path'], {}), '(spk_path)\n', (4343, 4353), True, 'from scipy.io.wavfile import read as wavread\n'), ((4508, 4564), 'nwbext_ecog.ecog_manual.ECoGSubject', 'ECoGSubject', ([], {'species': '"""homo sapiens"""', 'age': '"""PY21"""', 'sex': '"""M"""'}), "(species='homo sapiens', age='PY21', sex='M')\n", (4519, 4564), False, 'from nwbext_ecog.ecog_manual import CorticalSurfaces, ECoGSubject\n'), ((4586, 4604), 'nwbext_ecog.ecog_manual.CorticalSurfaces', 'CorticalSurfaces', ([], {}), '()\n', (4602, 4604), False, 'from nwbext_ecog.ecog_manual import CorticalSurfaces, ECoGSubject\n'), ((3482, 3504), 'numpy.random.randn', 'np.random.randn', (['(30)', '(1)'], {}), '(30, 1)\n', (3497, 3504), True, 'import numpy as np\n'), ((4649, 4671), 'numpy.random.randn', 'np.random.randn', (['(10)', '(3)'], {}), '(10, 3)\n', (4664, 4671), True, 'import numpy as np\n'), ((4684, 4716), 'numpy.random.randint', 'np.random.randint', (['(0)', '(9)', '(15, 3)'], {}), '(0, 9, (15, 3))\n', (4701, 4716), True, 'import numpy as np\n'), ((5250, 5301), 'pynwb.NWBHDF5IO', 'NWBHDF5IO', (['subject_fpath'], {'manager': 'manager', 'mode': '"""r"""'}), "(subject_fpath, manager=manager, mode='r')\n", (5259, 5301), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((5449, 5496), 'pynwb.NWBHDF5IO', 'NWBHDF5IO', (['fout_path'], {'manager': 'manager', 'mode': '"""w"""'}), "(fout_path, manager=manager, mode='w')\n", (5458, 5496), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((5544, 5569), 'pynwb.NWBHDF5IO', 'NWBHDF5IO', (['fout_path', '"""r"""'], {}), "(fout_path, 'r')\n", (5553, 5569), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((5119, 5170), 'pynwb.NWBHDF5IO', 'NWBHDF5IO', (['subject_fpath'], {'manager': 'manager', 'mode': '"""w"""'}), "(subject_fpath, manager=manager, mode='w')\n", (5128, 5170), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((490, 504), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (502, 504), False, 'from datetime import datetime\n'), ((1284, 1300), 'numpy.array', 'np.array', (['groups'], {}), '(groups)\n', (1292, 1300), True, 'import numpy as np\n'), ((5092, 5107), 'pytz.timezone', 'timezone', (['"""UTC"""'], {}), "('UTC')\n", (5100, 5107), False, 'from pytz import timezone\n'), ((5060, 5080), 'datetime.datetime', 'datetime', (['(1900)', '(1)', '(1)'], {}), '(1900, 1, 1)\n', (5068, 5080), False, 'from datetime import datetime\n')]
# -*- coding: utf-8 -*- # Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause) from copy import deepcopy import numpy as np from scipy import linalg import warnings from ._event import Discrete from .viz import plot_epochs from .utils import pupil_kernel from ._fixes import string_types, nanmean, nanstd from .parallel import parallel_func class Epochs(object): """ Create epoched data Parameters ---------- raw : instance of Raw | list The raw instance to create epochs from. Can also be a list of raw instances to use. events : ndarray (n_epochs) | list The events to construct epochs around. Can also be a list of arrays. event_id : int | dict The event ID to use. Can be a dict to supply multiple event types by name. tmin : float The time window before a particular event in seconds. tmax : float The time window after a particular event in seconds. ignore_missing : bool If True, do not warn if no events were found. Returns ------- epochs : instance of Epochs The epoched dataset. """ def __init__(self, raw, events, event_id, tmin, tmax, ignore_missing=False): if np.isscalar(event_id) and not isinstance(event_id, string_types): if event_id != int(event_id): raise RuntimeError('event_id must be an integer') event_id = int(event_id) event_id = {str(event_id): event_id} if not isinstance(event_id, dict): raise RuntimeError('event_id must be an int or dict') self.event_id = deepcopy(event_id) self.tmin = tmin self.tmax = tmax self._current = 0 if not isinstance(raw, list): raw = [raw] if not isinstance(events, list): events = [events] if len(raw) != len(events): raise ValueError('raw and events must match') event_keys = dict() my_event_id = event_id.values() for k, v in event_id.items(): if (not ignore_missing and v not in np.concatenate(events)[:, 1]): warnings.warn('Did not find event id %i' % v, RuntimeWarning) event_keys[v] = k assert len(raw) > 0 # figure out parameters to use idx_offsets = raw[0].time_as_index([self.tmin, self.tmax]) n_times = idx_offsets[1] - idx_offsets[0] self._n_times = n_times self.info = dict(sfreq=raw[0].info['sfreq'], data_cols=deepcopy(raw[0].info['sample_fields']), ps_units=raw[0].info['ps_units']) for r in raw[1:]: if r.info['sfreq'] != raw[0].info['sfreq']: raise RuntimeError('incompatible raw files') # process each raw file outs = [self._process_raw_events(rr, ee, my_event_id, event_keys, idx_offsets) for rr, ee in zip(raw, events)] _samples, _discretes, _events = zip(*outs) t_off = np.cumsum(np.concatenate(([0], [r.n_samples for r in raw]))) t_off = t_off[:-1] for ev, off in zip(_events, t_off): ev[:, 0] += off # Calculate offsets for epoch indices e_off = np.cumsum(np.concatenate(([0], [len(e) for e in _events]))) _events = np.concatenate(_events) self.events = _events self._data = np.empty((e_off[-1], len(self.info['data_cols']), self.n_times)) # Need to add offsets to our epoch indices for _samp, e1, e2, t in zip(_samples, e_off[:-1], e_off[1:], t_off): for ii in range(len(_samp)): self._data[e1:e2, ii] = _samp[ii] # deal with discretes for kind in _discretes[0].keys(): this_discrete = Discrete() for d in _discretes: this_discrete.extend(d[kind]) assert len(this_discrete) == len(self.events) setattr(self, kind, this_discrete) self.info['discretes'] = list(_discretes[0].keys()) def _process_raw_events(self, raw, events, my_event_id, event_keys, idx_offsets): times = raw.times.copy() sample_inds = [] keep_idx = [] # prevent the evil events = events[events[:, 0].argsort()] discretes = dict() for kind in raw.discrete.keys(): discretes[kind] = Discrete() for ii, (event, this_id) in enumerate(events): if this_id not in my_event_id: continue this_time = times[event] this_tmin, this_tmax = this_time + self.tmin, this_time + self.tmax inds_min, inds_max = raw.time_as_index(this_time)[0] + idx_offsets if max([inds_min, inds_max]) >= len(raw): continue if min([inds_min, inds_max]) < 0: continue inds = np.arange(inds_min, inds_max) sample_inds.append(inds) keep_idx.append(ii) for kind in raw.discrete.keys(): df = raw.discrete[kind] names = df.dtype.names comp_1 = df['stime'] comp_2 = df['etime'] if 'etime' in names else df['stime'] idx = np.where((comp_1 >= this_tmin) & (comp_2 <= this_tmax))[0] subarray = df[idx] subarray['stime'] -= this_time if 'etime' in subarray.dtype.names: subarray['etime'] -= this_time discretes[kind].append(subarray) events = events[keep_idx] sample_inds = np.array(sample_inds) samples = raw[:, sample_inds][0] for kind in raw.discrete.keys(): assert len(discretes[kind]) == len(events) return samples, discretes, events def __len__(self): return len(self.events) def __repr__(self): s = '<Epochs | {0} events | tmin: {1} tmax: {2}>' return s.format(len(self), self.tmin, self.tmax) def __iter__(self): """To make iteration over epochs easy. """ self._current = 0 return self def next(self, return_event_id=False): """To make iteration over epochs easy. """ if self._current >= len(self): raise StopIteration epoch = self._data[self._current] event = self.events[self._current, -1] self._current += 1 if not return_event_id: out = epoch else: out = (epoch, event) return out def __next__(self, *args, **kwargs): return self.next(*args, **kwargs) @property def data(self): return self._data def get_data(self, kind): """Get data of a particular kind Parameters ---------- kind : str Kind of data go obtain. Must be one of ``self.info['data_cols']``. Returns ------- data : array Array of data, n_epochs x n_times. """ if kind not in self.info['data_cols']: raise ValueError('kind "%s" must be one of %s' % (kind, self.info['data_cols'])) return self._data[:, self.info['data_cols'].index(kind)].copy() @property def data_frame(self): raise NotImplementedError @property def ch_names(self): return self.info['data_cols'] @property def n_times(self): return self._n_times @property def times(self): return (np.arange(self.n_times).astype(float) / self.info['sfreq'] + self.tmin) def _str_to_idx(self, string): """Convert epoch string label to set of indices""" if string not in self.event_id: raise IndexError('ID "%s" not found, must be one of %s' % (string, list(self.event_id.keys()))) idx = np.where(self.events[:, -1] == self.event_id[string])[0] return idx def __getitem__(self, idx): out = self.copy() if isinstance(idx, string_types): idx = self._str_to_idx(idx) elif isinstance(idx, list): if all([isinstance(ii, string_types) for ii in idx]): idx = np.concatenate([self._str_to_idx(ii) for ii in idx]) if isinstance(idx, slice): idx = np.arange(len(self))[idx] else: idx = np.atleast_1d(idx) idx = np.atleast_1d(np.sort(idx)) out._data = out._data[idx] out.events = out.events[idx] for discrete in self.info['discretes']: disc = getattr(self, discrete) setattr(out, discrete, Discrete(disc[k] for k in idx)) return out def time_as_index(self, times): """Convert time to indices Parameters ---------- times : list-like | float | int List of numbers or a number representing points in time. Returns ------- index : ndarray Indices corresponding to the times supplied. """ index = (np.atleast_1d(times) - self.times[0]) * self.info['sfreq'] return index.astype(int) def copy(self): """Return a copy of Epochs. """ return deepcopy(self) def plot(self, epoch_idx=None, picks=None, n_chunks=20, title_str='#%003i', show=True, draw_discrete=None, discrete_colors=None, block=False): """ Visualize single trials using Trellis plot. Parameters ---------- epoch_idx : array-like | int | None The epochs to visualize. If None, the first 20 epochs are shown. Defaults to None. n_chunks : int The number of chunks to use for display. picks : array-like | None Channels to be included. If None only good data channels are used. Defaults to None lines : array-like | list of tuple Events to draw as vertical lines title_str : None | str The string formatting to use for axes titles. If None, no titles will be shown. Defaults expand to ``#001, #002, ...`` show : bool Whether to show the figure or not. draw_discrete : {saccades, blinks, fixations} | list-like | None | The events to draw as vertical lines. discrete_colors: : list-like | None list of str or color objects with length of discrete events drawn. block : bool Whether to halt program execution until the figure is closed. Useful for rejecting bad trials on the fly by clicking on a sub plot. Returns ------- fig : Instance of matplotlib.figure.Figure The figure. """ return plot_epochs(epochs=self, epoch_idx=epoch_idx, picks=picks, n_chunks=n_chunks, title_str=title_str, show=show, draw_discrete=draw_discrete, discrete_colors=discrete_colors, block=block) def combine_event_ids(self, old_event_ids, new_event_id): """Collapse event_ids into a new event_id Parameters ---------- old_event_ids : str, or list Conditions to collapse together. new_event_id : dict, or int A one-element dict (or a single integer) for the new condition. Note that for safety, this cannot be any existing id (in epochs.event_id.values()). Notes ----- This For example (if epochs.event_id was {'Left': 1, 'Right': 2}: combine_event_ids(epochs, ['Left', 'Right'], {'Directional': 12}) would create a 'Directional' entry in epochs.event_id replacing 'Left' and 'Right' (combining their trials). """ old_event_ids = np.asanyarray(old_event_ids) if isinstance(new_event_id, int): new_event_id = {str(new_event_id): new_event_id} else: if not isinstance(new_event_id, dict): raise ValueError('new_event_id must be a dict or int') if not len(list(new_event_id.keys())) == 1: raise ValueError('new_event_id dict must have one entry') new_event_num = list(new_event_id.values())[0] if not isinstance(new_event_num, int): raise ValueError('new_event_id value must be an integer') if new_event_num in self.event_id.values(): raise ValueError('new_event_id value must not already exist') old_event_nums = np.array([self.event_id[key] for key in old_event_ids]) # find the ones to replace inds = np.any(self.events[:, 1][:, np.newaxis] == old_event_nums[np.newaxis, :], axis=1) # replace the event numbers in the events list self.events[inds, 1] = new_event_num # delete old entries for key in old_event_ids: self.event_id.pop(key) # add the new entry self.event_id.update(new_event_id) def _key_match(self, key): """Helper function for event dict use""" if key not in self.event_id: raise KeyError('Event "%s" is not in Epochs.' % key) return self.events[:, 1] == self.event_id[key] def drop_epochs(self, indices): """Drop epochs based on indices or boolean mask Parameters ---------- indices : array of ints or bools Set epochs to remove by specifying indices to remove or a boolean mask to apply (where True values get removed). Events are correspondingly modified. """ indices = np.atleast_1d(indices) if indices.ndim > 1: raise ValueError("indices must be a scalar or a 1-d array") if indices.dtype == bool: indices = np.where(indices)[0] out_of_bounds = (indices < 0) | (indices >= len(self.events)) if out_of_bounds.any(): raise IndexError("Epoch index %d is out of bounds" % indices[out_of_bounds][0]) old_idx = np.delete(np.arange(len(self)), indices) self.events = np.delete(self.events, indices, axis=0) self._data = np.delete(self._data, indices, axis=0) for key in self.info['discretes']: val = getattr(self, key) setattr(self, key, [val[ii] for ii in old_idx]) def equalize_event_counts(self, event_ids, method='mintime'): """Equalize the number of trials in each condition Parameters ---------- event_ids : list The event types to equalize. Each entry in the list can either be a str (single event) or a list of str. In the case where one of the entries is a list of str, event_ids in that list will be grouped together before equalizing trial counts across conditions. method : str If 'truncate', events will be truncated from the end of each event list. If 'mintime', timing differences between each event list will be minimized. Returns ------- epochs : instance of Epochs The modified Epochs instance. indices : array of int Indices from the original events list that were dropped. Notes ---- This method operates in-place. """ epochs = self if len(event_ids) == 0: raise ValueError('event_ids must have at least one element') # figure out how to equalize eq_inds = list() for eq in event_ids: eq = np.atleast_1d(eq) # eq is now a list of types key_match = np.zeros(epochs.events.shape[0]) for key in eq: key_match = np.logical_or(key_match, epochs._key_match(key)) eq_inds.append(np.where(key_match)[0]) event_times = [epochs.events[eqi, 0] for eqi in eq_inds] indices = _get_drop_indices(event_times, method) # need to re-index indices indices = np.concatenate([eqi[inds] for eqi, inds in zip(eq_inds, indices)]) epochs.drop_epochs(indices) # actually remove the indices return epochs, indices def pupil_zscores(self, baseline=(None, 0)): """Get normalized pupil data Parameters ---------- baseline : list 2-element list of time points to use as baseline. The default is (None, 0), which uses all negative time. Returns ------- pupil_data : array An n_epochs x n_time array of pupil size data. """ if 'ps' not in self.info['data_cols']: raise RuntimeError('no pupil data') if len(baseline) != 2: raise RuntimeError('baseline must be a 2-element list') baseline = np.array(baseline) if baseline[0] is None: baseline[0] = self.times[0] if baseline[1] is None: baseline[1] = self.times[-1] baseline = self.time_as_index(baseline) zs = self.get_data('ps') std = nanstd(zs.flat) bl = nanmean(zs[:, baseline[0]:baseline[1] + 1], axis=1) zs -= bl[:, np.newaxis] zs /= std return zs def deconvolve(self, spacing=0.1, baseline=(None, 0), bounds=None, max_iter=500, kernel=None, n_jobs=1, acc=1e-6, method='minimize', reg=100): """Deconvolve pupillary responses Parameters ---------- spacing : float | array Spacing of time points to use for deconvolution. Can also be an array to directly specify time points to use. baseline : list 2-element list of time points to use as baseline. The default is (None, 0), which uses all negative time. This is passed to pupil_zscores(). bounds : 2-element array | None Limits for deconvolution values. Can be, e.g. (0, np.inf) to constrain to positive values. max_iter : int Maximum number of iterations of minimization algorithm. kernel : array | None Kernel to assume when doing deconvolution. If None, the Hoeks and Levelt (1993) kernel will be used. n_jobs : array Number of jobs to run in parallel. acc : float The requested accuracy. Lower accuracy generally means smoother fits. method : str Can be "minimize" to use SLSQP or "regularize" to use Tikhonov-regularized pseudoinverse. reg : float Regularization factor for pseudoinverse calculation. Returns ------- fit : array Array of fits, of size n_epochs x n_fit_times. times : array The array of times at which points were fit. Notes ----- This method is adapted from: Wierda et al., 2012, "Pupil dilation deconvolution reveals the dynamics of attention at high temporal resolution." See: http://www.pnas.org/content/109/22/8456.long Our implementation does not, by default, force all weights to be greater than zero. It also does not do first-order detrending, which the Wierda paper discusses implementing. """ if bounds is not None: bounds = np.array(bounds) if bounds.ndim != 1 or bounds.size != 2: raise RuntimeError('bounds must be 2-element array or None') if kernel is None: kernel = pupil_kernel(self.info['sfreq']) else: kernel = np.array(kernel, np.float64) if kernel.ndim != 1: raise TypeError('kernel must be 1D') if not isinstance(method, string_types) or method not in\ ('minimize', 'inverse'): raise ValueError('method must be "minimize" or "inverse", got %s' % (method,)) # get the data (and make sure it exists) pupil_data = self.pupil_zscores(baseline) # set up parallel function (and check n_jobs) parallel, p_fun, n_jobs = parallel_func(_do_deconv, n_jobs) # figure out where the samples go n_samp = self.n_times if not isinstance(spacing, (np.ndarray, tuple, list)): times = np.arange(self.times[0], self.times[-1], spacing) times = np.unique(times) else: times = np.asanyarray(spacing) samples = self.time_as_index(times) if len(samples) == 0: warnings.warn('No usable samples') return np.array([]), np.array([]) # convert bounds to slsqp representation if bounds is not None: bounds = np.array([bounds for _ in range(len(samples))]) else: bounds = [] # compatible with old version of scipy # Build the convolution matrix conv_mat = np.zeros((n_samp, len(samples))) for li, loc in enumerate(samples): eidx = min(loc + len(kernel), n_samp) conv_mat[loc:eidx, li] = kernel[:eidx-loc] # do the fitting if method == 'inverse': u, s, v = linalg.svd(conv_mat, full_matrices=False) s[s < 1e-7 * s[0]] = 0 pos_s = s[s > 0] s[s > 0] = pos_s / (pos_s ** 2 + reg) inv_conv_mat = np.dot(v.T, s[:, np.newaxis] * u.T) fit = np.dot(pupil_data, inv_conv_mat.T) else: # minimize fit_fails = parallel( p_fun(data, conv_mat, bounds, max_iter, acc) for data in np.array_split(pupil_data, n_jobs)) fit = np.concatenate([f[0] for f in fit_fails]) fails = np.concatenate([f[1] for f in fit_fails]) if np.any(fails): reasons = ', '.join(str(r) for r in np.setdiff1d(np.unique(fails), [0])) warnings.warn('%i/%i fits did not converge (reasons: %s)' % (np.sum(fails != 0), len(fails), reasons)) return fit, times def _do_deconv(pupil_data, conv_mat, bounds, max_iter, acc): """Helper to parallelize deconvolution""" from scipy.optimize import fmin_slsqp x0 = np.zeros(conv_mat.shape[1]) fit = np.empty((len(pupil_data), conv_mat.shape[1])) failed = np.empty(len(pupil_data)) for di, data in enumerate(pupil_data): out = fmin_slsqp(_score, x0, args=(data, conv_mat), epsilon=1e-4, bounds=bounds, disp=False, full_output=True, iter=max_iter, acc=acc) fit[di, :] = out[0] failed[di] = out[3] return fit, failed def _score(vals, x_0, conv_mat): return np.mean((x_0 - conv_mat.dot(vals)) ** 2) def _get_drop_indices(event_times, method): """Helper to get indices to drop from multiple event timing lists""" small_idx = np.argmin([e.shape[0] for e in event_times]) small_e_times = event_times[small_idx] if method not in ['mintime', 'truncate']: raise ValueError('method must be either mintime or truncate, not ' '%s' % method) indices = list() for e in event_times: if method == 'mintime': mask = _minimize_time_diff(small_e_times, e) else: mask = np.ones(e.shape[0], dtype=bool) mask[small_e_times.shape[0]:] = False indices.append(np.where(np.logical_not(mask))[0]) return indices def _minimize_time_diff(t_shorter, t_longer): """Find a boolean mask to minimize timing differences""" keep = np.ones((len(t_longer)), dtype=bool) scores = np.ones((len(t_longer))) for iter in range(len(t_longer) - len(t_shorter)): scores.fill(np.inf) # Check every possible removal to see if it minimizes for idx in np.where(keep)[0]: keep[idx] = False scores[idx] = _area_between_times(t_shorter, t_longer[keep]) keep[idx] = True keep[np.argmin(scores)] = False return keep def _area_between_times(t1, t2): """Quantify the difference between two timing sets""" x1 = list(range(len(t1))) x2 = list(range(len(t2))) xs = np.concatenate((x1, x2)) return np.sum(np.abs(np.interp(xs, x1, t1) - np.interp(xs, x2, t2)))
[ "numpy.sum", "numpy.ones", "numpy.argmin", "scipy.linalg.svd", "numpy.arange", "numpy.interp", "numpy.unique", "scipy.optimize.fmin_slsqp", "numpy.logical_not", "copy.deepcopy", "numpy.sort", "numpy.dot", "numpy.delete", "numpy.concatenate", "numpy.isscalar", "numpy.asanyarray", "num...
[((22657, 22684), 'numpy.zeros', 'np.zeros', (['conv_mat.shape[1]'], {}), '(conv_mat.shape[1])\n', (22665, 22684), True, 'import numpy as np\n'), ((23318, 23362), 'numpy.argmin', 'np.argmin', (['[e.shape[0] for e in event_times]'], {}), '([e.shape[0] for e in event_times])\n', (23327, 23362), True, 'import numpy as np\n'), ((24624, 24648), 'numpy.concatenate', 'np.concatenate', (['(x1, x2)'], {}), '((x1, x2))\n', (24638, 24648), True, 'import numpy as np\n'), ((1634, 1652), 'copy.deepcopy', 'deepcopy', (['event_id'], {}), '(event_id)\n', (1642, 1652), False, 'from copy import deepcopy\n'), ((3422, 3445), 'numpy.concatenate', 'np.concatenate', (['_events'], {}), '(_events)\n', (3436, 3445), True, 'import numpy as np\n'), ((5773, 5794), 'numpy.array', 'np.array', (['sample_inds'], {}), '(sample_inds)\n', (5781, 5794), True, 'import numpy as np\n'), ((9419, 9433), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (9427, 9433), False, 'from copy import deepcopy\n'), ((12064, 12092), 'numpy.asanyarray', 'np.asanyarray', (['old_event_ids'], {}), '(old_event_ids)\n', (12077, 12092), True, 'import numpy as np\n'), ((12785, 12840), 'numpy.array', 'np.array', (['[self.event_id[key] for key in old_event_ids]'], {}), '([self.event_id[key] for key in old_event_ids])\n', (12793, 12840), True, 'import numpy as np\n'), ((12926, 13011), 'numpy.any', 'np.any', (['(self.events[:, 1][:, np.newaxis] == old_event_nums[np.newaxis, :])'], {'axis': '(1)'}), '(self.events[:, 1][:, np.newaxis] == old_event_nums[np.newaxis, :],\n axis=1)\n', (12932, 13011), True, 'import numpy as np\n'), ((13926, 13948), 'numpy.atleast_1d', 'np.atleast_1d', (['indices'], {}), '(indices)\n', (13939, 13948), True, 'import numpy as np\n'), ((14435, 14474), 'numpy.delete', 'np.delete', (['self.events', 'indices'], {'axis': '(0)'}), '(self.events, indices, axis=0)\n', (14444, 14474), True, 'import numpy as np\n'), ((14496, 14534), 'numpy.delete', 'np.delete', (['self._data', 'indices'], {'axis': '(0)'}), '(self._data, indices, axis=0)\n', (14505, 14534), True, 'import numpy as np\n'), ((17178, 17196), 'numpy.array', 'np.array', (['baseline'], {}), '(baseline)\n', (17186, 17196), True, 'import numpy as np\n'), ((22838, 22972), 'scipy.optimize.fmin_slsqp', 'fmin_slsqp', (['_score', 'x0'], {'args': '(data, conv_mat)', 'epsilon': '(0.0001)', 'bounds': 'bounds', 'disp': '(False)', 'full_output': '(True)', 'iter': 'max_iter', 'acc': 'acc'}), '(_score, x0, args=(data, conv_mat), epsilon=0.0001, bounds=bounds,\n disp=False, full_output=True, iter=max_iter, acc=acc)\n', (22848, 22972), False, 'from scipy.optimize import fmin_slsqp\n'), ((1241, 1262), 'numpy.isscalar', 'np.isscalar', (['event_id'], {}), '(event_id)\n', (1252, 1262), True, 'import numpy as np\n'), ((3132, 3181), 'numpy.concatenate', 'np.concatenate', (['([0], [r.n_samples for r in raw])'], {}), '(([0], [r.n_samples for r in raw]))\n', (3146, 3181), True, 'import numpy as np\n'), ((5036, 5065), 'numpy.arange', 'np.arange', (['inds_min', 'inds_max'], {}), '(inds_min, inds_max)\n', (5045, 5065), True, 'import numpy as np\n'), ((8065, 8118), 'numpy.where', 'np.where', (['(self.events[:, -1] == self.event_id[string])'], {}), '(self.events[:, -1] == self.event_id[string])\n', (8073, 8118), True, 'import numpy as np\n'), ((8570, 8588), 'numpy.atleast_1d', 'np.atleast_1d', (['idx'], {}), '(idx)\n', (8583, 8588), True, 'import numpy as np\n'), ((8617, 8629), 'numpy.sort', 'np.sort', (['idx'], {}), '(idx)\n', (8624, 8629), True, 'import numpy as np\n'), ((15902, 15919), 'numpy.atleast_1d', 'np.atleast_1d', (['eq'], {}), '(eq)\n', (15915, 15919), True, 'import numpy as np\n'), ((15984, 16016), 'numpy.zeros', 'np.zeros', (['epochs.events.shape[0]'], {}), '(epochs.events.shape[0])\n', (15992, 16016), True, 'import numpy as np\n'), ((19745, 19761), 'numpy.array', 'np.array', (['bounds'], {}), '(bounds)\n', (19753, 19761), True, 'import numpy as np\n'), ((20008, 20036), 'numpy.array', 'np.array', (['kernel', 'np.float64'], {}), '(kernel, np.float64)\n', (20016, 20036), True, 'import numpy as np\n'), ((20729, 20778), 'numpy.arange', 'np.arange', (['self.times[0]', 'self.times[-1]', 'spacing'], {}), '(self.times[0], self.times[-1], spacing)\n', (20738, 20778), True, 'import numpy as np\n'), ((20799, 20815), 'numpy.unique', 'np.unique', (['times'], {}), '(times)\n', (20808, 20815), True, 'import numpy as np\n'), ((20850, 20872), 'numpy.asanyarray', 'np.asanyarray', (['spacing'], {}), '(spacing)\n', (20863, 20872), True, 'import numpy as np\n'), ((20959, 20993), 'warnings.warn', 'warnings.warn', (['"""No usable samples"""'], {}), "('No usable samples')\n", (20972, 20993), False, 'import warnings\n'), ((21588, 21629), 'scipy.linalg.svd', 'linalg.svd', (['conv_mat'], {'full_matrices': '(False)'}), '(conv_mat, full_matrices=False)\n', (21598, 21629), False, 'from scipy import linalg\n'), ((21771, 21806), 'numpy.dot', 'np.dot', (['v.T', '(s[:, np.newaxis] * u.T)'], {}), '(v.T, s[:, np.newaxis] * u.T)\n', (21777, 21806), True, 'import numpy as np\n'), ((21825, 21859), 'numpy.dot', 'np.dot', (['pupil_data', 'inv_conv_mat.T'], {}), '(pupil_data, inv_conv_mat.T)\n', (21831, 21859), True, 'import numpy as np\n'), ((22063, 22104), 'numpy.concatenate', 'np.concatenate', (['[f[0] for f in fit_fails]'], {}), '([f[0] for f in fit_fails])\n', (22077, 22104), True, 'import numpy as np\n'), ((22125, 22166), 'numpy.concatenate', 'np.concatenate', (['[f[1] for f in fit_fails]'], {}), '([f[1] for f in fit_fails])\n', (22139, 22166), True, 'import numpy as np\n'), ((22182, 22195), 'numpy.any', 'np.any', (['fails'], {}), '(fails)\n', (22188, 22195), True, 'import numpy as np\n'), ((23736, 23767), 'numpy.ones', 'np.ones', (['e.shape[0]'], {'dtype': 'bool'}), '(e.shape[0], dtype=bool)\n', (23743, 23767), True, 'import numpy as np\n'), ((24255, 24269), 'numpy.where', 'np.where', (['keep'], {}), '(keep)\n', (24263, 24269), True, 'import numpy as np\n'), ((24419, 24436), 'numpy.argmin', 'np.argmin', (['scores'], {}), '(scores)\n', (24428, 24436), True, 'import numpy as np\n'), ((2177, 2238), 'warnings.warn', 'warnings.warn', (["('Did not find event id %i' % v)", 'RuntimeWarning'], {}), "('Did not find event id %i' % v, RuntimeWarning)\n", (2190, 2238), False, 'import warnings\n'), ((2604, 2642), 'copy.deepcopy', 'deepcopy', (["raw[0].info['sample_fields']"], {}), "(raw[0].info['sample_fields'])\n", (2612, 2642), False, 'from copy import deepcopy\n'), ((9243, 9263), 'numpy.atleast_1d', 'np.atleast_1d', (['times'], {}), '(times)\n', (9256, 9263), True, 'import numpy as np\n'), ((14108, 14125), 'numpy.where', 'np.where', (['indices'], {}), '(indices)\n', (14116, 14125), True, 'import numpy as np\n'), ((21013, 21025), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (21021, 21025), True, 'import numpy as np\n'), ((21027, 21039), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (21035, 21039), True, 'import numpy as np\n'), ((24674, 24695), 'numpy.interp', 'np.interp', (['xs', 'x1', 't1'], {}), '(xs, x1, t1)\n', (24683, 24695), True, 'import numpy as np\n'), ((24698, 24719), 'numpy.interp', 'np.interp', (['xs', 'x2', 't2'], {}), '(xs, x2, t2)\n', (24707, 24719), True, 'import numpy as np\n'), ((5393, 5448), 'numpy.where', 'np.where', (['((comp_1 >= this_tmin) & (comp_2 <= this_tmax))'], {}), '((comp_1 >= this_tmin) & (comp_2 <= this_tmax))\n', (5401, 5448), True, 'import numpy as np\n'), ((16148, 16167), 'numpy.where', 'np.where', (['key_match'], {}), '(key_match)\n', (16156, 16167), True, 'import numpy as np\n'), ((23850, 23870), 'numpy.logical_not', 'np.logical_not', (['mask'], {}), '(mask)\n', (23864, 23870), True, 'import numpy as np\n'), ((2130, 2152), 'numpy.concatenate', 'np.concatenate', (['events'], {}), '(events)\n', (2144, 2152), True, 'import numpy as np\n'), ((7691, 7714), 'numpy.arange', 'np.arange', (['self.n_times'], {}), '(self.n_times)\n', (7700, 7714), True, 'import numpy as np\n'), ((22009, 22043), 'numpy.array_split', 'np.array_split', (['pupil_data', 'n_jobs'], {}), '(pupil_data, n_jobs)\n', (22023, 22043), True, 'import numpy as np\n'), ((22429, 22447), 'numpy.sum', 'np.sum', (['(fails != 0)'], {}), '(fails != 0)\n', (22435, 22447), True, 'import numpy as np\n'), ((22298, 22314), 'numpy.unique', 'np.unique', (['fails'], {}), '(fails)\n', (22307, 22314), True, 'import numpy as np\n')]
import itertools import copy import numpy as np import scipy import scipy.linalg from functools import reduce __all__ = ['ImplicitSurface', 'ImplicitCollection', 'ImplicitPlane', 'ImplicitSphere', 'ImplicitXAlignedCylinder', 'ImplicitEllipse', 'ImplicitIntersection', 'ImplicitUnion', 'ImplicitDifference', 'ImplicitComplement', 'GridMapBase', 'GridMap', 'GridSlip' ] class ImplicitSurface(object): def __init__(self): pass def __call__(self): raise NotImplementedError('Must be implemented by subclass.') def interior(self, grid, asarray=False): val = self.__call__(grid) if asarray: retval = np.zeros_like(val) retval[np.where(val < 0.0)] = 1.0 return retval else: return np.where(val < 0.0) def exterior(self, grid, asarray=False): val = self.__call__(grid) if asarray: retval = np.zeros_like(val) retval[np.where(val >= 0.0)] = 1.0 return retval else: return np.where(val >= 0.0) class ImplicitCollection(ImplicitSurface): def __init__(self, *items): if np.iterable(items[0]): self.items = list(items[0]) else: self.items = list(items) def __call__(self): raise NotImplementedError('Must be implemented by subclass.') class ImplicitPlane(ImplicitSurface): def __init__(self, p, n): self.p = np.array(p) self.n = np.array(n) self.n = self.n/np.linalg.norm(self.n) self.d = -np.dot(self.p,self.n) def __call__(self, grid): return self.d + reduce(lambda x,y:x+y, list(map(lambda x,y:x*y,self.n,grid))) class ImplicitSphere(ImplicitSurface): def __init__(self, c=None, r=1.0): if c is None: self.c = None else: self.c = np.array(c) self.r = r def __call__(self, grid): if self.c is None: c = np.zeros_like(grid[0].shape) else: c = self.c return reduce(lambda x,y:x+y, list(map(lambda x,y:(y-x)**2,c,grid))) - self.r**2 class ImplicitXAlignedCylinder(ImplicitSurface): def __init__(self, c=None, length=1.0, r=1.0): if c is None: self.c = None else: self.c = np.array(c) self.len = length self.r = r def __call__(self, grid): if self.c is None: c = np.zeros_like(grid[0].shape) else: c = self.c g = grid[1:] cc = c[1:] # longways = (grid[1]-c[1])**2 - self.r**2 longways = reduce(lambda x,y:x+y, list(map(lambda x,y:(y-x)**2,cc,g))) - self.r**2 cutoff = np.abs(grid[0] - c[0]) - self.len/2 return np.maximum(longways, cutoff) class ImplicitEllipse(ImplicitSurface): def __init__(self, c=None, a=None, r=1.0): if c is None: self.c = None else: self.c = np.array(c) if a is None: self.a = None else: self.a = np.array(a) self.r = r def __call__(self, grid): if self.c is None: c = np.zeros(len(grid)) else: c = self.c if self.a is None: a = np.ones(len(grid)) else: a = self.a return reduce(lambda x,y:x+y, list(map(lambda x,y,z:(((y-x)**2)/z), c,grid,a)) ) - self.r**2 class ImplicitIntersection(ImplicitCollection): def __init__(self, *items): ImplicitCollection.__init__(self, *items) def __call__(self, grid): return reduce(lambda x,y: np.maximum(x,y), [x(grid) for x in self.items]) class ImplicitUnion(ImplicitCollection): def __init__(self, *items): ImplicitCollection.__init__(self, *items) def __call__(self, grid): return reduce(lambda x,y: np.minimum(x,y), [x(grid) for x in self.items]) class ImplicitDifference(ImplicitCollection): # Maybe sometime, this should just take *items, and pop the first one for # base. This way, we can allow a single list to be passed. For now, whatever. def __init__(self, base, *items): ImplicitCollection.__init__(self, *items) self.base = base def __call__(self, grid): items = [self.base] + self.items return reduce(lambda x,y: np.maximum(x,-y), [x(grid) for x in items]) class ImplicitComplement(ImplicitSurface): def __init__(self, base): self.base = base def __call__(self, grid): return -1.0*self.base(grid) # These must be defined so that the equality is switched if the complement # is the calling surface def interior(self, grid, asarray=False): val = self.__call__(grid) if asarray: retval = np.zeros_like(val) retval[np.where(val <= 0.0)] = 1.0 return retval else: return np.where(val <= 0.0) def exterior(self, grid, asarray=False): val = self.__call__(grid) if asarray: retval = np.zeros_like(val) retval[np.where(val > 0.0)] = 1.0 return retval else: return np.where(val > 0.0) class GridMapBase(object): def __init__(self): pass def __call__(self): raise NotImplementedError('Must be implemented by subclass.') class GridMap(GridMapBase): def __init__(self, funcs): self.funcs = funcs def __call__(self, grid): new_grid = [] for f,g in zip(self.funcs,grid): if f is not None: new_grid.append(f(g)) else: new_grid.append(g) return tuple(new_grid) class GridSlip(GridMapBase): # Creates a slip or a fault along the specifid plane def __init__(self, p, n): self.p = np.array(p) self.n = np.array(n) self.n = self.n/np.linalg.norm(self.n) self.d = -np.dot(self.p,self.n) self.basis = None def __call__(self, grid, direction, amount): # amount is a scalar # direction is a vector that will be normalized # the slip occurs along that vector's projection onto the plane, i.e., it is orthogonal to the normal # the exterior of the slip plane (the part the normal points to) is the part that is modified. d = np.array(direction) d = d/np.linalg.norm(d) dim = len(d) if self.basis is None: basis = [self.n] # Gramm schmidt while len(basis) != dim: c = np.random.rand(3) for b in basis: c -= np.dot(b,c)*b cn = np.linalg.norm(c) if cn > 1e-4: basis.append(c/cn) self.basis = basis[1:] # Project the slip direction onto the basis proj=0 for b in self.basis: proj += np.dot(d,b)*b # Scale the projection proj = amount*proj # Evaluate the plane to figure out what components of the old grid are shifted. val = self.d + reduce(lambda x,y:x+y, list(map(lambda x,y:x*y,self.n,grid))) loc = np.where(val >= 0.0) # Perform the shift. new_grid = [copy.deepcopy(g) for g in grid] for ng,p in zip(new_grid,proj): ng[loc] -=p return tuple(new_grid) class Weird(ImplicitSurface): def __init__(self, p,n, c=None, r=1.0): if c is None: self.c = None else: self.c = np.array(c) self.r = r self.p = np.array(p) self.n = np.array(n) self.n = self.n/np.linalg.norm(self.n) self.d = -np.dot(self.p,self.n) def __call__(self, grid): if self.c is None: c = np.zeros_like(grid[0].shape) else: c = self.c # Creates flat eye thingies # val1 = reduce(lambda x,y:x+y, map(lambda x,y:(y-x)**2,c,grid)) - self.r**2 # # val2 = self.d + reduce(lambda x,y:x+y, map(lambda x,y:x*y,self.n,grid)) # # return 4*val1/np.max(val1)+val2 val1 = reduce(lambda x,y:x+y, list(map(lambda x,y:(y-x)**2,c,grid))) - self.r**2 val2 = self.d + reduce(lambda x,y:x+y, list(map(lambda x,y:x*y,self.n,grid))) return 4*val1/np.max(val1)+val2 class Hyperbola(ImplicitSurface): def __init__(self, c=None, r=1.0): if c is None: self.c = None else: self.c = np.array(c) self.r = r def __call__(self, grid): if self.c is None: c = np.zeros_like(grid[0].shape) else: c = self.c return reduce(lambda x,y:-x+y, list(map(lambda x,y:(y-x)**2,c,grid))) - self.r**2 class Weird2(ImplicitSurface): def __init__(self, c=None, r=1.0, s=None): if c is None: self.c = None else: self.c = np.array(c) if s is None: self.s = None else: self.s = np.array(s) self.r = r def __call__(self, grid): c = np.zeros_like(grid[0].shape) if self.c is None else self.c s = np.ones_like(grid[0].shape) if self.s is None else self.s return ((grid[0]-c[0])**2)/s[0] + ((grid[1]-c[1])**1)/s[1] - self.r**2 #reduce(lambda x,y:-x+y, map(lambda x,y:(y-x)**2,c,grid)) - self.r**2 # FIXME #if __name__ == "__main__": # # import numpy as np # import matplotlib.pyplot as mpl # # from pysit import * # # x_lbc = PML(0.0, 100.0) # x_rbc = PML(0.0, 100.0) # z_lbc = PML(0.0, 100.0) # z_rbc = PML(0.0, 100.0) # # xmin, xmax = 0.0, 20 # zmin, zmax = 0.0, 10 # nx, nz = 500,250 # # x_config = (xmin, xmax, nx, x_lbc, x_rbc) # z_config = (zmin, zmax, nz, z_lbc, z_rbc) # # d = Domain((x_config, z_config)) # # grid = d.generate_grid() # grid = grid[0].reshape(d.shape).T, grid[1].reshape(d.shape).T # # p1 = ImplicitPlane((0.0,4.0),(0.0,-1.0)) # p2 = ImplicitPlane((0.0,6.0),(0.0,1.0)) # # w1 = Weird((0.0,5.0),(0.0,-1.0), (10,5)) # w2 = Weird((0.0,6.0),(0.0,1.0), (10,5)) # # w3 = Weird2((10,4),1.5,(-100.0,1.)) # w4 = Weird2((10,4),0.5,( 100.0,1.)) # # band = ImplicitIntersection(w1,w2) # band = ImplicitIntersection(p1,p2) # band = ImplicitDifference(w3,w4) # # g = GridSlip((10.0,5.0), (1,0.5)) # d = (0.0,-1.0) # a = 0.5 # new_grid = g(grid,d,a) # # # plt.figure() # plt.imshow(band(grid)) # plt.colorbar() # # plt.figure() # plt.imshow(band(new_grid)) # plt.colorbar() # # plt.figure() # plt.imshow(band.interior(grid)) # plt.colorbar() # # plt.figure() # plt.imshow(band.interior(new_grid)) # plt.colorbar() # # plt.show()
[ "copy.deepcopy", "numpy.zeros_like", "numpy.maximum", "numpy.abs", "numpy.ones_like", "numpy.minimum", "numpy.max", "numpy.where", "numpy.array", "numpy.linalg.norm", "numpy.iterable", "numpy.random.rand", "numpy.dot" ]
[((1298, 1319), 'numpy.iterable', 'np.iterable', (['items[0]'], {}), '(items[0])\n', (1309, 1319), True, 'import numpy as np\n'), ((1593, 1604), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (1601, 1604), True, 'import numpy as np\n'), ((1622, 1633), 'numpy.array', 'np.array', (['n'], {}), '(n)\n', (1630, 1633), True, 'import numpy as np\n'), ((2894, 2922), 'numpy.maximum', 'np.maximum', (['longways', 'cutoff'], {}), '(longways, cutoff)\n', (2904, 2922), True, 'import numpy as np\n'), ((5941, 5952), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (5949, 5952), True, 'import numpy as np\n'), ((5970, 5981), 'numpy.array', 'np.array', (['n'], {}), '(n)\n', (5978, 5981), True, 'import numpy as np\n'), ((6456, 6475), 'numpy.array', 'np.array', (['direction'], {}), '(direction)\n', (6464, 6475), True, 'import numpy as np\n'), ((7288, 7308), 'numpy.where', 'np.where', (['(val >= 0.0)'], {}), '(val >= 0.0)\n', (7296, 7308), True, 'import numpy as np\n'), ((7694, 7705), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (7702, 7705), True, 'import numpy as np\n'), ((7723, 7734), 'numpy.array', 'np.array', (['n'], {}), '(n)\n', (7731, 7734), True, 'import numpy as np\n'), ((799, 817), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (812, 817), True, 'import numpy as np\n'), ((923, 942), 'numpy.where', 'np.where', (['(val < 0.0)'], {}), '(val < 0.0)\n', (931, 942), True, 'import numpy as np\n'), ((1064, 1082), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (1077, 1082), True, 'import numpy as np\n'), ((1189, 1209), 'numpy.where', 'np.where', (['(val >= 0.0)'], {}), '(val >= 0.0)\n', (1197, 1209), True, 'import numpy as np\n'), ((1658, 1680), 'numpy.linalg.norm', 'np.linalg.norm', (['self.n'], {}), '(self.n)\n', (1672, 1680), True, 'import numpy as np\n'), ((1699, 1721), 'numpy.dot', 'np.dot', (['self.p', 'self.n'], {}), '(self.p, self.n)\n', (1705, 1721), True, 'import numpy as np\n'), ((2000, 2011), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (2008, 2011), True, 'import numpy as np\n'), ((2105, 2133), 'numpy.zeros_like', 'np.zeros_like', (['grid[0].shape'], {}), '(grid[0].shape)\n', (2118, 2133), True, 'import numpy as np\n'), ((2444, 2455), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (2452, 2455), True, 'import numpy as np\n'), ((2575, 2603), 'numpy.zeros_like', 'np.zeros_like', (['grid[0].shape'], {}), '(grid[0].shape)\n', (2588, 2603), True, 'import numpy as np\n'), ((2842, 2864), 'numpy.abs', 'np.abs', (['(grid[0] - c[0])'], {}), '(grid[0] - c[0])\n', (2848, 2864), True, 'import numpy as np\n'), ((3094, 3105), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (3102, 3105), True, 'import numpy as np\n'), ((3189, 3200), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (3197, 3200), True, 'import numpy as np\n'), ((4901, 4919), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (4914, 4919), True, 'import numpy as np\n'), ((5026, 5046), 'numpy.where', 'np.where', (['(val <= 0.0)'], {}), '(val <= 0.0)\n', (5034, 5046), True, 'import numpy as np\n'), ((5168, 5186), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (5181, 5186), True, 'import numpy as np\n'), ((5292, 5311), 'numpy.where', 'np.where', (['(val > 0.0)'], {}), '(val > 0.0)\n', (5300, 5311), True, 'import numpy as np\n'), ((6006, 6028), 'numpy.linalg.norm', 'np.linalg.norm', (['self.n'], {}), '(self.n)\n', (6020, 6028), True, 'import numpy as np\n'), ((6047, 6069), 'numpy.dot', 'np.dot', (['self.p', 'self.n'], {}), '(self.p, self.n)\n', (6053, 6069), True, 'import numpy as np\n'), ((6490, 6507), 'numpy.linalg.norm', 'np.linalg.norm', (['d'], {}), '(d)\n', (6504, 6507), True, 'import numpy as np\n'), ((7359, 7375), 'copy.deepcopy', 'copy.deepcopy', (['g'], {}), '(g)\n', (7372, 7375), False, 'import copy\n'), ((7645, 7656), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (7653, 7656), True, 'import numpy as np\n'), ((7759, 7781), 'numpy.linalg.norm', 'np.linalg.norm', (['self.n'], {}), '(self.n)\n', (7773, 7781), True, 'import numpy as np\n'), ((7800, 7822), 'numpy.dot', 'np.dot', (['self.p', 'self.n'], {}), '(self.p, self.n)\n', (7806, 7822), True, 'import numpy as np\n'), ((7896, 7924), 'numpy.zeros_like', 'np.zeros_like', (['grid[0].shape'], {}), '(grid[0].shape)\n', (7909, 7924), True, 'import numpy as np\n'), ((8573, 8584), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (8581, 8584), True, 'import numpy as np\n'), ((8678, 8706), 'numpy.zeros_like', 'np.zeros_like', (['grid[0].shape'], {}), '(grid[0].shape)\n', (8691, 8706), True, 'import numpy as np\n'), ((8998, 9009), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (9006, 9009), True, 'import numpy as np\n'), ((9094, 9105), 'numpy.array', 'np.array', (['s'], {}), '(s)\n', (9102, 9105), True, 'import numpy as np\n'), ((9169, 9197), 'numpy.zeros_like', 'np.zeros_like', (['grid[0].shape'], {}), '(grid[0].shape)\n', (9182, 9197), True, 'import numpy as np\n'), ((9240, 9267), 'numpy.ones_like', 'np.ones_like', (['grid[0].shape'], {}), '(grid[0].shape)\n', (9252, 9267), True, 'import numpy as np\n'), ((837, 856), 'numpy.where', 'np.where', (['(val < 0.0)'], {}), '(val < 0.0)\n', (845, 856), True, 'import numpy as np\n'), ((1102, 1122), 'numpy.where', 'np.where', (['(val >= 0.0)'], {}), '(val >= 0.0)\n', (1110, 1122), True, 'import numpy as np\n'), ((3747, 3763), 'numpy.maximum', 'np.maximum', (['x', 'y'], {}), '(x, y)\n', (3757, 3763), True, 'import numpy as np\n'), ((3984, 4000), 'numpy.minimum', 'np.minimum', (['x', 'y'], {}), '(x, y)\n', (3994, 4000), True, 'import numpy as np\n'), ((4461, 4478), 'numpy.maximum', 'np.maximum', (['x', '(-y)'], {}), '(x, -y)\n', (4471, 4478), True, 'import numpy as np\n'), ((4939, 4959), 'numpy.where', 'np.where', (['(val <= 0.0)'], {}), '(val <= 0.0)\n', (4947, 4959), True, 'import numpy as np\n'), ((5206, 5225), 'numpy.where', 'np.where', (['(val > 0.0)'], {}), '(val > 0.0)\n', (5214, 5225), True, 'import numpy as np\n'), ((6677, 6694), 'numpy.random.rand', 'np.random.rand', (['(3)'], {}), '(3)\n', (6691, 6694), True, 'import numpy as np\n'), ((6787, 6804), 'numpy.linalg.norm', 'np.linalg.norm', (['c'], {}), '(c)\n', (6801, 6804), True, 'import numpy as np\n'), ((7027, 7039), 'numpy.dot', 'np.dot', (['d', 'b'], {}), '(d, b)\n', (7033, 7039), True, 'import numpy as np\n'), ((8398, 8410), 'numpy.max', 'np.max', (['val1'], {}), '(val1)\n', (8404, 8410), True, 'import numpy as np\n'), ((6752, 6764), 'numpy.dot', 'np.dot', (['b', 'c'], {}), '(b, c)\n', (6758, 6764), True, 'import numpy as np\n')]
import glob, os, shutil import numpy as np def copy_file(image_dir, photo, output_dir): image_path = os.path.join(image_dir, "%s.jpg" % photo) if os.path.isfile(image_path): if not os.path.isdir(output_dir): os.makedirs(output_dir) shutil.copy(image_path, output_dir) meta_dir = "D:/data/fashion/image_retrieval/street2shop/meta/json" category_path = "D:/data/fashion/image_retrieval/street2shop/meta/json/category.npy" image_dir = "D:/data/fashion/image_retrieval/street2shop/images_resize" dataset_dir = "D:/data/fashion/image_retrieval/street2shop/tfrecord_images" train_query_dir = os.path.join(dataset_dir, "train", "query") train_index_dir = os.path.join(dataset_dir, "train", "index") test_query_dir = os.path.join(dataset_dir, "test", "query") test_index_dir = os.path.join(dataset_dir, "test", "index") retrieval_files = glob.glob(os.path.join(meta_dir, "retrieval_*.npy")) train_files = glob.glob(os.path.join(meta_dir, "train_*.npy")) test_files = glob.glob(os.path.join(meta_dir, "test_*.npy")) retrieval_files.sort() train_files.sort() test_files.sort() total = len(retrieval_files) for i in range(len(retrieval_files)): index_file = retrieval_files[i] train_file = train_files[i] test_file = test_files[i] category = os.path.splitext(os.path.basename(index_file))[0].split("_")[1] print(category) indices = np.load(index_file) trains = np.load(train_file) tests = np.load(test_file) index_map = {} ind_total = len(indices) for j, ind in enumerate(indices): print("category %d/%d, file %d/%d" % (i, total, j, ind_total)) photo = str(ind["photo"]) product = str(ind["product"]) if not product in index_map: index_map[product] = [] index_map[product].append(photo) tr_total = len(trains) for j, tr in enumerate(trains): print("category %d/%d, file %d/%d" % (i, total, j, tr_total)) photo = str(tr["photo"]) product = str(tr["product"]) if product not in index_map: print("skip: not in index for test") continue copy_file(image_dir, photo, os.path.join(train_query_dir, product)) for index_photo in index_map[product]: copy_file(image_dir, index_photo, os.path.join(train_index_dir, product)) te_total = len(tests) for j, te in enumerate(tests): print("category %d/%d, file %d/%d" % (i, total, j, te_total)) photo = str(te["photo"]) product = str(te["product"]) if product not in index_map: print("skip: not in index for train") continue copy_file(image_dir, photo, os.path.join(test_query_dir, product)) for index_photo in index_map[product]: copy_file(image_dir, index_photo, os.path.join(test_index_dir, product))
[ "numpy.load", "os.makedirs", "os.path.basename", "os.path.isdir", "os.path.isfile", "os.path.join", "shutil.copy" ]
[((626, 669), 'os.path.join', 'os.path.join', (['dataset_dir', '"""train"""', '"""query"""'], {}), "(dataset_dir, 'train', 'query')\n", (638, 669), False, 'import glob, os, shutil\n'), ((688, 731), 'os.path.join', 'os.path.join', (['dataset_dir', '"""train"""', '"""index"""'], {}), "(dataset_dir, 'train', 'index')\n", (700, 731), False, 'import glob, os, shutil\n'), ((749, 791), 'os.path.join', 'os.path.join', (['dataset_dir', '"""test"""', '"""query"""'], {}), "(dataset_dir, 'test', 'query')\n", (761, 791), False, 'import glob, os, shutil\n'), ((809, 851), 'os.path.join', 'os.path.join', (['dataset_dir', '"""test"""', '"""index"""'], {}), "(dataset_dir, 'test', 'index')\n", (821, 851), False, 'import glob, os, shutil\n'), ((107, 148), 'os.path.join', 'os.path.join', (['image_dir', "('%s.jpg' % photo)"], {}), "(image_dir, '%s.jpg' % photo)\n", (119, 148), False, 'import glob, os, shutil\n'), ((156, 182), 'os.path.isfile', 'os.path.isfile', (['image_path'], {}), '(image_path)\n', (170, 182), False, 'import glob, os, shutil\n'), ((881, 922), 'os.path.join', 'os.path.join', (['meta_dir', '"""retrieval_*.npy"""'], {}), "(meta_dir, 'retrieval_*.npy')\n", (893, 922), False, 'import glob, os, shutil\n'), ((948, 985), 'os.path.join', 'os.path.join', (['meta_dir', '"""train_*.npy"""'], {}), "(meta_dir, 'train_*.npy')\n", (960, 985), False, 'import glob, os, shutil\n'), ((1010, 1046), 'os.path.join', 'os.path.join', (['meta_dir', '"""test_*.npy"""'], {}), "(meta_dir, 'test_*.npy')\n", (1022, 1046), False, 'import glob, os, shutil\n'), ((1388, 1407), 'numpy.load', 'np.load', (['index_file'], {}), '(index_file)\n', (1395, 1407), True, 'import numpy as np\n'), ((1421, 1440), 'numpy.load', 'np.load', (['train_file'], {}), '(train_file)\n', (1428, 1440), True, 'import numpy as np\n'), ((1453, 1471), 'numpy.load', 'np.load', (['test_file'], {}), '(test_file)\n', (1460, 1471), True, 'import numpy as np\n'), ((270, 305), 'shutil.copy', 'shutil.copy', (['image_path', 'output_dir'], {}), '(image_path, output_dir)\n', (281, 305), False, 'import glob, os, shutil\n'), ((199, 224), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (212, 224), False, 'import glob, os, shutil\n'), ((238, 261), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (249, 261), False, 'import glob, os, shutil\n'), ((2162, 2200), 'os.path.join', 'os.path.join', (['train_query_dir', 'product'], {}), '(train_query_dir, product)\n', (2174, 2200), False, 'import glob, os, shutil\n'), ((2681, 2718), 'os.path.join', 'os.path.join', (['test_query_dir', 'product'], {}), '(test_query_dir, product)\n', (2693, 2718), False, 'import glob, os, shutil\n'), ((2295, 2333), 'os.path.join', 'os.path.join', (['train_index_dir', 'product'], {}), '(train_index_dir, product)\n', (2307, 2333), False, 'import glob, os, shutil\n'), ((2813, 2850), 'os.path.join', 'os.path.join', (['test_index_dir', 'product'], {}), '(test_index_dir, product)\n', (2825, 2850), False, 'import glob, os, shutil\n'), ((1307, 1335), 'os.path.basename', 'os.path.basename', (['index_file'], {}), '(index_file)\n', (1323, 1335), False, 'import glob, os, shutil\n')]
import os import io import base64 import face_recognition import numpy as np from PIL import Image, ImageDraw class PythonPredictor: def __init__(self, config): # extract face features of the following person image_data = [['<NAME>', 'assets/face.jpg']] self.known_face_encodings = [] self.known_face_names = [] # Load a sample picture and learn how to recognize it. for person in image_data: person_name = person[0] person_file = person[1] person_image = face_recognition.load_image_file(person_file) person_face_encoding = face_recognition.face_encodings(person_image)[0] self.known_face_encodings.append(person_face_encoding) self.known_face_names.append(person_name) def predict(self, payload): check_image = io.BytesIO(base64.b64decode(payload["base64"])) # Load an image with an unknown face unknown_image = face_recognition.load_image_file(check_image) # Find all the faces and face encodings in the unknown image face_locations = face_recognition.face_locations(unknown_image) face_encodings = face_recognition.face_encodings(unknown_image, face_locations) # Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library # See http://pillow.readthedocs.io/ for more about PIL/Pillow pil_image = Image.fromarray(unknown_image) # Create a Pillow ImageDraw Draw instance to draw with draw = ImageDraw.Draw(pil_image) # Loop through each face found in the unknown image for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): # See if the face is a match for the known face(s) matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding) name = "Unknown" # Or instead, use the known face with the smallest distance to the new face face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = self.known_face_names[best_match_index] # Draw a box around the face using the Pillow module draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255)) # Draw a label with a name below the face text_width, text_height = draw.textsize(name) draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255)) draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255)) # Remove the drawing library from memory as per the Pillow docs del draw # Display the resulting image #pil_image.save(output_file) im_file = io.BytesIO() pil_image.save(im_file, format="PNG") im_bytes = base64.b64encode(im_file.getvalue()).decode("utf-8") return im_bytes
[ "io.BytesIO", "face_recognition.face_distance", "face_recognition.compare_faces", "face_recognition.face_encodings", "base64.b64decode", "numpy.argmin", "PIL.Image.fromarray", "PIL.ImageDraw.Draw", "face_recognition.face_locations", "face_recognition.load_image_file" ]
[((974, 1019), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['check_image'], {}), '(check_image)\n', (1006, 1019), False, 'import face_recognition\n'), ((1115, 1161), 'face_recognition.face_locations', 'face_recognition.face_locations', (['unknown_image'], {}), '(unknown_image)\n', (1146, 1161), False, 'import face_recognition\n'), ((1187, 1249), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['unknown_image', 'face_locations'], {}), '(unknown_image, face_locations)\n', (1218, 1249), False, 'import face_recognition\n'), ((1448, 1478), 'PIL.Image.fromarray', 'Image.fromarray', (['unknown_image'], {}), '(unknown_image)\n', (1463, 1478), False, 'from PIL import Image, ImageDraw\n'), ((1557, 1582), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['pil_image'], {}), '(pil_image)\n', (1571, 1582), False, 'from PIL import Image, ImageDraw\n'), ((2937, 2949), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (2947, 2949), False, 'import io\n'), ((550, 595), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['person_file'], {}), '(person_file)\n', (582, 595), False, 'import face_recognition\n'), ((867, 902), 'base64.b64decode', 'base64.b64decode', (["payload['base64']"], {}), "(payload['base64'])\n", (883, 902), False, 'import base64\n'), ((1823, 1895), 'face_recognition.compare_faces', 'face_recognition.compare_faces', (['self.known_face_encodings', 'face_encoding'], {}), '(self.known_face_encodings, face_encoding)\n', (1853, 1895), False, 'import face_recognition\n'), ((2044, 2116), 'face_recognition.face_distance', 'face_recognition.face_distance', (['self.known_face_encodings', 'face_encoding'], {}), '(self.known_face_encodings, face_encoding)\n', (2074, 2116), False, 'import face_recognition\n'), ((2148, 2173), 'numpy.argmin', 'np.argmin', (['face_distances'], {}), '(face_distances)\n', (2157, 2173), True, 'import numpy as np\n'), ((631, 676), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['person_image'], {}), '(person_image)\n', (662, 676), False, 'import face_recognition\n')]
# read the csv files to get raw data import pandas as pd import numpy as np def read_data(filename): ''' Phyphox can output raw data as csv files. For a gyroscope data, it has such format: time, gyroscope x, gyroscope y, gyroscope z, absolute value. ''' try: # only if the file is found then start parsing file = pd.read_csv(filename) data = np.zeros((file.shape[1],file.shape[0])) data[0] = np.array(file['Time (s)']) data[1] = np.array(file['Gyroscope x (rad/s)']) data[2] = np.array(file['Gyroscope y (rad/s)']) data[3] = np.array(file['Gyroscope z (rad/s)']) data[4] = np.array(file['Absolute (rad/s)']) # return the data as a numpy array return(data) except: print("The file is not a csv file or it's not in the current folder.")
[ "pandas.read_csv", "numpy.zeros", "numpy.array" ]
[((363, 384), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (374, 384), True, 'import pandas as pd\n'), ((400, 440), 'numpy.zeros', 'np.zeros', (['(file.shape[1], file.shape[0])'], {}), '((file.shape[1], file.shape[0]))\n', (408, 440), True, 'import numpy as np\n'), ((467, 493), 'numpy.array', 'np.array', (["file['Time (s)']"], {}), "(file['Time (s)'])\n", (475, 493), True, 'import numpy as np\n'), ((512, 549), 'numpy.array', 'np.array', (["file['Gyroscope x (rad/s)']"], {}), "(file['Gyroscope x (rad/s)'])\n", (520, 549), True, 'import numpy as np\n'), ((568, 605), 'numpy.array', 'np.array', (["file['Gyroscope y (rad/s)']"], {}), "(file['Gyroscope y (rad/s)'])\n", (576, 605), True, 'import numpy as np\n'), ((624, 661), 'numpy.array', 'np.array', (["file['Gyroscope z (rad/s)']"], {}), "(file['Gyroscope z (rad/s)'])\n", (632, 661), True, 'import numpy as np\n'), ((680, 714), 'numpy.array', 'np.array', (["file['Absolute (rad/s)']"], {}), "(file['Absolute (rad/s)'])\n", (688, 714), True, 'import numpy as np\n')]
""" Python program that uses scipy for generating a valid arm trajectory A few useful resources https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.NonlinearConstraint.html#scipy.optimize.NonlinearConstraint https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize https://docs.scipy.org/doc/scipy/reference/optimize.html Most importantly, we note that nonlinear constraints are only supported with COBYLA, SLSQP and trust-constr solvers. Note: To set desired orientations, use Date: 2/2/2021 """ from __future__ import print_function import numpy as np import csv import time from scipy import signal from scipy.optimize import least_squares, Bounds, fmin import matplotlib.pyplot as plt import matplotlib as mpl import klampt # Class Trajectory Planner contains all the necessary getter and setter functions needed to either # 1) Generate a csv file with step position commands for a specific acceleration profile # 2) Implement class functions directly into simulation for real-time (albeit slow) optimization class TrajectoryPlanner3D(): # Function: Init # Pretty self-explanatory... def __init__(self, robot, sus): # Initializing necessary arrays for the active and passive states self.xa_init = None self.dxa_init = None self.xp_init = None self.dxp_init = None self.xa_target = None self.xp_target = None self.n_p = None self.n_a = None # Time parameters (default settings) self.T = 1.0 self.dt = 0.005 self.t_cmd = 10*self.dt self.n_coeffs = 5 self.n_steps = int(round(self.T / self.dt)) self.t = np.linspace(0, self.T, self.n_steps) # Optimizer parameters (default settings) self.w_xp = 3 self.w_control = 0.07 self.iteration = 0 # Butterworth filter parameters (default settings) self.butter_order = 1 self.butter_cutoff = 0.0625 # Initializing parameters for stiff/damp matrices and Klampt models self.sus = sus self.robot = robot # Initializing parameters self.g = 9.81 # m/s^2, gravitationnal acceleration # Function: Set Initial # Sets up initial passive and active states and derivatives. def set_initial(self, xa_init, dxa_init, xp_init, dxp_init): self.xa_init = xa_init self.dxa_init = dxa_init self.xp_init = xp_init self.dxp_init = dxp_init self.n_p = int(np.shape(xp_init)[0]) self.n_a = int(np.shape(xa_init)[0]) # Function: Set Target # Sets up active state targets def set_target(self, xa_target): self.xa_target = xa_target # Function: Set Time Parameter # Sets up time parameters (i.e. time steps, time horizon, command time chunks, etc.) def set_time_parameters(self, T, dt, mult_cmd, n_coeffs): self.T = T # T = secs, time horizon self.dt = dt # secs, time step self.n_steps = int(round(T / dt)) # number of time steps self.dt = T / self.n_steps # secs, actual time step self.t = np.linspace(0, T, self.n_steps) # time vector in seconds self.t_cmd = mult_cmd*dt # time of command chunk self.n_coeffs = n_coeffs # number of coefficients (needs to be a factor of n_steps) # Function: Get Time Parameters # Returns a list of the time parameters def get_time_parameters(self): return [self.T, self.dt, self.n_steps, self.t_cmd, self.n_coeffs] # Function: Set Objective Weights # Sets up the weights of the least squares optimizer cost vector (i.e. w_xp is the weight on the passive states # and w_control is the weight on the active state acceleration control input) def set_objective_weights(self, w_xp, w_control): self.w_xp = w_xp self.w_control = w_control # Function: Set Butterworth Settings # Sets up butterworth filter used to smooth acceleration control input (order and cutoff frequency) def set_butter_settings(butter_order, butter_cutoff): self.butter_order = butter_order self.butter_cutoff = butter_cutoff # Function: Get Passive State Target # Returns the target static passive state, calculated by using the stiffness matrix and gravity vectors # calculated using Klampt def get_xp_target(self, x_p): x = [0, 0, x_p[0], 0, x_p[1], x_p[2]] + list(self.xa_target) self.robot.setConfig(x) G = self.robot.getGravityForces([0, 0, -self.g]) K = np.asarray(self.sus.GetStiffnessMatrix(qPitch=x_p[1], qRoll=x_p[2])) G_p = np.array([G[2], G[4], G[5]]) v = G_p + np.dot(K, x_p) return np.dot(v, v) # Function: Function Evaluation # Calculates the current polynomial at all time steps def f_eval(self, time, coeffs): result = np.zeros((len(time))) t_chunks = np.split(time, len(coeffs)) # split time in self.n_coeffs groups for idx, t in enumerate(time): for chunk_idx, chunk in enumerate(t_chunks): if t in chunk: result[idx] = coeffs[chunk_idx] return result # Function: Input Evaluation # Objective function of least squares optimizer. For each active state, calculates control input using coeffs def u_eval(self, coeffs): u = list() b, a = signal.butter(self.butter_order, self.butter_cutoff) # first order, cutoff 62.5 hz for axis_idx in range(self.n_a): # Select cofficients of axis axis_idx axis_coeffs = coeffs[axis_idx * self.n_coeffs:(axis_idx + 1) * self.n_coeffs] # Evaluate the current polynomial at all time steps axis_u = self.f_eval(self.t, axis_coeffs) # Apply filter and append axis_u = signal.filtfilt(b, a, axis_u, padlen=20) u.append(axis_u) u = np.stack(u, axis=1) u = u.reshape((self.n_steps * self.n_a)) return u # Function: Forward Simulation Step # Calculates the passive and active states and derivatives of the next time step def forward_sim_step(self, xp, dxp, xa, dxa, ddxa): # For robot class function callbacks, state is [x y z yaw pitch roll 4DOF] state = np.concatenate(([0.0, 0.0], xp[0], 0, xp[1], xp[2], xa), axis=None) dstate = np.concatenate(([0.0, 0.0], dxp[0], 0, dxp[1], dxp[2], dxa), axis=None) self.robot.setConfig(state) self.robot.setVelocity(dstate) # Collect H, G, C, K, and B matrices and vectors. Resize for calculations H_mat = np.asarray(self.robot.getMassMatrix()) H_mat = np.delete(H_mat, [0, 1, 3], 0) H_mat = np.delete(H_mat, [0, 1, 3], 1) g_vec = self.robot.getGravityForces((0, 0, -self.g)) g_vec = np.array(g_vec) g_vec = np.delete(g_vec, [0, 1, 3]) c_vec = self.robot.getCoriolisForces() c_vec = np.array(c_vec) c_vec = np.delete(c_vec, [0, 1, 3]) Ks_mat = np.asarray(self.sus.GetStiffnessMatrix(z=xp[0], qPitch=xp[1], qRoll=xp[2])) Kb_mat = np.asarray(self.sus.GetDampingMatrix(z=xp[0], qPitch=xp[1], qRoll=xp[2])) # Resizing dynamics term to state vector relevent to the problem H11_mat = H_mat[0:self.n_p, 0:self.n_p] H12_mat = H_mat[0:self.n_p, self.n_p:(self.n_p + self.n_a)] Gp_vec = g_vec[0:self.n_p] Ga_vec = g_vec[self.n_p:self.n_a + self.n_p] Cp_vec = c_vec[0:self.n_p] # Right hand side of dynamics equation (without inertial matrix inverse) rhs = -(Cp_vec + np.matmul(Kb_mat, dxp) + np.matmul(Ks_mat, xp) + Gp_vec + np.matmul(H12_mat, ddxa)) # rhs = -(np.matmul(Kb_mat,dxp) + np.matmul(Ks_mat,xp) + Gp_vec ) # print(-(np.matmul(Kb_mat,dxp) + np.matmul(Ks_mat,xp) + Gp_vec ) ) (ddxp, _, _, _) = np.linalg.lstsq(H11_mat, rhs, rcond=None) # Kinematics calculations dxp_next = dxp + ddxp * self.dt dxa_next = dxa + ddxa * self.dt xp_next = xp + dxp * self.dt + 0.5 * ddxp * self.dt ** 2 xa_next = xa + dxa * self.dt + 0.5 * ddxa * self.dt ** 2 return (xp_next, dxp_next, xa_next, dxa_next) # Function: Forward Simulation # Returns full list of passive and active states, derivatives, and errors for plotting given control input. def forward_sim(self, u): # Initializing passive and active states and derivatives xp = np.zeros((self.n_steps, self.n_p)) xa = np.zeros((self.n_steps, self.n_a)) dxp = np.zeros((self.n_steps, self.n_p)) dxa = np.zeros((self.n_steps, self.n_a)) ddxa = u.reshape((self.n_steps, self.n_a)) delta_xp = np.zeros((self.n_steps, self.n_p)) delta_xa = np.zeros((self.n_steps, self.n_a)) # Assigning initial conditions xp[0, :] = self.xp_init xa[0, :] = self.xa_init dxp[0, :] = self.dxp_init dxa[0, :] = self.dxa_init delta_xp[0, :] = self.xp_init - self.xp_target delta_xa[0, :] = self.xa_init - self.xa_target # Forward simulation step for ii in range(self.n_steps - 1): xp[ii + 1, :], dxp[ii + 1, :], xa[ii + 1, :], dxa[ii + 1, :] = self.forward_sim_step(xp[ii, :], dxp[ii, :], xa[ii, :], dxa[ii, :], ddxa[ii, :]) delta_xp[ii + 1, :] = xp[ii + 1, :] - self.xp_target delta_xa[ii + 1, :] = xa[ii + 1, :] - self.xa_target return xp, xa, dxp, dxa, delta_xp, delta_xa # Function: Objective Function # Objective function to be solved using least squares optimizer def objective(self, coeffs): # Unwrap coeffs to polynomials u = self.u_eval(coeffs) _, _, _, _, delta_xp, delta_xa = self.forward_sim(u) # Calculate cost vector using weights and input cost_vector = list() cost_vector.append(self.w_xp * delta_xp.flatten()) cost_vector.append(delta_xa.flatten()) cost_vector.append(self.w_control * u.flatten()) cost_vector = np.concatenate((cost_vector), axis=None) # Prints out "loading bar" to show optimization progress self.iteration += 1 print("|"*self.iteration, end='\r') return cost_vector # Function: Get Commands # Double integrates control input to calculate position commands, then discretizes position command array into # step commands of length t_cmd. Used for practical real-life implementation def get_commands(self, ddu): # Double integration du = np.zeros((self.n_steps, self.n_a)) u = np.zeros((self.n_steps-1, self.n_a)) # remember to add xa_init to u u[0, :] = xa_init[:] for ii in range(self.n_a): for kk in range(1, self.n_steps): du[kk, ii] = du[kk-1, ii] + ddu[kk-1, ii] * self.dt for jj in range(1, self.n_steps-1): u[jj, ii] = u[jj-1, ii] + du[jj-1, ii] * self.dt # Split u into discrete command steps for mm in range(self.n_a): for nn in range(0, self.n_steps, int(round(self.t_cmd/self.dt))): u[nn:nn+int(round(self.t_cmd/self.dt)), mm] = u[nn, mm] return u, du # Function: Get Input # Uses the least squares optimizer to calculate the control acceleration input def get_input(self): # Initialize initial coefficients coeffs_init = np.zeros((self.n_a * self.n_coeffs)) # Calculating passive target state from solving the statices equation at xa_target xp_target0 = np.zeros((self.n_p)) self.xp_target = np.asarray(fmin(self.get_xp_target, xp_target0, xtol=0.000001, disp=False)) # Solve using least squares optimizer start = time.time() self.iteration = 0 print("Optimizing trajectory:") sol = least_squares(self.objective, coeffs_init, method='lm', jac='2-point', verbose=2, max_nfev=10) coeffs = sol.x ddu = self.u_eval(coeffs) ddu = ddu.reshape((self.n_steps, self.n_a)) print("Elapsed time: " + str(time.time() - start)) return ddu # Function: Plot Results # Plots the input acceleration, associated position commands, etc def plot_results(self, u_command, ddu, xp, xa, dxp, dxa, delta_xp, delta_xa): # Customizing Matplotlib: mpl.rcParams['font.size'] = 18 mpl.rcParams['lines.linewidth'] = 3 mpl.rcParams['axes.grid'] = True # Visualize fig, ax = plt.subplots(4, sharex=True, figsize=(16, 9)) fig.align_ylabels() ax[0].plot(self.t, xp[:, 0], label='z') ax[0].plot(self.t, xp[:, 1], label='pitch') ax[0].plot(self.t, xp[:, 2], label='roll') ax[0].legend() # ax[1].plot(t, xa[:, 0], label='motor1') # ax[1].plot(t, xa[:, 1], label='motor2') # ax[1].plot(t, xa[:, 2], label='motor3') # ax[1].plot(t, xa[:, 3], label='motor4') # ax[1].legend() ax[1].plot(self.t, delta_xa[:, 0], label='error_motor1') ax[1].plot(self.t, delta_xa[:, 1], label='error_motor2') ax[1].plot(self.t, delta_xa[:, 2], label='error_motor3') ax[1].plot(self.t, delta_xa[:, 3], label='error_motor4') ax[1].legend() ax[2].plot(self.t, ddu[:, 0], label='ddx_a_1') ax[2].plot(self.t, ddu[:, 1], label='ddx_a_2') ax[2].plot(self.t, ddu[:, 2], label='ddx_a_3') ax[2].plot(self.t, ddu[:, 3], label='ddx_a_4') ax[2].legend() ax[3].plot(self.t[:-1], u_command[:, 0], label='u_cmd_1') ax[3].plot(self.t[:-1], u_command[:, 1], label='u_cmd_2') ax[3].plot(self.t[:-1], u_command[:, 2], label='u_cmd_3') ax[3].plot(self.t[:-1], u_command[:, 3], label='u_cmd_4') ax[3].legend() ax[3].set_xlabel('Time [s]') plt.show() # Function: Main # Uses a least-squares optimizer to generate a trajectory path to minimize base vibrations, joint acceleration, # settling time, and overshoot. if __name__ == "__main__": # Intializations suspension and robot from SuspensionMatrices import Suspension_8legs sus = Suspension_8legs() # 3DOF model of the suspension, use with GetStiffnessMatrix and GetDampingMatrix world = klampt.WorldModel() res = world.readFile("./robot_sim.xml") robot = world.robot(0) # Initial states # Note: In realtime implementation, these are updated to current state whenever the trajectory planner is calleds # The state is [z pitch roll 4DOF] xa_init = np.array([0.0] * robot.numDrivers()) dxa_init = np.zeros((robot.numDrivers())) xp_init = np.zeros((3)) # xp_target[:] dxp_init = np.zeros((3)) # Initialize planner object and set parameters planner = TrajectoryPlanner3D(robot, sus) # Set initial and target positions planner.set_initial(xa_init, dxa_init, xp_init, dxp_init) """ INDIVIDUAL ACTIVE STATE TARGET Calculates position commands for single batch of target active states. """ # # For one single active state target # # Target states # xa_target = np.array([1.00, -np.pi/2, 1.00, np.pi/4]) # planner.set_target(xa_target) # # # Get input and double integrate to get position commands # ddu = planner.get_input() # u_command, du_command = planner.get_commands(ddu) # # # Plot results # xp, xa, dxp, dxa, delta_xp, delta_xa = planner.forward_sim(ddu) # planner.plot_results(u_command, ddu, xp, xa, dxp, dxa, delta_xp, delta_xa) """ MULTIPLE ACTIVE STATE TARGETS Calculates position commands for multiple arm orientations, then adds position commands to a .csv file for Gazebo simulation. Set of individual target active states for target orientations (i.e. orientation 1 is -2.0944, -1.0472, 0.5236) Then, provide a list of these desired orientations, q_set. You don't necessarily have to make q_d this way (with the nested for loops, etc), just as long as q_set is a list of orientations you want. """ q1_d = [-2.0944, -1.0472, 1.0472, 2.0944] # Motor 1 q2_d = [-1.0472, -2.0944, -3.1415] # Motor 2 q3_d = [0.5236, 1.000, 2.094] # Motor 3 planner.set_objective_weights(3, 0.01) # acceleration, control planner.set_time_parameters(1.0, 0.005, 10, 5) # T, dt, mult_cmd, n_coeffs q_set = [] for ii in range(len(q1_d)): for jj in range(len(q2_d)): for kk in range(len(q3_d)): q_set.append([q1_d[ii], q2_d[jj], q3_d[kk], 0]) """ DO NOT EDIT BELOW THIS LINE """ # Calculate position commands and add to .csv file to be read by Gazebo simulation file run_simulation2.py with open('./planned_trajectory.csv', 'w') as myfile: csvwriter = csv.writer(myfile, delimiter=',') csvwriter.writerow(planner.get_time_parameters()) sim_count = 1 num_simulations = len(q_set) for ii in range(len(q_set)): print("Running Simulation", sim_count, "of", num_simulations) xa_target = np.array(q_set[ii]) planner.set_target(xa_target) ddu = planner.get_input() u_command, du_command = planner.get_commands(ddu) # UNCOMMENT LINES BELOW to show plot of position commands, acceleration profile, etc # xp, xa, dxp, dxa, delta_xp, delta_xa = planner.forward_sim(ddu) # planner.plot_results(u_command, ddu, xp, xa, dxp, dxa, delta_xp, delta_xa) csvwriter.writerow(q_set[ii]) for k in range(0, np.shape(u_command)[1]): csvwriter.writerow(u_command[:, k].tolist()) sim_count += 1
[ "numpy.shape", "scipy.optimize.least_squares", "klampt.WorldModel", "numpy.linspace", "SuspensionMatrices.Suspension_8legs", "matplotlib.pyplot.subplots", "scipy.signal.butter", "numpy.stack", "scipy.optimize.fmin", "matplotlib.pyplot.show", "csv.writer", "numpy.dot", "numpy.delete", "nump...
[((14518, 14536), 'SuspensionMatrices.Suspension_8legs', 'Suspension_8legs', ([], {}), '()\n', (14534, 14536), False, 'from SuspensionMatrices import Suspension_8legs\n'), ((14631, 14650), 'klampt.WorldModel', 'klampt.WorldModel', ([], {}), '()\n', (14648, 14650), False, 'import klampt\n'), ((15012, 15023), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (15020, 15023), True, 'import numpy as np\n'), ((15056, 15067), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (15064, 15067), True, 'import numpy as np\n'), ((1719, 1755), 'numpy.linspace', 'np.linspace', (['(0)', 'self.T', 'self.n_steps'], {}), '(0, self.T, self.n_steps)\n', (1730, 1755), True, 'import numpy as np\n'), ((3252, 3283), 'numpy.linspace', 'np.linspace', (['(0)', 'T', 'self.n_steps'], {}), '(0, T, self.n_steps)\n', (3263, 3283), True, 'import numpy as np\n'), ((4800, 4828), 'numpy.array', 'np.array', (['[G[2], G[4], G[5]]'], {}), '([G[2], G[4], G[5]])\n', (4808, 4828), True, 'import numpy as np\n'), ((4877, 4889), 'numpy.dot', 'np.dot', (['v', 'v'], {}), '(v, v)\n', (4883, 4889), True, 'import numpy as np\n'), ((5562, 5614), 'scipy.signal.butter', 'signal.butter', (['self.butter_order', 'self.butter_cutoff'], {}), '(self.butter_order, self.butter_cutoff)\n', (5575, 5614), False, 'from scipy import signal\n'), ((6088, 6107), 'numpy.stack', 'np.stack', (['u'], {'axis': '(1)'}), '(u, axis=1)\n', (6096, 6107), True, 'import numpy as np\n'), ((6457, 6524), 'numpy.concatenate', 'np.concatenate', (['([0.0, 0.0], xp[0], 0, xp[1], xp[2], xa)'], {'axis': 'None'}), '(([0.0, 0.0], xp[0], 0, xp[1], xp[2], xa), axis=None)\n', (6471, 6524), True, 'import numpy as np\n'), ((6542, 6613), 'numpy.concatenate', 'np.concatenate', (['([0.0, 0.0], dxp[0], 0, dxp[1], dxp[2], dxa)'], {'axis': 'None'}), '(([0.0, 0.0], dxp[0], 0, dxp[1], dxp[2], dxa), axis=None)\n', (6556, 6613), True, 'import numpy as np\n'), ((6843, 6873), 'numpy.delete', 'np.delete', (['H_mat', '[0, 1, 3]', '(0)'], {}), '(H_mat, [0, 1, 3], 0)\n', (6852, 6873), True, 'import numpy as np\n'), ((6890, 6920), 'numpy.delete', 'np.delete', (['H_mat', '[0, 1, 3]', '(1)'], {}), '(H_mat, [0, 1, 3], 1)\n', (6899, 6920), True, 'import numpy as np\n'), ((6998, 7013), 'numpy.array', 'np.array', (['g_vec'], {}), '(g_vec)\n', (7006, 7013), True, 'import numpy as np\n'), ((7030, 7057), 'numpy.delete', 'np.delete', (['g_vec', '[0, 1, 3]'], {}), '(g_vec, [0, 1, 3])\n', (7039, 7057), True, 'import numpy as np\n'), ((7121, 7136), 'numpy.array', 'np.array', (['c_vec'], {}), '(c_vec)\n', (7129, 7136), True, 'import numpy as np\n'), ((7153, 7180), 'numpy.delete', 'np.delete', (['c_vec', '[0, 1, 3]'], {}), '(c_vec, [0, 1, 3])\n', (7162, 7180), True, 'import numpy as np\n'), ((8046, 8087), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['H11_mat', 'rhs'], {'rcond': 'None'}), '(H11_mat, rhs, rcond=None)\n', (8061, 8087), True, 'import numpy as np\n'), ((8645, 8679), 'numpy.zeros', 'np.zeros', (['(self.n_steps, self.n_p)'], {}), '((self.n_steps, self.n_p))\n', (8653, 8679), True, 'import numpy as np\n'), ((8693, 8727), 'numpy.zeros', 'np.zeros', (['(self.n_steps, self.n_a)'], {}), '((self.n_steps, self.n_a))\n', (8701, 8727), True, 'import numpy as np\n'), ((8742, 8776), 'numpy.zeros', 'np.zeros', (['(self.n_steps, self.n_p)'], {}), '((self.n_steps, self.n_p))\n', (8750, 8776), True, 'import numpy as np\n'), ((8791, 8825), 'numpy.zeros', 'np.zeros', (['(self.n_steps, self.n_a)'], {}), '((self.n_steps, self.n_a))\n', (8799, 8825), True, 'import numpy as np\n'), ((8897, 8931), 'numpy.zeros', 'np.zeros', (['(self.n_steps, self.n_p)'], {}), '((self.n_steps, self.n_p))\n', (8905, 8931), True, 'import numpy as np\n'), ((8951, 8985), 'numpy.zeros', 'np.zeros', (['(self.n_steps, self.n_a)'], {}), '((self.n_steps, self.n_a))\n', (8959, 8985), True, 'import numpy as np\n'), ((10420, 10458), 'numpy.concatenate', 'np.concatenate', (['cost_vector'], {'axis': 'None'}), '(cost_vector, axis=None)\n', (10434, 10458), True, 'import numpy as np\n'), ((10930, 10964), 'numpy.zeros', 'np.zeros', (['(self.n_steps, self.n_a)'], {}), '((self.n_steps, self.n_a))\n', (10938, 10964), True, 'import numpy as np\n'), ((10977, 11015), 'numpy.zeros', 'np.zeros', (['(self.n_steps - 1, self.n_a)'], {}), '((self.n_steps - 1, self.n_a))\n', (10985, 11015), True, 'import numpy as np\n'), ((11791, 11825), 'numpy.zeros', 'np.zeros', (['(self.n_a * self.n_coeffs)'], {}), '(self.n_a * self.n_coeffs)\n', (11799, 11825), True, 'import numpy as np\n'), ((11941, 11959), 'numpy.zeros', 'np.zeros', (['self.n_p'], {}), '(self.n_p)\n', (11949, 11959), True, 'import numpy as np\n'), ((12126, 12137), 'time.time', 'time.time', ([], {}), '()\n', (12135, 12137), False, 'import time\n'), ((12219, 12317), 'scipy.optimize.least_squares', 'least_squares', (['self.objective', 'coeffs_init'], {'method': '"""lm"""', 'jac': '"""2-point"""', 'verbose': '(2)', 'max_nfev': '(10)'}), "(self.objective, coeffs_init, method='lm', jac='2-point',\n verbose=2, max_nfev=10)\n", (12232, 12317), False, 'from scipy.optimize import least_squares, Bounds, fmin\n'), ((12882, 12927), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)'], {'sharex': '(True)', 'figsize': '(16, 9)'}), '(4, sharex=True, figsize=(16, 9))\n', (12894, 12927), True, 'import matplotlib.pyplot as plt\n'), ((14213, 14223), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14221, 14223), True, 'import matplotlib.pyplot as plt\n'), ((17180, 17213), 'csv.writer', 'csv.writer', (['myfile'], {'delimiter': '""","""'}), "(myfile, delimiter=',')\n", (17190, 17213), False, 'import csv\n'), ((4847, 4861), 'numpy.dot', 'np.dot', (['K', 'x_p'], {}), '(K, x_p)\n', (4853, 4861), True, 'import numpy as np\n'), ((6005, 6045), 'scipy.signal.filtfilt', 'signal.filtfilt', (['b', 'a', 'axis_u'], {'padlen': '(20)'}), '(b, a, axis_u, padlen=20)\n', (6020, 6045), False, 'from scipy import signal\n'), ((11998, 12058), 'scipy.optimize.fmin', 'fmin', (['self.get_xp_target', 'xp_target0'], {'xtol': '(1e-06)', 'disp': '(False)'}), '(self.get_xp_target, xp_target0, xtol=1e-06, disp=False)\n', (12002, 12058), False, 'from scipy.optimize import least_squares, Bounds, fmin\n'), ((17467, 17486), 'numpy.array', 'np.array', (['q_set[ii]'], {}), '(q_set[ii])\n', (17475, 17486), True, 'import numpy as np\n'), ((2545, 2562), 'numpy.shape', 'np.shape', (['xp_init'], {}), '(xp_init)\n', (2553, 2562), True, 'import numpy as np\n'), ((2590, 2607), 'numpy.shape', 'np.shape', (['xa_init'], {}), '(xa_init)\n', (2598, 2607), True, 'import numpy as np\n'), ((7844, 7868), 'numpy.matmul', 'np.matmul', (['H12_mat', 'ddxa'], {}), '(H12_mat, ddxa)\n', (7853, 7868), True, 'import numpy as np\n'), ((17967, 17986), 'numpy.shape', 'np.shape', (['u_command'], {}), '(u_command)\n', (17975, 17986), True, 'import numpy as np\n'), ((7811, 7832), 'numpy.matmul', 'np.matmul', (['Ks_mat', 'xp'], {}), '(Ks_mat, xp)\n', (7820, 7832), True, 'import numpy as np\n'), ((12460, 12471), 'time.time', 'time.time', ([], {}), '()\n', (12469, 12471), False, 'import time\n'), ((7786, 7808), 'numpy.matmul', 'np.matmul', (['Kb_mat', 'dxp'], {}), '(Kb_mat, dxp)\n', (7795, 7808), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Fri Sep 20 11:24:21 2019 @author: bwc """ # standard imports import numpy as np import matplotlib.pyplot as plt # custom imports import apt_fileio import plotting_stuff import peak_param_determination as ppd from histogram_functions import bin_dat import scipy.interpolate import image_registration.register_images import sel_align_m2q_log_xcorr import scipy.interpolate plt.close('all') nuv_fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\R45_data\R45_04472-v03.epos" #euv_fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\Final EPOS for APL Mat Paper\R20_07263-v02.epos" euv_fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\Final EPOS for APL Mat Paper\R20_07080-v01.epos" #euv_fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\Final EPOS for APL Mat Paper\R20_07086-v01.epos" #euv_fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\Final EPOS for APL Mat Paper\R20_07276-v03.epos" #epos = apt_fileio.read_epos_numpy(nuv_fn) #plotting_stuff.plot_TOF_vs_time(epos['m2q'],epos,1,clearFigure=True,user_ylim=[0,150]) epos = apt_fileio.read_epos_numpy(euv_fn) #epos = apt_fileio.read_epos_numpy(nuv_fn) plotting_stuff.plot_TOF_vs_time(epos['m2q'],epos,1,clearFigure=True,user_ylim=[0,80]) cts_per_slice=2**10 #m2q_roi = [0.9,190] m2q_roi = [0.8,80] import time t_start = time.time() pointwise_scales,piecewise_scales = sel_align_m2q_log_xcorr.get_all_scale_coeffs( epos['m2q'], m2q_roi=m2q_roi, cts_per_slice=cts_per_slice, max_scale=1.15) t_end = time.time() print('Total Time = ',t_end-t_start) # Compute corrected data m2q_corr = epos['m2q']/pointwise_scales wall_time = np.cumsum(epos['pslep'])/10000.0 wall_time = np.cumsum(epos['pslep'])/500000.0 dt = ppd.moving_average(np.diff(wall_time),n=512) ra = 1/dt pks = [14,16,32.2,44.3,60.3] #pks = [14,16,32,44,60] wid = 1 mask = None for pk in pks: if mask is None: mask = np.abs(m2q_corr-pk)<=wid/2 else: mask = mask | (np.abs(m2q_corr-pk)<=wid/2) fig = plt.figure(num=111) ax = fig.gca() ax.plot(wall_time,m2q_corr,'.', markersize=.1, marker=',', markeredgecolor='#1f77b4aa') ax.set(xlabel='event index', ylabel='ToF (ns)', ylim=[0,80]) ax.grid() fig.tight_layout() plt.pause(0.1) hist, edges = np.histogram(wall_time[mask],bins=piecewise_scales.size,range=(0,np.max(wall_time))) centers = (edges[1:]+edges[0:-1])/2 fig = plt.figure(num=11111) fig.clear() ax = fig.gca() ax.plot(hist,piecewise_scales,'.',markersize=2) #ax.set(xlabel='event index', ylabel='ToF (ns)', ylim=[0,80]) ax.grid() fig.tight_layout() plt.pause(0.1) fig = plt.figure(num=1111) fig.clear() ax = fig.gca() ax.plot(centers,hist) #ax.set(xlabel='event index', ylabel='ToF (ns)', ylim=[0,80]) ax2 = ax.twinx() ax2.plot(wall_time,pointwise_scales,'-', markersize=.1, marker=',', markeredgecolor='#1f77b4aa', color='tab:red') ax2.set(ylabel='sc') ax.grid() fig.tight_layout() plt.pause(0.1) # # #fig = plt.figure(num=1111123) #fig.clear() #ax = fig.gca() # #ax.plot(epos['v_dc'],'.',markersize=2) ##ax.set(xlabel='event index', ylabel='ToF (ns)', ylim=[0,80]) # #ax.grid() # #fig.tight_layout() #plt.pause(0.1) f = scipy.interpolate.interp1d(wall_time,pointwise_scales,fill_value='extrapolate') p_q = f(centers) fig = plt.figure(num=999) fig.clear() ax = fig.gca() ax.plot(p_q,hist,'.') ax.plot(p_q,hist,'.') ax.grid() fig.tight_layout() plt.pause(0.1) fig = plt.figure(num=999) fig.clear() ax = fig.gca() ax.plot(wall_time,(pointwise_scales-1)*20+1,'--',label='sc') ax.plot(centers,hist/500,'-',label='ct rate') ax.legend() ax.grid() fig.tight_layout() plt.pause(0.1)
[ "numpy.abs", "matplotlib.pyplot.close", "apt_fileio.read_epos_numpy", "time.time", "numpy.cumsum", "sel_align_m2q_log_xcorr.get_all_scale_coeffs", "matplotlib.pyplot.figure", "numpy.diff", "numpy.max", "matplotlib.pyplot.pause", "plotting_stuff.plot_TOF_vs_time" ]
[((420, 436), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (429, 436), True, 'import matplotlib.pyplot as plt\n'), ((1031, 1065), 'apt_fileio.read_epos_numpy', 'apt_fileio.read_epos_numpy', (['euv_fn'], {}), '(euv_fn)\n', (1057, 1065), False, 'import apt_fileio\n'), ((1109, 1203), 'plotting_stuff.plot_TOF_vs_time', 'plotting_stuff.plot_TOF_vs_time', (["epos['m2q']", 'epos', '(1)'], {'clearFigure': '(True)', 'user_ylim': '[0, 80]'}), "(epos['m2q'], epos, 1, clearFigure=True,\n user_ylim=[0, 80])\n", (1140, 1203), False, 'import plotting_stuff\n'), ((1279, 1290), 'time.time', 'time.time', ([], {}), '()\n', (1288, 1290), False, 'import time\n'), ((1327, 1450), 'sel_align_m2q_log_xcorr.get_all_scale_coeffs', 'sel_align_m2q_log_xcorr.get_all_scale_coeffs', (["epos['m2q']"], {'m2q_roi': 'm2q_roi', 'cts_per_slice': 'cts_per_slice', 'max_scale': '(1.15)'}), "(epos['m2q'], m2q_roi=m2q_roi,\n cts_per_slice=cts_per_slice, max_scale=1.15)\n", (1371, 1450), False, 'import sel_align_m2q_log_xcorr\n'), ((1683, 1694), 'time.time', 'time.time', ([], {}), '()\n', (1692, 1694), False, 'import time\n'), ((2176, 2195), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(111)'}), '(num=111)\n', (2186, 2195), True, 'import matplotlib.pyplot as plt\n'), ((2417, 2431), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (2426, 2431), True, 'import matplotlib.pyplot as plt\n'), ((2584, 2605), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(11111)'}), '(num=11111)\n', (2594, 2605), True, 'import matplotlib.pyplot as plt\n'), ((2775, 2789), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (2784, 2789), True, 'import matplotlib.pyplot as plt\n'), ((2802, 2822), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(1111)'}), '(num=1111)\n', (2812, 2822), True, 'import matplotlib.pyplot as plt\n'), ((3152, 3166), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (3161, 3166), True, 'import matplotlib.pyplot as plt\n'), ((3500, 3519), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(999)'}), '(num=999)\n', (3510, 3519), True, 'import matplotlib.pyplot as plt\n'), ((3624, 3638), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (3633, 3638), True, 'import matplotlib.pyplot as plt\n'), ((3652, 3671), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(999)'}), '(num=999)\n', (3662, 3671), True, 'import matplotlib.pyplot as plt\n'), ((3851, 3865), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (3860, 3865), True, 'import matplotlib.pyplot as plt\n'), ((1811, 1835), 'numpy.cumsum', 'np.cumsum', (["epos['pslep']"], {}), "(epos['pslep'])\n", (1820, 1835), True, 'import numpy as np\n'), ((1856, 1880), 'numpy.cumsum', 'np.cumsum', (["epos['pslep']"], {}), "(epos['pslep'])\n", (1865, 1880), True, 'import numpy as np\n'), ((1915, 1933), 'numpy.diff', 'np.diff', (['wall_time'], {}), '(wall_time)\n', (1922, 1933), True, 'import numpy as np\n'), ((2081, 2102), 'numpy.abs', 'np.abs', (['(m2q_corr - pk)'], {}), '(m2q_corr - pk)\n', (2087, 2102), True, 'import numpy as np\n'), ((2516, 2533), 'numpy.max', 'np.max', (['wall_time'], {}), '(wall_time)\n', (2522, 2533), True, 'import numpy as np\n'), ((2141, 2162), 'numpy.abs', 'np.abs', (['(m2q_corr - pk)'], {}), '(m2q_corr - pk)\n', (2147, 2162), True, 'import numpy as np\n')]
""" Module: System This module shall be used to implement subclasses of system. It wraps all information needed and generated by a simulation. """ import os import warnings import numpy as np import pandas as pd import scipy.constants as const from tqdm import tqdm pd.options.mode.use_inf_as_na = True # Typing from ensembler.util.basic_class import _baseClass from ensembler.util.ensemblerTypes import samplerCls, conditionCls, potentialCls, Number, Union, Iterable, NoReturn, \ List from ensembler.util import dataStructure as data from ensembler.samplers.newtonian import newtonianSampler from ensembler.samplers.stochastic import langevinIntegrator, metropolisMonteCarloIntegrator from ensembler.potentials.OneD import metadynamicsPotential as metadynamicsPotential1D, harmonicOscillatorPotential from ensembler.potentials.TwoD import metadynamicsPotential as metadynamicsPotential2D class system(_baseClass): """ The system class is managing the simulation approaches and all system data as well as the simulation results. """ # static attributes name = "system" state = data.basicState verbose: bool # general attributes nParticles: int nDimensions: int nStates: int """ Attributes """ @property def potential(self) -> potentialCls: """ The potential energy function class can be explored in a simulation Returns ------- _potentialCls systems potential energy class """ return self._potential @potential.setter def potential(self, potential: potentialCls): # if(issubclass(potential.__class__, _potentialCls)): self._potential = potential # else: # raise ValueError("Potential needs to be a subclass of potential") @property def sampler(self) -> samplerCls: """ The sampler method is used by the system to explore the potential energy function. Returns ------- _samplerCls the sampler method that can be used to explore the potential energy function. """ return self._integrator @sampler.setter def sampler(self, integrator: samplerCls): self._integrator = integrator @property def conditions(self) -> List[conditionCls]: """ conditions list contains the system conditions. These conditions are applied during the sampling of the potential energy function to add additional constraints. Returns ------- List[_conditionCls] the list of conditions coupled to the system. """ return self._conditions @conditions.setter def conditions(self, conditions: List[conditionCls]): if (isinstance(conditions, List)): self._conditions = conditions else: raise ValueError("Conditions needs to be a List of objs, that are a subclass of _conditionCls") @property def total_system_energy(self) -> Number: """ the total energy of the current system Returns ------- Number total energy of the current system """ return self._currentTotE @property def total_potential_energy(self) -> Number: """ the total potential energy of the current system Returns ------- Number total potential energy of the current system """ return self._currentTotPot @property def total_kinetic_energy(self) -> Number: """ the total kinetic energy of the current system Returns ------- Number total kinetic energy of the current system """ return self._currentTotKin @property def current_state(self) -> state: return self._currentState def set_current_state(self, current_position: Union[Number, Iterable[Number]], current_velocities: Union[Number, Iterable[Number]] = 0, current_force: Union[Number, Iterable[Number]] = 0, current_temperature: Number = 298): """ set_current_state set the current State of the system. Parameters ---------- current_position: Union[Number, Iterable[Number]] new current system position current_velocities: Union[Number, Iterable[Number]], optional new current system velocity. (default: 0) current_force: Union[Number, Iterable[Number]], optional new current system force. (default: 0) current_temperature: Union[Number, Iterable[Number]], optional new current system temperature. (default: 298) """ self._currentPosition = current_position self._currentForce = current_force self._currentVelocities = current_velocities self._currentTemperature = current_temperature self.currentState = self.state(self._currentPosition, self._currentTemperature, np.nan, np.nan, np.nan, np.nan, np.nan) self._update_energies() self.update_current_state() @property def trajectory(self) -> pd.DataFrame: return pd.DataFrame(list(map(lambda x: x._asdict(), self._trajectory)), columns=list(self.state.__dict__["_fields"])) @property def position(self) -> Union[Number, Iterable[Number]]: return self._currentPosition @position.setter def position(self, position: Union[Number, Iterable[Number]]): self._currentPosition = position if (len(self.trajectory) == 0): self.initial_position = self._currentPosition self._update_energies() self.update_current_state() def set_position(self, position: Union[Number, Iterable[Number]]): self.position = position @property def velocity(self) -> Union[Number, Iterable[Number]]: """ velocity The current velocity of the system Returns ------- Union[Number, Iterable[Number]] """ return self._currentVelocities @velocity.setter def velocity(self, velocity: Union[Number, Iterable[Number]]): self._currentVelocities = velocity self._update_energies() self.update_current_state() def set_velocities(self, velocities): self.velocities = velocities @property def temperature(self) -> Number: """ The set temperature of the system Returns ------- Number set temperature """ return self._temperature @temperature.setter def temperature(self, temperature: Number): self._temperature = temperature self._currentTemperature = temperature self._update_energies() def set_temperature(self, temperature: Number): """ set Temperature set the systems current temperature. Parameters ---------- temperature """ self.temperature = temperature @property def mass(self): return self._mass @mass.setter def mass(self, mass: float): self._mass = mass def __init__(self, potential: potentialCls=harmonicOscillatorPotential(), sampler: samplerCls=metropolisMonteCarloIntegrator(), conditions: Iterable[conditionCls] = None, temperature: Number = 298.0, start_position: (Iterable[Number] or Number) = None, mass: Number = 1, verbose: bool = True) -> NoReturn: """ The system class is wrapping all components needed for a simulation. It can be used as the control unit for executing a simulation (simulate) and also to manage the generated data or input data. Parameters ---------- potential : _potentialCls gives the potential function to be explored/sampled sampler : _samplerCls gives the method of choice to sample/explore the potential function conditions : Iterable[_conditionCls], optional apply the given conditions to the systems in a preset (tau) step iteration temperature : float, optional temperature of the system start_position : float, optional starting position of the system during the simulation mass : float, optional mass of the single particle verbose : bool, optional I can tell you a long iterative story... """ ################################ # Declare Attributes ################################# ##Physical parameters self.nParticles = 1 # FUTURE: adapt it to be multiple particles self._mass = mass # for one particle systems!!!! self._temperature = temperature # Output self._currentState = self.state(**{key: np.nan for key in self.state.__dict__["_fields"]}) self._trajectory =[] # tmpvars - private: self._currentTotE: (Number) = np.nan self._currentTotPot: (Number) = np.nan self._currentTotKin: (Number) = np.nan self._currentPosition: (Number or Iterable[Number]) = np.nan self._currentVelocities: (Number or Iterable[Number]) = np.nan self._currentForce: (Number or Iterable[Number]) = np.nan self._currentTemperature: (Number or Iterable[Number]) = np.nan # BUILD System ## Fundamental Parts: self._potential = potential self._integrator = sampler if(conditions is None): self._conditions = [] else: self._conditions = conditions ## set dim if (potential.constants[potential.nDimensions] > 0): self.nDimensions = potential.constants[potential.nDimensions] else: raise IOError( "Could not estimate the disered Dimensionality as potential dim was <1 and no initial position was given.") ###is the potential a state dependent one? - needed for initial pos. if (hasattr(potential, "nStates")): self.nStates = potential.constants[potential.nStates] else: self.nstates = 1 # PREPARE THE SYSTEM # Only init velocities, if the samplers uses them if (issubclass(sampler.__class__, (newtonianSampler, langevinIntegrator))): init_velocity = True else: init_velocity = False self.initialise(withdraw_Traj=True, init_position=True, init_velocity=init_velocity, set_initial_position=start_position) ##check if system should be coupled to conditions: # update for metadynamics simulation - local elevation bias is like a condition/potential hybrid. if (isinstance(self.potential, metadynamicsPotential1D) or isinstance(self.potential, metadynamicsPotential2D)): self._conditions.append(self.potential) for condition in self._conditions: if (not hasattr(condition, "system")): condition.couple_system(self) else: # warnings.warn("Decoupling system and coupling it again!") condition.couple_system(self) if (not hasattr(condition, "dt") and hasattr(self.sampler, "dt")): condition.dt = self.sampler.dt else: condition.dt = 1 self.verbose = verbose """ Initialisation """ def initialise(self, withdraw_Traj: bool = True, init_position: bool = True, init_velocity: bool = True, set_initial_position: Union[Number, Iterable[Number]] = None) -> NoReturn: """ initialise initialises the system, i.e. can set an initial position, initial velocities and initialize the forces. Parameters ---------- withdraw_Traj: bool, optional reset the simulation trajectory? init_position: bool, optional reinitialize the start_position - currentPosition init_velocity: bool, optional reinitialize the start_velocity - currentVelocity set_initial_position: Union[Number, Iterable[Number]], optional set the start_position to the given one. Returns ------- NoReturn """ if (withdraw_Traj): self.clear_trajectory() if (init_position): self._init_position(initial_position=set_initial_position) # Try to init the force try: self._currentForce = self.potential.force(self.initial_position) # initialise forces! except: warnings.warn("Could not initialize the force of the potential? Check if you need it!") if (init_velocity): self._init_velocities() # set initial Temperature self._currentTemperature = self.temperature # update current state self.step = 0 self.update_system_properties() self.update_current_state() self._trajectory.append(self.current_state) def _init_position(self, initial_position: Union[Number, Iterable[Number]] = None) -> NoReturn: """ _init_position this function initializes the current position of the system. Parameters ---------- initial_position: Union[Number, Iterable[Number]], optional if None, a random position is selected else the given position is used. """ if (isinstance(initial_position, type(None))): self.initial_position = self.random_position() elif ((isinstance(initial_position, Number) and self.nDimensions == 1) or (isinstance(initial_position, Iterable) and all( [isinstance(x, Number) for x in initial_position]) and self.nDimensions == len(initial_position))): self.initial_position = initial_position else: raise Exception("Did not understand the initial position! \n given: " + str( initial_position) + "\n Expected dimensions: " + str(self.nDimensions)) self._currentPosition = self.initial_position self.update_current_state() return self.initial_position def _init_velocities(self) -> NoReturn: """ _init_velocities Initializes the initial velocity randomly. """ if (self.nStates > 1): self._currentVelocities = [[self._gen_rand_vel() for dim in range(self.nDimensions)] for s in range(self.nStates)] if (self.nDimensions > 1) else [self._gen_rand_vel() for state in range(self.nStates)] else: self._currentVelocities = [self._gen_rand_vel() for dim in range(self.nDimensions)] if ( self.nDimensions > 1) else self._gen_rand_vel() self.veltemp = self.mass / const.gas_constant / 1000.0 * np.linalg.norm(self._currentVelocities) ** 2 # t self.update_current_state() return self._currentVelocities def _gen_rand_vel(self) -> Number: """ _gen_rand_vel get a random velocity according to the temperature and mass. Returns ------- Number, Iterable[Number] a randomly selected velocity """ return np.sqrt(const.gas_constant / 1000.0 * self.temperature / self.mass) * np.random.normal() def random_position(self) -> Union[Number, Iterable[Number]]: """ randomPos returns a randomly selected position for the system. Returns ------- Union[Number, Iterable[Number]] a random position """ random_pos = np.squeeze(np.array(np.subtract(np.multiply(np.random.rand(self.nDimensions), 20), 10))) if (len(random_pos.shape) == 0): return np.float(random_pos) else: return random_pos """ Update """ def calculate_total_kinetic_energy(self) -> Union[Iterable[Number], Number]: """ totKin returns the total kinetic energy of the system. Returns ------- Union[Iterable[Number], Number, np.nan] total kinetic energy. """ if (isinstance(self._currentVelocities, Number) or (isinstance(self._currentVelocities, Iterable) and all( [isinstance(x, Number) and not np.isnan(x) for x in self._currentVelocities]))): return np.sum(0.5 * self.mass * np.square(np.linalg.norm(self._currentVelocities))) else: return np.nan def calculate_total_potential_energy(self) -> Union[Iterable[Number], Number]: """ totPot return the total potential energy Returns ------- Union[Iterable[Number], Number] summed up total potential energies """ return self.potential.ene(self._currentPosition) def update_system_properties(self) -> NoReturn: """ updateSystemProperties updates the energies and temperature of the system Returns ------- NoReturn """ self._update_energies() self._update_temperature() def update_current_state(self) -> NoReturn: """ updateCurrentState update current state from the _current vars. Returns ------- NoReturn """ self._currentState = self.state(self._currentPosition, self._currentTemperature, self._currentTotE, self._currentTotPot, self._currentTotKin, self._currentForce, self._currentVelocities) def _update_temperature(self) -> NoReturn: """ this looks like a thermostat like thing! not implemented!@ TODO calc temperature from velocity Returns ------- NoReturn """ self._currentTemperature = self.temperature def _update_energies(self) -> NoReturn: """ _updateEne update all total energy terms. Returns ------- NoReturn """ self._currentTotPot = self.calculate_total_potential_energy() self._currentTotKin = self.calculate_total_kinetic_energy() self._currentTotE = self._currentTotPot if (np.isnan(self._currentTotKin)) else np.add(self._currentTotKin, self._currentTotPot) def _update_current_vars_from_current_state(self): """ _update_current_vars_from_current_state update the _current Vars from the currentState Returns ------- NoReturn """ self._currentPosition = self.current_state.position self._currentTemperature = self.current_state.temperature self._currentTotE = self.current_state.total_system_energy self._currentTotPot = self.current_state.total_potential_energy self._currentTotKin = self.state.total_kinetic_energy self._currentForce = self.current_state.dhdpos self._currentVelocities = self.current_state.velocity def _update_state_from_traj(self) -> NoReturn: """ _update_state_from_traj replaces the current state and the currentstate vars by the last trajectory state. Returns ------- NoReturn """ self.currentState = self.state(**self.trajectory.iloc[-1].to_dict()) self._update_current_vars_from_current_state() return """ Functionality """ def simulate(self, steps: int, withdraw_traj: bool = False, save_every_state: int = 1, init_system: bool = False, verbosity: bool = True, _progress_bar_prefix: str = "Simulation: ") -> state: """ this function executes the simulation, by exploring the potential energy function with the sampling method for the given n steps. Parameters ---------- steps: int number of integration steps init_system: bool, optional initialize the system. (default: False) withdraw_traj: bool, optional reset the current simulation trajectory. (default: False) save_every_state: int, optional save every n step. (and leave out the rest) (default: 1 - each step) verbosity: bool, optional change the verbosity of the simulation. (default: True) _progress_bar_prefix: str, optional prefix of tqdm progress bar. (default: "Simulation") Returns ------- state returns the last current state """ if (init_system): self._init_position() self._init_velocities() if (withdraw_traj): self._trajectory = [] self._trajectory.append(self.current_state) self.update_current_state() self.update_system_properties() # progressBar or no ProgressBar if (verbosity): iteration_queue = tqdm(range(steps), desc=_progress_bar_prefix + " Simulation: ", mininterval=1.0, leave=verbosity) else: iteration_queue = range(steps) # Simulation loop for self.step in iteration_queue: # Do one simulation Step. self.propagate() # Apply Restraints, Constraints ... self.apply_conditions() # Calc new Energy&and other system properties self.update_system_properties() # Set new State self.update_current_state() if (self.step % save_every_state == 0 and self.step != steps - 1): self._trajectory.append(self.current_state) self._trajectory.append(self.current_state) return self.current_state def propagate(self) -> ( Union[Iterable[Number], Number], Union[Iterable[Number], Number], Union[Iterable[Number], Number]): """ propagate Do a single exploration step. Not stored in the trajectory and no energies returned or updated. Returns ------- (Union[Iterable[Number], Number], Union[Iterable[Number], Number], Union[Iterable[Number], Number]) returns the new current position, the new current velocities and the new current forces """ self._currentPosition, self._currentVelocities, self._currentForce = self.sampler.step(self) return self._currentPosition, self._currentVelocities, self._currentForce def apply_conditions(self) -> NoReturn: """ applyConditions this function applies the coupled conditions to the current state of system. Returns ------- NoReturn """ for condition in self._conditions: condition.apply_coupled() def append_state(self, new_position: Union[Iterable[Number], Number], new_velocity: Union[Iterable[Number], Number], new_forces: Union[Iterable[Number], Number]) -> NoReturn: """ append_state appends a new state, based on the given arguments and updates the system to them. Parameters ---------- new_position: Union[Iterable[Number], Number] a new position new_velocity: Union[Iterable[Number], Number] a new velocity new_forces: Union[Iterable[Number], Number] a new Force """ self._currentPosition = new_position self._currentVelocities = new_velocity self._currentForce = new_forces self._update_temperature() self._update_energies() self.update_current_state() self._trajectory.append(self.current_state) def revert_step(self) -> NoReturn: """ revertStep removes the last step which was performed from the trajectory and sets back the system to the one before. Returns ------- NoReturn """ if(len(self._trajectory)>1): self._trajectory.pop() self._currentState = self._trajectory[-1] self._update_current_vars_from_current_state() else: warnings.warn("Could not revert step, as only 1 step is in the trajectory!") def clear_trajectory(self): """ deletes all entries of trajectory and adds current state as first timestep to the trajectory :return: None """ self._trajectory = [] def write_trajectory(self, out_path: str) -> str: """ writeTrajectory Writes the trajectory out to a file. Parameters ---------- out_path: str the string, where the traj csv should be stored. Returns ------- str returns the out_path See Also --------- save """ if (not os.path.exists(os.path.dirname(os.path.abspath(out_path)))): raise Exception("Could not find output folder: " + os.path.dirname(out_path)) traj = self.trajectory traj.to_csv(out_path, header=True) return out_path
[ "os.path.abspath", "os.path.dirname", "numpy.float", "numpy.isnan", "ensembler.samplers.stochastic.metropolisMonteCarloIntegrator", "numpy.linalg.norm", "numpy.random.normal", "ensembler.potentials.OneD.harmonicOscillatorPotential", "numpy.random.rand", "numpy.add", "warnings.warn", "numpy.sqr...
[((7362, 7391), 'ensembler.potentials.OneD.harmonicOscillatorPotential', 'harmonicOscillatorPotential', ([], {}), '()\n', (7389, 7391), False, 'from ensembler.potentials.OneD import metadynamicsPotential as metadynamicsPotential1D, harmonicOscillatorPotential\n'), ((7413, 7445), 'ensembler.samplers.stochastic.metropolisMonteCarloIntegrator', 'metropolisMonteCarloIntegrator', ([], {}), '()\n', (7443, 7445), False, 'from ensembler.samplers.stochastic import langevinIntegrator, metropolisMonteCarloIntegrator\n'), ((15706, 15773), 'numpy.sqrt', 'np.sqrt', (['(const.gas_constant / 1000.0 * self.temperature / self.mass)'], {}), '(const.gas_constant / 1000.0 * self.temperature / self.mass)\n', (15713, 15773), True, 'import numpy as np\n'), ((15776, 15794), 'numpy.random.normal', 'np.random.normal', ([], {}), '()\n', (15792, 15794), True, 'import numpy as np\n'), ((16250, 16270), 'numpy.float', 'np.float', (['random_pos'], {}), '(random_pos)\n', (16258, 16270), True, 'import numpy as np\n'), ((18802, 18831), 'numpy.isnan', 'np.isnan', (['self._currentTotKin'], {}), '(self._currentTotKin)\n', (18810, 18831), True, 'import numpy as np\n'), ((18838, 18886), 'numpy.add', 'np.add', (['self._currentTotKin', 'self._currentTotPot'], {}), '(self._currentTotKin, self._currentTotPot)\n', (18844, 18886), True, 'import numpy as np\n'), ((24890, 24966), 'warnings.warn', 'warnings.warn', (['"""Could not revert step, as only 1 step is in the trajectory!"""'], {}), "('Could not revert step, as only 1 step is in the trajectory!')\n", (24903, 24966), False, 'import warnings\n'), ((12822, 12914), 'warnings.warn', 'warnings.warn', (['"""Could not initialize the force of the potential? Check if you need it!"""'], {}), "(\n 'Could not initialize the force of the potential? Check if you need it!')\n", (12835, 12914), False, 'import warnings\n'), ((15291, 15330), 'numpy.linalg.norm', 'np.linalg.norm', (['self._currentVelocities'], {}), '(self._currentVelocities)\n', (15305, 15330), True, 'import numpy as np\n'), ((25632, 25657), 'os.path.abspath', 'os.path.abspath', (['out_path'], {}), '(out_path)\n', (25647, 25657), False, 'import os\n'), ((25725, 25750), 'os.path.dirname', 'os.path.dirname', (['out_path'], {}), '(out_path)\n', (25740, 25750), False, 'import os\n'), ((16145, 16177), 'numpy.random.rand', 'np.random.rand', (['self.nDimensions'], {}), '(self.nDimensions)\n', (16159, 16177), True, 'import numpy as np\n'), ((16916, 16955), 'numpy.linalg.norm', 'np.linalg.norm', (['self._currentVelocities'], {}), '(self._currentVelocities)\n', (16930, 16955), True, 'import numpy as np\n'), ((16812, 16823), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (16820, 16823), True, 'import numpy as np\n')]
#! /usr/bin/env python # System imports from setuptools import setup, Extension, find_packages from os import path import io try: from Cython.Distutils import build_ext except ImportError: USE_CYTHON = False else: USE_CYTHON = True packages = find_packages() # versioning MAJOR = 1 MINOR = 2 MICRO = 5 ISRELEASED = True VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) this_directory = path.abspath(path.dirname(__file__)) with io.open(path.join(this_directory, 'README.md')) as f: long_description = f.read() info = { 'name': 'pylj', 'description': 'Simple teaching tool for classical MD simulation', 'author': '<NAME>', 'author_email': '<EMAIL>', 'packages': packages, 'include_package_data': True, 'setup_requires': ['jupyter', 'numpy', 'matplotlib', 'cython', 'numba'], 'install_requires': ['jupyter', 'numpy', 'matplotlib', 'cython', 'numba'], 'version': VERSION, 'license': 'MIT', 'long_description': long_description, 'long_description_content_type': 'text/markdown', 'classifiers': ['Development Status :: 5 - Production/Stable', 'Framework :: Jupyter', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Chemistry', 'Topic :: Scientific/Engineering :: Physics'] } #################################################################### # this is where setup starts #################################################################### def setup_package(): if USE_CYTHON: # Obtain the numpy include directory. This logic works across numpy # versions. ext_modules = [] HAS_NUMPY = True try: import numpy as np except: info['setup_requires'] = ['numpy'] HAS_NUMPY = False if HAS_NUMPY: try: numpy_include = np.get_include() except AttributeError: numpy_include = np.get_numpy_include() # cslowstff extension module _cslowstuff = Extension( name='pylj.comp', sources=['src/_ccomp.pyx', 'src/comp.cpp'], include_dirs=[numpy_include], language='c++', extra_compile_args=[], extra_link_args=['-lpthread'] # libraries= # extra_compile_args = "...".split(), ) ext_modules.append(_cslowstuff) info['cmdclass'] = {'build_ext': build_ext} info['ext_modules'] = ext_modules info['zip_safe'] = False try: setup(**info) except ValueError: # there probably wasn't a C-compiler (windows). Try removing extension # compilation print("") print("*****WARNING*****") print("Please install a C++ compiler. If installing in windows you " "should then install from Visual Studio command prompt (this " "makes C compiler available") print("*****************") print("") info.pop('cmdclass') info.pop('ext_modules') setup(**info) if __name__ == '__main__': setup_package()
[ "setuptools.Extension", "setuptools.setup", "os.path.dirname", "numpy.get_numpy_include", "numpy.get_include", "os.path.join", "setuptools.find_packages" ]
[((258, 273), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (271, 273), False, 'from setuptools import setup, Extension, find_packages\n'), ((413, 435), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (425, 435), False, 'from os import path\n'), ((450, 488), 'os.path.join', 'path.join', (['this_directory', '"""README.md"""'], {}), "(this_directory, 'README.md')\n", (459, 488), False, 'from os import path\n'), ((3447, 3460), 'setuptools.setup', 'setup', ([], {}), '(**info)\n', (3452, 3460), False, 'from setuptools import setup, Extension, find_packages\n'), ((2671, 2850), 'setuptools.Extension', 'Extension', ([], {'name': '"""pylj.comp"""', 'sources': "['src/_ccomp.pyx', 'src/comp.cpp']", 'include_dirs': '[numpy_include]', 'language': '"""c++"""', 'extra_compile_args': '[]', 'extra_link_args': "['-lpthread']"}), "(name='pylj.comp', sources=['src/_ccomp.pyx', 'src/comp.cpp'],\n include_dirs=[numpy_include], language='c++', extra_compile_args=[],\n extra_link_args=['-lpthread'])\n", (2680, 2850), False, 'from setuptools import setup, Extension, find_packages\n'), ((3958, 3971), 'setuptools.setup', 'setup', ([], {}), '(**info)\n', (3963, 3971), False, 'from setuptools import setup, Extension, find_packages\n'), ((2496, 2512), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (2510, 2512), True, 'import numpy as np\n'), ((2580, 2602), 'numpy.get_numpy_include', 'np.get_numpy_include', ([], {}), '()\n', (2600, 2602), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.cm as cmx from matplotlib.animation import FuncAnimation import sklearn from sklearn import manifold from numpy import linalg class tsneAnimate(): def __init__(self,tsne): self.tsne = tsne self.isfit = False def getSteps(self,X,y): #based on https://github.com/oreillymedia/t-SNE-tutorial old_grad = sklearn.manifold.t_sne._gradient_descent positions = [] def _gradient_descent(objective, p0, it, n_iter, objective_error=None, n_iter_check=1, n_iter_without_progress=50, momentum=0.5, learning_rate=1000.0, min_gain=0.01, min_grad_norm=1e-7, min_error_diff=1e-7, verbose=0, args=None, kwargs=None): if args is None: args = [] if kwargs is None: kwargs = {} p = p0.copy().ravel() update = np.zeros_like(p) gains = np.ones_like(p) error = np.finfo(np.float).max best_error = np.finfo(np.float).max best_iter = 0 for i in range(it, n_iter): # We save the current position. positions.append(p.copy()) new_error, grad = objective(p, *args, **kwargs) grad_norm = linalg.norm(grad) inc = update * grad >= 0.0 dec = np.invert(inc) gains[inc] += 0.05 gains[dec] *= 0.95 np.clip(gains, min_gain, np.inf) grad *= gains update = momentum * update - learning_rate * grad p += update if (i + 1) % n_iter_check == 0: if new_error is None: new_error = objective_error(p, *args) error_diff = np.abs(new_error - error) error = new_error if verbose >= 2: m = "[t-SNE] Iteration %d: error = %.7f, gradient norm = %.7f" print(m % (i + 1, error, grad_norm)) if error < best_error: best_error = error best_iter = i elif i - best_iter > n_iter_without_progress: if verbose >= 2: print("[t-SNE] Iteration %d: did not make any progress " "during the last %d episodes. Finished." % (i + 1, n_iter_without_progress)) break if grad_norm <= min_grad_norm: if verbose >= 2: print("[t-SNE] Iteration %d: gradient norm %f. Finished." % (i + 1, grad_norm)) break if error_diff <= min_error_diff: if verbose >= 2: m = "[t-SNE] Iteration %d: error difference %f. Finished." print(m % (i + 1, error_diff)) break if new_error is not None: error = new_error return p, error, i #Replace old gradient func sklearn.manifold.t_sne._gradient_descent = _gradient_descent X_proj = self.tsne.fit_transform(X) self.isfit = True #return old gradient descent back sklearn.manifold.t_sne._gradient_descent = old_grad return positions def animate(self,X,y,useTqdm=0,filename=None,return_anim=True): pos = self.getSteps(X,y) y_mapping = {i:n for n,i in enumerate(set(y))} last_iter = pos[len(pos)-1].reshape(-1, 2) lims = np.max(last_iter,axis=0),np.min(last_iter,axis=0) NCOLORS = len(y_mapping) fig = plt.figure() fig.set_tight_layout(True) ax = fig.add_subplot(111) jet = plt.get_cmap('jet') cNorm = colors.Normalize(vmin=0, vmax=NCOLORS) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) A,B = np.array(list(zip(*pos[0].reshape(-1, 2)))) dots_list = [] for i in range(NCOLORS): colorVal = scalarMap.to_rgba(i) a,b = A[y == i],B[y == i] dots, = ax.plot(b,a,'o',color=colorVal) dots_list.append(dots) def init(): ax.set_xlim([lims[0][0],lims[1][0]]) ax.set_ylim([lims[0][1],lims[1][1]]) return [i for i in dots_list] def update(i): for j in range(len(dots_list)): a,b = np.array(list(zip(*pos[i].reshape(-1, 2)))) a,b = a[y == j],b[y == j] dots_list[j].set_xdata(a) dots_list[j].set_ydata(b) return [i for i in dots_list]+[ax] if useTqdm==0: frames = np.arange(0, len(pos)-1) elif useTqdm==1: from tqdm import tqdm frames = tqdm(np.arange(0, len(pos)-1)) elif useTqdm==2: from tqdm import tqdm_notebook frames = tqdm_notebook(np.arange(0, len(pos)-1)) anim = FuncAnimation(fig, update, frames=frames, init_func=init, interval=50) if return_anim: return anim if filename==None: plt.show() else: #anim.save(filename, fps=20, codec='libx264') anim.save(filename, dpi=80, writer='imagemagick')
[ "numpy.zeros_like", "numpy.ones_like", "matplotlib.pyplot.get_cmap", "matplotlib.colors.Normalize", "matplotlib.pyplot.show", "numpy.invert", "matplotlib.cm.ScalarMappable", "numpy.abs", "numpy.clip", "matplotlib.animation.FuncAnimation", "numpy.finfo", "matplotlib.pyplot.figure", "numpy.max...
[((4017, 4029), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4027, 4029), True, 'import matplotlib.pyplot as plt\n'), ((4113, 4132), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""jet"""'], {}), "('jet')\n", (4125, 4132), True, 'import matplotlib.pyplot as plt\n'), ((4151, 4189), 'matplotlib.colors.Normalize', 'colors.Normalize', ([], {'vmin': '(0)', 'vmax': 'NCOLORS'}), '(vmin=0, vmax=NCOLORS)\n', (4167, 4189), True, 'import matplotlib.colors as colors\n'), ((4210, 4250), 'matplotlib.cm.ScalarMappable', 'cmx.ScalarMappable', ([], {'norm': 'cNorm', 'cmap': 'jet'}), '(norm=cNorm, cmap=jet)\n', (4228, 4250), True, 'import matplotlib.cm as cmx\n'), ((5363, 5433), 'matplotlib.animation.FuncAnimation', 'FuncAnimation', (['fig', 'update'], {'frames': 'frames', 'init_func': 'init', 'interval': '(50)'}), '(fig, update, frames=frames, init_func=init, interval=50)\n', (5376, 5433), False, 'from matplotlib.animation import FuncAnimation\n'), ((1070, 1086), 'numpy.zeros_like', 'np.zeros_like', (['p'], {}), '(p)\n', (1083, 1086), True, 'import numpy as np\n'), ((1107, 1122), 'numpy.ones_like', 'np.ones_like', (['p'], {}), '(p)\n', (1119, 1122), True, 'import numpy as np\n'), ((3920, 3945), 'numpy.max', 'np.max', (['last_iter'], {'axis': '(0)'}), '(last_iter, axis=0)\n', (3926, 3945), True, 'import numpy as np\n'), ((3945, 3970), 'numpy.min', 'np.min', (['last_iter'], {'axis': '(0)'}), '(last_iter, axis=0)\n', (3951, 3970), True, 'import numpy as np\n'), ((5521, 5531), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5529, 5531), True, 'import matplotlib.pyplot as plt\n'), ((1143, 1161), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (1151, 1161), True, 'import numpy as np\n'), ((1191, 1209), 'numpy.finfo', 'np.finfo', (['np.float'], {}), '(np.float)\n', (1199, 1209), True, 'import numpy as np\n'), ((1465, 1482), 'numpy.linalg.norm', 'linalg.norm', (['grad'], {}), '(grad)\n', (1476, 1482), False, 'from numpy import linalg\n'), ((1549, 1563), 'numpy.invert', 'np.invert', (['inc'], {}), '(inc)\n', (1558, 1563), True, 'import numpy as np\n'), ((1650, 1682), 'numpy.clip', 'np.clip', (['gains', 'min_gain', 'np.inf'], {}), '(gains, min_gain, np.inf)\n', (1657, 1682), True, 'import numpy as np\n'), ((1993, 2018), 'numpy.abs', 'np.abs', (['(new_error - error)'], {}), '(new_error - error)\n', (1999, 2018), True, 'import numpy as np\n')]
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import math class ResidualBlock(nn.Module): """Residual Block with instance normalization.""" def __init__(self, dim_in, dim_out): super(ResidualBlock, self).__init__() self.main = nn.Sequential( nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True), nn.ReLU(inplace=True), nn.Conv2d(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True)) def forward(self, x): return x + self.main(x) class Generator(nn.Module): """Generator network.""" def __init__(self, conv_dim=1024, c_dim=5, image_size=256, op_channels=3): super(Generator, self).__init__() self.spatial = nn.Linear(c_dim,conv_dim,bias=False) #Use Conv2d here? Wont it be the same? layers = [] curr_dim = conv_dim for i in range(int(math.log2(image_size)-2)): layers.append(nn.ConvTranspose2d(curr_dim,curr_dim//2,kernel_size=4,stride=2,padding=1,bias=False)) layers.append(nn.InstanceNorm2d(curr_dim//2,affine=True,track_running_stats=True)) layers.append(nn.ReLU(inplace=True)) curr_dim=curr_dim//2 layers.append(nn.Conv2d(curr_dim,op_channels,kernel_size=3,stride=1,padding=1,bias=False)) layers.append(nn.Tanh()) self.upsample = nn.Sequential(*layers) def forward(self, c): # Replicate spatially and concatenate domain information. c_h = self.spatial(c) c_h = c_h.view(c_h.size(0), c_h.size(1), 1, 1) c_h = c_h.repeat(1, 1, 4, 4) x = self.upsample(c_h) return x class FE(nn.Module): """Intermediate layer to obtain latent space network with PatchGAN.""" def __init__(self, image_size=256, conv_dim=64, inp_channels=3): super(FE, self).__init__() layers = [] layers.append(nn.Conv2d(inp_channels, conv_dim, kernel_size=4, stride=2, padding=1)) layers.append(nn.LeakyReLU(0.01)) curr_dim = conv_dim for i in range(1, int(math.log2(image_size)-1)): layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1)) layers.append(nn.LeakyReLU(0.01)) curr_dim = curr_dim * 2 self.main = nn.Sequential(*layers) def forward(self, x): return self.main(x) class Discriminator(nn.Module): """ Outputs attributes and real/fake""" def __init__(self, image_size=256, conv_dim=64, c_dim=5): super(Discriminator,self).__init__() curr_dim=conv_dim for _ in range(1,int(math.log2(image_size)-1)): curr_dim = curr_dim*2 kernel_size=image_size//np.power(2,7) self.real_conv = nn.Conv2d(curr_dim, 1, kernel_size=3, stride=1, padding=1, bias=False) self.cls_conv = nn.Conv2d(curr_dim, c_dim, kernel_size=2, stride=1, bias=False) def forward(self,x): out_src = self.real_conv(x) out_cls = self.cls_conv(x) return out_src,out_cls.view(out_cls.size(0),out_cls.size(1)) class Q(nn.Module): """ Outputs logits and stats for G(x,c)""" def __init__(self,image_size=256,conv_dim=64,con_dim=2): super(Q,self).__init__() curr_dim=conv_dim for _ in range(1,int(math.log2(image_size)-1)): curr_dim=curr_dim*2 # Remove this and see!? self.conv=nn.Sequential(nn.Conv2d(curr_dim, 128, kernel_size=1,bias=False), nn.LeakyReLU(0.01,inplace=True), nn.Conv2d(128, 64, kernel_size=1,bias=False), nn.LeakyReLU(0.01,inplace=True)) self.conv_mu =nn.Conv2d(curr_dim,con_dim,kernel_size=2,stride=1,padding=0) self.conv_var=nn.Conv2d(curr_dim,con_dim,kernel_size=2,stride=1,padding=0) def forward(self,h): # out=self.conv(h) mu_out=self.conv_mu(h).squeeze() var_out=self.conv_var(h).squeeze().exp() return mu_out,var_out
[ "torch.nn.ReLU", "torch.nn.ConvTranspose2d", "torch.nn.Sequential", "torch.nn.Tanh", "numpy.power", "torch.nn.Conv2d", "torch.nn.InstanceNorm2d", "torch.nn.Linear", "torch.nn.LeakyReLU", "math.log2" ]
[((940, 978), 'torch.nn.Linear', 'nn.Linear', (['c_dim', 'conv_dim'], {'bias': '(False)'}), '(c_dim, conv_dim, bias=False)\n', (949, 978), True, 'import torch.nn as nn\n'), ((1582, 1604), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (1595, 1604), True, 'import torch.nn as nn\n'), ((2516, 2538), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (2529, 2538), True, 'import torch.nn as nn\n'), ((3000, 3070), 'torch.nn.Conv2d', 'nn.Conv2d', (['curr_dim', '(1)'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)'}), '(curr_dim, 1, kernel_size=3, stride=1, padding=1, bias=False)\n', (3009, 3070), True, 'import torch.nn as nn\n'), ((3096, 3159), 'torch.nn.Conv2d', 'nn.Conv2d', (['curr_dim', 'c_dim'], {'kernel_size': '(2)', 'stride': '(1)', 'bias': '(False)'}), '(curr_dim, c_dim, kernel_size=2, stride=1, bias=False)\n', (3105, 3159), True, 'import torch.nn as nn\n'), ((3955, 4019), 'torch.nn.Conv2d', 'nn.Conv2d', (['curr_dim', 'con_dim'], {'kernel_size': '(2)', 'stride': '(1)', 'padding': '(0)'}), '(curr_dim, con_dim, kernel_size=2, stride=1, padding=0)\n', (3964, 4019), True, 'import torch.nn as nn\n'), ((4038, 4102), 'torch.nn.Conv2d', 'nn.Conv2d', (['curr_dim', 'con_dim'], {'kernel_size': '(2)', 'stride': '(1)', 'padding': '(0)'}), '(curr_dim, con_dim, kernel_size=2, stride=1, padding=0)\n', (4047, 4102), True, 'import torch.nn as nn\n'), ((319, 393), 'torch.nn.Conv2d', 'nn.Conv2d', (['dim_in', 'dim_out'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)'}), '(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False)\n', (328, 393), True, 'import torch.nn as nn\n'), ((407, 472), 'torch.nn.InstanceNorm2d', 'nn.InstanceNorm2d', (['dim_out'], {'affine': '(True)', 'track_running_stats': '(True)'}), '(dim_out, affine=True, track_running_stats=True)\n', (424, 472), True, 'import torch.nn as nn\n'), ((486, 507), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (493, 507), True, 'import torch.nn as nn\n'), ((521, 596), 'torch.nn.Conv2d', 'nn.Conv2d', (['dim_out', 'dim_out'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)'}), '(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False)\n', (530, 596), True, 'import torch.nn as nn\n'), ((610, 675), 'torch.nn.InstanceNorm2d', 'nn.InstanceNorm2d', (['dim_out'], {'affine': '(True)', 'track_running_stats': '(True)'}), '(dim_out, affine=True, track_running_stats=True)\n', (627, 675), True, 'import torch.nn as nn\n'), ((1439, 1524), 'torch.nn.Conv2d', 'nn.Conv2d', (['curr_dim', 'op_channels'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(False)'}), '(curr_dim, op_channels, kernel_size=3, stride=1, padding=1, bias=False\n )\n', (1448, 1524), True, 'import torch.nn as nn\n'), ((1538, 1547), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1545, 1547), True, 'import torch.nn as nn\n'), ((2119, 2188), 'torch.nn.Conv2d', 'nn.Conv2d', (['inp_channels', 'conv_dim'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(inp_channels, conv_dim, kernel_size=4, stride=2, padding=1)\n', (2128, 2188), True, 'import torch.nn as nn\n'), ((2212, 2230), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.01)'], {}), '(0.01)\n', (2224, 2230), True, 'import torch.nn as nn\n'), ((2952, 2966), 'numpy.power', 'np.power', (['(2)', '(7)'], {}), '(2, 7)\n', (2960, 2966), True, 'import numpy as np\n'), ((3668, 3719), 'torch.nn.Conv2d', 'nn.Conv2d', (['curr_dim', '(128)'], {'kernel_size': '(1)', 'bias': '(False)'}), '(curr_dim, 128, kernel_size=1, bias=False)\n', (3677, 3719), True, 'import torch.nn as nn\n'), ((3753, 3785), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.01)'], {'inplace': '(True)'}), '(0.01, inplace=True)\n', (3765, 3785), True, 'import torch.nn as nn\n'), ((3818, 3863), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(64)'], {'kernel_size': '(1)', 'bias': '(False)'}), '(128, 64, kernel_size=1, bias=False)\n', (3827, 3863), True, 'import torch.nn as nn\n'), ((3899, 3931), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.01)'], {'inplace': '(True)'}), '(0.01, inplace=True)\n', (3911, 3931), True, 'import torch.nn as nn\n'), ((1153, 1248), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['curr_dim', '(curr_dim // 2)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)', 'bias': '(False)'}), '(curr_dim, curr_dim // 2, kernel_size=4, stride=2,\n padding=1, bias=False)\n', (1171, 1248), True, 'import torch.nn as nn\n'), ((1265, 1336), 'torch.nn.InstanceNorm2d', 'nn.InstanceNorm2d', (['(curr_dim // 2)'], {'affine': '(True)', 'track_running_stats': '(True)'}), '(curr_dim // 2, affine=True, track_running_stats=True)\n', (1282, 1336), True, 'import torch.nn as nn\n'), ((1360, 1381), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1367, 1381), True, 'import torch.nn as nn\n'), ((2344, 2413), 'torch.nn.Conv2d', 'nn.Conv2d', (['curr_dim', '(curr_dim * 2)'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '(1)'}), '(curr_dim, curr_dim * 2, kernel_size=4, stride=2, padding=1)\n', (2353, 2413), True, 'import torch.nn as nn\n'), ((2439, 2457), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.01)'], {}), '(0.01)\n', (2451, 2457), True, 'import torch.nn as nn\n'), ((1100, 1121), 'math.log2', 'math.log2', (['image_size'], {}), '(image_size)\n', (1109, 1121), False, 'import math\n'), ((2291, 2312), 'math.log2', 'math.log2', (['image_size'], {}), '(image_size)\n', (2300, 2312), False, 'import math\n'), ((2850, 2871), 'math.log2', 'math.log2', (['image_size'], {}), '(image_size)\n', (2859, 2871), False, 'import math\n'), ((3544, 3565), 'math.log2', 'math.log2', (['image_size'], {}), '(image_size)\n', (3553, 3565), False, 'import math\n')]
import theanets import numpy as np INS = 3 OUTS = 2 STEPS = 11 ALL = 30 BATCH = 10 class TestFunctions: def setUp(self): self.samples = np.random.randn(2 * STEPS, INS) self.labels = np.random.randn(2 * STEPS, OUTS) def test_batches_labeled(self): f = theanets.recurrent.batches( self.samples, self.labels, steps=STEPS, batch_size=BATCH) assert len(f()) == 2 assert f()[0].shape == (STEPS, BATCH, INS) assert f()[1].shape == (STEPS, BATCH, OUTS) def test_batches_unlabeled(self): f = theanets.recurrent.batches( self.samples, steps=STEPS, batch_size=BATCH) assert len(f()) == 1 assert f()[0].shape == (STEPS, BATCH, INS) class Base: def setUp(self): np.random.seed(3) self.inputs = np.random.randn(STEPS, ALL, INS).astype('f') self.outputs = np.random.randn(STEPS, ALL, OUTS).astype('f') self.probe = np.random.randn(STEPS, BATCH, INS).astype('f') def assert_shape(self, actual, expected): assert actual == expected, 'expected {}, got {}'.format(expected, actual) class TestNetwork(Base): def _build(self, *hiddens, **kwargs): return theanets.recurrent.Regressor( layers=(INS, ) + hiddens + (OUTS, ), hidden_activation='logistic', batch_size=BATCH, **kwargs) def test_predict(self): net = self._build(15, 13) y = net.predict(self.probe) self.assert_shape(y.shape, (STEPS, BATCH, OUTS)) def test_feed_forward(self): net = self._build(15, 13) hs = net.feed_forward(self.probe) assert len(hs) == 4 self.assert_shape(hs[0].shape, (STEPS, BATCH, INS)) self.assert_shape(hs[1].shape, (STEPS, BATCH, 15)) self.assert_shape(hs[2].shape, (STEPS, BATCH, 13)) self.assert_shape(hs[3].shape, (STEPS, BATCH, OUTS)) def test_multiple_recurrent(self): net = self._build(13, 14, 15, recurrent_layers={0, 1}) hs = net.feed_forward(self.probe) assert len(hs) == 5 self.assert_shape(hs[0].shape, (STEPS, BATCH, INS)) self.assert_shape(hs[1].shape, (STEPS, BATCH, 13)) self.assert_shape(hs[2].shape, (STEPS, BATCH, 14)) self.assert_shape(hs[3].shape, (STEPS, BATCH, 15)) self.assert_shape(hs[4].shape, (STEPS, BATCH, OUTS)) class TestPredictor(Base): def _build(self, *hiddens, **kwargs): return theanets.recurrent.Predictor( layers=(INS, ) + hiddens + (INS, ), hidden_activation='logistic', batch_size=10, **kwargs) def test_predict_onelayer(self): net = self._build(13) z = net.predict(self.probe) self.assert_shape(z.shape, (STEPS, BATCH, INS)) class TestClassifier(Base): def _build(self, *hiddens, **kwargs): return theanets.recurrent.Classifier( layers=(INS, ) + hiddens + (OUTS, ), hidden_activation='logistic', batch_size=BATCH, **kwargs) def test_classify_onelayer(self): net = self._build(13) z = net.classify(self.probe) self.assert_shape(z.shape, (STEPS, BATCH)) def test_classify_twolayer(self): net = self._build(13, 14) z = net.classify(self.probe) self.assert_shape(z.shape, (STEPS, BATCH)) class TestAutoencoder(Base): def _build(self, *hiddens, **kwargs): return theanets.recurrent.Autoencoder( layers=(INS, ) + hiddens + (INS, ), hidden_activation='logistic', batch_size=BATCH, **kwargs) def test_encode_onelayer(self): net = self._build(13) z = net.predict(self.probe) self.assert_shape(z.shape, (STEPS, BATCH, INS)) def test_encode_twolayer(self): net = self._build(13, 14) z = net.predict(self.probe) self.assert_shape(z.shape, (STEPS, BATCH, INS))
[ "theanets.recurrent.Classifier", "numpy.random.seed", "theanets.recurrent.Autoencoder", "numpy.random.randn", "theanets.recurrent.Regressor", "theanets.recurrent.Predictor", "theanets.recurrent.batches" ]
[((151, 182), 'numpy.random.randn', 'np.random.randn', (['(2 * STEPS)', 'INS'], {}), '(2 * STEPS, INS)\n', (166, 182), True, 'import numpy as np\n'), ((205, 237), 'numpy.random.randn', 'np.random.randn', (['(2 * STEPS)', 'OUTS'], {}), '(2 * STEPS, OUTS)\n', (220, 237), True, 'import numpy as np\n'), ((287, 375), 'theanets.recurrent.batches', 'theanets.recurrent.batches', (['self.samples', 'self.labels'], {'steps': 'STEPS', 'batch_size': 'BATCH'}), '(self.samples, self.labels, steps=STEPS,\n batch_size=BATCH)\n', (313, 375), False, 'import theanets\n'), ((568, 639), 'theanets.recurrent.batches', 'theanets.recurrent.batches', (['self.samples'], {'steps': 'STEPS', 'batch_size': 'BATCH'}), '(self.samples, steps=STEPS, batch_size=BATCH)\n', (594, 639), False, 'import theanets\n'), ((776, 793), 'numpy.random.seed', 'np.random.seed', (['(3)'], {}), '(3)\n', (790, 793), True, 'import numpy as np\n'), ((1211, 1336), 'theanets.recurrent.Regressor', 'theanets.recurrent.Regressor', ([], {'layers': '((INS,) + hiddens + (OUTS,))', 'hidden_activation': '"""logistic"""', 'batch_size': 'BATCH'}), "(layers=(INS,) + hiddens + (OUTS,),\n hidden_activation='logistic', batch_size=BATCH, **kwargs)\n", (1239, 1336), False, 'import theanets\n'), ((2474, 2595), 'theanets.recurrent.Predictor', 'theanets.recurrent.Predictor', ([], {'layers': '((INS,) + hiddens + (INS,))', 'hidden_activation': '"""logistic"""', 'batch_size': '(10)'}), "(layers=(INS,) + hiddens + (INS,),\n hidden_activation='logistic', batch_size=10, **kwargs)\n", (2502, 2595), False, 'import theanets\n'), ((2890, 3016), 'theanets.recurrent.Classifier', 'theanets.recurrent.Classifier', ([], {'layers': '((INS,) + hiddens + (OUTS,))', 'hidden_activation': '"""logistic"""', 'batch_size': 'BATCH'}), "(layers=(INS,) + hiddens + (OUTS,),\n hidden_activation='logistic', batch_size=BATCH, **kwargs)\n", (2919, 3016), False, 'import theanets\n'), ((3470, 3596), 'theanets.recurrent.Autoencoder', 'theanets.recurrent.Autoencoder', ([], {'layers': '((INS,) + hiddens + (INS,))', 'hidden_activation': '"""logistic"""', 'batch_size': 'BATCH'}), "(layers=(INS,) + hiddens + (INS,),\n hidden_activation='logistic', batch_size=BATCH, **kwargs)\n", (3500, 3596), False, 'import theanets\n'), ((816, 848), 'numpy.random.randn', 'np.random.randn', (['STEPS', 'ALL', 'INS'], {}), '(STEPS, ALL, INS)\n', (831, 848), True, 'import numpy as np\n'), ((884, 917), 'numpy.random.randn', 'np.random.randn', (['STEPS', 'ALL', 'OUTS'], {}), '(STEPS, ALL, OUTS)\n', (899, 917), True, 'import numpy as np\n'), ((951, 985), 'numpy.random.randn', 'np.random.randn', (['STEPS', 'BATCH', 'INS'], {}), '(STEPS, BATCH, INS)\n', (966, 985), True, 'import numpy as np\n')]
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.3.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% import pandas as pd # %% lat_CHC = -16.35 lon_CHC = -68.13 lat_ATTO = -2.1457 lon_ATTO = - 59.0048 _dic = dict(Amazon={'lat': lat_ATTO, 'lon': lon_ATTO}, Chacataya={'lat':lat_CHC, 'lon':lon_CHC} ) collocate_locations = pd.DataFrame.from_dict(_dic) collocate_locations # %% from oas_erf.util.Nd.sizedist_class_v2 import SizedistributionSurface, SizedistributionStation # %% from oas_erf.util.plot import plot_profiles from oas_erf.util.naming_conventions import var_info from oas_erf.util.imports import get_averaged_fields from IPython import get_ipython from useful_scit.imps import (plt) from matplotlib.lines import Line2D import seaborn as sns from oas_erf.data_info.simulation_types import get_diff_by_type, get_casen_by_type_mod from oas_erf.util.imports import get_averaged_fields from oas_erf.util.naming_conventions.var_info import get_fancy_var_name, get_fancy_unit_xr from oas_erf.util.plot.colors import get_case_col from oas_erf.util.plot.plot_maps import plot_map_diff, plot_map from oas_erf.constants import get_plotpath, path_data_info from oas_erf.util.practical_functions import make_folders import cartopy.crs as ccrs from matplotlib import gridspec from matplotlib import colors # noinspection PyBroadException try: _ipython = get_ipython() _magic = _ipython.magic _magic('load_ext autoreload') _magic('autoreload 2') except: pass # %% # %% p_level = 1013. pmin = 850. # minimum pressure level avg_over_lev = True # True#True#False#True pressure_adjust = True # Can only be false if avg_over_lev false. Plots particular hybrid sigma lev p_levels = [1013., 900., 800., 700., 600.] # used if not avg # %% # %% model = 'NorESM' startyear = '0004-01' endyear = '0008-12' # %% model = 'NorESM' startyear = '2008-01' endyear = '2014-12' # %% [markdown] # ## Cases # %% cases_sec = [ 'SECTv21_ctrl_koagD', #'NF1850_SECT_ctrl', #'NF1850_aeroxid2014_SECT_ctrl', ] cases_orig = [ 'noSECTv21_default_dd', 'noSECTv21_ox_ricc_dd', ] cases_pd = cases_orig + cases_sec # %% [markdown] # ## Cases # %% cases = cases_pd #+ cases_pi # %% from pathlib import Path # %% version = 'pd_amazon_chc' plot_path = get_plotpath('measurement_comp') filen_base = Path(plot_path + '/%s' % version) filen_base.mkdir(exist_ok=True) # print(plot_path) make_folders(plot_path) # %% from oas_erf.util.slice_average.avg_pkg import yearly_mean_dic # %% varl = ['NCONC01','N50','N60','Z3']#,'N60'] # %% cases # %% from oas_erf.util.collocate.collocate import CollocateModel # %% from oas_erf.data_info.variable_info import sized_varListNorESM,sized_varlist_SOA_SEC, sized_varlist_SO4_SEC # %% vl = sized_varListNorESM['NCONC']+sized_varListNorESM['NMR']+ sized_varListNorESM['SIGMA'] # %% vl_sec = sized_varlist_SO4_SEC + sized_varlist_SOA_SEC # %% [markdown] # ## Create collocated datasets: # %% dic_collds = {} # %% for case in cases_pd: print(case) _vl = vl isSec = (case in cases_sec) if isSec: _vl = vl + vl_sec collmod = CollocateModel(case, startyear, endyear, isSec, 'month', space_res='locations', locations = collocate_locations #[5,39.6], #False, ) collmod.locations = collocate_locations try: _ds = collmod.collocate_dataset_vars(_vl) except: collmod.load_raw_ds(_vl) _ds = collmod.collocate_dataset_vars(_vl) dic_collds[case] = _ds#.copy() #collmod.get # %% import xarray as xr # %% dic_sdist = {} dic_ds={} for case in cases_pd: print(case) _vl = vl isSec = (case in cases_sec) if isSec: _vl = vl + vl_sec sdist = SizedistributionStation.SizedistributionStation( case, startyear, endyear, [5,39.6], isSec, 'month', locations=collocate_locations, ) sdist.get_collocated_dataset(vl) ds = sdist.compute_sizedist_tot() for var in ['dNdlogD_mode01','dNdlogD_mode04','dNdlogD_mode02', 'dNdlogD_mode05','dNdlogD_mode06','dNdlogD_mode07', 'dNdlogD_mode08','dNdlogD_mode09','dNdlogD_mode10' ,'dNdlogD_mode12','dNdlogD_mode14']: ds[var] = sdist.compute_sizedist_mod_var(var)[var] dic_ds[case] = ds.copy() dic_sdist[case] = sdist # %% import xarray as xr # %% yscale = 'linear' for case in cases_orig: ds= dic_ds[case] ds['dNdlogD_mod'].isel(location=1,lev=-5).mean('time').plot(xscale='log', yscale=yscale, label=case) for case in cases_sec: ds= dic_ds[case] (ds['dNdlogD_sec']+ds['dNdlogD_mod']).isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale=yscale, label=case) plt.legend() plt.ylim([1e-1,5e3]) # %% import numpy as np # %% yscale = 'linear' for case in cases_orig: ds= dic_ds[case] (ds['dNdlogD_mod']*np.log(10)).isel(location=1,lev=-1).mean('time').plot(xscale='log', yscale=yscale, label=case) for case in cases_sec: ds= dic_ds[case] ((ds['dNdlogD_sec']+ds['dNdlogD_mod'])*np.log(10)).isel(location=1,lev=-1).mean('time').plot(xscale='log', yscale=yscale, label=case) plt.legend() plt.ylim([1e1,8e3]) plt.xlim([1e1,5e2]) # %% # %% from useful_scit.imps import * # %% from oas_erf.constants import project_base_path, project_name from pathlib import Path # %% base_dir = Path(project_base_path+project_name) # %% path_data = base_dir /'data/EBAS' path_data.exists() # %% fl = list(path_data.glob('*.1y.*.nc')) # %% fl # %% [markdown] # fl = path_data / 'BO0001R.*.1y.1h.BO01L_SMPS_UMSA-LAP_CHACALTAYA_BOLIVIA.DE08L_TROPOS_CL_SMPS.lev2.nc' # #'BO0001R.20120101000000.20190917174536.smps.particle_number_size_distribution.aerosol.1y.1h.BO01L_SMPS_UMSA-LAP_CHACALTAYA_BOLIVIA.DE08L_TROPOS_CL_SMPS.lev2.nc' # %% ds_obs = xr.open_mfdataset(fl, combine='by_coords') # %% ds_obs['particle_number_size_distribution_amean'] # %% ds_obs#['particle_number_size_distribution_amean'] # %% logD = np.log10(ds_obs['D']) # %% dlogD = logD.isel(D=slice(1,None)).values -logD.isel(D=slice(0,-1)) # %% dlogD # %% N = (ds_obs['particle_number_size_distribution_amean']*dlogD).sum('D')#.plot() # %% N.plot() # %% jupyter={"outputs_hidden": true} ds_obs # %% ds_obs['particle_number_size_distribution_amean'].isel(D=10,metadata_time=2 ).plot() # %% ds_obs['particle_number_size_distribution_amean'].isel(D=10).plot() # %% N.isel(metadata_time=0)#.plot() # %% ds_obs['particle_number_size_distribution_amean'].mean('metadata_time').mean('time').plot(xscale='log') ds_obs['particle_number_size_distribution_perc8413'].mean('metadata_time').mean('time').plot(xscale='log') ds_obs['particle_number_size_distribution_prec1587'].mean('metadata_time').mean('time').plot(xscale='log') # %% from oas_erf.data_info import get_nice_name_case # %% import numpy as np # %% np.log(10) # %% yscale = 'linear' cndic = dict(noSECTv21_default_dd='OsloAero$_{def}$', noSECTv21_ox_ricc_dd = 'OsloAero$_{imp}$') for case in cases_orig: ds= dic_ds[case] (np.log(10)*ds['dNdlogD_mod']).isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale=yscale, label=cndic[case], c = get_case_col(cndic[case])) for case in cases_sec: ds= dic_ds[case] (np.log(10)*(ds['dNdlogD_sec']+ds['dNdlogD_mod'])).isel(location=0,lev=-1).mean('time').plot(xscale='log', c = get_case_col('OsloAeroSec'), yscale=yscale, label='OsloAeroSec') plt.ylim([5,9e3]) plt.xlim([10,500]) #plt.yscale('log') #ds_obs['sizedist'].mean('Date').plot(xscale='log', c='k', label='OBS: ATTO tower')#x='diameter',robust = True) plt.legend() # %% yscale = 'linear' cndic = dict(noSECTv21_default_dd='OsloAero$_{def}$', noSECTv21_ox_ricc_dd = 'OsloAero$_{imp}$') for case in cases_orig: ds= dic_ds[case] (np.log(10)*ds['dNdlogD_mod']).isel(location=0,lev=-1).sel(time = slice('2014-01-01','2015-01-01')).mean('time').plot(xscale='log', yscale=yscale, label=cndic[case], c = get_case_col(cndic[case])) for case in cases_sec: ds= dic_ds[case] (np.log(10)*(ds['dNdlogD_sec']+ds['dNdlogD_mod'])).isel(location=0,lev=-1).sel(time = slice('2014-01-01','2015-01-01')).mean('time').plot(xscale='log', c = get_case_col('OsloAeroSec'), yscale=yscale, label='OsloAeroSec') plt.ylim([5,9e3]) plt.xlim([10,500]) #plt.yscale('log') #ds_obs['sizedist'].sel(Date = slice('2014-01-01','2015-01-01')).mean('Date').plot(xscale='log', c='k', label='OBS: ATTO tower')#x='diameter',robust = True) plt.legend() # %% ds['dNdlogD_mod'] # %% ds['dNdlogD_mod'].sel(location='Chacataya',lev=slice(970,1000)).mean('lev').mean('time') # %% for c in cases: ds= dic_ds[c] ds['dNdlogD_mod'].sel(location='Chacataya',lev=slice(970,1000)).mean('lev').mean('time').plot() ds['dNdlogD_mod'].sel(location='Chacataya',).isel(lev=-1).mean('time').plot() ds['dNdlogD_mod'].sel(location='Chacataya',).isel(lev=-2).mean('time').plot() ds['dNdlogD_mod'].sel(location='Chacataya',).isel(lev=-3).mean('time').plot() plt.xscale('log') plt.xlim([10,700]) plt.ylim([10,8000]) plt.ylim([10,8000]) plt.yscale('log') plt.show() # %% def mean_for_comp(ds, isSec=False, vmon = 'dNdlogD_mod', vsec='dNdlogD_sec', p0=970,p1=1000): log10 = np.log(10) _da = ds[vmon] if isSec: _da = _da + ds[vsec] da_dlog10 = log10*_da da_sel = da_dlog10.sel(location='Chacataya',lev = slice(p0,p1)).mean('lev') da_mean = da_sel.mean('time') return da_mean # %% yscale = 'linear' p0=650 p1=900 cndic = dict(noSECTv21_default_dd='OsloAero$_{def}$', noSECTv21_ox_ricc_dd = 'OsloAero$_{imp}$') f, ax = plt.subplots(figsize=[4.5,3], dpi=100) for case in cases_orig: ds= dic_ds[case] da = mean_for_comp(ds, p0=p0,p1=p1) da.plot(xscale='log', yscale=yscale, label=cndic[case], c = get_case_col(cndic[case])) for case in cases_sec: ds= dic_ds[case] da = mean_for_comp(ds, isSec=True, p0=p0,p1=p1) da.plot(xscale='log', c = get_case_col('OsloAeroSec'),yscale=yscale, label='OsloAeroSec') plt.ylim([20,16e3]) plt.xlim([8,600]) plt.yscale('log') da_obs = ds_obs['particle_number_size_distribution_amean'].mean('metadata_time') da_obs.mean('time').plot(xscale='log', c='k', label='Chacataya')#x='diameter',robust = True) #da_obs.groupby(da_obs.time.dt.month).mean().mean('month').plot(xscale='log', c='k', label='ATTO Tower')#x='diameter',robust = True) plt.legend(frameon=False) sns.despine(f) ax.set_ylabel('dN/dlog$_{10}$D$_p$ [cm$^{-3}$]') ax.set_xlabel('diameter [nm]') f.tight_layout() fn = filen_base /'CHC_sizedist_mean2' f.savefig(fn.with_suffix('.png')) f.savefig(fn.with_suffix('.pdf')) # %% ds_obs # %% def mean_for_comp_month(ds, isSec=False, vmon = 'dNdlogD_mod', vsec='dNdlogD_sec', p0=650, p1=900): log10 = np.log(10) _da = ds[vmon] if isSec: _da = _da + ds[vsec] da_dlog10 = log10*_da da_sel = da_dlog10.isel(location=1).sel(lev = slice(p0,p1)).mean('lev') da_mean = da_sel.groupby(da_sel.time.dt.month).mean() return da_mean # %% from matplotlib.colors import LogNorm # %% p0=650 p1=900 yscale = 'log' xscale='linear' f,axs = plt.subplots(1,4, figsize=[9 ,4], sharex=True, sharey=True, dpi=100) cndic = dict(noSECTv21_default_dd='OsloAero$_{def}$', noSECTv21_ox_ricc_dd = 'OsloAero$_{imp}$', SECTv21_ctrl_koagD = 'OsloAeroSec') norm = LogNorm(vmin=50, vmax=12000) plt_sett = dict( norm=norm, cmap='cividis', yscale=yscale, xscale=xscale, ylim=[10,500], add_colorbar=False, rasterized=True ) for case,ax in zip(cases_orig,axs): ds= dic_ds[case] da = mean_for_comp_month(ds, p0=p0, p1=p1) da.plot(x='month',**plt_sett,ax=ax)#, label=cndic[case], c = get_case_col(cndic[case])) ax.set_title(cndic[case]) for case, ax in zip(cases_sec, axs[len(cases_orig):]): ds= dic_ds[case] da = mean_for_comp_month(ds, isSec=True, p0=p0, p1=p1) da.plot(x='month',**plt_sett,ax=ax)#, label=cndic[case], c = get_case_col(cndic[case])) ax.set_title(cndic[case]) ax = axs[-1] da_obs = ds_obs['particle_number_size_distribution_amean'].mean('metadata_time') #da_obs.mean('time').plot(xscale='log', c='k', label='ATTO Tower')#x='diameter',robust = True) im = da_obs.groupby(da_obs.time.dt.month).mean().plot(x='month',**plt_sett, ax = ax)#x='diameter',robust = True) for ax in axs[1:].flatten(): ax.set_ylabel('') #for ax in axs_ba[-1,:].flatten(): # ax.set_xlabel('Latitude [$^\circ$ N]') f.subplots_adjust(right=0.8) cbar_ax = f.add_axes([0.83, 0.25, 0.015, 0.5]) cb = f.colorbar(im, cax=cbar_ax, extend = 'both', label= 'dN/dlog$_{10}$D$_p$ [cm$^{-3}$]' ) ax.set_title('Chacataya') fn = filen_base /'CHC_sizedist_month' f.savefig(fn.with_suffix('.png'), bbox_extra_artists=(cb,)) f.savefig(fn.with_suffix('.pdf'), bbox_extra_artists=(cb,)) plt.show() # %% [markdown] # ## Extra: # %% for case in cases_pd: ds = dic_ds[case] ds['dNdlogD_mod'].isel(location=1,lev=-1).mean('time').plot(xscale='log', yscale='log') for var in [ 'dNdlogD_mode01', 'dNdlogD_mode02', 'dNdlogD_mode04', 'dNdlogD_mode05', 'dNdlogD_mode06', 'dNdlogD_mode07', 'dNdlogD_mode08', 'dNdlogD_mode09', 'dNdlogD_mode10', 'dNdlogD_mode12', 'dNdlogD_mode14' ]: ds[var].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log', label=var) #ds['dNdlogD_mode02'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') #ds['dNdlogD_mode04'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') plt.legend() #plt.yscale('linear') plt.ylim([10e-1,1e4]) plt.title(case) plt.show() # %% for case in cases_pd: ds = dic_ds[case] #ds['dNdlogD_mod'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') for var in [#'dNdlogD_mode01', 'dNdlogD_mode02','dNdlogD_mode04', #'dNdlogD_mode05','dNdlogD_mode06','dNdlogD_mode07', #'dNdlogD_mode08', # 'dNdlogD_mode09','dNdlogD_mode10' #'dNdlogD_mode12','dNdlogD_mode14' ]: ds[var].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log', label=var) #ds['dNdlogD_mode02'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') #ds['dNdlogD_mode04'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') plt.legend() #plt.yscale('linear') plt.ylim([10e-1,1e4]) plt.title(case) #plt.show() # %% ds['dNdlogD_mod'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') for var in ['dNdlogD_mode01','dNdlogD_mode04','dNdlogD_mode02', 'dNdlogD_mode05','dNdlogD_mode06','dNdlogD_mode07', 'dNdlogD_mode08','dNdlogD_mode09','dNdlogD_mode10' ,'dNdlogD_mode12','dNdlogD_mode14']: ds[var].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log', label=var) #ds['dNdlogD_mode02'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') #ds['dNdlogD_mode04'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') plt.legend() plt.yscale('linear') plt.ylim([10e-1,7e2]) # %% ds['dNdlogD_mod'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') ds['dNdlogD_mode01'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') ds['dNdlogD_mode02'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') ds['dNdlogD_mode04'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') plt.ylim([10e-1,10e4]) # %% ds['dNdlogD_mod'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') ds['dNdlogD_mode01'].isel(location=0,lev=-1).mean('time').plot(xscale='log', yscale='log') # %% f, ax = plt.subplots(dpi=150) (ds['dNdlogD_mod']+ds['dNdlogD_sec']).sel(location='Chacataya').isel(lev=-1).plot(yscale='log', x='time', robust=True) # %%
[ "useful_scit.imps.plt.xlim", "useful_scit.imps.plt.legend", "oas_erf.constants.get_plotpath", "oas_erf.util.practical_functions.make_folders", "pathlib.Path", "matplotlib.colors.LogNorm", "useful_scit.imps.plt.xscale", "useful_scit.imps.plt.title", "oas_erf.util.Nd.sizedist_class_v2.Sizedistribution...
[((515, 543), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['_dic'], {}), '(_dic)\n', (537, 543), True, 'import pandas as pd\n'), ((2470, 2502), 'oas_erf.constants.get_plotpath', 'get_plotpath', (['"""measurement_comp"""'], {}), "('measurement_comp')\n", (2482, 2502), False, 'from oas_erf.constants import get_plotpath, path_data_info\n'), ((2516, 2549), 'pathlib.Path', 'Path', (["(plot_path + '/%s' % version)"], {}), "(plot_path + '/%s' % version)\n", (2520, 2549), False, 'from pathlib import Path\n'), ((2601, 2624), 'oas_erf.util.practical_functions.make_folders', 'make_folders', (['plot_path'], {}), '(plot_path)\n', (2613, 2624), False, 'from oas_erf.util.practical_functions import make_folders\n'), ((5114, 5126), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {}), '()\n', (5124, 5126), False, 'from useful_scit.imps import plt\n'), ((5127, 5150), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[0.1, 5000.0]'], {}), '([0.1, 5000.0])\n', (5135, 5150), False, 'from useful_scit.imps import plt\n'), ((5543, 5555), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {}), '()\n', (5553, 5555), False, 'from useful_scit.imps import plt\n'), ((5556, 5580), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[10.0, 8000.0]'], {}), '([10.0, 8000.0])\n', (5564, 5580), False, 'from useful_scit.imps import plt\n'), ((5576, 5599), 'useful_scit.imps.plt.xlim', 'plt.xlim', (['[10.0, 500.0]'], {}), '([10.0, 500.0])\n', (5584, 5599), False, 'from useful_scit.imps import plt\n'), ((5749, 5787), 'pathlib.Path', 'Path', (['(project_base_path + project_name)'], {}), '(project_base_path + project_name)\n', (5753, 5787), False, 'from pathlib import Path\n'), ((6201, 6243), 'xarray.open_mfdataset', 'xr.open_mfdataset', (['fl'], {'combine': '"""by_coords"""'}), "(fl, combine='by_coords')\n", (6218, 6243), True, 'import xarray as xr\n'), ((6370, 6391), 'numpy.log10', 'np.log10', (["ds_obs['D']"], {}), "(ds_obs['D'])\n", (6378, 6391), True, 'import numpy as np\n'), ((7239, 7249), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (7245, 7249), True, 'import numpy as np\n'), ((7894, 7915), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[5, 9000.0]'], {}), '([5, 9000.0])\n', (7902, 7915), False, 'from useful_scit.imps import plt\n'), ((7912, 7931), 'useful_scit.imps.plt.xlim', 'plt.xlim', (['[10, 500]'], {}), '([10, 500])\n', (7920, 7931), False, 'from useful_scit.imps import plt\n'), ((8062, 8074), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {}), '()\n', (8072, 8074), False, 'from useful_scit.imps import plt\n'), ((8810, 8831), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[5, 9000.0]'], {}), '([5, 9000.0])\n', (8818, 8831), False, 'from useful_scit.imps import plt\n'), ((8828, 8847), 'useful_scit.imps.plt.xlim', 'plt.xlim', (['[10, 500]'], {}), '([10, 500])\n', (8836, 8847), False, 'from useful_scit.imps import plt\n'), ((9023, 9035), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {}), '()\n', (9033, 9035), False, 'from useful_scit.imps import plt\n'), ((10176, 10215), 'useful_scit.imps.plt.subplots', 'plt.subplots', ([], {'figsize': '[4.5, 3]', 'dpi': '(100)'}), '(figsize=[4.5, 3], dpi=100)\n', (10188, 10215), False, 'from useful_scit.imps import plt\n'), ((10586, 10609), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[20, 16000.0]'], {}), '([20, 16000.0])\n', (10594, 10609), False, 'from useful_scit.imps import plt\n'), ((10606, 10624), 'useful_scit.imps.plt.xlim', 'plt.xlim', (['[8, 600]'], {}), '([8, 600])\n', (10614, 10624), False, 'from useful_scit.imps import plt\n'), ((10624, 10641), 'useful_scit.imps.plt.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (10634, 10641), False, 'from useful_scit.imps import plt\n'), ((10950, 10975), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {'frameon': '(False)'}), '(frameon=False)\n', (10960, 10975), False, 'from useful_scit.imps import plt\n'), ((10976, 10990), 'seaborn.despine', 'sns.despine', (['f'], {}), '(f)\n', (10987, 10990), True, 'import seaborn as sns\n'), ((11686, 11755), 'useful_scit.imps.plt.subplots', 'plt.subplots', (['(1)', '(4)'], {'figsize': '[9, 4]', 'sharex': '(True)', 'sharey': '(True)', 'dpi': '(100)'}), '(1, 4, figsize=[9, 4], sharex=True, sharey=True, dpi=100)\n', (11698, 11755), False, 'from useful_scit.imps import plt\n'), ((11919, 11947), 'matplotlib.colors.LogNorm', 'LogNorm', ([], {'vmin': '(50)', 'vmax': '(12000)'}), '(vmin=50, vmax=12000)\n', (11926, 11947), False, 'from matplotlib.colors import LogNorm\n'), ((13379, 13389), 'useful_scit.imps.plt.show', 'plt.show', ([], {}), '()\n', (13387, 13389), False, 'from useful_scit.imps import plt\n'), ((15685, 15697), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {}), '()\n', (15695, 15697), False, 'from useful_scit.imps import plt\n'), ((15698, 15718), 'useful_scit.imps.plt.yscale', 'plt.yscale', (['"""linear"""'], {}), "('linear')\n", (15708, 15718), False, 'from useful_scit.imps import plt\n'), ((15719, 15741), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[1.0, 700.0]'], {}), '([1.0, 700.0])\n', (15727, 15741), False, 'from useful_scit.imps import plt\n'), ((16108, 16133), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[1.0, 100000.0]'], {}), '([1.0, 100000.0])\n', (16116, 16133), False, 'from useful_scit.imps import plt\n'), ((16330, 16351), 'useful_scit.imps.plt.subplots', 'plt.subplots', ([], {'dpi': '(150)'}), '(dpi=150)\n', (16342, 16351), False, 'from useful_scit.imps import plt\n'), ((1555, 1568), 'IPython.get_ipython', 'get_ipython', ([], {}), '()\n', (1566, 1568), False, 'from IPython import get_ipython\n'), ((3310, 3425), 'oas_erf.util.collocate.collocate.CollocateModel', 'CollocateModel', (['case', 'startyear', 'endyear', 'isSec', '"""month"""'], {'space_res': '"""locations"""', 'locations': 'collocate_locations'}), "(case, startyear, endyear, isSec, 'month', space_res=\n 'locations', locations=collocate_locations)\n", (3324, 3425), False, 'from oas_erf.util.collocate.collocate import CollocateModel\n'), ((4101, 4237), 'oas_erf.util.Nd.sizedist_class_v2.SizedistributionStation.SizedistributionStation', 'SizedistributionStation.SizedistributionStation', (['case', 'startyear', 'endyear', '[5, 39.6]', 'isSec', '"""month"""'], {'locations': 'collocate_locations'}), "(case, startyear, endyear, [\n 5, 39.6], isSec, 'month', locations=collocate_locations)\n", (4148, 4237), False, 'from oas_erf.util.Nd.sizedist_class_v2 import SizedistributionSurface, SizedistributionStation\n'), ((9549, 9566), 'useful_scit.imps.plt.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (9559, 9566), False, 'from useful_scit.imps import plt\n'), ((9571, 9590), 'useful_scit.imps.plt.xlim', 'plt.xlim', (['[10, 700]'], {}), '([10, 700])\n', (9579, 9590), False, 'from useful_scit.imps import plt\n'), ((9594, 9614), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[10, 8000]'], {}), '([10, 8000])\n', (9602, 9614), False, 'from useful_scit.imps import plt\n'), ((9618, 9638), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[10, 8000]'], {}), '([10, 8000])\n', (9626, 9638), False, 'from useful_scit.imps import plt\n'), ((9642, 9659), 'useful_scit.imps.plt.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (9652, 9659), False, 'from useful_scit.imps import plt\n'), ((9664, 9674), 'useful_scit.imps.plt.show', 'plt.show', ([], {}), '()\n', (9672, 9674), False, 'from useful_scit.imps import plt\n'), ((9788, 9798), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (9794, 9798), True, 'import numpy as np\n'), ((11329, 11339), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (11335, 11339), True, 'import numpy as np\n'), ((14158, 14170), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {}), '()\n', (14168, 14170), False, 'from useful_scit.imps import plt\n'), ((14201, 14225), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[1.0, 10000.0]'], {}), '([1.0, 10000.0])\n', (14209, 14225), False, 'from useful_scit.imps import plt\n'), ((14227, 14242), 'useful_scit.imps.plt.title', 'plt.title', (['case'], {}), '(case)\n', (14236, 14242), False, 'from useful_scit.imps import plt\n'), ((14247, 14257), 'useful_scit.imps.plt.show', 'plt.show', ([], {}), '()\n', (14255, 14257), False, 'from useful_scit.imps import plt\n'), ((14973, 14985), 'useful_scit.imps.plt.legend', 'plt.legend', ([], {}), '()\n', (14983, 14985), False, 'from useful_scit.imps import plt\n'), ((15016, 15040), 'useful_scit.imps.plt.ylim', 'plt.ylim', (['[1.0, 10000.0]'], {}), '([1.0, 10000.0])\n', (15024, 15040), False, 'from useful_scit.imps import plt\n'), ((15042, 15057), 'useful_scit.imps.plt.title', 'plt.title', (['case'], {}), '(case)\n', (15051, 15057), False, 'from useful_scit.imps import plt\n'), ((7559, 7584), 'oas_erf.util.plot.colors.get_case_col', 'get_case_col', (['cndic[case]'], {}), '(cndic[case])\n', (7571, 7584), False, 'from oas_erf.util.plot.colors import get_case_col\n'), ((7745, 7772), 'oas_erf.util.plot.colors.get_case_col', 'get_case_col', (['"""OsloAeroSec"""'], {}), "('OsloAeroSec')\n", (7757, 7772), False, 'from oas_erf.util.plot.colors import get_case_col\n'), ((8430, 8455), 'oas_erf.util.plot.colors.get_case_col', 'get_case_col', (['cndic[case]'], {}), '(cndic[case])\n', (8442, 8455), False, 'from oas_erf.util.plot.colors import get_case_col\n'), ((8661, 8688), 'oas_erf.util.plot.colors.get_case_col', 'get_case_col', (['"""OsloAeroSec"""'], {}), "('OsloAeroSec')\n", (8673, 8688), False, 'from oas_erf.util.plot.colors import get_case_col\n'), ((10364, 10389), 'oas_erf.util.plot.colors.get_case_col', 'get_case_col', (['cndic[case]'], {}), '(cndic[case])\n', (10376, 10389), False, 'from oas_erf.util.plot.colors import get_case_col\n'), ((10522, 10549), 'oas_erf.util.plot.colors.get_case_col', 'get_case_col', (['"""OsloAeroSec"""'], {}), "('OsloAeroSec')\n", (10534, 10549), False, 'from oas_erf.util.plot.colors import get_case_col\n'), ((5266, 5276), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (5272, 5276), True, 'import numpy as np\n'), ((5448, 5458), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (5454, 5458), True, 'import numpy as np\n'), ((7435, 7445), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (7441, 7445), True, 'import numpy as np\n'), ((7635, 7645), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (7641, 7645), True, 'import numpy as np\n'), ((8261, 8271), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (8267, 8271), True, 'import numpy as np\n'), ((8506, 8516), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (8512, 8516), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import pyk4a from pyk4a import Config, PyK4A MAX_SAMPLES = 1000 def set_default_data(data): data["acc_x"] = MAX_SAMPLES * [data["acc_x"][-1]] data["acc_y"] = MAX_SAMPLES * [data["acc_y"][-1]] data["acc_z"] = MAX_SAMPLES * [data["acc_z"][-1]] data["gyro_x"] = MAX_SAMPLES * [data["acc_x"][-1]] data["gyro_y"] = MAX_SAMPLES * [data["acc_y"][-1]] data["gyro_z"] = MAX_SAMPLES * [data["acc_z"][-1]] def main(): k4a = PyK4A( Config( color_resolution=pyk4a.ColorResolution.RES_720P, depth_mode=pyk4a.DepthMode.NFOV_UNBINNED, synchronized_images_only=True, ) ) k4a.start() plt.ion() fig, axes = plt.subplots(3, sharex=False) data = { "temperature": [0] * MAX_SAMPLES, "acc_x": [0] * MAX_SAMPLES, "acc_y": [0] * MAX_SAMPLES, "acc_z": [0] * MAX_SAMPLES, "acc_timestamp": [0] * MAX_SAMPLES, "gyro_x": [0] * MAX_SAMPLES, "gyro_y": [0] * MAX_SAMPLES, "gyro_z": [0] * MAX_SAMPLES, "gyro_timestamp": [0] * MAX_SAMPLES, } y = np.zeros(MAX_SAMPLES) lines = { "temperature": axes[0].plot(y, label="temperature")[0], "acc_x": axes[1].plot(y, label="acc_x")[0], "acc_y": axes[1].plot(y, label="acc_y")[0], "acc_z": axes[1].plot(y, label="acc_z")[0], "gyro_x": axes[2].plot(y, label="gyro_x")[0], "gyro_y": axes[2].plot(y, label="gyro_y")[0], "gyro_z": axes[2].plot(y, label="gyro_z")[0], } for i in range(MAX_SAMPLES): sample = k4a.get_imu_sample() sample["acc_x"], sample["acc_y"], sample["acc_z"] = sample.pop("acc_sample") sample["gyro_x"], sample["gyro_y"], sample["gyro_z"] = sample.pop("gyro_sample") for k, v in sample.items(): data[k][i] = v if i == 0: set_default_data(data) for k in ("temperature", "acc_x", "acc_y", "acc_z", "gyro_x", "gyro_y", "gyro_z"): lines[k].set_data(range(MAX_SAMPLES), data[k]) acc_y = data["acc_x"] + data["acc_y"] + data["acc_z"] gyro_y = data["gyro_x"] + data["gyro_y"] + data["gyro_z"] lines["acc_x"].axes.set_ylim(min(acc_y), max(acc_y)) lines["gyro_x"].axes.set_ylim(min(gyro_y), max(gyro_y)) lines["temperature"].axes.set_ylim(min(data["temperature"][0 : i + 1]), max(data["temperature"][0 : i + 1])) fig.canvas.draw() fig.canvas.flush_events() k4a._stop_imu() k4a.stop() if __name__ == "__main__": main()
[ "numpy.zeros", "matplotlib.pyplot.ion", "matplotlib.pyplot.subplots", "pyk4a.Config" ]
[((717, 726), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (724, 726), True, 'import matplotlib.pyplot as plt\n'), ((743, 772), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)'], {'sharex': '(False)'}), '(3, sharex=False)\n', (755, 772), True, 'import matplotlib.pyplot as plt\n'), ((1151, 1172), 'numpy.zeros', 'np.zeros', (['MAX_SAMPLES'], {}), '(MAX_SAMPLES)\n', (1159, 1172), True, 'import numpy as np\n'), ((514, 647), 'pyk4a.Config', 'Config', ([], {'color_resolution': 'pyk4a.ColorResolution.RES_720P', 'depth_mode': 'pyk4a.DepthMode.NFOV_UNBINNED', 'synchronized_images_only': '(True)'}), '(color_resolution=pyk4a.ColorResolution.RES_720P, depth_mode=pyk4a.\n DepthMode.NFOV_UNBINNED, synchronized_images_only=True)\n', (520, 647), False, 'from pyk4a import Config, PyK4A\n')]
from typing import Union import numpy as np from experiments.utils import sample_uniform_weights from simulation.outcome_generators import OutcomeGenerator, generate_outcome_sw class SmallWorldSimulator(OutcomeGenerator): def __init__( self, id_to_graph_dict: dict, noise_mean: float = 0.0, noise_std: float = 1.0, dim_covariates: int = 20, ): super().__init__( id_to_graph_dict=id_to_graph_dict, noise_mean=noise_mean, noise_std=noise_std, ) self.covariates_weights = sample_uniform_weights( num_weights=3, dim_covariates=dim_covariates ) def set_id_to_graph_dict(self, id_to_graph_dict: dict): self.id_to_graph_dict = id_to_graph_dict def generate_outcomes_for_units( self, units: list, treatment_ids: list ) -> np.ndarray: return self.__generate_outcomes(units=units, treatment_ids=treatment_ids) def generate_outcomes_for_unit(self, unit: list, treatment_ids: list) -> np.ndarray: units = np.repeat(np.expand_dims(unit, axis=0), len(treatment_ids), axis=0) return self.__generate_outcomes(units=units, treatment_ids=treatment_ids) def __generate_outcomes( self, units: Union[list, np.ndarray], treatment_ids: list ) -> np.ndarray: outcomes = [] for covariates, treatment_id in zip(units, treatment_ids): graph_features = self.id_to_graph_dict[treatment_id]["graph_features"] outcome = ( generate_outcome_sw( covariates=covariates, graph_features=graph_features, random_weights=self.covariates_weights, ) + self._sample_noise() ) outcomes.append(outcome) return np.array(outcomes).squeeze()
[ "simulation.outcome_generators.generate_outcome_sw", "experiments.utils.sample_uniform_weights", "numpy.array", "numpy.expand_dims" ]
[((581, 649), 'experiments.utils.sample_uniform_weights', 'sample_uniform_weights', ([], {'num_weights': '(3)', 'dim_covariates': 'dim_covariates'}), '(num_weights=3, dim_covariates=dim_covariates)\n', (603, 649), False, 'from experiments.utils import sample_uniform_weights\n'), ((1086, 1114), 'numpy.expand_dims', 'np.expand_dims', (['unit'], {'axis': '(0)'}), '(unit, axis=0)\n', (1100, 1114), True, 'import numpy as np\n'), ((1555, 1672), 'simulation.outcome_generators.generate_outcome_sw', 'generate_outcome_sw', ([], {'covariates': 'covariates', 'graph_features': 'graph_features', 'random_weights': 'self.covariates_weights'}), '(covariates=covariates, graph_features=graph_features,\n random_weights=self.covariates_weights)\n', (1574, 1672), False, 'from simulation.outcome_generators import OutcomeGenerator, generate_outcome_sw\n'), ((1853, 1871), 'numpy.array', 'np.array', (['outcomes'], {}), '(outcomes)\n', (1861, 1871), True, 'import numpy as np\n')]
"""a bunch of functions to generate fake data""" import numpy as np from scipy.sparse import csr_matrix import scanpy as sc def pancakes(n_pts=100, n_cor=2, n_anticor=2, n_noise=2, minor_fraction=0.5, random_fraction=0.5, marker_fraction=0.9, noise_level=0.1, dropout_clust=True): # split = [0] * int(np.ceil(n_pts * (1 - minor_fraction))) + [1] * int(np.floor(n_pts * minor_fraction)) markers_on = np.random.choice([0, 1], size=(np.floor(n_pts * minor_fraction).astype('int'), n_cor), p=[1 - marker_fraction, marker_fraction]) markers_off = np.random.choice([0, 1], size=(np.ceil(n_pts * (1 - minor_fraction)).astype('int'), n_cor), p=[1 - noise_level, noise_level]) split_dims = np.vstack((markers_on, markers_off)) # split_dims = np.tile(split, (n_anticor,1)) normal_off = np.random.choice([0, 1], size=(np.floor(n_pts * minor_fraction).astype('int'), n_cor), p=[marker_fraction, 1 - marker_fraction]) normal_on = np.random.choice([0, 1], size=(np.ceil(n_pts * (1 - minor_fraction)).astype('int'), n_cor), p=[noise_level, 1 - noise_level]) split_dims = np.vstack((markers_on, markers_off)) off_dims = np.vstack((normal_on, normal_off)) # off = [0]*int(np.floor(n_pts*minor_fraction)) + [1]*int(np.ceil(n_pts *(1-minor_fraction))) # off_dims = np.tile(off, (n_cor, 1)).transpose() noisy_dims = np.random.choice([0, 1], size=(n_noise, n_pts), p=[1 - random_fraction, random_fraction]).transpose() if dropout_clust: mat = np.concatenate((split_dims, off_dims, noisy_dims), axis=1) else: mat = np.concatenate((split_dims, noisy_dims), axis=1) # print(mat.shape) adata = sc.AnnData(csr_matrix(mat)) labs = np.array(['normal'] * adata.shape[0]) labs[:np.floor(n_pts * minor_fraction).astype('int')] = 'rare' if dropout_clust: labs[-1 * np.floor(n_pts * minor_fraction).astype('int'):] = 'dropout' # print(len(labs)) adata.obs['label'] = labs # adata.obs['label'] = [str(x) for x in np.array(split)+np.array(off)] return adata
[ "numpy.ceil", "numpy.floor", "scipy.sparse.csr_matrix", "numpy.array", "numpy.random.choice", "numpy.vstack", "numpy.concatenate" ]
[((784, 820), 'numpy.vstack', 'np.vstack', (['(markers_on, markers_off)'], {}), '((markers_on, markers_off))\n', (793, 820), True, 'import numpy as np\n'), ((1244, 1280), 'numpy.vstack', 'np.vstack', (['(markers_on, markers_off)'], {}), '((markers_on, markers_off))\n', (1253, 1280), True, 'import numpy as np\n'), ((1296, 1330), 'numpy.vstack', 'np.vstack', (['(normal_on, normal_off)'], {}), '((normal_on, normal_off))\n', (1305, 1330), True, 'import numpy as np\n'), ((1849, 1886), 'numpy.array', 'np.array', (["(['normal'] * adata.shape[0])"], {}), "(['normal'] * adata.shape[0])\n", (1857, 1886), True, 'import numpy as np\n'), ((1641, 1699), 'numpy.concatenate', 'np.concatenate', (['(split_dims, off_dims, noisy_dims)'], {'axis': '(1)'}), '((split_dims, off_dims, noisy_dims), axis=1)\n', (1655, 1699), True, 'import numpy as np\n'), ((1724, 1772), 'numpy.concatenate', 'np.concatenate', (['(split_dims, noisy_dims)'], {'axis': '(1)'}), '((split_dims, noisy_dims), axis=1)\n', (1738, 1772), True, 'import numpy as np\n'), ((1820, 1835), 'scipy.sparse.csr_matrix', 'csr_matrix', (['mat'], {}), '(mat)\n', (1830, 1835), False, 'from scipy.sparse import csr_matrix\n'), ((1503, 1596), 'numpy.random.choice', 'np.random.choice', (['[0, 1]'], {'size': '(n_noise, n_pts)', 'p': '[1 - random_fraction, random_fraction]'}), '([0, 1], size=(n_noise, n_pts), p=[1 - random_fraction,\n random_fraction])\n', (1519, 1596), True, 'import numpy as np\n'), ((1897, 1929), 'numpy.floor', 'np.floor', (['(n_pts * minor_fraction)'], {}), '(n_pts * minor_fraction)\n', (1905, 1929), True, 'import numpy as np\n'), ((455, 487), 'numpy.floor', 'np.floor', (['(n_pts * minor_fraction)'], {}), '(n_pts * minor_fraction)\n', (463, 487), True, 'import numpy as np\n'), ((636, 673), 'numpy.ceil', 'np.ceil', (['(n_pts * (1 - minor_fraction))'], {}), '(n_pts * (1 - minor_fraction))\n', (643, 673), True, 'import numpy as np\n'), ((919, 951), 'numpy.floor', 'np.floor', (['(n_pts * minor_fraction)'], {}), '(n_pts * minor_fraction)\n', (927, 951), True, 'import numpy as np\n'), ((1098, 1135), 'numpy.ceil', 'np.ceil', (['(n_pts * (1 - minor_fraction))'], {}), '(n_pts * (1 - minor_fraction))\n', (1105, 1135), True, 'import numpy as np\n'), ((1994, 2026), 'numpy.floor', 'np.floor', (['(n_pts * minor_fraction)'], {}), '(n_pts * minor_fraction)\n', (2002, 2026), True, 'import numpy as np\n')]