code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
""" Script to generate BIDS-compliant events files from the original logfiles Author: <NAME> Mail: <EMAIL> """ import argparse import glob import os import numpy as np import pandas as pd parser = argparse.ArgumentParser(description='Parameters for the logfiles') parser.add_argument('-t', '--type', metavar='SubjectType', default='sub', choices=['sub', 'pilot'], help="Subject type. It can only be 'pilot' or 'sub'. " "Choices: %(choices)s. Default: %(default)s") parser.add_argument('-n', '--number', metavar='SubjectNum', type=int, help="Subject number. It will be formatted as a " "2-digit number (Max. 99)") parser.add_argument('-s', '--session', metavar='SessionNum', type=int, default=1, choices=[1, 2, 3], help="Session number. Choices: %(choices)s. " "Default: %(default)s") args = parser.parse_args() sub_type = args.type sub_num = "%02d" % args.number session = "%02d" % args.session class LogFile: """ Class to hold logfile info. Parameters ---------- path: path to a csv file Absolute or relative path to the logfile. Attributes ---------- path: path to a csv file Absolute or relative path to the logfile task: str Task which the logfile holds data about. Extracted from the filename """ def __init__(self, path: str): self.path = path self.task = self._get_task() def _get_task(self): """ Get task from filename Returns ------- task_name: str name of the task """ task = self.path.strip('.csv').split('_')[-1] return task class StanConverter: """ Opens and modifies a logfile according to BIDS-specification. Parameters ---------- output_path: path to a directory Absolute or relative path to the directory where the new files will be stored Attributes ---------- out_path: path to a directory Absolute or relative path to the directory where the new files will be stored """ def __init__(self, out_path: str): self.out_path = out_path def convert(self, logfile, task): """Calculates onset, duration and trial type of the logfile""" log_df = pd.read_csv(logfile) ttl_trial = log_df[log_df["trial_id"] == "fmri_trigger_wait"].index[0] t0 = log_df.iloc[ttl_trial]["time_elapsed"] task_df = log_df.iloc[ttl_trial:] task_df.reset_index(inplace=True) task_df["onset"] = task_df["time_elapsed"] - t0 task_df["duration"] = task_df["onset"].shift(-1) - task_df["onset"] task_df["onset"] /= 1000 task_df["duration"] /= 1000 # Specific task operations conv_df = self.convert_task(task_df, task) if task == 'DiscountFixed': columns = ["onset", "duration", "trial_type", "large_amount", "later_delay"] elif task == 'CardTaskHot': columns = ["onset", "duration", "trial_type", "gain_amount", "loss_amount", "num_loss_cards"] else: columns = ["onset", "duration", "trial_type"] # We remove the last row becase it is after the experiment ends shift_columns = ~conv_df.columns.isin(["onset", "duration"]) conv_df.loc[:, shift_columns] = conv_df.loc[:, shift_columns].shift(-1) conv_df = conv_df[columns][:-2] return conv_df def convert_task(self, logfile, task: str): converter = self._get_converter(task) return converter(logfile) def _get_converter(self, task: str): if task == 'StopSignal': return self._convert_ss elif task == 'Attention': return self._convert_ant elif task == 'TwobyTwo': return self._convert_twobytwo elif task == 'MotorSelectiveStopSignal': return self._convert_ms_ss elif task == 'Stroop': return self._convert_stroop elif task == 'DiscountFixed': return self._convert_discount_fixed elif task == 'Tower': return self._convert_towertask elif task == 'CardTaskHot': return self._convert_cardtask elif task == 'DotPatternExpectancy': return self._convert_dpx else: raise ValueError("{0} is not a valid task".format(task)) @staticmethod def _convert_ss(logfile): """Converter for the stop_signal task""" logfile['trial_type'] = np.where(logfile['trial_id'] == 'stim', logfile['SS_trial_type'], logfile['trial_id']) return logfile @staticmethod def _convert_ant(logfile): """Converter for the attention_network_task""" logfile['trial_type'] = np.where(logfile['trial_id'] == 'stim', logfile['cue'] + "_" + logfile['flanker_type'], logfile['trial_id']) return logfile @staticmethod def _convert_twobytwo(logfile): """Converter for the twobytwo task""" logfile['trial_type'] = np.where(logfile['trial_id'] == 'stim', "task" + logfile['task_switch'] + "_cue" + logfile['cue_switch'], logfile['trial_id']) return logfile @staticmethod def _convert_ms_ss(logfile): """Converter for the motor_selective_SS task""" logfile['trial_type'] = np.where(logfile['trial_id'] == 'stim', logfile['condition'], logfile['trial_id']) # We remove the last row becase it is after the experiment ends conv_df = logfile[["onset", "duration", "trial_type"]][:-1] return logfile @staticmethod def _convert_stroop(logfile): """Converter for the stroop task""" logfile['trial_type'] = np.where(logfile['trial_id'] == 'stim', logfile['condition'], logfile['trial_id']) return logfile @staticmethod def _convert_discount_fixed(logfile): """Converter for discount_fixed""" logfile.replace(np.nan, 'stim', regex=True, inplace=True) logfile['trial_type'] = logfile['trial_id'] return logfile @staticmethod def _convert_towertask(logfile): """Converter for towertask""" condition = np.logical_or(logfile['trial_id'] == 'to_hand', logfile['trial_id'] == 'to_board') logfile['trial_type'] = np.where(condition, logfile['condition'], np.where(logfile['trial_id'] == 'feedback', 'trial_end_and_next_start', logfile['trial_id'])) return logfile @staticmethod def _convert_cardtask(logfile): """Converter for Columbia card task hot""" logfile['trial_type'] = np.where(logfile['trial_id'] == 'stim', 'card_flip', np.where(logfile['trial_id'] == 'ITI', 'inter_trials', logfile['trial_id'])) return logfile @staticmethod def _convert_dpx(logfile): """Converter for dot_pattern_expectancy""" condition = np.logical_or(logfile['trial_id'] == 'cue', logfile['trial_id'] == 'probe') logfile['trial_type'] = np.where(condition, logfile['trial_id'] + "_" + logfile['condition'], logfile['trial_id']) return logfile def save_log(self, path, df): """Saves the logfile as .tsv""" log_pieces = os.path.basename(path).replace('.csv', '').split('_') log_name = log_pieces[0] + "_task-" + \ log_pieces[-1] + "_run" + \ log_pieces[-2] + "_events.tsv" df.to_csv(os.path.join(self.out_path, log_name), index=False, sep='\t') base_path = os.getcwd() input_path = os.path.join(base_path, 'logfiles') output_path = os.path.join(base_path, 'events_files') glob_string = sub_type + "-" + sub_num + "_ses-" + session + "*" logfiles = [LogFile(logfile) for logfile in glob.glob(os.path.join(input_path, glob_string))] converter = StanConverter(output_path) for logfile in logfiles: bids_df = converter.convert(logfile.path, logfile.task) converter.save_log(logfile.path, bids_df) # if __name__ == '__main__': # main()
[ "argparse.ArgumentParser", "os.path.basename", "os.getcwd", "pandas.read_csv", "numpy.where", "numpy.logical_or", "os.path.join" ]
[((201, 267), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Parameters for the logfiles"""'}), "(description='Parameters for the logfiles')\n", (224, 267), False, 'import argparse\n'), ((8805, 8816), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8814, 8816), False, 'import os\n'), ((8830, 8865), 'os.path.join', 'os.path.join', (['base_path', '"""logfiles"""'], {}), "(base_path, 'logfiles')\n", (8842, 8865), False, 'import os\n'), ((8880, 8919), 'os.path.join', 'os.path.join', (['base_path', '"""events_files"""'], {}), "(base_path, 'events_files')\n", (8892, 8919), False, 'import os\n'), ((2473, 2493), 'pandas.read_csv', 'pd.read_csv', (['logfile'], {}), '(logfile)\n', (2484, 2493), True, 'import pandas as pd\n'), ((4750, 4841), 'numpy.where', 'np.where', (["(logfile['trial_id'] == 'stim')", "logfile['SS_trial_type']", "logfile['trial_id']"], {}), "(logfile['trial_id'] == 'stim', logfile['SS_trial_type'], logfile[\n 'trial_id'])\n", (4758, 4841), True, 'import numpy as np\n'), ((5081, 5194), 'numpy.where', 'np.where', (["(logfile['trial_id'] == 'stim')", "(logfile['cue'] + '_' + logfile['flanker_type'])", "logfile['trial_id']"], {}), "(logfile['trial_id'] == 'stim', logfile['cue'] + '_' + logfile[\n 'flanker_type'], logfile['trial_id'])\n", (5089, 5194), True, 'import numpy as np\n'), ((5471, 5601), 'numpy.where', 'np.where', (["(logfile['trial_id'] == 'stim')", "('task' + logfile['task_switch'] + '_cue' + logfile['cue_switch'])", "logfile['trial_id']"], {}), "(logfile['trial_id'] == 'stim', 'task' + logfile['task_switch'] +\n '_cue' + logfile['cue_switch'], logfile['trial_id'])\n", (5479, 5601), True, 'import numpy as np\n'), ((5886, 5973), 'numpy.where', 'np.where', (["(logfile['trial_id'] == 'stim')", "logfile['condition']", "logfile['trial_id']"], {}), "(logfile['trial_id'] == 'stim', logfile['condition'], logfile[\n 'trial_id'])\n", (5894, 5973), True, 'import numpy as np\n'), ((6346, 6433), 'numpy.where', 'np.where', (["(logfile['trial_id'] == 'stim')", "logfile['condition']", "logfile['trial_id']"], {}), "(logfile['trial_id'] == 'stim', logfile['condition'], logfile[\n 'trial_id'])\n", (6354, 6433), True, 'import numpy as np\n'), ((6897, 6983), 'numpy.logical_or', 'np.logical_or', (["(logfile['trial_id'] == 'to_hand')", "(logfile['trial_id'] == 'to_board')"], {}), "(logfile['trial_id'] == 'to_hand', logfile['trial_id'] ==\n 'to_board')\n", (6910, 6983), True, 'import numpy as np\n'), ((8035, 8110), 'numpy.logical_or', 'np.logical_or', (["(logfile['trial_id'] == 'cue')", "(logfile['trial_id'] == 'probe')"], {}), "(logfile['trial_id'] == 'cue', logfile['trial_id'] == 'probe')\n", (8048, 8110), True, 'import numpy as np\n'), ((8177, 8271), 'numpy.where', 'np.where', (['condition', "(logfile['trial_id'] + '_' + logfile['condition'])", "logfile['trial_id']"], {}), "(condition, logfile['trial_id'] + '_' + logfile['condition'],\n logfile['trial_id'])\n", (8185, 8271), True, 'import numpy as np\n'), ((7170, 7266), 'numpy.where', 'np.where', (["(logfile['trial_id'] == 'feedback')", '"""trial_end_and_next_start"""', "logfile['trial_id']"], {}), "(logfile['trial_id'] == 'feedback', 'trial_end_and_next_start',\n logfile['trial_id'])\n", (7178, 7266), True, 'import numpy as np\n'), ((7712, 7787), 'numpy.where', 'np.where', (["(logfile['trial_id'] == 'ITI')", '"""inter_trials"""', "logfile['trial_id']"], {}), "(logfile['trial_id'] == 'ITI', 'inter_trials', logfile['trial_id'])\n", (7720, 7787), True, 'import numpy as np\n'), ((8729, 8766), 'os.path.join', 'os.path.join', (['self.out_path', 'log_name'], {}), '(self.out_path, log_name)\n', (8741, 8766), False, 'import os\n'), ((9052, 9089), 'os.path.join', 'os.path.join', (['input_path', 'glob_string'], {}), '(input_path, glob_string)\n', (9064, 9089), False, 'import os\n'), ((8512, 8534), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (8528, 8534), False, 'import os\n')]
# Copyright 2016 Google Inc. All Rights Reserved. # # 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. # ============================================================================== #!/usr/bin/env python2.7 """Send JPEG image to tensorflow_model_server loaded with inception model. """ from __future__ import print_function # This is a placeholder for a Google-internal import. from grpc.beta import implementations import tensorflow as tf from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_service_pb2 import skimage import skimage.io import skimage.transform import numpy as np import time tf.app.flags.DEFINE_string('server', 'localhost:9000', 'PredictionService host:port') tf.app.flags.DEFINE_string('image', '', 'path to image in JPEG format') FLAGS = tf.app.flags.FLAGS def load_image(path): # load image img = skimage.io.imread(path) img = img / 255.0 assert (0 <= img).all() and (img <= 1.0).all() # print "Original Image Shape: ", img.shape # we crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy: yy + short_edge, xx: xx + short_edge] # resize to 224, 224 resized_img = skimage.transform.resize(crop_img, (224, 224)) return resized_img def print_prob(prob, file_path): synset = [l.strip() for l in open(file_path).readlines()] # print prob pred = np.argsort(prob)[::-1] # Get top1 label top1 = synset[pred[0]] print(("Top1: ", top1, prob[pred[0]])) # Get top5 label top5 = [(synset[pred[i]], prob[pred[i]]) for i in range(5)] print(("Top5: ", top5)) return top1 # def get_batch(batch_size): # img = load_image("/home/yitao/Documents/fun-project/tensorflow-vgg/test_data/tiger.jpeg").reshape((1, 224, 224, 3)) # batch = np.concatenate((img, img, img), 0) # return batch # def get_batch(batch_size): # images = [] # for i in range(batch_size): # img = load_image("/home/yitao/Documents/fun-project/tensorflow-vgg/test_data/tiger.jpeg") # images.append(img.reshape((1, 224, 224, 3))) # batch = np.concatenate(images, 0) # return batch def myFuncWarmUp(stub, i): request = predict_pb2.PredictRequest() request.model_spec.name = 'vgg_model' request.model_spec.signature_name = 'predict_images' batchSize = 1 durationSum = 0.0 runNum = 13 for k in range(runNum): image_data = [] start = time.time() for j in range(batchSize): image_name = "/home/yitao/Downloads/inception-input/%s/dog-%s.jpg" % (str(i % 100).zfill(3), str(j).zfill(3)) img = load_image(image_name) image_data.append(img.reshape((1, 224, 224, 3))) batch = np.concatenate(image_data, 0) # print(batch.shape) request.inputs['images'].CopyFrom( tf.contrib.util.make_tensor_proto(np.float32(image_data[0]), shape=[batchSize, 224, 224, 3])) tmp_result = stub.Predict(request, 10.0) # 5 seconds # print(len(tmp_result.outputs["scores"].float_val)) end = time.time() duration = (end - start) print("it takes %s sec" % str(duration)) if (k != 0 and k != 3 and k != 8): durationSum += duration print("[Warm up] on average, it takes %s sec to run a batch of %d images over %d runs" % (str(durationSum / (runNum - 3)), batchSize, (runNum - 3))) def main(_): host, port = FLAGS.server.split(':') channel = implementations.insecure_channel(host, int(port)) stub = prediction_service_pb2.beta_create_PredictionService_stub(channel) myFuncWarmUp(stub, 0) if __name__ == '__main__': tf.app.run()
[ "numpy.concatenate", "tensorflow_serving.apis.predict_pb2.PredictRequest", "numpy.float32", "time.time", "numpy.argsort", "tensorflow_serving.apis.prediction_service_pb2.beta_create_PredictionService_stub", "skimage.transform.resize", "tensorflow.app.flags.DEFINE_string", "tensorflow.app.run", "sk...
[((1140, 1229), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""server"""', '"""localhost:9000"""', '"""PredictionService host:port"""'], {}), "('server', 'localhost:9000',\n 'PredictionService host:port')\n", (1166, 1229), True, 'import tensorflow as tf\n'), ((1253, 1324), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""image"""', '""""""', '"""path to image in JPEG format"""'], {}), "('image', '', 'path to image in JPEG format')\n", (1279, 1324), True, 'import tensorflow as tf\n'), ((1403, 1426), 'skimage.io.imread', 'skimage.io.imread', (['path'], {}), '(path)\n', (1420, 1426), False, 'import skimage\n'), ((1812, 1858), 'skimage.transform.resize', 'skimage.transform.resize', (['crop_img', '(224, 224)'], {}), '(crop_img, (224, 224))\n', (1836, 1858), False, 'import skimage\n'), ((2789, 2817), 'tensorflow_serving.apis.predict_pb2.PredictRequest', 'predict_pb2.PredictRequest', ([], {}), '()\n', (2815, 2817), False, 'from tensorflow_serving.apis import predict_pb2\n'), ((4037, 4103), 'tensorflow_serving.apis.prediction_service_pb2.beta_create_PredictionService_stub', 'prediction_service_pb2.beta_create_PredictionService_stub', (['channel'], {}), '(channel)\n', (4094, 4103), False, 'from tensorflow_serving.apis import prediction_service_pb2\n'), ((4160, 4172), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (4170, 4172), True, 'import tensorflow as tf\n'), ((2007, 2023), 'numpy.argsort', 'np.argsort', (['prob'], {}), '(prob)\n', (2017, 2023), True, 'import numpy as np\n'), ((3023, 3034), 'time.time', 'time.time', ([], {}), '()\n', (3032, 3034), False, 'import time\n'), ((3284, 3313), 'numpy.concatenate', 'np.concatenate', (['image_data', '(0)'], {}), '(image_data, 0)\n', (3298, 3313), True, 'import numpy as np\n'), ((3606, 3617), 'time.time', 'time.time', ([], {}), '()\n', (3615, 3617), False, 'import time\n'), ((3420, 3445), 'numpy.float32', 'np.float32', (['image_data[0]'], {}), '(image_data[0])\n', (3430, 3445), True, 'import numpy as np\n')]
""" File: eval_npy.py Created by: <NAME> Email: <EMAIL><at>gmail<dot>com """ import sys import os from optparse import OptionParser import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.functional as F from torch import optim from torch.optim import lr_scheduler from unet import UNet from hednet import HNNNet from utils import get_images from dataset import IDRIDDataset from torchvision import datasets, models, transforms from transform.transforms_group import * from torch.utils.data import DataLoader, Dataset import copy from logger import Logger import os from dice_loss import dice_loss, dice_coeff from tqdm import tqdm import matplotlib.pyplot as plt device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") parser = OptionParser() parser.add_option('-b', '--batch-size', dest='batchsize', default=2, type='int', help='batch size') parser.add_option('-p', '--log-dir', dest='logdir', default='eval', type='str', help='tensorboard log') parser.add_option('-m', '--model', dest='model', default='MODEL.pth.tar', type='str', help='models stored') parser.add_option('-n', '--net-name', dest='netname', default='unet', type='str', help='net name, unet or hednet') parser.add_option('-g', '--preprocess', dest='preprocess', action='store_true', default=False, help='preprocess input images') (args, _) = parser.parse_args() logger = Logger('./logs', args.logdir) net_name = args.netname lesions = ['ex', 'he', 'ma', 'se'] image_size = 512 image_dir = '/home/qiqix/SegmentationSub1' logdir = args.logdir if not os.path.exists(logdir): os.mkdir(logdir) softmax = nn.Softmax(1) def eval_model(model, eval_loader): model.to(device=device) model.eval() eval_tot = len(eval_loader) dice_coeffs_soft = np.zeros(4) dice_coeffs_hard = np.zeros(4) vis_images = [] with torch.set_grad_enabled(False): batch_id = 0 for inputs, true_masks in tqdm(eval_loader): inputs = inputs.to(device=device, dtype=torch.float) true_masks = true_masks.to(device=device, dtype=torch.float) bs, _, h, w = inputs.shape h_size = (h-1) // image_size + 1 w_size = (w-1) // image_size + 1 masks_pred = torch.zeros(true_masks.shape).to(dtype=torch.float) for i in range(h_size): for j in range(w_size): h_max = min(h, (i+1)*image_size) w_max = min(w, (j+1)*image_size) inputs_part = inputs[:,:, i*image_size:h_max, j*image_size:w_max] if net_name == 'unet': masks_pred[:, :, i*image_size:h_max, j*image_size:w_max] = model(inputs_part).to("cpu") elif net_name == 'hednet': masks_pred[:, :, i*image_size:h_max, j*image_size:w_max] = model(inputs_part)[-1].to("cpu") masks_pred_softmax = softmax(masks_pred) masks_max, _ = torch.max(masks_pred_softmax, 1) masks_soft = masks_pred_softmax[:, 1:-1, :, :] np.save(os.path.join(logdir, 'mask_soft_'+str(batch_id)+'.npy'), masks_soft.numpy()) np.save(os.path.join(logdir, 'mask_true_'+str(batch_id)+'.npy'), true_masks[:,1:-1].cpu().numpy()) masks_hard = (masks_pred_softmax == masks_max[:, None, :, :]).to(dtype=torch.float)[:, 1:-1, :, :] dice_coeffs_soft += dice_coeff(masks_soft, true_masks[:, 1:-1, :, :].to("cpu")) dice_coeffs_hard += dice_coeff(masks_hard, true_masks[:, 1:-1, :, :].to("cpu")) images_batch = generate_log_images_full(inputs, true_masks[:, 1:-1], masks_soft, masks_hard) images_batch = images_batch.to("cpu").numpy() vis_images.extend(images_batch) batch_id += 1 return dice_coeffs_soft / eval_tot, dice_coeffs_hard / eval_tot, vis_images def denormalize(inputs): if net_name == 'unet': return (inputs * 255.).to(device=device, dtype=torch.uint8) else: mean = torch.FloatTensor([0.485, 0.456, 0.406]).to(device) std = torch.FloatTensor([0.229, 0.224, 0.225]).to(device) return ((inputs * std[None, :, None, None] + mean[None, :, None, None])*255.).to(device=device, dtype=torch.uint8) def generate_log_images_full(inputs, true_masks, masks_soft, masks_hard): true_masks = (true_masks * 255.).to(device=device, dtype=torch.uint8) masks_soft = (masks_soft * 255.).to(device=device, dtype=torch.uint8) masks_hard = (masks_hard * 255.).to(device=device, dtype=torch.uint8) inputs = denormalize(inputs) bs, _, h, w = inputs.shape pad_size = 5 images_batch = (torch.ones((bs, 3, h*2+pad_size, w*2+pad_size)) * 255.).to(device=device, dtype=torch.uint8) images_batch[:, :, :h, :w] = inputs images_batch[:, :, :h, w+pad_size:] = true_masks[:, 3, :, :][:, None, :, :] images_batch[:, 0, :h, w+pad_size:] += true_masks[:, 0, :, :] images_batch[:, 1, :h, w+pad_size:] += true_masks[:, 1, :, :] images_batch[:, 2, :h, w+pad_size:] += true_masks[:, 2, :, :] images_batch[:, :, h+pad_size:, :w] = masks_soft[:, 3, :, :][:, None, :, :] images_batch[:, 0, h+pad_size:, :w] += masks_soft[:, 0, :, :] images_batch[:, 1, h+pad_size:, :w] += masks_soft[:, 1, :, :] images_batch[:, 2, h+pad_size:, :w] += masks_soft[:, 2, :, :] images_batch[:, :, h+pad_size:, w+pad_size:] = masks_hard[:, 3, :, :][:, None, :, :] images_batch[:, 0, h+pad_size:, w+pad_size:] += masks_hard[:, 0, :, :] images_batch[:, 1, h+pad_size:, w+pad_size:] += masks_hard[:, 1, :, :] images_batch[:, 2, h+pad_size:, w+pad_size:] += masks_hard[:, 2, :, :] return images_batch if __name__ == '__main__': if net_name == 'unet': model = UNet(n_channels=3, n_classes=6) else: model = HNNNet(pretrained=True, class_number=6) if os.path.isfile(args.model): print("=> loading checkpoint '{}'".format(args.model)) checkpoint = torch.load(args.model) model.load_state_dict(checkpoint['state_dict']) print('Model loaded from {}'.format(args.model)) else: print("=> no checkpoint found at '{}'".format(args.model)) sys.exit(0) eval_image_paths, eval_mask_paths = get_images(image_dir, args.preprocess, phase='test') if net_name == 'unet': eval_dataset = IDRIDDataset(eval_image_paths, eval_mask_paths, 4, transform= Compose([ ])) elif net_name == 'hednet': eval_dataset = IDRIDDataset(eval_image_paths, eval_mask_paths, 4, transform= Compose([ Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ])) eval_loader = DataLoader(eval_dataset, args.batchsize, shuffle=False) dice_coeffs_soft, dice_coeffs_hard, vis_images = eval_model(model, eval_loader) print(dice_coeffs_soft, dice_coeffs_hard) #logger.image_summary('eval_images', vis_images, step=0)
[ "os.mkdir", "optparse.OptionParser", "os.path.isfile", "torch.nn.Softmax", "torch.ones", "torch.utils.data.DataLoader", "torch.load", "os.path.exists", "torch.FloatTensor", "hednet.HNNNet", "torch.zeros", "tqdm.tqdm", "torch.cuda.is_available", "torch.max", "torch.set_grad_enabled", "s...
[((800, 814), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (812, 814), False, 'from optparse import OptionParser\n'), ((1516, 1545), 'logger.Logger', 'Logger', (['"""./logs"""', 'args.logdir'], {}), "('./logs', args.logdir)\n", (1522, 1545), False, 'from logger import Logger\n'), ((1750, 1763), 'torch.nn.Softmax', 'nn.Softmax', (['(1)'], {}), '(1)\n', (1760, 1763), True, 'import torch.nn as nn\n'), ((1694, 1716), 'os.path.exists', 'os.path.exists', (['logdir'], {}), '(logdir)\n', (1708, 1716), False, 'import os\n'), ((1722, 1738), 'os.mkdir', 'os.mkdir', (['logdir'], {}), '(logdir)\n', (1730, 1738), False, 'import os\n'), ((1900, 1911), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1908, 1911), True, 'import numpy as np\n'), ((1935, 1946), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1943, 1946), True, 'import numpy as np\n'), ((6037, 6063), 'os.path.isfile', 'os.path.isfile', (['args.model'], {}), '(args.model)\n', (6051, 6063), False, 'import os\n'), ((6423, 6475), 'utils.get_images', 'get_images', (['image_dir', 'args.preprocess'], {'phase': '"""test"""'}), "(image_dir, args.preprocess, phase='test')\n", (6433, 6475), False, 'from utils import get_images\n'), ((6953, 7008), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_dataset', 'args.batchsize'], {'shuffle': '(False)'}), '(eval_dataset, args.batchsize, shuffle=False)\n', (6963, 7008), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((753, 778), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (776, 778), False, 'import torch\n'), ((1981, 2010), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (2003, 2010), False, 'import torch\n'), ((2067, 2084), 'tqdm.tqdm', 'tqdm', (['eval_loader'], {}), '(eval_loader)\n', (2071, 2084), False, 'from tqdm import tqdm\n'), ((5927, 5958), 'unet.UNet', 'UNet', ([], {'n_channels': '(3)', 'n_classes': '(6)'}), '(n_channels=3, n_classes=6)\n', (5931, 5958), False, 'from unet import UNet\n'), ((5985, 6024), 'hednet.HNNNet', 'HNNNet', ([], {'pretrained': '(True)', 'class_number': '(6)'}), '(pretrained=True, class_number=6)\n', (5991, 6024), False, 'from hednet import HNNNet\n'), ((6149, 6171), 'torch.load', 'torch.load', (['args.model'], {}), '(args.model)\n', (6159, 6171), False, 'import torch\n'), ((6370, 6381), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (6378, 6381), False, 'import sys\n'), ((3105, 3137), 'torch.max', 'torch.max', (['masks_pred_softmax', '(1)'], {}), '(masks_pred_softmax, 1)\n', (3114, 3137), False, 'import torch\n'), ((4165, 4205), 'torch.FloatTensor', 'torch.FloatTensor', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (4182, 4205), False, 'import torch\n'), ((4231, 4271), 'torch.FloatTensor', 'torch.FloatTensor', (['[0.229, 0.224, 0.225]'], {}), '([0.229, 0.224, 0.225])\n', (4248, 4271), False, 'import torch\n'), ((4804, 4859), 'torch.ones', 'torch.ones', (['(bs, 3, h * 2 + pad_size, w * 2 + pad_size)'], {}), '((bs, 3, h * 2 + pad_size, w * 2 + pad_size))\n', (4814, 4859), False, 'import torch\n'), ((2378, 2407), 'torch.zeros', 'torch.zeros', (['true_masks.shape'], {}), '(true_masks.shape)\n', (2389, 2407), False, 'import torch\n')]
import torch import numpy as np import schnetpack as spk class MeanSquaredError(spk.metrics.MeanSquaredError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'MSE_' + target if name is None else name super(MeanSquaredError, self).__init__(target, model_output=model_output, bias_correction=bias_correction, name=name, element_wise=element_wise) def _get_diff(self, y, yp): diff = y - yp diff = (torch.abs(diff)) if self.bias_correction is not None: diff += self.bias_correction return diff class RootMeanSquaredError(MeanSquaredError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'RMSE_' + target if name is None else name super(RootMeanSquaredError, self).__init__(target, model_output, bias_correction, name, element_wise=element_wise) def aggregate(self): return np.sqrt(self.l2loss / self.n_entries) class MeanAbsoluteError(spk.metrics.MeanAbsoluteError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'MAE_' + target if name is None else name super(MeanAbsoluteError, self).__init__(target, model_output=model_output, bias_correction=bias_correction, name=name, element_wise=element_wise) def _get_diff(self, y, yp): diff = y - yp diff = (torch.abs(diff)) if self.bias_correction is not None: diff += self.bias_correction return diff class PhaseMeanSquaredError(spk.metrics.MeanSquaredError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'PhMSE_' + target if name is None else name super(PhaseMeanSquaredError, self).__init__(target, model_output=model_output, bias_correction=bias_correction, name=name, element_wise=element_wise) def _get_diff(self, y, yp): diff_a = torch.abs(y - yp) diff_b = torch.abs(y + yp) diff = torch.min(diff_a, diff_b) if self.bias_correction is not None: diff += self.bias_correction return diff class PhaseRootMeanSquaredError(PhaseMeanSquaredError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'PhRMSE_' + target if name is None else name super(PhaseRootMeanSquaredError, self).__init__(target, model_output, bias_correction, name, element_wise=element_wise) def aggregate(self): return np.sqrt(self.l2loss / self.n_entries) class PhaseMeanAbsoluteError(spk.metrics.MeanAbsoluteError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'PhMAE_' + target if name is None else name super(PhaseMeanAbsoluteError, self).__init__(target, model_output=model_output, bias_correction=bias_correction, name=name, element_wise=element_wise) def _get_diff(self, y, yp): diff_a = torch.abs(y - yp) diff_b = torch.abs(y + yp) diff = torch.min(diff_a, diff_b) if self.bias_correction is not None: diff += self.bias_correction return diff class PhaseRootMeanSquaredError_vec(PhaseMeanSquaredError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'PhRMSE_' + target if name is None else name super(PhaseRootMeanSquaredError_vec, self).__init__(target, model_output, bias_correction, name, element_wise=element_wise) def aggregate(self): return np.sqrt(self.l2loss / self.n_entries) class PhaseMeanAbsoluteError_vec(spk.metrics.MeanAbsoluteError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'PhMAE_' + target if name is None else name super(PhaseMeanAbsoluteError_vec, self).__init__(target, model_output=model_output, bias_correction=bias_correction, name=name, element_wise=element_wise) def _get_diff(self, y, yp): #assume that each state combination was found successfully diff = 0. for batch_sample in range(y.shape[0]): for istate_combi in range(y.shape[1]): diff_a = (y[batch_sample,istate_combi,:,:] - yp[batch_sample,istate_combi,:,:] ) diff_b = (y[batch_sample,istate_combi,:,:] + yp[batch_sample,istate_combi,:,:] ) mean_a = torch.mean(torch.abs(diff_a)) mean_b = torch.mean(torch.abs(diff_b)) if mean_a <= mean_b: diff += diff_a else: diff += diff_b if self.bias_correction is not None: diff += self.bias_correction diff = diff/(y.shape[0]*y.shape[1]) return diff class PhaseMeanSquaredError_vec(spk.metrics.MeanSquaredError): def __init__(self, target, model_output=None, bias_correction=None, name=None, element_wise=False): name = 'PhMSE_' + target if name is None else name super(PhaseMeanSquaredError_vec, self).__init__(target, model_output=model_output, bias_correction=bias_correction, name=name, element_wise=element_wise) def _get_diff(self, y, yp): #assume that each state combination was found successfully diff = 0. for batch_sample in range(y.shape[0]): for istate_combi in range(y.shape[1]): diff_a = (y[batch_sample,istate_combi,:,:] - yp[batch_sample,istate_combi,:,:] ) diff_b = (y[batch_sample,istate_combi,:,:] + yp[batch_sample,istate_combi,:,:] ) mean_a = torch.mean((diff_a)**2) mean_b = torch.mean((diff_b)**2) if mean_a <= mean_b: diff += diff_a**(1/2) else: diff += diff_b**(1/2) if self.bias_correction is not None: diff += self.bias_correction diff = (diff/(y.shape[0]*y.shape[1]))**2 return diff
[ "torch.mean", "torch.abs", "torch.min", "numpy.sqrt" ]
[((569, 584), 'torch.abs', 'torch.abs', (['diff'], {}), '(diff)\n', (578, 584), False, 'import torch\n'), ((1196, 1233), 'numpy.sqrt', 'np.sqrt', (['(self.l2loss / self.n_entries)'], {}), '(self.l2loss / self.n_entries)\n', (1203, 1233), True, 'import numpy as np\n'), ((1749, 1764), 'torch.abs', 'torch.abs', (['diff'], {}), '(diff)\n', (1758, 1764), False, 'import torch\n'), ((2374, 2391), 'torch.abs', 'torch.abs', (['(y - yp)'], {}), '(y - yp)\n', (2383, 2391), False, 'import torch\n'), ((2409, 2426), 'torch.abs', 'torch.abs', (['(y + yp)'], {}), '(y + yp)\n', (2418, 2426), False, 'import torch\n'), ((2442, 2467), 'torch.min', 'torch.min', (['diff_a', 'diff_b'], {}), '(diff_a, diff_b)\n', (2451, 2467), False, 'import torch\n'), ((3095, 3132), 'numpy.sqrt', 'np.sqrt', (['(self.l2loss / self.n_entries)'], {}), '(self.l2loss / self.n_entries)\n', (3102, 3132), True, 'import numpy as np\n'), ((3639, 3656), 'torch.abs', 'torch.abs', (['(y - yp)'], {}), '(y - yp)\n', (3648, 3656), False, 'import torch\n'), ((3674, 3691), 'torch.abs', 'torch.abs', (['(y + yp)'], {}), '(y + yp)\n', (3683, 3691), False, 'import torch\n'), ((3707, 3732), 'torch.min', 'torch.min', (['diff_a', 'diff_b'], {}), '(diff_a, diff_b)\n', (3716, 3732), False, 'import torch\n'), ((4366, 4403), 'numpy.sqrt', 'np.sqrt', (['(self.l2loss / self.n_entries)'], {}), '(self.l2loss / self.n_entries)\n', (4373, 4403), True, 'import numpy as np\n'), ((6562, 6585), 'torch.mean', 'torch.mean', (['(diff_a ** 2)'], {}), '(diff_a ** 2)\n', (6572, 6585), False, 'import torch\n'), ((6611, 6634), 'torch.mean', 'torch.mean', (['(diff_b ** 2)'], {}), '(diff_b ** 2)\n', (6621, 6634), False, 'import torch\n'), ((5314, 5331), 'torch.abs', 'torch.abs', (['diff_a'], {}), '(diff_a)\n', (5323, 5331), False, 'import torch\n'), ((5369, 5386), 'torch.abs', 'torch.abs', (['diff_b'], {}), '(diff_b)\n', (5378, 5386), False, 'import torch\n')]
from ._common import * from sklearn.metrics import roc_curve import numpy as np def _inner_roc_optimal_threshold(curve): dsts = curve[0] ** 2 + (1 - curve[1]) ** 2 argmin = np.argmin(dsts) val = curve[2][argmin] return curve[0][argmin], curve[1][argmin], val def roc_optimal_threshold(y_true, y_pred): curve = roc_curve(y_true, y_pred) _, __, val = _inner_roc_optimal_threshold(curve) return val def roc_plot(true,predicted, name=None, number_fmt='{:.2f}',ax=None): ax = default_ax(ax) curve = roc_curve(true,predicted) ax.plot(curve[0], curve[1],label=name) ax.set_xlabel('TPR') ax.set_ylabel('FPR') x, y, val = _inner_roc_optimal_threshold(curve) ax.scatter(x,y) ax.text(x,y,number_fmt.format(val),ha='left',va='top')
[ "sklearn.metrics.roc_curve", "numpy.argmin" ]
[((183, 198), 'numpy.argmin', 'np.argmin', (['dsts'], {}), '(dsts)\n', (192, 198), True, 'import numpy as np\n'), ((333, 358), 'sklearn.metrics.roc_curve', 'roc_curve', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (342, 358), False, 'from sklearn.metrics import roc_curve\n'), ((534, 560), 'sklearn.metrics.roc_curve', 'roc_curve', (['true', 'predicted'], {}), '(true, predicted)\n', (543, 560), False, 'from sklearn.metrics import roc_curve\n')]
import numpy as np from typing import Tuple, Callable def get_velocity_sets() -> np.ndarray: """ Get velocity set. Note that the length of the discrete velocities can be different. Returns: velocity set """ return np.array( [ [0, 0], [1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, 1], [-1, -1], [1, -1] ] ) def vel_to_opp_vel_mapping() -> np.ndarray: """ Opposite direction Returns: array with opposite directions of D2Q9 """ return np.array( [0, 3, 4, 1, 2, 7, 8, 5, 6] ) def get_w_i() -> np.ndarray: """ Return weights defined for a D2Q9 lattice. The weighting takes the different lengths of the discrete velocities of the velocity set into account. Returns: weights defined for a D2Q9 lattice """ return np.array( [4 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 36, 1 / 36, 1 / 36, 1 / 36] ) def reynolds_number(L: int, u: float, v: float) -> float: """ Compute the Reynolds number Args: L: characteristic length u: flow velocity v: kinematic viscosity Returns: Reynolds number """ return np.divide( L * u, v ) def strouhal_number(f: float, L: int, u: float) -> float: """ Computes the Strouhal number Args: f: vortex frequency L: characteristic length u: flow velocity Returns: Strouhal number """ return np.divide( f * L, u ) def compute_density(prob_densitiy_func: np.ndarray) -> np.ndarray: """ Compute local density Args: prob_densitiy_func: probability density function f(r,v,t) Returns: density given the probability density function """ assert prob_densitiy_func.shape[-1] == 9 return np.sum(prob_densitiy_func, axis=-1) def compute_velocity_field(density_func: np.ndarray, prob_density_func: np.ndarray) -> np.ndarray: """ Computes the velocity field Args: density_func: density rho(x) prob_density_func: probability density function f(r,v,t) Returns: velocity field given the density and probability density function """ assert prob_density_func.shape[-1] == 9 ux = np.divide( np.sum(prob_density_func[:, :, [1, 5, 8]], axis=2) - np.sum(prob_density_func[:, :, [3, 6, 7]], axis=2), density_func, out=np.zeros_like(density_func), where=density_func != 0 ) uy = np.divide( np.sum(prob_density_func[:, :, [2, 5, 6]], axis=2) - np.sum(prob_density_func[:, :, [4, 7, 8]], axis=2), density_func, out=np.zeros_like(density_func), where=density_func != 0 ) u = np.dstack((ux, uy)) return u def streaming(prob_density_func: np.ndarray) -> np.ndarray: """ Implements the streaming operator Args: prob_density_func: probability density function f(r,v,t) Returns: new probability density function after streaming """ assert prob_density_func.shape[-1] == 9 velocity_set = get_velocity_sets() new_prob_density_func = np.zeros_like(prob_density_func) for i in range(prob_density_func.shape[-1]): new_prob_density_func[..., i] = np.roll(prob_density_func[..., i], velocity_set[i], axis=(0, 1)) return new_prob_density_func def equilibrium_distr_func(density_func: np.ndarray, velocity_field: np.ndarray) -> np.ndarray: """ Computes the equilibrium distribution function Args: density_func: density rho(x) velocity_field: velocity u(x) Returns: equilibrium probability density function """ assert density_func.shape == velocity_field.shape[:-1] w_i = get_w_i() c_i = get_velocity_sets() ci_u = velocity_field @ c_i.T f_eq = w_i[np.newaxis, np.newaxis, ...] * np.expand_dims(density_func, axis=-1) * ( 1 + 3 * ci_u + (9 / 2) * np.power(ci_u, 2) - (3 / 2) * np.expand_dims(np.power(np.linalg.norm(velocity_field, axis=-1), 2), axis=-1) ) return f_eq def lattice_boltzmann_step(f: np.ndarray, density: np.ndarray, velocity: np.ndarray, omega: float, boundary: Callable[[np.ndarray, np.ndarray, np.ndarray, np.ndarray], np.ndarray] = None, parallel_communication: Callable[[np.ndarray], np.ndarray] = None) \ -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Carries out a lattice boltzmann step Args: f: probability density function f(r,v,t) density: density rho(x) velocity: velocity u(x) omega: relaxation boundary: function which executes the boundary conditions parallel_communication: function executing the communication step before streaming for parallel implementation Returns: new probability density function, new density function, new velocity function """ assert f.shape[0:2] == density.shape assert f.shape[0:2] == velocity.shape[0:2] assert 0 < omega < 2 f_eq = equilibrium_distr_func(density, velocity) f_pre = (f + (f_eq - f) * omega) if parallel_communication is not None: f_pre = parallel_communication(f_pre) f_post = streaming(f_pre) if boundary is not None: f_post = boundary(f_pre, f_post, density, velocity, f) density = compute_density(f_post) velocity = compute_velocity_field(density, f_post) return f_post, density, velocity
[ "numpy.dstack", "numpy.divide", "numpy.zeros_like", "numpy.sum", "numpy.roll", "numpy.power", "numpy.expand_dims", "numpy.array", "numpy.linalg.norm" ]
[((247, 340), 'numpy.array', 'np.array', (['[[0, 0], [1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, 1], [-1, -1], [1, -1]]'], {}), '([[0, 0], [1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, 1], [-1, -\n 1], [1, -1]])\n', (255, 340), True, 'import numpy as np\n'), ((626, 663), 'numpy.array', 'np.array', (['[0, 3, 4, 1, 2, 7, 8, 5, 6]'], {}), '([0, 3, 4, 1, 2, 7, 8, 5, 6])\n', (634, 663), True, 'import numpy as np\n'), ((947, 1024), 'numpy.array', 'np.array', (['[4 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 36, 1 / 36, 1 / 36, 1 / 36]'], {}), '([4 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 36, 1 / 36, 1 / 36, 1 / 36])\n', (955, 1024), True, 'import numpy as np\n'), ((1297, 1316), 'numpy.divide', 'np.divide', (['(L * u)', 'v'], {}), '(L * u, v)\n', (1306, 1316), True, 'import numpy as np\n'), ((1595, 1614), 'numpy.divide', 'np.divide', (['(f * L)', 'u'], {}), '(f * L, u)\n', (1604, 1614), True, 'import numpy as np\n'), ((1951, 1986), 'numpy.sum', 'np.sum', (['prob_densitiy_func'], {'axis': '(-1)'}), '(prob_densitiy_func, axis=-1)\n', (1957, 1986), True, 'import numpy as np\n'), ((2860, 2879), 'numpy.dstack', 'np.dstack', (['(ux, uy)'], {}), '((ux, uy))\n', (2869, 2879), True, 'import numpy as np\n'), ((3271, 3303), 'numpy.zeros_like', 'np.zeros_like', (['prob_density_func'], {}), '(prob_density_func)\n', (3284, 3303), True, 'import numpy as np\n'), ((3393, 3457), 'numpy.roll', 'np.roll', (['prob_density_func[..., i]', 'velocity_set[i]'], {'axis': '(0, 1)'}), '(prob_density_func[..., i], velocity_set[i], axis=(0, 1))\n', (3400, 3457), True, 'import numpy as np\n'), ((2411, 2461), 'numpy.sum', 'np.sum', (['prob_density_func[:, :, [1, 5, 8]]'], {'axis': '(2)'}), '(prob_density_func[:, :, [1, 5, 8]], axis=2)\n', (2417, 2461), True, 'import numpy as np\n'), ((2464, 2514), 'numpy.sum', 'np.sum', (['prob_density_func[:, :, [3, 6, 7]]'], {'axis': '(2)'}), '(prob_density_func[:, :, [3, 6, 7]], axis=2)\n', (2470, 2514), True, 'import numpy as np\n'), ((2550, 2577), 'numpy.zeros_like', 'np.zeros_like', (['density_func'], {}), '(density_func)\n', (2563, 2577), True, 'import numpy as np\n'), ((2645, 2695), 'numpy.sum', 'np.sum', (['prob_density_func[:, :, [2, 5, 6]]'], {'axis': '(2)'}), '(prob_density_func[:, :, [2, 5, 6]], axis=2)\n', (2651, 2695), True, 'import numpy as np\n'), ((2698, 2748), 'numpy.sum', 'np.sum', (['prob_density_func[:, :, [4, 7, 8]]'], {'axis': '(2)'}), '(prob_density_func[:, :, [4, 7, 8]], axis=2)\n', (2704, 2748), True, 'import numpy as np\n'), ((2784, 2811), 'numpy.zeros_like', 'np.zeros_like', (['density_func'], {}), '(density_func)\n', (2797, 2811), True, 'import numpy as np\n'), ((3999, 4036), 'numpy.expand_dims', 'np.expand_dims', (['density_func'], {'axis': '(-1)'}), '(density_func, axis=-1)\n', (4013, 4036), True, 'import numpy as np\n'), ((4102, 4119), 'numpy.power', 'np.power', (['ci_u', '(2)'], {}), '(ci_u, 2)\n', (4110, 4119), True, 'import numpy as np\n'), ((4168, 4207), 'numpy.linalg.norm', 'np.linalg.norm', (['velocity_field'], {'axis': '(-1)'}), '(velocity_field, axis=-1)\n', (4182, 4207), True, 'import numpy as np\n')]
############################## # Copyright (C) 2009-2011 by # <NAME> (<EMAIL>, <EMAIL>) # <NAME> (<EMAIL>, <EMAIL>) # <NAME> (<EMAIL>) # ... and other members of the Reconstruction Team of David Haussler's # lab (BME Dept. UCSC). # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ############################## class Data: """ A single Data object will be used to store small pieces of information that need to be used by many different functions. """ def __init__( self ): self.chroms = {} # values will be strings self.mafBlocksByChrom = {} # values will be lists of MafBlock objs self.gffRecordsByChrom = {} # values will be dicts of key: annot # names, value: list of GffRecord objs class MafBlock: """ a MafBlock object is made up of the reference and it's pair. The both have their own coordinates that define the nature of their alignment to one another. When buliding a MafBlock from file one can give refEnd and pairEnd values equal to refStart and pairStart and then walk through the sequences and use the increment method whenever there is not a gap '-' character in the sequence. Hap path edge (five, three) codes: * 0 = contig ends. * 1 = correct adjacency. * 2 = error adjacency. * 3 = scaffold gap """ def __init__( self ): self.refGenome = '' self.refChr = '' self.refStart = -1 self.refEnd = -1 self.refStrand = 0 self.refTotalLength = -1 self.refSeq = '' # future use self.pairGenome = '' self.pairChr = '' self.pairStart = -1 self.pairEnd = -1 self.pairStrand = 0 self.pairTotalLength = -1 self.pairSeq = '' # future use self.hpl = -1 self.hplStart = -1 self.hplEnd = -1 self.spl = -1 def increment( self ): self.refEnd += self.refStrand self.pairEnd += self.pairStrand class MafLine: """ a MafLine object stores the raw input from the maf file and is subsequently joined with another MafLine object to become one or more MafBlock objects. """ def __init__( self ): self.genome = '' self.chr = '' self.start = -1 self.length = -1 self.strand = '' self.totalLength = -1 self.sequence = '' # order > -1 implies this sequence is the comparativeGenome # and this is the order the sequence appears in the block from # (0..n-1) for a block with n sequences. self.order = -1 class GffRecord: """ a GffRecord object contains the relevant information needed from one line of a .gff file to create a plot of annotation density across the genome. """ def __init__( self ): self.chr = '' self.source = '' self.type = '' self.start = -1 self.end = -1 self.score = -1 self.strand = '' self.frame = '' self.group = '' def newMafWigDict( numBins ): """ Returns a new mafWigDict object. note that the xAxis starts with a dummy valuable. The xAxis must be filled in with objListUtility_xAxis(). """ import numpy import sys if numBins < 1: sys.stderr.write('Error: libMafGffPlot.py, numBins=%s is less than one.\n' % str(numBins)) sys.exit(1) return { 'maf' : numpy.zeros( shape = ( numBins )), 'maf1e2' : numpy.zeros( shape = ( numBins )), 'maf1e3' : numpy.zeros( shape = ( numBins )), 'maf1e4' : numpy.zeros( shape = ( numBins )), 'maf1e5' : numpy.zeros( shape = ( numBins )), 'maf1e6' : numpy.zeros( shape = ( numBins )), 'maf1e7' : numpy.zeros( shape = ( numBins )), 'xAxis' : -1, 'mafCpl1e2' : numpy.zeros( shape = ( numBins )), 'mafCpl1e3' : numpy.zeros( shape = ( numBins )), 'mafCpl1e4' : numpy.zeros( shape = ( numBins )), 'mafCpl1e5' : numpy.zeros( shape = ( numBins )), 'mafCpl1e6' : numpy.zeros( shape = ( numBins )), 'mafCpl1e7' : numpy.zeros( shape = ( numBins )), 'mafCtg1e2' : numpy.zeros( shape = ( numBins )), 'mafCtg1e3' : numpy.zeros( shape = ( numBins )), 'mafCtg1e4' : numpy.zeros( shape = ( numBins )), 'mafCtg1e5' : numpy.zeros( shape = ( numBins )), 'mafCtg1e6' : numpy.zeros( shape = ( numBins )), 'mafCtg1e7' : numpy.zeros( shape = ( numBins )), 'mafSpl1e2' : numpy.zeros( shape = ( numBins )), 'mafSpl1e3' : numpy.zeros( shape = ( numBins )), 'mafSpl1e4' : numpy.zeros( shape = ( numBins )), 'mafSpl1e5' : numpy.zeros( shape = ( numBins )), 'mafSpl1e6' : numpy.zeros( shape = ( numBins )), 'mafSpl1e7' : numpy.zeros( shape = ( numBins )), 'mafCpEdgeCount' : numpy.zeros( shape = ( numBins ), dtype=numpy.int ), 'mafCpEdgeMax' : 0, 'mafCpErrorCount' : numpy.zeros( shape = ( numBins ), dtype=numpy.int ), 'mafCpErrorMax' : 0, 'mafCpScafGapCount' : numpy.zeros( shape = ( numBins ), dtype=numpy.int ), 'mafCpScafGapMax' : 0, 'blockEdgeCount' : numpy.zeros( shape = ( numBins ), dtype=numpy.int ), 'blockEdgeMax' : 0, 'columnsInBlocks' : 0 } def objListToBinnedWiggle( objList, featLen, numBins, filename ): """ obj can be either a GffRecord object or a MafBlock object. featLen is the length of the chromosome. returns a numpy vector of length numBins normalized by the maximum possible number of bases per bin. """ from libMafGffPlot import GffRecord from libMafGffPlot import MafBlock from libMafGffPlot import newMafWigDict from libMafGffPlot import objListUtility_xAxis import numpy import sys if objList is None or len( objList ) < 1: return None if isinstance( objList[0], GffRecord ): """ the Gff return is a single numpy vector of numBins length """ data = {} # populate xAxis data['xAxis'] = objListUtility_xAxis( featLen, numBins ) annotTypes = set([ 'CDS', 'UTR', 'NXE', 'NGE', 'island', 'tandem', 'repeat' ]) for t in annotTypes: data[ t + 'Count' ] = numpy.zeros( shape = ( numBins )) data[ t + 'Max' ] = 0 for a in objList: if a.type not in annotTypes: continue # verify input if a.start > featLen or a.end > featLen: sys.stderr.write( 'libMafGffPlot.py: file %s has annotation on chr %s ' 'with bounds [%d - %d] which are beyond featLen (%d)\n' % ( filename, a.chr, a.start, a.end, featLen )) sys.exit(1) # index position in a 'numBins' length array. pos = objListUtility_rangeToPos( a.start, a.end, featLen, numBins ) # tough to follow index hack to get around the fact that numpy will not use # += 1 for a list of indices that contain repeats. plo, phi = pos.min(), pos.max() pbins = numpy.bincount( pos - plo ) data[ a.type + 'Count' ][ plo:phi + 1 ] += pbins for p in pos: if data[ a.type + 'Max' ] < data[ a.type + 'Count' ][ p ]: data[ a.type + 'Max' ] = data[ a.type + 'Count' ][ p ] return data elif isinstance( objList[0], MafBlock ): """ the Maf return is a dictionary with the following keys maf all maf block bases maf1e2 maf blocks 100 or greater maf1e3 maf blocks 1,000 or greater maf1e4 maf blocks 10,000 or greater maf1e5 maf blocks 100,000 or greater maf1e6 maf blocks 1,000,000 or greater maf1e7 maf blocks 10,000,000 or greater xAxis x Values mafCpl1eX maf contig paths of X or greater mafCtg1eX maf contigs of X or greater. taken from totalLength field of maf. mafSpl1eX maf scaffold paths of X or greater mafCpEdgeCounts each contig path has two edges, a left and a right mafCpEdgeMax max count mafCpErrorCounts contig paths are made up of segments, segments may have errors at junctions. mafCpErrorMax max count mafSpEdgeCounts Same as above, but for scaffold paths mafSpEdgeMax mafSpErrorCounts mafSpErrorMax blockEdgeCounts each block has two edges, a left and a right blockEdgeMax max count """ from libMafGffPlot import objListUtility_addContigPathEdgeErrors from libMafGffPlot import objListUtility_addBlockEdges from libMafGffPlot import objListUtility_normalizeCategories data = newMafWigDict( numBins ) # populate xAxis data['xAxis'] = objListUtility_xAxis( featLen, numBins ) for mb in objList: # do block edges objListUtility_addBlockEdges( data, mb, featLen, numBins ) # do contige path edges and errors objListUtility_addContigPathEdgeErrors( data, mb, featLen, numBins ) # do all of the different maf block flavors objListUtility_mafBlockCounts( data, mb, featLen, numBins ) # normalize all categories objListUtility_normalizeCategories( data, featLen, numBins ) return data # closing the elif isinstance() checks else: return None def objListUtility_addContigPathEdgeErrors( data, mb, featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() """ from libMafGffPlot import objListUtility_indexToPos import math posSt = objListUtility_indexToPos( mb.refStart, featLen, numBins ) posEnd = objListUtility_indexToPos( mb.refEnd, featLen, numBins ) # five prime if mb.hplStart == 0: # edge data['mafCpEdgeCount'][ posSt ] += 1.0 if data['mafCpEdgeCount'][ posSt ] > data[ 'mafCpEdgeMax' ]: data[ 'mafCpEdgeMax' ] = data['mafCpEdgeCount'][ posSt ] elif mb.hplStart == 2: # error data['mafCpErrorCount'][ posSt ] += 1.0 if data['mafCpErrorCount'][ posSt ] > data[ 'mafCpErrorMax' ]: data[ 'mafCpErrorMax' ] = data['mafCpErrorCount'][ posSt ] elif mb.hplStart == 3: # scaffold gap data['mafCpScafGapCount'][ posSt ] += 1.0 if data['mafCpScafGapCount'][ posSt ] > data[ 'mafCpScafGapMax' ]: data[ 'mafCpScafGapMax' ] = data['mafCpScafGapCount'][ posSt ] # three prime if mb.hplEnd == 0: # edge data['mafCpEdgeCount'][ posEnd ] += 1.0 if data['mafCpEdgeCount'][ posEnd ] > data[ 'mafCpEdgeMax' ]: data[ 'mafCpEdgeMax' ] = data['mafCpEdgeCount'][ posEnd ] elif mb.hplEnd == 2: # error data['mafCpErrorCount'][ posEnd ] += 1.0 if data['mafCpErrorCount'][ posEnd ] > data[ 'mafCpErrorMax' ]: data[ 'mafCpErrorMax' ] = data['mafCpErrorCount'][ posEnd ] elif mb.hplEnd == 3: # scaffold gap data['mafCpScafGapCount'][ posEnd ] += 1.0 if data['mafCpScafGapCount'][ posEnd ] > data[ 'mafCpScafGapMax' ]: data[ 'mafCpScafGapMax' ] = data['mafCpScafGapCount'][ posEnd ] def objListUtility_normalizeCategories( data, featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() """ import math import sys maxPossibleCount = math.ceil( float( featLen ) / float( numBins )) for r in [ 'maf', 'maf1e2', 'maf1e3', 'maf1e4', 'maf1e5', 'maf1e6', 'maf1e7', 'mafCpl1e2', 'mafCpl1e3', 'mafCpl1e4', 'mafCpl1e5', 'mafCpl1e6', 'mafCpl1e7', 'mafCtg1e2', 'mafCtg1e3', 'mafCtg1e4', 'mafCtg1e5', 'mafCtg1e6', 'mafCtg1e7', 'mafSpl1e2', 'mafSpl1e3', 'mafSpl1e4', 'mafSpl1e5', 'mafSpl1e6', 'mafSpl1e7' ]: # verify data 1 if sum( data[ r ] > maxPossibleCount ) > 0: sys.stderr.write('libMafGffPlot.py: Error in normalization step, category \'%s\' has elements ' 'greater than max %d (featLen/numBins = %d/%d)\n' % ( r, maxPossibleCount, featLen, numBins )) # verify data 2 i = -1 for d in data[ r ]: i += 1 if d > maxPossibleCount: start = math.floor( i * ( float( featLen ) / numBins )) end = math.floor( (i + 1) * ( float( featLen ) / numBins )) sys.stderr.write(' i=%d [%d,%d] count %d\n' % ( i, start, end, d )) sys.exit(1) # normalize data[ r ] /= float( maxPossibleCount ) def objListUtility_addBlockEdges( data, mb, featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() """ from libMafGffPlot import objListUtility_indexToPos import math import sys for r in [ mb.refStart, mb.refEnd ]: if r > featLen: sys.stderr.write('libMafGffPlot.py: Error in block edge step, a position is ' 'greater than the feature length, %d > %d.\n' % (r, featLen)) sys.exit(1) p = objListUtility_indexToPos( r, featLen, numBins ) if p < 0: sys.stderr.write('libMafGffPlot.py: Error in block edge step, a position, %d, is less than 0\n' % p ) elif p >= len( data['blockEdgeCount'] ): sys.stderr.write('a position, %d, is greater than or ' 'equal to len(data[\'blockEdgeCount\']) %d [%d-%d]\n' % (p, len(data['blockEdgeCount']), mb.refStart, mb.refEnd)) data['blockEdgeCount'][ p ] += 1.0 if data['blockEdgeCount'][ p ] > data[ 'blockEdgeMax' ]: data[ 'blockEdgeMax' ] = data['blockEdgeCount'][ p ] def objListUtility_mafBlockCounts( data, mb, featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() This is by far the most costly routine in the objList creation process """ from libMafGffPlot import objListUtility_rangeToPos import numpy length = mb.refEnd - ( mb.refStart + 1 ) # tough to follow index hack to get around the fact that numpy will not use # += 1 for a list of indices that contain repeats. pos = objListUtility_rangeToPos( mb.refStart, mb.refEnd, featLen, numBins ) plo, phi = pos.min(), pos.max() pbins = numpy.bincount( pos - plo ) data['maf'][ plo:phi + 1 ] += pbins for i in xrange( 2, 8 ): if length >= 10 ** i: data[ 'maf1e%d' % i ][ plo:phi+1 ] += pbins if mb.spl >= 10 ** i: data[ 'mafSpl1e%d' % i ][ plo:phi+1 ] += pbins if mb.pairTotalLength >= 10 ** i: data[ 'mafCtg1e%d' % i ][ plo:phi+1 ] += pbins if mb.hpl >= 10 ** i: data[ 'mafCpl1e%d' % i ][ plo:phi+1 ] += pbins def objListUtility_xAxis( featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() """ import numpy xaxis = numpy.linspace( start=0, stop=featLen, num=numBins ) return xaxis def objListUtility_indexToPos( p, featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() Takes in a single index position in a [1, featLen] range and then provides the appropriate position in an array of length numBins. Maps an integer to the space [0, numBins]. """ import math import numpy # map point p from [1, featLen] to [0, featLen - 1] z = float( p - 1.0 ) # scale z to [0, featLen) z /= featLen # map to [0, numBins) z *= float( numBins ) # return the index in a length numBins array return math.floor( z ) def objListUtility_rangeToPos( p1, p2, featLen, numBins ): """ Utility function for the MafBlock instance version of libMafGffPlot.objListToBinnedWiggle() Takes in two positions, p1 and p2, that are in the range [1, featLen] and returns a numpy array containing indices in the range [0, numBins]. Maps the integers p1..p2 to the space [0, numBins]. NOTE: the array we return can contain repeated indices. If it does and you store the result in pos to access another array , a, you cannot simply use a[ pos ] += 1 and get what you expect. Instead, use: plo, phi = pos.min(), pos.max() pbins = numpy.bincount( pos - plo ) a[ plo:phi+1 ] += pbins This will be slightly faster than walking through each value in pos and incrementing. """ import numpy # convert [1, featLen ] to [0, featLen - 1] z = numpy.arange( start=p1, stop=p2 + 1.0, step=1, dtype=numpy.int ) - 1.0 # scale elements in array to [0, 1) z /= featLen # map elements in array to [0, numBins) z *= float( numBins ) # return indices for the mapping return ( numpy.floor( z ) ).astype('int') def packData( packMe, filename, options, prot='py23Bin' ): """ packData takes some data and a filename and packs it away. prot refers to the protocol to use. """ import cPickle protocols = { 'ASCII' : 0, 'pre23Bin' : 1, 'py23Bin' : 2 } f = open( filename, 'wb' ) cPickle.dump( packMe, f, protocol = protocols[ prot ] ) f.close() def unpackData( filename, options, data ): """ unpackData unpacks a pickle object """ import cPickle import os if not os.path.exists( filename ): sys.stderr.write( 'Error, %s does not exist.\n' % filename ) sys.exit(1) f = open( filename, 'rb' ) d = cPickle.load( f ) f.close() return d
[ "libMafGffPlot.objListUtility_xAxis", "libMafGffPlot.objListUtility_normalizeCategories", "libMafGffPlot.objListUtility_indexToPos", "numpy.floor", "libMafGffPlot.objListUtility_rangeToPos", "math.floor", "cPickle.load", "numpy.zeros", "os.path.exists", "cPickle.dump", "sys.stderr.write", "lib...
[((11004, 11060), 'libMafGffPlot.objListUtility_indexToPos', 'objListUtility_indexToPos', (['mb.refStart', 'featLen', 'numBins'], {}), '(mb.refStart, featLen, numBins)\n', (11029, 11060), False, 'from libMafGffPlot import objListUtility_indexToPos\n'), ((11075, 11129), 'libMafGffPlot.objListUtility_indexToPos', 'objListUtility_indexToPos', (['mb.refEnd', 'featLen', 'numBins'], {}), '(mb.refEnd, featLen, numBins)\n', (11100, 11129), False, 'from libMafGffPlot import objListUtility_indexToPos\n'), ((15689, 15756), 'libMafGffPlot.objListUtility_rangeToPos', 'objListUtility_rangeToPos', (['mb.refStart', 'mb.refEnd', 'featLen', 'numBins'], {}), '(mb.refStart, mb.refEnd, featLen, numBins)\n', (15714, 15756), False, 'from libMafGffPlot import objListUtility_rangeToPos\n'), ((15805, 15830), 'numpy.bincount', 'numpy.bincount', (['(pos - plo)'], {}), '(pos - plo)\n', (15819, 15830), False, 'import numpy\n'), ((16439, 16489), 'numpy.linspace', 'numpy.linspace', ([], {'start': '(0)', 'stop': 'featLen', 'num': 'numBins'}), '(start=0, stop=featLen, num=numBins)\n', (16453, 16489), False, 'import numpy\n'), ((17139, 17152), 'math.floor', 'math.floor', (['z'], {}), '(z)\n', (17149, 17152), False, 'import math\n'), ((18607, 18656), 'cPickle.dump', 'cPickle.dump', (['packMe', 'f'], {'protocol': 'protocols[prot]'}), '(packMe, f, protocol=protocols[prot])\n', (18619, 18656), False, 'import cPickle\n'), ((18960, 18975), 'cPickle.load', 'cPickle.load', (['f'], {}), '(f)\n', (18972, 18975), False, 'import cPickle\n'), ((4376, 4387), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4384, 4387), False, 'import sys\n'), ((4415, 4441), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4426, 4441), False, 'import numpy\n'), ((4477, 4503), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4488, 4503), False, 'import numpy\n'), ((4539, 4565), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4550, 4565), False, 'import numpy\n'), ((4601, 4627), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4612, 4627), False, 'import numpy\n'), ((4663, 4689), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4674, 4689), False, 'import numpy\n'), ((4725, 4751), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4736, 4751), False, 'import numpy\n'), ((4787, 4813), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4798, 4813), False, 'import numpy\n'), ((4880, 4906), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4891, 4906), False, 'import numpy\n'), ((4942, 4968), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (4953, 4968), False, 'import numpy\n'), ((5004, 5030), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5015, 5030), False, 'import numpy\n'), ((5066, 5092), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5077, 5092), False, 'import numpy\n'), ((5128, 5154), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5139, 5154), False, 'import numpy\n'), ((5190, 5216), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5201, 5216), False, 'import numpy\n'), ((5252, 5278), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5263, 5278), False, 'import numpy\n'), ((5314, 5340), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5325, 5340), False, 'import numpy\n'), ((5376, 5402), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5387, 5402), False, 'import numpy\n'), ((5438, 5464), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5449, 5464), False, 'import numpy\n'), ((5500, 5526), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5511, 5526), False, 'import numpy\n'), ((5562, 5588), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5573, 5588), False, 'import numpy\n'), ((5624, 5650), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5635, 5650), False, 'import numpy\n'), ((5686, 5712), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5697, 5712), False, 'import numpy\n'), ((5748, 5774), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5759, 5774), False, 'import numpy\n'), ((5810, 5836), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5821, 5836), False, 'import numpy\n'), ((5872, 5898), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5883, 5898), False, 'import numpy\n'), ((5934, 5960), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (5945, 5960), False, 'import numpy\n'), ((6004, 6047), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins', 'dtype': 'numpy.int'}), '(shape=numBins, dtype=numpy.int)\n', (6015, 6047), False, 'import numpy\n'), ((6130, 6173), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins', 'dtype': 'numpy.int'}), '(shape=numBins, dtype=numpy.int)\n', (6141, 6173), False, 'import numpy\n'), ((6256, 6299), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins', 'dtype': 'numpy.int'}), '(shape=numBins, dtype=numpy.int)\n', (6267, 6299), False, 'import numpy\n'), ((6382, 6425), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins', 'dtype': 'numpy.int'}), '(shape=numBins, dtype=numpy.int)\n', (6393, 6425), False, 'import numpy\n'), ((7248, 7286), 'libMafGffPlot.objListUtility_xAxis', 'objListUtility_xAxis', (['featLen', 'numBins'], {}), '(featLen, numBins)\n', (7268, 7286), False, 'from libMafGffPlot import objListUtility_xAxis\n'), ((14557, 14603), 'libMafGffPlot.objListUtility_indexToPos', 'objListUtility_indexToPos', (['r', 'featLen', 'numBins'], {}), '(r, featLen, numBins)\n', (14582, 14603), False, 'from libMafGffPlot import objListUtility_indexToPos\n'), ((18012, 18074), 'numpy.arange', 'numpy.arange', ([], {'start': 'p1', 'stop': '(p2 + 1.0)', 'step': '(1)', 'dtype': 'numpy.int'}), '(start=p1, stop=p2 + 1.0, step=1, dtype=numpy.int)\n', (18024, 18074), False, 'import numpy\n'), ((18810, 18834), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (18824, 18834), False, 'import os\n'), ((18844, 18902), 'sys.stderr.write', 'sys.stderr.write', (["('Error, %s does not exist.\\n' % filename)"], {}), "('Error, %s does not exist.\\n' % filename)\n", (18860, 18902), False, 'import sys\n'), ((18911, 18922), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (18919, 18922), False, 'import sys\n'), ((7458, 7484), 'numpy.zeros', 'numpy.zeros', ([], {'shape': 'numBins'}), '(shape=numBins)\n', (7469, 7484), False, 'import numpy\n'), ((8033, 8092), 'libMafGffPlot.objListUtility_rangeToPos', 'objListUtility_rangeToPos', (['a.start', 'a.end', 'featLen', 'numBins'], {}), '(a.start, a.end, featLen, numBins)\n', (8058, 8092), False, 'from libMafGffPlot import objListUtility_rangeToPos\n'), ((8311, 8336), 'numpy.bincount', 'numpy.bincount', (['(pos - plo)'], {}), '(pos - plo)\n', (8325, 8336), False, 'import numpy\n'), ((10023, 10045), 'libMafGffPlot.newMafWigDict', 'newMafWigDict', (['numBins'], {}), '(numBins)\n', (10036, 10045), False, 'from libMafGffPlot import newMafWigDict\n'), ((10100, 10138), 'libMafGffPlot.objListUtility_xAxis', 'objListUtility_xAxis', (['featLen', 'numBins'], {}), '(featLen, numBins)\n', (10120, 10138), False, 'from libMafGffPlot import objListUtility_xAxis\n'), ((10579, 10637), 'libMafGffPlot.objListUtility_normalizeCategories', 'objListUtility_normalizeCategories', (['data', 'featLen', 'numBins'], {}), '(data, featLen, numBins)\n', (10613, 10637), False, 'from libMafGffPlot import objListUtility_normalizeCategories\n'), ((13307, 13503), 'sys.stderr.write', 'sys.stderr.write', (['("""libMafGffPlot.py: Error in normalization step, category \'%s\' has elements greater than max %d (featLen/numBins = %d/%d)\n"""\n % (r, maxPossibleCount, featLen, numBins))'], {}), '(\n """libMafGffPlot.py: Error in normalization step, category \'%s\' has elements greater than max %d (featLen/numBins = %d/%d)\n"""\n % (r, maxPossibleCount, featLen, numBins))\n', (13323, 13503), False, 'import sys\n'), ((14332, 14481), 'sys.stderr.write', 'sys.stderr.write', (['("""libMafGffPlot.py: Error in block edge step, a position is greater than the feature length, %d > %d.\n"""\n % (r, featLen))'], {}), '(\n """libMafGffPlot.py: Error in block edge step, a position is greater than the feature length, %d > %d.\n"""\n % (r, featLen))\n', (14348, 14481), False, 'import sys\n'), ((14534, 14545), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (14542, 14545), False, 'import sys\n'), ((14631, 14741), 'sys.stderr.write', 'sys.stderr.write', (["('libMafGffPlot.py: Error in block edge step, a position, %d, is less than 0\\n'\n % p)"], {}), "(\n 'libMafGffPlot.py: Error in block edge step, a position, %d, is less than 0\\n'\n % p)\n", (14647, 14741), False, 'import sys\n'), ((18254, 18268), 'numpy.floor', 'numpy.floor', (['z'], {}), '(z)\n', (18265, 18268), False, 'import numpy\n'), ((7703, 7885), 'sys.stderr.write', 'sys.stderr.write', (['("""libMafGffPlot.py: file %s has annotation on chr %s with bounds [%d - %d] which are beyond featLen (%d)\n"""\n % (filename, a.chr, a.start, a.end, featLen))'], {}), '(\n """libMafGffPlot.py: file %s has annotation on chr %s with bounds [%d - %d] which are beyond featLen (%d)\n"""\n % (filename, a.chr, a.start, a.end, featLen))\n', (7719, 7885), False, 'import sys\n'), ((7951, 7962), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (7959, 7962), False, 'import sys\n'), ((10201, 10257), 'libMafGffPlot.objListUtility_addBlockEdges', 'objListUtility_addBlockEdges', (['data', 'mb', 'featLen', 'numBins'], {}), '(data, mb, featLen, numBins)\n', (10229, 10257), False, 'from libMafGffPlot import objListUtility_addBlockEdges\n'), ((10323, 10389), 'libMafGffPlot.objListUtility_addContigPathEdgeErrors', 'objListUtility_addContigPathEdgeErrors', (['data', 'mb', 'featLen', 'numBins'], {}), '(data, mb, featLen, numBins)\n', (10361, 10389), False, 'from libMafGffPlot import objListUtility_addContigPathEdgeErrors\n'), ((13840, 13907), 'sys.stderr.write', 'sys.stderr.write', (["(' i=%d [%d,%d] count %d\\n' % (i, start, end, d))"], {}), "(' i=%d [%d,%d] count %d\\n' % (i, start, end, d))\n", (13856, 13907), False, 'import sys\n'), ((13925, 13936), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13933, 13936), False, 'import sys\n')]
"""Solution problems / methods / algorithms module""" import collections import cvxpy as cp import gurobipy as gp import itertools import numpy as np import pandas as pd import scipy.optimize import scipy.sparse as sp import typing import mesmo.config import mesmo.utils logger = mesmo.config.get_logger(__name__) class OptimizationProblem(mesmo.utils.ObjectBase): r"""Optimization problem object class, which allows the definition and solution of convex optimization problems. The optimization problem object serves as a container for the parameters, variables, constraints and objective terms. The object provides methods for defining variables, parameters, constraints and objectives as well as methods for solving the numerical optimization problem and obtaining results for variables, objective value and dual values. - This documentation assumes a fundamental understanding of convex optimization. As a general reference on this topic, refer to: *<NAME> and <NAME>, Convex optimization. Cambridge University Press, 2004.* Available at: https://web.stanford.edu/~boyd/cvxbook/ - The optimization problem object currently supports convex optimization problems in the form of 1) linear program (LP) or 2) quadratic program (QP) with only linear constraints. - The solve method currently implements interfaces to 1) Gurobi and 2) CVXPY, where the latter is a high-level convex optimization interface, which in turn allows interfacing further third-party solvers. The intention is to implement more direct solver interfaces on a as-need basis (please raise an issue!), as these interfaces are assumed to allow higher performance than CVXPY for large-scale problems. However, CVXPY is kept as a fallback to allow a high degree of compatibility with various solvers. The optimization problem object internally translates optimizations into LP / QP standard form. Where the following formulation is assumed for the standard form: .. math:: \begin{align} \min_{\boldsymbol{x}} \quad & \boldsymbol{c}^{\intercal} \boldsymbol{x} + \frac{1}{2} \boldsymbol{x}^{\intercal} \boldsymbol{Q} \boldsymbol{x} + d \\ \text{s.t.} \quad & \boldsymbol{A} \boldsymbol{x} \leq \boldsymbol{b} \quad : \ \boldsymbol{\mu} \end{align} The vectors :math:`\boldsymbol{x}` and :math:`\boldsymbol{\mu}` are the variable vector and associated constraint dual variable vector. The matrix :math:`\boldsymbol{A}` defines the linear constraint coefficients, whereas the matrix :math:`\boldsymbol{Q}` defines quadradtic objective coefficients. The vectors :math:`\boldsymbol{b}` and :math:`\boldsymbol{c}` define constant constraint terms and linear objective coefficients. Lastly, the scalar :math:`d` defines the constant objective term. Note that the scalar :math:`d` represents a slight abuse of the standard form to include constant objective term, which may prove useful for comparing objective values across different problem definitions. Example: Consider the following optimization problem: .. math:: \begin{align} \min_{\boldsymbol{a},\boldsymbol{b}} \quad & \sum_{i=1}^{n=1000} b_i \\ \text{s.t.} \quad & \boldsymbol{b} = \boldsymbol{a} \cdot \boldsymbol{P} \\ & -10 \leq \boldsymbol{a} \leq +10 \end{align} The matrix :math:`\boldsymbol{P} \in \mathbb{R}^{n \times n}` is an abitrary parameter matrix. The vectors :math:`\boldsymbol{a}, \boldsymbol{b} \in \mathbb{R}^{n \times 1}` are decision variable vectors. The symbol :math:`n` defines the problem dimension. This problem can be defined and solved with the optimization problem interface as follows:: # Instantiate optimization problem. optimization_problem = mesmo.solutions.OptimizationProblem() # Define optimization parameters. optimization_problem.define_parameter('parameter_matrix', parameter_matrix) # Define optimization variables. optimization_problem.define_variable('a_vector', a_index=range(dimension)) optimization_problem.define_variable('b_vector', b_index=range(dimension)) # Define optimization constraints. optimization_problem.define_constraint( ('variable', 1.0, dict(name='b_vector')), '==', ('variable', 'parameter_matrix', dict(name='a_vector')), ) optimization_problem.define_constraint( ('constant', -10.0), '<=', ('variable', 1.0, dict(name='a_vector')), ) optimization_problem.define_constraint( ('constant', +10.0), '>=', ('variable', 1.0, dict(name='a_vector')), ) # Define optimization objective. optimization_problem.define_objective(('variable', 1.0, dict(name='b_vector'))) # Solve optimization problem. optimization_problem.solve() # Obtain results. results = optimization_problem.get_results() a_vector = results['a_vector'] b_vector = results['b_vector'] This example is also available as standalone script at: ``examples/run_general_optimization_problem.py`` """ variables: pd.DataFrame constraints: pd.DataFrame constraints_len: int parameters: dict flags: dict a_dict: dict b_dict: dict c_dict: dict q_dict: dict d_dict: dict x_vector: np.ndarray mu_vector: np.ndarray results: dict duals: dict objective: float def __init__(self): # Instantiate index sets. # - Variables are instantiated with 'name' and 'timestep' keys, but more may be added in ``define_variable()``. # - Constraints are instantiated with 'name', 'timestep' and 'constraint_type' keys, # but more may be added in ``define_constraint()``. self.variables = pd.DataFrame(columns=["name", "timestep", "variable_type"]) self.constraints = pd.DataFrame(columns=["name", "timestep", "constraint_type"]) self.constraints_len = 0 # Instantiate parameters / flags dictionary. self.parameters = dict() self.flags = dict() # Instantiate A matrix / b vector / c vector / Q matrix / d constant dictionaries. # - Final matrix / vector are only created in ``get_a_matrix()``, ``get_b_vector()``, ``get_c_vector()``, # ``get_q_matrix()`` and ``get_d_constant()``. # - Uses `defaultdict(list)` to enable more convenient collecting of elements into lists. This avoids # accidental overwriting of dictionary entries. self.a_dict = collections.defaultdict(list) self.b_dict = collections.defaultdict(list) self.c_dict = collections.defaultdict(list) self.q_dict = collections.defaultdict(list) self.d_dict = collections.defaultdict(list) def define_variable( self, name: str, variable_type: str = "continuous", **keys, ): """Define decision variable with given name and key set. - Variables are defined by passing a name string and index key sets. The variable dimension is determined by the dimension of the index key sets. Accepted key set values are 1) lists, 2) tuples, 3) numpy arrays, 4) pandas index objects and 5) range objects. - If multiple index key sets are passed, the variable dimension is determined as the cartesian product of the key sets. However, note that variables always take the shape of column vectors in constraint and objective definitions. That means, multiple key sets are not interpreted as array dimensions. - The variable type can be defined with the keyword argument `variable_type` as either 'continuous', 'integer' or 'binary'. The variable type defaults to 'continuous'. """ # Validate variable type. variable_types = ["continuous", "integer", "binary"] if variable_type not in ["continuous", "integer", "binary"]: raise ValueError( f"For variable definitions, the key `variable_type` is reserved and must be a valid variable type." f"Valid variable types are {variable_types}." ) # Obtain new variables based on ``keys``. # - Variable dimensions are constructed based by taking the product of the given key sets. new_variables = pd.DataFrame( itertools.product( [name], [variable_type], *[ list(value) if type(value) in [pd.MultiIndex, pd.Index, pd.DatetimeIndex, np.ndarray, list, tuple, range] else [value] for value in keys.values() ], ), columns=["name", "variable_type", *keys.keys()], ) # Add new variables to index. # - Duplicate definitions are automatically removed. self.variables = pd.concat([self.variables, new_variables], ignore_index=True).drop_duplicates( ignore_index=True ) def define_parameter(self, name: str, value: typing.Union[float, np.ndarray, sp.spmatrix]): """Define constant parameters with given name and numerical value. - Numerical values can be numerical value can be real-valued 1) float, 2) numpy array and 3) scipy sparse matrix. - Defining parameters is optional. – Numerical values can also be directly passed in the constraints / objective definitions. However, using parameters allows updating the numerical values of the problem without re-defining the complete problem. """ # Validate dimensions, if parameter already defined. if name in self.parameters.keys(): if np.shape(value) != np.shape(self.parameters[name]): ValueError(f"Mismatch of redefined parameter: {name}") # Set parameter value. self.parameters[name] = value def define_constraint( self, *elements: typing.Union[ str, typing.Tuple[str, typing.Union[str, float, np.ndarray, sp.spmatrix]], typing.Tuple[str, typing.Union[str, float, np.ndarray, sp.spmatrix], dict], ], **kwargs, ): """Define linear constraint for given list of constraint elements. - Constraints are defined as list of tuples and strings, where tuples are either 1) variable terms or 2) constant terms and strings represent operators (==, <= or >=). If multiple variable and constant terms are on either side of the operator, these are interpreted as summation of the variables / constants. - Constant terms are tuples in the form (‘constant’, numerical value), where the numerical value can be real-valued 1) float, 2) numpy array, 3) scipy sparse matrix or 4) a parameter name string. The numerical value is expected to represent a column vector with appropriate size matching the constraint dimension. If a float value is given as numerical value, the value is multiplied with a column vector of ones of appropriate size. - Variable terms are tuples in the form (‘variable’, numerical factor, dict(name=variable name, keys…)), where the numerical factor can be real-valued 1) float, 2) numpy array, 3) scipy sparse matrix or 4) a parameter name string. The numerical factor is multiplied with the variable vector and is expected to represent a matrix of appropriate size for the multiplication. If a float value is given as numerical factor, the value is multiplied with a identity matrix of appropriate size. Keys can be optionally given to select / slice a portion of the variable vector. Note that variables always take the shape of column vectors. """ # Instantiate constraint element aggregation variables. variables = list() constants = list() operator = None # Instantiate left-hand / right-hand side indicator. Starting from left-hand side. side = "left" # Aggregate constraint elements. for element in elements: # Tuples are variables / constants. if isinstance(element, tuple): # Obtain element attributes. element_type = element[0] element_value = element[1] element_keys = element[2] if len(element) > 2 else None # Identify variables. if element_type in ("variable", "var", "v"): # Move right-hand variables to left-hand side. if side == "right": factor = -1.0 else: factor = 1.0 # Raise error if no keys defined. if element_keys is None: raise ValueError(f"Missing keys for variable: \n{element}") # Append element to variables. variables.append((factor, element_value, element_keys)) # Identify constants. elif element_type in ("constant", "con", "c"): # Move left-hand constants to right-hand side. if side == "left": factor = -1.0 else: factor = 1.0 # Append element to constants. constants.append((factor, element_value, element_keys)) # Raise error if element type cannot be identified. else: raise ValueError(f"Invalid constraint element type: {element_type}") # Strings are operators. elif element in ["==", "<=", ">="]: # Raise error if operator is first element. if element == elements[0]: ValueError(f"Operator is first element of a constraint.") # Raise error if operator is last element. if element == elements[-1]: ValueError(f"Operator is last element of a constraint.") # Raise error if operator is already defined. if operator is not None: ValueError(f"Multiple operators defined in one constraint.") # Set operator. operator = element # Update left-hand / right-hand side indicator. Moving to right-hand side. side = "right" # Raise error if element type cannot be identified. else: raise ValueError(f"Invalid constraint element: \n{element}") # Raise error if operator missing. if operator is None: raise ValueError("Cannot define constraint without operator (==, <= or >=).") self.define_constraint_low_level(variables, operator, constants, **kwargs) def define_constraint_low_level( self, variables: typing.List[typing.Tuple[float, typing.Union[str, float, np.ndarray, sp.spmatrix], dict]], operator: str, constants: typing.List[typing.Tuple[float, typing.Union[str, float, np.ndarray, sp.spmatrix], dict]], keys: dict = None, broadcast: typing.Union[str, list, tuple] = None, ): # Raise error if no variables in constraint. if len(variables) == 0: raise ValueError(f"Cannot define constraint without variables.") # Run checks for constraint index keys. if keys is not None: # Raise error if ``keys`` is not a dictionary. if type(keys) is not dict: raise TypeError(f"Constraint `keys` parameter must be a dictionary, but instead is: {type(keys)}") # Raise error if no 'name' key was defined. if "name" not in keys.keys(): raise ValueError(f"'name' key is required in constraint `keys` dictionary. Only found: {keys.keys()}") # TODO: Raise error if using reserved 'constraint_type' key. # Run type checks for broadcast argument. if broadcast is not None: if type(broadcast) is str: broadcast = [broadcast] elif type(broadcast) not in [list, tuple]: raise ValueError(f"Invalid type of broadcast argument: {type(broadcast)}") # For equality constraint, define separate upper / lower inequality. if operator in ["=="]: # Define upper inequality. self.define_constraint_low_level( variables, ">=", constants, keys=dict(keys, constraint_type="==>=") if keys is not None else None, broadcast=broadcast, ) # Define lower inequality. self.define_constraint_low_level( variables, "<=", constants, keys=dict(keys, constraint_type="==<=") if keys is not None else None, broadcast=broadcast, ) # For inequality constraint, add into A matrix / b vector dictionaries. elif operator in ["<=", ">="]: # If greater-than-equal, invert signs. if operator == ">=": operator_factor = -1.0 else: operator_factor = 1.0 # Instantiate constraint index. constraint_index = None # Process variables. for variable_factor, variable_value, variable_keys in variables: # If any variable key values are empty, ignore variable & do not add any A matrix entry. for key_value in variable_keys.values(): if isinstance(key_value, (list, tuple, pd.MultiIndex, pd.Index, np.ndarray)): if len(key_value) == 0: continue # Skip variable & go to next iteration. # Obtain variable integer index & raise error if variable or key does not exist. variable_index = tuple(self.get_variable_index(**variable_keys, raise_empty_index_error=True)) # Obtain broadcast dimension length for variable. if broadcast is not None: broadcast_len = 1 for broadcast_key in broadcast: if broadcast_key not in variable_keys.keys(): raise ValueError(f"Invalid broadcast dimension: {broadcast_key}") else: broadcast_len *= len(variable_keys[broadcast_key]) else: broadcast_len = 1 # String values are interpreted as parameter name. if type(variable_value) is str: parameter_name = variable_value variable_value = self.parameters[parameter_name] else: parameter_name = None # Flat arrays are interpreted as row vectors (1, n). if len(np.shape(variable_value)) == 1: variable_value = np.array([variable_value]) # Scalar values are multiplied with identity matrix of appropriate size. if len(np.shape(variable_value)) == 0: variable_value = variable_value * sp.eye(len(variable_index)) # If broadcasting, value is repeated in block-diagonal matrix. elif broadcast_len > 1: if type(variable_value) is np.matrix: variable_value = np.array(variable_value) variable_value = sp.block_diag([variable_value] * broadcast_len) # If not yet defined, obtain constraint index based on dimension of first variable. if constraint_index is None: constraint_index = tuple( range(self.constraints_len, self.constraints_len + np.shape(variable_value)[0]) ) # Raise error if variable dimensions are inconsistent. if np.shape(variable_value) != (len(constraint_index), len(variable_index)): raise ValueError(f"Dimension mismatch at variable: \n{variable_keys}") # Append A matrix entry. # - If parameter, pass tuple of factor, parameter name and broadcasting dimension length. if parameter_name is None: self.a_dict[constraint_index, variable_index].append( operator_factor * variable_factor * variable_value ) else: self.a_dict[constraint_index, variable_index].append( (operator_factor * variable_factor, parameter_name, broadcast_len) ) # Process constants. for constant_factor, constant_value, constant_keys in constants: # If constant value is string, it is interpreted as parameter. if type(constant_value) is str: parameter_name = constant_value constant_value = self.parameters[parameter_name] else: parameter_name = None # Obtain broadcast dimension length for constant. if (broadcast is not None) and (constant_keys is not None): broadcast_len = 1 for broadcast_key in broadcast: # TODO: Raise error if not in keys. if broadcast_key in constant_keys.keys(): broadcast_len *= len(constant_keys[broadcast_key]) else: broadcast_len = 1 # If constant is sparse, convert to dense array. if isinstance(constant_value, sp.spmatrix): constant_value = constant_value.toarray() # If constant is scalar, cast into vector of appropriate size. if len(np.shape(constant_value)) == 0: constant_value = constant_value * np.ones(len(constraint_index)) # If broadcasting, values are repeated along broadcast dimension. elif broadcast_len > 1: constant_value = np.concatenate([constant_value] * broadcast_len, axis=0) # Raise error if constant is not a scalar, column vector (n, 1) or flat array (n, ). if len(np.shape(constant_value)) > 1: if np.shape(constant_value)[1] > 1: raise ValueError(f"Constant must be column vector (n, 1), not row vector (1, n).") # If not yet defined, obtain constraint index based on dimension of first constant. if constraint_index is None: constraint_index = tuple(range(self.constraints_len, self.constraints_len + len(constant_value))) # Raise error if constant dimensions are inconsistent. if len(constant_value) != len(constraint_index): raise ValueError(f"Dimension mismatch at constant: \n{constant_keys}") # Append b vector entry. if parameter_name is None: self.b_dict[constraint_index].append(operator_factor * constant_factor * constant_value) else: self.b_dict[constraint_index].append( (operator_factor * constant_factor, parameter_name, broadcast_len) ) # Append constraints index entries. if keys is not None: # Set constraint type: if "constraint_type" in keys.keys(): if keys["constraint_type"] not in ("==>=", "==<="): keys["constraint_type"] = operator else: keys["constraint_type"] = operator # Obtain new constraints based on ``keys``. # - Constraint dimensions are constructed based by taking the product of the given key sets. new_constraints = pd.DataFrame( itertools.product( *[ list(value) if type(value) in [pd.MultiIndex, pd.Index, pd.DatetimeIndex, np.ndarray, list, tuple] else [value] for value in keys.values() ] ), columns=keys.keys(), ) # Raise error if key set dimension does not align with constant dimension. if len(new_constraints) != len(constraint_index): raise ValueError( f"Constraint key set dimension ({len(new_constraints)})" f" does not align with constraint value dimension ({len(constraint_index)})." ) # Add new constraints to index. new_constraints.index = constraint_index self.constraints = self.constraints.append(new_constraints) self.constraints_len += len(constraint_index) else: # Only change constraints size, if no ``keys`` defined. # - This is for speedup, as updating the constraints index set with above operation is slow. self.constraints_len += len(constraint_index) # Raise error for invalid operator. else: ValueError(f"Invalid constraint operator: {operator}") def define_objective( self, *elements: typing.Union[ str, typing.Tuple[str, typing.Union[str, float, np.ndarray, sp.spmatrix]], typing.Tuple[str, typing.Union[str, float, np.ndarray, sp.spmatrix], dict], typing.Tuple[str, typing.Union[str, float, np.ndarray, sp.spmatrix], dict, dict], ], **kwargs, ): """Define objective terms for the given list of objective elements. - Objective terms are defined as list of tuples, where tuples are either 1) variable terms or 2) constant terms. Each term is expected to evaluate to a scalar value. If multiple variable and constant terms are defined, these are interpreted as summation of the variables / constants. - Constant terms are tuples in the form (‘constant’, numerical value), where the numerical value can be 1) float value or 2) a parameter name string. - Variable terms are tuples in the form (‘variable’, numerical factor, dict(name=variable name, keys…)), where the numerical factor can be 1) float value, 2) numpy array, 3) scipy sparse matrix or 4) a parameter name string. The numerical factor is multiplied with the variable vector and is expected to represent a matrix of appropriate size for the multiplication, such that the multiplication evaluates to a scalar. If a float value is given as numerical factor, the value is multiplied with a row vector of ones of appropriate size. Keys can be optionally given to select / slice a portion of the variable vector. Note that variables always take the shape of column vectors. """ # Instantiate objective element aggregation variables. variables = list() variables_quadratic = list() constants = list() # Aggregate objective elements. for element in elements: # Tuples are variables / constants. if isinstance(element, tuple): # Obtain element attributes. element_type = element[0] element_value = element[1] element_keys_1 = element[2] if len(element) > 2 else None element_keys_2 = element[3] if len(element) > 3 else None # Identify variables. if element_type in ("variable", "var", "v"): # Append element to variables / quadratic variables. if element_keys_2 is None: variables.append((element_value, element_keys_1)) else: variables_quadratic.append((element_value, element_keys_1, element_keys_2)) # Identify constants. elif element_type in ("constant", "con", "c"): # Add element to constant. constants.append((element_value, element_keys_1)) # Raise error if element type cannot be identified. else: raise ValueError(f"Invalid objective element type: {element[0]}") # Raise error if element type cannot be identified. else: raise ValueError(f"Invalid objective element: \n{element}") self.define_objective_low_level(variables, variables_quadratic, constants, **kwargs) def define_objective_low_level( self, variables: typing.List[typing.Tuple[typing.Union[str, float, np.ndarray, sp.spmatrix], dict]], variables_quadratic: typing.List[typing.Tuple[typing.Union[str, float, np.ndarray, sp.spmatrix], dict, dict]], constants: typing.List[typing.Tuple[typing.Union[str, float, np.ndarray, sp.spmatrix], dict]], broadcast: typing.Union[str, list, tuple] = None, ): # Run type checks for broadcast argument. if broadcast is not None: if type(broadcast) is str: broadcast = [broadcast] elif type(broadcast) not in [list, tuple]: raise ValueError(f"Invalid type of broadcast argument: {type(broadcast)}") # Process variables. for variable_value, variable_keys in variables: # If any variable key values are empty, ignore variable & do not add any c vector entry. for key_value in variable_keys.values(): if isinstance(key_value, (list, tuple, pd.MultiIndex, pd.Index, np.ndarray)): if len(key_value) == 0: continue # Skip variable & go to next iteration. # Obtain variable index & raise error if variable or key does not exist. variable_index = tuple(self.get_variable_index(**variable_keys, raise_empty_index_error=True)) # Obtain broadcast dimension length for variable. if broadcast is not None: broadcast_len = 1 for broadcast_key in broadcast: if broadcast_key not in variable_keys.keys(): raise ValueError(f"Invalid broadcast dimension: {broadcast_key}") else: broadcast_len *= len(variable_keys[broadcast_key]) else: broadcast_len = 1 # String values are interpreted as parameter name. if type(variable_value) is str: parameter_name = variable_value variable_value = self.parameters[parameter_name] else: parameter_name = None # Scalar values are multiplied with row vector of ones of appropriate size. if len(np.shape(variable_value)) == 0: variable_value = variable_value * np.ones((1, len(variable_index))) # If broadcasting, values are repeated along broadcast dimension. else: if broadcast_len > 1: if len(np.shape(variable_value)) > 1: variable_value = np.concatenate([variable_value] * broadcast_len, axis=1) else: variable_value = np.concatenate([[variable_value]] * broadcast_len, axis=1) # Raise error if vector is not a row vector (1, n) or flat array (n, ). if len(np.shape(variable_value)) > 1: if np.shape(variable_value)[0] > 1: raise ValueError( f"Objective factor must be row vector (1, n) or flat array (n, )," f" not column vector (n, 1) nor matrix (m, n)." ) # Raise error if variable dimensions are inconsistent. if ( np.shape(variable_value)[1] != len(variable_index) if len(np.shape(variable_value)) > 1 else np.shape(variable_value)[0] != len(variable_index) ): raise ValueError(f"Objective factor dimension mismatch at variable: \n{variable_keys}") # Add c vector entry. # - If parameter, pass tuple of parameter name and broadcasting dimension length. if parameter_name is None: self.c_dict[variable_index].append(variable_value) else: self.c_dict[variable_index].append((parameter_name, broadcast_len)) # Process quadratic variables. for variable_value, variable_keys_1, variable_keys_2 in variables_quadratic: # If any variable key values are empty, ignore variable & do not add any c vector entry. for key_value in list(variable_keys_1.values()) + list(variable_keys_2.values()): if isinstance(key_value, (list, tuple, pd.MultiIndex, pd.Index, np.ndarray)): if len(key_value) == 0: continue # Skip variable & go to next iteration. # Obtain variable index & raise error if variable or key does not exist. variable_1_index = tuple(self.get_variable_index(**variable_keys_1, raise_empty_index_error=True)) variable_2_index = tuple(self.get_variable_index(**variable_keys_2, raise_empty_index_error=True)) # Obtain broadcast dimension length for variable. if broadcast is not None: broadcast_len = 1 for broadcast_key in broadcast: if broadcast_key not in variable_keys_1.keys(): raise ValueError(f"Invalid broadcast dimension: {broadcast_key}") else: broadcast_len *= len(variable_keys_1[broadcast_key]) else: broadcast_len = 1 # String values are interpreted as parameter name. if type(variable_value) is str: parameter_name = variable_value variable_value = self.parameters[parameter_name] else: parameter_name = None # Flat arrays are interpreted as diagonal matrix. if len(np.shape(variable_value)) == 1: # TODO: Raise error for flat arrays instead? variable_value = sp.diags(variable_value) # Scalar values are multiplied with diagonal matrix of ones of appropriate size. if len(np.shape(variable_value)) == 0: variable_value = variable_value * sp.eye(len(variable_1_index)) # If broadcasting, values are repeated along broadcast dimension. else: if type(variable_value) is np.matrix: variable_value = np.array(variable_value) variable_value = sp.block_diag([variable_value] * broadcast_len) # Raise error if variable dimensions are inconsistent. if np.shape(variable_value)[0] != len(variable_1_index): raise ValueError( f"Quadratic objective factor dimension mismatch at variable 1: \n{variable_keys_1}" f"\nThe shape of quadratic objective factor matrix must be " f"{(len(variable_1_index), len(variable_2_index))}, based on the variable dimensions." ) if np.shape(variable_value)[1] != len(variable_2_index): raise ValueError( f"Quadratic objective factor dimension mismatch at variable 2: \n{variable_keys_2}" f"\nThe shape of quadratic objective factor matrix must be " f"{(len(variable_1_index), len(variable_2_index))}, based on the variable dimensions." ) # Add Q matrix entry. # - If parameter, pass tuple of parameter name and broadcasting dimension length. if parameter_name is None: self.q_dict[variable_1_index, variable_2_index].append(variable_value) else: self.q_dict[variable_1_index, variable_2_index].append((parameter_name, broadcast_len)) # Process constants. for constant_value, constant_keys in constants: # If constant value is string, it is interpreted as parameter. if type(constant_value) is str: parameter_name = constant_value constant_value = self.parameters[parameter_name] else: parameter_name = None # Obtain broadcast dimension length for constant. if (broadcast is not None) and (constant_keys is not None): broadcast_len = 1 for broadcast_key in broadcast: if broadcast_key in constant_keys.keys(): broadcast_len *= len(constant_keys[broadcast_key]) else: broadcast_len = 1 # Raise error if constant is not a scalar (1, ) or (1, 1) or float. if type(constant_value) is not float: if np.shape(constant_value) not in [(1,), (1, 1)]: raise ValueError(f"Objective constant must be scalar or (1, ) or (1, 1).") # If broadcasting, value is repeated along broadcast dimension. if broadcast_len > 1: constant_value = constant_value * broadcast_len # Append d constant entry. if parameter_name is None: self.d_dict[0].append(constant_value) else: self.d_dict[0].append((parameter_name, broadcast_len)) def get_variable_index(self, name: str, raise_empty_index_error: bool = False, **keys): """Utility method for obtaining a variable integer index vector for given variable name / keys.""" return mesmo.utils.get_index(self.variables, name=name, **keys, raise_empty_index_error=raise_empty_index_error) def get_variable_keys(self, name: str, **keys): """Utility method for obtaining a variable key dataframe for given variable name / keys. - This intended for debugging / inspection of the key value order, e.g. such that numerical factors can be constructed accordingly. """ return self.variables.loc[self.get_variable_index(name, **keys)].dropna(axis="columns", how="all") def get_a_matrix(self) -> sp.csr_matrix: r"""Obtain :math:`\boldsymbol{A}` matrix for the standard-form problem (see :class:`OptimizationProblem`).""" # Log time. mesmo.utils.log_time("get optimization problem A matrix", logger_object=logger) # Instantiate collections. values_list = list() rows_list = list() columns_list = list() # Collect matrix entries. for constraint_index, variable_index in self.a_dict: for values in self.a_dict[constraint_index, variable_index]: # If value is tuple, treat as parameter. if type(values) is tuple: factor, parameter_name, broadcast_len = values values = self.parameters[parameter_name] if len(np.shape(values)) == 1: values = np.array([values]) if len(np.shape(values)) == 0: values = values * sp.eye(len(variable_index)) elif broadcast_len > 1: if type(values) is np.matrix: values = np.array(values) values = sp.block_diag([values] * broadcast_len) values = values * factor # Obtain row index, column index and values for entry in A matrix. rows, columns, values = sp.find(values) rows = np.array(constraint_index)[rows] columns = np.array(variable_index)[columns] # Insert entry in collections. values_list.append(values) rows_list.append(rows) columns_list.append(columns) # Instantiate A matrix. a_matrix = sp.coo_matrix( (np.concatenate(values_list), (np.concatenate(rows_list), np.concatenate(columns_list))), shape=(self.constraints_len, len(self.variables)), ).tocsr() # Log time. mesmo.utils.log_time("get optimization problem A matrix", logger_object=logger) return a_matrix def get_b_vector(self) -> np.ndarray: r"""Obtain :math:`\boldsymbol{b}` vector for the standard-form problem (see :class:`OptimizationProblem`).""" # Log time. mesmo.utils.log_time("get optimization problem b vector", logger_object=logger) # Instantiate array. b_vector = np.zeros((self.constraints_len, 1)) # Fill vector entries. for constraint_index in self.b_dict: for values in self.b_dict[constraint_index]: # If value is tuple, treat as parameter. if type(values) is tuple: factor, parameter_name, broadcast_len = values values = self.parameters[parameter_name] if len(np.shape(values)) == 0: values = values * np.ones(len(constraint_index)) elif broadcast_len > 1: values = np.concatenate([values] * broadcast_len, axis=0) values = values * factor # Insert entry in b vector. b_vector[constraint_index, 0] += values.ravel() # Log time. mesmo.utils.log_time("get optimization problem b vector", logger_object=logger) return b_vector def get_c_vector(self) -> np.ndarray: r"""Obtain :math:`\boldsymbol{c}` vector for the standard-form problem (see :class:`OptimizationProblem`).""" # Log time. mesmo.utils.log_time("get optimization problem c vector", logger_object=logger) # Instantiate array. c_vector = np.zeros((1, len(self.variables))) # Fill vector entries. for variable_index in self.c_dict: for values in self.c_dict[variable_index]: # If value is tuple, treat as parameter. if type(values) is tuple: parameter_name, broadcast_len = values values = self.parameters[parameter_name] if len(np.shape(values)) == 0: values = values * np.ones(len(variable_index)) elif broadcast_len > 1: if len(np.shape(values)) > 1: values = np.concatenate([values] * broadcast_len, axis=1) else: values = np.concatenate([[values]] * broadcast_len, axis=1) # Insert entry in c vector. c_vector[0, variable_index] += values.ravel() # Log time. mesmo.utils.log_time("get optimization problem c vector", logger_object=logger) return c_vector def get_q_matrix(self) -> sp.spmatrix: r"""Obtain :math:`\boldsymbol{Q}` matrix for the standard-form problem (see :class:`OptimizationProblem`).""" # Log time. mesmo.utils.log_time("get optimization problem Q matrix", logger_object=logger) # Instantiate collections. values_list = list() rows_list = list() columns_list = list() # Collect matrix entries. for variable_1_index, variable_2_index in self.q_dict: for values in self.q_dict[variable_1_index, variable_2_index]: # If value is tuple, treat as parameter. if type(values) is tuple: parameter_name, broadcast_len = values values = self.parameters[parameter_name] if len(np.shape(values)) == 1: values = sp.diags(values) if len(np.shape(values)) == 0: values = values * sp.eye(len(variable_1_index)) elif broadcast_len > 1: if type(values) is np.matrix: values = np.array(values) values = sp.block_diag([values] * broadcast_len) # Obtain row index, column index and values for entry in Q matrix. rows, columns, values = sp.find(values) rows = np.array(variable_1_index)[rows] columns = np.array(variable_2_index)[columns] # Insert entry in collections. values_list.append(values) rows_list.append(rows) columns_list.append(columns) # Instantiate Q matrix. q_matrix = ( sp.coo_matrix( (np.concatenate(values_list), (np.concatenate(rows_list), np.concatenate(columns_list))), shape=(len(self.variables), len(self.variables)), ).tocsr() if len(self.q_dict) > 0 else sp.csr_matrix((len(self.variables), len(self.variables))) ) # Log time. mesmo.utils.log_time("get optimization problem Q matrix", logger_object=logger) return q_matrix def get_d_constant(self) -> float: r"""Obtain :math:`d` value for the standard-form problem (see :class:`OptimizationProblem`).""" # Log time. mesmo.utils.log_time("get optimization problem d constant", logger_object=logger) # Instantiate array. d_constant = 0.0 # Fill vector entries. for values in self.d_dict[0]: # If value is tuple, treat as parameter. if type(values) is tuple: parameter_name, broadcast_len = values values = self.parameters[parameter_name] if broadcast_len > 1: values = values * broadcast_len # Insert entry to d constant. d_constant += float(values) # Log time. mesmo.utils.log_time("get optimization problem d constant", logger_object=logger) return d_constant def solve(self): r"""Solve the optimization problem. - The solve method compiles the standard form of the optimization problem (see :class:`OptimizationProblem`) and passes the standard-form problem to the optimization solver interface. - The solve method currently implements interfaces to 1) Gurobi and 2) CVXPY, where the latter is a high-level convex optimization interface, which in turn allows interfacing further third-party solvers. The intention is to implement more direct solver interfaces on a as-need basis (please raise an issue!), as these interfaces are assumed to allow higher performance than CVXPY for large-scale problems. However, CVXPY is kept as a fallback to allow a high degree of compatibility with various solvers. - The choice of solver and solver interface can be controlled through the config parameters ``optimization > solver_name`` and ``optimization > solver_interface`` (see ``mesmo/config_default.yml``). The default workflow of the solve method is as follows: 1. Obtain problem definition through selected solver interface via :meth:`get_cvxpy_problem()` or :meth:`get_gurobi_problem()`. 2. Solve optimization problem and obtain standard-form results via :meth:`solve_cvxpy()` or :meth:`solve_gurobi()`. The standard-form results include the 1) :math:`\boldsymbol{x}` variable vector value, 2) :math:`\boldsymbol{\mu}` dual vector value and 3) objective value, which are stored into the object attributes :attr:`x_vector`, :attr:`mu_vector` and :attr:`objective`. 3. Obtain results with respect to the original problem formulation via :meth:`get_results()` and :meth:`get_duals()`. These results are 1) decision variable values and 2) constraint dual values, which are stored into the object attributes :attr:`results` and :attr:`duals`. Low-level customizations of the problem definition are possible, e.g. definition of quadratic constraints or second-order conic (SOC) constraints via the solver interfaces, with the following workflow. 1. Obtain problem definition through selected solver interface via :meth:`get_cvxpy_problem()` or :meth:`get_gurobi_problem()`. 2. Customize problem definitions, e.g. add custom constraints directly with the Gurobi or CVXPY interfaces. 3. Solve optimization problem and obtain standard-form results via :meth:`solve_cvxpy()` or :meth:`solve_gurobi()`. 4. Obtain results with respect to the original problem formulation via :meth:`get_results()` and :meth:`get_duals()`. """ # TODO: Add example for low-level customization solve workflow. # Log time. mesmo.utils.log_time(f"solve optimization problem problem", logger_object=logger) logger.debug( f"Solver name: {mesmo.config.config['optimization']['solver_name']};" f" Solver interface: {mesmo.config.config['optimization']['solver_interface']};" f" Problem statistics: {len(self.variables)} variables, {self.constraints_len} constraints" ) # Use CVXPY solver interface, if selected. if mesmo.config.config["optimization"]["solver_interface"] == "cvxpy": self.solve_cvxpy(*self.get_cvxpy_problem()) # Use direct solver interfaces, if selected. elif mesmo.config.config["optimization"]["solver_interface"] == "direct": if mesmo.config.config["optimization"]["solver_name"] == "gurobi": self.solve_gurobi(*self.get_gurobi_problem()) elif mesmo.config.config["optimization"]["solver_name"] == "highs": self.solve_highs() # If no direct solver interface found, fall back to CVXPY interface. else: logger.debug( f"No direct solver interface implemented for" f" '{mesmo.config.config['optimization']['solver_name']}'. Falling back to CVXPY." ) self.solve_cvxpy(*self.get_cvxpy_problem()) # Raise error, if invalid solver interface selected. else: raise ValueError(f"Invalid solver interface: '{mesmo.config.config['optimization']['solver_interface']}'") # Get results / duals. self.results = self.get_results() # Do not retrieve dual variables if mu vector cannot be retrieved. See `solve_gurobi()`. if not all(np.isnan(self.mu_vector)): self.duals = self.get_duals() # Log time. mesmo.utils.log_time(f"solve optimization problem problem", logger_object=logger) def get_gurobi_problem(self) -> (gp.Model, gp.MVar, gp.MConstr, gp.MQuadExpr): """Obtain standard-form problem via Gurobi direct interface.""" # Instantiate Gurobi model. # - A Gurobi model holds a single optimization problem. It consists of a set of variables, a set of constraints, # and the associated attributes. gurobipy_problem = gp.Model() # Set solver parameters. gurobipy_problem.setParam("OutputFlag", int(mesmo.config.config["optimization"]["show_solver_output"])) for key, value in mesmo.config.solver_parameters.items(): gurobipy_problem.setParam(key, value) # Define variables. # - Need to express vectors as 1-D arrays to enable matrix multiplication in constraints (gurobipy limitation). # - Lower bound defaults to 0 and needs to be explicitly overwritten. x_vector = gurobipy_problem.addMVar( shape=(len(self.variables),), lb=-np.inf, ub=np.inf, vtype=gp.GRB.CONTINUOUS, name="x_vector" ) if (self.variables.loc[:, "variable_type"] == "integer").any(): x_vector[self.variables.loc[:, "variable_type"] == "integer"].setAttr("vtype", gp.GRB.INTEGER) if (self.variables.loc[:, "variable_type"] == "binary").any(): x_vector[self.variables.loc[:, "variable_type"] == "binary"].setAttr("vtype", gp.GRB.BINARY) # Define constraints. # - 1-D arrays are interpreted as column vectors (n, 1) (based on gurobipy convention). constraints = self.get_a_matrix() @ x_vector <= self.get_b_vector().ravel() constraints = gurobipy_problem.addConstr(constraints, name="constraints") # Define objective. # - 1-D arrays are interpreted as column vectors (n, 1) (based on gurobipy convention). objective = ( self.get_c_vector().ravel() @ x_vector + x_vector @ (0.5 * self.get_q_matrix()) @ x_vector + self.get_d_constant() ) gurobipy_problem.setObjective(objective, gp.GRB.MINIMIZE) return (gurobipy_problem, x_vector, constraints, objective) def solve_gurobi( self, gurobipy_problem: gp.Model, x_vector: gp.MVar, constraints: gp.MConstr, objective: gp.MQuadExpr ) -> gp.Model: """Solve optimization problem via Gurobi direct interface.""" # Solve optimization problem. gurobipy_problem.optimize() # Raise error if no optimal solution. status_labels = { gp.GRB.INFEASIBLE: "Infeasible", gp.GRB.INF_OR_UNBD: "Infeasible or Unbounded", gp.GRB.UNBOUNDED: "Unbounded", gp.GRB.SUBOPTIMAL: "Suboptimal", } status = gurobipy_problem.getAttr("Status") if status not in [gp.GRB.OPTIMAL, gp.GRB.SUBOPTIMAL]: status = status_labels[status] if status in status_labels.keys() else f"{status} (See Gurobi documentation)" raise RuntimeError(f"Gurobi exited with non-optimal solution status: {status}") elif status == gp.GRB.SUBOPTIMAL: status = status_labels[status] if status in status_labels.keys() else f"{status} (See Gurobi documentation)" logger.warning(f"Gurobi exited with non-optimal solution status: {status}") # Store results. self.x_vector = np.transpose([x_vector.getAttr("x")]) if ( (gurobipy_problem.getAttr("NumQCNZs") == 0) and not ((self.variables.loc[:, "variable_type"] == "integer").any()) and not ((self.variables.loc[:, "variable_type"] == "binary").any()) ): self.mu_vector = np.transpose([constraints.getAttr("Pi")]) else: # Duals are not retrieved if quadratic or SOC constraints have been added to the model. logger.warning( f"Duals of the optimization problem's constraints are not retrieved," f" because either variables have been defined as non-continuous" f" or quadratic / SOC constraints have been added to the problem." f"\nPlease retrieve the duals manually." ) self.mu_vector = np.nan * np.zeros(constraints.shape) self.objective = float(objective.getValue()) return gurobipy_problem def get_cvxpy_problem( self, ) -> (cp.Variable, typing.List[typing.Union[cp.NonPos, cp.Zero, cp.SOC, cp.PSD]], cp.Expression): """Obtain standard-form problem via CVXPY interface.""" # Define variables. x_vector = cp.Variable( shape=(len(self.variables), 1), name="x_vector", integer=( (index, 0) for index, is_integer in enumerate(self.variables.loc[:, "variable_type"] == "integer") if is_integer ) if (self.variables.loc[:, "variable_type"] == "integer").any() else False, boolean=( (index, 0) for index, is_binary in enumerate(self.variables.loc[:, "variable_type"] == "binary") if is_binary ) if (self.variables.loc[:, "variable_type"] == "binary").any() else False, ) # Define constraints. constraints = [self.get_a_matrix() @ x_vector <= self.get_b_vector()] # Define objective. objective = ( self.get_c_vector() @ x_vector + cp.quad_form(x_vector, 0.5 * self.get_q_matrix()) + self.get_d_constant() ) return (x_vector, constraints, objective) def solve_cvxpy( self, x_vector: cp.Variable, constraints: typing.List[typing.Union[cp.NonPos, cp.Zero, cp.SOC, cp.PSD]], objective: cp.Expression, ) -> cp.Problem: """Solve optimization problem via CVXPY interface.""" # Instantiate CVXPY problem. cvxpy_problem = cp.Problem(cp.Minimize(objective), constraints) # Solve optimization problem. cvxpy_problem.solve( solver=( mesmo.config.config["optimization"]["solver_name"].upper() if mesmo.config.config["optimization"]["solver_name"] is not None else None ), verbose=mesmo.config.config["optimization"]["show_solver_output"], **mesmo.config.solver_parameters, ) # Assert that solver exited with an optimal solution. If not, raise an error. if not (cvxpy_problem.status == cp.OPTIMAL): raise RuntimeError(f"CVXPY exited with non-optimal solution status: {cvxpy_problem.status}") # Store results. self.x_vector = x_vector.value self.mu_vector = constraints[0].dual_value self.objective = float(cvxpy_problem.objective.value) return cvxpy_problem def solve_highs(self) -> scipy.optimize.OptimizeResult: """Solve optimization problem via SciPy HiGHS interface.""" # Raise warning if Q matrix is not zero, because HiGHS interface below doesn't consider QP expressions yet. if any((self.get_q_matrix() != 0).data): logger.warning(f"Found QP expression: The HiGHS solver interface does not yet support QP solution.") # Replace infinite values in b vector with maximum floating point value. # - Reason: SciPy optimization interface doesn't accept infinite values. b_vector = self.get_b_vector().ravel() b_vector[b_vector == np.inf] = np.finfo(float).max # Solve optimization problem. scipy_result = scipy.optimize.linprog( self.get_c_vector().ravel(), A_ub=self.get_a_matrix(), b_ub=b_vector, bounds=(None, None), method="highs", options=dict( disp=mesmo.config.config["optimization"]["show_solver_output"], time_limit=mesmo.config.config["optimization"]["time_limit"], ), ) # Assert that solver exited with an optimal solution. If not, raise an error. if not (scipy_result.status == 0): raise RuntimeError(f"HiGHS exited with non-optimal solution status: {scipy_result.message}") # Store results. self.x_vector = np.transpose([scipy_result.x]) self.mu_vector = np.transpose([scipy_result.ineqlin.marginals]) self.objective = scipy_result.fun return scipy_result def get_results(self, x_vector: typing.Union[cp.Variable, np.ndarray] = None) -> dict: """Obtain results for decisions variables. - Results are returned as dictionary with keys corresponding to the variable names that have been defined. """ # Log time. mesmo.utils.log_time("get optimization problem results", logger_object=logger) # Obtain x vector. if x_vector is None: x_vector = self.x_vector elif type(x_vector) is cp.Variable: x_vector = x_vector.value # Instantiate results object. results = dict.fromkeys(self.variables.loc[:, "name"].unique()) # Obtain results for each variable. for name in results: # Get variable dimensions. variable_dimensions = ( self.variables.iloc[self.get_variable_index(name), :] .drop(["name", "variable_type"], axis=1) .drop_duplicates() .dropna(axis=1) ) if len(variable_dimensions.columns) > 0: # Get results from x vector as pandas series. results[name] = pd.Series( x_vector[self.get_variable_index(name), 0], index=pd.MultiIndex.from_frame(variable_dimensions) ) # Reshape to dataframe with timesteps as index and other variable dimensions as columns. if "timestep" in variable_dimensions.columns: results[name] = results[name].unstack( level=[key for key in variable_dimensions.columns if key != "timestep"] ) # If results are obtained as series, convert to dataframe with variable name as column. if type(results[name]) is pd.Series: results[name] = pd.DataFrame(results[name], columns=[name]) else: # Scalar values are obtained as float. results[name] = float(x_vector[self.get_variable_index(name), 0]) # Log time. mesmo.utils.log_time("get optimization problem results", logger_object=logger) return results def get_duals(self) -> dict: """Obtain results for constraint dual variables. - Duals are returned as dictionary with keys corresponding to the constraint names that have been defined. """ # Log time. mesmo.utils.log_time("get optimization problem duals", logger_object=logger) # Instantiate results object. results = dict.fromkeys(self.constraints.loc[:, "name"].unique()) # Obtain results for each constraint. for name in results: # Get constraint dimensions & constraint type. # TODO: Check if this works for scalar constraints without timesteps. constraint_dimensions = pd.MultiIndex.from_frame( self.constraints.iloc[mesmo.utils.get_index(self.constraints, name=name), :] .drop(["name", "constraint_type"], axis=1) .drop_duplicates() .dropna(axis=1) ) constraint_type = pd.Series( self.constraints.loc[self.constraints.loc[:, "name"] == name, "constraint_type"].unique() ) # Get results from x vector as pandas series. if constraint_type.str.contains("==").any(): results[name] = pd.Series( 0.0 - self.mu_vector[ self.constraints.index[ mesmo.utils.get_index(self.constraints, name=name, constraint_type="==>=") ], 0, ] - self.mu_vector[ self.constraints.index[ mesmo.utils.get_index(self.constraints, name=name, constraint_type="==<=") ], 0, ], index=constraint_dimensions, ) elif constraint_type.str.contains(">=").any(): results[name] = pd.Series( 0.0 - self.mu_vector[ self.constraints.index[ mesmo.utils.get_index(self.constraints, name=name, constraint_type=">=") ], 0, ], index=constraint_dimensions, ) elif constraint_type.str.contains("<=").any(): results[name] = pd.Series( 0.0 - self.mu_vector[ self.constraints.index[ mesmo.utils.get_index(self.constraints, name=name, constraint_type="<=") ], 0, ], index=constraint_dimensions, ) # Reshape to dataframe with timesteps as index and other constraint dimensions as columns. results[name] = results[name].unstack( level=[key for key in constraint_dimensions.names if key != "timestep"] ) # If no other dimensions, e.g. for scalar constraints, convert to dataframe with constraint name as column. if type(results[name]) is pd.Series: results[name] = pd.DataFrame(results[name], columns=[name]) # Log time. mesmo.utils.log_time("get optimization problem duals", logger_object=logger) return results def evaluate_objective(self, x_vector: np.ndarray) -> float: r"""Utility function for evaluating the objective value for a given :math:`x` vector value.""" objective = float( self.get_c_vector() @ x_vector + x_vector.T @ (0.5 * self.get_q_matrix()) @ x_vector + self.get_d_constant() ) return objective
[ "pandas.DataFrame", "scipy.sparse.diags", "scipy.sparse.find", "numpy.transpose", "numpy.zeros", "gurobipy.Model", "numpy.isnan", "collections.defaultdict", "numpy.finfo", "numpy.shape", "numpy.array", "pandas.MultiIndex.from_frame", "scipy.sparse.block_diag", "pandas.concat", "numpy.con...
[((6193, 6252), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['name', 'timestep', 'variable_type']"}), "(columns=['name', 'timestep', 'variable_type'])\n", (6205, 6252), True, 'import pandas as pd\n'), ((6280, 6341), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['name', 'timestep', 'constraint_type']"}), "(columns=['name', 'timestep', 'constraint_type'])\n", (6292, 6341), True, 'import pandas as pd\n'), ((6943, 6972), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (6966, 6972), False, 'import collections\n'), ((6995, 7024), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (7018, 7024), False, 'import collections\n'), ((7047, 7076), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (7070, 7076), False, 'import collections\n'), ((7099, 7128), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (7122, 7128), False, 'import collections\n'), ((7151, 7180), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (7174, 7180), False, 'import collections\n'), ((41696, 41731), 'numpy.zeros', 'np.zeros', (['(self.constraints_len, 1)'], {}), '((self.constraints_len, 1))\n', (41704, 41731), True, 'import numpy as np\n'), ((52232, 52242), 'gurobipy.Model', 'gp.Model', ([], {}), '()\n', (52240, 52242), True, 'import gurobipy as gp\n'), ((60107, 60137), 'numpy.transpose', 'np.transpose', (['[scipy_result.x]'], {}), '([scipy_result.x])\n', (60119, 60137), True, 'import numpy as np\n'), ((60163, 60209), 'numpy.transpose', 'np.transpose', (['[scipy_result.ineqlin.marginals]'], {}), '([scipy_result.ineqlin.marginals])\n', (60175, 60209), True, 'import numpy as np\n'), ((57771, 57793), 'cvxpy.Minimize', 'cp.Minimize', (['objective'], {}), '(objective)\n', (57782, 57793), True, 'import cvxpy as cp\n'), ((59340, 59355), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (59348, 59355), True, 'import numpy as np\n'), ((9322, 9383), 'pandas.concat', 'pd.concat', (['[self.variables, new_variables]'], {'ignore_index': '(True)'}), '([self.variables, new_variables], ignore_index=True)\n', (9331, 9383), True, 'import pandas as pd\n'), ((10152, 10167), 'numpy.shape', 'np.shape', (['value'], {}), '(value)\n', (10160, 10167), True, 'import numpy as np\n'), ((10171, 10202), 'numpy.shape', 'np.shape', (['self.parameters[name]'], {}), '(self.parameters[name])\n', (10179, 10202), True, 'import numpy as np\n'), ((35252, 35276), 'scipy.sparse.diags', 'sp.diags', (['variable_value'], {}), '(variable_value)\n', (35260, 35276), True, 'import scipy.sparse as sp\n'), ((35746, 35793), 'scipy.sparse.block_diag', 'sp.block_diag', (['([variable_value] * broadcast_len)'], {}), '([variable_value] * broadcast_len)\n', (35759, 35793), True, 'import scipy.sparse as sp\n'), ((40687, 40702), 'scipy.sparse.find', 'sp.find', (['values'], {}), '(values)\n', (40694, 40702), True, 'import scipy.sparse as sp\n'), ((45354, 45369), 'scipy.sparse.find', 'sp.find', (['values'], {}), '(values)\n', (45361, 45369), True, 'import scipy.sparse as sp\n'), ((51668, 51692), 'numpy.isnan', 'np.isnan', (['self.mu_vector'], {}), '(self.mu_vector)\n', (51676, 51692), True, 'import numpy as np\n'), ((56036, 56063), 'numpy.zeros', 'np.zeros', (['constraints.shape'], {}), '(constraints.shape)\n', (56044, 56063), True, 'import numpy as np\n'), ((65736, 65779), 'pandas.DataFrame', 'pd.DataFrame', (['results[name]'], {'columns': '[name]'}), '(results[name], columns=[name])\n', (65748, 65779), True, 'import pandas as pd\n'), ((31756, 31780), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (31764, 31780), True, 'import numpy as np\n'), ((32392, 32416), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (32400, 32416), True, 'import numpy as np\n'), ((35126, 35150), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (35134, 35150), True, 'import numpy as np\n'), ((35389, 35413), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (35397, 35413), True, 'import numpy as np\n'), ((35688, 35712), 'numpy.array', 'np.array', (['variable_value'], {}), '(variable_value)\n', (35696, 35712), True, 'import numpy as np\n'), ((35877, 35901), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (35885, 35901), True, 'import numpy as np\n'), ((36290, 36314), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (36298, 36314), True, 'import numpy as np\n'), ((37996, 38020), 'numpy.shape', 'np.shape', (['constant_value'], {}), '(constant_value)\n', (38004, 38020), True, 'import numpy as np\n'), ((40726, 40752), 'numpy.array', 'np.array', (['constraint_index'], {}), '(constraint_index)\n', (40734, 40752), True, 'import numpy as np\n'), ((40785, 40809), 'numpy.array', 'np.array', (['variable_index'], {}), '(variable_index)\n', (40793, 40809), True, 'import numpy as np\n'), ((45393, 45419), 'numpy.array', 'np.array', (['variable_1_index'], {}), '(variable_1_index)\n', (45401, 45419), True, 'import numpy as np\n'), ((45452, 45478), 'numpy.array', 'np.array', (['variable_2_index'], {}), '(variable_2_index)\n', (45460, 45478), True, 'import numpy as np\n'), ((62138, 62181), 'pandas.DataFrame', 'pd.DataFrame', (['results[name]'], {'columns': '[name]'}), '(results[name], columns=[name])\n', (62150, 62181), True, 'import pandas as pd\n'), ((19581, 19607), 'numpy.array', 'np.array', (['[variable_value]'], {}), '([variable_value])\n', (19589, 19607), True, 'import numpy as np\n'), ((20571, 20595), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (20579, 20595), True, 'import numpy as np\n'), ((32105, 32161), 'numpy.concatenate', 'np.concatenate', (['([variable_value] * broadcast_len)'], {'axis': '(1)'}), '([variable_value] * broadcast_len, axis=1)\n', (32119, 32161), True, 'import numpy as np\n'), ((32229, 32287), 'numpy.concatenate', 'np.concatenate', (['([[variable_value]] * broadcast_len)'], {'axis': '(1)'}), '([[variable_value]] * broadcast_len, axis=1)\n', (32243, 32287), True, 'import numpy as np\n'), ((32442, 32466), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (32450, 32466), True, 'import numpy as np\n'), ((32873, 32897), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (32881, 32897), True, 'import numpy as np\n'), ((32799, 32823), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (32807, 32823), True, 'import numpy as np\n'), ((32924, 32948), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (32932, 32948), True, 'import numpy as np\n'), ((40154, 40172), 'numpy.array', 'np.array', (['[values]'], {}), '([values])\n', (40162, 40172), True, 'import numpy as np\n'), ((41073, 41100), 'numpy.concatenate', 'np.concatenate', (['values_list'], {}), '(values_list)\n', (41087, 41100), True, 'import numpy as np\n'), ((44866, 44882), 'scipy.sparse.diags', 'sp.diags', (['values'], {}), '(values)\n', (44874, 44882), True, 'import scipy.sparse as sp\n'), ((61535, 61580), 'pandas.MultiIndex.from_frame', 'pd.MultiIndex.from_frame', (['variable_dimensions'], {}), '(variable_dimensions)\n', (61559, 61580), True, 'import pandas as pd\n'), ((19512, 19536), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (19520, 19536), True, 'import numpy as np\n'), ((19720, 19744), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (19728, 19744), True, 'import numpy as np\n'), ((20114, 20161), 'scipy.sparse.block_diag', 'sp.block_diag', (['([variable_value] * broadcast_len)'], {}), '([variable_value] * broadcast_len)\n', (20127, 20161), True, 'import scipy.sparse as sp\n'), ((22520, 22544), 'numpy.shape', 'np.shape', (['constant_value'], {}), '(constant_value)\n', (22528, 22544), True, 'import numpy as np\n'), ((22796, 22852), 'numpy.concatenate', 'np.concatenate', (['([constant_value] * broadcast_len)'], {'axis': '(0)'}), '([constant_value] * broadcast_len, axis=0)\n', (22810, 22852), True, 'import numpy as np\n'), ((22978, 23002), 'numpy.shape', 'np.shape', (['constant_value'], {}), '(constant_value)\n', (22986, 23002), True, 'import numpy as np\n'), ((32033, 32057), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (32041, 32057), True, 'import numpy as np\n'), ((40097, 40113), 'numpy.shape', 'np.shape', (['values'], {}), '(values)\n', (40105, 40113), True, 'import numpy as np\n'), ((40200, 40216), 'numpy.shape', 'np.shape', (['values'], {}), '(values)\n', (40208, 40216), True, 'import numpy as np\n'), ((40479, 40518), 'scipy.sparse.block_diag', 'sp.block_diag', (['([values] * broadcast_len)'], {}), '([values] * broadcast_len)\n', (40492, 40518), True, 'import scipy.sparse as sp\n'), ((41103, 41128), 'numpy.concatenate', 'np.concatenate', (['rows_list'], {}), '(rows_list)\n', (41117, 41128), True, 'import numpy as np\n'), ((41130, 41158), 'numpy.concatenate', 'np.concatenate', (['columns_list'], {}), '(columns_list)\n', (41144, 41158), True, 'import numpy as np\n'), ((42120, 42136), 'numpy.shape', 'np.shape', (['values'], {}), '(values)\n', (42128, 42136), True, 'import numpy as np\n'), ((42294, 42342), 'numpy.concatenate', 'np.concatenate', (['([values] * broadcast_len)'], {'axis': '(0)'}), '([values] * broadcast_len, axis=0)\n', (42308, 42342), True, 'import numpy as np\n'), ((43360, 43376), 'numpy.shape', 'np.shape', (['values'], {}), '(values)\n', (43368, 43376), True, 'import numpy as np\n'), ((44809, 44825), 'numpy.shape', 'np.shape', (['values'], {}), '(values)\n', (44817, 44825), True, 'import numpy as np\n'), ((44910, 44926), 'numpy.shape', 'np.shape', (['values'], {}), '(values)\n', (44918, 44926), True, 'import numpy as np\n'), ((45191, 45230), 'scipy.sparse.block_diag', 'sp.block_diag', (['([values] * broadcast_len)'], {}), '([values] * broadcast_len)\n', (45204, 45230), True, 'import scipy.sparse as sp\n'), ((45760, 45787), 'numpy.concatenate', 'np.concatenate', (['values_list'], {}), '(values_list)\n', (45774, 45787), True, 'import numpy as np\n'), ((20052, 20076), 'numpy.array', 'np.array', (['variable_value'], {}), '(variable_value)\n', (20060, 20076), True, 'import numpy as np\n'), ((23032, 23056), 'numpy.shape', 'np.shape', (['constant_value'], {}), '(constant_value)\n', (23040, 23056), True, 'import numpy as np\n'), ((40429, 40445), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (40437, 40445), True, 'import numpy as np\n'), ((43590, 43638), 'numpy.concatenate', 'np.concatenate', (['([values] * broadcast_len)'], {'axis': '(1)'}), '([values] * broadcast_len, axis=1)\n', (43604, 43638), True, 'import numpy as np\n'), ((43706, 43756), 'numpy.concatenate', 'np.concatenate', (['([[values]] * broadcast_len)'], {'axis': '(1)'}), '([[values]] * broadcast_len, axis=1)\n', (43720, 43756), True, 'import numpy as np\n'), ((45141, 45157), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (45149, 45157), True, 'import numpy as np\n'), ((45790, 45815), 'numpy.concatenate', 'np.concatenate', (['rows_list'], {}), '(rows_list)\n', (45804, 45815), True, 'import numpy as np\n'), ((45817, 45845), 'numpy.concatenate', 'np.concatenate', (['columns_list'], {}), '(columns_list)\n', (45831, 45845), True, 'import numpy as np\n'), ((43530, 43546), 'numpy.shape', 'np.shape', (['values'], {}), '(values)\n', (43538, 43546), True, 'import numpy as np\n'), ((20429, 20453), 'numpy.shape', 'np.shape', (['variable_value'], {}), '(variable_value)\n', (20437, 20453), True, 'import numpy as np\n')]
""" train_gymcc.py train an agent on gym classic control environment. Supported environments : """ import os import sys import time import argparse import importlib from functools import partial from collections import OrderedDict import gym import numpy as np import yaml from stable_baselines.common import set_global_seeds from stable_baselines.common.cmd_util import make_atari_env from stable_baselines.common.vec_env import VecFrameStack, SubprocVecEnv, VecNormalize, DummyVecEnv from stable_baselines.common.noise import AdaptiveParamNoiseSpec, NormalActionNoise, OrnsteinUhlenbeckActionNoise from stable_baselines.ppo2.ppo2 import constfn # todo: consider adding it directly to the config class of ppo try: import mpi4py from mpi4py import MPI except ImportError: mpi4py = None from zoo.utils import make_env, ALGOS, linear_schedule, get_latest_run_id, get_wrapper_class, find_saved_model from zoo.utils.hyperparams_opt import hyperparam_optimization from zoo.utils.noise import LinearNormalActionNoise from my_zoo.utils.common import * from my_zoo.hyperparams.default_config import CC_ENVS CONFIGS_DIR = os.path.join(os.path.expanduser('~'),'share','Data','MLA','stbl','configs') LOGGER_NAME=os.path.splitext(os.path.basename(__file__))[0] def parse_cmd_line(): parser = argparse.ArgumentParser() parser.add_argument('exparams', type=str, help='experiment params file path') parser.add_argument('-d','--gpuid',type=str,default='',help='gpu id or "cpu"') parser.add_argument('--num_experiments', help='number of experiments', default=1,type=int) parser.add_argument('--seed', help='Random generator seed', type=int, default=1) parser.add_argument('-i', '--trained_agent', help='Path to a pretrained agent to continue training', default='', type=str) parser.add_argument('-n', '--n_timesteps', help='Overwrite the number of timesteps', default=-1,type=int) parser.add_argument('--log_interval', help='Override log interval (default: -1, no change)', default=-1,type=int) args = parser.parse_args() return args def create_logger(exp_params,stdout_to_log=True): log_file_name=os.path.join(exp_params.output_root_dir,exp_params.name+'.log') log_level=exp_params.log_level log_format=exp_params.log_format logger = MyLogger(LOGGER_NAME,filename=log_file_name, level=log_level,format=log_format).get_logger() if stdout_to_log: sys.stdout = StreamToLogger(logger, logging.INFO) sys.stderr = StreamToLogger(logger, logging.ERROR) return logger def get_create_env(algo,seed,env_params): # logger = logging.getLogger(LOGGER_NAME) env_id = CC_ENVS.get(env_params.env_id,None) assert env_id , "env {0} is not supported".format(env_id) is_atari= 'NoFrameskip' in env_id # n_envs = experiment_params.get('n_envs', 1) normalize_kwargs = {'norm_obs':env_params.norm_obs,'norm_reward':env_params.norm_reward} normalize = normalize_kwargs['norm_obs'] or normalize_kwargs['norm_reward'] # obtain a class object from a wrapper name string in hyperparams # and delete the entry env_wrapper = get_wrapper_class(env_params.as_dict()) if env_params.env_wrapper else None def _create_env(n_envs): """ Create the environment and wrap it if necessary :param n_envs: (int) :return: (gym.Env) """ if is_atari: logger.info("Using Atari wrapper") env = make_atari_env(env_id, num_env=n_envs, seed=seed) # Frame-stacking with 4 frames env = VecFrameStack(env, n_stack=4) elif algo in ['dqn', 'ddpg']: if normalize: logger.warning("WARNING: normalization not supported yet for DDPG/DQN") env = gym.make(env_id) env.seed(seed) if env_wrapper is not None: env = env_wrapper(env) else: if n_envs == 1: env = DummyVecEnv([make_env(env_id, 0, seed, wrapper_class=env_wrapper)]) else: # env = SubprocVecEnv([make_env(env_id, i, seed) for i in range(n_envs)]) # On most env, SubprocVecEnv does not help and is quite memory hungry env = DummyVecEnv([make_env(env_id, i, seed, wrapper_class=env_wrapper) for i in range(n_envs)]) if normalize: logger.info("Normalization activated: {}".format(normalize_kwargs)) env = VecNormalize(env, **normalize_kwargs) # Optional Frame-stacking if env_params.frame_stack>1: n_stack = env_params.frame_stack env = VecFrameStack(env, n_stack) logger.info("Stacking {} frames".format(n_stack)) return env return _create_env # return partial(_create_env,env_wrapper) def parse_agent_params(hyperparams,n_actions,n_timesteps): algo = hyperparams['algorithm'] del hyperparams['algorithm'] # Parse the schedule parameters for the relevant algorithms if algo in ["ppo2", "sac", "td3"]: for key in ['learning_rate', 'cliprange', 'cliprange_vf']: if key not in hyperparams or hyperparams[key] is None: continue if isinstance(hyperparams[key], str): schedule, initial_value = hyperparams[key].split('_') initial_value = float(initial_value) hyperparams[key] = linear_schedule(initial_value) elif isinstance(hyperparams[key], (float, int)): # Negative value: ignore (ex: for clipping) if hyperparams[key] < 0: continue hyperparams[key] = constfn(float(hyperparams[key])) else: raise ValueError('Invalid value for {}: {}'.format(key, hyperparams[key])) # Parse noise string for DDPG and SAC if algo in ['ddpg', 'sac', 'td3'] and hyperparams.get('noise_type') is not None: noise_type = hyperparams['noise_type'].strip() noise_std = hyperparams['noise_std'] if 'adaptive-param' in noise_type: assert algo == 'ddpg', 'Parameter is not supported by SAC' hyperparams['param_noise'] = AdaptiveParamNoiseSpec(initial_stddev=noise_std, desired_action_stddev=noise_std) elif 'normal' in noise_type: if 'lin' in noise_type: hyperparams['action_noise'] = LinearNormalActionNoise(mean=np.zeros(n_actions), sigma=noise_std * np.ones(n_actions), final_sigma=hyperparams.get('noise_std_final', 0.0) * np.ones(n_actions), max_steps=n_timesteps) else: hyperparams['action_noise'] = NormalActionNoise(mean=np.zeros(n_actions), sigma=noise_std * np.ones(n_actions)) elif 'ornstein-uhlenbeck' in noise_type: hyperparams['action_noise'] = OrnsteinUhlenbeckActionNoise(mean=np.zeros(n_actions), sigma=noise_std * np.ones(n_actions)) else: raise RuntimeError('Unknown noise type "{}"'.format(noise_type)) logger.info("Applying {} noise with std {}".format(noise_type, noise_std)) del hyperparams['noise_type'] del hyperparams['noise_std'] if 'noise_std_final' in hyperparams: del hyperparams['noise_std_final'] return def do_hpopt(algo,create_env,experiment_params,output_dir): if experiment_params.verbose > 0: logger.info("Optimizing hyperparameters") def create_model(*_args, **kwargs): """ Helper to create a model with different hyperparameters """ return ALGOS[algo](env=create_env(experiment_params.n_envs), tensorboard_log=experiment_params.agent_params.tensorboard_log, verbose=0, **kwargs) data_frame = hyperparam_optimization(algo, create_model, create_env, n_trials=experiment_params.n_trials, n_timesteps=experiment_params.n_timesteps, hyperparams=experiment_params.agent_params, n_jobs=experiment_params.n_jobs, seed=experiment_params.seed, sampler_method=experiment_params.sampler, pruner_method=experiment_params.pruner, verbose=experiment_params.verbose) env_id = experiment_params.env_params.env_id report_name = "report_{}_{}-trials-{}-{}-{}_{}.csv".format(env_id, experiment_params.n_trials, experiment_params.n_timesteps, experiment_params.sampler, experiment_params.pruner, int(time.time())) log_path = os.path.join(output_dir, report_name) if experiment_params.verbose: logger.info("Writing report to {}".format(log_path)) os.makedirs(os.path.dirname(log_path), exist_ok=True) data_frame.to_csv(log_path) return def run_experiment(experiment_params): # logger = logging.getLogger(LOGGER_NAME) seed=experiment_params.seed rank = 0 if mpi4py is not None and MPI.COMM_WORLD.Get_size() > 1: print("Using MPI for multiprocessing with {} workers".format(MPI.COMM_WORLD.Get_size())) rank = MPI.COMM_WORLD.Get_rank() print("Worker rank: {}".format(rank)) # make sure that each worker has its own seed seed += rank # we allow only one worker to "speak" if rank != 0: experiment_params.verbose = 0 logger.info(title("starting experiment seed {}".format(seed),30)) # create a working directory for the relevant seed output_dir=os.path.join(experiment_params.output_root_dir,str(seed)) os.makedirs(output_dir, exist_ok=True) # logger.info(experiment_params.as_dict()) # set global seeds set_global_seeds(experiment_params.seed) agent_hyperparams = experiment_params.agent_params.as_dict() env_params_dict = experiment_params.env_params.as_dict() exparams_dict = experiment_params.as_dict() saved_env_params = OrderedDict([(key, str(env_params_dict[key])) for key in sorted(env_params_dict.keys())]) saved_agent_hyperparams = OrderedDict([(key, str(agent_hyperparams[key])) for key in sorted(agent_hyperparams.keys())]) saved_hyperparams = OrderedDict([(key, str(exparams_dict[key])) for key in exparams_dict.keys()]) saved_hyperparams['agent_params']=saved_agent_hyperparams saved_hyperparams['env_params'] = saved_env_params # parse algorithm algo = agent_hyperparams['algorithm'] experiment_params.agent_params.seed = seed if experiment_params.verbose>0: experiment_params.agent_params.verbose = experiment_params.verbose experiment_params.agent_params.tensorboard_log = output_dir ################### # make the env n_envs = experiment_params.n_envs env_id = experiment_params.env_params.env_id logger.info('using {0} instances of {1} :'.format(n_envs,env_id)) create_env = get_create_env(algo,seed,experiment_params.env_params) env = create_env(n_envs) # Stop env processes to free memory - not clear.... if experiment_params.hp_optimize and n_envs > 1: env.close() ##################### # create the agent if ALGOS[algo] is None: raise ValueError('{} requires MPI to be installed'.format(algo)) # n_actions = env.action_space.shape[0] n_actions = 1 if isinstance(env.action_space,gym.spaces.Discrete) else env.action_space.shape[0] parse_agent_params(agent_hyperparams,n_actions,experiment_params.n_timesteps) if experiment_params.trained_agent: valid_extension = experiment_params.trained_agent.endswith('.pkl') or experiment_params.trained_agent.endswith('.zip') assert valid_extension and os.path.isfile(experiment_params.trained_agent), \ "The trained_agent must be a valid path to a .zip/.pkl file" # todo: handle the case of "her" wrapper. if experiment_params.hp_optimize: # do_hpopt(algo,create_env,experiment_params,output_dir) logger.warning("hyper parameter optimization is not yet supported") else: normalize = experiment_params.env_params.norm_obs or experiment_params.env_params.norm_reward trained_agent = experiment_params.trained_agent if trained_agent: valid_extension = trained_agent.endswith('.pkl') or trained_agent.endswith('.zip') assert valid_extension and os.path.isfile(trained_agent), \ "The trained_agent must be a valid path to a .zip/.pkl file" logger.info("loading pretrained agent to continue training") # if policy is defined, delete as it will be loaded with the trained agent del agent_hyperparams['policy'] model = ALGOS[algo].load(trained_agent, env=env,**agent_hyperparams) exp_folder = trained_agent[:-4] if normalize: logger.info("Loading saved running average") env.load_running_average(exp_folder) else: # create a model from scratch model = ALGOS[algo](env=env, **agent_hyperparams) kwargs = {} if experiment_params.log_interval > -1: kwargs = {'log_interval': experiment_params.log_interval} model.learn(int(experiment_params.n_timesteps), **kwargs) # Save trained model save_path = output_dir params_path = "{}/{}".format(save_path, 'model_params') os.makedirs(params_path, exist_ok=True) # Only save worker of rank 0 when using mpi if rank == 0: logger.info("Saving to {}".format(save_path)) model.save(params_path) # Save hyperparams # note that in order to save as yaml I need to avoid using classes in the definition. # e.g. CustomDQNPolicy will not work. I need to put a string and parse it later with open(os.path.join(output_dir, 'config.yml'), 'w') as f: yaml.dump(saved_hyperparams, f) if normalize: # Unwrap if isinstance(env, VecFrameStack): env = env.venv # Important: save the running average, for testing the agent we need that normalization env.save_running_average(params_path) logger.info(title("completed experiment seed {seed}",30)) return def main(): args = parse_cmd_line() print('reading experiment params from '+args.exparams) module_path = 'my_zoo.hyperparams.'+args.exparams exp_params_module = importlib.import_module(module_path) experiment_params = getattr(exp_params_module,'experiment_params') # set compute device if args.gpuid=='cpu': set_gpu_device('') elif len(args.gpuid)>0: set_gpu_device(args.gpuid) else: pass # create experiment folder and logger exp_folder_name = args.exparams + '-' + time.strftime("%d-%m-%Y_%H-%M-%S") experiment_params.output_root_dir = os.path.join(experiment_params.output_root_dir,exp_folder_name) os.makedirs(experiment_params.output_root_dir, exist_ok=True) global logger logger = create_logger(experiment_params,stdout_to_log=False) # check if some cmd line arguments should override the experiment params if args.n_timesteps > -1: logger.info("overriding n_timesteps with {}".format(args.n_timesteps)) experiment_params.n_timesteps=args.n_timesteps if args.log_interval > -1: logger.info("overriding log_interval with {}".format(args.log_interval)) experiment_params.log_interval=args.log_interval if args.trained_agent != '': logger.info("overriding trained_agent with {}".format(args.trained_agent)) experiment_params.trained_agent=args.trained_agent logger.info(title('Starting {0} experiments'.format(args.num_experiments), 40)) for e in range(args.num_experiments): seed = args.seed+100*e experiment_params.seed = seed # run experiment will generate its own sub folder for each seed # not yet clear how to support hyper parameter search... run_experiment(experiment_params) # prepare for shutdown logger sys.stdout=sys.__stdout__ sys.stderr=sys.__stderr__ logging.shutdown() return if __name__ == '__main__': suppress_tensorflow_warnings() main()
[ "argparse.ArgumentParser", "stable_baselines.common.set_global_seeds", "stable_baselines.common.noise.AdaptiveParamNoiseSpec", "stable_baselines.common.cmd_util.make_atari_env", "yaml.dump", "time.strftime", "numpy.ones", "os.path.isfile", "os.path.join", "zoo.utils.linear_schedule", "os.path.di...
[((1146, 1169), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (1164, 1169), False, 'import os\n'), ((1309, 1334), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1332, 1334), False, 'import argparse\n'), ((2177, 2243), 'os.path.join', 'os.path.join', (['exp_params.output_root_dir', "(exp_params.name + '.log')"], {}), "(exp_params.output_root_dir, exp_params.name + '.log')\n", (2189, 2243), False, 'import os\n'), ((2703, 2739), 'my_zoo.hyperparams.default_config.CC_ENVS.get', 'CC_ENVS.get', (['env_params.env_id', 'None'], {}), '(env_params.env_id, None)\n', (2714, 2739), False, 'from my_zoo.hyperparams.default_config import CC_ENVS\n'), ((8227, 8609), 'zoo.utils.hyperparams_opt.hyperparam_optimization', 'hyperparam_optimization', (['algo', 'create_model', 'create_env'], {'n_trials': 'experiment_params.n_trials', 'n_timesteps': 'experiment_params.n_timesteps', 'hyperparams': 'experiment_params.agent_params', 'n_jobs': 'experiment_params.n_jobs', 'seed': 'experiment_params.seed', 'sampler_method': 'experiment_params.sampler', 'pruner_method': 'experiment_params.pruner', 'verbose': 'experiment_params.verbose'}), '(algo, create_model, create_env, n_trials=\n experiment_params.n_trials, n_timesteps=experiment_params.n_timesteps,\n hyperparams=experiment_params.agent_params, n_jobs=experiment_params.\n n_jobs, seed=experiment_params.seed, sampler_method=experiment_params.\n sampler, pruner_method=experiment_params.pruner, verbose=\n experiment_params.verbose)\n', (8250, 8609), False, 'from zoo.utils.hyperparams_opt import hyperparam_optimization\n'), ((9287, 9324), 'os.path.join', 'os.path.join', (['output_dir', 'report_name'], {}), '(output_dir, report_name)\n', (9299, 9324), False, 'import os\n'), ((10292, 10330), 'os.makedirs', 'os.makedirs', (['output_dir'], {'exist_ok': '(True)'}), '(output_dir, exist_ok=True)\n', (10303, 10330), False, 'import os\n'), ((10407, 10447), 'stable_baselines.common.set_global_seeds', 'set_global_seeds', (['experiment_params.seed'], {}), '(experiment_params.seed)\n', (10423, 10447), False, 'from stable_baselines.common import set_global_seeds\n'), ((15201, 15237), 'importlib.import_module', 'importlib.import_module', (['module_path'], {}), '(module_path)\n', (15224, 15237), False, 'import importlib\n'), ((15636, 15700), 'os.path.join', 'os.path.join', (['experiment_params.output_root_dir', 'exp_folder_name'], {}), '(experiment_params.output_root_dir, exp_folder_name)\n', (15648, 15700), False, 'import os\n'), ((15704, 15765), 'os.makedirs', 'os.makedirs', (['experiment_params.output_root_dir'], {'exist_ok': '(True)'}), '(experiment_params.output_root_dir, exist_ok=True)\n', (15715, 15765), False, 'import os\n'), ((1238, 1264), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (1254, 1264), False, 'import os\n'), ((9438, 9463), 'os.path.dirname', 'os.path.dirname', (['log_path'], {}), '(log_path)\n', (9453, 9463), False, 'import os\n'), ((9831, 9856), 'mpi4py.MPI.COMM_WORLD.Get_rank', 'MPI.COMM_WORLD.Get_rank', ([], {}), '()\n', (9854, 9856), False, 'from mpi4py import MPI\n'), ((14098, 14137), 'os.makedirs', 'os.makedirs', (['params_path'], {'exist_ok': '(True)'}), '(params_path, exist_ok=True)\n', (14109, 14137), False, 'import os\n'), ((15561, 15595), 'time.strftime', 'time.strftime', (['"""%d-%m-%Y_%H-%M-%S"""'], {}), "('%d-%m-%Y_%H-%M-%S')\n", (15574, 15595), False, 'import time\n'), ((3507, 3556), 'stable_baselines.common.cmd_util.make_atari_env', 'make_atari_env', (['env_id'], {'num_env': 'n_envs', 'seed': 'seed'}), '(env_id, num_env=n_envs, seed=seed)\n', (3521, 3556), False, 'from stable_baselines.common.cmd_util import make_atari_env\n'), ((3618, 3647), 'stable_baselines.common.vec_env.VecFrameStack', 'VecFrameStack', (['env'], {'n_stack': '(4)'}), '(env, n_stack=4)\n', (3631, 3647), False, 'from stable_baselines.common.vec_env import VecFrameStack, SubprocVecEnv, VecNormalize, DummyVecEnv\n'), ((4684, 4711), 'stable_baselines.common.vec_env.VecFrameStack', 'VecFrameStack', (['env', 'n_stack'], {}), '(env, n_stack)\n', (4697, 4711), False, 'from stable_baselines.common.vec_env import VecFrameStack, SubprocVecEnv, VecNormalize, DummyVecEnv\n'), ((6245, 6331), 'stable_baselines.common.noise.AdaptiveParamNoiseSpec', 'AdaptiveParamNoiseSpec', ([], {'initial_stddev': 'noise_std', 'desired_action_stddev': 'noise_std'}), '(initial_stddev=noise_std, desired_action_stddev=\n noise_std)\n', (6267, 6331), False, 'from stable_baselines.common.noise import AdaptiveParamNoiseSpec, NormalActionNoise, OrnsteinUhlenbeckActionNoise\n'), ((9257, 9268), 'time.time', 'time.time', ([], {}), '()\n', (9266, 9268), False, 'import time\n'), ((9688, 9713), 'mpi4py.MPI.COMM_WORLD.Get_size', 'MPI.COMM_WORLD.Get_size', ([], {}), '()\n', (9711, 9713), False, 'from mpi4py import MPI\n'), ((12387, 12434), 'os.path.isfile', 'os.path.isfile', (['experiment_params.trained_agent'], {}), '(experiment_params.trained_agent)\n', (12401, 12434), False, 'import os\n'), ((3818, 3834), 'gym.make', 'gym.make', (['env_id'], {}), '(env_id)\n', (3826, 3834), False, 'import gym\n'), ((5463, 5493), 'zoo.utils.linear_schedule', 'linear_schedule', (['initial_value'], {}), '(initial_value)\n', (5478, 5493), False, 'from zoo.utils import make_env, ALGOS, linear_schedule, get_latest_run_id, get_wrapper_class, find_saved_model\n'), ((9788, 9813), 'mpi4py.MPI.COMM_WORLD.Get_size', 'MPI.COMM_WORLD.Get_size', ([], {}), '()\n', (9811, 9813), False, 'from mpi4py import MPI\n'), ((13066, 13095), 'os.path.isfile', 'os.path.isfile', (['trained_agent'], {}), '(trained_agent)\n', (13080, 13095), False, 'import os\n'), ((14617, 14648), 'yaml.dump', 'yaml.dump', (['saved_hyperparams', 'f'], {}), '(saved_hyperparams, f)\n', (14626, 14648), False, 'import yaml\n'), ((4512, 4549), 'stable_baselines.common.vec_env.VecNormalize', 'VecNormalize', (['env'], {}), '(env, **normalize_kwargs)\n', (4524, 4549), False, 'from stable_baselines.common.vec_env import VecFrameStack, SubprocVecEnv, VecNormalize, DummyVecEnv\n'), ((14550, 14588), 'os.path.join', 'os.path.join', (['output_dir', '"""config.yml"""'], {}), "(output_dir, 'config.yml')\n", (14562, 14588), False, 'import os\n'), ((4018, 4070), 'zoo.utils.make_env', 'make_env', (['env_id', '(0)', 'seed'], {'wrapper_class': 'env_wrapper'}), '(env_id, 0, seed, wrapper_class=env_wrapper)\n', (4026, 4070), False, 'from zoo.utils import make_env, ALGOS, linear_schedule, get_latest_run_id, get_wrapper_class, find_saved_model\n'), ((4302, 4354), 'zoo.utils.make_env', 'make_env', (['env_id', 'i', 'seed'], {'wrapper_class': 'env_wrapper'}), '(env_id, i, seed, wrapper_class=env_wrapper)\n', (4310, 4354), False, 'from zoo.utils import make_env, ALGOS, linear_schedule, get_latest_run_id, get_wrapper_class, find_saved_model\n'), ((6539, 6558), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n', (6547, 6558), True, 'import numpy as np\n'), ((6992, 7011), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n', (7000, 7011), True, 'import numpy as np\n'), ((7240, 7259), 'numpy.zeros', 'np.zeros', (['n_actions'], {}), '(n_actions)\n', (7248, 7259), True, 'import numpy as np\n'), ((6648, 6666), 'numpy.ones', 'np.ones', (['n_actions'], {}), '(n_actions)\n', (6655, 6666), True, 'import numpy as np\n'), ((6792, 6810), 'numpy.ones', 'np.ones', (['n_actions'], {}), '(n_actions)\n', (6799, 6810), True, 'import numpy as np\n'), ((7095, 7113), 'numpy.ones', 'np.ones', (['n_actions'], {}), '(n_actions)\n', (7102, 7113), True, 'import numpy as np\n'), ((7350, 7368), 'numpy.ones', 'np.ones', (['n_actions'], {}), '(n_actions)\n', (7357, 7368), True, 'import numpy as np\n')]
import random import numpy as np import matplotlib.pyplot as plt from PIL import Image class LimGenerator(): def __init__(self, layers): super(LimGenerator, self).__init__() self.layers = layers self.colors = [(163, 156, 255), (236, 177, 161), (22, 22, 22), (190, 0, 32), (0, 0, 0), (255, 255, 255), (36, 8, 0), (2, 0, 29)] def random_color(self, index, layer, change : bool = False): im = layer.convert("RGBA") color = self.colors[index] if change: color = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) data = np.array(im) red_channel, green_channel, blue_channel, alpha_channel = data.T target_area = (red_channel == 255) & (blue_channel == 255) & (green_channel == 255) data[..., :-1][target_area.T] = color return Image.fromarray(data) def display(self, color_change : bool = False): canvas = [] for index, layer in enumerate(self.layers): canvas.append(self.random_color(index, layer, color_change)) for layer in canvas: _ = plt.imshow(layer) plt.axis("off") plt.show() def collage(self): fig, axs = plt.subplots(nrows=3, ncols=3) for ax in axs.ravel(): canvas = [] for index, layer in enumerate(self.layers): canvas.append(self.random_color(index, layer, True)) for layer in canvas: ax.imshow(layer) ax.axis("off") plt.title("Hayoung Lim", x=0.5, y=1, loc="center", fontsize=8) plt.axis("off") plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.imshow", "matplotlib.pyplot.axis", "numpy.array", "random.randrange", "PIL.Image.fromarray", "matplotlib.pyplot.subplots" ]
[((622, 634), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (630, 634), True, 'import numpy as np\n'), ((861, 882), 'PIL.Image.fromarray', 'Image.fromarray', (['data'], {}), '(data)\n', (876, 882), False, 'from PIL import Image\n'), ((1161, 1176), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1169, 1176), True, 'import matplotlib.pyplot as plt\n'), ((1185, 1195), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1193, 1195), True, 'import matplotlib.pyplot as plt\n'), ((1243, 1273), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'ncols': '(3)'}), '(nrows=3, ncols=3)\n', (1255, 1273), True, 'import matplotlib.pyplot as plt\n'), ((1564, 1626), 'matplotlib.pyplot.title', 'plt.title', (['"""Hayoung Lim"""'], {'x': '(0.5)', 'y': '(1)', 'loc': '"""center"""', 'fontsize': '(8)'}), "('Hayoung Lim', x=0.5, y=1, loc='center', fontsize=8)\n", (1573, 1626), True, 'import matplotlib.pyplot as plt\n'), ((1707, 1722), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1715, 1722), True, 'import matplotlib.pyplot as plt\n'), ((1731, 1741), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1739, 1741), True, 'import matplotlib.pyplot as plt\n'), ((1126, 1143), 'matplotlib.pyplot.imshow', 'plt.imshow', (['layer'], {}), '(layer)\n', (1136, 1143), True, 'import matplotlib.pyplot as plt\n'), ((529, 553), 'random.randrange', 'random.randrange', (['(0)', '(255)'], {}), '(0, 255)\n', (545, 553), False, 'import random\n'), ((555, 579), 'random.randrange', 'random.randrange', (['(0)', '(255)'], {}), '(0, 255)\n', (571, 579), False, 'import random\n'), ((581, 605), 'random.randrange', 'random.randrange', (['(0)', '(255)'], {}), '(0, 255)\n', (597, 605), False, 'import random\n')]
# Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2013-2015 SCoT Development Team """ Utility functions """ from __future__ import division from functools import partial import numpy as np def check_random_state(seed): """Turn seed into a np.random.RandomState instance. If seed is None, return the RandomState singleton used by np.random. If seed is an int, return a new RandomState instance seeded with seed. If seed is already a RandomState instance, return it. Otherwise raise ValueError. """ if seed is None or seed is np.random: return np.random.mtrand._rand if isinstance(seed, (int, np.integer)): return np.random.RandomState(seed) if isinstance(seed, np.random.RandomState): return seed raise ValueError('%r cannot be used to seed a numpy.random.RandomState' ' instance' % seed) def cuthill_mckee(matrix): """Implementation of the Cuthill-McKee algorithm. Permute a symmetric binary matrix into a band matrix form with a small bandwidth. Parameters ---------- matrix : ndarray, dtype=bool, shape = [n, n] The matrix is internally converted to a symmetric matrix by setting each element [i,j] to True if either [i,j] or [j,i] evaluates to true. Returns ------- order : list of int Permutation intices Examples -------- >>> A = np.array([[0,0,1,1], [0,0,0,0], [1,0,1,0], [1,0,0,0]]) >>> p = cuthill_mckee(A) >>> A array([[0, 0, 1, 1], [0, 0, 0, 0], [1, 0, 1, 0], [1, 0, 0, 0]]) >>> A[p,:][:,p] array([[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 1]]) """ matrix = np.atleast_2d(matrix) n, m = matrix.shape assert(n == m) # make sure the matrix is really symmetric. This is equivalent to # converting a directed adjacency matrix into a undirected adjacency matrix. matrix = np.logical_or(matrix, matrix.T) degree = np.sum(matrix, 0) order = [np.argmin(degree)] for i in range(n): adj = np.nonzero(matrix[order[i]])[0] adj = [a for a in adj if a not in order] if not adj: idx = [i for i in range(n) if i not in order] order.append(idx[np.argmin(degree[idx])]) else: if len(adj) == 1: order.append(adj[0]) else: adj = np.asarray(adj) i = adj[np.argsort(degree[adj])] order.extend(i.tolist()) if len(order) == n: break return order #noinspection PyPep8Naming class memoize(object): """Cache the return value of a method. This class is meant to be used as a decorator of methods. The return value from a given method invocation will be cached on the instance whose method was invoked. All arguments passed to a method decorated with memoize must be hashable. If a memoized method is invoked directly on its class the result will not be cached. Instead the method will be invoked like a static method: """ def __init__(self, func): self.func = func #noinspection PyUnusedLocal def __get__(self, obj, objtype=None): if obj is None: return self.func return partial(self, obj) def __call__(self, *args, **kw): obj = args[0] try: cache = obj.__cache except AttributeError: cache = obj.__cache = {} key = (self.func, args[1:], frozenset(kw.items())) try: res = cache[key] except KeyError: res = cache[key] = self.func(*args, **kw) return res def cartesian(arrays, out=None): """Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. out : ndarray Array to place the cartesian product in. Returns ------- out : ndarray 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays. Examples -------- >>> cartesian(([1, 2, 3], [4, 5], [6, 7])) array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) References ---------- http://stackoverflow.com/a/1235363/3005167 """ arrays = [np.asarray(x) for x in arrays] dtype = arrays[0].dtype n = np.prod([x.size for x in arrays]) if out is None: out = np.zeros([n, len(arrays)], dtype=dtype) m = n // arrays[0].size out[:, 0] = np.repeat(arrays[0], m) if arrays[1:]: cartesian(arrays[1:], out=out[0:m, 1:]) for j in range(1, arrays[0].size): out[j * m: (j + 1) * m, 1:] = out[0:m, 1:] return out
[ "numpy.atleast_2d", "functools.partial", "numpy.sum", "numpy.asarray", "numpy.random.RandomState", "numpy.argmin", "numpy.nonzero", "numpy.argsort", "numpy.logical_or", "numpy.prod", "numpy.repeat" ]
[((1780, 1801), 'numpy.atleast_2d', 'np.atleast_2d', (['matrix'], {}), '(matrix)\n', (1793, 1801), True, 'import numpy as np\n'), ((2010, 2041), 'numpy.logical_or', 'np.logical_or', (['matrix', 'matrix.T'], {}), '(matrix, matrix.T)\n', (2023, 2041), True, 'import numpy as np\n'), ((2056, 2073), 'numpy.sum', 'np.sum', (['matrix', '(0)'], {}), '(matrix, 0)\n', (2062, 2073), True, 'import numpy as np\n'), ((4675, 4708), 'numpy.prod', 'np.prod', (['[x.size for x in arrays]'], {}), '([x.size for x in arrays])\n', (4682, 4708), True, 'import numpy as np\n'), ((4828, 4851), 'numpy.repeat', 'np.repeat', (['arrays[0]', 'm'], {}), '(arrays[0], m)\n', (4837, 4851), True, 'import numpy as np\n'), ((709, 736), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (730, 736), True, 'import numpy as np\n'), ((2087, 2104), 'numpy.argmin', 'np.argmin', (['degree'], {}), '(degree)\n', (2096, 2104), True, 'import numpy as np\n'), ((3355, 3373), 'functools.partial', 'partial', (['self', 'obj'], {}), '(self, obj)\n', (3362, 3373), False, 'from functools import partial\n'), ((4607, 4620), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (4617, 4620), True, 'import numpy as np\n'), ((2144, 2172), 'numpy.nonzero', 'np.nonzero', (['matrix[order[i]]'], {}), '(matrix[order[i]])\n', (2154, 2172), True, 'import numpy as np\n'), ((2478, 2493), 'numpy.asarray', 'np.asarray', (['adj'], {}), '(adj)\n', (2488, 2493), True, 'import numpy as np\n'), ((2332, 2354), 'numpy.argmin', 'np.argmin', (['degree[idx]'], {}), '(degree[idx])\n', (2341, 2354), True, 'import numpy as np\n'), ((2518, 2541), 'numpy.argsort', 'np.argsort', (['degree[adj]'], {}), '(degree[adj])\n', (2528, 2541), True, 'import numpy as np\n')]
from sklearn.decomposition import PCA import matplotlib.pyplot as plt import time as timelib import numpy as np import pandas as pd def compute_pca(session_data, session_features, cluster_types, verbose = False): """ Compute principal components analysis Parameters ---------- session_data: pandas dataframe of sessions session_features: list of string, pca with those features cluster_types: list of string, cluster types wanted Returns ------- 3 Numpy array """ if verbose == True: start_time = timelib.time() print("\n * Principal component analysis ...") pca = PCA() column_names = ['pc%d'%i for i in range(1,len(session_features)+1)] session_data_reduced = pca.fit_transform(session_data[session_features]) session_data_reduced = pd.DataFrame(data = session_data_reduced,columns = column_names, index = session_data.index) for cluster_type in cluster_types: session_data_reduced[cluster_type] = session_data_reduced.index.map(session_data[cluster_type]) if verbose == True: print(" Principal component analysis completed in %.1f seconds"%(timelib.time() - start_time)) return session_data_reduced, pca.explained_variance_ratio_, pca.components_; def plot_explained_variance(explained_variance_ratio, threshold_explained_variance = 0.8, verbose = False, filename = None): """ Plot explained variance of each princpal components Parameters ---------- explained_variance_ratio: numpy array, recupered with funcrtion "compute_pca" threshold_explained_variance: float between 0 and 1, to trace vertical line on the figure Returns ------- None """ if verbose == True: start_time = timelib.time() print("\n * Plotting explained variance ratio of all components from PCA ...") list_pc = [] for i in np.arange(1,explained_variance_ratio.shape[0]+1): list_pc.append("C"+str(i)) x = np.arange(explained_variance_ratio.shape[0]) n_components_threshold = len(explained_variance_ratio[explained_variance_ratio.cumsum()<threshold_explained_variance]) +1 plt.scatter(x,explained_variance_ratio) plt.axvline(x = n_components_threshold - 1, label = "%.1f of cumulated\n explained variance"%threshold_explained_variance, color = 'r', linewidth = 0.5) plt.xticks(x, list_pc) plt.grid(axis='y', linestyle='--') plt.xlabel("Components") plt.ylabel("Explanied variance ratio") plt.title("Explained variance ratio of each component") plt.legend() if filename is not None: plt.savefig("./%s.pdf"%filename) plt.show() if verbose == True: print(" Plot completed in %.1f seconds."%(timelib.time() - start_time)) return; def scatterplot(session_data_pca, components, feature_names, cluster_type, verbose = False, filename = None): """ Plot scatterplot of sessions along PC1 and PC2 axis, and the composition of these two components, with sessions colored in function of their cluster Parameters ---------- session_data_pca: numpy array, recupered with function "compute_pca" components: numpy array, recupered with function "compute_pca" feature_names: list of string, pca with those features cluster_type: cluster type wanted Returns ------- None """ if verbose == True: start_time = timelib.time() print("\n * Plotting scatterplot of Principal Component 1 and 2 ...") fig, (ax1, ax2) = plt.subplots(1,2,figsize=(8,4)) rows = feature_names columns = ["PC-1","PC-2"] matrix = np.transpose(components) ax1.matshow(matrix, cmap="coolwarm", clim=[-1, 1]) for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): c = matrix[i,j] ax1.text(j,i, '%0.2f'%c, va='center', ha='center', color="k", size=10) ax1.set_xticks(range(2)) ax1.set_yticks(range(len(feature_names))) ax1.set_xticklabels(columns) ax1.set_yticklabels(rows) cluster_ids = session_data_pca[cluster_type].unique() cluster_ids.sort() for cluster_id in cluster_ids: ax2.scatter(session_data_pca[session_data_pca[cluster_type]==cluster_id].pc1,\ session_data_pca[session_data_pca[cluster_type]==cluster_id].pc2,label=str(cluster_id)) ax2.legend(title = 'cluster_id') ax2.set_xlabel("PC-1") ax2.set_ylabel("PC-2") ax2.set_title("Scatterplot of PC-1 and PC-2") ax2.invert_yaxis() if filename is not None: plt.savefig("./%s.png"%filename) plt.show() if verbose == True: print(" Plot completed in %.1f seconds."%(timelib.time() - start_time)) return; def scatterplot_centroids(session_data_pca,cluster_type,components,feature_names,filename = None,verbose = False): """ Plot scatterplot of the centroids of each clustera long PC1 and PC2 axis, and the composition of these two components Parameters ---------- session_data_pca: numpy array, recupered with function "compute_pca" cluster_type: cluster type wanted components: numpy array, recupered with function "compute_pca" feature_names: list of string, pca with those features Returns ------- None """ if verbose == True: start_time = timelib.time() print("\n * Plotting scatterplot with clusters of Principal Component 1 and 2 ...") fig, (ax1, ax2) = plt.subplots(1,2,figsize=(8,4)) # Explanation of components rows = feature_names columns = ["PC-1","PC-2"] matrix = np.transpose(components) ax1.matshow(matrix, cmap="coolwarm", clim=[-1, 1]) for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): c = matrix[i,j] ax1.text(j,i, '%0.2f'%c, va='center', ha='center', color="k", size=10) ax1.set_xticks(range(2)) ax1.set_yticks(range(len(feature_names))) ax1.set_xticklabels(columns) ax1.set_yticklabels(rows) # Scatterplot of clusters num_cluster = session_data_pca[cluster_type].unique() num_cluster.sort() ax2.axis('equal') ax2.set_xlabel('PC-1',fontsize=16) ax2.set_ylabel('PC-2',fontsize=16) xlim_min = np.array([session_data_pca[session_data_pca[cluster_type]==cluster_id].pc1.mean()-\ 50*(session_data_pca[session_data_pca[cluster_type]==cluster_id].\ shape[0]/session_data_pca.shape[0])for cluster_id in num_cluster]).min() xlim_max = np.array([session_data_pca[session_data_pca[cluster_type]==cluster_id].pc1.mean()+\ 50*(session_data_pca[session_data_pca[cluster_type]==cluster_id].\ shape[0]/session_data_pca.shape[0])for cluster_id in num_cluster]).max() ylim_min = np.array([session_data_pca[session_data_pca[cluster_type]==cluster_id].pc2.mean()-\ 50*(session_data_pca[session_data_pca[cluster_type]==cluster_id].\ shape[0]/session_data_pca.shape[0])for cluster_id in num_cluster]).min() ylim_max = np.array([session_data_pca[session_data_pca[cluster_type]==cluster_id].pc2.mean()+\ 50*(session_data_pca[session_data_pca[cluster_type]==cluster_id].\ shape[0]/session_data_pca.shape[0])for cluster_id in num_cluster]).max() ax2.set_xbound(xlim_min,xlim_max) ax2.set_ybound((ylim_min,ylim_max)) #ax2.set_xlim((-1.5,1.75)) #ax2.set_ylim((-1.5,1.5)) ax2.invert_yaxis() # Labeling the clusters for cluster_id in num_cluster: # Cluster_size cluster_size=10000*(session_data_pca[session_data_pca[cluster_type]==cluster_id].shape[0]/session_data_pca.shape[0]) # Cluster label cluster_label = str(cluster_id) # Plotting the circles ax2.scatter(session_data_pca[session_data_pca[cluster_type]==cluster_id].pc1.mean(),\ session_data_pca[session_data_pca[cluster_type]==cluster_id].pc2.mean(),\ marker='o', c="white", alpha = 0.8, s=cluster_size, edgecolor='k') # Plotting the cluster label ax2.scatter(session_data_pca[session_data_pca[cluster_type]==cluster_id].pc1.mean(),\ session_data_pca[session_data_pca[cluster_type]==cluster_id].pc2.mean(),\ marker='$%s$' % (cluster_label), alpha=0.9, s=50, edgecolor='k') plt.tight_layout() if verbose == True: print(" Plot completed in %.1f seconds."%(timelib.time() - start_time)) if filename is not None: plt.savefig("./%s.pdf"%filename) plt.show() plt.clf() plt.close() return;
[ "matplotlib.pyplot.title", "matplotlib.pyplot.clf", "numpy.arange", "matplotlib.pyplot.tight_layout", "pandas.DataFrame", "matplotlib.pyplot.axvline", "matplotlib.pyplot.close", "numpy.transpose", "matplotlib.pyplot.xticks", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "matplotlib.p...
[((689, 694), 'sklearn.decomposition.PCA', 'PCA', ([], {}), '()\n', (692, 694), False, 'from sklearn.decomposition import PCA\n'), ((871, 963), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'session_data_reduced', 'columns': 'column_names', 'index': 'session_data.index'}), '(data=session_data_reduced, columns=column_names, index=\n session_data.index)\n', (883, 963), True, 'import pandas as pd\n'), ((1984, 2035), 'numpy.arange', 'np.arange', (['(1)', '(explained_variance_ratio.shape[0] + 1)'], {}), '(1, explained_variance_ratio.shape[0] + 1)\n', (1993, 2035), True, 'import numpy as np\n'), ((2077, 2121), 'numpy.arange', 'np.arange', (['explained_variance_ratio.shape[0]'], {}), '(explained_variance_ratio.shape[0])\n', (2086, 2121), True, 'import numpy as np\n'), ((2252, 2292), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'explained_variance_ratio'], {}), '(x, explained_variance_ratio)\n', (2263, 2292), True, 'import matplotlib.pyplot as plt\n'), ((2296, 2454), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(n_components_threshold - 1)', 'label': '("""%.1f of cumulated\n explained variance""" % threshold_explained_variance)', 'color': '"""r"""', 'linewidth': '(0.5)'}), '(x=n_components_threshold - 1, label=\n """%.1f of cumulated\n explained variance""" %\n threshold_explained_variance, color=\'r\', linewidth=0.5)\n', (2307, 2454), True, 'import matplotlib.pyplot as plt\n'), ((2453, 2475), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', 'list_pc'], {}), '(x, list_pc)\n', (2463, 2475), True, 'import matplotlib.pyplot as plt\n'), ((2480, 2514), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'axis': '"""y"""', 'linestyle': '"""--"""'}), "(axis='y', linestyle='--')\n", (2488, 2514), True, 'import matplotlib.pyplot as plt\n'), ((2519, 2543), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Components"""'], {}), "('Components')\n", (2529, 2543), True, 'import matplotlib.pyplot as plt\n'), ((2548, 2586), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Explanied variance ratio"""'], {}), "('Explanied variance ratio')\n", (2558, 2586), True, 'import matplotlib.pyplot as plt\n'), ((2591, 2646), 'matplotlib.pyplot.title', 'plt.title', (['"""Explained variance ratio of each component"""'], {}), "('Explained variance ratio of each component')\n", (2600, 2646), True, 'import matplotlib.pyplot as plt\n'), ((2651, 2663), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2661, 2663), True, 'import matplotlib.pyplot as plt\n'), ((2738, 2748), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2746, 2748), True, 'import matplotlib.pyplot as plt\n'), ((3682, 3716), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(8, 4)'}), '(1, 2, figsize=(8, 4))\n', (3694, 3716), True, 'import matplotlib.pyplot as plt\n'), ((3782, 3806), 'numpy.transpose', 'np.transpose', (['components'], {}), '(components)\n', (3794, 3806), True, 'import numpy as np\n'), ((4738, 4748), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4746, 4748), True, 'import matplotlib.pyplot as plt\n'), ((5674, 5708), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(8, 4)'}), '(1, 2, figsize=(8, 4))\n', (5686, 5708), True, 'import matplotlib.pyplot as plt\n'), ((5806, 5830), 'numpy.transpose', 'np.transpose', (['components'], {}), '(components)\n', (5818, 5830), True, 'import numpy as np\n'), ((8665, 8683), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (8681, 8683), True, 'import matplotlib.pyplot as plt\n'), ((8865, 8875), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8873, 8875), True, 'import matplotlib.pyplot as plt\n'), ((8880, 8889), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (8887, 8889), True, 'import matplotlib.pyplot as plt\n'), ((8894, 8905), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (8903, 8905), True, 'import matplotlib.pyplot as plt\n'), ((598, 612), 'time.time', 'timelib.time', ([], {}), '()\n', (610, 612), True, 'import time as timelib\n'), ((1841, 1855), 'time.time', 'timelib.time', ([], {}), '()\n', (1853, 1855), True, 'import time as timelib\n'), ((2701, 2735), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./%s.pdf' % filename)"], {}), "('./%s.pdf' % filename)\n", (2712, 2735), True, 'import matplotlib.pyplot as plt\n'), ((3556, 3570), 'time.time', 'timelib.time', ([], {}), '()\n', (3568, 3570), True, 'import time as timelib\n'), ((4701, 4735), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./%s.png' % filename)"], {}), "('./%s.png' % filename)\n", (4712, 4735), True, 'import matplotlib.pyplot as plt\n'), ((5534, 5548), 'time.time', 'timelib.time', ([], {}), '()\n', (5546, 5548), True, 'import time as timelib\n'), ((8828, 8862), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('./%s.pdf' % filename)"], {}), "('./%s.pdf' % filename)\n", (8839, 8862), True, 'import matplotlib.pyplot as plt\n'), ((1208, 1222), 'time.time', 'timelib.time', ([], {}), '()\n', (1220, 1222), True, 'import time as timelib\n'), ((2827, 2841), 'time.time', 'timelib.time', ([], {}), '()\n', (2839, 2841), True, 'import time as timelib\n'), ((4832, 4846), 'time.time', 'timelib.time', ([], {}), '()\n', (4844, 4846), True, 'import time as timelib\n'), ((8761, 8775), 'time.time', 'timelib.time', ([], {}), '()\n', (8773, 8775), True, 'import time as timelib\n')]
#!/usr/bin/env python # coding: utf-8 # In[1]: from keras.models import load_model import pandas as pd import numpy as np from PIL import Image,ImageOps import CharacterSegmentation as cs import matplotlib.pyplot as plt from matplotlib.pyplot import figure import os # In[2]: INPUT_IMAGE = './input/input_1.jpg' SEGMENTED_OUTPUT_DIR = './segmented/' EMNIST_PATH = './data/emnist/' MODEL_PATH = './model/alphanum_model_binary_ex_88.h5' mapping_processed = EMNIST_PATH + 'processed-mapping.csv' # ## Character Segmentation # In[3]: img = Image.open(INPUT_IMAGE) plt.imshow(img) # In[4]: cs.image_segmentation(INPUT_IMAGE) # In[5]: segmented_images = [] files = [f for r, d, f in os.walk(SEGMENTED_OUTPUT_DIR)][0] for f in files: segmented_images.append(Image.open(SEGMENTED_OUTPUT_DIR + f)) # In[6]: figure(figsize=(18,18)) size = len(segmented_images) for i in range(size): img = segmented_images[i] plt.subplot(2, size, i + 1) plt.imshow(img) # ## Making images bolder to avoid artifacts on resizing # In[7]: import cv2 import numpy as np files = [f for r, d, f in os.walk(SEGMENTED_OUTPUT_DIR)][0] for f in files: filename = SEGMENTED_OUTPUT_DIR + f img = cv2.imread(filename, 0) kernel = np.ones((2,2), np.uint8) dilation = cv2.erode(img, kernel, iterations = 1) cv2.imwrite(filename, dilation) # ## Converting Segmented Characters to EMNIST format # In[8]: def img2emnist(filepath, char_code): img = Image.open(filepath).resize((28, 28)) inv_img = ImageOps.invert(img) flatten = np.array(inv_img).flatten() flatten = flatten / 255 flatten = np.where(flatten > 0.5, 1, 0) csv_img = ','.join([str(num) for num in flatten]) csv_str = '{},{}'.format(char_code, csv_img) return csv_str # In[9]: temp_filename = 'test.csv' if os.path.exists(temp_filename): os.remove(temp_filename) f_test = open(temp_filename, 'a+') column_names = ','.join(["label"] + ["pixel" + str(i) for i in range(784)]) print(column_names, file=f_test) files = [f for r, d, f in os.walk(SEGMENTED_OUTPUT_DIR)][0] for f in files: csv = img2emnist(SEGMENTED_OUTPUT_DIR + f, -1) print(csv, file=f_test) f_test.close() # In[10]: test_df = pd.read_csv(temp_filename) test_df # ## Character Recognition # In[11]: data = pd.read_csv(temp_filename) X_data = data.drop(labels = ["label"], axis = 1) X_data = X_data.values.reshape(-1,28,28,1) # In[12]: figure(figsize=(14,14)) size = X_data.shape[0] for i in range(size): v = X_data[i][:,:,0].astype('uint8') img = Image.fromarray(255* v) plt.subplot(2, size, i + 1) plt.imshow(img) # In[13]: df = pd.read_csv(mapping_processed) code2char = {} for index, row in df.iterrows(): code2char[row['id']] = row['char'] # In[16]: model = load_model(MODEL_PATH) # In[15]: # predict results results = model.predict(X_data) # select the index with the maximum probability results = np.argmax(results, axis = 1) parsed_str = "" for r in results: parsed_str += code2char[r] parsed_str
[ "keras.models.load_model", "os.remove", "numpy.argmax", "pandas.read_csv", "CharacterSegmentation.image_segmentation", "os.walk", "numpy.ones", "matplotlib.pyplot.figure", "cv2.erode", "matplotlib.pyplot.imshow", "cv2.imwrite", "os.path.exists", "PIL.ImageOps.invert", "matplotlib.pyplot.su...
[((548, 571), 'PIL.Image.open', 'Image.open', (['INPUT_IMAGE'], {}), '(INPUT_IMAGE)\n', (558, 571), False, 'from PIL import Image, ImageOps\n'), ((572, 587), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (582, 587), True, 'import matplotlib.pyplot as plt\n'), ((601, 635), 'CharacterSegmentation.image_segmentation', 'cs.image_segmentation', (['INPUT_IMAGE'], {}), '(INPUT_IMAGE)\n', (622, 635), True, 'import CharacterSegmentation as cs\n'), ((826, 850), 'matplotlib.pyplot.figure', 'figure', ([], {'figsize': '(18, 18)'}), '(figsize=(18, 18))\n', (832, 850), False, 'from matplotlib.pyplot import figure\n'), ((1842, 1871), 'os.path.exists', 'os.path.exists', (['temp_filename'], {}), '(temp_filename)\n', (1856, 1871), False, 'import os\n'), ((2247, 2273), 'pandas.read_csv', 'pd.read_csv', (['temp_filename'], {}), '(temp_filename)\n', (2258, 2273), True, 'import pandas as pd\n'), ((2331, 2357), 'pandas.read_csv', 'pd.read_csv', (['temp_filename'], {}), '(temp_filename)\n', (2342, 2357), True, 'import pandas as pd\n'), ((2464, 2488), 'matplotlib.pyplot.figure', 'figure', ([], {'figsize': '(14, 14)'}), '(figsize=(14, 14))\n', (2470, 2488), False, 'from matplotlib.pyplot import figure\n'), ((2685, 2715), 'pandas.read_csv', 'pd.read_csv', (['mapping_processed'], {}), '(mapping_processed)\n', (2696, 2715), True, 'import pandas as pd\n'), ((2825, 2847), 'keras.models.load_model', 'load_model', (['MODEL_PATH'], {}), '(MODEL_PATH)\n', (2835, 2847), False, 'from keras.models import load_model\n'), ((2971, 2997), 'numpy.argmax', 'np.argmax', (['results'], {'axis': '(1)'}), '(results, axis=1)\n', (2980, 2997), True, 'import numpy as np\n'), ((936, 963), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', 'size', '(i + 1)'], {}), '(2, size, i + 1)\n', (947, 963), True, 'import matplotlib.pyplot as plt\n'), ((968, 983), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (978, 983), True, 'import matplotlib.pyplot as plt\n'), ((1212, 1235), 'cv2.imread', 'cv2.imread', (['filename', '(0)'], {}), '(filename, 0)\n', (1222, 1235), False, 'import cv2\n'), ((1250, 1275), 'numpy.ones', 'np.ones', (['(2, 2)', 'np.uint8'], {}), '((2, 2), np.uint8)\n', (1257, 1275), True, 'import numpy as np\n'), ((1290, 1326), 'cv2.erode', 'cv2.erode', (['img', 'kernel'], {'iterations': '(1)'}), '(img, kernel, iterations=1)\n', (1299, 1326), False, 'import cv2\n'), ((1333, 1364), 'cv2.imwrite', 'cv2.imwrite', (['filename', 'dilation'], {}), '(filename, dilation)\n', (1344, 1364), False, 'import cv2\n'), ((1532, 1552), 'PIL.ImageOps.invert', 'ImageOps.invert', (['img'], {}), '(img)\n', (1547, 1552), False, 'from PIL import Image, ImageOps\n'), ((1642, 1671), 'numpy.where', 'np.where', (['(flatten > 0.5)', '(1)', '(0)'], {}), '(flatten > 0.5, 1, 0)\n', (1650, 1671), True, 'import numpy as np\n'), ((1877, 1901), 'os.remove', 'os.remove', (['temp_filename'], {}), '(temp_filename)\n', (1886, 1901), False, 'import os\n'), ((2585, 2609), 'PIL.Image.fromarray', 'Image.fromarray', (['(255 * v)'], {}), '(255 * v)\n', (2600, 2609), False, 'from PIL import Image, ImageOps\n'), ((2618, 2645), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', 'size', '(i + 1)'], {}), '(2, size, i + 1)\n', (2629, 2645), True, 'import matplotlib.pyplot as plt\n'), ((2650, 2665), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (2660, 2665), True, 'import matplotlib.pyplot as plt\n'), ((775, 811), 'PIL.Image.open', 'Image.open', (['(SEGMENTED_OUTPUT_DIR + f)'], {}), '(SEGMENTED_OUTPUT_DIR + f)\n', (785, 811), False, 'from PIL import Image, ImageOps\n'), ((697, 726), 'os.walk', 'os.walk', (['SEGMENTED_OUTPUT_DIR'], {}), '(SEGMENTED_OUTPUT_DIR)\n', (704, 726), False, 'import os\n'), ((1112, 1141), 'os.walk', 'os.walk', (['SEGMENTED_OUTPUT_DIR'], {}), '(SEGMENTED_OUTPUT_DIR)\n', (1119, 1141), False, 'import os\n'), ((1480, 1500), 'PIL.Image.open', 'Image.open', (['filepath'], {}), '(filepath)\n', (1490, 1500), False, 'from PIL import Image, ImageOps\n'), ((1572, 1589), 'numpy.array', 'np.array', (['inv_img'], {}), '(inv_img)\n', (1580, 1589), True, 'import numpy as np\n'), ((2074, 2103), 'os.walk', 'os.walk', (['SEGMENTED_OUTPUT_DIR'], {}), '(SEGMENTED_OUTPUT_DIR)\n', (2081, 2103), False, 'import os\n')]
import os import numpy as np import time import tensorflow as tf import dcgan from utils import save_checkpoint, load_checkpoint from config_device import config_device def train_dcgan(data, config): training_graph = tf.Graph() with training_graph.as_default(): tf.set_random_seed(1) gan = dcgan.dcgan(output_size=config.output_size, batch_size=config.batch_size, nd_layers=config.nd_layers, ng_layers=config.ng_layers, df_dim=config.df_dim, gf_dim=config.gf_dim, c_dim=config.c_dim, z_dim=config.z_dim, flip_labels=config.flip_labels, data_format=config.data_format, transpose_b=config.transpose_matmul_b) gan.training_graph() update_op = gan.optimizer(config.learning_rate, config.beta1) checkpoint_dir = os.path.join(config.checkpoint_dir, config.experiment) sess_config = config_device(config.arch) with tf.Session(config=sess_config) as sess: writer = tf.summary.FileWriter('./logs/'+config.experiment+'/train', sess.graph) init_op = tf.global_variables_initializer() sess.run(init_op) if config.save_checkpoint: load_checkpoint(sess, gan.saver, 'dcgan', checkpoint_dir) epoch = sess.run(gan.increment_epoch) start_time = time.time() time_logs = [] for epoch in range(epoch, epoch + config.epoch): num_batches = data.shape[0] // config.batch_size for idx in range(0, num_batches): batch_images = data[idx*config.batch_size:(idx+1)*config.batch_size] _, g_sum, d_sum = sess.run([update_op, gan.g_summary, gan.d_summary], feed_dict={gan.images: batch_images}) global_step = gan.global_step.eval() writer.add_summary(g_sum, global_step) writer.add_summary(d_sum, global_step) if global_step > 4: if global_step > 5: time_logs.append(time.time() - time_ref) time_ref = time.time() if config.verbose: errD_fake = gan.d_loss_fake.eval() errD_real = gan.d_loss_real.eval({gan.images: batch_images}) errG = gan.g_loss.eval() print("Epoch: [%2d] Step: [%4d/%4d] time: %4.4f, d_loss: %.8f, g_loss: %.8f" \ % (epoch, idx, num_batches, time.time() - start_time, errD_fake+errD_real, errG)) elif global_step%100 == 0: print("Epoch: [%2d] Step: [%4d/%4d] time: %4.4f"%(epoch, idx, num_batches, time.time() - start_time)) # save a checkpoint every epoch if config.save_checkpoint: save_checkpoint(sess, gan.saver, 'dcgan', checkpoint_dir, epoch) sess.run(gan.increment_epoch) tf.reset_default_graph() return np.average(time_logs), np.std(time_logs)/np.sqrt(len(time_logs))
[ "utils.save_checkpoint", "numpy.average", "tensorflow.global_variables_initializer", "tensorflow.reset_default_graph", "numpy.std", "tensorflow.Session", "dcgan.dcgan", "tensorflow.set_random_seed", "time.time", "utils.load_checkpoint", "tensorflow.summary.FileWriter", "config_device.config_de...
[((223, 233), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (231, 233), True, 'import tensorflow as tf\n'), ((3262, 3286), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (3284, 3286), True, 'import tensorflow as tf\n'), ((282, 303), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (300, 303), True, 'import tensorflow as tf\n'), ((319, 652), 'dcgan.dcgan', 'dcgan.dcgan', ([], {'output_size': 'config.output_size', 'batch_size': 'config.batch_size', 'nd_layers': 'config.nd_layers', 'ng_layers': 'config.ng_layers', 'df_dim': 'config.df_dim', 'gf_dim': 'config.gf_dim', 'c_dim': 'config.c_dim', 'z_dim': 'config.z_dim', 'flip_labels': 'config.flip_labels', 'data_format': 'config.data_format', 'transpose_b': 'config.transpose_matmul_b'}), '(output_size=config.output_size, batch_size=config.batch_size,\n nd_layers=config.nd_layers, ng_layers=config.ng_layers, df_dim=config.\n df_dim, gf_dim=config.gf_dim, c_dim=config.c_dim, z_dim=config.z_dim,\n flip_labels=config.flip_labels, data_format=config.data_format,\n transpose_b=config.transpose_matmul_b)\n', (330, 652), False, 'import dcgan\n'), ((1022, 1076), 'os.path.join', 'os.path.join', (['config.checkpoint_dir', 'config.experiment'], {}), '(config.checkpoint_dir, config.experiment)\n', (1034, 1076), False, 'import os\n'), ((1100, 1126), 'config_device.config_device', 'config_device', (['config.arch'], {}), '(config.arch)\n', (1113, 1126), False, 'from config_device import config_device\n'), ((3298, 3319), 'numpy.average', 'np.average', (['time_logs'], {}), '(time_logs)\n', (3308, 3319), True, 'import numpy as np\n'), ((1140, 1170), 'tensorflow.Session', 'tf.Session', ([], {'config': 'sess_config'}), '(config=sess_config)\n', (1150, 1170), True, 'import tensorflow as tf\n'), ((1201, 1276), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (["('./logs/' + config.experiment + '/train')", 'sess.graph'], {}), "('./logs/' + config.experiment + '/train', sess.graph)\n", (1222, 1276), True, 'import tensorflow as tf\n'), ((1296, 1329), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1327, 1329), True, 'import tensorflow as tf\n'), ((1550, 1561), 'time.time', 'time.time', ([], {}), '()\n', (1559, 1561), False, 'import time\n'), ((3321, 3338), 'numpy.std', 'np.std', (['time_logs'], {}), '(time_logs)\n', (3327, 3338), True, 'import numpy as np\n'), ((1416, 1473), 'utils.load_checkpoint', 'load_checkpoint', (['sess', 'gan.saver', '"""dcgan"""', 'checkpoint_dir'], {}), "(sess, gan.saver, 'dcgan', checkpoint_dir)\n", (1431, 1473), False, 'from utils import save_checkpoint, load_checkpoint\n'), ((3146, 3210), 'utils.save_checkpoint', 'save_checkpoint', (['sess', 'gan.saver', '"""dcgan"""', 'checkpoint_dir', 'epoch'], {}), "(sess, gan.saver, 'dcgan', checkpoint_dir, epoch)\n", (3161, 3210), False, 'from utils import save_checkpoint, load_checkpoint\n'), ((2397, 2408), 'time.time', 'time.time', ([], {}), '()\n', (2406, 2408), False, 'import time\n'), ((2338, 2349), 'time.time', 'time.time', ([], {}), '()\n', (2347, 2349), False, 'import time\n'), ((2806, 2817), 'time.time', 'time.time', ([], {}), '()\n', (2815, 2817), False, 'import time\n'), ((3007, 3018), 'time.time', 'time.time', ([], {}), '()\n', (3016, 3018), False, 'import time\n')]
import pandas as pd import importlib import seaborn as sns import re import praw from matplotlib import pyplot as plt import numpy as np import pickle import sys import os #os.chdir("HelperFunctions") from ChangePointAnalysis import BayesianMethods, Preprocess, PopularWords #os.chdir("../") def compute_changepoints(subreddit = "Jokes", up_to = None, daily_words = 2, method = "Metropolis", steps = 30000, tune = 5000): starting_dir = os.getcwd() subreddit_path = f"../Data/subreddit_{subreddit}/" df = Preprocess.load_and_preprocess(subreddit_path) df = pd.DataFrame( df) results_df = pd.DataFrame() with open("mcmc_config.txt") as file: contents = file.read() exec(contents) pop_words = PopularWords.popular_words_unioned_each_date(df, daily_words) print(pop_words, "pop_words") DATA_FOLDER = f"../Data/subreddit_{subreddit}/Changepoints/{method}_{steps}Draws_{tune}Tune/" if not os.path.isdir(DATA_FOLDER): print("making directory", DATA_FOLDER) os.makedirs(DATA_FOLDER) print('made') print(os.getcwd()) os.chdir(DATA_FOLDER) for word in pop_words[:up_to]: print('working on', word) data = BayesianMethods.bayesian_optional_change_point(df, keyword = word, statistic = 'count', plot = False, method = method, steps = steps, tune = tune) # for readability, this should be packaged as a dictionary trace = data[1] mu_1 = BayesianMethods.beta_mean( trace['alpha_1'], trace['beta_1'] ) mu_2 = BayesianMethods.beta_mean( trace['alpha_2'], trace['beta_2'] ) timeseries_df = data[0] timeseries_df = timeseries_df.rename( columns = {"tau" : "change point guess",word : "\"" + word + "\""}) timeseries_df.plot() plt.ylim(0,1) plt.ylabel("Proportion of posts containing this word") plt.xticks(rotation=90) plt.savefig(f"ChangePoint_{word}.png") plt.title(f"p = {data[-1]}, mu_2 - mu_1 = {int(1000*mu_2 - mu_1)/1000}") results_word = { "change_point_confidence" : data[-1], "mus": (mu_1, mu_2), "mu_diff" : mu_2 - mu_1, "tau_map" : str(data[3]) , "tau_std" : np.std(data[1]['tau']) , "entropy" : BayesianMethods.entropy(data[0]['tau'])} results_word["change_point_guess" ] = data[4] for x in results_word.keys(): results_word[x] = [results_word[x]] print(results_word) results_row = pd.DataFrame( results_word, index = [word]) print('appending') results_df = results_df.append(results_row) with open(f'{word}_data.pickle', 'wb') as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) results_df.to_csv("../results.csv") os.chdir(starting_dir) def changepointanalysis(subreddits = ["Jokes", "WallStreetBets", "WritingPrompts", "TraditionalCurses", "TwoSentenceHorror"], up_to = None, daily_words = 2, method = "Metropolis", steps = 30000, tune = 5000): for subreddit in subreddits: print("working on ", subreddit) compute_changepoints(subreddit, up_to = up_to, daily_words = daily_words, method = "Metropolis", steps = steps, tune = tune) #changepointanalysis()
[ "pandas.DataFrame", "ChangePointAnalysis.BayesianMethods.bayesian_optional_change_point", "pickle.dump", "os.makedirs", "matplotlib.pyplot.ylim", "os.getcwd", "os.path.isdir", "numpy.std", "ChangePointAnalysis.PopularWords.popular_words_unioned_each_date", "ChangePointAnalysis.BayesianMethods.beta...
[((446, 457), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (455, 457), False, 'import os\n'), ((523, 569), 'ChangePointAnalysis.Preprocess.load_and_preprocess', 'Preprocess.load_and_preprocess', (['subreddit_path'], {}), '(subreddit_path)\n', (553, 569), False, 'from ChangePointAnalysis import BayesianMethods, Preprocess, PopularWords\n'), ((579, 595), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {}), '(df)\n', (591, 595), True, 'import pandas as pd\n'), ((614, 628), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (626, 628), True, 'import pandas as pd\n'), ((743, 804), 'ChangePointAnalysis.PopularWords.popular_words_unioned_each_date', 'PopularWords.popular_words_unioned_each_date', (['df', 'daily_words'], {}), '(df, daily_words)\n', (787, 804), False, 'from ChangePointAnalysis import BayesianMethods, Preprocess, PopularWords\n'), ((1107, 1128), 'os.chdir', 'os.chdir', (['DATA_FOLDER'], {}), '(DATA_FOLDER)\n', (1115, 1128), False, 'import os\n'), ((2758, 2780), 'os.chdir', 'os.chdir', (['starting_dir'], {}), '(starting_dir)\n', (2766, 2780), False, 'import os\n'), ((950, 976), 'os.path.isdir', 'os.path.isdir', (['DATA_FOLDER'], {}), '(DATA_FOLDER)\n', (963, 976), False, 'import os\n'), ((1033, 1057), 'os.makedirs', 'os.makedirs', (['DATA_FOLDER'], {}), '(DATA_FOLDER)\n', (1044, 1057), False, 'import os\n'), ((1090, 1101), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1099, 1101), False, 'import os\n'), ((1216, 1355), 'ChangePointAnalysis.BayesianMethods.bayesian_optional_change_point', 'BayesianMethods.bayesian_optional_change_point', (['df'], {'keyword': 'word', 'statistic': '"""count"""', 'plot': '(False)', 'method': 'method', 'steps': 'steps', 'tune': 'tune'}), "(df, keyword=word, statistic=\n 'count', plot=False, method=method, steps=steps, tune=tune)\n", (1262, 1355), False, 'from ChangePointAnalysis import BayesianMethods, Preprocess, PopularWords\n'), ((1471, 1531), 'ChangePointAnalysis.BayesianMethods.beta_mean', 'BayesianMethods.beta_mean', (["trace['alpha_1']", "trace['beta_1']"], {}), "(trace['alpha_1'], trace['beta_1'])\n", (1496, 1531), False, 'from ChangePointAnalysis import BayesianMethods, Preprocess, PopularWords\n'), ((1551, 1611), 'ChangePointAnalysis.BayesianMethods.beta_mean', 'BayesianMethods.beta_mean', (["trace['alpha_2']", "trace['beta_2']"], {}), "(trace['alpha_2'], trace['beta_2'])\n", (1576, 1611), False, 'from ChangePointAnalysis import BayesianMethods, Preprocess, PopularWords\n'), ((1800, 1814), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (1808, 1814), True, 'from matplotlib import pyplot as plt\n'), ((1822, 1876), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Proportion of posts containing this word"""'], {}), "('Proportion of posts containing this word')\n", (1832, 1876), True, 'from matplotlib import pyplot as plt\n'), ((1885, 1908), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (1895, 1908), True, 'from matplotlib import pyplot as plt\n'), ((1917, 1955), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""ChangePoint_{word}.png"""'], {}), "(f'ChangePoint_{word}.png')\n", (1928, 1955), True, 'from matplotlib import pyplot as plt\n'), ((2457, 2497), 'pandas.DataFrame', 'pd.DataFrame', (['results_word'], {'index': '[word]'}), '(results_word, index=[word])\n', (2469, 2497), True, 'import pandas as pd\n'), ((2188, 2210), 'numpy.std', 'np.std', (["data[1]['tau']"], {}), "(data[1]['tau'])\n", (2194, 2210), True, 'import numpy as np\n'), ((2225, 2264), 'ChangePointAnalysis.BayesianMethods.entropy', 'BayesianMethods.entropy', (["data[0]['tau']"], {}), "(data[0]['tau'])\n", (2248, 2264), False, 'from ChangePointAnalysis import BayesianMethods, Preprocess, PopularWords\n'), ((2653, 2712), 'pickle.dump', 'pickle.dump', (['data', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(data, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (2664, 2712), False, 'import pickle\n')]
import h5py import numpy as np from yaml import safe_load from sys import getsizeof import random from warnings import warn from progressbar import progressbar SKIPPED = 0 # # # # def get_box_lat(around=None, diff_lats=0.23468057366362416, lat_cyclon_min=None, lat_cyclon_max=None): if diff_lats < 0: warn("Negative step given. Changing sign to have positive value.") diff_lats = abs(diff_lats) ymin_out = (lat_cyclon_min - around * diff_lats) ymax_out = (lat_cyclon_max + around * diff_lats) # check if box goes around the edges if ymin_out < -90: ymin_out = -180 - (ymin_out) if ymax_out > 90: ymax_out = 180 - ymax_out return (ymin_out, ymax_out) # # # # # # def get_box_lon(around=None, diff_lons=0.31277150304083406, lon_cyclon_min=None, lon_cyclon_max=None): if diff_lons < 0: warn("Negative step given. Changing sign to have positive value.") diff_lons = abs(diff_lons) ymin_out = (lon_cyclon_min - around * diff_lons) ymax_out = (lon_cyclon_max + around * diff_lons) # check if box goes around the edges if ymin_out < 0: ymin_out = 360 + ymin_out if ymax_out > 360: ymax_out = ymax_out - 360 return (ymin_out, ymax_out) # # # # # def select_box_cyclon(image=None, time=None, lat_cyclon_min=None, lat_cyclon_max=None, lon_cyclon_min=None, lon_cyclon_max=None, lats=None, lons=None, around=10): assert around > 0, "Box_size = "+str(around)+". Please give the box size as positive. You may need to increae the box size for the whole data." lat_cyclon_min, lat_cyclon_max = get_box_lat(lat_cyclon_min=lat_cyclon_min, lat_cyclon_max=lat_cyclon_max, around=around) lon_cyclon_min, lon_cyclon_max = get_box_lon(lon_cyclon_min=lon_cyclon_min, lon_cyclon_max=lon_cyclon_max, around=around) if lon_cyclon_min > lon_cyclon_max: return { 'lat_min': lat_cyclon_min, 'lat_max': lat_cyclon_max, 'lon_min': lon_cyclon_min, 'lon_max': lon_cyclon_max, 'time': time, 'images': np.append( image[:, slice( np. where(np.isclose(lats, lat_cyclon_min, 1e-6))[0][0], np. where(np.isclose(lats, lat_cyclon_max, 1e-6))[0][0]), slice( 0, np.where( np.isclose(lons, lon_cyclon_max, 1e-6))[0][0])], image[:, slice( np. where(np.isclose(lats, lat_cyclon_min, 1e-6))[0][0], np. where(np.isclose(lats, lat_cyclon_max, 1e-6))[0][0]), slice( np. where(np.isclose(lons, lon_cyclon_min, 1e-6))[0][0] , -1)], axis = 2) } else: return { 'lat_min': lat_cyclon_min, 'lat_max': lat_cyclon_max, 'lon_min': lon_cyclon_min, 'lon_max': lon_cyclon_max, 'time': time, 'images': image[:, slice( np.where(np.isclose(lats, lat_cyclon_min, 1e-6))[0][0], np.where(np.isclose(lats, lat_cyclon_max, 1e-6))[0][0]), slice( np.where(np.isclose(lons, lon_cyclon_min, 1e-6))[0][0], np.where(np.isclose(lons, lon_cyclon_max, 1e-6))[0][0])] } def do_selection(image = None, lats = None, lons = None, cyclon = None, box_size = 120, i = None, times = None, verbose = 1): global SKIPPED try: return (select_box_cyclon(image=image[:, :, :], time=times[i], lat_cyclon_min=lats[cyclon[0]], lat_cyclon_max=lats[cyclon[2]], lon_cyclon_min=lons[cyclon[1]], around=((box_size - abs(cyclon[0] - cyclon[2])) / 2), lon_cyclon_max=lons[cyclon[3]], lats=lats[()], lons=lons[()])) except Exception as e: SKIPPED += 1 if verbose == 1: print("\n", e) warn("For some reason the selection at step "+str(i)+" did not work. May be due to error in data (some latitudes have indexes above 1152)") return None # # # def main(): global SKIPPED # load configurations print("[INFO] Loading vars") with open("./config.yml", 'r') as file: config_var = safe_load(file)["geo_localize"] data_path = config_var['input_path'] print("[INFO] Preparing data") h5f = h5py.File(data_path) images = h5f["data"][()] # (1460,16,768,1152) numpy array boxes = h5f["boxes"] # (1460,15,5) numpy array lats = h5f['latitude'] lons = h5f['longitude'] times = h5f['time'] # size of the box around the anomaly to be taken box_size = config_var['box_size'] HOW_MANY = config_var['iterations'] if HOW_MANY == "All": HOW_MANY = images.shape[0] assert type(HOW_MANY) is int, "Plase give the number of interations either as an integer or as 'All'." print('[INFO] Numbero of iterations %i' %HOW_MANY) print("[INFO] Selecting data with cyclons") data_with_cyclon = [ do_selection(image=images[i], lats=lats, lons=lons, cyclon=cyclon, box_size=box_size, times = times, verbose = int(config_var['verbose_selection']), i=i) for i in progressbar((range(HOW_MANY))) for cyclon in boxes[i][(boxes[i, :, -1] == 2) | (boxes[i, :, -1] == 1)] ] print('[INFO] Skipped %i cyclons' %SKIPPED) # eliminate the Nones and keep only images with the correct size. This should take too long data_with_cyclon = [el for el in data_with_cyclon if ((el is not None) and (el['images'].shape == (images.shape[1],box_size, box_size)))] print("[INFO] Preparing output file") hf = h5py.File(config_var['output_path'], 'w') for key in data_with_cyclon[0].keys(): hf.create_dataset(key, data=np.stack([el[key] for el in data_with_cyclon], axis=0), compression='gzip') print("[INFO] Saving output file") hf.close() if __name__ == "__main__": main()
[ "numpy.stack", "h5py.File", "numpy.isclose", "yaml.safe_load", "warnings.warn" ]
[((5452, 5472), 'h5py.File', 'h5py.File', (['data_path'], {}), '(data_path)\n', (5461, 5472), False, 'import h5py\n'), ((6848, 6889), 'h5py.File', 'h5py.File', (["config_var['output_path']", '"""w"""'], {}), "(config_var['output_path'], 'w')\n", (6857, 6889), False, 'import h5py\n'), ((362, 428), 'warnings.warn', 'warn', (['"""Negative step given. Changing sign to have positive value."""'], {}), "('Negative step given. Changing sign to have positive value.')\n", (366, 428), False, 'from warnings import warn\n'), ((960, 1026), 'warnings.warn', 'warn', (['"""Negative step given. Changing sign to have positive value."""'], {}), "('Negative step given. Changing sign to have positive value.')\n", (964, 1026), False, 'from warnings import warn\n'), ((5334, 5349), 'yaml.safe_load', 'safe_load', (['file'], {}), '(file)\n', (5343, 5349), False, 'from yaml import safe_load\n'), ((6991, 7045), 'numpy.stack', 'np.stack', (['[el[key] for el in data_with_cyclon]'], {'axis': '(0)'}), '([el[key] for el in data_with_cyclon], axis=0)\n', (6999, 7045), True, 'import numpy as np\n'), ((3934, 3973), 'numpy.isclose', 'np.isclose', (['lats', 'lat_cyclon_min', '(1e-06)'], {}), '(lats, lat_cyclon_min, 1e-06)\n', (3944, 3973), True, 'import numpy as np\n'), ((4012, 4051), 'numpy.isclose', 'np.isclose', (['lats', 'lat_cyclon_max', '(1e-06)'], {}), '(lats, lat_cyclon_max, 1e-06)\n', (4022, 4051), True, 'import numpy as np\n'), ((4116, 4155), 'numpy.isclose', 'np.isclose', (['lons', 'lon_cyclon_min', '(1e-06)'], {}), '(lons, lon_cyclon_min, 1e-06)\n', (4126, 4155), True, 'import numpy as np\n'), ((4194, 4233), 'numpy.isclose', 'np.isclose', (['lons', 'lon_cyclon_max', '(1e-06)'], {}), '(lons, lon_cyclon_max, 1e-06)\n', (4204, 4233), True, 'import numpy as np\n'), ((2766, 2805), 'numpy.isclose', 'np.isclose', (['lats', 'lat_cyclon_min', '(1e-06)'], {}), '(lats, lat_cyclon_min, 1e-06)\n', (2776, 2805), True, 'import numpy as np\n'), ((2875, 2914), 'numpy.isclose', 'np.isclose', (['lats', 'lat_cyclon_max', '(1e-06)'], {}), '(lats, lat_cyclon_max, 1e-06)\n', (2885, 2914), True, 'import numpy as np\n'), ((3047, 3086), 'numpy.isclose', 'np.isclose', (['lons', 'lon_cyclon_max', '(1e-06)'], {}), '(lons, lon_cyclon_max, 1e-06)\n', (3057, 3086), True, 'import numpy as np\n'), ((3212, 3251), 'numpy.isclose', 'np.isclose', (['lats', 'lat_cyclon_min', '(1e-06)'], {}), '(lats, lat_cyclon_min, 1e-06)\n', (3222, 3251), True, 'import numpy as np\n'), ((3321, 3360), 'numpy.isclose', 'np.isclose', (['lats', 'lat_cyclon_max', '(1e-06)'], {}), '(lats, lat_cyclon_max, 1e-06)\n', (3331, 3360), True, 'import numpy as np\n'), ((3460, 3499), 'numpy.isclose', 'np.isclose', (['lons', 'lon_cyclon_min', '(1e-06)'], {}), '(lons, lon_cyclon_min, 1e-06)\n', (3470, 3499), True, 'import numpy as np\n')]
import os.path import tensorflow as tf import helper import warnings import time from distutils.version import LooseVersion import project_tests as tests import numpy as np from moviepy.editor import VideoFileClip from moviepy.editor import ImageSequenceClip # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) LEARNING_RATE = 0.001 DECAY_RATE = 0.90 DECAY_AFTER_N_STEPS = 50 KEEP_PROB = 0.5 EPOCHS = 50 BATCH_SIZE = 5 CLASSES = 2 IMAGE_SHAPE = (160, 576) L2_REG = 0.001 STD_DEV = 0.01 DATA_DIR = './data' MODEL_DIR = './model' VIDEO_DIR = './video' def load_vgg(sess, vgg_path): """ Load Pretrained VGG Model into TensorFlow. :param sess: TensorFlow Session :param vgg_path: Path to vgg folder, containing "variables/" and "saved_model.pb" :return: Tuple of Tensors from VGG model (input_image, keep_prob, layer3_out, layer4_out, layer7_out) """ vgg_tag = 'vgg16' vgg_input_tensor_name = 'image_input:0' vgg_keep_prob_tensor_name = 'keep_prob:0' vgg_layer3_out_tensor_name = 'layer3_out:0' vgg_layer4_out_tensor_name = 'layer4_out:0' vgg_layer7_out_tensor_name = 'layer7_out:0' tf.saved_model.loader.load(sess, [vgg_tag], vgg_path) graph = tf.get_default_graph() input_image = graph.get_tensor_by_name(vgg_input_tensor_name) keep_prob = graph.get_tensor_by_name(vgg_keep_prob_tensor_name) layer3_out = graph.get_tensor_by_name(vgg_layer3_out_tensor_name) # pooled layer 3 layer4_out = graph.get_tensor_by_name(vgg_layer4_out_tensor_name) # pooled layer 4 layer7_out = graph.get_tensor_by_name(vgg_layer7_out_tensor_name) # convolved layer 7 return input_image, keep_prob, layer3_out, layer4_out, layer7_out tests.test_load_vgg(load_vgg, tf) def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes): """ Create the layers for a fully convolutional network. Build skip-layers using the vgg layers. :param vgg_layer3_out: TF Tensor for VGG Layer 3 output :param vgg_layer4_out: TF Tensor for VGG Layer 4 output :param vgg_layer7_out: TF Tensor for VGG Layer 7 output :param num_classes: Number of classes to classify :return: The Tensor for the last layer of output """ # layer 7 1x1 convolution to conserve spatial information layer7_1x1 = tf.layers.conv2d(vgg_layer7_out, num_classes, 1, padding='same', kernel_initializer= tf.random_normal_initializer(stddev=STD_DEV), kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_REG)) # layer 7 1x1 convolution upsampled to reverse the convolution operation layer7_upsampled = tf.layers.conv2d_transpose(layer7_1x1, num_classes, 4, 2, padding='same', kernel_initializer= tf.random_normal_initializer(stddev=STD_DEV), kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_REG)) # layer 4 1x1 convolution to conserve spatial information layer4_1x1 = tf.layers.conv2d(vgg_layer4_out, num_classes, 1, padding='same', kernel_initializer= tf.random_normal_initializer(stddev=STD_DEV), kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_REG)) # Skip connection between convolved layer 4 & convolved + upsampled layer 7 to retain the original context layer4_7_skip_connection = tf.add(layer7_upsampled, layer4_1x1) # Upscaling again in preparation for creating the skip connection between layer 7 & layer 3 layer7_final = tf.layers.conv2d_transpose(layer4_7_skip_connection, num_classes, 4, 2, padding='same', kernel_initializer= tf.random_normal_initializer(stddev=STD_DEV), kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_REG)) # layer 3 1x1 convolution to conserve spatial information layer3_1x1 = tf.layers.conv2d(vgg_layer3_out, num_classes, 1, padding='same', kernel_initializer= tf.random_normal_initializer(stddev=STD_DEV), kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_REG)) # Skip connection between convolved layer 3 & upsampled layer 7 layer3_7_skip_connection = tf.add(layer3_1x1, layer7_final) # final layer upscaling layer_last = tf.layers.conv2d_transpose(layer3_7_skip_connection, num_classes, 16, 8, padding='same', kernel_initializer= tf.random_normal_initializer(stddev=STD_DEV), kernel_regularizer=tf.contrib.layers.l2_regularizer(L2_REG)) return layer_last tests.test_layers(layers) def optimize(nn_last_layer, correct_label, learning_rate, num_classes): """ Build the TensorFLow loss and optimizer operations. :param nn_last_layer: TF Tensor of the last layer in the neural network :param correct_label: TF Placeholder for the correct label image :param learning_rate: TF Placeholder for the learning rate :param num_classes: Number of classes to classify :return: Tuple of (logits, train_op, cross_entropy_loss, decaying_learning_rate) """ # Reshape data so that there are n rows & 2 columns (1 column for each label) logits = tf.reshape(nn_last_layer, (-1, num_classes)) labels = tf.reshape(correct_label, (-1, num_classes)) cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels)) # Apply decaying learning rate i.e. the learning rate decreases as the epochs increase global_step = tf.Variable(0, trainable=False) initial_learning_rate = learning_rate # 1 step = 1 training batch decaying_learning_rate = tf.train.exponential_decay(initial_learning_rate, global_step, DECAY_AFTER_N_STEPS, DECAY_RATE, staircase=True) # Optimizer for reducing loss optimizer = tf.train.AdamOptimizer(decaying_learning_rate) train_op = optimizer.minimize(cross_entropy_loss, global_step=global_step) return logits, train_op, cross_entropy_loss, decaying_learning_rate tests.test_optimize(optimize) def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate, decaying_learning_rate): """ Train neural network and print out the loss during training. :param sess: TF Session :param epochs: Number of epochs :param batch_size: Batch size :param get_batches_fn: Function to get batches of training data. Call using get_batches_fn(batch_size) :param train_op: TF Operation to train the neural network :param cross_entropy_loss: TF Tensor for the amount of loss :param input_image: TF Placeholder for input images :param correct_label: TF Placeholder for label images :param keep_prob: TF Placeholder for dropout keep probability :param learning_rate: TF Placeholder for learning rate :param decaying_learning_rate: TF Placeholder for decaying learning rate :return: Dictionary of (epoch_no, avg_loss_across_batches) """ epoch_loss = {} batch_loss = [] sess.run(tf.global_variables_initializer()) for epoch in range(epochs): start_time = time.time() print('Epoch: {} START...'.format(epoch + 1)) batch_counter = 1 for image, label in get_batches_fn(batch_size): _, loss, decaying_rate = sess.run([train_op, cross_entropy_loss, decaying_learning_rate], feed_dict={ input_image: image, correct_label: label, keep_prob: KEEP_PROB, learning_rate: LEARNING_RATE }) print(" Batch {} >>> Loss = {:.4f}, Learning Rate = {:.6f}".format(batch_counter, loss, decaying_rate)) batch_loss.append(loss) batch_counter += 1 end_time = time.time() elapsed = end_time - start_time hours = elapsed//3600 minutes = (elapsed%3600)//60 seconds = (elapsed%3600)%60 print("Epoch: {} END. Time taken: {:.0f} hours {:.0f} minutes {:.0f} seconds\n".format(epoch + 1, hours, minutes, seconds)) epoch_loss[epoch] = np.average(batch_loss) return epoch_loss tests.test_train_nn(train_nn) def run(): num_classes = CLASSES image_shape = IMAGE_SHAPE data_dir = DATA_DIR runs_dir = './runs' tests.test_for_kitti_dataset(data_dir) # Download pretrained vgg model helper.maybe_download_pretrained_vgg(data_dir) # OPTIONAL: Train and Inference on the cityscapes dataset instead of the Kitti dataset. # You'll need a GPU with at least 10 teraFLOPS to train on. # https://www.cityscapes-dataset.com/ with tf.Session() as sess: # Path to vgg model vgg_path = os.path.join(data_dir, 'vgg') # Create function to get batches get_batches_fn = helper.gen_batch_function(os.path.join(data_dir, 'data_road/training'), image_shape) # OPTIONAL: Augment Images for better results # https://datascience.stackexchange.com/questions/5224/how-to-prepare-augment-images-for-neural-network # Build NN using load_vgg, layers, and optimize function correct_label = tf.placeholder(tf.int32, [None, None, None, num_classes], name='correct_label') learning_rate = tf.placeholder(tf.float32, name='learning_rate') input_image, keep_prob, vgg_layer3_out, vgg_layer4_out, vgg_layer7_out = load_vgg(sess, vgg_path) nn_last_layer = layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes) logits, train_op, cross_entropy_loss, decaying_learning_rate = optimize(nn_last_layer, correct_label, learning_rate, num_classes) start_time = time.time() epoch_loss = train_nn(sess, EPOCHS, BATCH_SIZE, get_batches_fn, train_op, cross_entropy_loss, input_image, correct_label, keep_prob, learning_rate, decaying_learning_rate) end_time = time.time() elapsed = end_time - start_time hours = elapsed//3600 minutes = (elapsed%3600)//60 seconds = (elapsed%3600)%60 print("Training time: {:.0f} hours {:.0f} minutes {:.0f} seconds".format(hours, minutes, seconds)) log_file_path = './' + str(EPOCHS) + '_log.txt' log_file = open(log_file_path, 'w') log_file.write('Epoch,Loss\n') for key in epoch_loss.keys(): log_file.write('{},{}\n'.format(key, epoch_loss[key])) log_file.close() start_time = time.time() # Save inference data using helper.save_inference_samples helper.save_inference_samples(runs_dir, data_dir, sess, image_shape, logits, keep_prob, input_image) end_time = time.time() elapsed = end_time - start_time hours = elapsed//3600 minutes = (elapsed%3600)//60 seconds = (elapsed%3600)%60 print("Inference time: {:.0f} hours {:.0f} minutes {:.0f} seconds".format(hours, minutes, seconds)) # Save model for later use #saver = tf.train.Saver() #saver.save(sess, MODEL_DIR + '/model_meta') #print("Model saved to {} directory".format(MODEL_DIR)) # OPTIONAL: Apply the trained model to a video start_time = time.time() processed_frames = [] # Load video #video_clip = VideoFileClip(VIDEO_DIR + '/project_video.mp4') video_clip = VideoFileClip(VIDEO_DIR + '/solidWhiteRight.mp4') frame_counter = 1; for frame in video_clip.iter_frames(): processed_frame = helper.segment_single_image(sess, logits, keep_prob, input_image, frame, image_shape) # Collect processed frame processed_frames.append(processed_frame) print("Frame {} processed".format(frame_counter)) frame_counter += 1 # Stitcha all frames to get the video processed_video = ImageSequenceClip(processed_frames, fps=video_clip.fps) processed_video.write_videofile(VIDEO_DIR + '/solidWhiteRight_processed.mp4', audio=False) print("Processed video written to {} directory".format(VIDEO_DIR)) end_time = time.time() elapsed = end_time - start_time hours = elapsed//3600 minutes = (elapsed%3600)//60 seconds = (elapsed%3600)%60 print("Video processing time: {:.0f} hours {:.0f} minutes {:.0f} seconds".format(hours, minutes, seconds)) if __name__ == '__main__': run()
[ "helper.segment_single_image", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.reshape", "tensorflow.Variable", "project_tests.test_for_kitti_dataset", "project_tests.test_train_nn", "moviepy.editor.ImageSequenceClip", "tensorflow.get_default_graph", "project_tests.test_load_vgg", "moviepy...
[((2091, 2124), 'project_tests.test_load_vgg', 'tests.test_load_vgg', (['load_vgg', 'tf'], {}), '(load_vgg, tf)\n', (2110, 2124), True, 'import project_tests as tests\n'), ((5024, 5049), 'project_tests.test_layers', 'tests.test_layers', (['layers'], {}), '(layers)\n', (5041, 5049), True, 'import project_tests as tests\n'), ((6482, 6511), 'project_tests.test_optimize', 'tests.test_optimize', (['optimize'], {}), '(optimize)\n', (6501, 6511), True, 'import project_tests as tests\n'), ((8868, 8897), 'project_tests.test_train_nn', 'tests.test_train_nn', (['train_nn'], {}), '(train_nn)\n', (8887, 8897), True, 'import project_tests as tests\n'), ((295, 323), 'distutils.version.LooseVersion', 'LooseVersion', (['tf.__version__'], {}), '(tf.__version__)\n', (307, 323), False, 'from distutils.version import LooseVersion\n'), ((327, 346), 'distutils.version.LooseVersion', 'LooseVersion', (['"""1.0"""'], {}), "('1.0')\n", (339, 346), False, 'from distutils.version import LooseVersion\n'), ((516, 541), 'tensorflow.test.gpu_device_name', 'tf.test.gpu_device_name', ([], {}), '()\n', (539, 541), True, 'import tensorflow as tf\n'), ((547, 624), 'warnings.warn', 'warnings.warn', (['"""No GPU found. Please use a GPU to train your neural network."""'], {}), "('No GPU found. Please use a GPU to train your neural network.')\n", (560, 624), False, 'import warnings\n'), ((1529, 1582), 'tensorflow.saved_model.loader.load', 'tf.saved_model.loader.load', (['sess', '[vgg_tag]', 'vgg_path'], {}), '(sess, [vgg_tag], vgg_path)\n', (1555, 1582), True, 'import tensorflow as tf\n'), ((1595, 1617), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1615, 1617), True, 'import tensorflow as tf\n'), ((3775, 3811), 'tensorflow.add', 'tf.add', (['layer7_upsampled', 'layer4_1x1'], {}), '(layer7_upsampled, layer4_1x1)\n', (3781, 3811), True, 'import tensorflow as tf\n'), ((4644, 4676), 'tensorflow.add', 'tf.add', (['layer3_1x1', 'layer7_final'], {}), '(layer3_1x1, layer7_final)\n', (4650, 4676), True, 'import tensorflow as tf\n'), ((5638, 5682), 'tensorflow.reshape', 'tf.reshape', (['nn_last_layer', '(-1, num_classes)'], {}), '(nn_last_layer, (-1, num_classes))\n', (5648, 5682), True, 'import tensorflow as tf\n'), ((5696, 5740), 'tensorflow.reshape', 'tf.reshape', (['correct_label', '(-1, num_classes)'], {}), '(correct_label, (-1, num_classes))\n', (5706, 5740), True, 'import tensorflow as tf\n'), ((5971, 6002), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)'}), '(0, trainable=False)\n', (5982, 6002), True, 'import tensorflow as tf\n'), ((6107, 6222), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['initial_learning_rate', 'global_step', 'DECAY_AFTER_N_STEPS', 'DECAY_RATE'], {'staircase': '(True)'}), '(initial_learning_rate, global_step,\n DECAY_AFTER_N_STEPS, DECAY_RATE, staircase=True)\n', (6133, 6222), True, 'import tensorflow as tf\n'), ((6274, 6320), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['decaying_learning_rate'], {}), '(decaying_learning_rate)\n', (6296, 6320), True, 'import tensorflow as tf\n'), ((9018, 9056), 'project_tests.test_for_kitti_dataset', 'tests.test_for_kitti_dataset', (['data_dir'], {}), '(data_dir)\n', (9046, 9056), True, 'import project_tests as tests\n'), ((9098, 9144), 'helper.maybe_download_pretrained_vgg', 'helper.maybe_download_pretrained_vgg', (['data_dir'], {}), '(data_dir)\n', (9134, 9144), False, 'import helper\n'), ((5786, 5855), 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'labels'}), '(logits=logits, labels=labels)\n', (5825, 5855), True, 'import tensorflow as tf\n'), ((7536, 7569), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (7567, 7569), True, 'import tensorflow as tf\n'), ((7624, 7635), 'time.time', 'time.time', ([], {}), '()\n', (7633, 7635), False, 'import time\n'), ((8503, 8514), 'time.time', 'time.time', ([], {}), '()\n', (8512, 8514), False, 'import time\n'), ((8818, 8840), 'numpy.average', 'np.average', (['batch_loss'], {}), '(batch_loss)\n', (8828, 8840), True, 'import numpy as np\n'), ((9355, 9367), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (9365, 9367), True, 'import tensorflow as tf\n'), ((9871, 9950), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, None, None, num_classes]'], {'name': '"""correct_label"""'}), "(tf.int32, [None, None, None, num_classes], name='correct_label')\n", (9885, 9950), True, 'import tensorflow as tf\n'), ((9975, 10023), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""learning_rate"""'}), "(tf.float32, name='learning_rate')\n", (9989, 10023), True, 'import tensorflow as tf\n'), ((10385, 10396), 'time.time', 'time.time', ([], {}), '()\n', (10394, 10396), False, 'import time\n'), ((10645, 10656), 'time.time', 'time.time', ([], {}), '()\n', (10654, 10656), False, 'import time\n'), ((11221, 11232), 'time.time', 'time.time', ([], {}), '()\n', (11230, 11232), False, 'import time\n'), ((11307, 11411), 'helper.save_inference_samples', 'helper.save_inference_samples', (['runs_dir', 'data_dir', 'sess', 'image_shape', 'logits', 'keep_prob', 'input_image'], {}), '(runs_dir, data_dir, sess, image_shape, logits,\n keep_prob, input_image)\n', (11336, 11411), False, 'import helper\n'), ((11428, 11439), 'time.time', 'time.time', ([], {}), '()\n', (11437, 11439), False, 'import time\n'), ((11971, 11982), 'time.time', 'time.time', ([], {}), '()\n', (11980, 11982), False, 'import time\n'), ((12126, 12175), 'moviepy.editor.VideoFileClip', 'VideoFileClip', (["(VIDEO_DIR + '/solidWhiteRight.mp4')"], {}), "(VIDEO_DIR + '/solidWhiteRight.mp4')\n", (12139, 12175), False, 'from moviepy.editor import VideoFileClip\n'), ((12623, 12678), 'moviepy.editor.ImageSequenceClip', 'ImageSequenceClip', (['processed_frames'], {'fps': 'video_clip.fps'}), '(processed_frames, fps=video_clip.fps)\n', (12640, 12678), False, 'from moviepy.editor import ImageSequenceClip\n'), ((12872, 12883), 'time.time', 'time.time', ([], {}), '()\n', (12881, 12883), False, 'import time\n'), ((673, 698), 'tensorflow.test.gpu_device_name', 'tf.test.gpu_device_name', ([], {}), '()\n', (696, 698), True, 'import tensorflow as tf\n'), ((2794, 2838), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'STD_DEV'}), '(stddev=STD_DEV)\n', (2822, 2838), True, 'import tensorflow as tf\n'), ((2888, 2928), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['L2_REG'], {}), '(L2_REG)\n', (2920, 2928), True, 'import tensorflow as tf\n'), ((3158, 3202), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'STD_DEV'}), '(stddev=STD_DEV)\n', (3186, 3202), True, 'import tensorflow as tf\n'), ((3252, 3292), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['L2_REG'], {}), '(L2_REG)\n', (3284, 3292), True, 'import tensorflow as tf\n'), ((3492, 3536), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'STD_DEV'}), '(stddev=STD_DEV)\n', (3520, 3536), True, 'import tensorflow as tf\n'), ((3586, 3626), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['L2_REG'], {}), '(L2_REG)\n', (3618, 3626), True, 'import tensorflow as tf\n'), ((4069, 4113), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'STD_DEV'}), '(stddev=STD_DEV)\n', (4097, 4113), True, 'import tensorflow as tf\n'), ((4163, 4203), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['L2_REG'], {}), '(L2_REG)\n', (4195, 4203), True, 'import tensorflow as tf\n'), ((4403, 4447), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'STD_DEV'}), '(stddev=STD_DEV)\n', (4431, 4447), True, 'import tensorflow as tf\n'), ((4497, 4537), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['L2_REG'], {}), '(L2_REG)\n', (4529, 4537), True, 'import tensorflow as tf\n'), ((4865, 4909), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'STD_DEV'}), '(stddev=STD_DEV)\n', (4893, 4909), True, 'import tensorflow as tf\n'), ((4959, 4999), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['L2_REG'], {}), '(L2_REG)\n', (4991, 4999), True, 'import tensorflow as tf\n'), ((12280, 12369), 'helper.segment_single_image', 'helper.segment_single_image', (['sess', 'logits', 'keep_prob', 'input_image', 'frame', 'image_shape'], {}), '(sess, logits, keep_prob, input_image, frame,\n image_shape)\n', (12307, 12369), False, 'import helper\n')]
""" Simulation of behavioral experiment. This module tests the previously trained model. The stimuli was selected taking into account hangman entropy in edges (initial and final positions). Summary of behavioral experiment: ================================= Stimuli: 3 types of words (all 7-letter Hebrew words): - extreme 'negative': 50 words where it should be much better to fixate at the beginning compared to end - extreme 'positive': 50 words where it should be much better to fixate at the end compared to beginning - 'mid' words: 100 words not from the extremes, continuously either better at the beginning or at the end Procedure: For each subject for each word, the fixation position is manipulated: - either at the beginning of the word (location 2/7), - or at the end of the word (location 6/7). """ __author__ = '<NAME>' import argparse import datetime import re import os, sys, inspect from os.path import join, exists, basename, dirname import numpy as np npa=np.array import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import pandas as pd import random from scipy.stats import sem #Add source folder to the path SCRIPT_FOLDER = os.path.realpath(os.path.abspath( os.path.split(inspect.getfile(inspect.currentframe()))[0])) MAIN_FOLDER = join(SCRIPT_FOLDER, os.pardir, os.pardir, os.pardir) MODULES_FOLDER = join(MAIN_FOLDER, "src") if MODULES_FOLDER not in sys.path: sys.path.insert(0, MODULES_FOLDER) #Own imports from models.nn_utils import * from myUtils.results import Prediction, Results from myUtils.simulation import Simulation from myUtils.misc import extend_filename_proc from myStats.anova import * fn_test_results = "results_hangman_test.csv" def test(word_fixation_list, model, alls2i, wordlen, lang, dimming=1.0): """ Test the word_fixation_list on the given model and return the predictions. :param word_fixation_list: :param model: :param alls2i: :param wordlen: :param lang: :return: results """ #Initialize object to store results results = Results(wordlen, lang, "HangmanExp", prefix="hangmanexp_") #Initialize variables to store hidden layer activation hfreqs, hbins = [], [] bins=np.arange(0,1,0.05) #Run the model for i,(word,fixation) in enumerate(word_fixation_list): x, y = prepare_input_output_seqs(word, alls2i) prediction = model.forward(x,fixation, test_mode=True, dimming=dimming) datum = Prediction(word, alls2i.w2i[word], None, fixation, prediction.view((-1)).data, hidden_state=model.hidden_state) results.add_datum(datum) return results def online_test(responses_data, epoch, model, alls2i, wordlen, lang, seed, simulation_params, output_dir, save_model_dir, means_time, stress_time, rank): #Simulate the test test_results, stress = test_extreme_stimuli(responses_data, model, alls2i, wordlen, lang, compute_stress=True) #Output per-trial test results (model performance) fname=join(output_dir, fn_test_results) fname=fname if rank is None else extend_filename_proc(fname, rank) results_to_csv(test_results, fname) #Compute means over conditions means_cond, errors_cond = means_over_trials_per_condition(test_results) #Compute significance results_df=pd.read_csv(fname, sep=";") pa,pb,paxb=anova_stepwise(results_df) significant=paxb<0.01 #Plot # fname="hangman_mean_correct_epoch%i_%s.png"%(epoch,["","significant"][#significant]) # myPlots.plot_hangman_mean_correct(test_results, fname=join(output_dir,# fname)) #Save means means_time.append([epoch, *means_cond, *errors_cond, significant]) #errors_cond[0], errors_cond[1], errors_cond[2], errors_cond[3], significant]) #Save stress stress_time.append([epoch, stress[2]["extreme_neg"], stress[2]["extreme_pos"], stress[6]["extreme_neg"], stress[6]["extreme_pos"]]) def test_extreme_stimuli(stimuli, model, alls2i, wordlen, lang, compute_stress=True, dimming=1.0): #Test over each of four conditions: extreme_pos/extreme_neg x fixation_2/fixation6 entropy_conds = ["neg", "pos"] fixation_conds = [2, 6] #Accumulators correct={f:{e:0 for e in entropy_conds} for f in fixation_conds} stress={"f2mean_neg":None,"f2mean_pos":None,"f6mean_neg":None,"f6mean_pos":None} for fix_cond in fixation_conds: for ent_cond in entropy_conds: #Get list of words and fixation position based on actual condition words = stimuli[stimuli["condition"]==("extreme_%s"%ent_cond)]["target"] word_fixation_list=[(w,fix_cond) for w in words] #Test and get results for this condition results = test(word_fixation_list, model, alls2i, lang, wordlen, dimming=dimming) correct[fix_cond][ent_cond] = results.as_dict_fixation_nmaxprob()[fix_cond] if compute_stress: stress["f%imean_%s"%(fix_cond,ent_cond)] = results.average_stress() #Save summary (means, stds, ...) #results.dump_summary() return correct, stress def means_over_trials_per_condition(data): """ Return mean performance (mean number of correct guesses) per condition, and standard error. Order: f2neg, f2pos, f6neg, f6pos (first means, then standard error) :param data: :return: """ entropy_conds=["neg", "pos"] f2_means = [sum(m)/len(m) for m in [data[2][e] for e in entropy_conds]] f6_means = [sum(m)/len(m) for m in [data[6][e] for e in entropy_conds]] f2_error = [sem(m) for m in [data[2][e] for e in entropy_conds]] f6_error = [sem(m) for m in [data[6][e] for e in entropy_conds]] return [*f2_means, *f6_means], [*f2_error, *f6_error] def means_to_csv(data, output_dir, append=False): """ Creates file with one line per epoch, and a column for the performance in each test condition, aggregated over trials. :param data: :param output_dir: :return: """ #Create text lines lines="" for datum in data: line=";".join([str(d) for d in datum]) lines+=line lines+="\n" #Write output fname=join(output_dir, "means_hangman_test.csv") if not append or not exists(fname): print("Creating new file for test results: %s"%fname) header=";".join(["epoch", "f2mean_neg", "f2mean_pos", "f6mean_neg", "f6mean_pos", "f2error_neg", "f2error_pos", "f6error_neg", "f6error_pos", "significant"]) header+="\n" with open(fname, "w") as fh: fh.write(header) fh.write(lines) else: with open(fname, "a") as fh: fh.write(lines) return fname def stress_to_csv(data, output_dir, append=False): lines="" for datum in data: line=";".join([str(d) for d in datum]) lines+=line lines+="\n" fname=join(output_dir, "stress_hangman_test.csv") if not append or not exists(fname): header=";".join(["epoch", "f2mean_neg", "f2mean_pos", "f6mean_neg", "f6mean_pos"]) header+="\n" with open(fname, "w") as fh: fh.write(header) fh.write(lines) else: with open(fname, "a") as fh: fh.write(lines) return fname def results_to_csv(results_dict, fname): header=";".join(["trial", "fixpos", "entropy", "correct"]) header+="\n" trial=0 with open(fname, "w") as fh: fh.write(header) for fix_cond, entropies in results_dict.items(): for ent_cond, correct in entropies.items(): for c in correct: line=";".join([str(trial), str(fix_cond), ent_cond, str(c)]) line+="\n" fh.write(line) trial+=1 return fname def results_to_df(results_dict): trial = 0 data=[] for fix_cond, entropies in results_dict.items(): for ent_cond, correct in entropies.items(): for c in correct: data.append((trial, fix_cond, ent_cond, c)) trial+=1 labels="trial;fixpos;entropy;correct".split(";") return pd.DataFrame.from_records(data, columns=labels) def load_and_test(stimuli, lang, path_to_model, seed, epoch, output_dir, dimming=1.0): """ Loads and tests one model. Adds additional parameters that are specific to the simulation of the McConkey experiment.""" #Fixed parameter of the mcconnkey behavioral experiment #todo wordlength=7 #Set the seed on random and on numpy random.seed(seed) np.random.seed(seed) #Check if output directory is correctly set if output_dir[-1] == "/": output_dir=output_dir[:-1] if basename(output_dir) == "seed%i"%seed: pass elif not basename(output_dir).startswith("seed"): if not exists(output_dir): os.mkdir(output_dir) output_dir=join(output_dir,"seed%i"%seed) else: raise Exception("Are you sure this is the output directory you want? %s"%output_dir) if not exists(output_dir): os.mkdir(output_dir) #Create simulation from saved model and details simulation = Simulation(seed, None, None, lang, wordlength , "", None, path_to_model, None) #Run the test results, stress = test_extreme_stimuli(stimuli, simulation.model, simulation.alls2i, lang, wordlength, dimming=dimming) #Write out results per trial (disabled for now) #results_to_csv(results, join(output_dir, fn_test_results)) #Aggregate over trials, for each condition (order: f2neg, f2pos, f6neg, f6pos) mean,error = means_over_trials_per_condition(results) #Compute significance of interaction between entropy and fixation results_df=results_to_df(results) p_entropy, p_fix, p_inter, aov_table = anova_mcconkey_test(results_df) significant=p_inter<0.01 #Output means, errors, and significance of interaction for this model, appending it to the file with records for each epoch datum=[epoch, *mean, *error, significant] means_to_csv([datum], output_dir, append=True) #Output stress, appending it to the file with records for each epoch datum=[epoch, stress['f2mean_neg'], stress['f2mean_pos'], stress['f6mean_neg'], stress['f6mean_pos']] stress_to_csv([datum], output_dir, append=True) print("Completed test for seed %i epoch %i! \nResults in %s"%(seed, epoch, output_dir)) def single_run_interface(): parser = argparse.ArgumentParser() parser.add_argument("--encoding", type=str, default="utf-8", help="Encoding of input data. Default=utf-8; alternative=latin1") parser.add_argument("--path_to_model", required=True, type=str, help="Path to saved_models folder.") parser.add_argument("--seed", type=int, required=True, help="Seed. ") parser.add_argument("--epoch", type=int, required=True, help="Epoch.") parser.add_argument("--lang", type=str, required=True, help="Language (hb or en). ") parser.add_argument("--dimming", type=float, default=1.0, help="Apply dimming to test input. The dimming value D must be 0 < D < 1. ") parser.add_argument("--test_data", required=True, type=str, help="Path to csv with test data.") parser.add_argument("--output_dir", required=True, type=str, help="Path where plots and other results will be stored. ") args = parser.parse_args() if args.encoding not in ("utf-8", "latin1"): raise Exception("Encoding unknown: %s"%args.encoding) #Load behavioral data from mcconkey experiment, for words to test stimuli=pd.read_csv(args.test_data, sep= ",") load_and_test(stimuli, args.lang, args.path_to_model, args.seed, args.epoch, args.output_dir) def batch_process(test_data_file, lang, path_to_saved_models, output_dir): for path_to_model in os.listdir(path_to_saved_models): seed, epoch = re.match(".+_seed(\d+)_ep(\d+)",path_to_model).groups() #Load behavioral data from mcconkey experiment, for words to test stimuli=pd.read_csv(test_data_file, sep= ",") load_and_test(stimuli, lang, join(path_to_saved_models,path_to_model), int(seed), int(epoch), output_dir) def whole_seed_interface(): parser = argparse.ArgumentParser() parser.add_argument("--encoding", type=str, default="utf-8", help="Encoding of input data. Default=utf-8; alternative=latin1") parser.add_argument("--path_to_saved_models", required=True, type=str, help="Path to saved_models folder.") parser.add_argument("--lang", type=str, required=True, help="Language (hb or en). ") parser.add_argument("--dimming", type=float, default=1.0, help="Apply dimming to test input. The dimming value D must be 0 < D < 1. ") parser.add_argument("--test_data", required=True, type=str, help="Path to csv with test data.") parser.add_argument("--output_dir", required=True, type=str, help="Path where plots and other results will be stored. ") args = parser.parse_args() if args.encoding not in ("utf-8", "latin1"): raise Exception("Encoding unknown: %s"%args.encoding) if not exists(args.path_to_saved_models): raise Exception("% does not exist!"%args.path_to_saved_models) stimuli=pd.read_csv(args.test_data, sep= ",") batch_process(stimuli, args.lang, args.path_to_saved_models, args.output_dir) #This is a hardcoded method for debugging purposes, but for some reason it is MUCH faster #in the HPC than any other interface! def __debugging_main(): print("WARNING: you are running the program in debugging mode. The input parameters are ignored. Change test.py in order to avoid this.", file=sys.stderr) #Parameters lang = "en" name = "deleteme_en" dimming = 0.35 seeds=range(1,2+1) epochs=range(0,20+1,5) prepath="/home/rgalhama/Research/L2STATS/nnfixrec/" #prepath="/psyhome/u7/rgalhama/nnfixrec/" outfolder = name if dimming < 1.0: outfolder += "_dimming%.2f"%dimming output_dir = join(prepath,"results/%s"%outfolder) if lang == "hb": fn_stimuli="../../../data/human_experiment/stimuli_comparison_with_wiki.csv" else: fn_stimuli="../../../data/en_test/test_data.csv" stimuli=pd.read_csv(fn_stimuli, sep= ",") for seed in seeds: for epoch in epochs: path_to_model = join(prepath,"saved_models/"+name+"/"+name+"_seed%i_ep%i"%(seed,epoch)) load_and_test(stimuli, lang, path_to_model, seed, epoch, output_dir, dimming=dimming) if __name__ == "__main__": #__debugging_main() #whole_seed_interface() single_run_interface()
[ "os.mkdir", "numpy.random.seed", "argparse.ArgumentParser", "pandas.read_csv", "numpy.arange", "myUtils.misc.extend_filename_proc", "os.path.join", "warnings.simplefilter", "myUtils.simulation.Simulation", "os.path.exists", "random.seed", "os.path.basename", "re.match", "scipy.stats.sem", ...
[((1063, 1125), 'warnings.simplefilter', 'warnings.simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (1084, 1125), False, 'import warnings\n'), ((1348, 1400), 'os.path.join', 'join', (['SCRIPT_FOLDER', 'os.pardir', 'os.pardir', 'os.pardir'], {}), '(SCRIPT_FOLDER, os.pardir, os.pardir, os.pardir)\n', (1352, 1400), False, 'from os.path import join, exists, basename, dirname\n'), ((1418, 1442), 'os.path.join', 'join', (['MAIN_FOLDER', '"""src"""'], {}), "(MAIN_FOLDER, 'src')\n", (1422, 1442), False, 'from os.path import join, exists, basename, dirname\n'), ((1482, 1516), 'sys.path.insert', 'sys.path.insert', (['(0)', 'MODULES_FOLDER'], {}), '(0, MODULES_FOLDER)\n', (1497, 1516), False, 'import os, sys, inspect\n'), ((2122, 2180), 'myUtils.results.Results', 'Results', (['wordlen', 'lang', '"""HangmanExp"""'], {'prefix': '"""hangmanexp_"""'}), "(wordlen, lang, 'HangmanExp', prefix='hangmanexp_')\n", (2129, 2180), False, 'from myUtils.results import Prediction, Results\n'), ((2276, 2297), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(0.05)'], {}), '(0, 1, 0.05)\n', (2285, 2297), True, 'import numpy as np\n'), ((3053, 3086), 'os.path.join', 'join', (['output_dir', 'fn_test_results'], {}), '(output_dir, fn_test_results)\n', (3057, 3086), False, 'from os.path import join, exists, basename, dirname\n'), ((3352, 3379), 'pandas.read_csv', 'pd.read_csv', (['fname'], {'sep': '""";"""'}), "(fname, sep=';')\n", (3363, 3379), True, 'import pandas as pd\n'), ((6212, 6254), 'os.path.join', 'join', (['output_dir', '"""means_hangman_test.csv"""'], {}), "(output_dir, 'means_hangman_test.csv')\n", (6216, 6254), False, 'from os.path import join, exists, basename, dirname\n'), ((6916, 6959), 'os.path.join', 'join', (['output_dir', '"""stress_hangman_test.csv"""'], {}), "(output_dir, 'stress_hangman_test.csv')\n", (6920, 6959), False, 'from os.path import join, exists, basename, dirname\n'), ((8174, 8221), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['data'], {'columns': 'labels'}), '(data, columns=labels)\n', (8199, 8221), True, 'import pandas as pd\n'), ((8570, 8587), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (8581, 8587), False, 'import random\n'), ((8592, 8612), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (8606, 8612), True, 'import numpy as np\n'), ((9193, 9270), 'myUtils.simulation.Simulation', 'Simulation', (['seed', 'None', 'None', 'lang', 'wordlength', '""""""', 'None', 'path_to_model', 'None'], {}), "(seed, None, None, lang, wordlength, '', None, path_to_model, None)\n", (9203, 9270), False, 'from myUtils.simulation import Simulation\n'), ((10480, 10505), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10503, 10505), False, 'import argparse\n'), ((11571, 11607), 'pandas.read_csv', 'pd.read_csv', (['args.test_data'], {'sep': '""","""'}), "(args.test_data, sep=',')\n", (11582, 11607), True, 'import pandas as pd\n'), ((11811, 11843), 'os.listdir', 'os.listdir', (['path_to_saved_models'], {}), '(path_to_saved_models)\n', (11821, 11843), False, 'import os, sys, inspect\n'), ((12211, 12236), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (12234, 12236), False, 'import argparse\n'), ((13209, 13245), 'pandas.read_csv', 'pd.read_csv', (['args.test_data'], {'sep': '""","""'}), "(args.test_data, sep=',')\n", (13220, 13245), True, 'import pandas as pd\n'), ((13975, 14014), 'os.path.join', 'join', (['prepath', "('results/%s' % outfolder)"], {}), "(prepath, 'results/%s' % outfolder)\n", (13979, 14014), False, 'from os.path import join, exists, basename, dirname\n'), ((14199, 14231), 'pandas.read_csv', 'pd.read_csv', (['fn_stimuli'], {'sep': '""","""'}), "(fn_stimuli, sep=',')\n", (14210, 14231), True, 'import pandas as pd\n'), ((3124, 3157), 'myUtils.misc.extend_filename_proc', 'extend_filename_proc', (['fname', 'rank'], {}), '(fname, rank)\n', (3144, 3157), False, 'from myUtils.misc import extend_filename_proc\n'), ((5613, 5619), 'scipy.stats.sem', 'sem', (['m'], {}), '(m)\n', (5616, 5619), False, 'from scipy.stats import sem\n'), ((5682, 5688), 'scipy.stats.sem', 'sem', (['m'], {}), '(m)\n', (5685, 5688), False, 'from scipy.stats import sem\n'), ((8734, 8754), 'os.path.basename', 'basename', (['output_dir'], {}), '(output_dir)\n', (8742, 8754), False, 'from os.path import join, exists, basename, dirname\n'), ((9073, 9091), 'os.path.exists', 'exists', (['output_dir'], {}), '(output_dir)\n', (9079, 9091), False, 'from os.path import join, exists, basename, dirname\n'), ((9101, 9121), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (9109, 9121), False, 'import os, sys, inspect\n'), ((12014, 12050), 'pandas.read_csv', 'pd.read_csv', (['test_data_file'], {'sep': '""","""'}), "(test_data_file, sep=',')\n", (12025, 12050), True, 'import pandas as pd\n'), ((13090, 13123), 'os.path.exists', 'exists', (['args.path_to_saved_models'], {}), '(args.path_to_saved_models)\n', (13096, 13123), False, 'from os.path import join, exists, basename, dirname\n'), ((6280, 6293), 'os.path.exists', 'exists', (['fname'], {}), '(fname)\n', (6286, 6293), False, 'from os.path import join, exists, basename, dirname\n'), ((6985, 6998), 'os.path.exists', 'exists', (['fname'], {}), '(fname)\n', (6991, 6998), False, 'from os.path import join, exists, basename, dirname\n'), ((8927, 8960), 'os.path.join', 'join', (['output_dir', "('seed%i' % seed)"], {}), "(output_dir, 'seed%i' % seed)\n", (8931, 8960), False, 'from os.path import join, exists, basename, dirname\n'), ((12090, 12131), 'os.path.join', 'join', (['path_to_saved_models', 'path_to_model'], {}), '(path_to_saved_models, path_to_model)\n', (12094, 12131), False, 'from os.path import join, exists, basename, dirname\n'), ((14314, 14401), 'os.path.join', 'join', (['prepath', "('saved_models/' + name + '/' + name + '_seed%i_ep%i' % (seed, epoch))"], {}), "(prepath, 'saved_models/' + name + '/' + name + '_seed%i_ep%i' % (seed,\n epoch))\n", (14318, 14401), False, 'from os.path import join, exists, basename, dirname\n'), ((8855, 8873), 'os.path.exists', 'exists', (['output_dir'], {}), '(output_dir)\n', (8861, 8873), False, 'from os.path import join, exists, basename, dirname\n'), ((8887, 8907), 'os.mkdir', 'os.mkdir', (['output_dir'], {}), '(output_dir)\n', (8895, 8907), False, 'import os, sys, inspect\n'), ((11867, 11916), 're.match', 're.match', (['""".+_seed(\\\\d+)_ep(\\\\d+)"""', 'path_to_model'], {}), "('.+_seed(\\\\d+)_ep(\\\\d+)', path_to_model)\n", (11875, 11916), False, 'import re\n'), ((1304, 1326), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (1324, 1326), False, 'import os, sys, inspect\n'), ((8799, 8819), 'os.path.basename', 'basename', (['output_dir'], {}), '(output_dir)\n', (8807, 8819), False, 'from os.path import join, exists, basename, dirname\n')]
from numpy import dot, linalg class PCA: def __init__(self): pass def fit(self, x): sigma = dot(x.T, x) / float(len(x)) u, s, _ = linalg.svd(sigma, full_matrices=0) return u, s def project(self, x, u, k): U_reduce = u[:, :k] return dot(x, U_reduce) def recover(self, z, u, k): U_reduce = u[:, :k] return dot(z, U_reduce.T);
[ "numpy.dot", "numpy.linalg.svd" ]
[((165, 199), 'numpy.linalg.svd', 'linalg.svd', (['sigma'], {'full_matrices': '(0)'}), '(sigma, full_matrices=0)\n', (175, 199), False, 'from numpy import dot, linalg\n'), ((296, 312), 'numpy.dot', 'dot', (['x', 'U_reduce'], {}), '(x, U_reduce)\n', (299, 312), False, 'from numpy import dot, linalg\n'), ((389, 407), 'numpy.dot', 'dot', (['z', 'U_reduce.T'], {}), '(z, U_reduce.T)\n', (392, 407), False, 'from numpy import dot, linalg\n'), ((119, 130), 'numpy.dot', 'dot', (['x.T', 'x'], {}), '(x.T, x)\n', (122, 130), False, 'from numpy import dot, linalg\n')]
""" RLU 2020 """ import functools import numpy as np from inspect import getfullargspec import copy #import numba def gaussian_argument_variation(std, n=100): """Function decorator that varies input arguments of a given function stochastically and produces a list of function returns for every stochastic iteration. Args: std (dict) : dictionary that specifies the std. deviation for selected function arguments, e.g. {"a":3, "c"=4} n (int) : number of stochastic samples Returns: (array) : an array of length n with the function return values for the stochastically varied inputs """ def decorator(func): argspec = getfullargspec(func) @functools.wraps(func) #@numba.jit def wrapper(*args, **kwargs): center = func(*args, **kwargs) new_args = list(args) new_kwargs = copy.copy(kwargs) all_argument_names = argspec.args argument_names = list(std.keys()) argument_indices = [argspec.args.index(k) for k in argument_names] def set_arg_by_index(i, val): if i < len(args): new_args[i] = val else: new_kwargs[all_argument_names[i]] = val def get_arg_by_index(i): if i < len(args): return args[i] else: return kwargs[all_argument_names[i]] argument_values = [get_arg_by_index(i) for i in argument_indices] argument_std = [std[k] for k in argument_names] argument_sizes = [np.size(arg) for arg in argument_values] arg_zip = list(zip(argument_indices, argument_names, argument_values, argument_std, argument_sizes)) res_list = [] for j in range(n): for i,k,arg,arg_std,arg_size in arg_zip: if arg_size==1: variation = np.random.normal(0,arg_std) else: variation = np.random.normal(0,arg_std,np.size(arg)) set_arg_by_index(i, arg + variation) res_list.append(func(*new_args, **new_kwargs)) return res_list return wrapper return decorator
[ "numpy.size", "inspect.getfullargspec", "copy.copy", "numpy.random.normal", "functools.wraps" ]
[((676, 696), 'inspect.getfullargspec', 'getfullargspec', (['func'], {}), '(func)\n', (690, 696), False, 'from inspect import getfullargspec\n'), ((706, 727), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (721, 727), False, 'import functools\n'), ((888, 905), 'copy.copy', 'copy.copy', (['kwargs'], {}), '(kwargs)\n', (897, 905), False, 'import copy\n'), ((1679, 1691), 'numpy.size', 'np.size', (['arg'], {}), '(arg)\n', (1686, 1691), True, 'import numpy as np\n'), ((2040, 2068), 'numpy.random.normal', 'np.random.normal', (['(0)', 'arg_std'], {}), '(0, arg_std)\n', (2056, 2068), True, 'import numpy as np\n'), ((2157, 2169), 'numpy.size', 'np.size', (['arg'], {}), '(arg)\n', (2164, 2169), True, 'import numpy as np\n')]
import numpy as np class SGD: def __init__(self, lr=0.01): self.lr = lr def update(self, params, grads): for key in params.keys(): params[key] -= self.lr * grads[key] class Momentum: def __init__(self, lr=0.01, momentum=0.9): self.lr = lr self.momentum = momentum self.v = None def update(self, params, grads): if self.v is None: self.v = {} for key, val in params.items(): self.v[key] = np.zeros_like(val) for key in params.keys(): self.v[key] = self.momentum*self.v[key] - self.lr*grads[key] params[key] += self.v[key] class Nesterov: def __init__(self, lr=0.01, momentum=0.9): self.lr = lr self.momentum = momentum self.v = None def update(self, params, grads): if self.v is None: self.v = {} for key, val in params.items(): self.v[key] = np.zeros_like(val) for key in params.keys(): params[key] += self.momentum * self.momentum * self.v[key] params[key] -= (1 + self.momentum) * self.lr * grads[key] self.v[key] *= self.momentum self.v[key] -= self.lr * grads[key] class AdaGrad: def __init__(self, lr=0.01): self.lr = lr self.h = None def update(self, params, grads): if self.h is None: self.h = {} for key, val in params.items(): self.h[key] = np.zeros_like(val) for key in params.keys(): self.h[key] += grads[key] * grads[key] params[key] -= self.lr * grads[key] / (np.sqrt(self.h[key]) + 1e-7) class RMSProp: def __init__(self, lr=0.01, decay_rate = 0.99): self.lr = lr self.decay_rate = decay_rate self.h = None def update(self, params, grads): if self.h is None: self.h = {} for key, val in params.items(): self.h[key] = np.zeros_like(val) for key in params.keys(): self.h[key] *= self.decay_rate self.h[key] += (1 - self.decay_rate) * grads[key] * grads[key] params[key] -= self.lr * grads[key] / (np.sqrt(self.h[key] + 1e-7)) class Adam: def __init__(self, lr=0.001, rho1=0.9, rho2=0.999): self.lr = lr self.rho1 = rho1 self.rho2 = rho2 self.iter = 0 self.m = None self.v = None self.epsilon = 1e-8 def update(self, params, grads): if self.m is None: self.m, self.v = {}, {} for key, val in params.items(): self.m[key] = np.zeros_like(val) self.v[key] = np.zeros_like(val) self.iter += 1 for key in params.keys(): self.m[key] = self.rho1*self.m[key] + (1-self.rho1)*grads[key] self.v[key] = self.rho2*self.v[key] + (1-self.rho2)*(grads[key]**2) m = self.m[key] / (1 - self.rho1**self.iter) v = self.v[key] / (1 - self.rho2**self.iter) params[key] -= self.lr * m / (np.sqrt(v) + self.epsilon) if __name__=="__main__": for CLS in [SGD, Momentum, Nesterov, AdaGrad, RMSProp, Adam]: print(CLS) cls = CLS() params = {"affine1":np.random.randn(6).reshape(2,3), "affine2":np.random.randn(6).reshape(2,3) } grads = {"affine1":np.random.randn(6).reshape(2,3), "affine2":np.random.randn(6).reshape(2,3) } print("params\n", params) print("grads\n", grads) cls.update(params, grads) print("params after\n", params)
[ "numpy.random.randn", "numpy.zeros_like", "numpy.sqrt" ]
[((509, 527), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (522, 527), True, 'import numpy as np\n'), ((979, 997), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (992, 997), True, 'import numpy as np\n'), ((1534, 1552), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (1547, 1552), True, 'import numpy as np\n'), ((2031, 2049), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (2044, 2049), True, 'import numpy as np\n'), ((2254, 2282), 'numpy.sqrt', 'np.sqrt', (['(self.h[key] + 1e-07)'], {}), '(self.h[key] + 1e-07)\n', (2261, 2282), True, 'import numpy as np\n'), ((2693, 2711), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (2706, 2711), True, 'import numpy as np\n'), ((2742, 2760), 'numpy.zeros_like', 'np.zeros_like', (['val'], {}), '(val)\n', (2755, 2760), True, 'import numpy as np\n'), ((1690, 1710), 'numpy.sqrt', 'np.sqrt', (['self.h[key]'], {}), '(self.h[key])\n', (1697, 1710), True, 'import numpy as np\n'), ((3133, 3143), 'numpy.sqrt', 'np.sqrt', (['v'], {}), '(v)\n', (3140, 3143), True, 'import numpy as np\n'), ((3345, 3363), 'numpy.random.randn', 'np.random.randn', (['(6)'], {}), '(6)\n', (3360, 3363), True, 'import numpy as np\n'), ((3410, 3428), 'numpy.random.randn', 'np.random.randn', (['(6)'], {}), '(6)\n', (3425, 3428), True, 'import numpy as np\n'), ((3492, 3510), 'numpy.random.randn', 'np.random.randn', (['(6)'], {}), '(6)\n', (3507, 3510), True, 'import numpy as np\n'), ((3555, 3573), 'numpy.random.randn', 'np.random.randn', (['(6)'], {}), '(6)\n', (3570, 3573), True, 'import numpy as np\n')]
#!/usr/bin/python ''' (C) <NAME>, February 2015 ''' import argparse import numpy as np from matplotlib import pyplot as plt if __name__ == "__main__": parser = argparse.ArgumentParser(description="A small utility to plot RAW greyscale images") parser.add_argument("input_image_name", help="Name of the raw image file", type=str) parser.add_argument("width", help="Width of the image", type=int) parser.add_argument("height", help="Height of the image",type=int) parser_args = vars(parser.parse_args()) ''' load up data (assumed 8 bit unsigned) ''' my_img = np.fromfile(parser_args["input_image_name"],dtype=np.uint8) #this loads up unsigned chars (8 bit) if len(my_img) != parser_args["width"] * parser_args["height"]: raise argparse.ArgumentTypeError("Invalid width and height specified. Does not match amount of data read") my_img = my_img.reshape([parser_args["height"],parser_args["width"]]) ''' loading successful: let's go make a color map of the data... will be good enough as a viewer there is a bunch of color maps defined here: http://matplotlib.org/examples/color/colormaps_reference.html ''' plt.figure() plt.imshow(my_img,cmap=plt.get_cmap("cubehelix")) plt.colorbar() plt.show()
[ "matplotlib.pyplot.show", "argparse.ArgumentParser", "matplotlib.pyplot.get_cmap", "numpy.fromfile", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.figure", "argparse.ArgumentTypeError" ]
[((167, 255), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""A small utility to plot RAW greyscale images"""'}), "(description=\n 'A small utility to plot RAW greyscale images')\n", (190, 255), False, 'import argparse\n'), ((575, 635), 'numpy.fromfile', 'np.fromfile', (["parser_args['input_image_name']"], {'dtype': 'np.uint8'}), "(parser_args['input_image_name'], dtype=np.uint8)\n", (586, 635), True, 'import numpy as np\n'), ((1131, 1143), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1141, 1143), True, 'from matplotlib import pyplot as plt\n'), ((1196, 1210), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1208, 1210), True, 'from matplotlib import pyplot as plt\n'), ((1212, 1222), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1220, 1222), True, 'from matplotlib import pyplot as plt\n'), ((746, 851), 'argparse.ArgumentTypeError', 'argparse.ArgumentTypeError', (['"""Invalid width and height specified. Does not match amount of data read"""'], {}), "(\n 'Invalid width and height specified. Does not match amount of data read')\n", (772, 851), False, 'import argparse\n'), ((1168, 1193), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""cubehelix"""'], {}), "('cubehelix')\n", (1180, 1193), True, 'from matplotlib import pyplot as plt\n')]
import torch # import CLIP.clip as clip_orig # OpenAI/CLIP from clip import clip # open_clip repo from clip.model import * # open_clip repo from training.main import convert_models_to_fp32 # open_clip repo import torch.distributed as dist import PIL from PIL import Image, ImageDraw from pathlib import Path import json import numpy as np import cv2 import matplotlib.pyplot as plt import os import argparse from tqdm import tqdm import time MODEL_CONFIGS_DIR = "/scratch/cluster/albertyu/dev/open_clip/src/training/model_configs" #@title Control context expansion (number of attention layers to consider) num_last_layers_for_saliency = 1 #@param {type:"number"} def saliency_map(images, texts, model, preprocess, device, im_size): def create_single_saliency_map(image_relevance, image): patch_side_length = int(np.sqrt(image_relevance.shape[0])) image_relevance = image_relevance.reshape(1, 1, patch_side_length, patch_side_length) image_relevance = torch.nn.functional.interpolate(image_relevance, size=im_size, mode='bilinear') image_relevance = image_relevance.reshape(im_size, im_size).to(device).data.cpu().numpy() image_relevance = (image_relevance - image_relevance.min()) / (image_relevance.max() - image_relevance.min()) image = image.permute(1, 2, 0).data.cpu().numpy() image = (image - image.min()) / (image.max() - image.min()) pil_image = Image.fromarray(np.uint8(255 * image)) image = pil_image.resize((im_size, im_size), resample=PIL.Image.BICUBIC) image = np.float32(np.array(image)) / 255 attn_dot_im = np.tile(np.expand_dims(image_relevance, axis=-1), (1, 1, 3)) * image return attn_dot_im, image_relevance, image def create_saliency_maps(logits_per_image, images, im_size): batch_size = images.shape[0] index = [i for i in range(batch_size)] one_hot = np.zeros((logits_per_image.shape[0], logits_per_image.shape[1]), dtype=np.float32) one_hot[torch.arange(logits_per_image.shape[0]), index] = 1 one_hot = torch.from_numpy(one_hot).requires_grad_(True) one_hot = torch.sum(one_hot.cuda() * logits_per_image) model.zero_grad() image_attn_blocks = list(dict(model.module.visual.transformer.resblocks.named_children()).values()) num_tokens = image_attn_blocks[0].attn_probs.shape[-1] R = torch.eye(num_tokens, num_tokens, dtype=image_attn_blocks[0].attn_probs.dtype).to(device) R = R.unsqueeze(0).expand(batch_size, num_tokens, num_tokens) for i, blk in enumerate(image_attn_blocks): if i <= len(image_attn_blocks) - 1 - num_last_layers_for_saliency: continue grad = torch.autograd.grad(one_hot, [blk.attn_probs], retain_graph=True)[0].detach() cam = blk.attn_probs.detach() cam = cam.reshape(-1, cam.shape[-1], cam.shape[-1]) grad = grad.reshape(-1, grad.shape[-1], grad.shape[-1]) cam = grad * cam cam = cam.reshape(batch_size, -1, cam.shape[-1], cam.shape[-1]) cam = cam.clamp(min=0).mean(dim=1) R = R + torch.bmm(cam, R) image_relevances = R[:, 0, 1:] attn_dot_im_list = [] image_relevance_list = [] image_list = [] for i in range(batch_size): attn_dot_im, image_relevance, image = create_single_saliency_map(image_relevances[i], images[i]) attn_dot_im_list.append(attn_dot_im) image_relevance_list.append(image_relevance) image_list.append(image) return np.array(attn_dot_im_list), np.array(image_relevance_list), np.array(image_list) images = torch.cat([preprocess(Image.fromarray(im)).unsqueeze(0).to(device) for im in images]) # image = preprocess(image).unsqueeze(0).to(device) # texts = clip.tokenize(texts).to(device) texts = texts.long().to(device) start_time = time.time() image_features, text_features, logit_scale = model(images, texts) # cosine similarity as logits logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text = logits_per_image.t() # print("foward", time.time() - start_time) probs = logits_per_image.softmax(dim=-1).detach().cpu().numpy() # doesn't seem to be used?? start_time = time.time() attn_dot_ims, image_relevances, images = create_saliency_maps(logits_per_image, images, im_size) print("backward", time.time() - start_time) return attn_dot_ims, image_relevances, images def save_heatmap(images, texts, text_strs, model, preprocess, device, output_fnames, im_size=224): # create heatmap from mask on image def show_cam_on_image(img, mask): heatmap = cv2.applyColorMap(np.uint8(255 * mask), cv2.COLORMAP_JET) heatmap = np.float32(heatmap) / 255 img = np.float32(img) cam = heatmap + img cam = cam / np.max(cam) return cam, img attn_dot_ims, attns, images = saliency_map(images, texts, model, preprocess, device, im_size=im_size) for i in range(len(images)): attn_dot_im, attn, image = attn_dot_ims[i], attns[i], images[i] output_fname = output_fnames[i] text = text_strs[i] vis, orig_img = show_cam_on_image(image, attn) vis, orig_img = np.uint8(255 * vis), np.uint8(255 * orig_img) attn_dot_im = np.uint8(255 * attn_dot_im) vis = cv2.cvtColor(vis, cv2.COLOR_RGB2BGR) vis_concat = np.concatenate([orig_img, vis, attn_dot_im], axis=1) vis_concat_captioned = add_caption_to_np_img(vis_concat, text) plt.imsave(output_fname, vis_concat_captioned) def add_caption_to_np_img(im_arr, caption): caption_img = Image.new('RGB', (im_arr.shape[1], 20), (255, 255, 255)) # PIL.Image seems to operate on transposed axes d = ImageDraw.Draw(caption_img) d.text((5, 5), caption, fill=(0, 0, 0)) caption_img_arr = np.uint8(np.array(caption_img)) final_arr = np.concatenate([im_arr, caption_img_arr], axis=0) return final_arr class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def load_eval_ids_and_file_id_to_annotation_map(args): with open(args.val_file, "r") as f: lines = f.readlines() val_ex = [] for line in lines: val_ex.append(int(line.rstrip().split(".jpg")[0])) with open(args.test_file, "r") as f: lines = f.readlines() test_ex = [] for line in lines: test_ex.append(int(line.rstrip().split(".jpg")[0])) with open(args.annotations_path, "r") as f: lines = f.readlines() file_id_to_annotation_map = {} # int: str for example in lines: filename, annotation = example.split("\t") file_id = int(filename.split(".jpg")[0]) # removes the .jpg if file_id in test_ex: file_id_to_annotation_map[file_id] = annotation.rstrip() np.random.seed(0) file_ids_to_eval = np.random.choice(list(file_id_to_annotation_map.keys()), args.num_evals) wall_only_file_ids = [key for key in file_id_to_annotation_map if file_id_to_annotation_map[key] == "wall"] wall_pair_file_ids = [key for key in file_id_to_annotation_map if ("wall" in file_id_to_annotation_map[key]) and (len(file_id_to_annotation_map[key].split(" ")) == 2) ] file_ids_to_eval = np.concatenate((file_ids_to_eval, np.array(wall_only_file_ids), np.array(wall_pair_file_ids))) print("file_ids_to_eval", file_ids_to_eval) return file_ids_to_eval, file_id_to_annotation_map def load_model_preprocess(checkpoint, gpu=0, device="cuda", freeze_clip=True): possible_model_classes = ['ViT-B/32', 'RN50-small', 'RN50', 'ViT-B/16-small', 'ViT-B/16'] for possible_model_class in possible_model_classes: if possible_model_class in checkpoint: model_class = possible_model_class print("model_class:", model_class) break if checkpoint: print("Before dist init") successful_port = False port = 6100 while not successful_port: try: dist.init_process_group( backend="nccl", init_method=f"tcp://127.0.0.1:{port}", world_size=1,#torch.cuda.device_count(), rank=gpu, ) except: port += 1 else: successful_port = True print("after dist init") model_config_file = os.path.join(MODEL_CONFIGS_DIR, f"{model_class.replace('/', '-')}.json") print('Loading model from', model_config_file) assert os.path.exists(model_config_file) with open(model_config_file, 'r') as f: model_info = json.load(f) model = CLIP(**model_info) convert_weights(model) preprocess = clip._transform(model.visual.input_resolution, is_train=False, color_jitter=False) convert_models_to_fp32(model) model.cuda(gpu) model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[gpu], find_unused_parameters=True, broadcast_buffers=False) checkpoint = torch.load(checkpoint, map_location=device) sd = checkpoint["state_dict"] model.load_state_dict(sd) if freeze_clip: print("Freezing clip") model.eval() else: print("Allowing clip to be finetuneable") model.train() else: model, preprocess = clip.load(model_class, device=device, jit=False) return model, preprocess if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--num-evals", type=int, required=True) # Below: Saliency-like filepaths. parser.add_argument("--val-file", type=str, required=True) parser.add_argument("--test-file", type=str, required=True) parser.add_argument("--annotations-path", type=str, required=True) # open_clip-trained checkpoint parser.add_argument("--checkpoint", type=str, default=None) parser.add_argument("--gpu", type=int, default=None) parser.add_argument("--image-dir", type=str, required=True) parser.add_argument("--output-dir", type=str, default="output_heatmaps") parser.add_argument("--im-size", type=int, default=224) args = parser.parse_args() if not os.path.exists(args.output_dir): os.mkdir(args.output_dir) device = "cuda" if torch.cuda.is_available() else "cpu" model, preprocess = load_model_preprocess(args.checkpoint, args.gpu) file_ids_to_eval, file_id_to_annotation_map = load_eval_ids_and_file_id_to_annotation_map(args) # file_ids_to_eval = file_ids_to_eval[:2] text_strs = [file_id_to_annotation_map[eval_id] for eval_id in file_ids_to_eval] texts = clip.tokenize(text_strs) image_paths = [os.path.join(args.image_dir, f"{eval_id}.jpg") for eval_id in file_ids_to_eval] images = np.array([np.array(Image.open(image_path)) for image_path in image_paths]) text_strs = [file_id_to_annotation_map[eval_id] for eval_id in file_ids_to_eval] # texts = clip.tokenize(texts).to(device) output_fnames = [os.path.join(args.output_dir, f"{eval_id}.jpg") for eval_id in file_ids_to_eval] save_heatmap(images, texts, text_strs, model, preprocess, device, output_fnames, args.im_size) # attn_dot_im, attn, image = saliency_map(image, text, model, preprocess, device, args.im_size) # print("attn_dot_im", attn_dot_im.shape) # print("attn", attn.shape) # print("image", image.shape) # for eval_id in tqdm(file_ids_to_eval): # caption = file_id_to_annotation_map[eval_id] # image_path = os.path.join(args.image_dir, f"{eval_id}.jpg") # image_arr = np.array(Image.open(image_path)) # # print(color.BOLD + color.PURPLE + color.UNDERLINE + 'text: ' + texts[0] + color.END) # output_fname = os.path.join(args.output_dir, f"{eval_id}.jpg") # save_heatmap(image_arr, caption, model, preprocess, device, output_fname, args.im_size) # produce local copy commands commands = [] for eval_id in file_ids_to_eval: output_path = os.path.join(os.getcwd(), args.output_dir) command = "scp titan1:{}/{}.jpg .".format(output_path, eval_id) commands.append(command) print("Copy commands") print(commands)
[ "os.mkdir", "PIL.Image.new", "clip.clip._transform", "numpy.random.seed", "argparse.ArgumentParser", "torch.eye", "clip.clip.tokenize", "torch.bmm", "torch.autograd.grad", "matplotlib.pyplot.imsave", "torch.arange", "os.path.join", "clip.clip.load", "cv2.cvtColor", "torch.nn.parallel.Dis...
[((3937, 3948), 'time.time', 'time.time', ([], {}), '()\n', (3946, 3948), False, 'import time\n'), ((4331, 4342), 'time.time', 'time.time', ([], {}), '()\n', (4340, 4342), False, 'import time\n'), ((5726, 5782), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(im_arr.shape[1], 20)', '(255, 255, 255)'], {}), "('RGB', (im_arr.shape[1], 20), (255, 255, 255))\n", (5735, 5782), False, 'from PIL import Image, ImageDraw\n'), ((5843, 5870), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['caption_img'], {}), '(caption_img)\n', (5857, 5870), False, 'from PIL import Image, ImageDraw\n'), ((5985, 6034), 'numpy.concatenate', 'np.concatenate', (['[im_arr, caption_img_arr]'], {'axis': '(0)'}), '([im_arr, caption_img_arr], axis=0)\n', (5999, 6034), True, 'import numpy as np\n'), ((7120, 7137), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (7134, 7137), True, 'import numpy as np\n'), ((9851, 9876), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9874, 9876), False, 'import argparse\n'), ((11024, 11048), 'clip.clip.tokenize', 'clip.tokenize', (['text_strs'], {}), '(text_strs)\n', (11037, 11048), False, 'from clip import clip\n'), ((982, 1061), 'torch.nn.functional.interpolate', 'torch.nn.functional.interpolate', (['image_relevance'], {'size': 'im_size', 'mode': '"""bilinear"""'}), "(image_relevance, size=im_size, mode='bilinear')\n", (1013, 1061), False, 'import torch\n'), ((1904, 1991), 'numpy.zeros', 'np.zeros', (['(logits_per_image.shape[0], logits_per_image.shape[1])'], {'dtype': 'np.float32'}), '((logits_per_image.shape[0], logits_per_image.shape[1]), dtype=np.\n float32)\n', (1912, 1991), True, 'import numpy as np\n'), ((4855, 4870), 'numpy.float32', 'np.float32', (['img'], {}), '(img)\n', (4865, 4870), True, 'import numpy as np\n'), ((5383, 5410), 'numpy.uint8', 'np.uint8', (['(255 * attn_dot_im)'], {}), '(255 * attn_dot_im)\n', (5391, 5410), True, 'import numpy as np\n'), ((5425, 5461), 'cv2.cvtColor', 'cv2.cvtColor', (['vis', 'cv2.COLOR_RGB2BGR'], {}), '(vis, cv2.COLOR_RGB2BGR)\n', (5437, 5461), False, 'import cv2\n'), ((5483, 5535), 'numpy.concatenate', 'np.concatenate', (['[orig_img, vis, attn_dot_im]'], {'axis': '(1)'}), '([orig_img, vis, attn_dot_im], axis=1)\n', (5497, 5535), True, 'import numpy as np\n'), ((5615, 5661), 'matplotlib.pyplot.imsave', 'plt.imsave', (['output_fname', 'vis_concat_captioned'], {}), '(output_fname, vis_concat_captioned)\n', (5625, 5661), True, 'import matplotlib.pyplot as plt\n'), ((5946, 5967), 'numpy.array', 'np.array', (['caption_img'], {}), '(caption_img)\n', (5954, 5967), True, 'import numpy as np\n'), ((8861, 8894), 'os.path.exists', 'os.path.exists', (['model_config_file'], {}), '(model_config_file)\n', (8875, 8894), False, 'import os\n'), ((9068, 9155), 'clip.clip._transform', 'clip._transform', (['model.visual.input_resolution'], {'is_train': '(False)', 'color_jitter': '(False)'}), '(model.visual.input_resolution, is_train=False, color_jitter\n =False)\n', (9083, 9155), False, 'from clip import clip\n'), ((9159, 9188), 'training.main.convert_models_to_fp32', 'convert_models_to_fp32', (['model'], {}), '(model)\n', (9181, 9188), False, 'from training.main import convert_models_to_fp32\n'), ((9229, 9353), 'torch.nn.parallel.DistributedDataParallel', 'torch.nn.parallel.DistributedDataParallel', (['model'], {'device_ids': '[gpu]', 'find_unused_parameters': '(True)', 'broadcast_buffers': '(False)'}), '(model, device_ids=[gpu],\n find_unused_parameters=True, broadcast_buffers=False)\n', (9270, 9353), False, 'import torch\n'), ((9397, 9440), 'torch.load', 'torch.load', (['checkpoint'], {'map_location': 'device'}), '(checkpoint, map_location=device)\n', (9407, 9440), False, 'import torch\n'), ((9730, 9778), 'clip.clip.load', 'clip.load', (['model_class'], {'device': 'device', 'jit': '(False)'}), '(model_class, device=device, jit=False)\n', (9739, 9778), False, 'from clip import clip\n'), ((10578, 10609), 'os.path.exists', 'os.path.exists', (['args.output_dir'], {}), '(args.output_dir)\n', (10592, 10609), False, 'import os\n'), ((10619, 10644), 'os.mkdir', 'os.mkdir', (['args.output_dir'], {}), '(args.output_dir)\n', (10627, 10644), False, 'import os\n'), ((10669, 10694), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (10692, 10694), False, 'import torch\n'), ((11068, 11114), 'os.path.join', 'os.path.join', (['args.image_dir', 'f"""{eval_id}.jpg"""'], {}), "(args.image_dir, f'{eval_id}.jpg')\n", (11080, 11114), False, 'import os\n'), ((11388, 11435), 'os.path.join', 'os.path.join', (['args.output_dir', 'f"""{eval_id}.jpg"""'], {}), "(args.output_dir, f'{eval_id}.jpg')\n", (11400, 11435), False, 'import os\n'), ((827, 860), 'numpy.sqrt', 'np.sqrt', (['image_relevance.shape[0]'], {}), '(image_relevance.shape[0])\n', (834, 860), True, 'import numpy as np\n'), ((1440, 1461), 'numpy.uint8', 'np.uint8', (['(255 * image)'], {}), '(255 * image)\n', (1448, 1461), True, 'import numpy as np\n'), ((3601, 3627), 'numpy.array', 'np.array', (['attn_dot_im_list'], {}), '(attn_dot_im_list)\n', (3609, 3627), True, 'import numpy as np\n'), ((3629, 3659), 'numpy.array', 'np.array', (['image_relevance_list'], {}), '(image_relevance_list)\n', (3637, 3659), True, 'import numpy as np\n'), ((3661, 3681), 'numpy.array', 'np.array', (['image_list'], {}), '(image_list)\n', (3669, 3681), True, 'import numpy as np\n'), ((4466, 4477), 'time.time', 'time.time', ([], {}), '()\n', (4475, 4477), False, 'import time\n'), ((4757, 4777), 'numpy.uint8', 'np.uint8', (['(255 * mask)'], {}), '(255 * mask)\n', (4765, 4777), True, 'import numpy as np\n'), ((4815, 4834), 'numpy.float32', 'np.float32', (['heatmap'], {}), '(heatmap)\n', (4825, 4834), True, 'import numpy as np\n'), ((4919, 4930), 'numpy.max', 'np.max', (['cam'], {}), '(cam)\n', (4925, 4930), True, 'import numpy as np\n'), ((5315, 5334), 'numpy.uint8', 'np.uint8', (['(255 * vis)'], {}), '(255 * vis)\n', (5323, 5334), True, 'import numpy as np\n'), ((5336, 5360), 'numpy.uint8', 'np.uint8', (['(255 * orig_img)'], {}), '(255 * orig_img)\n', (5344, 5360), True, 'import numpy as np\n'), ((7596, 7624), 'numpy.array', 'np.array', (['wall_only_file_ids'], {}), '(wall_only_file_ids)\n', (7604, 7624), True, 'import numpy as np\n'), ((7626, 7654), 'numpy.array', 'np.array', (['wall_pair_file_ids'], {}), '(wall_pair_file_ids)\n', (7634, 7654), True, 'import numpy as np\n'), ((8968, 8980), 'json.load', 'json.load', (['f'], {}), '(f)\n', (8977, 8980), False, 'import json\n'), ((12401, 12412), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (12410, 12412), False, 'import os\n'), ((1571, 1586), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (1579, 1586), True, 'import numpy as np\n'), ((1624, 1664), 'numpy.expand_dims', 'np.expand_dims', (['image_relevance'], {'axis': '(-1)'}), '(image_relevance, axis=-1)\n', (1638, 1664), True, 'import numpy as np\n'), ((2003, 2042), 'torch.arange', 'torch.arange', (['logits_per_image.shape[0]'], {}), '(logits_per_image.shape[0])\n', (2015, 2042), False, 'import torch\n'), ((2073, 2098), 'torch.from_numpy', 'torch.from_numpy', (['one_hot'], {}), '(one_hot)\n', (2089, 2098), False, 'import torch\n'), ((2393, 2471), 'torch.eye', 'torch.eye', (['num_tokens', 'num_tokens'], {'dtype': 'image_attn_blocks[0].attn_probs.dtype'}), '(num_tokens, num_tokens, dtype=image_attn_blocks[0].attn_probs.dtype)\n', (2402, 2471), False, 'import torch\n'), ((3152, 3169), 'torch.bmm', 'torch.bmm', (['cam', 'R'], {}), '(cam, R)\n', (3161, 3169), False, 'import torch\n'), ((8325, 8432), 'torch.distributed.init_process_group', 'dist.init_process_group', ([], {'backend': '"""nccl"""', 'init_method': 'f"""tcp://127.0.0.1:{port}"""', 'world_size': '(1)', 'rank': 'gpu'}), "(backend='nccl', init_method=\n f'tcp://127.0.0.1:{port}', world_size=1, rank=gpu)\n", (8348, 8432), True, 'import torch.distributed as dist\n'), ((11180, 11202), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (11190, 11202), False, 'from PIL import Image, ImageDraw\n'), ((2728, 2793), 'torch.autograd.grad', 'torch.autograd.grad', (['one_hot', '[blk.attn_probs]'], {'retain_graph': '(True)'}), '(one_hot, [blk.attn_probs], retain_graph=True)\n', (2747, 2793), False, 'import torch\n'), ((3718, 3737), 'PIL.Image.fromarray', 'Image.fromarray', (['im'], {}), '(im)\n', (3733, 3737), False, 'from PIL import Image, ImageDraw\n')]
import numpy as np def compute_D(mdp, gamma, policy, P_0=None, t_max=None, threshold=1e-6): ''' Computes occupancy measure of a MDP under a given time-constrained policy -- the expected discounted number of times that policy π visits state s in a given number of timesteps. The version w/o discount is described in Algorithm 9.3 of Ziebart's thesis: http://www.cs.cmu.edu/~bziebart/publications/thesis-bziebart.pdf. The discounted version can be found in the supplement to Levine's "Nonlinear Inverse Reinforcement Learning with Gaussian Processes" (GPIRL): https://graphics.stanford.edu/projects/gpirl/gpirl_supplement.pdf. Parameters ---------- mdp : object Instance of the MDP class. gamma : float Discount factor; 0<=gamma<=1. policy : 2D numpy array policy[s,a] is the probability of taking action a in state s. P_0 : 1D numpy array of shape (mdp.nS) i-th element is the probability that the traj will start in state i. t_max : int number of timesteps the policy is executed. Returns ------- 1D numpy array of shape (mdp.nS) ''' if P_0 is None: P_0 = np.ones(mdp.nS) / mdp.nS D_prev = np.zeros_like(P_0) t = 0 diff = float("inf") while diff > threshold: # ∀ s: D[s] <- P_0[s] D = np.copy(P_0) for s in range(mdp.nS): for a in range(mdp.nA): # for all s_prime reachable from s by taking a do: for p_sprime, s_prime, _ in mdp.P[s][a]: D[s_prime] += gamma * D_prev[s] * policy[s, a] * p_sprime diff = np.amax(abs(D_prev - D)) D_prev = np.copy(D) if t_max is not None: t+=1 if t==t_max: break return D
[ "numpy.zeros_like", "numpy.ones", "numpy.copy" ]
[((1238, 1256), 'numpy.zeros_like', 'np.zeros_like', (['P_0'], {}), '(P_0)\n', (1251, 1256), True, 'import numpy as np\n'), ((1380, 1392), 'numpy.copy', 'np.copy', (['P_0'], {}), '(P_0)\n', (1387, 1392), True, 'import numpy as np\n'), ((1726, 1736), 'numpy.copy', 'np.copy', (['D'], {}), '(D)\n', (1733, 1736), True, 'import numpy as np\n'), ((1200, 1215), 'numpy.ones', 'np.ones', (['mdp.nS'], {}), '(mdp.nS)\n', (1207, 1215), True, 'import numpy as np\n')]
import numpy as np from tqdm import tqdm import xlrd from copy import deepcopy valid_schedules = [] all_valid_schedules = [] class_name_to_class_ID = {} class_ID_to_class_name = {} class_names = set() class_name_combos = [] class_ID_combos = [] def get_class_name_ID_dicts(excel_data): global class_names, class_name_to_class_ID, class_ID_to_class_name class_combos = excel_data.split('\n') for class_combo in class_combos: classes = class_combo.split('\t') for c in classes: class_names.add(c) class_ID = 0 for class_name in class_names: class_name_to_class_ID[str(class_name)] = class_ID class_ID += 1 class_ID_to_class_name = {v: k for k, v in class_name_to_class_ID.items()} def get_class_name_combos_class_ID_combos(excel_data): global class_name_combos, class_ID_combos class_combos = excel_data.split('\n') for class_combo in class_combos: classes = class_combo.split('\t') class_name_combo = [] class_ID_combo = [] for c in classes: class_name_combo.append(c) class_ID_combo.append(class_name_to_class_ID[c]) class_name_combos.append(class_name_combo) class_ID_combos.append(class_ID_combo) def get_class_combo_matrix(num_combos, num_classes): A = np.zeros((num_combos, num_classes)) for i in range(len(class_ID_combos)): class_ID_combo = class_ID_combos[i] for c in class_ID_combo: A[i, c] = 1 return A def get_valid_schedule_per_slot(A, num_combos, num_classes): x_list = [] for i in range(2**num_classes): small_x = list("{0:b}".format(i)) small_x = np.array([float(m) for m in small_x]) x = np.zeros(num_classes) for j in range(len(small_x)): x[len(x) - 1 - j] = small_x[len(small_x) - 1 - j] if sum(np.matmul(A, x) <= 1) == num_combos: x_list.append(x) return x_list def each_exam_is_in(x1, x2, x3, x4, x5, num_classes): exam_is_in = True for i in range(num_classes): if x1[i] + x2[i] + x3[i] + x4[i] + x5[i] != 1: exam_is_in = False break return exam_is_in def get_valid_schedules(x_list, num_classes): x_list_final = [] for x1 in tqdm(x_list): for x2 in x_list: for x3 in x_list: for x4 in x_list: for x5 in x_list: exam_is_in = each_exam_is_in(x1, x2, x3, x4, x5, num_classes) if exam_is_in: x = (x1,x2,x3,x4,x5) x_list_final.append(x) return x_list_final def load_classes(excel_data, slot_count_): """ Load classes for a given excel_data string, containing 3 columns on each line separated by tabs. Load the schedule to a global variable for later access. E.g: Classname1 <tab> ClassName2 <tab> ClassName3 Classname4 <tab> ClassName5 <tab> ClassName6 """ global slot_count, valid_schedules, all_valid_schedules slot_count = slot_count_ get_class_name_ID_dicts(excel_data) get_class_name_combos_class_ID_combos(excel_data) num_combos = len(class_name_combos) num_class_per_combo = len(class_name_combos[0]) #which is always 3 num_classes = len(class_name_to_class_ID) class_combo_matrix = get_class_combo_matrix(num_combos, num_classes) valid_schedule_per_slot = get_valid_schedule_per_slot(class_combo_matrix, num_combos, num_classes) valid_schedules = get_valid_schedules(valid_schedule_per_slot, num_classes) all_valid_schedules = deepcopy(valid_schedules) return def get_potential_classes_for_slot(slot_number): """ Get the names of exams available to pick for a given slot_number Returns list of names of exams. """ potential_classes = set() for valid_schedule in valid_schedules: slot = valid_schedule[slot_number] for i in range(len(slot)): if slot[i] == 1: class_name = class_ID_to_class_name[i] potential_classes.add(class_name) return list(potential_classes) def select_class_for_slot(class_name, slot_number): """ Select a class_name for a certain slot_number. Class name is selected from one of get_potential_classes_for_slot(slot_number) Do the necessary manipulation """ global valid_schedules valid_schedules_new = [] class_ID = class_name_to_class_ID[class_name] for valid_schedule in valid_schedules: slot = valid_schedule[slot_number] if slot[class_ID] == 1: valid_schedules_new.append(valid_schedule) valid_schedules = deepcopy(valid_schedules_new) return def reset_selections(): """ Resets all made selection, returning to initial state """ global valid_schedules valid_schedules = deepcopy(all_valid_schedules) return def get_all_potential_classes(): """ Returns a dictonary of potential classes for all slots { [slot_number]: [...classes_available] ... } """ return # excel_data = 'Physics\tChemistry\tBusiness\nPhysics\tChemistry\tEcon\nPhysics\tCS\tEcon\nChemistry\tBiology\tEcon' # slot_count_ = 5
[ "copy.deepcopy", "tqdm.tqdm", "numpy.zeros", "numpy.matmul" ]
[((1374, 1409), 'numpy.zeros', 'np.zeros', (['(num_combos, num_classes)'], {}), '((num_combos, num_classes))\n', (1382, 1409), True, 'import numpy as np\n'), ((2376, 2388), 'tqdm.tqdm', 'tqdm', (['x_list'], {}), '(x_list)\n', (2380, 2388), False, 'from tqdm import tqdm\n'), ((3757, 3782), 'copy.deepcopy', 'deepcopy', (['valid_schedules'], {}), '(valid_schedules)\n', (3765, 3782), False, 'from copy import deepcopy\n'), ((4860, 4889), 'copy.deepcopy', 'deepcopy', (['valid_schedules_new'], {}), '(valid_schedules_new)\n', (4868, 4889), False, 'from copy import deepcopy\n'), ((5065, 5094), 'copy.deepcopy', 'deepcopy', (['all_valid_schedules'], {}), '(all_valid_schedules)\n', (5073, 5094), False, 'from copy import deepcopy\n'), ((1818, 1839), 'numpy.zeros', 'np.zeros', (['num_classes'], {}), '(num_classes)\n', (1826, 1839), True, 'import numpy as np\n'), ((1955, 1970), 'numpy.matmul', 'np.matmul', (['A', 'x'], {}), '(A, x)\n', (1964, 1970), True, 'import numpy as np\n')]
import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from models.langevin import sample_langevin class EnergyBasedModel(nn.Module): def __init__(self, net, alpha=1, step_size=10, sample_step=60, noise_std=0.005, buffer_size=10000, replay_ratio=0.95, langevin_clip_grad=0.01, clip_x=(0, 1)): super().__init__() self.net = net self.alpha = alpha self.step_size = step_size self.sample_step = sample_step self.noise_std = noise_std self.buffer_size = buffer_size self.buffer = SampleBuffer(max_samples=buffer_size, replay_ratio=replay_ratio) self.replay_ratio = replay_ratio self.replay = True if self.replay_ratio > 0 else False self.langevin_clip_grad = langevin_clip_grad self.clip_x = clip_x self.own_optimizer = False def forward(self, x): return self.net(x).view(-1) def predict(self, x): return self(x) def validation_step(self, x, y=None): with torch.no_grad(): pos_e = self(x) return {'loss': pos_e.mean(), 'predict': pos_e, } def train_step(self, x, optimizer, clip_grad=None, y=None): neg_x = self.sample(shape=x.shape, device=x.device, replay=self.replay) optimizer.zero_grad() pos_e = self(x) neg_e = self(neg_x) ebm_loss = pos_e.mean() - neg_e.mean() reg_loss = (pos_e ** 2).mean() + (neg_e ** 2).mean() weight_norm = sum([(w ** 2).sum() for w in self.net.parameters()]) loss = ebm_loss + self.alpha * reg_loss # + self.beta * weight_norm loss.backward() if clip_grad is not None: # torch.nn.utils.clip_grad_norm_(self.parameters(), max_norm=clip_grad) clip_grad_ebm(self.parameters(), optimizer) optimizer.step() return {'loss': loss.item(), 'ebm_loss': ebm_loss.item(), 'pos_e': pos_e.mean().item(), 'neg_e': neg_e.mean().item(), 'reg_loss': reg_loss.item(), 'neg_sample': neg_x.detach().cpu(), 'weight_norm': weight_norm.item()} def sample(self, shape, device, replay=True, intermediate=False, step_size=None, sample_step=None): if step_size is None: step_size = self.step_size if sample_step is None: sample_step = self.sample_step # initialize x0 = self.buffer.sample(shape, device, replay=replay) # run langevin sample_x = sample_langevin(x0, self, step_size, sample_step, noise_scale=self.noise_std, intermediate_samples=intermediate, clip_x=self.clip_x, clip_grad=self.langevin_clip_grad, ) # push samples if replay: self.buffer.push(sample_x) return sample_x class SampleBuffer: def __init__(self, max_samples=10000, replay_ratio=0.95, bound=None): self.max_samples = max_samples self.buffer = [] self.replay_ratio = replay_ratio if bound is None: self.bound = (0, 1) else: self.bound = bound def __len__(self): return len(self.buffer) def push(self, samples): samples = samples.detach().to('cpu') for sample in samples: self.buffer.append(sample) if len(self.buffer) > self.max_samples: self.buffer.pop(0) def get(self, n_samples): samples = random.choices(self.buffer, k=n_samples) samples = torch.stack(samples, 0) return samples def sample(self, shape, device, replay=False): if len(self.buffer) < 1 or not replay: # empty buffer return self.random(shape, device) n_replay = (np.random.rand(shape[0]) < self.replay_ratio).sum() replay_sample = self.get(n_replay).to(device) n_random = shape[0] - n_replay if n_random > 0: random_sample = self.random((n_random,) + shape[1:], device) return torch.cat([replay_sample, random_sample]) else: return replay_sample def random(self, shape, device): if self.bound is None: r = torch.rand(*shape, dtype=torch.float).to(device) elif self.bound == 'spherical': r = torch.randn(*shape, dtype=torch.float).to(device) norm = r.view(len(r), -1).norm(dim=-1) if len(shape) == 4: r = r / norm[:, None, None, None] elif len(shape) == 2: r = r / norm[:, None] else: raise NotImplementedError elif len(self.bound) == 2: r = torch.rand(*shape, dtype=torch.float).to(device) r = r * (self.bound[1] - self.bound[0]) + self.bound[0] return r class SampleBufferV2: def __init__(self, max_samples=10000, replay_ratio=0.95): self.max_samples = max_samples self.buffer = [] self.replay_ratio = replay_ratio def __len__(self): return len(self.buffer) def push(self, samples): samples = samples.detach().to('cpu') for sample in samples: self.buffer.append(sample) if len(self.buffer) > self.max_samples: self.buffer.pop(0) def get(self, n_samples): samples = random.choices(self.buffer, k=n_samples) samples = torch.stack(samples, 0) return samples def clip_grad_ebm(parameters, optimizer): with torch.no_grad(): for group in optimizer.param_groups: for p in group['params']: state = optimizer.state[p] if 'step' not in state or state['step'] < 1: continue step = state['step'] exp_avg_sq = state['exp_avg_sq'] _, beta2 = group['betas'] bound = 3 * torch.sqrt(exp_avg_sq / (1 - beta2 ** step)) + 0.1 p.grad.data.copy_(torch.max(torch.min(p.grad.data, bound), -bound))
[ "torch.stack", "torch.sqrt", "torch.min", "random.choices", "torch.cat", "torch.randn", "torch.rand", "numpy.random.rand", "torch.no_grad", "models.langevin.sample_langevin" ]
[((2592, 2768), 'models.langevin.sample_langevin', 'sample_langevin', (['x0', 'self', 'step_size', 'sample_step'], {'noise_scale': 'self.noise_std', 'intermediate_samples': 'intermediate', 'clip_x': 'self.clip_x', 'clip_grad': 'self.langevin_clip_grad'}), '(x0, self, step_size, sample_step, noise_scale=self.\n noise_std, intermediate_samples=intermediate, clip_x=self.clip_x,\n clip_grad=self.langevin_clip_grad)\n', (2607, 2768), False, 'from models.langevin import sample_langevin\n'), ((3685, 3725), 'random.choices', 'random.choices', (['self.buffer'], {'k': 'n_samples'}), '(self.buffer, k=n_samples)\n', (3699, 3725), False, 'import random\n'), ((3744, 3767), 'torch.stack', 'torch.stack', (['samples', '(0)'], {}), '(samples, 0)\n', (3755, 3767), False, 'import torch\n'), ((5547, 5587), 'random.choices', 'random.choices', (['self.buffer'], {'k': 'n_samples'}), '(self.buffer, k=n_samples)\n', (5561, 5587), False, 'import random\n'), ((5606, 5629), 'torch.stack', 'torch.stack', (['samples', '(0)'], {}), '(samples, 0)\n', (5617, 5629), False, 'import torch\n'), ((5706, 5721), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5719, 5721), False, 'import torch\n'), ((1081, 1096), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1094, 1096), False, 'import torch\n'), ((4236, 4277), 'torch.cat', 'torch.cat', (['[replay_sample, random_sample]'], {}), '([replay_sample, random_sample])\n', (4245, 4277), False, 'import torch\n'), ((3973, 3997), 'numpy.random.rand', 'np.random.rand', (['shape[0]'], {}), '(shape[0])\n', (3987, 3997), True, 'import numpy as np\n'), ((4410, 4447), 'torch.rand', 'torch.rand', (['*shape'], {'dtype': 'torch.float'}), '(*shape, dtype=torch.float)\n', (4420, 4447), False, 'import torch\n'), ((4516, 4554), 'torch.randn', 'torch.randn', (['*shape'], {'dtype': 'torch.float'}), '(*shape, dtype=torch.float)\n', (4527, 4554), False, 'import torch\n'), ((6098, 6142), 'torch.sqrt', 'torch.sqrt', (['(exp_avg_sq / (1 - beta2 ** step))'], {}), '(exp_avg_sq / (1 - beta2 ** step))\n', (6108, 6142), False, 'import torch\n'), ((6193, 6222), 'torch.min', 'torch.min', (['p.grad.data', 'bound'], {}), '(p.grad.data, bound)\n', (6202, 6222), False, 'import torch\n'), ((4883, 4920), 'torch.rand', 'torch.rand', (['*shape'], {'dtype': 'torch.float'}), '(*shape, dtype=torch.float)\n', (4893, 4920), False, 'import torch\n')]
""" Macrocycle Vertices =================== """ from __future__ import annotations import typing import numpy as np from scipy.spatial.distance import euclidean from ...molecules import BuildingBlock from ..topology_graph import Edge, Vertex class CycleVertex(Vertex): """ Represents a vertex in a macrocycle. """ def __init__( self, id: int, position: typing.Union[np.ndarray, tuple[float, float, float]], flip: bool, angle: float, ) -> None: """ Initialize a :class:`.CycleVertex` instance. Parameters: id: The id of the vertex. position: The position of the vertex. flip: If ``True``, the orientation of building blocks placed by the vertex will be flipped. angle: The position of the vertex along the cycle, specified by the `angle`. """ super().__init__(id, position) self._flip = flip self._angle = angle def clone(self) -> CycleVertex: clone = self._clone() clone._flip = self._flip clone._angle = self._angle return clone def get_flip(self) -> bool: """ Return ``True`` if the vertex flips building blocks it places. Returns: ``True`` if the vertex flips building blocks it places. """ return self._flip def place_building_block( self, building_block: BuildingBlock, edges: tuple[Edge, ...], ) -> np.ndarray: assert ( building_block.get_num_functional_groups() == 2 ), ( f'{building_block} needs to have exactly 2 functional ' 'groups but has ' f'{building_block.get_num_functional_groups()}.' ) building_block = building_block.with_centroid( position=self._position, atom_ids=building_block.get_placer_ids(), ) fg0, fg1 = building_block.get_functional_groups() fg0_position = building_block.get_centroid( atom_ids=fg0.get_placer_ids(), ) fg1_position = building_block.get_centroid( atom_ids=fg1.get_placer_ids(), ) return building_block.with_rotation_between_vectors( start=fg1_position - fg0_position, target=np.array([-1 if self._flip else 1, 0, 0]), origin=self._position, ).with_rotation_about_axis( angle=self._angle-(np.pi/2), axis=np.array([0, 0, 1]), origin=self._position, ).get_position_matrix() def map_functional_groups_to_edges( self, building_block: BuildingBlock, edges: tuple[Edge, ...], ) -> dict[int, int]: fg0_position = building_block.get_centroid( atom_ids=next( building_block.get_functional_groups() ).get_placer_ids(), ) def fg0_distance(edge: Edge) -> float: return euclidean(edge.get_position(), fg0_position) edge0 = min(edges, key=fg0_distance) return { 0: edge0.get_id(), 1: ( edges[1].get_id() if edge0 is edges[0] else edges[0].get_id() ), } def __str__(self) -> str: return ( f'Vertex(id={self._id}, ' f'position={tuple(self._position.tolist())}, ' f'flip={self._flip}, ' f'angle={self._angle})' )
[ "numpy.array" ]
[((2607, 2626), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (2615, 2626), True, 'import numpy as np\n'), ((2435, 2476), 'numpy.array', 'np.array', (['[-1 if self._flip else 1, 0, 0]'], {}), '([-1 if self._flip else 1, 0, 0])\n', (2443, 2476), True, 'import numpy as np\n')]
import numpy as np from scipy.ndimage.interpolation import affine_transform import elasticdeform import multiprocessing as mp def patch_extraction(Xb, yb, sizePatches=128, Npatches=1): """ 3D patch extraction """ batch_size, rows, columns, slices, channels = Xb.shape X_patches = np.empty((batch_size*Npatches, sizePatches, sizePatches, sizePatches, channels)) y_patches = np.empty((batch_size*Npatches, sizePatches, sizePatches, sizePatches)) i = 0 for b in range(batch_size): for p in range(Npatches): x = np.random.randint(rows-sizePatches+1) y = np.random.randint(columns-sizePatches+1) z = np.random.randint(slices-sizePatches+1) X_patches[i] = Xb[b, x:x+sizePatches, y:y+sizePatches, z:z+sizePatches, :] y_patches[i] = yb[b, x:x+sizePatches, y:y+sizePatches, z:z+sizePatches] i += 1 return X_patches, y_patches def flip3D(X, y): """ Flip the 3D image respect one of the 3 axis chosen randomly """ choice = np.random.randint(3) if choice == 0: # flip on x X_flip, y_flip = X[::-1, :, :, :], y[::-1, :, :] if choice == 1: # flip on y X_flip, y_flip = X[:, ::-1, :, :], y[:, ::-1, :] if choice == 2: # flip on z X_flip, y_flip = X[:, :, ::-1, :], y[:, :, ::-1] return X_flip, y_flip def rotation3D(X, y): """ Rotate a 3D image with alfa, beta and gamma degree respect the axis x, y and z respectively. The three angles are chosen randomly between 0-30 degrees """ alpha, beta, gamma = np.pi*np.random.random_sample(3,)/2 Rx = np.array([[1, 0, 0], [0, np.cos(alpha), -np.sin(alpha)], [0, np.sin(alpha), np.cos(alpha)]]) Ry = np.array([[np.cos(beta), 0, np.sin(beta)], [0, 1, 0], [-np.sin(beta), 0, np.cos(beta)]]) Rz = np.array([[np.cos(gamma), -np.sin(gamma), 0], [np.sin(gamma), np.cos(gamma), 0], [0, 0, 1]]) R = np.dot(np.dot(Rx, Ry), Rz) X_rot = np.empty_like(X) for channel in range(X.shape[-1]): X_rot[:,:,:,channel] = affine_transform(X[:,:,:,channel], R, offset=0, order=3, mode='constant') y_rot = affine_transform(y, R, offset=0, order=0, mode='constant') return X_rot, y_rot def brightness(X, y): """ Changing the brighness of a image using power-law gamma transformation. Gain and gamma are chosen randomly for each image channel. Gain chosen between [0.9 - 1.1] Gamma chosen between [0.9 - 1.1] new_im = gain * im^gamma """ X_new = np.zeros(X.shape) for c in range(X.shape[-1]): im = X[:,:,:,c] gain, gamma = (1.2 - 0.8) * np.random.random_sample(2,) + 0.8 im_new = np.sign(im)*gain*(np.abs(im)**gamma) X_new[:,:,:,c] = im_new return X_new, y def elastic(X, y): """ Elastic deformation on a image and its target """ [Xel, yel] = elasticdeform.deform_random_grid([X, y], sigma=2, axis=[(0, 1, 2), (0, 1, 2)], order=[1, 0], mode='constant') return Xel, yel def random_decisions(N): """ Generate N random decisions for augmentation N should be equal to the batch size """ decisions = np.zeros((N, 4)) # 4 is number of aug techniques to combine (patch extraction excluded) for n in range(N): decisions[n] = np.random.randint(2, size=4) return decisions def combine_aug(X, y, do): """ Combine randomly the different augmentation techniques written above """ Xnew, ynew = X, y # make sure to use at least the 25% of original images if np.random.random_sample()>0.75: return Xnew, ynew else: if do[0] == 1: Xnew, ynew = flip3D(Xnew, ynew) if do[1] == 1: Xnew, ynew = brightness(Xnew, ynew) if do[2] == 1: Xnew, ynew = rotation3D(Xnew, ynew) if do[3] == 1: Xnew, ynew = elastic(Xnew, ynew) return Xnew, ynew def aug_batch(Xb, Yb): """ Generate a augmented image batch """ batch_size = len(Xb) newXb, newYb = np.empty_like(Xb), np.empty_like(Yb) decisions = random_decisions(batch_size) inputs = [(X, y, do) for X, y, do in zip(Xb, Yb, decisions)] pool = mp.Pool(processes=8) multi_result = pool.starmap(combine_aug, inputs) pool.close() for i in range(len(Xb)): newXb[i], newYb[i] = multi_result[i][0], multi_result[i][1] return newXb, newYb
[ "numpy.abs", "numpy.random.random_sample", "numpy.empty", "scipy.ndimage.interpolation.affine_transform", "numpy.zeros", "numpy.empty_like", "numpy.sign", "numpy.random.randint", "elasticdeform.deform_random_grid", "numpy.sin", "numpy.cos", "multiprocessing.Pool", "numpy.dot" ]
[((306, 392), 'numpy.empty', 'np.empty', (['(batch_size * Npatches, sizePatches, sizePatches, sizePatches, channels)'], {}), '((batch_size * Npatches, sizePatches, sizePatches, sizePatches,\n channels))\n', (314, 392), True, 'import numpy as np\n'), ((403, 475), 'numpy.empty', 'np.empty', (['(batch_size * Npatches, sizePatches, sizePatches, sizePatches)'], {}), '((batch_size * Npatches, sizePatches, sizePatches, sizePatches))\n', (411, 475), True, 'import numpy as np\n'), ((1086, 1106), 'numpy.random.randint', 'np.random.randint', (['(3)'], {}), '(3)\n', (1103, 1106), True, 'import numpy as np\n'), ((2152, 2168), 'numpy.empty_like', 'np.empty_like', (['X'], {}), '(X)\n', (2165, 2168), True, 'import numpy as np\n'), ((2325, 2383), 'scipy.ndimage.interpolation.affine_transform', 'affine_transform', (['y', 'R'], {'offset': '(0)', 'order': '(0)', 'mode': '"""constant"""'}), "(y, R, offset=0, order=0, mode='constant')\n", (2341, 2383), False, 'from scipy.ndimage.interpolation import affine_transform\n'), ((2720, 2737), 'numpy.zeros', 'np.zeros', (['X.shape'], {}), '(X.shape)\n', (2728, 2737), True, 'import numpy as np\n'), ((3090, 3204), 'elasticdeform.deform_random_grid', 'elasticdeform.deform_random_grid', (['[X, y]'], {'sigma': '(2)', 'axis': '[(0, 1, 2), (0, 1, 2)]', 'order': '[1, 0]', 'mode': '"""constant"""'}), "([X, y], sigma=2, axis=[(0, 1, 2), (0, 1, 2\n )], order=[1, 0], mode='constant')\n", (3122, 3204), False, 'import elasticdeform\n'), ((3377, 3393), 'numpy.zeros', 'np.zeros', (['(N, 4)'], {}), '((N, 4))\n', (3385, 3393), True, 'import numpy as np\n'), ((4471, 4491), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': '(8)'}), '(processes=8)\n', (4478, 4491), True, 'import multiprocessing as mp\n'), ((2115, 2129), 'numpy.dot', 'np.dot', (['Rx', 'Ry'], {}), '(Rx, Ry)\n', (2121, 2129), True, 'import numpy as np\n'), ((2239, 2315), 'scipy.ndimage.interpolation.affine_transform', 'affine_transform', (['X[:, :, :, channel]', 'R'], {'offset': '(0)', 'order': '(3)', 'mode': '"""constant"""'}), "(X[:, :, :, channel], R, offset=0, order=3, mode='constant')\n", (2255, 2315), False, 'from scipy.ndimage.interpolation import affine_transform\n'), ((3511, 3539), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(4)'}), '(2, size=4)\n', (3528, 3539), True, 'import numpy as np\n'), ((3780, 3805), 'numpy.random.random_sample', 'np.random.random_sample', ([], {}), '()\n', (3803, 3805), True, 'import numpy as np\n'), ((4296, 4313), 'numpy.empty_like', 'np.empty_like', (['Xb'], {}), '(Xb)\n', (4309, 4313), True, 'import numpy as np\n'), ((4315, 4332), 'numpy.empty_like', 'np.empty_like', (['Yb'], {}), '(Yb)\n', (4328, 4332), True, 'import numpy as np\n'), ((566, 607), 'numpy.random.randint', 'np.random.randint', (['(rows - sizePatches + 1)'], {}), '(rows - sizePatches + 1)\n', (583, 607), True, 'import numpy as np\n'), ((621, 665), 'numpy.random.randint', 'np.random.randint', (['(columns - sizePatches + 1)'], {}), '(columns - sizePatches + 1)\n', (638, 665), True, 'import numpy as np\n'), ((678, 721), 'numpy.random.randint', 'np.random.randint', (['(slices - sizePatches + 1)'], {}), '(slices - sizePatches + 1)\n', (695, 721), True, 'import numpy as np\n'), ((1639, 1665), 'numpy.random.random_sample', 'np.random.random_sample', (['(3)'], {}), '(3)\n', (1662, 1665), True, 'import numpy as np\n'), ((1722, 1735), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (1728, 1735), True, 'import numpy as np\n'), ((1777, 1790), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (1783, 1790), True, 'import numpy as np\n'), ((1792, 1805), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (1798, 1805), True, 'import numpy as np\n'), ((1834, 1846), 'numpy.cos', 'np.cos', (['beta'], {}), '(beta)\n', (1840, 1846), True, 'import numpy as np\n'), ((1851, 1863), 'numpy.sin', 'np.sin', (['beta'], {}), '(beta)\n', (1857, 1863), True, 'import numpy as np\n'), ((1934, 1946), 'numpy.cos', 'np.cos', (['beta'], {}), '(beta)\n', (1940, 1946), True, 'import numpy as np\n'), ((1975, 1988), 'numpy.cos', 'np.cos', (['gamma'], {}), '(gamma)\n', (1981, 1988), True, 'import numpy as np\n'), ((2030, 2043), 'numpy.sin', 'np.sin', (['gamma'], {}), '(gamma)\n', (2036, 2043), True, 'import numpy as np\n'), ((2045, 2058), 'numpy.cos', 'np.cos', (['gamma'], {}), '(gamma)\n', (2051, 2058), True, 'import numpy as np\n'), ((2839, 2865), 'numpy.random.random_sample', 'np.random.random_sample', (['(2)'], {}), '(2)\n', (2862, 2865), True, 'import numpy as np\n'), ((2890, 2901), 'numpy.sign', 'np.sign', (['im'], {}), '(im)\n', (2897, 2901), True, 'import numpy as np\n'), ((2908, 2918), 'numpy.abs', 'np.abs', (['im'], {}), '(im)\n', (2914, 2918), True, 'import numpy as np\n'), ((1738, 1751), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (1744, 1751), True, 'import numpy as np\n'), ((1917, 1929), 'numpy.sin', 'np.sin', (['beta'], {}), '(beta)\n', (1923, 1929), True, 'import numpy as np\n'), ((1991, 2004), 'numpy.sin', 'np.sin', (['gamma'], {}), '(gamma)\n', (1997, 2004), True, 'import numpy as np\n')]
import numpy as np from scipy.cluster.hierarchy import dendrogram, linkage from sklearn import preprocessing from sklearn.cluster import KMeans from matplotlib import pyplot as plt data = np.load('Data/dji_5yr_20d_log_close_data.npy') data = preprocessing.minmax_scale(data, axis=1) print(data.shape) km = KMeans( n_clusters=4, init='random', n_init=10, max_iter=300, tol=1e-04, random_state=0 ) y_km = km.fit_predict(data) print(str(y_km)) print(len([i for i in y_km if i == 1])) plt.plot(np.mean(data[y_km == 0], axis=0), color='g', label='Cluster 1 with {} sample'.format(len(data[y_km == 0]))) plt.plot(np.mean(data[y_km == 1], axis=0), color='b', label='Cluster 2 with {} sample'.format(len(data[y_km == 1]))) plt.plot(np.mean(data[y_km == 2], axis=0), color='r', label='Cluster 3 with {} sample'.format(len(data[y_km == 2]))) plt.plot(np.mean(data[y_km == 3], axis=0), color='orange', label='Cluster 4 with {} sample'.format(len(data[y_km == 3]))) plt.legend() plt.xlabel('Date') plt.show() # labels = np.random.randint(1230, size=50) # linked = linkage(data[labels,:], 'single') # plt.figure(figsize=(10, 7)) # dendrogram(linked, # orientation='top', # labels=labels, # distance_sort='descending', # show_leaf_counts=True, # leaf_font_size=14) # plt.show()
[ "numpy.load", "matplotlib.pyplot.show", "sklearn.cluster.KMeans", "matplotlib.pyplot.legend", "sklearn.preprocessing.minmax_scale", "numpy.mean", "matplotlib.pyplot.xlabel" ]
[((189, 235), 'numpy.load', 'np.load', (['"""Data/dji_5yr_20d_log_close_data.npy"""'], {}), "('Data/dji_5yr_20d_log_close_data.npy')\n", (196, 235), True, 'import numpy as np\n'), ((243, 283), 'sklearn.preprocessing.minmax_scale', 'preprocessing.minmax_scale', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (269, 283), False, 'from sklearn import preprocessing\n'), ((307, 399), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(4)', 'init': '"""random"""', 'n_init': '(10)', 'max_iter': '(300)', 'tol': '(0.0001)', 'random_state': '(0)'}), "(n_clusters=4, init='random', n_init=10, max_iter=300, tol=0.0001,\n random_state=0)\n", (313, 399), False, 'from sklearn.cluster import KMeans\n'), ((968, 980), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (978, 980), True, 'from matplotlib import pyplot as plt\n'), ((981, 999), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {}), "('Date')\n", (991, 999), True, 'from matplotlib import pyplot as plt\n'), ((1000, 1010), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1008, 1010), True, 'from matplotlib import pyplot as plt\n'), ((504, 536), 'numpy.mean', 'np.mean', (['data[y_km == 0]'], {'axis': '(0)'}), '(data[y_km == 0], axis=0)\n', (511, 536), True, 'import numpy as np\n'), ((621, 653), 'numpy.mean', 'np.mean', (['data[y_km == 1]'], {'axis': '(0)'}), '(data[y_km == 1], axis=0)\n', (628, 653), True, 'import numpy as np\n'), ((738, 770), 'numpy.mean', 'np.mean', (['data[y_km == 2]'], {'axis': '(0)'}), '(data[y_km == 2], axis=0)\n', (745, 770), True, 'import numpy as np\n'), ((855, 887), 'numpy.mean', 'np.mean', (['data[y_km == 3]'], {'axis': '(0)'}), '(data[y_km == 3], axis=0)\n', (862, 887), True, 'import numpy as np\n')]
import datetime as dt import numpy as np import pandas as pd import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from sqlalchemy import and_, or_ from os import environ, path from flask import Flask, jsonify from dateutil.relativedelta import * app = Flask(__name__) Base = automap_base() ################################################# # Database Setup ################################################# engine = create_engine("sqlite:////Users/katma/Documents/GitHub/Trilogoy/Homework/sqlalchemy-challenge/Resources/hawaii.sqlite") # reflect an existing database into a new model # reflect the tables Base.prepare(engine, reflect=True) Base.classes.keys() # Save references to each table measurement = Base.classes.measurement station = Base.classes.station # Create our session (link) from Python to the DB session = Session(engine) ################################################# # Flask Setup ################################################# @app.route("/") def welcome(): """List all available api routes.""" return ( f"Available Climate API Routes:<br/></br></br>" f"Follow this for information Stations: </br></br>" f"/api/v1.0/stations</br></br>" f"Follow this for information on Precipitation: </br></br>" f"/api/v1.0/precipitation</br></br>" f"Follow this for information Temperature: </br></br>" f"/api/v1.0/tobs</br></br>" f"Follow this to review set Start date averages: </br></br>" f"/api/v1.0/temp/<start></br></br>" f"Follow this for a set start and end date average: </br></br>" f"/api/v1.0/temp/<start>/<end></br></br>" ) #Convert the query results to a dictionary using date as the key and prcp as the value. #Return the JSON representation of your dictionary. @app.route("/api/v1.0/precipitation") def prcp(): # # Create our session (link) from Python to the DB session = Session(engine) # Find last point in data to calculate 1 year ago lastpoint = session.query(measurement.date).order_by(measurement.date.desc()).first()[0] lastpoint=dt.datetime.strptime(lastpoint, "%Y-%m-%d") # Calculate the date 1 year ago from the last data point in the database year_ago = dt.date(2017,8,23) - relativedelta(months=12) query = session.query(measurement.date,measurement.prcp).\ filter(measurement.date >= year_ago).all() #dictionary fullprcplist = [] for date, prcp in query: prcp_dict = {} prcp_dict["Date"] = date prcp_dict["Precipitation"] = prcp fullprcplist.append(prcp_dict) return jsonify(fullprcplist) #Return a JSON list of stations from the dataset. @app.route("/api/v1.0/stations") def stations(): # Create our session (link) from Python to the DB session = Session(engine) # Query stations stations = session.query(station.station).order_by(station.station).all() stations = list(np.ravel(stations)) return jsonify(stations) @app.route("/api/v1.0/tobs") def tobs(): # Create our session (link) from Python to the DB session = Session(engine) # Calculate the date 1 year ago from the last data point in the database lastpoint = session.query(measurement.date).order_by(measurement.date.desc()).first().date lastpoint lastpoint=dt.datetime.strptime(lastpoint, "%Y-%m-%d") year_ago = dt.date(2017,8,23) - relativedelta(months=12) # Query topstations topstations = session.query(measurement.station,func.count(measurement.station)).group_by(measurement.station).order_by(func.count(measurement.station).desc()).\ filter(measurement.date >= '2016-08-23').all() #Under the assumption I need to use the highest row count from query topstation1 = (topstations[0]) topstation1 = (topstation1[0]) # Using the station id from the previous query, calculate the lowest temperature recorded, # highest temperature recorded, and average temperature of the most active station? query = session.query((measurement.date),func.min(measurement.tobs),func.avg(measurement.tobs),func.max(measurement.tobs)).\ filter(measurement.station == 'USC00519397').filter(measurement.date >= year_ago).group_by(measurement.date).all() toplist = [] for date, min, avg, max in query: loopyboi = {} loopyboi["Date"] = date loopyboi["Minimum Temp"] = min loopyboi["Average Temp"] = avg loopyboi["Max Temp"] = max toplist.append(loopyboi) return jsonify(toplist) @app.route('/api/v1.0/temp/<start>', defaults={'end': None}) def temperatures(start, end): # Create our session (link) from Python to the DB session = Session(engine) # Query query = session.query(func.min(measurement.tobs), func.avg(measurement.tobs), func.max(measurement.tobs)).\ filter(measurement.date >= start).all() session.close() #create list templist = {} for mini, avge, maxi in query: templist["Minimum Temp"] = mini templist["Average Temp"] = avge templist["Max Temp"] = maxi return jsonify(templist) @app.route('/api/v1.0/temp/<start>/<end>') def temperatures2(start, end): session = Session(engine) query1 = session.query(func.min(measurement.tobs), func.avg(measurement.tobs), func.max(measurement.tobs)).\ filter(measurement.date >= start).filter(measurement.date <= end).group_by(measurement.date).all() session.close() #create list templist = [] for mini, avge, maxi in query1: loopyboi = {} loopyboi["Minimum Temp"] = mini loopyboi["Average Temp"] = avge loopyboi["Max Temp"] = maxi templist.append(loopyboi) return jsonify(templist) if __name__ == '__main__': app.run(debug=True)
[ "sqlalchemy.func.avg", "numpy.ravel", "flask.Flask", "datetime.date", "sqlalchemy.orm.Session", "datetime.datetime.strptime", "flask.jsonify", "sqlalchemy.func.min", "sqlalchemy.func.count", "sqlalchemy.create_engine", "sqlalchemy.ext.automap.automap_base", "sqlalchemy.func.max" ]
[((345, 360), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (350, 360), False, 'from flask import Flask, jsonify\n'), ((368, 382), 'sqlalchemy.ext.automap.automap_base', 'automap_base', ([], {}), '()\n', (380, 382), False, 'from sqlalchemy.ext.automap import automap_base\n'), ((509, 638), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:////Users/katma/Documents/GitHub/Trilogoy/Homework/sqlalchemy-challenge/Resources/hawaii.sqlite"""'], {}), "(\n 'sqlite:////Users/katma/Documents/GitHub/Trilogoy/Homework/sqlalchemy-challenge/Resources/hawaii.sqlite'\n )\n", (522, 638), False, 'from sqlalchemy import create_engine, func\n'), ((919, 934), 'sqlalchemy.orm.Session', 'Session', (['engine'], {}), '(engine)\n', (926, 934), False, 'from sqlalchemy.orm import Session\n'), ((2017, 2032), 'sqlalchemy.orm.Session', 'Session', (['engine'], {}), '(engine)\n', (2024, 2032), False, 'from sqlalchemy.orm import Session\n'), ((2195, 2238), 'datetime.datetime.strptime', 'dt.datetime.strptime', (['lastpoint', '"""%Y-%m-%d"""'], {}), "(lastpoint, '%Y-%m-%d')\n", (2215, 2238), True, 'import datetime as dt\n'), ((2718, 2739), 'flask.jsonify', 'jsonify', (['fullprcplist'], {}), '(fullprcplist)\n', (2725, 2739), False, 'from flask import Flask, jsonify\n'), ((2919, 2934), 'sqlalchemy.orm.Session', 'Session', (['engine'], {}), '(engine)\n', (2926, 2934), False, 'from sqlalchemy.orm import Session\n'), ((3087, 3104), 'flask.jsonify', 'jsonify', (['stations'], {}), '(stations)\n', (3094, 3104), False, 'from flask import Flask, jsonify\n'), ((3216, 3231), 'sqlalchemy.orm.Session', 'Session', (['engine'], {}), '(engine)\n', (3223, 3231), False, 'from sqlalchemy.orm import Session\n'), ((3432, 3475), 'datetime.datetime.strptime', 'dt.datetime.strptime', (['lastpoint', '"""%Y-%m-%d"""'], {}), "(lastpoint, '%Y-%m-%d')\n", (3452, 3475), True, 'import datetime as dt\n'), ((4626, 4642), 'flask.jsonify', 'jsonify', (['toplist'], {}), '(toplist)\n', (4633, 4642), False, 'from flask import Flask, jsonify\n'), ((4803, 4818), 'sqlalchemy.orm.Session', 'Session', (['engine'], {}), '(engine)\n', (4810, 4818), False, 'from sqlalchemy.orm import Session\n'), ((5231, 5248), 'flask.jsonify', 'jsonify', (['templist'], {}), '(templist)\n', (5238, 5248), False, 'from flask import Flask, jsonify\n'), ((5339, 5354), 'sqlalchemy.orm.Session', 'Session', (['engine'], {}), '(engine)\n', (5346, 5354), False, 'from sqlalchemy.orm import Session\n'), ((5863, 5880), 'flask.jsonify', 'jsonify', (['templist'], {}), '(templist)\n', (5870, 5880), False, 'from flask import Flask, jsonify\n'), ((2328, 2348), 'datetime.date', 'dt.date', (['(2017)', '(8)', '(23)'], {}), '(2017, 8, 23)\n', (2335, 2348), True, 'import datetime as dt\n'), ((3055, 3073), 'numpy.ravel', 'np.ravel', (['stations'], {}), '(stations)\n', (3063, 3073), True, 'import numpy as np\n'), ((3491, 3511), 'datetime.date', 'dt.date', (['(2017)', '(8)', '(23)'], {}), '(2017, 8, 23)\n', (3498, 3511), True, 'import datetime as dt\n'), ((4861, 4887), 'sqlalchemy.func.min', 'func.min', (['measurement.tobs'], {}), '(measurement.tobs)\n', (4869, 4887), False, 'from sqlalchemy import create_engine, func\n'), ((4889, 4915), 'sqlalchemy.func.avg', 'func.avg', (['measurement.tobs'], {}), '(measurement.tobs)\n', (4897, 4915), False, 'from sqlalchemy import create_engine, func\n'), ((4917, 4943), 'sqlalchemy.func.max', 'func.max', (['measurement.tobs'], {}), '(measurement.tobs)\n', (4925, 4943), False, 'from sqlalchemy import create_engine, func\n'), ((3686, 3717), 'sqlalchemy.func.count', 'func.count', (['measurement.station'], {}), '(measurement.station)\n', (3696, 3717), False, 'from sqlalchemy import create_engine, func\n'), ((3614, 3645), 'sqlalchemy.func.count', 'func.count', (['measurement.station'], {}), '(measurement.station)\n', (3624, 3645), False, 'from sqlalchemy import create_engine, func\n'), ((4148, 4174), 'sqlalchemy.func.min', 'func.min', (['measurement.tobs'], {}), '(measurement.tobs)\n', (4156, 4174), False, 'from sqlalchemy import create_engine, func\n'), ((4175, 4201), 'sqlalchemy.func.avg', 'func.avg', (['measurement.tobs'], {}), '(measurement.tobs)\n', (4183, 4201), False, 'from sqlalchemy import create_engine, func\n'), ((4202, 4228), 'sqlalchemy.func.max', 'func.max', (['measurement.tobs'], {}), '(measurement.tobs)\n', (4210, 4228), False, 'from sqlalchemy import create_engine, func\n'), ((5388, 5414), 'sqlalchemy.func.min', 'func.min', (['measurement.tobs'], {}), '(measurement.tobs)\n', (5396, 5414), False, 'from sqlalchemy import create_engine, func\n'), ((5416, 5442), 'sqlalchemy.func.avg', 'func.avg', (['measurement.tobs'], {}), '(measurement.tobs)\n', (5424, 5442), False, 'from sqlalchemy import create_engine, func\n'), ((5444, 5470), 'sqlalchemy.func.max', 'func.max', (['measurement.tobs'], {}), '(measurement.tobs)\n', (5452, 5470), False, 'from sqlalchemy import create_engine, func\n')]
import librosa import numpy as np import math def ratio_to_cents(r): return 1200.0 * np.log2(r) def ratio_to_cents_protected(f1, f2): out = np.zeros_like(f1) key = (f1!=0.0) * (f2!=0.0) out[key] = 1200.0 * np.log2(f1[key]/f2[key]) out[f1==0.0] = -np.inf out[f2==0.0] = np.inf out[(f1==0.0) * (f2==0.0)] = 0.0 return out def cents_to_ratio(c): return np.power(2, c/1200.0) def freq_to_midi(f): return 69.0 + 12.0 * np.log2(f/440.0) def midi_to_freq(m): return np.power(2, (m-69.0)/12.0) * 440.0 if m!= 0.0 else 0.0 def bin_to_freq(b, sr, n_fft): return b * float(sr) / float(n_fft) def freq_to_bin(f, sr, n_fft): return np.round(f/(float(sr)/float(n_fft))).astype('int') def ppitch(y, sr=44100, n_fft=8820, win_length=1024, hop_length=2048, num_peaks=20, num_pitches=3, min_peak=2, max_peak=743, min_fund=55.0, max_fund=1000.0, harm_offset=0, harm_rolloff=0.75, ml_width=25, bounce_width=0, bounce_hist=0, bounce_ratios=None, max_harm=32767, npartial=7): # other params will go here with update (sept 2018) # go to time-freq if_gram, D = librosa.core.ifgram(y, sr=sr, n_fft=n_fft, win_length=win_length,hop_length=hop_length) peak_thresh = 1e-3 min_bin = 2 max_bin = freq_to_bin(float(max_peak), sr, n_fft) if npartial is not None: harm_rolloff = math.log(2, float(npartial)) num_bins, num_frames = if_gram.shape pitches = np.zeros([num_frames, num_pitches]) peaks = np.zeros([num_frames, num_peaks]) fundamentals = np.zeros([num_frames, num_pitches]) confidences = np.zeros([num_frames, num_pitches]) for i in range(num_frames): frqs = if_gram[:,i] mags = np.abs(D[:,i]) total_power = mags.sum() max_amp = np.max(mags) lower = mags[(min_bin-1):(max_bin)] middle = mags[(min_bin) :(max_bin+1)] upper = mags[(min_bin+1):(max_bin+2)] peaks_mask_all = (middle > lower) & (middle > upper) zeros_left = np.zeros(min_bin) zeros_right = np.zeros(num_bins - min_bin - max_bin + 1) peaks_mask_all = np.concatenate((zeros_left, peaks_mask_all, zeros_right)) peaks_mags_all = peaks_mask_all * mags top20 = np.argsort(peaks_mags_all)[::-1][0:num_peaks] peaks_frqs = frqs[top20] peaks_mags = mags[top20] num_peaks_found = top20.shape[0] min_freq = float(min_fund) max_freq = float(max_fund) def b2f(index): return min_freq * np.power(np.power(2, 1.0/48.0), index) max_histo_bin = int(math.log(max_freq / min_freq, math.pow(2, 1.0/48.0))) histo = np.fromfunction(lambda x,y: b2f(y), (num_peaks_found, max_histo_bin)) frqs_tile = np.tile(peaks_frqs, (max_histo_bin,1)).transpose() mags_tile = np.tile(peaks_mags, (max_histo_bin,1)).transpose() def ml_a(amp): return np.sqrt(np.sqrt(amp/max_amp)) def ml_t(r1, r2): max_dist = ml_width cents = np.abs(ratio_to_cents_protected(r1,r2)) dist = np.clip(1.0 - (cents / max_dist), 0, 1) return dist def ml_i(nearest_multiple): out = np.zeros_like(nearest_multiple) out[nearest_multiple.nonzero()] = 1/np.power(nearest_multiple[nearest_multiple.nonzero()], harm_rolloff) return out ml = (ml_a(mags_tile) * \ ml_t((frqs_tile/histo), (frqs_tile/histo).round()) * \ ml_i((frqs_tile/histo).round())).sum(axis=0) num_found = 0 maybe = 0 found_so_far = [] bounce_list = list(np.ravel(pitches[i-bounce_hist:i])) bounce_ratios = [1.0, 2.0, 3.0/2.0, 3.0, 4.0] if bounce_ratios is None else bounce_ratios prev_frame = list(pitches[i-1]) if i>0 else [] indices = ml.argsort()[::-1] while num_found < num_pitches and maybe <= ml.shape[0]: this_one = b2f(indices[maybe]) bounce1 = any([any([abs(ratio_to_cents( this_one/(other_one*harm))) < bounce_width for harm in bounce_ratios]) for other_one in bounce_list]) bounce2 = any([any([abs(ratio_to_cents (other_one/(this_one*harm))) < bounce_width for harm in bounce_ratios]) for other_one in bounce_list]) bounce = bounce1 or bounce2 if not bounce: found_so_far += [this_one] bounce_list += [this_one] num_found += 1 maybe += 1 indices = ml.argsort()[::-1][0:num_pitches] pitches[i] = np.array(found_so_far) confidences[i] = ml[indices] peaks[i] = peaks_frqs ml_peaks = pitches[i] width = 25 frame_fundamentals = [] for bin_frq in ml_peaks: nearest_harmonic = (peaks_frqs/bin_frq).round() mask = np.abs(ratio_to_cents_protected( (peaks_frqs/bin_frq), (peaks_frqs/bin_frq).round())) <= width weights = ml_i( (peaks_frqs/bin_frq).round() ) A = np.matrix(nearest_harmonic).T b = np.matrix(peaks_frqs).T W = np.matrix(np.diag(mask * weights)) fund = np.linalg.lstsq(W*A, W*b)[0][0].item() frame_fundamentals += [fund] fundamentals[i] = np.array(frame_fundamentals) tracks = np.copy(pitches) return fundamentals, pitches, D, peaks, confidences, tracks # error at this point def voice_tracks(pitches, confidences): out = np.zeros_like(pitches) out[0] = pitches[0] out_confidences = np.zeros_like(confidences) out_confidences[0] = confidences[0] num_frames, num_voices = pitches.shape for i in range(1,num_frames): prev_frame = out[i-1] next_frame = pitches[i] delta = np.abs(ratio_to_cents(np.atleast_2d(prev_frame).T/np.repeat( np.atleast_2d(next_frame),num_voices,axis=0))) delta_sorted = np.unravel_index(np.argsort(delta.ravel()), delta.shape) num_found = 0; found_prevs = []; found_nexts = []; index = 0 while num_found < num_voices: prev_voice,next_voice = delta_sorted[0][index], delta_sorted[1][index] if prev_voice not in found_prevs and next_voice not in found_nexts: out[i][prev_voice] = pitches[i][next_voice] out_confidences[i][prev_voice] = confidences[i][next_voice] found_prevs += [prev_voice] found_nexts += [next_voice] num_found += 1 index += 1 return out, out_confidences def pitchsets(pitches, win=3): pitches_change = change_filter(pitches) pitches_sustain = sustain_filter(pitches_change, win=win) pitchsets = np.sort(np.array(list(set(np.argwhere(np.nan_to_num(pitches_sustain))[:,0])))) return pitchsets, np.where(np.nan_to_num(pitches_sustain)) def change_filter(pitches): wpitches = np.copy(pitches) out = np.zeros_like(wpitches) out[out==0] = np.nan wpitches = freq_to_midi(wpitches).round() indices = np.diff(wpitches, axis=0).nonzero() out[0] = pitches[0] out[1:][indices] = pitches[1:][indices] return out def sustain_filter(pitches, win=3): out = np.zeros_like(pitches) for i in range(pitches.shape[0]-win): for j in range(pitches.shape[1]): out[i,j] = pitches[i,j] * np.isnan(pitches[i+1:i+win,j]).all() out[out==0] = np.nan return out def pitch_onsets(funds, win=2, depth=25): onsets = np.zeros_like(funds) for i in range(funds.shape[0]): for j in range(funds.shape[1]): onsets[i,j] = (np.abs(pyfid.ratio_to_cents(funds[i-win:i,:] / funds[i,j])) <= thresh).any(axis=1).all() return onsets
[ "numpy.abs", "numpy.nan_to_num", "numpy.ravel", "numpy.clip", "numpy.isnan", "numpy.argsort", "librosa.core.ifgram", "numpy.tile", "numpy.diag", "numpy.atleast_2d", "numpy.zeros_like", "numpy.copy", "math.pow", "numpy.power", "numpy.max", "numpy.log2", "numpy.concatenate", "numpy.m...
[((149, 166), 'numpy.zeros_like', 'np.zeros_like', (['f1'], {}), '(f1)\n', (162, 166), True, 'import numpy as np\n'), ((375, 398), 'numpy.power', 'np.power', (['(2)', '(c / 1200.0)'], {}), '(2, c / 1200.0)\n', (383, 398), True, 'import numpy as np\n'), ((1098, 1190), 'librosa.core.ifgram', 'librosa.core.ifgram', (['y'], {'sr': 'sr', 'n_fft': 'n_fft', 'win_length': 'win_length', 'hop_length': 'hop_length'}), '(y, sr=sr, n_fft=n_fft, win_length=win_length,\n hop_length=hop_length)\n', (1117, 1190), False, 'import librosa\n'), ((1410, 1445), 'numpy.zeros', 'np.zeros', (['[num_frames, num_pitches]'], {}), '([num_frames, num_pitches])\n', (1418, 1445), True, 'import numpy as np\n'), ((1463, 1496), 'numpy.zeros', 'np.zeros', (['[num_frames, num_peaks]'], {}), '([num_frames, num_peaks])\n', (1471, 1496), True, 'import numpy as np\n'), ((1525, 1560), 'numpy.zeros', 'np.zeros', (['[num_frames, num_pitches]'], {}), '([num_frames, num_pitches])\n', (1533, 1560), True, 'import numpy as np\n'), ((1579, 1614), 'numpy.zeros', 'np.zeros', (['[num_frames, num_pitches]'], {}), '([num_frames, num_pitches])\n', (1587, 1614), True, 'import numpy as np\n'), ((5000, 5016), 'numpy.copy', 'np.copy', (['pitches'], {}), '(pitches)\n', (5007, 5016), True, 'import numpy as np\n'), ((5155, 5177), 'numpy.zeros_like', 'np.zeros_like', (['pitches'], {}), '(pitches)\n', (5168, 5177), True, 'import numpy as np\n'), ((5221, 5247), 'numpy.zeros_like', 'np.zeros_like', (['confidences'], {}), '(confidences)\n', (5234, 5247), True, 'import numpy as np\n'), ((6475, 6491), 'numpy.copy', 'np.copy', (['pitches'], {}), '(pitches)\n', (6482, 6491), True, 'import numpy as np\n'), ((6501, 6524), 'numpy.zeros_like', 'np.zeros_like', (['wpitches'], {}), '(wpitches)\n', (6514, 6524), True, 'import numpy as np\n'), ((6770, 6792), 'numpy.zeros_like', 'np.zeros_like', (['pitches'], {}), '(pitches)\n', (6783, 6792), True, 'import numpy as np\n'), ((7042, 7062), 'numpy.zeros_like', 'np.zeros_like', (['funds'], {}), '(funds)\n', (7055, 7062), True, 'import numpy as np\n'), ((89, 99), 'numpy.log2', 'np.log2', (['r'], {}), '(r)\n', (96, 99), True, 'import numpy as np\n'), ((219, 245), 'numpy.log2', 'np.log2', (['(f1[key] / f2[key])'], {}), '(f1[key] / f2[key])\n', (226, 245), True, 'import numpy as np\n'), ((1685, 1700), 'numpy.abs', 'np.abs', (['D[:, i]'], {}), '(D[:, i])\n', (1691, 1700), True, 'import numpy as np\n'), ((1743, 1755), 'numpy.max', 'np.max', (['mags'], {}), '(mags)\n', (1749, 1755), True, 'import numpy as np\n'), ((1960, 1977), 'numpy.zeros', 'np.zeros', (['min_bin'], {}), '(min_bin)\n', (1968, 1977), True, 'import numpy as np\n'), ((1996, 2038), 'numpy.zeros', 'np.zeros', (['(num_bins - min_bin - max_bin + 1)'], {}), '(num_bins - min_bin - max_bin + 1)\n', (2004, 2038), True, 'import numpy as np\n'), ((2060, 2117), 'numpy.concatenate', 'np.concatenate', (['(zeros_left, peaks_mask_all, zeros_right)'], {}), '((zeros_left, peaks_mask_all, zeros_right))\n', (2074, 2117), True, 'import numpy as np\n'), ((4316, 4338), 'numpy.array', 'np.array', (['found_so_far'], {}), '(found_so_far)\n', (4324, 4338), True, 'import numpy as np\n'), ((4959, 4987), 'numpy.array', 'np.array', (['frame_fundamentals'], {}), '(frame_fundamentals)\n', (4967, 4987), True, 'import numpy as np\n'), ((443, 461), 'numpy.log2', 'np.log2', (['(f / 440.0)'], {}), '(f / 440.0)\n', (450, 461), True, 'import numpy as np\n'), ((492, 522), 'numpy.power', 'np.power', (['(2)', '((m - 69.0) / 12.0)'], {}), '(2, (m - 69.0) / 12.0)\n', (500, 522), True, 'import numpy as np\n'), ((2940, 2977), 'numpy.clip', 'np.clip', (['(1.0 - cents / max_dist)', '(0)', '(1)'], {}), '(1.0 - cents / max_dist, 0, 1)\n', (2947, 2977), True, 'import numpy as np\n'), ((3045, 3076), 'numpy.zeros_like', 'np.zeros_like', (['nearest_multiple'], {}), '(nearest_multiple)\n', (3058, 3076), True, 'import numpy as np\n'), ((3427, 3463), 'numpy.ravel', 'np.ravel', (['pitches[i - bounce_hist:i]'], {}), '(pitches[i - bounce_hist:i])\n', (3435, 3463), True, 'import numpy as np\n'), ((6398, 6428), 'numpy.nan_to_num', 'np.nan_to_num', (['pitches_sustain'], {}), '(pitches_sustain)\n', (6411, 6428), True, 'import numpy as np\n'), ((6607, 6632), 'numpy.diff', 'np.diff', (['wpitches'], {'axis': '(0)'}), '(wpitches, axis=0)\n', (6614, 6632), True, 'import numpy as np\n'), ((2175, 2201), 'numpy.argsort', 'np.argsort', (['peaks_mags_all'], {}), '(peaks_mags_all)\n', (2185, 2201), True, 'import numpy as np\n'), ((2514, 2537), 'math.pow', 'math.pow', (['(2)', '(1.0 / 48.0)'], {}), '(2, 1.0 / 48.0)\n', (2522, 2537), False, 'import math\n'), ((2641, 2680), 'numpy.tile', 'np.tile', (['peaks_frqs', '(max_histo_bin, 1)'], {}), '(peaks_frqs, (max_histo_bin, 1))\n', (2648, 2680), True, 'import numpy as np\n'), ((2708, 2747), 'numpy.tile', 'np.tile', (['peaks_mags', '(max_histo_bin, 1)'], {}), '(peaks_mags, (max_histo_bin, 1))\n', (2715, 2747), True, 'import numpy as np\n'), ((2801, 2823), 'numpy.sqrt', 'np.sqrt', (['(amp / max_amp)'], {}), '(amp / max_amp)\n', (2808, 2823), True, 'import numpy as np\n'), ((4738, 4765), 'numpy.matrix', 'np.matrix', (['nearest_harmonic'], {}), '(nearest_harmonic)\n', (4747, 4765), True, 'import numpy as np\n'), ((4778, 4799), 'numpy.matrix', 'np.matrix', (['peaks_frqs'], {}), '(peaks_frqs)\n', (4787, 4799), True, 'import numpy as np\n'), ((4822, 4845), 'numpy.diag', 'np.diag', (['(mask * weights)'], {}), '(mask * weights)\n', (4829, 4845), True, 'import numpy as np\n'), ((2429, 2452), 'numpy.power', 'np.power', (['(2)', '(1.0 / 48.0)'], {}), '(2, 1.0 / 48.0)\n', (2437, 2452), True, 'import numpy as np\n'), ((5451, 5476), 'numpy.atleast_2d', 'np.atleast_2d', (['prev_frame'], {}), '(prev_frame)\n', (5464, 5476), True, 'import numpy as np\n'), ((5496, 5521), 'numpy.atleast_2d', 'np.atleast_2d', (['next_frame'], {}), '(next_frame)\n', (5509, 5521), True, 'import numpy as np\n'), ((6907, 6942), 'numpy.isnan', 'np.isnan', (['pitches[i + 1:i + win, j]'], {}), '(pitches[i + 1:i + win, j])\n', (6915, 6942), True, 'import numpy as np\n'), ((4861, 4890), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['(W * A)', '(W * b)'], {}), '(W * A, W * b)\n', (4876, 4890), True, 'import numpy as np\n'), ((6325, 6355), 'numpy.nan_to_num', 'np.nan_to_num', (['pitches_sustain'], {}), '(pitches_sustain)\n', (6338, 6355), True, 'import numpy as np\n')]
import base64 import io import cv2 import numpy as np from PIL import Image def rawtoPILImg(raw_img): assert raw_img is not None image = Image.open(io.BytesIO(raw_img)) return image def rawtoOCVImg(raw_img): assert raw_img is not None im_arr = np.frombuffer(raw_img, dtype=np.uint8) # im_arr is one-dim Numpy array img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR) return img def b64toOCVImg(base64_img): picture_raw = base64.b64decode(base64_img) return rawtoOCVImg(picture_raw) # im_arr = np.frombuffer(picture_raw, dtype=np.uint8) # im_arr is one-dim Numpy array # img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR) # return img def b64toPILImg(base64_img): picture_raw = base64.b64decode(base64_img) return rawtoPILImg(picture_raw) # image = Image.open(io.BytesIO(picture_raw)) # return image def save_ocv_image(image, image_path): print(image_path) cv2.imwrite(image_path, image) def resize(orig_img, w, h): return cv2.resize(orig_img, (w, h), interpolation = cv2.INTER_AREA)
[ "io.BytesIO", "numpy.frombuffer", "cv2.imwrite", "cv2.imdecode", "base64.b64decode", "cv2.resize" ]
[((268, 306), 'numpy.frombuffer', 'np.frombuffer', (['raw_img'], {'dtype': 'np.uint8'}), '(raw_img, dtype=np.uint8)\n', (281, 306), True, 'import numpy as np\n'), ((350, 394), 'cv2.imdecode', 'cv2.imdecode', (['im_arr'], {'flags': 'cv2.IMREAD_COLOR'}), '(im_arr, flags=cv2.IMREAD_COLOR)\n', (362, 394), False, 'import cv2\n'), ((458, 486), 'base64.b64decode', 'base64.b64decode', (['base64_img'], {}), '(base64_img)\n', (474, 486), False, 'import base64\n'), ((736, 764), 'base64.b64decode', 'base64.b64decode', (['base64_img'], {}), '(base64_img)\n', (752, 764), False, 'import base64\n'), ((936, 966), 'cv2.imwrite', 'cv2.imwrite', (['image_path', 'image'], {}), '(image_path, image)\n', (947, 966), False, 'import cv2\n'), ((1007, 1065), 'cv2.resize', 'cv2.resize', (['orig_img', '(w, h)'], {'interpolation': 'cv2.INTER_AREA'}), '(orig_img, (w, h), interpolation=cv2.INTER_AREA)\n', (1017, 1065), False, 'import cv2\n'), ((159, 178), 'io.BytesIO', 'io.BytesIO', (['raw_img'], {}), '(raw_img)\n', (169, 178), False, 'import io\n')]
import os import math import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from utils import tfwatcher from utils.tf_metric_loss import masked_minimum, masked_maximum, triplet_semihard_loss, npairs_loss, lifted_struct_loss # @tf.custom_gradient # def pseudo_loss(x, grad): # def pseudo_grad(dy): # return grad, None # return tf.constant(0.), pseudo_grad def pair_shuffle(x): num_features = x.shape[1].value x = tf.reshape(x, [-1, 2, num_features]) x1, x2 = x[:,0], x[:,1] select = tf.random_uniform(tf.shape(x1)) >= 0.5 x1_new = tf.where(select, x1, x2) x2_new = tf.where(select, x2, x1) x_new = tf.reshape(tf.stack([x1_new, x2_new], axis=1), [-1, num_features]) return x_new def group_shuffle(x, groups=4): num_features = x.shape[1].value input_splits = tf.split(x, groups, axis=0) x = tf.reshape(x, [-1, 2, num_features]) x1, x2 = x[:,0], x[:,1] select = tf.random_uniform(tf.shape(x1)) >= 0.5 x1_new = tf.where(select, x1, x2) x2_new = tf.where(select, x2, x1) x_new = tf.reshape(tf.stack([x1_new, x2_new], axis=1), [-1, num_features]) return x_new def group_normalize(x, groups, name=None): import math num_features = x.shape[1].value assert num_features % groups == 0 gdim = int(num_features / groups) x_normed = tf.nn.l2_normalize(tf.reshape(x, [-1, groups, gdim]), dim=2) x_normed = tf.reshape(x_normed, [-1, num_features], name=name) return x_normed def batch_norm(x, center=True, scale=True, name=None): batch_norm_params = { 'decay': 0.995, 'epsilon': 1e-8, 'center': center, 'scale': scale, 'updates_collections': None, 'variables_collections': [ tf.GraphKeys.TRAINABLE_VARIABLES ], 'param_initializers': {'gamma': tf.constant_initializer(0.1)}, } x_normed = slim.batch_norm(x, **batch_norm_params) return tf.identity(x_normed, name=name) def normalize_embeddings(features, normalization, name=None): if normalization == 'l2': return tf.nn.l2_normalize(features, dim=1, name=name) if normalization == 'batch': return batch_norm(features, name=name) elif normalization == 'std_batch': return batch_norm(features, False, False, name) elif normalization == 'scale_batch': return batch_norm(features, False, True, name) elif normalization.startswith('grpl2'): gdim = normalization.split(':')[1] gdim = int(grp_size) return group_normalize(x, gdim, name) else: raise ValueError('Unkown normalization for embeddings: {}'.format(normalization)) def euclidean_distance(X, Y, sqrt=False): '''Compute the distance between each X and Y. Args: X: a (m x d) tensor Y: a (d x n) tensor Returns: diffs: an m x n distance matrix. ''' with tf.name_scope('EuclideanDistance'): XX = tf.reduce_sum(tf.square(X), 1, keep_dims=True) YY = tf.reduce_sum(tf.square(Y), 0, keep_dims=True) XY = tf.matmul(X, Y) diffs = XX + YY - 2*XY diffs = tf.maximum(0.0, diffs) if sqrt == True: diffs = tf.sqrt(diffs) return diffs def mahalanobis_distance(X, Y, sigma_sq_inv, sqrt=False): '''Compute the distance between each X and Y. Args: X: a (m x d) tensor Y: a (d x n) tensor sigma_sq: a (m, d) tensor Returns: diffs: an m x n distance matrix. ''' with tf.name_scope('MahalanobisDistance'): XX = tf.reduce_sum(tf.square(X) * sigma_sq_inv, 1, keep_dims=True) YY = tf.matmul(sigma_sq_inv, tf.square(Y)) XY = tf.matmul(X * sigma_sq_inv, Y) diffs = XX + YY - 2*XY if sqrt == True: diffs = tf.sqrt(tf.maximum(0.0, diffs)) return diffs def uncertain_distance(X, Y, sigma_sq_X, sigma_sq_Y, mean=False): with tf.name_scope('UncertainDistance'): if mean: D = X.shape[1].value Y = tf.transpose(Y) XX = tf.reduce_sum(tf.square(X), 1, keep_dims=True) YY = tf.reduce_sum(tf.square(Y), 0, keep_dims=True) XY = tf.matmul(X, Y) diffs = XX + YY - 2*XY sigma_sq_Y = tf.transpose(sigma_sq_Y) sigma_sq_X = tf.reduce_mean(sigma_sq_X, axis=1, keep_dims=True) sigma_sq_Y = tf.reduce_mean(sigma_sq_Y, axis=0, keep_dims=True) sigma_sq_fuse = sigma_sq_X + sigma_sq_Y diffs = diffs / (1e-8 + sigma_sq_fuse) + D * tf.log(sigma_sq_fuse) return diffs else: D = X.shape[1].value X = tf.reshape(X, [-1, 1, D]) Y = tf.reshape(Y, [1, -1, D]) sigma_sq_X = tf.reshape(sigma_sq_X, [-1, 1, D]) sigma_sq_Y = tf.reshape(sigma_sq_Y, [1, -1, D]) sigma_sq_fuse = sigma_sq_X + sigma_sq_Y diffs = tf.square(X-Y) / (1e-10 + sigma_sq_fuse) + tf.log(sigma_sq_fuse) return tf.reduce_sum(diffs, axis=2) def softmax_loss(prelogits, label, num_classes, weight_decay, scope='SoftmaxLoss', reuse=None): num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope(scope, reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, num_features), regularizer=slim.l2_regularizer(weight_decay), initializer=slim.xavier_initializer(uniform=False), trainable = True, dtype=tf.float32) biases = tf.get_variable('biases', shape=(1, num_classes), initializer=tf.constant_initializer(0.), trainable = False, dtype=tf.float32) if False: bn_params = { 'decay': 0.995, 'epsilon': 1e-8, 'center': True, 'scale': True, 'trainable': True, 'is_training': True, 'param_initializers': {'gamma': tf.constant_initializer(0.01)}, } with slim.arg_scope([slim.fully_connected], normalizer_fn=None):#slim.batch_norm): weights = slim.fully_connected(weights, num_features+1, activation_fn=None, scope='fc1') # weights = slim.fully_connected(weights, num_features, activation_fn=None, # normalizer_fn=None, scope='fc2') weights, biases = weights[:,:num_features], tf.transpose(weights[:,num_features:]) # Shuffle!!! prelogits = pair_shuffle(prelogits) logits = tf.matmul(prelogits, tf.transpose(weights)) + biases # logits = - euclidean_distance(prelogits, tf.transpose(weights)) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\ labels=label, logits=logits), name='loss') if False and weights not in tf.trainable_variables(): alpha = 0.01 # Update centers unique_label, unique_idx, unique_count = tf.unique_with_counts(label) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = tf.gather(weights, label) diff_centers = diff_centers / tf.cast(appear_times, tf.float32) diff_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(weights, label, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) return loss def softmax_loss2(prelogits, label, num_classes, weight_decay, scope='SoftmaxLoss', return_logits =False, reuse=None): num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope(scope, reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, num_features), regularizer=slim.l2_regularizer(weight_decay), initializer=slim.xavier_initializer(), trainable = True, dtype=tf.float32) biases = tf.get_variable('biases', shape=(1, num_classes), initializer=tf.constant_initializer(0.), trainable = True, dtype=tf.float32) logits = tf.matmul(prelogits, tf.transpose(weights)) + biases # logits = euclidean_distance(prelogits, tf.transpose(weights)) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\ labels=label, logits=logits), name='loss') if weights not in tf.trainable_variables(): alpha = 0.01 # Update centers unique_label, unique_idx, unique_count = tf.unique_with_counts(label) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = tf.gather(weights, label) diff_centers = diff_centers / tf.cast(appear_times, tf.float32) diff_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(weights, label, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) if not return_logits: return loss else: return loss, logits '''def center_loss(features, labels, num_classes, alpha=0.5, coef=0.05, scope='CenterLoss', reuse=None): num_features = features.shape[1].value batch_size = tf.shape(features)[0] with tf.variable_scope(scope, reuse=reuse): centers = tf.get_variable('centers', shape=(num_classes, num_features), # initializer=slim.xavier_initializer(), initializer=tf.truncated_normal_initializer(stddev=0.1), trainable=False, collections=[tf.GraphKeys.GLOBAL_VARIABLES, tf.GraphKeys.TRAINABLE_VARIABLES], dtype=tf.float32) centers_batch = tf.gather(centers, labels) diff_centers = centers_batch - features loss = coef * 0.5 * tf.reduce_mean(tf.reduce_sum(tf.square(diff_centers), axis=1), name='center_loss') # Update centers unique_label, unique_idx, unique_count = tf.unique_with_counts(labels) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = diff_centers / tf.cast(appear_times, tf.float32) diff_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(centers, labels, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) return loss''' def center_loss(features, labels, num_classes, alpha=0.5, coef=0.05, scope='CenterLoss', reuse=None): num_features = features.shape[1].value batch_size = tf.shape(features)[0] with tf.variable_scope(scope, reuse=reuse): centers = tf.get_variable('centers', shape=(num_classes, num_features), # initializer=slim.xavier_initializer(), initializer=tf.truncated_normal_initializer(stddev=0.1), trainable=False, collections=[tf.GraphKeys.GLOBAL_VARIABLES, tf.GraphKeys.TRAINABLE_VARIABLES], dtype=tf.float32) centers_batch = tf.gather(centers, labels) diff_centers = centers_batch - features loss = coef * 0.5 * tf.reduce_mean(tf.reduce_sum(tf.square(diff_centers), axis=1), name='center_loss') # Update centers unique_label, unique_idx, unique_count = tf.unique_with_counts(labels) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = diff_centers / tf.cast(appear_times, tf.float32) diff_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(centers, labels, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) return loss def ring_loss(features, coef=0.01, scope='RingLoss', reuse=None): num_features = features.shape[1].value batch_size = tf.shape(features)[0] with tf.variable_scope(scope, reuse=reuse): R = tf.get_variable('R', shape=(), initializer=tf.constant_initializer(1.0), trainable=True, dtype=tf.float32) # use averaging norm instead R = tf.reduce_mean(tf.norm(features, axis=1)) loss = coef * 0.5 * tf.reduce_mean(tf.square(tf.norm(features, axis=1) - R), name='ring_loss') return loss def decov_loss(features, coef=0.01, scope='DecovLoss'): num_features = features.shape[1].value batch_size = tf.shape(features)[0] with tf.variable_scope(scope): cov = tf.square(tf.matmul(tf.transpose(features), features)) nondiag = tf.logical_not(tf.eye(batch_size, dtype=tf.bool)) loss = coef * tf.reduce_mean(tf.boolean_mask(cov,nondiag), name='decov_loss') return loss def cosine_softmax(prelogits, label, num_classes, weight_decay, gamma=16.0, reuse=None): nrof_features = prelogits.shape[1].value with tf.variable_scope('Logits', reuse=reuse): weights = tf.get_variable('weights', shape=(nrof_features, num_classes), regularizer=slim.l2_regularizer(weight_decay), initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.1), dtype=tf.float32) alpha = tf.get_variable('alpha', shape=(), regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(1.00), trainable=True, dtype=tf.float32) weights_normed = tf.nn.l2_normalize(weights, dim=0) prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1) if gamma == 'auto': gamma = tf.nn.softplus(alpha) else: assert type(gamma) == float gamma = tf.constant(gamma) logits = gamma * tf.matmul(prelogits_normed, weights_normed) cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\ labels=label, logits=logits), name='cross_entropy') tf.summary.scalar('gamma', gamma) tf.add_to_collection('watch_list', ('gamma', gamma)) return logits, cross_entropy def norm_loss(prelogits, alpha, reuse=None): with tf.variable_scope('NormLoss', reuse=reuse): sigma = tf.get_variable('sigma', shape=(), # regularizer=slim.l2_regularizer(weight_decay), initializer=tf.constant_initializer(0.1), trainable=True, dtype=tf.float32) prelogits_norm = tf.reduce_sum(tf.square(prelogits), axis=1) # norm_loss = alpha * tf.square(tf.sqrt(prelogits_norm) - sigma) norm_loss = alpha * prelogits_norm norm_loss = tf.reduce_mean(norm_loss, axis=0, name='norm_loss') # tf.summary.scalar('sigma', sigma) # tf.add_to_collection('watch_list', ('sigma', sigma)) return norm_loss def angular_softmax(prelogits, label, num_classes, global_step, m, lamb_min, lamb_max, weight_decay, reuse=None): num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] lamb_min = lamb_min lamb_max = lamb_max lambda_m_theta = [ lambda x: x**0, lambda x: x**1, lambda x: 2.0*(x**2) - 1.0, lambda x: 4.0*(x**3) - 3.0*x, lambda x: 8.0*(x**4) - 8.0*(x**2) + 1.0, lambda x: 16.0*(x**5) - 20.0*(x**3) + 5.0*x ] with tf.variable_scope('AngularSoftmax', reuse=reuse): weights = tf.get_variable('weights', shape=(num_features, num_classes), regularizer=slim.l2_regularizer(1e-4), initializer=slim.xavier_initializer(uniform=False), # initializer=tf.random_normal_initializer(stddev=0.01), trainable=True, dtype=tf.float32) lamb = tf.get_variable('lambda', shape=(), initializer=tf.constant_initializer(lamb_max), trainable=False, dtype=tf.float32) prelogits_norm = tf.sqrt(tf.reduce_sum(tf.square(prelogits), axis=1, keep_dims=True)) weights_normed = tf.nn.l2_normalize(weights, dim=0) prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1) # Compute cosine and phi cos_theta = tf.matmul(prelogits_normed, weights_normed) cos_theta = tf.minimum(1.0, tf.maximum(-1.0, cos_theta)) theta = tf.acos(cos_theta) cos_m_theta = lambda_m_theta[m](cos_theta) k = tf.floor(m*theta / 3.14159265) phi_theta = tf.pow(-1.0, k) * cos_m_theta - 2.0 * k cos_theta = cos_theta * prelogits_norm phi_theta = phi_theta * prelogits_norm lamb_new = tf.maximum(lamb_min, lamb_max/(1.0+0.1*tf.cast(global_step, tf.float32))) update_lamb = tf.assign(lamb, lamb_new) # Compute loss with tf.control_dependencies([update_lamb]): label_dense = tf.one_hot(label, num_classes, dtype=tf.float32) logits = cos_theta logits -= label_dense * cos_theta * 1.0 / (1.0+lamb) logits += label_dense * phi_theta * 1.0 / (1.0+lamb) cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\ labels=label, logits=logits), name='cross_entropy') tf.add_to_collection('watch_list', ('lamb', lamb)) return cross_entropy def am_softmax(prelogits, label, num_classes, global_step, weight_decay, scale=16.0, m=1.0, alpha=None, reduce_mean=True, scope='AM-Softmax', reuse=None): ''' Tensorflow implementation of AM-Sofmax, proposed in: <NAME>, <NAME>, <NAME>, and <NAME>. Additive margin softmax for face verification. arXiv:1801.05599, 2018. ''' num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope(scope, reuse=reuse): weights = tf.get_variable('weights', shape=(num_features, num_classes), regularizer=slim.l2_regularizer(weight_decay), # initializer=slim.xavier_initializer(), initializer=tf.random_normal_initializer(stddev=0.01), trainable=True, dtype=tf.float32) _scale = tf.get_variable('scale', shape=(), regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(1.00), trainable=True, dtype=tf.float32) tf.add_to_collection('classifier_weights', weights) # Normalizing the vecotors weights_normed = tf.nn.l2_normalize(weights, dim=0) prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1) # prelogits_normed = prelogits # Label and logits between batch and examplars label_mat = tf.one_hot(label, num_classes, dtype=tf.float32) label_mask_pos = tf.cast(label_mat, tf.bool) label_mask_neg = tf.logical_not(label_mask_pos) dist_mat = tf.matmul(prelogits_normed, weights_normed) logits_pos = tf.boolean_mask(dist_mat, label_mask_pos) logits_neg = tf.boolean_mask(dist_mat, label_mask_neg) if scale == 'auto': # Automatic learned scale scale = tf.log(tf.exp(1.0) + tf.exp(_scale)) else: # Assigned scale value assert type(scale) == float scale = tf.constant(scale) # Losses _logits_pos = tf.reshape(logits_pos, [batch_size, -1]) _logits_neg = tf.reshape(logits_neg, [batch_size, -1]) _logits_pos = _logits_pos * scale _logits_neg = _logits_neg * scale _logits_neg = tf.reduce_logsumexp(_logits_neg, axis=1)[:,None] loss = tf.nn.relu(m + _logits_neg - _logits_pos) if reduce_mean: loss = tf.reduce_mean(loss, name='am_softmax') # Analysis tfwatcher.insert('scale', scale) return loss def adacos(embedding, label, num_classes, s='auto'): # Squeezing is necessary for Keras. It expands the dimension to (n, 1) label = tf.reshape(label, [-1]) num_features = embedding.shape[1].value with tf.variable_scope('adacos_loss'): w = tf.get_variable(name='weights', shape=(num_features, num_classes), initializer=tf.random_normal_initializer(0.01), trainable=True, dtype=tf.float32) if s == 'auto': s_init = math.sqrt(2) * math.log(num_classes - 1) _s = tf.get_variable('s_', shape=(), aggregation=tf.VariableAggregation.MEAN, initializer=tf.constant_initializer(s_init), trainable=False, dtype=tf.float32) # s = tf.log(tf.exp(0.0) + tf.exp(s_)) # Normalize features and weights and compute dot product x = tf.nn.l2_normalize(embedding, axis=1) w = tf.nn.l2_normalize(w, axis=0) logits = tf.matmul(x, w) theta = tf.math.acos( tf.clip_by_value(logits, -1.0 + tf.keras.backend.epsilon(), 1.0 - tf.keras.backend.epsilon())) one_hot = tf.one_hot(label, depth=num_classes) b_avg = tf.where(one_hot < 1.0, tf.exp(_s * logits), tf.zeros_like(logits)) b_avg = tf.reduce_mean(tf.reduce_sum(b_avg, axis=1)) theta_class = tf.gather_nd( theta, tf.stack([ tf.range(tf.shape(label)[0]), tf.cast(label, tf.int32) ], axis=1)) mid_index = tf.shape(theta_class)[0] // 2 + 1 theta_med = tf.nn.top_k(theta_class, mid_index).values[-1] # Since _s is not trainable, this assignment is safe. Also, # tf.function ensures that this will run in the right order. update_s = tf.assign(_s, tf.math.log(b_avg) / tf.math.cos(tf.minimum(math.pi/4, theta_med))) with tf.control_dependencies([update_s]): scaled_logits = _s * logits loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=scaled_logits, labels=label)) tfwatcher.insert('s', _s) return loss def arcface_loss(embedding, labels, num_classes, s=64., m=0.5, mm=0.35): ''' :param embedding: the input embedding vectors :param labels: the input labels, the shape should be eg: (batch_size, 1) :param s: scalar value default is 64 :param num_classes: output class num :param m: the margin value, default is 0.5 :return: the final cacualted output, this output is send into the tf.nn.softmax directly ''' num_features = embedding.shape[1].value batch_size = tf.shape(embedding)[0] cos_m = math.cos(m) sin_m = math.sin(m) # mm = sin_m * m # issue 1 threshold = math.cos(math.pi - m) w_init = None with tf.variable_scope('arcface_loss'): weights = tf.get_variable(name='weights', shape=(num_features, num_classes), initializer=tf.random_normal_initializer(0.01), trainable=True, dtype=tf.float32) # Normalize scale to be positive if automatic if s == 'auto': s_ = tf.get_variable('s_', shape=(), regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(1.0), trainable=True, dtype=tf.float32) s = tf.log(tf.exp(0.0) + tf.exp(s_)) tfwatcher.insert('s', s) else: assert type(s) in [float, int] s = tf.constant(s) # inputs and weights norm embedding = tf.nn.l2_normalize(embedding, axis=1) weights = tf.nn.l2_normalize(weights, axis=0) # cos(theta+m) cos_t = tf.matmul(embedding, weights, name='cos_t') cos_t2 = tf.square(cos_t, name='cos_2') sin_t2 = tf.subtract(1., cos_t2, name='sin_2') sin_t = tf.sqrt(sin_t2 + 1e-6, name='sin_t') cos_mt = s * (cos_t * cos_m - sin_t * sin_m) # this condition controls the theta+m should in range [0, pi] # 0<=theta+m<=pi # -m<=theta<=pi-m # cond_v = cos_t - threshold # cond = tf.cast(tf.nn.relu(cond_v, name='if_else'), dtype=tf.bool) cond = tf.greater(cos_t, threshold) keep_vals = s * (cos_t - mm) cos_mt_temp = tf.where(cond, cos_mt, keep_vals) mask = tf.one_hot(labels, depth=num_classes, name='one_hot_mask') mask = tf.cast(mask, tf.bool) # inv_mask = tf.subtract(1., mask, name='inverse_mask') s_cos_t = s * cos_t logits = tf.where(mask, cos_mt_temp, s_cos_t) # inv_mask * s_cos_t + mask * cos_mt_temp loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)) return loss def am_softmax_imprint(prelogits, label, num_classes, global_step, weight_decay, learning_rate, scale=16.0, m=1.0, alpha='auto', multi_lr=False, weights_target=None, label_target=None, reuse=None): ''' Variant of AM-Softmax where weights are dynamically imprinted. ''' num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope('AM-Softmax', reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, num_features), initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.0), # initializer=tf.constant_initializer(0), trainable=False, dtype=tf.float32) _scale = tf.get_variable('_scale', shape=(), regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(0.0), trainable=True, dtype=tf.float32) tf.add_to_collection('classifier_weights', weights) # Normalizing the vecotors prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1) weights_normed = tf.nn.l2_normalize(weights, dim=1) # Label and logits between batch and examplars label_mat_glob = tf.one_hot(label, num_classes, dtype=tf.float32) label_mask_pos_glob = tf.cast(label_mat_glob, tf.bool) label_mask_neg_glob = tf.logical_not(label_mask_pos_glob) logits_glob = tf.matmul(prelogits_normed, tf.transpose(weights_normed)) # logits_glob = -0.5 * euclidean_distance(prelogits_normed, tf.transpose(weights_normed)) logits_pos = tf.boolean_mask(logits_glob, label_mask_pos_glob) logits_neg = tf.boolean_mask(logits_glob, label_mask_neg_glob) if scale == 'auto': # Automatic learned scale scale = tf.log(tf.exp(0.0) + tf.exp(_scale)) else: # Assigned scale value assert type(scale) == float scale = tf.constant(scale) # Losses logits_pos = tf.reshape(logits_pos, [batch_size, -1]) logits_neg = tf.reshape(logits_neg, [batch_size, -1]) logits_pos = logits_pos * scale logits_neg = logits_neg * scale logits_neg = tf.reduce_logsumexp(logits_neg, axis=1)[:,None] loss_ = tf.nn.softplus(m + logits_neg - logits_pos) loss = tf.reduce_mean(loss_, name='am_softmax') # Update centers if not weights in tf.trainable_variables(): if multi_lr: alpha = alpha * learning_rate if weights_target is None: print('Imprinting target...') weights_target = prelogits_normed label_target = label weights_batch = tf.gather(weights, label_target) diff_centers = weights_batch - weights_target unique_label, unique_idx, unique_count = tf.unique_with_counts(label_target) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = diff_centers / tf.cast(appear_times, tf.float32) diffTrue_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(weights, label_target, diff_centers) with tf.control_dependencies([centers_update_op]): # weights_batch = tf.gather(weights, label) # weights_new = tf.nn.l2_normalize(weights_batch, dim=1) # centers_update_op = tf.scatter_update(weights, label, weights_new) centers_update_op = tf.assign(weights, tf.nn.l2_normalize(weights,dim=1)) # centers_update_op = tf.group(centers_update_op) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) # Analysis tfwatcher.insert('scale', scale) return loss def matrix_normalize(w, iterations=5): ''' Sinkhorn-Knopp algorithm for matrix normalization. Sinkhorn's theorem.''' for i in range(iterations): w = w / tf.reduce_sum(w, axis=1, keep_dims=True) w = w / tf.reduce_sum(w, axis=0, keep_dims=True) return w def group_loss(prelogits, weights, label, num_classes, global_step, weight_decay, scale=16.0, m=1.0, alpha=None, reuse=None): n_groups = weights.shape[1].value # weights = tf.nn.softmax(weights, axis=0) weights = matrix_normalize(tf.exp(weights)) prelogits_splits = tf.split(prelogits, n_groups, axis=1) weights_splits = tf.split(weights, n_groups, axis=1) from functools import partial loss = partial(am_softmax, num_classes=num_classes, global_step=global_step, weight_decay=weight_decay, scale=scale, m=m, alpha=alpha, reduce_mean=False, reuse=reuse) print('{} groups'.format(n_groups)) loss_all = 0. for i in range(n_groups): prelogits_splits[i], loss_all += tf.reduce_sum(weights_splits[i] * loss(prelogits, label, scope='loss_{}'.format(i))) tfwatcher.insert('w{}'.format(i+1), tf.reduce_sum(weights_splits[i])) if False: weight_reg = tf.reduce_sum(weights, axis=0) weight_reg = weight_reg / tf.reduce_sum(weight_reg) weight_reg = tf.reduce_mean(-tf.log(weight_reg)) loss_all += weight_reg tfwatcher.insert('wreg', weight_reg) weight_std = tf.reduce_mean(tf.nn.moments(weights, axes=[1])[1]) tfwatcher.insert('wstd', weight_std) tf.summary.image('weight', weights[None, :32, :, None]) return loss_all def euc_loss(prelogits, label, num_classes, global_step, weight_decay, m=1.0, alpha=0.5, reuse=None): num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope('EucLoss', reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, num_features), # initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.05), initializer=tf.constant_initializer(0), trainable=True, dtype=tf.float32) if False: prelogits_ = tf.reshape(prelogits, [-1, 1, num_features]) weights_ = tf.reshape(weights, [1, -1, num_features]) dist = np.square(prelogits_ - weights_) dist = tf.transpose(dist, [0, 2, 1]) dist = tf.reshape(dist, [-1, num_classes]) logits = - 0.5 * dist label_ = tf.tile(tf.reshape(label, [-1,1]), [1, num_features]) label_ = tf.reshape(label_, [-1]) loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\ labels=label_, logits=logits), name='loss') else: weights_ = weights # batch_norm(weights) # Label and logits between batch and examplars label_mat_glob = tf.one_hot(label, num_classes, dtype=tf.float32) label_mask_pos_glob = tf.cast(label_mat_glob, tf.bool) label_mask_neg_glob = tf.logical_not(label_mask_pos_glob) dist_glob = euclidean_distance(prelogits, tf.transpose(weights_)) dist_pos = tf.boolean_mask(dist_glob, label_mask_pos_glob) dist_neg = tf.boolean_mask(dist_glob, label_mask_neg_glob) # Losses dist_pos = tf.log(tf.reshape(dist_pos, [batch_size, -1]) + 1e-6) dist_neg = tf.log(tf.reshape(dist_neg, [batch_size, -1]) + 1e-6) dist_neg = -tf.reduce_logsumexp(-dist_neg, axis=1)[:,None] #loss_pos = tf.reduce_mean(dist_pos) #loss_neg = tf.reduce_mean(tf.nn.relu(m - dist_neg)) loss = tf.reduce_logsumexp(tf.nn.softplus(m + dist_pos - dist_neg)) tfwatcher.insert('mean_mu', tf.reduce_mean(tf.norm(weights, axis=1))) tfwatcher.insert('mean_feat', tf.reduce_mean(tf.norm(prelogits, axis=1))) # Update centers if not weights in tf.trainable_variables(): weights_target = prelogits label_target = label weights_batch = tf.gather(weights, label_target) diff_centers = weights_batch - weights_target unique_label, unique_idx, unique_count = tf.unique_with_counts(label_target) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = diff_centers / tf.cast(appear_times, tf.float32) diff_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(weights, label_target, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) return loss def split_softmax(prelogits, label, num_classes, global_step, weight_decay, gamma=16.0, m=1.0, reuse=None): nrof_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope('SplitSoftmax', reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, nrof_features), regularizer=slim.l2_regularizer(weight_decay), initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.5), # initializer=tf.constant_initializer(0), trainable=True, dtype=tf.float32) alpha = tf.get_variable('alpha', shape=(), regularizer=slim.l2_regularizer(1e-4), initializer=tf.constant_initializer(1.00), trainable=True, dtype=tf.float32) beta = tf.get_variable('beta', shape=(), # regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(0.0), trainable=True, dtype=tf.float32) # Normalizing the vecotors # weights_normed = weights weights_normed = tf.nn.l2_normalize(weights, dim=1) # prelogits_normed = prelogits prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1) # norm_ = tf.norm(prelogits_normed, axis=1) # tfwatcher.insert('pnorm', tf.reduce_mean(norm_)) coef = -1.0 # Label and logits between batch and examplars label_mat_glob = tf.one_hot(label, num_classes, dtype=tf.float32) label_mask_pos_glob = tf.cast(label_mat_glob, tf.bool) label_mask_neg_glob = tf.logical_not(label_mask_pos_glob) # label_exp_batch = tf.expand_dims(label, 1) # label_exp_glob = tf.expand_dims(label_history, 1) # label_mat_glob = tf.equal(label_exp_batch, tf.transpose(label_exp_glob)) # label_mask_pos_glob = tf.cast(label_mat_glob, tf.bool) # label_mask_neg_glob = tf.logical_not(label_mat_glob) dist_mat_glob = euclidean_distance(prelogits_normed, tf.transpose(weights_normed), False) # dist_mat_glob = tf.matmul(prelogits_normed, tf.transpose(weights_normed)) dist_pos_glob = tf.boolean_mask(dist_mat_glob, label_mask_pos_glob) dist_neg_glob = tf.boolean_mask(dist_mat_glob, label_mask_neg_glob) logits_glob = coef * dist_mat_glob logits_pos_glob = tf.boolean_mask(logits_glob, label_mask_pos_glob) logits_neg_glob = tf.boolean_mask(logits_glob, label_mask_neg_glob) # Label and logits within batch label_exp_batch = tf.expand_dims(label, 1) label_mat_batch = tf.equal(label_exp_batch, tf.transpose(label_exp_batch)) label_mask_pos_batch = tf.cast(label_mat_batch, tf.bool) label_mask_neg_batch = tf.logical_not(label_mask_pos_batch) mask_non_diag = tf.logical_not(tf.cast(tf.eye(batch_size), tf.bool)) label_mask_pos_batch = tf.logical_and(label_mask_pos_batch, mask_non_diag) dist_mat_batch = euclidean_distance(prelogits_normed, tf.transpose(prelogits_normed), False) # dist_mat_batch = tf.matmul(prelogits_normed, tf.transpose(prelogits_normed)) dist_pos_batch = tf.boolean_mask(dist_mat_batch, label_mask_pos_batch) dist_neg_batch = tf.boolean_mask(dist_mat_batch, label_mask_neg_batch) logits_batch = coef * dist_mat_batch logits_pos_batch = tf.boolean_mask(logits_batch, label_mask_pos_batch) logits_neg_batch = tf.boolean_mask(logits_batch, label_mask_neg_batch) dist_pos = dist_pos_batch dist_neg = dist_neg_batch logits_pos = logits_pos_batch logits_neg = logits_neg_batch if gamma == 'auto': # gamma = tf.nn.softplus(alpha) gamma = tf.log(tf.exp(1.0) + tf.exp(alpha)) elif type(gamma) == tuple: t_min, decay = gamma epsilon = 1.0 t = tf.maximum(t_min, 1.0/(epsilon + decay*tf.cast(global_step, tf.float32))) gamma = 1.0 / t else: assert type(gamma) == float gamma = tf.constant(gamma) # Losses t_pos = (beta) t_neg = (beta) logits_pos = tf.reshape(logits_pos, [batch_size, -1]) logits_neg = tf.reshape(logits_neg, [batch_size, -1]) logits_pos = tf.stop_gradient(logits_pos) * gamma + beta logits_neg = tf.stop_gradient(logits_neg) * gamma + beta loss_gb = tf.reduce_mean(tf.nn.softplus(-logits_pos)) + tf.reduce_mean(tf.nn.softplus(logits_neg)) g,b = tf.stop_gradient(gamma), tf.stop_gradient(beta) loss_pos = tf.reduce_mean(g*dist_pos) loss_neg = tf.nn.softplus(tf.reduce_logsumexp(b - g * dist_neg)) # _logits_neg = tf.reduce_logsumexp(_logits_neg, axis=1)[:,None] # _logits_neg = -tf.reduce_max(-_logits_neg, axis=1)[:,None] tfwatcher.insert('neg', tf.reduce_mean(loss_neg)) tfwatcher.insert('pos', tf.reduce_mean(loss_pos)) tfwatcher.insert('lneg', tf.reduce_mean(logits_neg)) tfwatcher.insert('lpos', tf.reduce_mean(logits_pos)) #num_violate = tf.reduce_sum(tf.cast(tf.greater(m + _logits_neg - _logits_pos, 0.), tf.float32), axis=1, keep_dims=True) #loss = tf.reduce_sum(tf.nn.relu(m + _logits_neg - _logits_pos), axis=1, keep_dims=True) / (num_violate + 1e-8) #tfwatcher.insert('nv', tf.reduce_mean(num_violate)) # loss = tf.nn.softplus(m + _logits_neg - _logits_pos) loss = tf.reduce_mean(loss_gb + loss_pos + loss_neg, name='split_loss') # Update centers if not weights in tf.trainable_variables(): weights_batch = tf.gather(weights, label) diff_centers = weights_batch - prelogits_normed unique_label, unique_idx, unique_count = tf.unique_with_counts(label) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = diff_centers / tf.cast((1 + appear_times), tf.float32) diff_centers = 0.5 * diff_centers centers_update_op = tf.scatter_sub(weights, label, diff_centers) with tf.control_dependencies([centers_update_op]): centers_update_op = tf.assign(weights, tf.nn.l2_normalize(weights,dim=1)) # centers_decay_op = tf.assign_sub(weights, 2*weight_decay*weights)# weight decay centers_update_op = tf.group(centers_update_op) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) # Analysis tf.summary.scalar('gamma', gamma) # tf.summary.scalar('alpha', alpha) tf.summary.scalar('beta', beta) tfwatcher.insert('gamma', gamma) tfwatcher.insert('beta', beta) return loss def centers_by_label(features, label): # Compute centers within batch unique_label, unique_idx, unique_count = tf.unique_with_counts(label) num_centers = tf.size(unique_label) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) weighted_prelogits = features / tf.cast(appear_times, tf.float32) centers = tf.unsorted_segment_sum(weighted_prelogits, unique_idx, num_centers) return centers, unique_label, unique_idx, unique_count def pair_loss(prelogits, label, num_classes, global_step, weight_decay, gamma=16.0, m=1.0, reuse=None): nrof_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope('PairLoss', reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, nrof_features), regularizer=slim.l2_regularizer(weight_decay), initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.0), # initializer=tf.constant_initializer(0), trainable=True, dtype=tf.float32) alpha = tf.get_variable('alpha', shape=(), regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(1.00), trainable=True, dtype=tf.float32) beta = tf.get_variable('beta', shape=(), # regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(0.0), trainable=True, dtype=tf.float32) # Normalizing the vecotors weights_normed = tf.nn.l2_normalize(weights, dim=1) prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1) # weights_normed = weights # prelogits_normed = prelogits prelogits_reshape = tf.reshape(prelogits_normed, [-1,2,tf.shape(prelogits_normed)[1]]) prelogits_tmp = prelogits_reshape[:,0,:] prelogits_pro = prelogits_reshape[:,1,:] dist_mat_batch = -euclidean_distance(prelogits_tmp, tf.transpose(prelogits_pro), False) # dist_mat_batch = tf.matmul(prelogits_tmp, tf.transpose(prelogits_pro)) logits_mat_batch = dist_mat_batch num_pairs = tf.shape(prelogits_reshape)[0] label_mask_pos_batch = tf.cast(tf.eye(num_pairs), tf.bool) label_mask_neg_batch = tf.logical_not(label_mask_pos_batch) dist_pos_batch = tf.boolean_mask(dist_mat_batch, label_mask_pos_batch) dist_neg_batch = tf.boolean_mask(dist_mat_batch, label_mask_neg_batch) logits_pos_batch = tf.boolean_mask(logits_mat_batch, label_mask_pos_batch) logits_neg_batch = tf.boolean_mask(logits_mat_batch, label_mask_neg_batch) logits_pos = logits_pos_batch logits_neg = logits_neg_batch dist_pos = dist_pos_batch dist_neg = dist_neg_batch if gamma == 'auto': # gamma = tf.nn.softplus(alpha) gamma = tf.log(tf.exp(1.0) + tf.exp(alpha)) elif type(gamma) == tuple: t_min, decay = gamma epsilon = 1.0 t = tf.maximum(t_min, 1.0/(epsilon + decay*tf.cast(global_step, tf.float32))) gamma = 1.0 / t else: assert type(gamma) == float gamma = tf.constant(gamma) hinge_loss = lambda x: tf.nn.relu(1.0 + x) margin_func = hinge_loss # Losses losses = [] t_pos = (beta) t_neg = (beta) _logits_pos = tf.reshape(logits_pos, [num_pairs, -1]) _logits_neg_1 = tf.reshape(logits_neg, [num_pairs, -1]) _logits_neg_2 = tf.reshape(logits_neg, [-1, num_pairs]) _logits_pos = _logits_pos * gamma _logits_neg_1 = tf.reduce_max(_logits_neg_1, axis=1)[:,None] _logits_neg_2 = tf.reduce_max(_logits_neg_2, axis=0)[:,None] _logits_neg = tf.maximum(_logits_neg_1, _logits_neg_2) # _logits_neg_1 = tf.reduce_logsumexp(gamma*_logits_neg_1, axis=1)[:,None] # _logits_neg_2 = tf.reduce_logsumexp(gamma*_logits_neg_2, axis=0)[:,None] loss_pos = tf.nn.relu(m + _logits_neg_1 - _logits_pos) * 0.5 loss_neg = tf.nn.relu(m + _logits_neg_2 - _logits_pos) * 0.5 loss = tf.reduce_mean(loss_pos + loss_neg) loss = tf.identity(loss, name='pair_loss') losses.extend([loss]) tfwatcher.insert('ploss', loss) # Analysis tf.summary.scalar('gamma', gamma) tf.summary.scalar('alpha', alpha) tf.summary.scalar('beta', beta) tf.summary.histogram('dist_pos', dist_pos) tf.summary.histogram('dist_neg', dist_neg) tfwatcher.insert('gamma', gamma) return losses def pair_loss_twin(prelogits_tmp, prelogits_pro, label_tmp, label_pro, num_classes, global_step, weight_decay, gamma=16.0, m=1.0, reuse=None): num_features = prelogits_tmp.shape[1].value batch_size = tf.shape(prelogits_tmp)[0] + tf.shape(prelogits_pro)[0] with tf.variable_scope('PairLoss', reuse=reuse): alpha = tf.get_variable('alpha', shape=(), # regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(1.00), trainable=True, dtype=tf.float32) beta = tf.get_variable('beta', shape=(), # regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(0.0), trainable=True, dtype=tf.float32) # Normalizing the vecotors prelogits_tmp = tf.nn.l2_normalize(prelogits_tmp, dim=1) prelogits_pro = tf.nn.l2_normalize(prelogits_pro, dim=1) dist_mat_batch = -euclidean_distance(prelogits_tmp, tf.transpose(prelogits_pro),False) # dist_mat_batch = tf.matmul(prelogits_tmp, tf.transpose(prelogits_pro)) logits_mat_batch = dist_mat_batch num_pairs = tf.shape(prelogits_tmp)[0] # label_tmp_batch = tf.expand_dims(label_tmp, 1) # label_pro_batch = tf.expand_dims(label_pro, 1) # label_mat_batch = tf.equal(label_tmp_batch, tf.transpose(label_pro_batch)) # label_mask_pos_batch = tf.cast(label_mat_batch, tf.bool) label_mask_pos_batch = tf.cast(tf.eye(num_pairs), tf.bool) label_mask_neg_batch = tf.logical_not(label_mask_pos_batch) logits_pos = tf.boolean_mask(logits_mat_batch, label_mask_pos_batch) logits_neg_1 = tf.boolean_mask(logits_mat_batch, label_mask_neg_batch) logits_neg_2 = tf.boolean_mask(tf.transpose(logits_mat_batch), label_mask_neg_batch) if gamma == 'auto': # gamma = tf.nn.softplus(alpha) gamma = tf.log(tf.exp(1.0) + tf.exp(alpha)) elif type(gamma) == tuple: t_min, decay = gamma epsilon = 1.0 t = tf.maximum(t_min, 1.0/(epsilon + decay*tf.cast(global_step, tf.float32))) gamma = 1.0 / t else: assert type(gamma) == float gamma = tf.constant(gamma) # Losses losses = [] t_pos = (beta) t_neg = (beta) _logits_pos = tf.reshape(logits_pos, [num_pairs, -1]) _logits_neg_1 = tf.reshape(logits_neg_1, [num_pairs, -1]) _logits_neg_2 = tf.reshape(logits_neg_2, [num_pairs, -1]) _logits_neg_1 = tf.reduce_max(_logits_neg_1, axis=1)[:,None] _logits_neg_2 = tf.reduce_max(_logits_neg_2, axis=1)[:,None] _logits_neg = tf.maximum(_logits_neg_1, _logits_neg_2) # _logits_neg = tf.concat([_logits_neg_1, _logits_neg_2], axis=1) # _logits_neg = tf.reduce_logsumexp(_logits_neg, axis=1)[:,None] num_violate = tf.reduce_sum(tf.cast(tf.greater(m + _logits_neg - _logits_pos, 0.), tf.float32), axis=1, keep_dims=True) loss_1 = tf.reduce_sum(tf.nn.relu(m + _logits_neg - _logits_pos), axis=1, keep_dims=True) * 0.5 # / (num_violate + 1e-8) loss_2 = tf.reduce_sum(tf.nn.relu(m + _logits_neg - _logits_pos), axis=1, keep_dims=True) * 0.5 # / (num_violate + 1e-8) loss = tf.reduce_mean(loss_1 + loss_2) loss = tf.identity(loss, name='pair_loss') losses.extend([loss]) # Analysis tf.summary.scalar('gamma', gamma) tf.summary.scalar('alpha', alpha) tf.summary.scalar('beta', beta) tf.summary.histogram('dist_pos', _logits_pos) tf.summary.histogram('dist_neg', _logits_neg) tfwatcher.insert("gamma", gamma) return losses def l2centers(features, label, centers, coef): centers_batch = tf.gather(centers, label) loss = tf.reduce_mean(coef * tf.reduce_sum(tf.square(features - centers_batch), axis=1), name='l2centers') return loss def pair_regression(features, targets, coef): features = tf.nn.l2_normalize(features, dim=1) targets = tf.nn.l2_normalize(targets, dim=1) loss = coef * tf.reduce_mean(tf.reduce_sum(tf.square(features - targets), axis=1)) return loss def triplet_loss(labels, embeddings, margin, normalize=False): with tf.name_scope('TripletLoss'): if normalize: embeddings = tf.nn.l2_normalize(embeddings, dim=1) batch_size = tf.shape(embeddings)[0] num_features = embeddings.shape[1].value diag_mask = tf.eye(batch_size, dtype=tf.bool) non_diag_mask = tf.logical_not(diag_mask) dist_mat = euclidean_distance(embeddings, tf.transpose(embeddings), False) label_mat = tf.equal(labels[:,None], labels[None,:]) label_mask_pos = tf.logical_and(non_diag_mask, label_mat) label_mask_neg = tf.logical_and(non_diag_mask, tf.logical_not(label_mat)) dist_pos = tf.boolean_mask(dist_mat, label_mask_pos) dist_neg = tf.boolean_mask(dist_mat, label_mask_neg) dist_pos = tf.reshape(dist_pos, [batch_size, -1]) dist_neg = tf.reshape(dist_neg, [batch_size, -1]) # Hard Negative Mining dist_neg = -tf.reduce_max(-dist_neg, axis=1, keep_dims=True) loss = tf.nn.relu(dist_pos - dist_neg + margin) loss = tf.reduce_mean(loss, name='TripletLoss') return loss def average_nonneg(losses, axis=None): valid = tf.cast(tf.greater(losses, 0.0), tf.float32) valid_count = tf.reduce_sum(valid, axis=axis) loss = tf.reduce_sum(losses, axis=axis) / (valid_count + 1e-8) return loss def uncertain_pair_loss(mu, log_sigma_sq, coef=1.0): with tf.name_scope('UncertainPairLoss'): batch_size = tf.shape(mu)[0] num_features = mu.shape[1].value mu = tf.reshape(mu, [-1, 2, num_features]) sigma_sq = tf.exp(tf.reshape(log_sigma_sq, [-1, 2, num_features])) mu1, mu2 = mu[:,0], mu[:,1] sigma_sq1, sigma_sq2 = sigma_sq[:,0], sigma_sq[:,1] mu_diff = mu1 - mu2 sigma_sq_sum = sigma_sq1 + sigma_sq2 eps = 1e-8 loss = tf.square(mu_diff) / (eps + sigma_sq_sum) + tf.log(sigma_sq_sum) loss = tf.reduce_mean(tf.reduce_sum(loss, axis=1)) return loss def masked_reduce_mean(tensor, mask, axis, eps=1e-8): mask = tf.cast(mask, tf.float32) num_valid = tf.reduce_sum(mask, axis=axis) return tf.reduce_sum(tensor * mask, axis=axis) / (num_valid + eps) def triplet_avghard_loss(labels, embeddings, margin=1., normalize=False): with tf.name_scope('AvgHardTripletLoss'): if normalize: embeddings = tf.nn.l2_normalize(embeddings, dim=1) batch_size = tf.shape(embeddings)[0] num_features = embeddings.shape[1].value dist_mat = euclidean_distance(embeddings, tf.transpose(embeddings), False) diag_mask = tf.eye(batch_size, dtype=tf.bool) non_diag_mask = tf.logical_not(diag_mask) label_mat = tf.equal(labels[:,None], labels[None,:]) label_mask_pos = tf.logical_and(non_diag_mask, label_mat) label_mask_neg = tf.logical_not(label_mat) # Followings are different from hard negative mining dist_tensor_neg = tf.tile(dist_mat, [1, batch_size]) dist_tensor_neg = tf.reshape(dist_tensor_neg, [batch_size, batch_size, batch_size]) label_tensor_neg= tf.tile(label_mask_neg, [1, batch_size]) label_tensor_neg = tf.reshape(label_tensor_neg, [batch_size, batch_size, batch_size]) loss = tf.nn.relu(dist_mat[:,:,None] - dist_tensor_neg + margin) # Mask the third dimension to pick the negative samples mask = tf.logical_and(label_tensor_neg, tf.greater(loss, 0.)) loss = masked_reduce_mean(loss, mask, axis=2) # Mask the first two dimension to only keep positive pairs loss = tf.boolean_mask(loss, label_mask_pos) loss = tf.reduce_mean(loss) return loss def uncertain_triplet_loss(labels, embeddings, log_sigma_sq, margin=100., coef=1.0, normalize=False): with tf.name_scope('TripletLoss'): if normalize: embeddings = tf.nn.l2_normalize(embeddings, dim=1) batch_size = tf.shape(embeddings)[0] num_features = embeddings.shape[1].value diag_mask = tf.eye(batch_size, dtype=tf.bool) non_diag_mask = tf.logical_not(diag_mask) sigma_sq = tf.exp(log_sigma_sq) dist_mat = uncertain_distance(embeddings, embeddings, sigma_sq, sigma_sq) # dist_mat_ = uncertain_distance(embeddings, tf.transpose(embeddings), tf.stop_gradient(sigma_sq), tf.stop_gradient(sigma_sq)) label_mat = tf.equal(labels[:,None], labels[None,:]) label_mask_pos = tf.logical_and(non_diag_mask, label_mat) label_mask_neg = tf.logical_and(non_diag_mask, tf.logical_not(label_mat)) if False: dist_mat_tile = tf.tile(tf.reshape(dist_mat, [batch_size, 1, -1]), [1, batch_size ,1]) dist_mat_tile = tf.reshape(dist_mat_tile, [-1, batch_size]) label_mat_tile = tf.tile(tf.reshape(label_mat, [batch_size, 1, -1]), [1, batch_size, 1]) label_mat_tile = tf.reshape(label_mat_tile, [-1, batch_size]) dist_flatten = tf.reshape(dist_mat, [-1, 1]) label_flatten = tf.reshape(label_mask_pos, [-1]) loss = dist_flatten - dist_mat_tile + margin valid = tf.cast( tf.logical_and(tf.logical_not(label_mat_tile), tf.greater(loss, 0.0)), tf.float32) loss = tf.nn.relu(loss) # Set rows of impostor pairs to zero # valid = tf.cast(tf.reshape(label_flatten, [-1,1]), tf.float32) * valid valid = tf.boolean_mask(valid, label_flatten) loss = tf.boolean_mask(loss, label_flatten) # loss = tf.reshape(loss, [batch_size, -1]) # valid = tf.reshape(valid, [batch_size, -1]) valid_count = tf.reduce_sum(valid, axis=1) + 1e-8 loss = tf.reduce_sum(loss * valid, axis=1) / valid_count loss = tf.reduce_mean(loss) else: dist_pos = tf.boolean_mask(dist_mat, label_mask_pos) dist_neg = tf.boolean_mask(dist_mat, label_mask_neg) dist_pos = tf.reshape(dist_pos, [-1,1]) dist_neg = tf.reshape(dist_neg, [1,-1]) # return tf.reduce_mean(dist_pos) if True: loss = dist_pos - dist_neg + margin valid = tf.cast(tf.greater(loss, 0.0), tf.float32) valid_count = tf.reduce_sum(valid, axis=1) + 1e-8 loss = tf.reduce_sum(tf.nn.relu(loss) * valid, axis=1) / valid_count loss = tf.reduce_mean(dist_pos) elif False: loss_pos = tf.reduce_mean(dist_pos) loss_neg = tf.stop_gradient(dist_pos) - dist_neg + margin valid = tf.cast(tf.greater(loss_neg, 0.0), tf.float32) valid_count = tf.reduce_sum(valid, axis=1) + 1e-8 loss_neg = tf.reduce_mean(tf.reduce_sum(valid* loss_neg, axis=1) / valid_count) loss = loss_pos + loss_neg else: # margin = tf.stop_gradient(tf.reduce_mean(dist_pos)) print('Constrastive Loss: margin={}'.format(margin)) loss_pos = tf.reduce_mean(dist_pos) loss_neg = tf.reduce_mean(tf.nn.relu(margin - dist_neg)) # loss_neg = average_nonneg(tf.nn.relu(margin - dist_neg)) loss = loss_pos + loss_neg tfwatcher.insert('lneg', loss_neg) loss = coef * loss # dist_pos = tf.boolean_mask(dist_mat, label_mask_pos) # dist_neg = tf.boolean_mask(dist_mat_, label_mask_neg) # dist_pos = tf.reshape(dist_pos, [batch_size, -1]) # dist_neg = tf.reshape(dist_neg, [batch_size, -1]) # Hard Negative Mining # dist_neg = -tf.reduce_max(-dist_neg, axis=1, keep_dims=True) # loss = tf.reduce_mean(dist_pos) - tf.reduce_mean(dist_neg) # loss = tf.nn.relu(dist_pos - dist_neg + margin) # loss = tf.reduce_mean(dist_pos - dist_neg) # loss = tf.reduce_mean(loss, name='TripletLoss') tfwatcher.insert('mean_sigma', tf.reduce_mean(tf.exp(0.5*log_sigma_sq))) return loss def contrastive_loss(labels, embeddings, margin, normalize=False): with tf.name_scope('ContrastiveLoss'): if normalize: embeddings = tf.nn.l2_normalize(embeddings, dim=1) batch_size = tf.shape(embeddings)[0] num_features = embeddings.shape[1].value diag_mask = tf.eye(batch_size, dtype=tf.bool) non_diag_mask = tf.logical_not(diag_mask) dist_mat = euclidean_distance(embeddings, tf.transpose(embeddings), False) label_mat = tf.equal(labels[:,None], labels[None,:]) label_mask_pos = tf.logical_and(non_diag_mask, label_mat) label_mask_neg = tf.logical_and(non_diag_mask, tf.logical_not(label_mat)) dist_pos = tf.boolean_mask(dist_mat, label_mask_pos) dist_neg = tf.boolean_mask(dist_mat, label_mask_neg) # Keep hards triplets # dist_pos = tf.reshape(dist_pos, [batch_size, -1]) # dist_neg = tf.reshape(dist_neg, [batch_size, -1]) # dist_neg = tf.reduce_min(dist_neg, axis=1, keep_dims=True) loss_pos = tf.reduce_mean(dist_pos) loss_neg = tf.reduce_mean(tf.nn.relu(margin - dist_neg)) loss = tf.identity(loss_pos + loss_neg, name='contrastive_loss') return loss def scaled_npair(prelogits, labels, num_classes, scale='auto', scale_decay=1e-2, m=1.0, reuse=None): num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope('NPairLoss', reuse=reuse): _scale = tf.get_variable('_scale', shape=(), regularizer=slim.l2_regularizer(scale_decay), initializer=tf.constant_initializer(0.00), trainable=True, dtype=tf.float32) # Normalizing the vecotors prelogits = tf.nn.l2_normalize(prelogits, dim=1) # Label and logits within batch label_exp = tf.expand_dims(labels, 1) label_mat = tf.equal(label_exp, tf.transpose(label_exp)) label_mask_pos = tf.cast(label_mat, tf.bool) label_mask_neg = tf.logical_not(label_mask_pos) mask_non_diag = tf.logical_not(tf.cast(tf.eye(batch_size), tf.bool)) label_mask_pos = tf.logical_and(label_mask_pos, mask_non_diag) logits_mat = - euclidean_distance(prelogits, tf.transpose(prelogits), False) # logits_mat = tf.matmul(prelogits, tf.transpose(prelogits)) logits_pos = tf.boolean_mask(logits_mat, label_mask_pos) logits_neg = tf.boolean_mask(logits_mat, label_mask_neg) if scale == 'auto': scale = tf.nn.softplus(_scale) else: assert type(scale) == float scale = tf.constant(scale) # Losses logits_pos = tf.reshape(logits_pos, [batch_size, -1]) logits_neg = tf.reshape(logits_neg, [batch_size, -1]) logits_pos = logits_pos * scale logits_neg = logits_neg * scale logits_neg = tf.reduce_logsumexp(logits_neg, axis=1)[:,None] loss_ = tf.nn.softplus(m + logits_neg - logits_pos) loss = tf.reduce_mean(loss_, name='npair') # Analysis tf.summary.scalar('scale', scale) tfwatcher.insert("scale", scale) return loss def conditional_loss(z_mean, z_log_sigma_sq, labels, num_classes, global_step, coef, alpha, weight_decay=5e-4, reuse=None): num_features = z_mean.shape[1].value batch_size = tf.shape(z_mean)[0] with tf.variable_scope('ConditionalLoss', reuse=reuse): weights_ = tf.get_variable('weights', shape=(num_classes, num_features), regularizer=slim.l2_regularizer(weight_decay), initializer=slim.xavier_initializer(uniform=False), # initializer=tf.truncated_normal_initializer(stddev=0.0), # initializer=tf.constant_initializer(0), trainable=True, dtype=tf.float32) _scale = tf.get_variable('_scale', shape=(), regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(1.00), trainable=True, dtype=tf.float32) scale = tf.log(tf.exp(1.0) + tf.exp(_scale)) # weights = tf.nn.l2_normalize(weights_, dim=1) # weights = batch_norm(tf.identity(weights)) bn_params = { 'decay': 0.995, 'epsilon': 1e-8, 'center': True, 'scale': True, 'trainable': True, 'is_training': True, 'param_initializers': {'gamma': tf.constant_initializer(0.01)}, } with slim.arg_scope([slim.fully_connected], normalizer_fn=None): pass weights = slim.fully_connected(weights_, num_features, biases_initializer = None, activation_fn=None, scope='fc1') # weights = slim.fully_connected(weights, num_features, activation_fn=None, # normalizer_fn=None, scope='fc2') weights = tf.nn.l2_normalize(weights_, dim=1) # logits = tf.matmul(prelogits, tf.transpose(weights)) + biases logits = - scale * euclidean_distance(z_mean, tf.transpose(weights)) loss_cls = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\ labels=labels, logits=logits), name='loss') z_inv_sigma_sq = tf.exp(-z_log_sigma_sq) weights_batch = tf.gather(weights, labels) neg_log_likelihood = 0.5 * tf.square(z_mean - weights_batch) * z_inv_sigma_sq + 0.5 * z_log_sigma_sq loss_nll = tf.reduce_sum(neg_log_likelihood, axis=1) loss_nll = tf.reduce_mean(loss_nll, name='conditional_loss') loss = loss_cls + coef * loss_nll # Update centers if not weights_ in tf.trainable_variables(): labels_unique, unique_idx = tf.unique(labels) xc = z_mean * z_inv_sigma_sq xc_unique = tf.unsorted_segment_sum(xc, unique_idx, tf.shape(labels_unique)[0]) c_unique = tf.unsorted_segment_sum(z_inv_sigma_sq, unique_idx, tf.shape(labels_unique)[0]) xc_normed = xc_unique / c_unique labels_target = labels weights_target = z_mean confidence_target = z_inv_sigma_sq weights_batch = tf.gather(weights, labels_target) diff_centers = weights_batch - weights_target diff_centers = alpha * diff_centers * confidence_target centers_update_op = tf.scatter_sub(weights, labels_target, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) tfwatcher.insert('mean_sigma', tf.reduce_mean(tf.exp(z_log_sigma_sq))) tfwatcher.insert('nll', loss_nll) tfwatcher.insert('scale', scale) return loss def gaussian_log_likelihood(mu, log_sigma_sq, z): sigma_sq = tf.exp(log_sigma_sq) log_likelihood = log_sigma_sq + tf.square(mu - z) / sigma_sq log_likelihood = 0.5 * tf.reduce_sum(log_likelihood, axis=1) return log_likelihood def gaussian_kl_divergence(mu1, log_sigma_sq1, mu2, log_sigma_sq2): sigma_sq1, sigma_sq2 = tf.exp(log_sigma_sq1), tf.exp(log_sigma_sq2) divergence = log_sigma_sq2 - log_sigma_sq1 + (sigma_sq1 + tf.square(mu2 - mu1)) / sigma_sq2 - 1.0 divergence = 0.5 * tf.reduce_sum(divergence, axis=1) return divergence def pair_ml_similarity(mu1, log_sigma_sq1, mu2, log_sigma_sq2): sigma_sq1, sigma_sq2 = tf.exp(log_sigma_sq1), tf.exp(log_sigma_sq2) sigma_sq_sum = sigma_sq1 + sigma_sq2 dist = tf.log(sigma_sq_sum) + tf.square(mu2 - mu1) / sigma_sq_sum dist = tf.reduce_sum(dist, axis=1) return dist def select_classes(weights, labels, background_size): num_classes = weights.shape[0].value indices = tf.random.shuffle(tf.range(num_classes))[:background_size] assert labels.shape.ndims == 1 indices = tf.concat([indices, labels], axis=0) indices, unique_idx = tf.unique(indices) weights = tf.gather(weights, indices) labels = tf.gather(unique_idx, labels) return weights, labels def class_divergence(z_mu, z_log_sigma_sq, labels, num_classes, global_step, weight_decay, coef, alpha=0.1, margin=100., reuse=None): num_features = z_mu.shape[1].value batch_size = tf.shape(z_mu)[0] with tf.variable_scope('DivergenceLoss', reuse=reuse): class_mu = tf.get_variable('class_mu', shape=(num_classes, 16), regularizer=slim.l2_regularizer(0.0), # initializer=slim.xavier_initializer(), initializer=tf.random_normal_initializer(stddev=0.01), # initializer=tf.constant_initializer(0), trainable=True, dtype=tf.float32) class_log_sigma_sq = tf.get_variable('class_log_sigma_sq', shape=(num_classes, num_features), regularizer=slim.l2_regularizer(0.0), # initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.0), initializer=tf.constant_initializer(-10), trainable=True, dtype=tf.float32) class_mu = slim.fully_connected(class_mu, num_features, activation_fn=tf.nn.relu, scope='fc1') class_mu = slim.fully_connected(class_mu, num_features, activation_fn=None, scope='fc2') tf.add_to_collection('class_mu', class_mu) tf.add_to_collection('class_log_sigma_sq', class_log_sigma_sq) # class_mu = tf.nn.l2_normalize(class_mu, axis=1) # class_mu = batch_norm(class_mu, name='normed_mu') if True: # class_mu = batch_norm(tf.identity(class_mu)) batch_mu = tf.gather(class_mu, labels) batch_log_sigma_sq= tf.gather(class_log_sigma_sq, labels) # divergence = gaussian_kl_divergence(batch_mu, batch_log_sigma_sq, z_mu, z_log_sigma_sq) divergence = pair_ml_similarity(batch_mu, batch_log_sigma_sq, z_mu, z_log_sigma_sq) # divergence = gaussian_log_likelihood(z_mu, z_log_sigma_sq, batch_mu) loss = tf.reduce_mean(divergence, name='divergence_loss') tfwatcher.insert('mean_dist', tf.reduce_mean(tf.abs(z_mu-batch_mu))) elif True: dist_mat = uncertain_distance(z_mu, class_mu, tf.exp(z_log_sigma_sq), tf.exp(class_log_sigma_sq), True) # dist_mat = euclidean_distance(z_mu, tf.transpose(class_mu)) label_mat = tf.one_hot(labels, num_classes, dtype=tf.float32) label_mask_pos = tf.cast(label_mat, tf.bool) label_mask_neg = tf.logical_not(label_mask_pos) dist_pos = tf.boolean_mask(dist_mat, label_mask_pos) dist_neg = tf.boolean_mask(dist_mat, label_mask_neg) dist_pos = tf.reshape(dist_pos, [batch_size, 1]) dist_neg = tf.reshape(dist_neg, [1, -1]) valid = tf.cast(tf.greater(dist_pos - dist_neg + margin, 0.), tf.float32) valid_count = tf.reduce_sum(valid, axis=1) + 1e-8 valid_count = tf.stop_gradient(valid_count) loss = tf.reduce_sum(tf.nn.relu(dist_pos - dist_neg + margin), axis=1) / valid_count # loss = tf.nn.softplus(dist_pos + tf.reduce_logsumexp(-dist_neg, axis=1) + margin) loss = tf.reduce_mean(loss) loss = coef * loss tfwatcher.insert('class_sigma', tf.reduce_mean(tf.exp(0.5*class_log_sigma_sq))) tfwatcher.insert('mean_sigma', tf.reduce_mean(tf.exp(0.5*z_log_sigma_sq))) if False and not class_mu in tf.trainable_variables(): z_inv_sigma_sq = tf.exp(-z_log_sigma_sq) labels_unique, unique_idx, unique_count = tf.unique_with_counts(labels) xc = z_mu * z_inv_sigma_sq xc_unique = tf.unsorted_segment_sum(xc, unique_idx, tf.shape(labels_unique)[0]) c_unique = tf.unsorted_segment_sum(z_inv_sigma_sq, unique_idx, tf.shape(labels_unique)[0]) xc_normed = xc_unique / c_unique # tfwatcher.insert('old_c', tf.reduce_mean(z_inv_sigma_sq)) # tfwatcher.insert('new_c', tf.reduce_mean(c_unique)) # tfwatcher.insert('labels_unique', labels_unique) appear_times = tf.cast(tf.gather(unique_count, unique_idx), tf.float32) appear_times = tf.reshape(appear_times, [-1, 1]) if True: # Confidence Decay c_decay = 1.0 decay_op = tf.assign(class_log_sigma_sq, class_log_sigma_sq - tf.log(c_decay)) with tf.control_dependencies([decay_op]): # Incremental Updating mu_batch = xc_normed c_batch = c_unique mu_old = tf.gather(class_mu, labels_unique) log_sigma_sq_old = tf.gather(class_log_sigma_sq, labels_unique) c_old = tf.exp(-log_sigma_sq_old) c_new = c_old + c_batch mu_new = (mu_old * c_old + mu_batch * c_batch) / c_new # Update variables labels_target = labels_unique mu_target = xc_normed c_target = c_unique class_mu_update_op = tf.scatter_update(class_mu, labels_target, mu_target) class_log_sigma_sq_update_op = tf.scatter_update(class_log_sigma_sq, labels_target, -tf.log(c_target)) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, class_mu_update_op) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, class_log_sigma_sq_update_op) else: labels_target = labels weights_target = z_mu confidence_target = z_inv_sigma_sq weights_batch = tf.gather(class_mu, labels_target) diff_centers = weights_batch - weights_target diff_centers = alpha * diff_centers / appear_times # * confidence_target centers_update_op = tf.scatter_sub(class_mu, labels_target, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) return loss def mean_dev(z_mean, z_log_sigma_sq, labels, num_classes, global_step, weight_decay, learning_rate, coef, alpha, multi_lr, reuse=None): num_features = z_mean.shape[1].value batch_size = tf.shape(z_mean)[0] weights_trainable = True if alpha is None else False with tf.variable_scope('ConditionalLoss', reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, num_features), regularizer=slim.l2_regularizer(0.0), initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.0), # initializer=tf.constant_initializer(0), trainable=False, dtype=tf.float32) # weights = batch_norm(tf.identity(weights)) # z_inv_sigma_sq = tf.exp(-z_log_sigma_sq) labels_unique, unique_idx = tf.unique(labels) weights_batch = tf.gather(weights, labels_unique) xc = z_mean * z_inv_sigma_sq xc_unique = tf.unsorted_segment_sum(xc, unique_idx, tf.shape(labels_unique)[0]) c_unique = tf.unsorted_segment_sum(z_inv_sigma_sq, unique_idx, tf.shape(labels_unique)[0]) xc_normed = xc_unique / c_unique deviation = tf.reduce_sum(tf.square(xc_normed - weights_batch), axis=1) loss = coef * tf.reduce_mean(deviation) # Update centers if weights not in tf.trainable_variables(): if multi_lr: alpha = alpha * learning_rate diff_centers = weights_batch - xc_normed diff_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(weights, labels_unique, diff_centers) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) tfwatcher.insert('mean_sigma', tf.reduce_mean(tf.exp(z_log_sigma_sq))) return loss def dim_pool(prelogits, confidence, label, num_classes, global_step, weight_decay, learning_rate, group_size, scale=16.0, m=1.0, alpha='auto', reuse=None): ''' Variant of AM-Softmax where weights are dynamically imprinted. ''' num_features = prelogits.shape[1].value batch_size = tf.shape(prelogits)[0] with tf.variable_scope('DPLoss', reuse=reuse): weights = tf.get_variable('weights', shape=(num_classes, num_features), initializer=slim.xavier_initializer(), # initializer=tf.truncated_normal_initializer(stddev=0.0), # initializer=tf.constant_initializer(0), trainable=False, dtype=tf.float32) _scale = tf.get_variable('_scale', shape=(), regularizer=slim.l2_regularizer(1e-2), initializer=tf.constant_initializer(0.0), trainable=True, dtype=tf.float32) tf.add_to_collection('classifier_weights', weights) # Normalizing the vecotors prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1) # prelogits_normed= prelogits weights_normed = tf.nn.l2_normalize(weights, dim=1) # Pooling # label_unique, unique_idx, unique_count = tf.unique_with_counts(label) # prelogits_mean = tf.unsorted_segment_sum(prelogits_normed, unique_idx, tf.shape(label_unique)[0]) # prelogits_mean = prelogits_mean / tf.cast(tf.reshape(unique_count, [-1,1]), tf.float32) prelogits_mean = tf.reshape(prelogits_normed, [-1, group_size, num_features]) confidence = tf.reshape(confidence, [-1, group_size, num_features]) confidence = tf.nn.softmax(confidence, axis=1) # confidence = tf.nn.sigmoid(confidence) # confidence = confidenf.log(ce / tf.reduce_sum(confidence, axis=1, keep_dims=True) prelogits_mean = prelogits_mean * confidence prelogits_mean = tf.reduce_sum(prelogits_mean, axis=1) # Normalize Again # prelogits_mean = tf.nn.l2_normalize(prelogits_mean, dim=1) label_mean = tf.reshape(label, [-1, group_size])[:,0] print(prelogits_mean.shape) # centers = tf.gather(weights, label_mean) # loss = tf.reduce_mean(tf.reduce_sum(tf.square(prelogits_mean - centers), axis=1)) # Update centers if False: if not weights in tf.trainable_variables(): weights_target = prelogits_normedactivation label_target = label weights_batch = tf.gather(weights, label_target) diff_centers = weights_batch - weights_target unique_label, unique_idx, unique_count = tf.unique_with_counts(label_target) appear_times = tf.gather(unique_count, unique_idx) appear_times = tf.reshape(appear_times, [-1, 1]) diff_centers = diff_centers / tf.cast(appear_times, tf.float32) diff_centers = alpha * diff_centers centers_update_op = tf.scatter_sub(weights, label_target, diff_centers) with tf.control_dependencies([centers_update_op]): centers_update_op = tf.assign(weights, tf.nn.l2_normalize(weights,dim=1)) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op) tfwatcher.insert('meanp', tf.reduce_mean(prelogits_mean)) return triplet_loss(label_mean, prelogits_mean, m) # return contrastive_loss(label_mean, prelogits_mean, m, normalize=False) # return loss # return am_softmax_imprint(prelogits_mean, label_mean, num_classes, global_step, # weight_decay, learning_rate, scale=scale, m=m, alpha=alpha, reuse=reuse) num_classes_batch = tf.shape(prelogits_mean)[0] dist_mat = euclidean_distance(prelogits_mean, tf.transpose(prelogits_mean), False) diag_mask = tf.eye(num_classes_batch, dtype=tf.bool) non_diag_mask = tf.logical_not(diag_mask) label_mean = tf.reshape(label, [-1, group_size])[:,0] label_mat = tf.equal(label_mean[:,None], label_mean[None,:]) label_mask_pos = tf.logical_and(non_diag_mask, label_mat) label_mask_neg = tf.logical_and(non_diag_mask, tf.logical_not(label_mat)) dist_pos = tf.boolean_mask(dist_mat, label_mask_pos) dist_neg = tf.boolean_mask(dist_mat, label_mask_neg) dist_pos = tf.reshape(dist_pos, [num_classes_batch, -1]) dist_neg = tf.reshape(dist_neg, [num_classes_batch, -1]) # return tf.reduce_mean(dist_pos) # Hard Negative Mining dist_neg = -tf.reduce_max(-dist_neg, axis=1, keep_dims=True) loss = tf.nn.relu(dist_pos - dist_neg + m) loss = tf.reduce_mean(loss, name='DPLoss') return loss
[ "tensorflow.zeros_like", "tensorflow.unique", "tensorflow.sqrt", "tensorflow.contrib.slim.batch_norm", "tensorflow.nn.relu", "tensorflow.logical_and", "tensorflow.stack", "tensorflow.unsorted_segment_sum", "tensorflow.norm", "tensorflow.summary.image", "tensorflow.stop_gradient", "math.sin", ...
[((469, 505), 'tensorflow.reshape', 'tf.reshape', (['x', '[-1, 2, num_features]'], {}), '(x, [-1, 2, num_features])\n', (479, 505), True, 'import tensorflow as tf\n'), ((599, 623), 'tensorflow.where', 'tf.where', (['select', 'x1', 'x2'], {}), '(select, x1, x2)\n', (607, 623), True, 'import tensorflow as tf\n'), ((637, 661), 'tensorflow.where', 'tf.where', (['select', 'x2', 'x1'], {}), '(select, x2, x1)\n', (645, 661), True, 'import tensorflow as tf\n'), ((850, 877), 'tensorflow.split', 'tf.split', (['x', 'groups'], {'axis': '(0)'}), '(x, groups, axis=0)\n', (858, 877), True, 'import tensorflow as tf\n'), ((886, 922), 'tensorflow.reshape', 'tf.reshape', (['x', '[-1, 2, num_features]'], {}), '(x, [-1, 2, num_features])\n', (896, 922), True, 'import tensorflow as tf\n'), ((1016, 1040), 'tensorflow.where', 'tf.where', (['select', 'x1', 'x2'], {}), '(select, x1, x2)\n', (1024, 1040), True, 'import tensorflow as tf\n'), ((1054, 1078), 'tensorflow.where', 'tf.where', (['select', 'x2', 'x1'], {}), '(select, x2, x1)\n', (1062, 1078), True, 'import tensorflow as tf\n'), ((1444, 1495), 'tensorflow.reshape', 'tf.reshape', (['x_normed', '[-1, num_features]'], {'name': 'name'}), '(x_normed, [-1, num_features], name=name)\n', (1454, 1495), True, 'import tensorflow as tf\n'), ((1897, 1936), 'tensorflow.contrib.slim.batch_norm', 'slim.batch_norm', (['x'], {}), '(x, **batch_norm_params)\n', (1912, 1936), True, 'import tensorflow.contrib.slim as slim\n'), ((1952, 1984), 'tensorflow.identity', 'tf.identity', (['x_normed'], {'name': 'name'}), '(x_normed, name=name)\n', (1963, 1984), True, 'import tensorflow as tf\n'), ((14202, 14235), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""gamma"""', 'gamma'], {}), "('gamma', gamma)\n", (14219, 14235), True, 'import tensorflow as tf\n'), ((14240, 14292), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""watch_list"""', "('gamma', gamma)"], {}), "('watch_list', ('gamma', gamma))\n", (14260, 14292), True, 'import tensorflow as tf\n'), ((14839, 14890), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['norm_loss'], {'axis': '(0)', 'name': '"""norm_loss"""'}), "(norm_loss, axis=0, name='norm_loss')\n", (14853, 14890), True, 'import tensorflow as tf\n'), ((20161, 20184), 'tensorflow.reshape', 'tf.reshape', (['label', '[-1]'], {}), '(label, [-1])\n', (20171, 20184), True, 'import tensorflow as tf\n'), ((21012, 21049), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['embedding'], {'axis': '(1)'}), '(embedding, axis=1)\n', (21030, 21049), True, 'import tensorflow as tf\n'), ((21062, 21091), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['w'], {'axis': '(0)'}), '(w, axis=0)\n', (21080, 21091), True, 'import tensorflow as tf\n'), ((21109, 21124), 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), '(x, w)\n', (21118, 21124), True, 'import tensorflow as tf\n'), ((21297, 21333), 'tensorflow.one_hot', 'tf.one_hot', (['label'], {'depth': 'num_classes'}), '(label, depth=num_classes)\n', (21307, 21333), True, 'import tensorflow as tf\n'), ((22413, 22438), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""s"""', '_s'], {}), "('s', _s)\n", (22429, 22438), False, 'from utils import tfwatcher\n'), ((22996, 23007), 'math.cos', 'math.cos', (['m'], {}), '(m)\n', (23004, 23007), False, 'import math\n'), ((23020, 23031), 'math.sin', 'math.sin', (['m'], {}), '(m)\n', (23028, 23031), False, 'import math\n'), ((23080, 23101), 'math.cos', 'math.cos', (['(math.pi - m)'], {}), '(math.pi - m)\n', (23088, 23101), False, 'import math\n'), ((29629, 29666), 'tensorflow.split', 'tf.split', (['prelogits', 'n_groups'], {'axis': '(1)'}), '(prelogits, n_groups, axis=1)\n', (29637, 29666), True, 'import tensorflow as tf\n'), ((29688, 29723), 'tensorflow.split', 'tf.split', (['weights', 'n_groups'], {'axis': '(1)'}), '(weights, n_groups, axis=1)\n', (29696, 29723), True, 'import tensorflow as tf\n'), ((29769, 29937), 'functools.partial', 'partial', (['am_softmax'], {'num_classes': 'num_classes', 'global_step': 'global_step', 'weight_decay': 'weight_decay', 'scale': 'scale', 'm': 'm', 'alpha': 'alpha', 'reduce_mean': '(False)', 'reuse': 'reuse'}), '(am_softmax, num_classes=num_classes, global_step=global_step,\n weight_decay=weight_decay, scale=scale, m=m, alpha=alpha, reduce_mean=\n False, reuse=reuse)\n', (29776, 29937), False, 'from functools import partial\n'), ((30583, 30619), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""wstd"""', 'weight_std'], {}), "('wstd', weight_std)\n", (30599, 30619), False, 'from utils import tfwatcher\n'), ((30624, 30679), 'tensorflow.summary.image', 'tf.summary.image', (['"""weight"""', 'weights[None, :32, :, None]'], {}), "('weight', weights[None, :32, :, None])\n", (30640, 30679), True, 'import tensorflow as tf\n'), ((40934, 40962), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['label'], {}), '(label)\n', (40955, 40962), True, 'import tensorflow as tf\n'), ((40981, 41002), 'tensorflow.size', 'tf.size', (['unique_label'], {}), '(unique_label)\n', (40988, 41002), True, 'import tensorflow as tf\n'), ((41022, 41057), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (41031, 41057), True, 'import tensorflow as tf\n'), ((41077, 41110), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (41087, 41110), True, 'import tensorflow as tf\n'), ((41195, 41263), 'tensorflow.unsorted_segment_sum', 'tf.unsorted_segment_sum', (['weighted_prelogits', 'unique_idx', 'num_centers'], {}), '(weighted_prelogits, unique_idx, num_centers)\n', (41218, 41263), True, 'import tensorflow as tf\n'), ((49466, 49491), 'tensorflow.gather', 'tf.gather', (['centers', 'label'], {}), '(centers, label)\n', (49475, 49491), True, 'import tensorflow as tf\n'), ((49686, 49721), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['features'], {'dim': '(1)'}), '(features, dim=1)\n', (49704, 49721), True, 'import tensorflow as tf\n'), ((49736, 49770), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['targets'], {'dim': '(1)'}), '(targets, dim=1)\n', (49754, 49770), True, 'import tensorflow as tf\n'), ((51204, 51235), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['valid'], {'axis': 'axis'}), '(valid, axis=axis)\n', (51217, 51235), True, 'import tensorflow as tf\n'), ((52057, 52082), 'tensorflow.cast', 'tf.cast', (['mask', 'tf.float32'], {}), '(mask, tf.float32)\n', (52064, 52082), True, 'import tensorflow as tf\n'), ((52099, 52129), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['mask'], {'axis': 'axis'}), '(mask, axis=axis)\n', (52112, 52129), True, 'import tensorflow as tf\n'), ((64890, 64923), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""nll"""', 'loss_nll'], {}), "('nll', loss_nll)\n", (64906, 64923), False, 'from utils import tfwatcher\n'), ((64928, 64960), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""scale"""', 'scale'], {}), "('scale', scale)\n", (64944, 64960), False, 'from utils import tfwatcher\n'), ((65044, 65064), 'tensorflow.exp', 'tf.exp', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (65050, 65064), True, 'import tensorflow as tf\n'), ((65802, 65829), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['dist'], {'axis': '(1)'}), '(dist, axis=1)\n', (65815, 65829), True, 'import tensorflow as tf\n'), ((66071, 66107), 'tensorflow.concat', 'tf.concat', (['[indices, labels]'], {'axis': '(0)'}), '([indices, labels], axis=0)\n', (66080, 66107), True, 'import tensorflow as tf\n'), ((66135, 66153), 'tensorflow.unique', 'tf.unique', (['indices'], {}), '(indices)\n', (66144, 66153), True, 'import tensorflow as tf\n'), ((66169, 66196), 'tensorflow.gather', 'tf.gather', (['weights', 'indices'], {}), '(weights, indices)\n', (66178, 66196), True, 'import tensorflow as tf\n'), ((66210, 66239), 'tensorflow.gather', 'tf.gather', (['unique_idx', 'labels'], {}), '(unique_idx, labels)\n', (66219, 66239), True, 'import tensorflow as tf\n'), ((685, 719), 'tensorflow.stack', 'tf.stack', (['[x1_new, x2_new]'], {'axis': '(1)'}), '([x1_new, x2_new], axis=1)\n', (693, 719), True, 'import tensorflow as tf\n'), ((1102, 1136), 'tensorflow.stack', 'tf.stack', (['[x1_new, x2_new]'], {'axis': '(1)'}), '([x1_new, x2_new], axis=1)\n', (1110, 1136), True, 'import tensorflow as tf\n'), ((1386, 1419), 'tensorflow.reshape', 'tf.reshape', (['x', '[-1, groups, gdim]'], {}), '(x, [-1, groups, gdim])\n', (1396, 1419), True, 'import tensorflow as tf\n'), ((2092, 2138), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['features'], {'dim': '(1)', 'name': 'name'}), '(features, dim=1, name=name)\n', (2110, 2138), True, 'import tensorflow as tf\n'), ((2916, 2950), 'tensorflow.name_scope', 'tf.name_scope', (['"""EuclideanDistance"""'], {}), "('EuclideanDistance')\n", (2929, 2950), True, 'import tensorflow as tf\n'), ((3085, 3100), 'tensorflow.matmul', 'tf.matmul', (['X', 'Y'], {}), '(X, Y)\n', (3094, 3100), True, 'import tensorflow as tf\n'), ((3148, 3170), 'tensorflow.maximum', 'tf.maximum', (['(0.0)', 'diffs'], {}), '(0.0, diffs)\n', (3158, 3170), True, 'import tensorflow as tf\n'), ((3537, 3573), 'tensorflow.name_scope', 'tf.name_scope', (['"""MahalanobisDistance"""'], {}), "('MahalanobisDistance')\n", (3550, 3573), True, 'import tensorflow as tf\n'), ((3714, 3744), 'tensorflow.matmul', 'tf.matmul', (['(X * sigma_sq_inv)', 'Y'], {}), '(X * sigma_sq_inv, Y)\n', (3723, 3744), True, 'import tensorflow as tf\n'), ((3950, 3984), 'tensorflow.name_scope', 'tf.name_scope', (['"""UncertainDistance"""'], {}), "('UncertainDistance')\n", (3963, 3984), True, 'import tensorflow as tf\n'), ((5221, 5240), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (5229, 5240), True, 'import tensorflow as tf\n'), ((5253, 5290), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'reuse'}), '(scope, reuse=reuse)\n', (5270, 5290), True, 'import tensorflow as tf\n'), ((7779, 7798), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (7787, 7798), True, 'import tensorflow as tf\n'), ((7811, 7848), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'reuse'}), '(scope, reuse=reuse)\n', (7828, 7848), True, 'import tensorflow as tf\n'), ((10810, 10828), 'tensorflow.shape', 'tf.shape', (['features'], {}), '(features)\n', (10818, 10828), True, 'import tensorflow as tf\n'), ((10841, 10878), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'reuse'}), '(scope, reuse=reuse)\n', (10858, 10878), True, 'import tensorflow as tf\n'), ((11277, 11303), 'tensorflow.gather', 'tf.gather', (['centers', 'labels'], {}), '(centers, labels)\n', (11286, 11303), True, 'import tensorflow as tf\n'), ((11539, 11568), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['labels'], {}), '(labels)\n', (11560, 11568), True, 'import tensorflow as tf\n'), ((11592, 11627), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (11601, 11627), True, 'import tensorflow as tf\n'), ((11651, 11684), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (11661, 11684), True, 'import tensorflow as tf\n'), ((11829, 11874), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['centers', 'labels', 'diff_centers'], {}), '(centers, labels, diff_centers)\n', (11843, 11874), True, 'import tensorflow as tf\n'), ((11883, 11947), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (11903, 11947), True, 'import tensorflow as tf\n'), ((12097, 12115), 'tensorflow.shape', 'tf.shape', (['features'], {}), '(features)\n', (12105, 12115), True, 'import tensorflow as tf\n'), ((12128, 12165), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'reuse'}), '(scope, reuse=reuse)\n', (12145, 12165), True, 'import tensorflow as tf\n'), ((12651, 12669), 'tensorflow.shape', 'tf.shape', (['features'], {}), '(features)\n', (12659, 12669), True, 'import tensorflow as tf\n'), ((12682, 12706), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), '(scope)\n', (12699, 12706), True, 'import tensorflow as tf\n'), ((13106, 13146), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Logits"""'], {'reuse': 'reuse'}), "('Logits', reuse=reuse)\n", (13123, 13146), True, 'import tensorflow as tf\n'), ((13713, 13747), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(0)'}), '(weights, dim=0)\n', (13731, 13747), True, 'import tensorflow as tf\n'), ((13775, 13811), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (13793, 13811), True, 'import tensorflow as tf\n'), ((14084, 14159), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'label', 'logits': 'logits'}), '(labels=label, logits=logits)\n', (14130, 14159), True, 'import tensorflow as tf\n'), ((14382, 14424), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""NormLoss"""'], {'reuse': 'reuse'}), "('NormLoss', reuse=reuse)\n", (14399, 14424), True, 'import tensorflow as tf\n'), ((14685, 14705), 'tensorflow.square', 'tf.square', (['prelogits'], {}), '(prelogits)\n', (14694, 14705), True, 'import tensorflow as tf\n'), ((15201, 15220), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (15209, 15220), True, 'import tensorflow as tf\n'), ((15534, 15582), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""AngularSoftmax"""'], {'reuse': 'reuse'}), "('AngularSoftmax', reuse=reuse)\n", (15551, 15582), True, 'import tensorflow as tf\n'), ((16227, 16261), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(0)'}), '(weights, dim=0)\n', (16245, 16261), True, 'import tensorflow as tf\n'), ((16289, 16325), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (16307, 16325), True, 'import tensorflow as tf\n'), ((16380, 16423), 'tensorflow.matmul', 'tf.matmul', (['prelogits_normed', 'weights_normed'], {}), '(prelogits_normed, weights_normed)\n', (16389, 16423), True, 'import tensorflow as tf\n'), ((16505, 16523), 'tensorflow.acos', 'tf.acos', (['cos_theta'], {}), '(cos_theta)\n', (16512, 16523), True, 'import tensorflow as tf\n'), ((16587, 16619), 'tensorflow.floor', 'tf.floor', (['(m * theta / 3.14159265)'], {}), '(m * theta / 3.14159265)\n', (16595, 16619), True, 'import tensorflow as tf\n'), ((16889, 16914), 'tensorflow.assign', 'tf.assign', (['lamb', 'lamb_new'], {}), '(lamb, lamb_new)\n', (16898, 16914), True, 'import tensorflow as tf\n'), ((17420, 17470), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""watch_list"""', "('lamb', lamb)"], {}), "('watch_list', ('lamb', lamb))\n", (17440, 17470), True, 'import tensorflow as tf\n'), ((17916, 17935), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (17924, 17935), True, 'import tensorflow as tf\n'), ((17948, 17985), 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'reuse'}), '(scope, reuse=reuse)\n', (17965, 17985), True, 'import tensorflow as tf\n'), ((18565, 18616), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""classifier_weights"""', 'weights'], {}), "('classifier_weights', weights)\n", (18585, 18616), True, 'import tensorflow as tf\n'), ((18678, 18712), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(0)'}), '(weights, dim=0)\n', (18696, 18712), True, 'import tensorflow as tf\n'), ((18740, 18776), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (18758, 18776), True, 'import tensorflow as tf\n'), ((18892, 18940), 'tensorflow.one_hot', 'tf.one_hot', (['label', 'num_classes'], {'dtype': 'tf.float32'}), '(label, num_classes, dtype=tf.float32)\n', (18902, 18940), True, 'import tensorflow as tf\n'), ((18966, 18993), 'tensorflow.cast', 'tf.cast', (['label_mat', 'tf.bool'], {}), '(label_mat, tf.bool)\n', (18973, 18993), True, 'import tensorflow as tf\n'), ((19019, 19049), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos'], {}), '(label_mask_pos)\n', (19033, 19049), True, 'import tensorflow as tf\n'), ((19070, 19113), 'tensorflow.matmul', 'tf.matmul', (['prelogits_normed', 'weights_normed'], {}), '(prelogits_normed, weights_normed)\n', (19079, 19113), True, 'import tensorflow as tf\n'), ((19135, 19176), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_pos'], {}), '(dist_mat, label_mask_pos)\n', (19150, 19176), True, 'import tensorflow as tf\n'), ((19198, 19239), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_neg'], {}), '(dist_mat, label_mask_neg)\n', (19213, 19239), True, 'import tensorflow as tf\n'), ((19533, 19573), 'tensorflow.reshape', 'tf.reshape', (['logits_pos', '[batch_size, -1]'], {}), '(logits_pos, [batch_size, -1])\n', (19543, 19573), True, 'import tensorflow as tf\n'), ((19596, 19636), 'tensorflow.reshape', 'tf.reshape', (['logits_neg', '[batch_size, -1]'], {}), '(logits_neg, [batch_size, -1])\n', (19606, 19636), True, 'import tensorflow as tf\n'), ((19809, 19850), 'tensorflow.nn.relu', 'tf.nn.relu', (['(m + _logits_neg - _logits_pos)'], {}), '(m + _logits_neg - _logits_pos)\n', (19819, 19850), True, 'import tensorflow as tf\n'), ((19962, 19994), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""scale"""', 'scale'], {}), "('scale', scale)\n", (19978, 19994), False, 'from utils import tfwatcher\n'), ((20247, 20279), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""adacos_loss"""'], {}), "('adacos_loss')\n", (20264, 20279), True, 'import tensorflow as tf\n'), ((21403, 21422), 'tensorflow.exp', 'tf.exp', (['(_s * logits)'], {}), '(_s * logits)\n', (21409, 21422), True, 'import tensorflow as tf\n'), ((21453, 21474), 'tensorflow.zeros_like', 'tf.zeros_like', (['logits'], {}), '(logits)\n', (21466, 21474), True, 'import tensorflow as tf\n'), ((21507, 21535), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['b_avg'], {'axis': '(1)'}), '(b_avg, axis=1)\n', (21520, 21535), True, 'import tensorflow as tf\n'), ((22180, 22215), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_s]'], {}), '([update_s])\n', (22203, 22215), True, 'import tensorflow as tf\n'), ((22961, 22980), 'tensorflow.shape', 'tf.shape', (['embedding'], {}), '(embedding)\n', (22969, 22980), True, 'import tensorflow as tf\n'), ((23129, 23162), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""arcface_loss"""'], {}), "('arcface_loss')\n", (23146, 23162), True, 'import tensorflow as tf\n'), ((23934, 23971), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['embedding'], {'axis': '(1)'}), '(embedding, axis=1)\n', (23952, 23971), True, 'import tensorflow as tf\n'), ((23990, 24025), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'axis': '(0)'}), '(weights, axis=0)\n', (24008, 24025), True, 'import tensorflow as tf\n'), ((24065, 24108), 'tensorflow.matmul', 'tf.matmul', (['embedding', 'weights'], {'name': '"""cos_t"""'}), "(embedding, weights, name='cos_t')\n", (24074, 24108), True, 'import tensorflow as tf\n'), ((24126, 24156), 'tensorflow.square', 'tf.square', (['cos_t'], {'name': '"""cos_2"""'}), "(cos_t, name='cos_2')\n", (24135, 24156), True, 'import tensorflow as tf\n'), ((24174, 24212), 'tensorflow.subtract', 'tf.subtract', (['(1.0)', 'cos_t2'], {'name': '"""sin_2"""'}), "(1.0, cos_t2, name='sin_2')\n", (24185, 24212), True, 'import tensorflow as tf\n'), ((24228, 24265), 'tensorflow.sqrt', 'tf.sqrt', (['(sin_t2 + 1e-06)'], {'name': '"""sin_t"""'}), "(sin_t2 + 1e-06, name='sin_t')\n", (24235, 24265), True, 'import tensorflow as tf\n'), ((24577, 24605), 'tensorflow.greater', 'tf.greater', (['cos_t', 'threshold'], {}), '(cos_t, threshold)\n', (24587, 24605), True, 'import tensorflow as tf\n'), ((24666, 24699), 'tensorflow.where', 'tf.where', (['cond', 'cos_mt', 'keep_vals'], {}), '(cond, cos_mt, keep_vals)\n', (24674, 24699), True, 'import tensorflow as tf\n'), ((24716, 24774), 'tensorflow.one_hot', 'tf.one_hot', (['labels'], {'depth': 'num_classes', 'name': '"""one_hot_mask"""'}), "(labels, depth=num_classes, name='one_hot_mask')\n", (24726, 24774), True, 'import tensorflow as tf\n'), ((24790, 24812), 'tensorflow.cast', 'tf.cast', (['mask', 'tf.bool'], {}), '(mask, tf.bool)\n', (24797, 24812), True, 'import tensorflow as tf\n'), ((24924, 24960), 'tensorflow.where', 'tf.where', (['mask', 'cos_mt_temp', 's_cos_t'], {}), '(mask, cos_mt_temp, s_cos_t)\n', (24932, 24960), True, 'import tensorflow as tf\n'), ((25481, 25500), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (25489, 25500), True, 'import tensorflow as tf\n'), ((25513, 25557), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""AM-Softmax"""'], {'reuse': 'reuse'}), "('AM-Softmax', reuse=reuse)\n", (25530, 25557), True, 'import tensorflow as tf\n'), ((26135, 26186), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""classifier_weights"""', 'weights'], {}), "('classifier_weights', weights)\n", (26155, 26186), True, 'import tensorflow as tf\n'), ((26251, 26287), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (26269, 26287), True, 'import tensorflow as tf\n'), ((26313, 26347), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(1)'}), '(weights, dim=1)\n', (26331, 26347), True, 'import tensorflow as tf\n'), ((26429, 26477), 'tensorflow.one_hot', 'tf.one_hot', (['label', 'num_classes'], {'dtype': 'tf.float32'}), '(label, num_classes, dtype=tf.float32)\n', (26439, 26477), True, 'import tensorflow as tf\n'), ((26508, 26540), 'tensorflow.cast', 'tf.cast', (['label_mat_glob', 'tf.bool'], {}), '(label_mat_glob, tf.bool)\n', (26515, 26540), True, 'import tensorflow as tf\n'), ((26571, 26606), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos_glob'], {}), '(label_mask_pos_glob)\n', (26585, 26606), True, 'import tensorflow as tf\n'), ((26807, 26856), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_glob', 'label_mask_pos_glob'], {}), '(logits_glob, label_mask_pos_glob)\n', (26822, 26856), True, 'import tensorflow as tf\n'), ((26878, 26927), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_glob', 'label_mask_neg_glob'], {}), '(logits_glob, label_mask_neg_glob)\n', (26893, 26927), True, 'import tensorflow as tf\n'), ((27220, 27260), 'tensorflow.reshape', 'tf.reshape', (['logits_pos', '[batch_size, -1]'], {}), '(logits_pos, [batch_size, -1])\n', (27230, 27260), True, 'import tensorflow as tf\n'), ((27282, 27322), 'tensorflow.reshape', 'tf.reshape', (['logits_neg', '[batch_size, -1]'], {}), '(logits_neg, [batch_size, -1])\n', (27292, 27322), True, 'import tensorflow as tf\n'), ((27490, 27533), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['(m + logits_neg - logits_pos)'], {}), '(m + logits_neg - logits_pos)\n', (27504, 27533), True, 'import tensorflow as tf\n'), ((27549, 27589), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss_'], {'name': '"""am_softmax"""'}), "(loss_, name='am_softmax')\n", (27563, 27589), True, 'import tensorflow as tf\n'), ((28997, 29029), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""scale"""', 'scale'], {}), "('scale', scale)\n", (29013, 29029), False, 'from utils import tfwatcher\n'), ((29588, 29603), 'tensorflow.exp', 'tf.exp', (['weights'], {}), '(weights)\n', (29594, 29603), True, 'import tensorflow as tf\n'), ((30281, 30311), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['weights'], {'axis': '(0)'}), '(weights, axis=0)\n', (30294, 30311), True, 'import tensorflow as tf\n'), ((30468, 30504), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""wreg"""', 'weight_reg'], {}), "('wreg', weight_reg)\n", (30484, 30504), False, 'from utils import tfwatcher\n'), ((30885, 30904), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (30893, 30904), True, 'import tensorflow as tf\n'), ((30917, 30958), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""EucLoss"""'], {'reuse': 'reuse'}), "('EucLoss', reuse=reuse)\n", (30934, 30958), True, 'import tensorflow as tf\n'), ((34065, 34084), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (34073, 34084), True, 'import tensorflow as tf\n'), ((34097, 34143), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""SplitSoftmax"""'], {'reuse': 'reuse'}), "('SplitSoftmax', reuse=reuse)\n", (34114, 34143), True, 'import tensorflow as tf\n'), ((35100, 35134), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(1)'}), '(weights, dim=1)\n', (35118, 35134), True, 'import tensorflow as tf\n'), ((35201, 35237), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (35219, 35237), True, 'import tensorflow as tf\n'), ((35459, 35507), 'tensorflow.one_hot', 'tf.one_hot', (['label', 'num_classes'], {'dtype': 'tf.float32'}), '(label, num_classes, dtype=tf.float32)\n', (35469, 35507), True, 'import tensorflow as tf\n'), ((35538, 35570), 'tensorflow.cast', 'tf.cast', (['label_mat_glob', 'tf.bool'], {}), '(label_mat_glob, tf.bool)\n', (35545, 35570), True, 'import tensorflow as tf\n'), ((35601, 35636), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos_glob'], {}), '(label_mask_pos_glob)\n', (35615, 35636), True, 'import tensorflow as tf\n'), ((36168, 36219), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat_glob', 'label_mask_pos_glob'], {}), '(dist_mat_glob, label_mask_pos_glob)\n', (36183, 36219), True, 'import tensorflow as tf\n'), ((36244, 36295), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat_glob', 'label_mask_neg_glob'], {}), '(dist_mat_glob, label_mask_neg_glob)\n', (36259, 36295), True, 'import tensorflow as tf\n'), ((36366, 36415), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_glob', 'label_mask_pos_glob'], {}), '(logits_glob, label_mask_pos_glob)\n', (36381, 36415), True, 'import tensorflow as tf\n'), ((36442, 36491), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_glob', 'label_mask_neg_glob'], {}), '(logits_glob, label_mask_neg_glob)\n', (36457, 36491), True, 'import tensorflow as tf\n'), ((36560, 36584), 'tensorflow.expand_dims', 'tf.expand_dims', (['label', '(1)'], {}), '(label, 1)\n', (36574, 36584), True, 'import tensorflow as tf\n'), ((36699, 36732), 'tensorflow.cast', 'tf.cast', (['label_mat_batch', 'tf.bool'], {}), '(label_mat_batch, tf.bool)\n', (36706, 36732), True, 'import tensorflow as tf\n'), ((36764, 36800), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos_batch'], {}), '(label_mask_pos_batch)\n', (36778, 36800), True, 'import tensorflow as tf\n'), ((36909, 36960), 'tensorflow.logical_and', 'tf.logical_and', (['label_mask_pos_batch', 'mask_non_diag'], {}), '(label_mask_pos_batch, mask_non_diag)\n', (36923, 36960), True, 'import tensorflow as tf\n'), ((37175, 37228), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat_batch', 'label_mask_pos_batch'], {}), '(dist_mat_batch, label_mask_pos_batch)\n', (37190, 37228), True, 'import tensorflow as tf\n'), ((37254, 37307), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat_batch', 'label_mask_neg_batch'], {}), '(dist_mat_batch, label_mask_neg_batch)\n', (37269, 37307), True, 'import tensorflow as tf\n'), ((37382, 37433), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_batch', 'label_mask_pos_batch'], {}), '(logits_batch, label_mask_pos_batch)\n', (37397, 37433), True, 'import tensorflow as tf\n'), ((37461, 37512), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_batch', 'label_mask_neg_batch'], {}), '(logits_batch, label_mask_neg_batch)\n', (37476, 37512), True, 'import tensorflow as tf\n'), ((38188, 38228), 'tensorflow.reshape', 'tf.reshape', (['logits_pos', '[batch_size, -1]'], {}), '(logits_pos, [batch_size, -1])\n', (38198, 38228), True, 'import tensorflow as tf\n'), ((38250, 38290), 'tensorflow.reshape', 'tf.reshape', (['logits_neg', '[batch_size, -1]'], {}), '(logits_neg, [batch_size, -1])\n', (38260, 38290), True, 'import tensorflow as tf\n'), ((38611, 38639), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(g * dist_pos)'], {}), '(g * dist_pos)\n', (38625, 38639), True, 'import tensorflow as tf\n'), ((39518, 39582), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(loss_gb + loss_pos + loss_neg)'], {'name': '"""split_loss"""'}), "(loss_gb + loss_pos + loss_neg, name='split_loss')\n", (39532, 39582), True, 'import tensorflow as tf\n'), ((40599, 40632), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""gamma"""', 'gamma'], {}), "('gamma', gamma)\n", (40616, 40632), True, 'import tensorflow as tf\n'), ((40685, 40716), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""beta"""', 'beta'], {}), "('beta', beta)\n", (40702, 40716), True, 'import tensorflow as tf\n'), ((40725, 40757), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""gamma"""', 'gamma'], {}), "('gamma', gamma)\n", (40741, 40757), False, 'from utils import tfwatcher\n'), ((40766, 40796), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""beta"""', 'beta'], {}), "('beta', beta)\n", (40782, 40796), False, 'from utils import tfwatcher\n'), ((41147, 41180), 'tensorflow.cast', 'tf.cast', (['appear_times', 'tf.float32'], {}), '(appear_times, tf.float32)\n', (41154, 41180), True, 'import tensorflow as tf\n'), ((41508, 41527), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (41516, 41527), True, 'import tensorflow as tf\n'), ((41540, 41582), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""PairLoss"""'], {'reuse': 'reuse'}), "('PairLoss', reuse=reuse)\n", (41557, 41582), True, 'import tensorflow as tf\n'), ((42504, 42538), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(1)'}), '(weights, dim=1)\n', (42522, 42538), True, 'import tensorflow as tf\n'), ((42566, 42602), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (42584, 42602), True, 'import tensorflow as tf\n'), ((43254, 43290), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos_batch'], {}), '(label_mask_pos_batch)\n', (43268, 43290), True, 'import tensorflow as tf\n'), ((43316, 43369), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat_batch', 'label_mask_pos_batch'], {}), '(dist_mat_batch, label_mask_pos_batch)\n', (43331, 43369), True, 'import tensorflow as tf\n'), ((43395, 43448), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat_batch', 'label_mask_neg_batch'], {}), '(dist_mat_batch, label_mask_neg_batch)\n', (43410, 43448), True, 'import tensorflow as tf\n'), ((43477, 43532), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_mat_batch', 'label_mask_pos_batch'], {}), '(logits_mat_batch, label_mask_pos_batch)\n', (43492, 43532), True, 'import tensorflow as tf\n'), ((43560, 43615), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_mat_batch', 'label_mask_neg_batch'], {}), '(logits_mat_batch, label_mask_neg_batch)\n', (43575, 43615), True, 'import tensorflow as tf\n'), ((44394, 44433), 'tensorflow.reshape', 'tf.reshape', (['logits_pos', '[num_pairs, -1]'], {}), '(logits_pos, [num_pairs, -1])\n', (44404, 44433), True, 'import tensorflow as tf\n'), ((44458, 44497), 'tensorflow.reshape', 'tf.reshape', (['logits_neg', '[num_pairs, -1]'], {}), '(logits_neg, [num_pairs, -1])\n', (44468, 44497), True, 'import tensorflow as tf\n'), ((44522, 44561), 'tensorflow.reshape', 'tf.reshape', (['logits_neg', '[-1, num_pairs]'], {}), '(logits_neg, [-1, num_pairs])\n', (44532, 44561), True, 'import tensorflow as tf\n'), ((44765, 44805), 'tensorflow.maximum', 'tf.maximum', (['_logits_neg_1', '_logits_neg_2'], {}), '(_logits_neg_1, _logits_neg_2)\n', (44775, 44805), True, 'import tensorflow as tf\n'), ((45126, 45161), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(loss_pos + loss_neg)'], {}), '(loss_pos + loss_neg)\n', (45140, 45161), True, 'import tensorflow as tf\n'), ((45177, 45212), 'tensorflow.identity', 'tf.identity', (['loss'], {'name': '"""pair_loss"""'}), "(loss, name='pair_loss')\n", (45188, 45212), True, 'import tensorflow as tf\n'), ((45251, 45282), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""ploss"""', 'loss'], {}), "('ploss', loss)\n", (45267, 45282), False, 'from utils import tfwatcher\n'), ((45311, 45344), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""gamma"""', 'gamma'], {}), "('gamma', gamma)\n", (45328, 45344), True, 'import tensorflow as tf\n'), ((45353, 45386), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""alpha"""', 'alpha'], {}), "('alpha', alpha)\n", (45370, 45386), True, 'import tensorflow as tf\n'), ((45395, 45426), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""beta"""', 'beta'], {}), "('beta', beta)\n", (45412, 45426), True, 'import tensorflow as tf\n'), ((45435, 45477), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""dist_pos"""', 'dist_pos'], {}), "('dist_pos', dist_pos)\n", (45455, 45477), True, 'import tensorflow as tf\n'), ((45486, 45528), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""dist_neg"""', 'dist_neg'], {}), "('dist_neg', dist_neg)\n", (45506, 45528), True, 'import tensorflow as tf\n'), ((45538, 45570), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""gamma"""', 'gamma'], {}), "('gamma', gamma)\n", (45554, 45570), False, 'from utils import tfwatcher\n'), ((45883, 45925), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""PairLoss"""'], {'reuse': 'reuse'}), "('PairLoss', reuse=reuse)\n", (45900, 45925), True, 'import tensorflow as tf\n'), ((46450, 46490), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits_tmp'], {'dim': '(1)'}), '(prelogits_tmp, dim=1)\n', (46468, 46490), True, 'import tensorflow as tf\n'), ((46515, 46555), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits_pro'], {'dim': '(1)'}), '(prelogits_pro, dim=1)\n', (46533, 46555), True, 'import tensorflow as tf\n'), ((47201, 47237), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos_batch'], {}), '(label_mask_pos_batch)\n', (47215, 47237), True, 'import tensorflow as tf\n'), ((47260, 47315), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_mat_batch', 'label_mask_pos_batch'], {}), '(logits_mat_batch, label_mask_pos_batch)\n', (47275, 47315), True, 'import tensorflow as tf\n'), ((47339, 47394), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_mat_batch', 'label_mask_neg_batch'], {}), '(logits_mat_batch, label_mask_neg_batch)\n', (47354, 47394), True, 'import tensorflow as tf\n'), ((48030, 48069), 'tensorflow.reshape', 'tf.reshape', (['logits_pos', '[num_pairs, -1]'], {}), '(logits_pos, [num_pairs, -1])\n', (48040, 48069), True, 'import tensorflow as tf\n'), ((48094, 48135), 'tensorflow.reshape', 'tf.reshape', (['logits_neg_1', '[num_pairs, -1]'], {}), '(logits_neg_1, [num_pairs, -1])\n', (48104, 48135), True, 'import tensorflow as tf\n'), ((48160, 48201), 'tensorflow.reshape', 'tf.reshape', (['logits_neg_2', '[num_pairs, -1]'], {}), '(logits_neg_2, [num_pairs, -1])\n', (48170, 48201), True, 'import tensorflow as tf\n'), ((48380, 48420), 'tensorflow.maximum', 'tf.maximum', (['_logits_neg_1', '_logits_neg_2'], {}), '(_logits_neg_1, _logits_neg_2)\n', (48390, 48420), True, 'import tensorflow as tf\n'), ((48972, 49003), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(loss_1 + loss_2)'], {}), '(loss_1 + loss_2)\n', (48986, 49003), True, 'import tensorflow as tf\n'), ((49019, 49054), 'tensorflow.identity', 'tf.identity', (['loss'], {'name': '"""pair_loss"""'}), "(loss, name='pair_loss')\n", (49030, 49054), True, 'import tensorflow as tf\n'), ((49113, 49146), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""gamma"""', 'gamma'], {}), "('gamma', gamma)\n", (49130, 49146), True, 'import tensorflow as tf\n'), ((49155, 49188), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""alpha"""', 'alpha'], {}), "('alpha', alpha)\n", (49172, 49188), True, 'import tensorflow as tf\n'), ((49197, 49228), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""beta"""', 'beta'], {}), "('beta', beta)\n", (49214, 49228), True, 'import tensorflow as tf\n'), ((49237, 49282), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""dist_pos"""', '_logits_pos'], {}), "('dist_pos', _logits_pos)\n", (49257, 49282), True, 'import tensorflow as tf\n'), ((49291, 49336), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""dist_neg"""', '_logits_neg'], {}), "('dist_neg', _logits_neg)\n", (49311, 49336), True, 'import tensorflow as tf\n'), ((49346, 49378), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""gamma"""', 'gamma'], {}), "('gamma', gamma)\n", (49362, 49378), False, 'from utils import tfwatcher\n'), ((49954, 49982), 'tensorflow.name_scope', 'tf.name_scope', (['"""TripletLoss"""'], {}), "('TripletLoss')\n", (49967, 49982), True, 'import tensorflow as tf\n'), ((50191, 50224), 'tensorflow.eye', 'tf.eye', (['batch_size'], {'dtype': 'tf.bool'}), '(batch_size, dtype=tf.bool)\n', (50197, 50224), True, 'import tensorflow as tf\n'), ((50249, 50274), 'tensorflow.logical_not', 'tf.logical_not', (['diag_mask'], {}), '(diag_mask)\n', (50263, 50274), True, 'import tensorflow as tf\n'), ((50393, 50435), 'tensorflow.equal', 'tf.equal', (['labels[:, None]', 'labels[None, :]'], {}), '(labels[:, None], labels[None, :])\n', (50401, 50435), True, 'import tensorflow as tf\n'), ((50459, 50499), 'tensorflow.logical_and', 'tf.logical_and', (['non_diag_mask', 'label_mat'], {}), '(non_diag_mask, label_mat)\n', (50473, 50499), True, 'import tensorflow as tf\n'), ((50611, 50652), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_pos'], {}), '(dist_mat, label_mask_pos)\n', (50626, 50652), True, 'import tensorflow as tf\n'), ((50673, 50714), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_neg'], {}), '(dist_mat, label_mask_neg)\n', (50688, 50714), True, 'import tensorflow as tf\n'), ((50743, 50781), 'tensorflow.reshape', 'tf.reshape', (['dist_pos', '[batch_size, -1]'], {}), '(dist_pos, [batch_size, -1])\n', (50753, 50781), True, 'import tensorflow as tf\n'), ((50801, 50839), 'tensorflow.reshape', 'tf.reshape', (['dist_neg', '[batch_size, -1]'], {}), '(dist_neg, [batch_size, -1])\n', (50811, 50839), True, 'import tensorflow as tf\n'), ((50966, 51006), 'tensorflow.nn.relu', 'tf.nn.relu', (['(dist_pos - dist_neg + margin)'], {}), '(dist_pos - dist_neg + margin)\n', (50976, 51006), True, 'import tensorflow as tf\n'), ((51022, 51062), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {'name': '"""TripletLoss"""'}), "(loss, name='TripletLoss')\n", (51036, 51062), True, 'import tensorflow as tf\n'), ((51149, 51172), 'tensorflow.greater', 'tf.greater', (['losses', '(0.0)'], {}), '(losses, 0.0)\n', (51159, 51172), True, 'import tensorflow as tf\n'), ((51247, 51279), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['losses'], {'axis': 'axis'}), '(losses, axis=axis)\n', (51260, 51279), True, 'import tensorflow as tf\n'), ((51385, 51419), 'tensorflow.name_scope', 'tf.name_scope', (['"""UncertainPairLoss"""'], {}), "('UncertainPairLoss')\n", (51398, 51419), True, 'import tensorflow as tf\n'), ((51514, 51551), 'tensorflow.reshape', 'tf.reshape', (['mu', '[-1, 2, num_features]'], {}), '(mu, [-1, 2, num_features])\n', (51524, 51551), True, 'import tensorflow as tf\n'), ((52141, 52180), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(tensor * mask)'], {'axis': 'axis'}), '(tensor * mask, axis=axis)\n', (52154, 52180), True, 'import tensorflow as tf\n'), ((52287, 52322), 'tensorflow.name_scope', 'tf.name_scope', (['"""AvgHardTripletLoss"""'], {}), "('AvgHardTripletLoss')\n", (52300, 52322), True, 'import tensorflow as tf\n'), ((52622, 52655), 'tensorflow.eye', 'tf.eye', (['batch_size'], {'dtype': 'tf.bool'}), '(batch_size, dtype=tf.bool)\n', (52628, 52655), True, 'import tensorflow as tf\n'), ((52680, 52705), 'tensorflow.logical_not', 'tf.logical_not', (['diag_mask'], {}), '(diag_mask)\n', (52694, 52705), True, 'import tensorflow as tf\n'), ((52726, 52768), 'tensorflow.equal', 'tf.equal', (['labels[:, None]', 'labels[None, :]'], {}), '(labels[:, None], labels[None, :])\n', (52734, 52768), True, 'import tensorflow as tf\n'), ((52792, 52832), 'tensorflow.logical_and', 'tf.logical_and', (['non_diag_mask', 'label_mat'], {}), '(non_diag_mask, label_mat)\n', (52806, 52832), True, 'import tensorflow as tf\n'), ((52858, 52883), 'tensorflow.logical_not', 'tf.logical_not', (['label_mat'], {}), '(label_mat)\n', (52872, 52883), True, 'import tensorflow as tf\n'), ((52974, 53008), 'tensorflow.tile', 'tf.tile', (['dist_mat', '[1, batch_size]'], {}), '(dist_mat, [1, batch_size])\n', (52981, 53008), True, 'import tensorflow as tf\n'), ((53035, 53100), 'tensorflow.reshape', 'tf.reshape', (['dist_tensor_neg', '[batch_size, batch_size, batch_size]'], {}), '(dist_tensor_neg, [batch_size, batch_size, batch_size])\n', (53045, 53100), True, 'import tensorflow as tf\n'), ((53128, 53168), 'tensorflow.tile', 'tf.tile', (['label_mask_neg', '[1, batch_size]'], {}), '(label_mask_neg, [1, batch_size])\n', (53135, 53168), True, 'import tensorflow as tf\n'), ((53196, 53262), 'tensorflow.reshape', 'tf.reshape', (['label_tensor_neg', '[batch_size, batch_size, batch_size]'], {}), '(label_tensor_neg, [batch_size, batch_size, batch_size])\n', (53206, 53262), True, 'import tensorflow as tf\n'), ((53279, 53338), 'tensorflow.nn.relu', 'tf.nn.relu', (['(dist_mat[:, :, None] - dist_tensor_neg + margin)'], {}), '(dist_mat[:, :, None] - dist_tensor_neg + margin)\n', (53289, 53338), True, 'import tensorflow as tf\n'), ((53609, 53646), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['loss', 'label_mask_pos'], {}), '(loss, label_mask_pos)\n', (53624, 53646), True, 'import tensorflow as tf\n'), ((53662, 53682), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (53676, 53682), True, 'import tensorflow as tf\n'), ((53818, 53846), 'tensorflow.name_scope', 'tf.name_scope', (['"""TripletLoss"""'], {}), "('TripletLoss')\n", (53831, 53846), True, 'import tensorflow as tf\n'), ((54055, 54088), 'tensorflow.eye', 'tf.eye', (['batch_size'], {'dtype': 'tf.bool'}), '(batch_size, dtype=tf.bool)\n', (54061, 54088), True, 'import tensorflow as tf\n'), ((54113, 54138), 'tensorflow.logical_not', 'tf.logical_not', (['diag_mask'], {}), '(diag_mask)\n', (54127, 54138), True, 'import tensorflow as tf\n'), ((54159, 54179), 'tensorflow.exp', 'tf.exp', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (54165, 54179), True, 'import tensorflow as tf\n'), ((54435, 54477), 'tensorflow.equal', 'tf.equal', (['labels[:, None]', 'labels[None, :]'], {}), '(labels[:, None], labels[None, :])\n', (54443, 54477), True, 'import tensorflow as tf\n'), ((54501, 54541), 'tensorflow.logical_and', 'tf.logical_and', (['non_diag_mask', 'label_mat'], {}), '(non_diag_mask, label_mat)\n', (54515, 54541), True, 'import tensorflow as tf\n'), ((58253, 58285), 'tensorflow.name_scope', 'tf.name_scope', (['"""ContrastiveLoss"""'], {}), "('ContrastiveLoss')\n", (58266, 58285), True, 'import tensorflow as tf\n'), ((58490, 58523), 'tensorflow.eye', 'tf.eye', (['batch_size'], {'dtype': 'tf.bool'}), '(batch_size, dtype=tf.bool)\n', (58496, 58523), True, 'import tensorflow as tf\n'), ((58548, 58573), 'tensorflow.logical_not', 'tf.logical_not', (['diag_mask'], {}), '(diag_mask)\n', (58562, 58573), True, 'import tensorflow as tf\n'), ((58692, 58734), 'tensorflow.equal', 'tf.equal', (['labels[:, None]', 'labels[None, :]'], {}), '(labels[:, None], labels[None, :])\n', (58700, 58734), True, 'import tensorflow as tf\n'), ((58758, 58798), 'tensorflow.logical_and', 'tf.logical_and', (['non_diag_mask', 'label_mat'], {}), '(non_diag_mask, label_mat)\n', (58772, 58798), True, 'import tensorflow as tf\n'), ((58910, 58951), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_pos'], {}), '(dist_mat, label_mask_pos)\n', (58925, 58951), True, 'import tensorflow as tf\n'), ((58972, 59013), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_neg'], {}), '(dist_mat, label_mask_neg)\n', (58987, 59013), True, 'import tensorflow as tf\n'), ((59254, 59278), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['dist_pos'], {}), '(dist_pos)\n', (59268, 59278), True, 'import tensorflow as tf\n'), ((59368, 59425), 'tensorflow.identity', 'tf.identity', (['(loss_pos + loss_neg)'], {'name': '"""contrastive_loss"""'}), "(loss_pos + loss_neg, name='contrastive_loss')\n", (59379, 59425), True, 'import tensorflow as tf\n'), ((59627, 59646), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (59635, 59646), True, 'import tensorflow as tf\n'), ((59659, 59702), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""NPairLoss"""'], {'reuse': 'reuse'}), "('NPairLoss', reuse=reuse)\n", (59676, 59702), True, 'import tensorflow as tf\n'), ((60000, 60036), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (60018, 60036), True, 'import tensorflow as tf\n'), ((60098, 60123), 'tensorflow.expand_dims', 'tf.expand_dims', (['labels', '(1)'], {}), '(labels, 1)\n', (60112, 60123), True, 'import tensorflow as tf\n'), ((60214, 60241), 'tensorflow.cast', 'tf.cast', (['label_mat', 'tf.bool'], {}), '(label_mat, tf.bool)\n', (60221, 60241), True, 'import tensorflow as tf\n'), ((60267, 60297), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos'], {}), '(label_mask_pos)\n', (60281, 60297), True, 'import tensorflow as tf\n'), ((60400, 60445), 'tensorflow.logical_and', 'tf.logical_and', (['label_mask_pos', 'mask_non_diag'], {}), '(label_mask_pos, mask_non_diag)\n', (60414, 60445), True, 'import tensorflow as tf\n'), ((60622, 60665), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_mat', 'label_mask_pos'], {}), '(logits_mat, label_mask_pos)\n', (60637, 60665), True, 'import tensorflow as tf\n'), ((60687, 60730), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['logits_mat', 'label_mask_neg'], {}), '(logits_mat, label_mask_neg)\n', (60702, 60730), True, 'import tensorflow as tf\n'), ((60935, 60975), 'tensorflow.reshape', 'tf.reshape', (['logits_pos', '[batch_size, -1]'], {}), '(logits_pos, [batch_size, -1])\n', (60945, 60975), True, 'import tensorflow as tf\n'), ((60997, 61037), 'tensorflow.reshape', 'tf.reshape', (['logits_neg', '[batch_size, -1]'], {}), '(logits_neg, [batch_size, -1])\n', (61007, 61037), True, 'import tensorflow as tf\n'), ((61205, 61248), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['(m + logits_neg - logits_pos)'], {}), '(m + logits_neg - logits_pos)\n', (61219, 61248), True, 'import tensorflow as tf\n'), ((61264, 61299), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss_'], {'name': '"""npair"""'}), "(loss_, name='npair')\n", (61278, 61299), True, 'import tensorflow as tf\n'), ((61328, 61361), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""scale"""', 'scale'], {}), "('scale', scale)\n", (61345, 61361), True, 'import tensorflow as tf\n'), ((61370, 61402), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""scale"""', 'scale'], {}), "('scale', scale)\n", (61386, 61402), False, 'from utils import tfwatcher\n'), ((61615, 61631), 'tensorflow.shape', 'tf.shape', (['z_mean'], {}), '(z_mean)\n', (61623, 61631), True, 'import tensorflow as tf\n'), ((61644, 61693), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""ConditionalLoss"""'], {'reuse': 'reuse'}), "('ConditionalLoss', reuse=reuse)\n", (61661, 61693), True, 'import tensorflow as tf\n'), ((63210, 63245), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights_'], {'dim': '(1)'}), '(weights_, dim=1)\n', (63228, 63245), True, 'import tensorflow as tf\n'), ((63564, 63587), 'tensorflow.exp', 'tf.exp', (['(-z_log_sigma_sq)'], {}), '(-z_log_sigma_sq)\n', (63570, 63587), True, 'import tensorflow as tf\n'), ((63613, 63639), 'tensorflow.gather', 'tf.gather', (['weights', 'labels'], {}), '(weights, labels)\n', (63622, 63639), True, 'import tensorflow as tf\n'), ((63768, 63809), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['neg_log_likelihood'], {'axis': '(1)'}), '(neg_log_likelihood, axis=1)\n', (63781, 63809), True, 'import tensorflow as tf\n'), ((63829, 63878), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss_nll'], {'name': '"""conditional_loss"""'}), "(loss_nll, name='conditional_loss')\n", (63843, 63878), True, 'import tensorflow as tf\n'), ((65157, 65194), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['log_likelihood'], {'axis': '(1)'}), '(log_likelihood, axis=1)\n', (65170, 65194), True, 'import tensorflow as tf\n'), ((65317, 65338), 'tensorflow.exp', 'tf.exp', (['log_sigma_sq1'], {}), '(log_sigma_sq1)\n', (65323, 65338), True, 'import tensorflow as tf\n'), ((65340, 65361), 'tensorflow.exp', 'tf.exp', (['log_sigma_sq2'], {}), '(log_sigma_sq2)\n', (65346, 65361), True, 'import tensorflow as tf\n'), ((65487, 65520), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['divergence'], {'axis': '(1)'}), '(divergence, axis=1)\n', (65500, 65520), True, 'import tensorflow as tf\n'), ((65635, 65656), 'tensorflow.exp', 'tf.exp', (['log_sigma_sq1'], {}), '(log_sigma_sq1)\n', (65641, 65656), True, 'import tensorflow as tf\n'), ((65658, 65679), 'tensorflow.exp', 'tf.exp', (['log_sigma_sq2'], {}), '(log_sigma_sq2)\n', (65664, 65679), True, 'import tensorflow as tf\n'), ((65732, 65752), 'tensorflow.log', 'tf.log', (['sigma_sq_sum'], {}), '(sigma_sq_sum)\n', (65738, 65752), True, 'import tensorflow as tf\n'), ((66469, 66483), 'tensorflow.shape', 'tf.shape', (['z_mu'], {}), '(z_mu)\n', (66477, 66483), True, 'import tensorflow as tf\n'), ((66496, 66544), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""DivergenceLoss"""'], {'reuse': 'reuse'}), "('DivergenceLoss', reuse=reuse)\n", (66513, 66544), True, 'import tensorflow as tf\n'), ((67356, 67443), 'tensorflow.contrib.slim.fully_connected', 'slim.fully_connected', (['class_mu', 'num_features'], {'activation_fn': 'tf.nn.relu', 'scope': '"""fc1"""'}), "(class_mu, num_features, activation_fn=tf.nn.relu,\n scope='fc1')\n", (67376, 67443), True, 'import tensorflow.contrib.slim as slim\n'), ((67459, 67536), 'tensorflow.contrib.slim.fully_connected', 'slim.fully_connected', (['class_mu', 'num_features'], {'activation_fn': 'None', 'scope': '"""fc2"""'}), "(class_mu, num_features, activation_fn=None, scope='fc2')\n", (67479, 67536), True, 'import tensorflow.contrib.slim as slim\n'), ((67546, 67588), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""class_mu"""', 'class_mu'], {}), "('class_mu', class_mu)\n", (67566, 67588), True, 'import tensorflow as tf\n'), ((67597, 67659), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""class_log_sigma_sq"""', 'class_log_sigma_sq'], {}), "('class_log_sigma_sq', class_log_sigma_sq)\n", (67617, 67659), True, 'import tensorflow as tf\n'), ((72615, 72631), 'tensorflow.shape', 'tf.shape', (['z_mean'], {}), '(z_mean)\n', (72623, 72631), True, 'import tensorflow as tf\n'), ((72701, 72750), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""ConditionalLoss"""'], {'reuse': 'reuse'}), "('ConditionalLoss', reuse=reuse)\n", (72718, 72750), True, 'import tensorflow as tf\n'), ((73283, 73300), 'tensorflow.unique', 'tf.unique', (['labels'], {}), '(labels)\n', (73292, 73300), True, 'import tensorflow as tf\n'), ((73326, 73359), 'tensorflow.gather', 'tf.gather', (['weights', 'labels_unique'], {}), '(weights, labels_unique)\n', (73335, 73359), True, 'import tensorflow as tf\n'), ((74573, 74592), 'tensorflow.shape', 'tf.shape', (['prelogits'], {}), '(prelogits)\n', (74581, 74592), True, 'import tensorflow as tf\n'), ((74605, 74645), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""DPLoss"""'], {'reuse': 'reuse'}), "('DPLoss', reuse=reuse)\n", (74622, 74645), True, 'import tensorflow as tf\n'), ((75223, 75274), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""classifier_weights"""', 'weights'], {}), "('classifier_weights', weights)\n", (75243, 75274), True, 'import tensorflow as tf\n'), ((75339, 75375), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['prelogits'], {'dim': '(1)'}), '(prelogits, dim=1)\n', (75357, 75375), True, 'import tensorflow as tf\n'), ((75439, 75473), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(1)'}), '(weights, dim=1)\n', (75457, 75473), True, 'import tensorflow as tf\n'), ((75805, 75865), 'tensorflow.reshape', 'tf.reshape', (['prelogits_normed', '[-1, group_size, num_features]'], {}), '(prelogits_normed, [-1, group_size, num_features])\n', (75815, 75865), True, 'import tensorflow as tf\n'), ((75888, 75942), 'tensorflow.reshape', 'tf.reshape', (['confidence', '[-1, group_size, num_features]'], {}), '(confidence, [-1, group_size, num_features])\n', (75898, 75942), True, 'import tensorflow as tf\n'), ((75965, 75998), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['confidence'], {'axis': '(1)'}), '(confidence, axis=1)\n', (75978, 75998), True, 'import tensorflow as tf\n'), ((76219, 76256), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['prelogits_mean'], {'axis': '(1)'}), '(prelogits_mean, axis=1)\n', (76232, 76256), True, 'import tensorflow as tf\n'), ((78211, 78251), 'tensorflow.eye', 'tf.eye', (['num_classes_batch'], {'dtype': 'tf.bool'}), '(num_classes_batch, dtype=tf.bool)\n', (78217, 78251), True, 'import tensorflow as tf\n'), ((78276, 78301), 'tensorflow.logical_not', 'tf.logical_not', (['diag_mask'], {}), '(diag_mask)\n', (78290, 78301), True, 'import tensorflow as tf\n'), ((78389, 78439), 'tensorflow.equal', 'tf.equal', (['label_mean[:, None]', 'label_mean[None, :]'], {}), '(label_mean[:, None], label_mean[None, :])\n', (78397, 78439), True, 'import tensorflow as tf\n'), ((78463, 78503), 'tensorflow.logical_and', 'tf.logical_and', (['non_diag_mask', 'label_mat'], {}), '(non_diag_mask, label_mat)\n', (78477, 78503), True, 'import tensorflow as tf\n'), ((78616, 78657), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_pos'], {}), '(dist_mat, label_mask_pos)\n', (78631, 78657), True, 'import tensorflow as tf\n'), ((78678, 78719), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_neg'], {}), '(dist_mat, label_mask_neg)\n', (78693, 78719), True, 'import tensorflow as tf\n'), ((78748, 78793), 'tensorflow.reshape', 'tf.reshape', (['dist_pos', '[num_classes_batch, -1]'], {}), '(dist_pos, [num_classes_batch, -1])\n', (78758, 78793), True, 'import tensorflow as tf\n'), ((78813, 78858), 'tensorflow.reshape', 'tf.reshape', (['dist_neg', '[num_classes_batch, -1]'], {}), '(dist_neg, [num_classes_batch, -1])\n', (78823, 78858), True, 'import tensorflow as tf\n'), ((79036, 79071), 'tensorflow.nn.relu', 'tf.nn.relu', (['(dist_pos - dist_neg + m)'], {}), '(dist_pos - dist_neg + m)\n', (79046, 79071), True, 'import tensorflow as tf\n'), ((79087, 79122), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {'name': '"""DPLoss"""'}), "(loss, name='DPLoss')\n", (79101, 79122), True, 'import tensorflow as tf\n'), ((565, 577), 'tensorflow.shape', 'tf.shape', (['x1'], {}), '(x1)\n', (573, 577), True, 'import tensorflow as tf\n'), ((982, 994), 'tensorflow.shape', 'tf.shape', (['x1'], {}), '(x1)\n', (990, 994), True, 'import tensorflow as tf\n'), ((1845, 1873), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (1868, 1873), True, 'import tensorflow as tf\n'), ((2979, 2991), 'tensorflow.square', 'tf.square', (['X'], {}), '(X)\n', (2988, 2991), True, 'import tensorflow as tf\n'), ((3039, 3051), 'tensorflow.square', 'tf.square', (['Y'], {}), '(Y)\n', (3048, 3051), True, 'import tensorflow as tf\n'), ((3216, 3230), 'tensorflow.sqrt', 'tf.sqrt', (['diffs'], {}), '(diffs)\n', (3223, 3230), True, 'import tensorflow as tf\n'), ((3687, 3699), 'tensorflow.square', 'tf.square', (['Y'], {}), '(Y)\n', (3696, 3699), True, 'import tensorflow as tf\n'), ((4053, 4068), 'tensorflow.transpose', 'tf.transpose', (['Y'], {}), '(Y)\n', (4065, 4068), True, 'import tensorflow as tf\n'), ((4214, 4229), 'tensorflow.matmul', 'tf.matmul', (['X', 'Y'], {}), '(X, Y)\n', (4223, 4229), True, 'import tensorflow as tf\n'), ((4291, 4315), 'tensorflow.transpose', 'tf.transpose', (['sigma_sq_Y'], {}), '(sigma_sq_Y)\n', (4303, 4315), True, 'import tensorflow as tf\n'), ((4341, 4391), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['sigma_sq_X'], {'axis': '(1)', 'keep_dims': '(True)'}), '(sigma_sq_X, axis=1, keep_dims=True)\n', (4355, 4391), True, 'import tensorflow as tf\n'), ((4417, 4467), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['sigma_sq_Y'], {'axis': '(0)', 'keep_dims': '(True)'}), '(sigma_sq_Y, axis=0, keep_dims=True)\n', (4431, 4467), True, 'import tensorflow as tf\n'), ((4689, 4714), 'tensorflow.reshape', 'tf.reshape', (['X', '[-1, 1, D]'], {}), '(X, [-1, 1, D])\n', (4699, 4714), True, 'import tensorflow as tf\n'), ((4731, 4756), 'tensorflow.reshape', 'tf.reshape', (['Y', '[1, -1, D]'], {}), '(Y, [1, -1, D])\n', (4741, 4756), True, 'import tensorflow as tf\n'), ((4782, 4816), 'tensorflow.reshape', 'tf.reshape', (['sigma_sq_X', '[-1, 1, D]'], {}), '(sigma_sq_X, [-1, 1, D])\n', (4792, 4816), True, 'import tensorflow as tf\n'), ((4842, 4876), 'tensorflow.reshape', 'tf.reshape', (['sigma_sq_Y', '[1, -1, D]'], {}), '(sigma_sq_Y, [1, -1, D])\n', (4852, 4876), True, 'import tensorflow as tf\n'), ((5033, 5061), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['diffs'], {'axis': '(2)'}), '(diffs, axis=2)\n', (5046, 5061), True, 'import tensorflow as tf\n'), ((6822, 6897), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'label', 'logits': 'logits'}), '(labels=label, logits=logits)\n', (6868, 6897), True, 'import tensorflow as tf\n'), ((7096, 7124), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['label'], {}), '(label)\n', (7117, 7124), True, 'import tensorflow as tf\n'), ((7152, 7187), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (7161, 7187), True, 'import tensorflow as tf\n'), ((7215, 7248), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (7225, 7248), True, 'import tensorflow as tf\n'), ((7277, 7302), 'tensorflow.gather', 'tf.gather', (['weights', 'label'], {}), '(weights, label)\n', (7286, 7302), True, 'import tensorflow as tf\n'), ((7459, 7503), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'label', 'diff_centers'], {}), '(weights, label, diff_centers)\n', (7473, 7503), True, 'import tensorflow as tf\n'), ((7516, 7580), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (7536, 7580), True, 'import tensorflow as tf\n'), ((8483, 8558), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'label', 'logits': 'logits'}), '(labels=label, logits=logits)\n', (8529, 8558), True, 'import tensorflow as tf\n'), ((8614, 8638), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (8636, 8638), True, 'import tensorflow as tf\n'), ((8747, 8775), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['label'], {}), '(label)\n', (8768, 8775), True, 'import tensorflow as tf\n'), ((8803, 8838), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (8812, 8838), True, 'import tensorflow as tf\n'), ((8866, 8899), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (8876, 8899), True, 'import tensorflow as tf\n'), ((8928, 8953), 'tensorflow.gather', 'tf.gather', (['weights', 'label'], {}), '(weights, label)\n', (8937, 8953), True, 'import tensorflow as tf\n'), ((9110, 9154), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'label', 'diff_centers'], {}), '(weights, label, diff_centers)\n', (9124, 9154), True, 'import tensorflow as tf\n'), ((9167, 9231), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (9187, 9231), True, 'import tensorflow as tf\n'), ((11723, 11756), 'tensorflow.cast', 'tf.cast', (['appear_times', 'tf.float32'], {}), '(appear_times, tf.float32)\n', (11730, 11756), True, 'import tensorflow as tf\n'), ((12383, 12408), 'tensorflow.norm', 'tf.norm', (['features'], {'axis': '(1)'}), '(features, axis=1)\n', (12390, 12408), True, 'import tensorflow as tf\n'), ((12810, 12843), 'tensorflow.eye', 'tf.eye', (['batch_size'], {'dtype': 'tf.bool'}), '(batch_size, dtype=tf.bool)\n', (12816, 12843), True, 'import tensorflow as tf\n'), ((13861, 13882), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['alpha'], {}), '(alpha)\n', (13875, 13882), True, 'import tensorflow as tf\n'), ((13957, 13975), 'tensorflow.constant', 'tf.constant', (['gamma'], {}), '(gamma)\n', (13968, 13975), True, 'import tensorflow as tf\n'), ((14002, 14045), 'tensorflow.matmul', 'tf.matmul', (['prelogits_normed', 'weights_normed'], {}), '(prelogits_normed, weights_normed)\n', (14011, 14045), True, 'import tensorflow as tf\n'), ((16460, 16487), 'tensorflow.maximum', 'tf.maximum', (['(-1.0)', 'cos_theta'], {}), '(-1.0, cos_theta)\n', (16470, 16487), True, 'import tensorflow as tf\n'), ((16960, 16998), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_lamb]'], {}), '([update_lamb])\n', (16983, 16998), True, 'import tensorflow as tf\n'), ((17026, 17074), 'tensorflow.one_hot', 'tf.one_hot', (['label', 'num_classes'], {'dtype': 'tf.float32'}), '(label, num_classes, dtype=tf.float32)\n', (17036, 17074), True, 'import tensorflow as tf\n'), ((19474, 19492), 'tensorflow.constant', 'tf.constant', (['scale'], {}), '(scale)\n', (19485, 19492), True, 'import tensorflow as tf\n'), ((19744, 19784), 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['_logits_neg'], {'axis': '(1)'}), '(_logits_neg, axis=1)\n', (19763, 19784), True, 'import tensorflow as tf\n'), ((19894, 19933), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {'name': '"""am_softmax"""'}), "(loss, name='am_softmax')\n", (19908, 19933), True, 'import tensorflow as tf\n'), ((21840, 21875), 'tensorflow.nn.top_k', 'tf.nn.top_k', (['theta_class', 'mid_index'], {}), '(theta_class, mid_index)\n', (21851, 21875), True, 'import tensorflow as tf\n'), ((22079, 22097), 'tensorflow.math.log', 'tf.math.log', (['b_avg'], {}), '(b_avg)\n', (22090, 22097), True, 'import tensorflow as tf\n'), ((22304, 22391), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'scaled_logits', 'labels': 'label'}), '(logits=scaled_logits, labels\n =label)\n', (22350, 22391), True, 'import tensorflow as tf\n'), ((23766, 23790), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""s"""', 's'], {}), "('s', s)\n", (23782, 23790), False, 'from utils import tfwatcher\n'), ((23864, 23878), 'tensorflow.constant', 'tf.constant', (['s'], {}), '(s)\n', (23875, 23878), True, 'import tensorflow as tf\n'), ((25034, 25110), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'labels'}), '(logits=logits, labels=labels)\n', (25080, 25110), True, 'import tensorflow as tf\n'), ((26658, 26686), 'tensorflow.transpose', 'tf.transpose', (['weights_normed'], {}), '(weights_normed)\n', (26670, 26686), True, 'import tensorflow as tf\n'), ((27162, 27180), 'tensorflow.constant', 'tf.constant', (['scale'], {}), '(scale)\n', (27173, 27180), True, 'import tensorflow as tf\n'), ((27425, 27464), 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['logits_neg'], {'axis': '(1)'}), '(logits_neg, axis=1)\n', (27444, 27464), True, 'import tensorflow as tf\n'), ((27939, 27971), 'tensorflow.gather', 'tf.gather', (['weights', 'label_target'], {}), '(weights, label_target)\n', (27948, 27971), True, 'import tensorflow as tf\n'), ((28083, 28118), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['label_target'], {}), '(label_target)\n', (28104, 28118), True, 'import tensorflow as tf\n'), ((28146, 28181), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (28155, 28181), True, 'import tensorflow as tf\n'), ((28209, 28242), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (28219, 28242), True, 'import tensorflow as tf\n'), ((28403, 28454), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'label_target', 'diff_centers'], {}), '(weights, label_target, diff_centers)\n', (28417, 28454), True, 'import tensorflow as tf\n'), ((28904, 28968), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (28924, 28968), True, 'import tensorflow as tf\n'), ((29217, 29257), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['w'], {'axis': '(1)', 'keep_dims': '(True)'}), '(w, axis=1, keep_dims=True)\n', (29230, 29257), True, 'import tensorflow as tf\n'), ((29274, 29314), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['w'], {'axis': '(0)', 'keep_dims': '(True)'}), '(w, axis=0, keep_dims=True)\n', (29287, 29314), True, 'import tensorflow as tf\n'), ((30211, 30243), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['weights_splits[i]'], {}), '(weights_splits[i])\n', (30224, 30243), True, 'import tensorflow as tf\n'), ((30346, 30371), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['weight_reg'], {}), '(weight_reg)\n', (30359, 30371), True, 'import tensorflow as tf\n'), ((30539, 30571), 'tensorflow.nn.moments', 'tf.nn.moments', (['weights'], {'axes': '[1]'}), '(weights, axes=[1])\n', (30552, 30571), True, 'import tensorflow as tf\n'), ((31340, 31384), 'tensorflow.reshape', 'tf.reshape', (['prelogits', '[-1, 1, num_features]'], {}), '(prelogits, [-1, 1, num_features])\n', (31350, 31384), True, 'import tensorflow as tf\n'), ((31408, 31450), 'tensorflow.reshape', 'tf.reshape', (['weights', '[1, -1, num_features]'], {}), '(weights, [1, -1, num_features])\n', (31418, 31450), True, 'import tensorflow as tf\n'), ((31470, 31502), 'numpy.square', 'np.square', (['(prelogits_ - weights_)'], {}), '(prelogits_ - weights_)\n', (31479, 31502), True, 'import numpy as np\n'), ((31522, 31551), 'tensorflow.transpose', 'tf.transpose', (['dist', '[0, 2, 1]'], {}), '(dist, [0, 2, 1])\n', (31534, 31551), True, 'import tensorflow as tf\n'), ((31571, 31606), 'tensorflow.reshape', 'tf.reshape', (['dist', '[-1, num_classes]'], {}), '(dist, [-1, num_classes])\n', (31581, 31606), True, 'import tensorflow as tf\n'), ((31747, 31771), 'tensorflow.reshape', 'tf.reshape', (['label_', '[-1]'], {}), '(label_, [-1])\n', (31757, 31771), True, 'import tensorflow as tf\n'), ((32072, 32120), 'tensorflow.one_hot', 'tf.one_hot', (['label', 'num_classes'], {'dtype': 'tf.float32'}), '(label, num_classes, dtype=tf.float32)\n', (32082, 32120), True, 'import tensorflow as tf\n'), ((32155, 32187), 'tensorflow.cast', 'tf.cast', (['label_mat_glob', 'tf.bool'], {}), '(label_mat_glob, tf.bool)\n', (32162, 32187), True, 'import tensorflow as tf\n'), ((32222, 32257), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos_glob'], {}), '(label_mask_pos_glob)\n', (32236, 32257), True, 'import tensorflow as tf\n'), ((32360, 32407), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_glob', 'label_mask_pos_glob'], {}), '(dist_glob, label_mask_pos_glob)\n', (32375, 32407), True, 'import tensorflow as tf\n'), ((32431, 32478), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_glob', 'label_mask_neg_glob'], {}), '(dist_glob, label_mask_neg_glob)\n', (32446, 32478), True, 'import tensorflow as tf\n'), ((33270, 33302), 'tensorflow.gather', 'tf.gather', (['weights', 'label_target'], {}), '(weights, label_target)\n', (33279, 33302), True, 'import tensorflow as tf\n'), ((33414, 33449), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['label_target'], {}), '(label_target)\n', (33435, 33449), True, 'import tensorflow as tf\n'), ((33477, 33512), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (33486, 33512), True, 'import tensorflow as tf\n'), ((33540, 33573), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (33550, 33573), True, 'import tensorflow as tf\n'), ((33730, 33781), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'label_target', 'diff_centers'], {}), '(weights, label_target, diff_centers)\n', (33744, 33781), True, 'import tensorflow as tf\n'), ((33794, 33858), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (33814, 33858), True, 'import tensorflow as tf\n'), ((36023, 36051), 'tensorflow.transpose', 'tf.transpose', (['weights_normed'], {}), '(weights_normed)\n', (36035, 36051), True, 'import tensorflow as tf\n'), ((36637, 36666), 'tensorflow.transpose', 'tf.transpose', (['label_exp_batch'], {}), '(label_exp_batch)\n', (36649, 36666), True, 'import tensorflow as tf\n'), ((37024, 37054), 'tensorflow.transpose', 'tf.transpose', (['prelogits_normed'], {}), '(prelogits_normed)\n', (37036, 37054), True, 'import tensorflow as tf\n'), ((38544, 38567), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['gamma'], {}), '(gamma)\n', (38560, 38567), True, 'import tensorflow as tf\n'), ((38569, 38591), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['beta'], {}), '(beta)\n', (38585, 38591), True, 'import tensorflow as tf\n'), ((38672, 38709), 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['(b - g * dist_neg)'], {}), '(b - g * dist_neg)\n', (38691, 38709), True, 'import tensorflow as tf\n'), ((38903, 38927), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss_neg'], {}), '(loss_neg)\n', (38917, 38927), True, 'import tensorflow as tf\n'), ((38961, 38985), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss_pos'], {}), '(loss_pos)\n', (38975, 38985), True, 'import tensorflow as tf\n'), ((39020, 39046), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['logits_neg'], {}), '(logits_neg)\n', (39034, 39046), True, 'import tensorflow as tf\n'), ((39081, 39107), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['logits_pos'], {}), '(logits_pos)\n', (39095, 39107), True, 'import tensorflow as tf\n'), ((39690, 39715), 'tensorflow.gather', 'tf.gather', (['weights', 'label'], {}), '(weights, label)\n', (39699, 39715), True, 'import tensorflow as tf\n'), ((39829, 39857), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['label'], {}), '(label)\n', (39850, 39857), True, 'import tensorflow as tf\n'), ((39885, 39920), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (39894, 39920), True, 'import tensorflow as tf\n'), ((39948, 39981), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (39958, 39981), True, 'import tensorflow as tf\n'), ((40142, 40186), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'label', 'diff_centers'], {}), '(weights, label, diff_centers)\n', (40156, 40186), True, 'import tensorflow as tf\n'), ((40466, 40493), 'tensorflow.group', 'tf.group', (['centers_update_op'], {}), '(centers_update_op)\n', (40474, 40493), True, 'import tensorflow as tf\n'), ((40506, 40570), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (40526, 40570), True, 'import tensorflow as tf\n'), ((43125, 43152), 'tensorflow.shape', 'tf.shape', (['prelogits_reshape'], {}), '(prelogits_reshape)\n', (43133, 43152), True, 'import tensorflow as tf\n'), ((43195, 43212), 'tensorflow.eye', 'tf.eye', (['num_pairs'], {}), '(num_pairs)\n', (43201, 43212), True, 'import tensorflow as tf\n'), ((44233, 44252), 'tensorflow.nn.relu', 'tf.nn.relu', (['(1.0 + x)'], {}), '(1.0 + x)\n', (44243, 44252), True, 'import tensorflow as tf\n'), ((44629, 44665), 'tensorflow.reduce_max', 'tf.reduce_max', (['_logits_neg_1'], {'axis': '(1)'}), '(_logits_neg_1, axis=1)\n', (44642, 44665), True, 'import tensorflow as tf\n'), ((44698, 44734), 'tensorflow.reduce_max', 'tf.reduce_max', (['_logits_neg_2'], {'axis': '(0)'}), '(_logits_neg_2, axis=0)\n', (44711, 44734), True, 'import tensorflow as tf\n'), ((44992, 45035), 'tensorflow.nn.relu', 'tf.nn.relu', (['(m + _logits_neg_1 - _logits_pos)'], {}), '(m + _logits_neg_1 - _logits_pos)\n', (45002, 45035), True, 'import tensorflow as tf\n'), ((45061, 45104), 'tensorflow.nn.relu', 'tf.nn.relu', (['(m + _logits_neg_2 - _logits_pos)'], {}), '(m + _logits_neg_2 - _logits_pos)\n', (45071, 45104), True, 'import tensorflow as tf\n'), ((45818, 45841), 'tensorflow.shape', 'tf.shape', (['prelogits_tmp'], {}), '(prelogits_tmp)\n', (45826, 45841), True, 'import tensorflow as tf\n'), ((45847, 45870), 'tensorflow.shape', 'tf.shape', (['prelogits_pro'], {}), '(prelogits_pro)\n', (45855, 45870), True, 'import tensorflow as tf\n'), ((46809, 46832), 'tensorflow.shape', 'tf.shape', (['prelogits_tmp'], {}), '(prelogits_tmp)\n', (46817, 46832), True, 'import tensorflow as tf\n'), ((47142, 47159), 'tensorflow.eye', 'tf.eye', (['num_pairs'], {}), '(num_pairs)\n', (47148, 47159), True, 'import tensorflow as tf\n'), ((47434, 47464), 'tensorflow.transpose', 'tf.transpose', (['logits_mat_batch'], {}), '(logits_mat_batch)\n', (47446, 47464), True, 'import tensorflow as tf\n'), ((48244, 48280), 'tensorflow.reduce_max', 'tf.reduce_max', (['_logits_neg_1'], {'axis': '(1)'}), '(_logits_neg_1, axis=1)\n', (48257, 48280), True, 'import tensorflow as tf\n'), ((48313, 48349), 'tensorflow.reduce_max', 'tf.reduce_max', (['_logits_neg_2'], {'axis': '(1)'}), '(_logits_neg_2, axis=1)\n', (48326, 48349), True, 'import tensorflow as tf\n'), ((50036, 50073), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['embeddings'], {'dim': '(1)'}), '(embeddings, dim=1)\n', (50054, 50073), True, 'import tensorflow as tf\n'), ((50096, 50116), 'tensorflow.shape', 'tf.shape', (['embeddings'], {}), '(embeddings)\n', (50104, 50116), True, 'import tensorflow as tf\n'), ((50330, 50354), 'tensorflow.transpose', 'tf.transpose', (['embeddings'], {}), '(embeddings)\n', (50342, 50354), True, 'import tensorflow as tf\n'), ((50555, 50580), 'tensorflow.logical_not', 'tf.logical_not', (['label_mat'], {}), '(label_mat)\n', (50569, 50580), True, 'import tensorflow as tf\n'), ((50893, 50941), 'tensorflow.reduce_max', 'tf.reduce_max', (['(-dist_neg)'], {'axis': '(1)', 'keep_dims': '(True)'}), '(-dist_neg, axis=1, keep_dims=True)\n', (50906, 50941), True, 'import tensorflow as tf\n'), ((51442, 51454), 'tensorflow.shape', 'tf.shape', (['mu'], {}), '(mu)\n', (51450, 51454), True, 'import tensorflow as tf\n'), ((51578, 51625), 'tensorflow.reshape', 'tf.reshape', (['log_sigma_sq', '[-1, 2, num_features]'], {}), '(log_sigma_sq, [-1, 2, num_features])\n', (51588, 51625), True, 'import tensorflow as tf\n'), ((51885, 51905), 'tensorflow.log', 'tf.log', (['sigma_sq_sum'], {}), '(sigma_sq_sum)\n', (51891, 51905), True, 'import tensorflow as tf\n'), ((51936, 51963), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['loss'], {'axis': '(1)'}), '(loss, axis=1)\n', (51949, 51963), True, 'import tensorflow as tf\n'), ((52376, 52413), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['embeddings'], {'dim': '(1)'}), '(embeddings, dim=1)\n', (52394, 52413), True, 'import tensorflow as tf\n'), ((52436, 52456), 'tensorflow.shape', 'tf.shape', (['embeddings'], {}), '(embeddings)\n', (52444, 52456), True, 'import tensorflow as tf\n'), ((52560, 52584), 'tensorflow.transpose', 'tf.transpose', (['embeddings'], {}), '(embeddings)\n', (52572, 52584), True, 'import tensorflow as tf\n'), ((53450, 53471), 'tensorflow.greater', 'tf.greater', (['loss', '(0.0)'], {}), '(loss, 0.0)\n', (53460, 53471), True, 'import tensorflow as tf\n'), ((53900, 53937), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['embeddings'], {'dim': '(1)'}), '(embeddings, dim=1)\n', (53918, 53937), True, 'import tensorflow as tf\n'), ((53960, 53980), 'tensorflow.shape', 'tf.shape', (['embeddings'], {}), '(embeddings)\n', (53968, 53980), True, 'import tensorflow as tf\n'), ((54597, 54622), 'tensorflow.logical_not', 'tf.logical_not', (['label_mat'], {}), '(label_mat)\n', (54611, 54622), True, 'import tensorflow as tf\n'), ((54770, 54813), 'tensorflow.reshape', 'tf.reshape', (['dist_mat_tile', '[-1, batch_size]'], {}), '(dist_mat_tile, [-1, batch_size])\n', (54780, 54813), True, 'import tensorflow as tf\n'), ((54945, 54989), 'tensorflow.reshape', 'tf.reshape', (['label_mat_tile', '[-1, batch_size]'], {}), '(label_mat_tile, [-1, batch_size])\n', (54955, 54989), True, 'import tensorflow as tf\n'), ((55031, 55060), 'tensorflow.reshape', 'tf.reshape', (['dist_mat', '[-1, 1]'], {}), '(dist_mat, [-1, 1])\n', (55041, 55060), True, 'import tensorflow as tf\n'), ((55089, 55121), 'tensorflow.reshape', 'tf.reshape', (['label_mask_pos', '[-1]'], {}), '(label_mask_pos, [-1])\n', (55099, 55121), True, 'import tensorflow as tf\n'), ((55324, 55340), 'tensorflow.nn.relu', 'tf.nn.relu', (['loss'], {}), '(loss)\n', (55334, 55340), True, 'import tensorflow as tf\n'), ((55498, 55535), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['valid', 'label_flatten'], {}), '(valid, label_flatten)\n', (55513, 55535), True, 'import tensorflow as tf\n'), ((55555, 55591), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['loss', 'label_flatten'], {}), '(loss, label_flatten)\n', (55570, 55591), True, 'import tensorflow as tf\n'), ((55872, 55892), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (55886, 55892), True, 'import tensorflow as tf\n'), ((55934, 55975), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_pos'], {}), '(dist_mat, label_mask_pos)\n', (55949, 55975), True, 'import tensorflow as tf\n'), ((56000, 56041), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_neg'], {}), '(dist_mat, label_mask_neg)\n', (56015, 56041), True, 'import tensorflow as tf\n'), ((56074, 56103), 'tensorflow.reshape', 'tf.reshape', (['dist_pos', '[-1, 1]'], {}), '(dist_pos, [-1, 1])\n', (56084, 56103), True, 'import tensorflow as tf\n'), ((56126, 56155), 'tensorflow.reshape', 'tf.reshape', (['dist_neg', '[1, -1]'], {}), '(dist_neg, [1, -1])\n', (56136, 56155), True, 'import tensorflow as tf\n'), ((58335, 58372), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['embeddings'], {'dim': '(1)'}), '(embeddings, dim=1)\n', (58353, 58372), True, 'import tensorflow as tf\n'), ((58395, 58415), 'tensorflow.shape', 'tf.shape', (['embeddings'], {}), '(embeddings)\n', (58403, 58415), True, 'import tensorflow as tf\n'), ((58629, 58653), 'tensorflow.transpose', 'tf.transpose', (['embeddings'], {}), '(embeddings)\n', (58641, 58653), True, 'import tensorflow as tf\n'), ((58854, 58879), 'tensorflow.logical_not', 'tf.logical_not', (['label_mat'], {}), '(label_mat)\n', (58868, 58879), True, 'import tensorflow as tf\n'), ((59313, 59342), 'tensorflow.nn.relu', 'tf.nn.relu', (['(margin - dist_neg)'], {}), '(margin - dist_neg)\n', (59323, 59342), True, 'import tensorflow as tf\n'), ((60164, 60187), 'tensorflow.transpose', 'tf.transpose', (['label_exp'], {}), '(label_exp)\n', (60176, 60187), True, 'import tensorflow as tf\n'), ((60780, 60802), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['_scale'], {}), '(_scale)\n', (60794, 60802), True, 'import tensorflow as tf\n'), ((60877, 60895), 'tensorflow.constant', 'tf.constant', (['scale'], {}), '(scale)\n', (60888, 60895), True, 'import tensorflow as tf\n'), ((61140, 61179), 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['logits_neg'], {'axis': '(1)'}), '(logits_neg, axis=1)\n', (61159, 61179), True, 'import tensorflow as tf\n'), ((62798, 62856), 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.fully_connected]'], {'normalizer_fn': 'None'}), '([slim.fully_connected], normalizer_fn=None)\n', (62812, 62856), True, 'import tensorflow.contrib.slim as slim\n'), ((62914, 63020), 'tensorflow.contrib.slim.fully_connected', 'slim.fully_connected', (['weights_', 'num_features'], {'biases_initializer': 'None', 'activation_fn': 'None', 'scope': '"""fc1"""'}), "(weights_, num_features, biases_initializer=None,\n activation_fn=None, scope='fc1')\n", (62934, 63020), True, 'import tensorflow.contrib.slim as slim\n'), ((63432, 63508), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'labels', 'logits': 'logits'}), '(labels=labels, logits=logits)\n', (63478, 63508), True, 'import tensorflow as tf\n'), ((64041, 64058), 'tensorflow.unique', 'tf.unique', (['labels'], {}), '(labels)\n', (64050, 64058), True, 'import tensorflow as tf\n'), ((64488, 64521), 'tensorflow.gather', 'tf.gather', (['weights', 'labels_target'], {}), '(weights, labels_target)\n', (64497, 64521), True, 'import tensorflow as tf\n'), ((64680, 64732), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'labels_target', 'diff_centers'], {}), '(weights, labels_target, diff_centers)\n', (64694, 64732), True, 'import tensorflow as tf\n'), ((64745, 64809), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (64765, 64809), True, 'import tensorflow as tf\n'), ((64861, 64883), 'tensorflow.exp', 'tf.exp', (['z_log_sigma_sq'], {}), '(z_log_sigma_sq)\n', (64867, 64883), True, 'import tensorflow as tf\n'), ((65101, 65118), 'tensorflow.square', 'tf.square', (['(mu - z)'], {}), '(mu - z)\n', (65110, 65118), True, 'import tensorflow as tf\n'), ((65755, 65775), 'tensorflow.square', 'tf.square', (['(mu2 - mu1)'], {}), '(mu2 - mu1)\n', (65764, 65775), True, 'import tensorflow as tf\n'), ((65980, 66001), 'tensorflow.range', 'tf.range', (['num_classes'], {}), '(num_classes)\n', (65988, 66001), True, 'import tensorflow as tf\n'), ((67883, 67910), 'tensorflow.gather', 'tf.gather', (['class_mu', 'labels'], {}), '(class_mu, labels)\n', (67892, 67910), True, 'import tensorflow as tf\n'), ((67943, 67980), 'tensorflow.gather', 'tf.gather', (['class_log_sigma_sq', 'labels'], {}), '(class_log_sigma_sq, labels)\n', (67952, 67980), True, 'import tensorflow as tf\n'), ((68282, 68332), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['divergence'], {'name': '"""divergence_loss"""'}), "(divergence, name='divergence_loss')\n", (68296, 68332), True, 'import tensorflow as tf\n'), ((69799, 69822), 'tensorflow.exp', 'tf.exp', (['(-z_log_sigma_sq)'], {}), '(-z_log_sigma_sq)\n', (69805, 69822), True, 'import tensorflow as tf\n'), ((69878, 69907), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['labels'], {}), '(labels)\n', (69899, 69907), True, 'import tensorflow as tf\n'), ((70514, 70547), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (70524, 70547), True, 'import tensorflow as tf\n'), ((73661, 73697), 'tensorflow.square', 'tf.square', (['(xc_normed - weights_batch)'], {}), '(xc_normed - weights_batch)\n', (73670, 73697), True, 'import tensorflow as tf\n'), ((73729, 73754), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['deviation'], {}), '(deviation)\n', (73743, 73754), True, 'import tensorflow as tf\n'), ((73808, 73832), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (73830, 73832), True, 'import tensorflow as tf\n'), ((74039, 74091), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'labels_unique', 'diff_centers'], {}), '(weights, labels_unique, diff_centers)\n', (74053, 74091), True, 'import tensorflow as tf\n'), ((74104, 74168), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (74124, 74168), True, 'import tensorflow as tf\n'), ((74220, 74242), 'tensorflow.exp', 'tf.exp', (['z_log_sigma_sq'], {}), '(z_log_sigma_sq)\n', (74226, 74242), True, 'import tensorflow as tf\n'), ((76374, 76409), 'tensorflow.reshape', 'tf.reshape', (['label', '[-1, group_size]'], {}), '(label, [-1, group_size])\n', (76384, 76409), True, 'import tensorflow as tf\n'), ((77659, 77689), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['prelogits_mean'], {}), '(prelogits_mean)\n', (77673, 77689), True, 'import tensorflow as tf\n'), ((78069, 78093), 'tensorflow.shape', 'tf.shape', (['prelogits_mean'], {}), '(prelogits_mean)\n', (78077, 78093), True, 'import tensorflow as tf\n'), ((78152, 78180), 'tensorflow.transpose', 'tf.transpose', (['prelogits_mean'], {}), '(prelogits_mean)\n', (78164, 78180), True, 'import tensorflow as tf\n'), ((78328, 78363), 'tensorflow.reshape', 'tf.reshape', (['label', '[-1, group_size]'], {}), '(label, [-1, group_size])\n', (78338, 78363), True, 'import tensorflow as tf\n'), ((78559, 78584), 'tensorflow.logical_not', 'tf.logical_not', (['label_mat'], {}), '(label_mat)\n', (78573, 78584), True, 'import tensorflow as tf\n'), ((78963, 79011), 'tensorflow.reduce_max', 'tf.reduce_max', (['(-dist_neg)'], {'axis': '(1)', 'keep_dims': '(True)'}), '(-dist_neg, axis=1, keep_dims=True)\n', (78976, 79011), True, 'import tensorflow as tf\n'), ((3602, 3614), 'tensorflow.square', 'tf.square', (['X'], {}), '(X)\n', (3611, 3614), True, 'import tensorflow as tf\n'), ((3830, 3852), 'tensorflow.maximum', 'tf.maximum', (['(0.0)', 'diffs'], {}), '(0.0, diffs)\n', (3840, 3852), True, 'import tensorflow as tf\n'), ((4100, 4112), 'tensorflow.square', 'tf.square', (['X'], {}), '(X)\n', (4109, 4112), True, 'import tensorflow as tf\n'), ((4164, 4176), 'tensorflow.square', 'tf.square', (['Y'], {}), '(Y)\n', (4173, 4176), True, 'import tensorflow as tf\n'), ((4992, 5013), 'tensorflow.log', 'tf.log', (['sigma_sq_fuse'], {}), '(sigma_sq_fuse)\n', (4998, 5013), True, 'import tensorflow as tf\n'), ((5400, 5433), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (5419, 5433), True, 'import tensorflow.contrib.slim as slim\n'), ((5463, 5501), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {'uniform': '(False)'}), '(uniform=False)\n', (5486, 5501), True, 'import tensorflow.contrib.slim as slim\n'), ((5666, 5694), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (5689, 5694), True, 'import tensorflow as tf\n'), ((6120, 6178), 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.fully_connected]'], {'normalizer_fn': 'None'}), '([slim.fully_connected], normalizer_fn=None)\n', (6134, 6178), True, 'import tensorflow.contrib.slim as slim\n'), ((6224, 6309), 'tensorflow.contrib.slim.fully_connected', 'slim.fully_connected', (['weights', '(num_features + 1)'], {'activation_fn': 'None', 'scope': '"""fc1"""'}), "(weights, num_features + 1, activation_fn=None, scope='fc1'\n )\n", (6244, 6309), True, 'import tensorflow.contrib.slim as slim\n'), ((6684, 6705), 'tensorflow.transpose', 'tf.transpose', (['weights'], {}), '(weights)\n', (6696, 6705), True, 'import tensorflow as tf\n'), ((6963, 6987), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (6985, 6987), True, 'import tensorflow as tf\n'), ((7345, 7378), 'tensorflow.cast', 'tf.cast', (['appear_times', 'tf.float32'], {}), '(appear_times, tf.float32)\n', (7352, 7378), True, 'import tensorflow as tf\n'), ((7958, 7991), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (7977, 7991), True, 'import tensorflow.contrib.slim as slim\n'), ((8021, 8046), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {}), '()\n', (8044, 8046), True, 'import tensorflow.contrib.slim as slim\n'), ((8211, 8239), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (8234, 8239), True, 'import tensorflow as tf\n'), ((8347, 8368), 'tensorflow.transpose', 'tf.transpose', (['weights'], {}), '(weights)\n', (8359, 8368), True, 'import tensorflow as tf\n'), ((8996, 9029), 'tensorflow.cast', 'tf.cast', (['appear_times', 'tf.float32'], {}), '(appear_times, tf.float32)\n', (9003, 9029), True, 'import tensorflow as tf\n'), ((11045, 11088), 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': '(0.1)'}), '(stddev=0.1)\n', (11076, 11088), True, 'import tensorflow as tf\n'), ((12238, 12266), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (12261, 12266), True, 'import tensorflow as tf\n'), ((12742, 12764), 'tensorflow.transpose', 'tf.transpose', (['features'], {}), '(features)\n', (12754, 12764), True, 'import tensorflow as tf\n'), ((12882, 12911), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['cov', 'nondiag'], {}), '(cov, nondiag)\n', (12897, 12911), True, 'import tensorflow as tf\n'), ((13257, 13290), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (13276, 13290), True, 'import tensorflow.contrib.slim as slim\n'), ((13320, 13345), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {}), '()\n', (13343, 13345), True, 'import tensorflow.contrib.slim as slim\n'), ((13535, 13560), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.01)'], {}), '(0.01)\n', (13554, 13560), True, 'import tensorflow.contrib.slim as slim\n'), ((13590, 13618), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (13613, 13618), True, 'import tensorflow as tf\n'), ((14562, 14590), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), '(0.1)\n', (14585, 14590), True, 'import tensorflow as tf\n'), ((15692, 15719), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.0001)'], {}), '(0.0001)\n', (15711, 15719), True, 'import tensorflow.contrib.slim as slim\n'), ((15747, 15785), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {'uniform': '(False)'}), '(uniform=False)\n', (15770, 15785), True, 'import tensorflow.contrib.slim as slim\n'), ((16005, 16038), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['lamb_max'], {}), '(lamb_max)\n', (16028, 16038), True, 'import tensorflow as tf\n'), ((16155, 16175), 'tensorflow.square', 'tf.square', (['prelogits'], {}), '(prelogits)\n', (16164, 16175), True, 'import tensorflow as tf\n'), ((16638, 16653), 'tensorflow.pow', 'tf.pow', (['(-1.0)', 'k'], {}), '(-1.0, k)\n', (16644, 16653), True, 'import tensorflow as tf\n'), ((17294, 17369), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'label', 'logits': 'logits'}), '(labels=label, logits=logits)\n', (17340, 17369), True, 'import tensorflow as tf\n'), ((18095, 18128), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (18114, 18128), True, 'import tensorflow.contrib.slim as slim\n'), ((18215, 18256), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': '(0.01)'}), '(stddev=0.01)\n', (18243, 18256), True, 'import tensorflow as tf\n'), ((18404, 18429), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.01)'], {}), '(0.01)\n', (18423, 18429), True, 'import tensorflow.contrib.slim as slim\n'), ((18459, 18487), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (18482, 18487), True, 'import tensorflow as tf\n'), ((20410, 20444), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.01)'], {}), '(0.01)\n', (20438, 20444), True, 'import tensorflow as tf\n'), ((20566, 20578), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (20575, 20578), False, 'import math\n'), ((20581, 20606), 'math.log', 'math.log', (['(num_classes - 1)'], {}), '(num_classes - 1)\n', (20589, 20606), False, 'import math\n'), ((21216, 21242), 'tensorflow.keras.backend.epsilon', 'tf.keras.backend.epsilon', ([], {}), '()\n', (21240, 21242), True, 'import tensorflow as tf\n'), ((21250, 21276), 'tensorflow.keras.backend.epsilon', 'tf.keras.backend.epsilon', ([], {}), '()\n', (21274, 21276), True, 'import tensorflow as tf\n'), ((21709, 21733), 'tensorflow.cast', 'tf.cast', (['label', 'tf.int32'], {}), '(label, tf.int32)\n', (21716, 21733), True, 'import tensorflow as tf\n'), ((21786, 21807), 'tensorflow.shape', 'tf.shape', (['theta_class'], {}), '(theta_class)\n', (21794, 21807), True, 'import tensorflow as tf\n'), ((22132, 22166), 'tensorflow.minimum', 'tf.minimum', (['(math.pi / 4)', 'theta_med'], {}), '(math.pi / 4, theta_med)\n', (22142, 22166), True, 'import tensorflow as tf\n'), ((23295, 23329), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.01)'], {}), '(0.01)\n', (23323, 23329), True, 'import tensorflow as tf\n'), ((25667, 25692), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {}), '()\n', (25690, 25692), True, 'import tensorflow.contrib.slim as slim\n'), ((25975, 26000), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.01)'], {}), '(0.01)\n', (25994, 26000), True, 'import tensorflow.contrib.slim as slim\n'), ((26030, 26058), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (26053, 26058), True, 'import tensorflow as tf\n'), ((27642, 27666), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (27664, 27666), True, 'import tensorflow as tf\n'), ((28285, 28318), 'tensorflow.cast', 'tf.cast', (['appear_times', 'tf.float32'], {}), '(appear_times, tf.float32)\n', (28292, 28318), True, 'import tensorflow as tf\n'), ((28472, 28516), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[centers_update_op]'], {}), '([centers_update_op])\n', (28495, 28516), True, 'import tensorflow as tf\n'), ((30409, 30427), 'tensorflow.log', 'tf.log', (['weight_reg'], {}), '(weight_reg)\n', (30415, 30427), True, 'import tensorflow as tf\n'), ((31201, 31227), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), '(0)\n', (31224, 31227), True, 'import tensorflow as tf\n'), ((31680, 31706), 'tensorflow.reshape', 'tf.reshape', (['label', '[-1, 1]'], {}), '(label, [-1, 1])\n', (31690, 31706), True, 'import tensorflow as tf\n'), ((31807, 31883), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'label_', 'logits': 'logits'}), '(labels=label_, logits=logits)\n', (31853, 31883), True, 'import tensorflow as tf\n'), ((32313, 32335), 'tensorflow.transpose', 'tf.transpose', (['weights_'], {}), '(weights_)\n', (32325, 32335), True, 'import tensorflow as tf\n'), ((32881, 32920), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['(m + dist_pos - dist_neg)'], {}), '(m + dist_pos - dist_neg)\n', (32895, 32920), True, 'import tensorflow as tf\n'), ((33144, 33168), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (33166, 33168), True, 'import tensorflow as tf\n'), ((33616, 33649), 'tensorflow.cast', 'tf.cast', (['appear_times', 'tf.float32'], {}), '(appear_times, tf.float32)\n', (33623, 33649), True, 'import tensorflow as tf\n'), ((34254, 34287), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (34273, 34287), True, 'import tensorflow.contrib.slim as slim\n'), ((34317, 34342), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {}), '()\n', (34340, 34342), True, 'import tensorflow.contrib.slim as slim\n'), ((34622, 34649), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.0001)'], {}), '(0.0001)\n', (34641, 34649), True, 'import tensorflow.contrib.slim as slim\n'), ((34677, 34705), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (34700, 34705), True, 'import tensorflow as tf\n'), ((34908, 34936), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (34931, 34936), True, 'import tensorflow as tf\n'), ((36848, 36866), 'tensorflow.eye', 'tf.eye', (['batch_size'], {}), '(batch_size)\n', (36854, 36866), True, 'import tensorflow as tf\n'), ((38082, 38100), 'tensorflow.constant', 'tf.constant', (['gamma'], {}), '(gamma)\n', (38093, 38100), True, 'import tensorflow as tf\n'), ((38313, 38341), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['logits_pos'], {}), '(logits_pos)\n', (38329, 38341), True, 'import tensorflow as tf\n'), ((38378, 38406), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['logits_neg'], {}), '(logits_neg)\n', (38394, 38406), True, 'import tensorflow as tf\n'), ((38455, 38482), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['(-logits_pos)'], {}), '(-logits_pos)\n', (38469, 38482), True, 'import tensorflow as tf\n'), ((38501, 38527), 'tensorflow.nn.softplus', 'tf.nn.softplus', (['logits_neg'], {}), '(logits_neg)\n', (38515, 38527), True, 'import tensorflow as tf\n'), ((39636, 39660), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (39658, 39660), True, 'import tensorflow as tf\n'), ((40024, 40061), 'tensorflow.cast', 'tf.cast', (['(1 + appear_times)', 'tf.float32'], {}), '(1 + appear_times, tf.float32)\n', (40031, 40061), True, 'import tensorflow as tf\n'), ((40204, 40248), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[centers_update_op]'], {}), '([centers_update_op])\n', (40227, 40248), True, 'import tensorflow as tf\n'), ((41693, 41726), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (41712, 41726), True, 'import tensorflow.contrib.slim as slim\n'), ((41756, 41781), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {}), '()\n', (41779, 41781), True, 'import tensorflow.contrib.slim as slim\n'), ((42061, 42086), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.01)'], {}), '(0.01)\n', (42080, 42086), True, 'import tensorflow.contrib.slim as slim\n'), ((42116, 42144), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (42139, 42144), True, 'import tensorflow as tf\n'), ((42347, 42375), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (42370, 42375), True, 'import tensorflow as tf\n'), ((42936, 42963), 'tensorflow.transpose', 'tf.transpose', (['prelogits_pro'], {}), '(prelogits_pro)\n', (42948, 42963), True, 'import tensorflow as tf\n'), ((44182, 44200), 'tensorflow.constant', 'tf.constant', (['gamma'], {}), '(gamma)\n', (44193, 44200), True, 'import tensorflow as tf\n'), ((46063, 46091), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (46086, 46091), True, 'import tensorflow as tf\n'), ((46294, 46322), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (46317, 46322), True, 'import tensorflow as tf\n'), ((46621, 46648), 'tensorflow.transpose', 'tf.transpose', (['prelogits_pro'], {}), '(prelogits_pro)\n', (46633, 46648), True, 'import tensorflow as tf\n'), ((47903, 47921), 'tensorflow.constant', 'tf.constant', (['gamma'], {}), '(gamma)\n', (47914, 47921), True, 'import tensorflow as tf\n'), ((48614, 48660), 'tensorflow.greater', 'tf.greater', (['(m + _logits_neg - _logits_pos)', '(0.0)'], {}), '(m + _logits_neg - _logits_pos, 0.0)\n', (48624, 48660), True, 'import tensorflow as tf\n'), ((48730, 48771), 'tensorflow.nn.relu', 'tf.nn.relu', (['(m + _logits_neg - _logits_pos)'], {}), '(m + _logits_neg - _logits_pos)\n', (48740, 48771), True, 'import tensorflow as tf\n'), ((48859, 48900), 'tensorflow.nn.relu', 'tf.nn.relu', (['(m + _logits_neg - _logits_pos)'], {}), '(m + _logits_neg - _logits_pos)\n', (48869, 48900), True, 'import tensorflow as tf\n'), ((49539, 49574), 'tensorflow.square', 'tf.square', (['(features - centers_batch)'], {}), '(features - centers_batch)\n', (49548, 49574), True, 'import tensorflow as tf\n'), ((49819, 49848), 'tensorflow.square', 'tf.square', (['(features - targets)'], {}), '(features - targets)\n', (49828, 49848), True, 'import tensorflow as tf\n'), ((51841, 51859), 'tensorflow.square', 'tf.square', (['mu_diff'], {}), '(mu_diff)\n', (51850, 51859), True, 'import tensorflow as tf\n'), ((54679, 54720), 'tensorflow.reshape', 'tf.reshape', (['dist_mat', '[batch_size, 1, -1]'], {}), '(dist_mat, [batch_size, 1, -1])\n', (54689, 54720), True, 'import tensorflow as tf\n'), ((54852, 54894), 'tensorflow.reshape', 'tf.reshape', (['label_mat', '[batch_size, 1, -1]'], {}), '(label_mat, [batch_size, 1, -1])\n', (54862, 54894), True, 'import tensorflow as tf\n'), ((55734, 55762), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['valid'], {'axis': '(1)'}), '(valid, axis=1)\n', (55747, 55762), True, 'import tensorflow as tf\n'), ((55802, 55837), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(loss * valid)'], {'axis': '(1)'}), '(loss * valid, axis=1)\n', (55815, 55837), True, 'import tensorflow as tf\n'), ((56528, 56552), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['dist_pos'], {}), '(dist_pos)\n', (56542, 56552), True, 'import tensorflow as tf\n'), ((58127, 58153), 'tensorflow.exp', 'tf.exp', (['(0.5 * log_sigma_sq)'], {}), '(0.5 * log_sigma_sq)\n', (58133, 58153), True, 'import tensorflow as tf\n'), ((59785, 59817), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['scale_decay'], {}), '(scale_decay)\n', (59804, 59817), True, 'import tensorflow.contrib.slim as slim\n'), ((59847, 59875), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (59870, 59875), True, 'import tensorflow as tf\n'), ((60345, 60363), 'tensorflow.eye', 'tf.eye', (['batch_size'], {}), '(batch_size)\n', (60351, 60363), True, 'import tensorflow as tf\n'), ((60500, 60523), 'tensorflow.transpose', 'tf.transpose', (['prelogits'], {}), '(prelogits)\n', (60512, 60523), True, 'import tensorflow as tf\n'), ((61804, 61837), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['weight_decay'], {}), '(weight_decay)\n', (61823, 61837), True, 'import tensorflow.contrib.slim as slim\n'), ((61867, 61905), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {'uniform': '(False)'}), '(uniform=False)\n', (61890, 61905), True, 'import tensorflow.contrib.slim as slim\n'), ((62187, 62212), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.01)'], {}), '(0.01)\n', (62206, 62212), True, 'import tensorflow.contrib.slim as slim\n'), ((62242, 62270), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (62265, 62270), True, 'import tensorflow as tf\n'), ((62362, 62373), 'tensorflow.exp', 'tf.exp', (['(1.0)'], {}), '(1.0)\n', (62368, 62373), True, 'import tensorflow as tf\n'), ((62376, 62390), 'tensorflow.exp', 'tf.exp', (['_scale'], {}), '(_scale)\n', (62382, 62390), True, 'import tensorflow as tf\n'), ((62743, 62772), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.01)'], {}), '(0.01)\n', (62766, 62772), True, 'import tensorflow as tf\n'), ((63373, 63394), 'tensorflow.transpose', 'tf.transpose', (['weights'], {}), '(weights)\n', (63385, 63394), True, 'import tensorflow as tf\n'), ((63974, 63998), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (63996, 63998), True, 'import tensorflow as tf\n'), ((66646, 66670), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.0)'], {}), '(0.0)\n', (66665, 66670), True, 'import tensorflow.contrib.slim as slim\n'), ((66757, 66798), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': '(0.01)'}), '(stddev=0.01)\n', (66785, 66798), True, 'import tensorflow as tf\n'), ((67054, 67078), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.0)'], {}), '(0.0)\n', (67073, 67078), True, 'import tensorflow.contrib.slim as slim\n'), ((67240, 67268), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(-10)'], {}), '(-10)\n', (67263, 67268), True, 'import tensorflow as tf\n'), ((68651, 68700), 'tensorflow.one_hot', 'tf.one_hot', (['labels', 'num_classes'], {'dtype': 'tf.float32'}), '(labels, num_classes, dtype=tf.float32)\n', (68661, 68700), True, 'import tensorflow as tf\n'), ((68730, 68757), 'tensorflow.cast', 'tf.cast', (['label_mat', 'tf.bool'], {}), '(label_mat, tf.bool)\n', (68737, 68757), True, 'import tensorflow as tf\n'), ((68787, 68817), 'tensorflow.logical_not', 'tf.logical_not', (['label_mask_pos'], {}), '(label_mask_pos)\n', (68801, 68817), True, 'import tensorflow as tf\n'), ((68842, 68883), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_pos'], {}), '(dist_mat, label_mask_pos)\n', (68857, 68883), True, 'import tensorflow as tf\n'), ((68907, 68948), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['dist_mat', 'label_mask_neg'], {}), '(dist_mat, label_mask_neg)\n', (68922, 68948), True, 'import tensorflow as tf\n'), ((68973, 69010), 'tensorflow.reshape', 'tf.reshape', (['dist_pos', '[batch_size, 1]'], {}), '(dist_pos, [batch_size, 1])\n', (68983, 69010), True, 'import tensorflow as tf\n'), ((69034, 69063), 'tensorflow.reshape', 'tf.reshape', (['dist_neg', '[1, -1]'], {}), '(dist_neg, [1, -1])\n', (69044, 69063), True, 'import tensorflow as tf\n'), ((69239, 69268), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['valid_count'], {}), '(valid_count)\n', (69255, 69268), True, 'import tensorflow as tf\n'), ((69482, 69502), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (69496, 69502), True, 'import tensorflow as tf\n'), ((69587, 69619), 'tensorflow.exp', 'tf.exp', (['(0.5 * class_log_sigma_sq)'], {}), '(0.5 * class_log_sigma_sq)\n', (69593, 69619), True, 'import tensorflow as tf\n'), ((69674, 69702), 'tensorflow.exp', 'tf.exp', (['(0.5 * z_log_sigma_sq)'], {}), '(0.5 * z_log_sigma_sq)\n', (69680, 69702), True, 'import tensorflow as tf\n'), ((70438, 70473), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (70447, 70473), True, 'import tensorflow as tf\n'), ((72022, 72056), 'tensorflow.gather', 'tf.gather', (['class_mu', 'labels_target'], {}), '(class_mu, labels_target)\n', (72031, 72056), True, 'import tensorflow as tf\n'), ((72244, 72297), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['class_mu', 'labels_target', 'diff_centers'], {}), '(class_mu, labels_target, diff_centers)\n', (72258, 72297), True, 'import tensorflow as tf\n'), ((72314, 72378), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (72334, 72378), True, 'import tensorflow as tf\n'), ((72860, 72884), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.0)'], {}), '(0.0)\n', (72879, 72884), True, 'import tensorflow.contrib.slim as slim\n'), ((72914, 72939), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {}), '()\n', (72937, 72939), True, 'import tensorflow.contrib.slim as slim\n'), ((73458, 73481), 'tensorflow.shape', 'tf.shape', (['labels_unique'], {}), '(labels_unique)\n', (73466, 73481), True, 'import tensorflow as tf\n'), ((73557, 73580), 'tensorflow.shape', 'tf.shape', (['labels_unique'], {}), '(labels_unique)\n', (73565, 73580), True, 'import tensorflow as tf\n'), ((74755, 74780), 'tensorflow.contrib.slim.xavier_initializer', 'slim.xavier_initializer', ([], {}), '()\n', (74778, 74780), True, 'import tensorflow.contrib.slim as slim\n'), ((75063, 75088), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.01)'], {}), '(0.01)\n', (75082, 75088), True, 'import tensorflow.contrib.slim as slim\n'), ((75118, 75146), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), '(0.0)\n', (75141, 75146), True, 'import tensorflow as tf\n'), ((76841, 76873), 'tensorflow.gather', 'tf.gather', (['weights', 'label_target'], {}), '(weights, label_target)\n', (76850, 76873), True, 'import tensorflow as tf\n'), ((76993, 77028), 'tensorflow.unique_with_counts', 'tf.unique_with_counts', (['label_target'], {}), '(label_target)\n', (77014, 77028), True, 'import tensorflow as tf\n'), ((77060, 77095), 'tensorflow.gather', 'tf.gather', (['unique_count', 'unique_idx'], {}), '(unique_count, unique_idx)\n', (77069, 77095), True, 'import tensorflow as tf\n'), ((77127, 77160), 'tensorflow.reshape', 'tf.reshape', (['appear_times', '[-1, 1]'], {}), '(appear_times, [-1, 1])\n', (77137, 77160), True, 'import tensorflow as tf\n'), ((77329, 77380), 'tensorflow.scatter_sub', 'tf.scatter_sub', (['weights', 'label_target', 'diff_centers'], {}), '(weights, label_target, diff_centers)\n', (77343, 77380), True, 'import tensorflow as tf\n'), ((77558, 77622), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'centers_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, centers_update_op)\n', (77578, 77622), True, 'import tensorflow as tf\n'), ((4578, 4599), 'tensorflow.log', 'tf.log', (['sigma_sq_fuse'], {}), '(sigma_sq_fuse)\n', (4584, 4599), True, 'import tensorflow as tf\n'), ((4949, 4965), 'tensorflow.square', 'tf.square', (['(X - Y)'], {}), '(X - Y)\n', (4958, 4965), True, 'import tensorflow as tf\n'), ((6057, 6086), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.01)'], {}), '(0.01)\n', (6080, 6086), True, 'import tensorflow as tf\n'), ((6532, 6571), 'tensorflow.transpose', 'tf.transpose', (['weights[:, num_features:]'], {}), '(weights[:, num_features:])\n', (6544, 6571), True, 'import tensorflow as tf\n'), ((11410, 11433), 'tensorflow.square', 'tf.square', (['diff_centers'], {}), '(diff_centers)\n', (11419, 11433), True, 'import tensorflow as tf\n'), ((19335, 19346), 'tensorflow.exp', 'tf.exp', (['(1.0)'], {}), '(1.0)\n', (19341, 19346), True, 'import tensorflow as tf\n'), ((19349, 19363), 'tensorflow.exp', 'tf.exp', (['_scale'], {}), '(_scale)\n', (19355, 19363), True, 'import tensorflow as tf\n'), ((20753, 20784), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['s_init'], {}), '(s_init)\n', (20776, 20784), True, 'import tensorflow as tf\n'), ((23554, 23579), 'tensorflow.contrib.slim.l2_regularizer', 'slim.l2_regularizer', (['(0.01)'], {}), '(0.01)\n', (23573, 23579), True, 'import tensorflow.contrib.slim as slim\n'), ((23609, 23637), 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), '(1.0)\n', (23632, 23637), True, 'import tensorflow as tf\n'), ((23728, 23739), 'tensorflow.exp', 'tf.exp', (['(0.0)'], {}), '(0.0)\n', (23734, 23739), True, 'import tensorflow as tf\n'), ((23742, 23752), 'tensorflow.exp', 'tf.exp', (['s_'], {}), '(s_)\n', (23748, 23752), True, 'import tensorflow as tf\n'), ((27023, 27034), 'tensorflow.exp', 'tf.exp', (['(0.0)'], {}), '(0.0)\n', (27029, 27034), True, 'import tensorflow as tf\n'), ((27037, 27051), 'tensorflow.exp', 'tf.exp', (['_scale'], {}), '(_scale)\n', (27043, 27051), True, 'import tensorflow as tf\n'), ((28791, 28825), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(1)'}), '(weights, dim=1)\n', (28809, 28825), True, 'import tensorflow as tf\n'), ((32531, 32569), 'tensorflow.reshape', 'tf.reshape', (['dist_pos', '[batch_size, -1]'], {}), '(dist_pos, [batch_size, -1])\n', (32541, 32569), True, 'import tensorflow as tf\n'), ((32608, 32646), 'tensorflow.reshape', 'tf.reshape', (['dist_neg', '[batch_size, -1]'], {}), '(dist_neg, [batch_size, -1])\n', (32618, 32646), True, 'import tensorflow as tf\n'), ((32679, 32717), 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['(-dist_neg)'], {'axis': '(1)'}), '(-dist_neg, axis=1)\n', (32698, 32717), True, 'import tensorflow as tf\n'), ((32978, 33002), 'tensorflow.norm', 'tf.norm', (['weights'], {'axis': '(1)'}), '(weights, axis=1)\n', (32985, 33002), True, 'import tensorflow as tf\n'), ((33062, 33088), 'tensorflow.norm', 'tf.norm', (['prelogits'], {'axis': '(1)'}), '(prelogits, axis=1)\n', (33069, 33088), True, 'import tensorflow as tf\n'), ((37767, 37778), 'tensorflow.exp', 'tf.exp', (['(1.0)'], {}), '(1.0)\n', (37773, 37778), True, 'import tensorflow as tf\n'), ((37781, 37794), 'tensorflow.exp', 'tf.exp', (['alpha'], {}), '(alpha)\n', (37787, 37794), True, 'import tensorflow as tf\n'), ((40305, 40339), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(1)'}), '(weights, dim=1)\n', (40323, 40339), True, 'import tensorflow as tf\n'), ((42741, 42767), 'tensorflow.shape', 'tf.shape', (['prelogits_normed'], {}), '(prelogits_normed)\n', (42749, 42767), True, 'import tensorflow as tf\n'), ((43867, 43878), 'tensorflow.exp', 'tf.exp', (['(1.0)'], {}), '(1.0)\n', (43873, 43878), True, 'import tensorflow as tf\n'), ((43881, 43894), 'tensorflow.exp', 'tf.exp', (['alpha'], {}), '(alpha)\n', (43887, 43894), True, 'import tensorflow as tf\n'), ((47588, 47599), 'tensorflow.exp', 'tf.exp', (['(1.0)'], {}), '(1.0)\n', (47594, 47599), True, 'import tensorflow as tf\n'), ((47602, 47615), 'tensorflow.exp', 'tf.exp', (['alpha'], {}), '(alpha)\n', (47608, 47615), True, 'import tensorflow as tf\n'), ((55227, 55257), 'tensorflow.logical_not', 'tf.logical_not', (['label_mat_tile'], {}), '(label_mat_tile)\n', (55241, 55257), True, 'import tensorflow as tf\n'), ((55259, 55280), 'tensorflow.greater', 'tf.greater', (['loss', '(0.0)'], {}), '(loss, 0.0)\n', (55269, 55280), True, 'import tensorflow as tf\n'), ((56319, 56340), 'tensorflow.greater', 'tf.greater', (['loss', '(0.0)'], {}), '(loss, 0.0)\n', (56329, 56340), True, 'import tensorflow as tf\n'), ((56384, 56412), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['valid'], {'axis': '(1)'}), '(valid, axis=1)\n', (56397, 56412), True, 'import tensorflow as tf\n'), ((56604, 56628), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['dist_pos'], {}), '(dist_pos)\n', (56618, 56628), True, 'import tensorflow as tf\n'), ((57163, 57187), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['dist_pos'], {}), '(dist_pos)\n', (57177, 57187), True, 'import tensorflow as tf\n'), ((57395, 57429), 'utils.tfwatcher.insert', 'tfwatcher.insert', (['"""lneg"""', 'loss_neg'], {}), "('lneg', loss_neg)\n", (57411, 57429), False, 'from utils import tfwatcher\n'), ((63675, 63708), 'tensorflow.square', 'tf.square', (['(z_mean - weights_batch)'], {}), '(z_mean - weights_batch)\n', (63684, 63708), True, 'import tensorflow as tf\n'), ((64164, 64187), 'tensorflow.shape', 'tf.shape', (['labels_unique'], {}), '(labels_unique)\n', (64172, 64187), True, 'import tensorflow as tf\n'), ((64267, 64290), 'tensorflow.shape', 'tf.shape', (['labels_unique'], {}), '(labels_unique)\n', (64275, 64290), True, 'import tensorflow as tf\n'), ((65424, 65444), 'tensorflow.square', 'tf.square', (['(mu2 - mu1)'], {}), '(mu2 - mu1)\n', (65433, 65444), True, 'import tensorflow as tf\n'), ((68391, 68414), 'tensorflow.abs', 'tf.abs', (['(z_mu - batch_mu)'], {}), '(z_mu - batch_mu)\n', (68397, 68414), True, 'import tensorflow as tf\n'), ((68494, 68516), 'tensorflow.exp', 'tf.exp', (['z_log_sigma_sq'], {}), '(z_log_sigma_sq)\n', (68500, 68516), True, 'import tensorflow as tf\n'), ((68518, 68544), 'tensorflow.exp', 'tf.exp', (['class_log_sigma_sq'], {}), '(class_log_sigma_sq)\n', (68524, 68544), True, 'import tensorflow as tf\n'), ((69093, 69138), 'tensorflow.greater', 'tf.greater', (['(dist_pos - dist_neg + margin)', '(0.0)'], {}), '(dist_pos - dist_neg + margin, 0.0)\n', (69103, 69138), True, 'import tensorflow as tf\n'), ((69177, 69205), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['valid'], {'axis': '(1)'}), '(valid, axis=1)\n', (69190, 69205), True, 'import tensorflow as tf\n'), ((69743, 69767), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (69765, 69767), True, 'import tensorflow as tf\n'), ((70011, 70034), 'tensorflow.shape', 'tf.shape', (['labels_unique'], {}), '(labels_unique)\n', (70019, 70034), True, 'import tensorflow as tf\n'), ((70114, 70137), 'tensorflow.shape', 'tf.shape', (['labels_unique'], {}), '(labels_unique)\n', (70122, 70137), True, 'import tensorflow as tf\n'), ((70783, 70818), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[decay_op]'], {}), '([decay_op])\n', (70806, 70818), True, 'import tensorflow as tf\n'), ((70974, 71008), 'tensorflow.gather', 'tf.gather', (['class_mu', 'labels_unique'], {}), '(class_mu, labels_unique)\n', (70983, 71008), True, 'import tensorflow as tf\n'), ((71048, 71092), 'tensorflow.gather', 'tf.gather', (['class_log_sigma_sq', 'labels_unique'], {}), '(class_log_sigma_sq, labels_unique)\n', (71057, 71092), True, 'import tensorflow as tf\n'), ((71121, 71146), 'tensorflow.exp', 'tf.exp', (['(-log_sigma_sq_old)'], {}), '(-log_sigma_sq_old)\n', (71127, 71146), True, 'import tensorflow as tf\n'), ((71482, 71535), 'tensorflow.scatter_update', 'tf.scatter_update', (['class_mu', 'labels_target', 'mu_target'], {}), '(class_mu, labels_target, mu_target)\n', (71499, 71535), True, 'import tensorflow as tf\n'), ((71680, 71745), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'class_mu_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, class_mu_update_op)\n', (71700, 71745), True, 'import tensorflow as tf\n'), ((71766, 71841), 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'class_log_sigma_sq_update_op'], {}), '(tf.GraphKeys.UPDATE_OPS, class_log_sigma_sq_update_op)\n', (71786, 71841), True, 'import tensorflow as tf\n'), ((76686, 76710), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (76708, 76710), True, 'import tensorflow as tf\n'), ((77207, 77240), 'tensorflow.cast', 'tf.cast', (['appear_times', 'tf.float32'], {}), '(appear_times, tf.float32)\n', (77214, 77240), True, 'import tensorflow as tf\n'), ((77402, 77446), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[centers_update_op]'], {}), '([centers_update_op])\n', (77425, 77446), True, 'import tensorflow as tf\n'), ((12463, 12488), 'tensorflow.norm', 'tf.norm', (['features'], {'axis': '(1)'}), '(features, axis=1)\n', (12470, 12488), True, 'import tensorflow as tf\n'), ((16832, 16864), 'tensorflow.cast', 'tf.cast', (['global_step', 'tf.float32'], {}), '(global_step, tf.float32)\n', (16839, 16864), True, 'import tensorflow as tf\n'), ((21664, 21679), 'tensorflow.shape', 'tf.shape', (['label'], {}), '(label)\n', (21672, 21679), True, 'import tensorflow as tf\n'), ((56735, 56760), 'tensorflow.greater', 'tf.greater', (['loss_neg', '(0.0)'], {}), '(loss_neg, 0.0)\n', (56745, 56760), True, 'import tensorflow as tf\n'), ((56804, 56832), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['valid'], {'axis': '(1)'}), '(valid, axis=1)\n', (56817, 56832), True, 'import tensorflow as tf\n'), ((57230, 57259), 'tensorflow.nn.relu', 'tf.nn.relu', (['(margin - dist_neg)'], {}), '(margin - dist_neg)\n', (57240, 57259), True, 'import tensorflow as tf\n'), ((69303, 69343), 'tensorflow.nn.relu', 'tf.nn.relu', (['(dist_pos - dist_neg + margin)'], {}), '(dist_pos - dist_neg + margin)\n', (69313, 69343), True, 'import tensorflow as tf\n'), ((70728, 70743), 'tensorflow.log', 'tf.log', (['c_decay'], {}), '(c_decay)\n', (70734, 70743), True, 'import tensorflow as tf\n'), ((77507, 77541), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['weights'], {'dim': '(1)'}), '(weights, dim=1)\n', (77525, 77541), True, 'import tensorflow as tf\n'), ((56457, 56473), 'tensorflow.nn.relu', 'tf.nn.relu', (['loss'], {}), '(loss)\n', (56467, 56473), True, 'import tensorflow as tf\n'), ((56656, 56682), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['dist_pos'], {}), '(dist_pos)\n', (56672, 56682), True, 'import tensorflow as tf\n'), ((56882, 56921), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(valid * loss_neg)'], {'axis': '(1)'}), '(valid * loss_neg, axis=1)\n', (56895, 56921), True, 'import tensorflow as tf\n'), ((71642, 71658), 'tensorflow.log', 'tf.log', (['c_target'], {}), '(c_target)\n', (71648, 71658), True, 'import tensorflow as tf\n'), ((37945, 37977), 'tensorflow.cast', 'tf.cast', (['global_step', 'tf.float32'], {}), '(global_step, tf.float32)\n', (37952, 37977), True, 'import tensorflow as tf\n'), ((44045, 44077), 'tensorflow.cast', 'tf.cast', (['global_step', 'tf.float32'], {}), '(global_step, tf.float32)\n', (44052, 44077), True, 'import tensorflow as tf\n'), ((47766, 47798), 'tensorflow.cast', 'tf.cast', (['global_step', 'tf.float32'], {}), '(global_step, tf.float32)\n', (47773, 47798), True, 'import tensorflow as tf\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # import argparse import logging # import os import sys import matplotlib.pyplot as plt import numpy as np # from matplotlib import cm # from mud import __version__ as __mud_version__ from scipy.stats import gaussian_kde as kde # A standard kernel density estimator from scipy.stats import norm, uniform # The standard Normal distribution # from mud_examples import __version__ from mud_examples.parsers import parse_args from mud_examples.utils import check_dir plt.rcParams["figure.figsize"] = 10, 10 plt.rcParams["font.size"] = 24 __author__ = "<NAME>" __copyright__ = "Mathematical Michael" __license__ = "mit" _logger = logging.getLogger(__name__) # TODO: use this def setup_logging(loglevel): """Setup basic logging Args: loglevel (int): minimum loglevel for emitting messages """ logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" logging.basicConfig( level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S" ) def main(args): """ Main entrypoint for example-generation """ args = parse_args(args) setup_logging(args.loglevel) np.random.seed(args.seed) # example = args.example # num_trials = args.num_trials # fsize = args.fsize # linewidth = args.linewidth # seed = args.seed # inputdim = args.input_dim # save = args.save # alt = args.alt # bayes = args.bayes # prefix = args.prefix # dist = args.dist fdir = "figures/comparison" check_dir(fdir) presentation = False save = True if not presentation: plt.rcParams["mathtext.fontset"] = "stix" plt.rcParams["font.family"] = "STIXGeneral" # number of samples from initial and observed mean (mu) and st. dev (sigma) N, mu, sigma = int(1e3), 0.25, 0.1 lam = np.random.uniform(low=-1, high=1, size=N) # Evaluate the QoI map on this initial sample set to form a predicted data qvals_predict = QoI(lam, 5) # Evaluate lam^5 samples # Estimate the push-forward density for the QoI pi_predict = kde(qvals_predict) # Compute more observations for use in BIP tick_fsize = 28 legend_fsize = 24 for num_data in [1, 5, 10, 20]: np.random.seed( 123456 ) # Just for reproducibility, you can comment out if you want. data = norm.rvs(loc=mu, scale=sigma ** 2, size=num_data) # We will estimate the observed distribution using a parametric estimate to keep # the assumptions involved as similar as possible between the BIP and the SIP # So, we will assume the sigma is known but that the mean mu is unknown and estimated # from data to fit a Gaussian distribution mu_est = np.mean(data) r_approx = np.divide( norm.pdf(qvals_predict, loc=mu_est, scale=sigma), pi_predict(qvals_predict) ) # Use r to compute weighted KDE approximating the updated density update_kde = kde(lam, weights=r_approx) # Construct estimated push-forward of this updated density pf_update_kde = kde(qvals_predict, weights=r_approx) likelihood_vals = np.zeros(N) for i in range(N): likelihood_vals[i] = data_likelihood( qvals_predict[i], data, num_data, sigma ) # compute normalizing constants C_nonlinear = np.mean(likelihood_vals) data_like_normalized = likelihood_vals / C_nonlinear posterior_kde = kde(lam, weights=data_like_normalized) # Construct push-forward of statistical Bayesian posterior pf_posterior_kde = kde(qvals_predict, weights=data_like_normalized) # Plot the initial, updated, and posterior densities fig, ax = plt.subplots(figsize=(10, 10)) lam_plot = np.linspace(-1, 1, num=1000) ax.plot( lam_plot, uniform.pdf(lam_plot, loc=-1, scale=2), "b--", linewidth=4, label="Initial/Prior", ) ax.plot(lam_plot, update_kde(lam_plot), "k-.", linewidth=4, label="Update") ax.plot(lam_plot, posterior_kde(lam_plot), "g:", linewidth=4, label="Posterior") ax.set_xlim([-1, 1]) if num_data > 1: plt.annotate(f"$N={num_data}$", (-0.75, 5), fontsize=legend_fsize * 1.5) ax.set_ylim([0, 28]) # fix axis height for comparisons # else: # ax.set_ylim([0, 5]) ax.tick_params(axis="x", labelsize=tick_fsize) ax.tick_params(axis="y", labelsize=tick_fsize) ax.set_xlabel("$\\Lambda$", fontsize=1.25 * tick_fsize) ax.legend(fontsize=legend_fsize, loc="upper left") if save: fig.savefig(f"{fdir}/bip-vs-sip-{num_data}.png", bbox_inches="tight") plt.close(fig) # plt.show() # Plot the push-forward of the initial, observed density, # and push-forward of pullback and stats posterior fig, ax = plt.subplots(figsize=(10, 10)) qplot = np.linspace(-1, 1, num=1000) ax.plot( qplot, norm.pdf(qplot, loc=mu, scale=sigma), "r-", linewidth=6, label="$N(0.25, 0.1^2)$", ) ax.plot(qplot, pi_predict(qplot), "b-.", linewidth=4, label="PF of Initial") ax.plot(qplot, pf_update_kde(qplot), "k--", linewidth=4, label="PF of Update") ax.plot( qplot, pf_posterior_kde(qplot), "g:", linewidth=4, label="PF of Posterior" ) ax.set_xlim([-1, 1]) if num_data > 1: plt.annotate(f"$N={num_data}$", (-0.75, 5), fontsize=legend_fsize * 1.5) ax.set_ylim([0, 28]) # fix axis height for comparisons # else: # ax.set_ylim([0, 5]) ax.tick_params(axis="x", labelsize=tick_fsize) ax.tick_params(axis="y", labelsize=tick_fsize) ax.set_xlabel("$\\mathcal{D}$", fontsize=1.25 * tick_fsize) ax.legend(fontsize=legend_fsize, loc="upper left") if save: fig.savefig(f"{fdir}/bip-vs-sip-pf-{num_data}.png", bbox_inches="tight") plt.close(fig) # plt.show() def run(): main(sys.argv[1:]) ############################################################ def QoI(lam, p): """ Defines a QoI mapping function as monomials to some power p """ q = lam ** p return q def data_likelihood(qvals, data, num_data, sigma): v = 1.0 for i in range(num_data): v *= norm.pdf(qvals - data[i], loc=0, scale=sigma) return v if __name__ == "__main__": run()
[ "numpy.random.uniform", "numpy.random.seed", "scipy.stats.uniform.pdf", "logging.basicConfig", "matplotlib.pyplot.annotate", "scipy.stats.norm.rvs", "matplotlib.pyplot.close", "scipy.stats.gaussian_kde", "numpy.zeros", "scipy.stats.norm.pdf", "mud_examples.utils.check_dir", "numpy.mean", "nu...
[((681, 708), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (698, 708), False, 'import logging\n'), ((936, 1041), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'loglevel', 'stream': 'sys.stdout', 'format': 'logformat', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(level=loglevel, stream=sys.stdout, format=logformat,\n datefmt='%Y-%m-%d %H:%M:%S')\n", (955, 1041), False, 'import logging\n'), ((1140, 1156), 'mud_examples.parsers.parse_args', 'parse_args', (['args'], {}), '(args)\n', (1150, 1156), False, 'from mud_examples.parsers import parse_args\n'), ((1194, 1219), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (1208, 1219), True, 'import numpy as np\n'), ((1664, 1679), 'mud_examples.utils.check_dir', 'check_dir', (['fdir'], {}), '(fdir)\n', (1673, 1679), False, 'from mud_examples.utils import check_dir\n'), ((1979, 2020), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-1)', 'high': '(1)', 'size': 'N'}), '(low=-1, high=1, size=N)\n', (1996, 2020), True, 'import numpy as np\n'), ((2229, 2247), 'scipy.stats.gaussian_kde', 'kde', (['qvals_predict'], {}), '(qvals_predict)\n', (2232, 2247), True, 'from scipy.stats import gaussian_kde as kde\n'), ((2382, 2404), 'numpy.random.seed', 'np.random.seed', (['(123456)'], {}), '(123456)\n', (2396, 2404), True, 'import numpy as np\n'), ((2504, 2553), 'scipy.stats.norm.rvs', 'norm.rvs', ([], {'loc': 'mu', 'scale': '(sigma ** 2)', 'size': 'num_data'}), '(loc=mu, scale=sigma ** 2, size=num_data)\n', (2512, 2553), False, 'from scipy.stats import norm, uniform\n'), ((2892, 2905), 'numpy.mean', 'np.mean', (['data'], {}), '(data)\n', (2899, 2905), True, 'import numpy as np\n'), ((3131, 3157), 'scipy.stats.gaussian_kde', 'kde', (['lam'], {'weights': 'r_approx'}), '(lam, weights=r_approx)\n', (3134, 3157), True, 'from scipy.stats import gaussian_kde as kde\n'), ((3250, 3286), 'scipy.stats.gaussian_kde', 'kde', (['qvals_predict'], {'weights': 'r_approx'}), '(qvals_predict, weights=r_approx)\n', (3253, 3286), True, 'from scipy.stats import gaussian_kde as kde\n'), ((3314, 3325), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (3322, 3325), True, 'import numpy as np\n'), ((3536, 3560), 'numpy.mean', 'np.mean', (['likelihood_vals'], {}), '(likelihood_vals)\n', (3543, 3560), True, 'import numpy as np\n'), ((3647, 3685), 'scipy.stats.gaussian_kde', 'kde', (['lam'], {'weights': 'data_like_normalized'}), '(lam, weights=data_like_normalized)\n', (3650, 3685), True, 'from scipy.stats import gaussian_kde as kde\n'), ((3781, 3829), 'scipy.stats.gaussian_kde', 'kde', (['qvals_predict'], {'weights': 'data_like_normalized'}), '(qvals_predict, weights=data_like_normalized)\n', (3784, 3829), True, 'from scipy.stats import gaussian_kde as kde\n'), ((3910, 3940), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (3922, 3940), True, 'import matplotlib.pyplot as plt\n'), ((3960, 3988), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)'], {'num': '(1000)'}), '(-1, 1, num=1000)\n', (3971, 3988), True, 'import numpy as np\n'), ((5139, 5169), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (5151, 5169), True, 'import matplotlib.pyplot as plt\n'), ((5186, 5214), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)'], {'num': '(1000)'}), '(-1, 1, num=1000)\n', (5197, 5214), True, 'import numpy as np\n'), ((6675, 6720), 'scipy.stats.norm.pdf', 'norm.pdf', (['(qvals - data[i])'], {'loc': '(0)', 'scale': 'sigma'}), '(qvals - data[i], loc=0, scale=sigma)\n', (6683, 6720), False, 'from scipy.stats import norm, uniform\n'), ((2949, 2997), 'scipy.stats.norm.pdf', 'norm.pdf', (['qvals_predict'], {'loc': 'mu_est', 'scale': 'sigma'}), '(qvals_predict, loc=mu_est, scale=sigma)\n', (2957, 2997), False, 'from scipy.stats import norm, uniform\n'), ((4040, 4078), 'scipy.stats.uniform.pdf', 'uniform.pdf', (['lam_plot'], {'loc': '(-1)', 'scale': '(2)'}), '(lam_plot, loc=-1, scale=2)\n', (4051, 4078), False, 'from scipy.stats import norm, uniform\n'), ((4408, 4480), 'matplotlib.pyplot.annotate', 'plt.annotate', (['f"""$N={num_data}$"""', '(-0.75, 5)'], {'fontsize': '(legend_fsize * 1.5)'}), "(f'$N={num_data}$', (-0.75, 5), fontsize=legend_fsize * 1.5)\n", (4420, 4480), True, 'import matplotlib.pyplot as plt\n'), ((4959, 4973), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4968, 4973), True, 'import matplotlib.pyplot as plt\n'), ((5263, 5299), 'scipy.stats.norm.pdf', 'norm.pdf', (['qplot'], {'loc': 'mu', 'scale': 'sigma'}), '(qplot, loc=mu, scale=sigma)\n', (5271, 5299), False, 'from scipy.stats import norm, uniform\n'), ((5745, 5817), 'matplotlib.pyplot.annotate', 'plt.annotate', (['f"""$N={num_data}$"""', '(-0.75, 5)'], {'fontsize': '(legend_fsize * 1.5)'}), "(f'$N={num_data}$', (-0.75, 5), fontsize=legend_fsize * 1.5)\n", (5757, 5817), True, 'import matplotlib.pyplot as plt\n'), ((6303, 6317), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (6312, 6317), True, 'import matplotlib.pyplot as plt\n')]
import pandas as pd import numpy as np import os, sys, glob, time, gc import plotly.graph_objs as go from plotly.offline import init_notebook_mode, iplot import torch # calculate M values using a single DD interaction model. def M_list_return(time_table, wL_value, AB_list, n_pulse): AB_list = np.array(AB_list) A = AB_list[:,0].reshape(len(AB_list), 1) # (annotated output dimensions in following lines) B = AB_list[:,1].reshape(len(AB_list), 1) # a,1 a = len(AB_list) w_tilda = pow(pow(A+wL_value, 2) + B*B, 1/2) # a,1 mz = (A + wL_value) / w_tilda # a,1 mx = B / w_tilda # a,1 alpha = w_tilda * time_table.reshape(1, len(time_table)) # a,b b=len(time_table) beta = wL_value * time_table.reshape(1, len(time_table)) # 1,b phi = np.arccos(np.cos(alpha) * np.cos(beta) - mz * np.sin(alpha) * np.sin(beta)) # a,b K1 = (1 - np.cos(alpha)) * (1 - np.cos(beta)) # a,b K2 = 1 + np.cos(phi) # a,b K = pow(mx,2) * (K1 / K2) # a,b M_list_temp = 1 - K * pow(np.sin(n_pulse * phi/2), 2) # a,b M_list = np.prod(M_list_temp, axis=0) return M_list # return modified data by adding marginal_values to the original data def get_marginal_arr(arr_data, margin_value, random_type='uni', mean=0, std=1): if random_type=='uni': return arr_data + np.random.uniform(low=-margin_value, high=margin_value, size=arr_data.shape) elif random_type=='nor': return arr_data + (std*np.random.randn(size=arr_data.shape) - mean) # generate target (A,B) candidates with repect to B range from the target AB list(variable: target_AB). def gen_target_wrt_B(target_AB, class_batch, B_resol, B_start, B_num, B_target_gap): ''' This generate target spin lists divided by B range return: numpy array _ shape: (B_num, class_batch, 2) ''' target_lists = np.zeros((B_num, class_batch, 2)) B_value_lists = np.arange(B_start, B_start+B_resol*B_num, B_resol) for idx, B_temp in enumerate(B_value_lists): indices = ((target_AB[:, 1] >= B_temp+B_target_gap) & (target_AB[:, 1] < (B_temp+B_resol-B_target_gap))) target_temp = target_AB[indices] indices = np.random.randint(target_temp.shape[0], size=class_batch) target_lists[idx] = target_temp[indices] return target_lists # generate side (A,B) candidates of the target period but of different B values. def gen_side_same_ABlist(target_AB, side_same_num, B_resol, B_start, B_num, B_side_gap, B_side_max): indices = ((target_AB[:, 1] < B_start-B_side_gap) | ((target_AB[:, 1] > B_start+(B_resol*B_num)+B_side_gap) & (target_AB[:, 1]<B_side_max))) side_temp = target_AB[indices] indices = np.random.randint(side_temp.shape[0], size=side_same_num) side_same_AB_candi = side_temp[indices] return side_same_AB_candi # generate side (A,B) candidates of the A range: range(25000, 55000, 10000) of B values with (B_side_min, B_side_max) def gen_mid_AB_candi(A_start, AB_lists_dic, B_side_min, B_side_max, side_num): idx_lists = np.arange(25000, 55000, 10000) AB_mid_candi = np.zeros((2*idx_lists.shape[0], side_num, 2)) for idx, temp_idx in enumerate(idx_lists): try: temp_list = AB_lists_dic[A_start+temp_idx] indices = ((temp_list[:,1]>B_side_min) & (temp_list[:,1]<B_side_max)) AB_list_temp = temp_list[indices] indices = np.random.randint(AB_list_temp.shape[0], size=side_num) AB_mid_candi[2*idx] = AB_list_temp[indices] temp_list = AB_lists_dic[A_start-temp_idx] indices = ((temp_list[:,1]>B_side_min) & (temp_list[:,1]<B_side_max)) AB_list_temp = temp_list[indices] indices = np.random.randint(AB_list_temp.shape[0], size=side_num) AB_mid_candi[2*idx+1] = AB_list_temp[indices] except IndexError: print("AB_mid_candi_IndexError: {}".format(temp_idx)) return AB_mid_candi[:2*idx] return AB_mid_candi # generate side (A,B) candidates of the A range: range(55000, 105000, 10000) of B values with (B_side_min, B_side_max) def gen_far_AB_candi(A_start, AB_lists_dic, B_side_min, B_side_max, side_num): idx_lists = np.arange(55000, 105000, 10000) AB_far_candi = np.zeros((2*idx_lists.shape[0], side_num, 2)) for idx, temp_idx in enumerate(idx_lists): try: temp_list = AB_lists_dic[A_start+temp_idx] indices = ((temp_list[:,1]>B_side_min) & (temp_list[:,1]<B_side_max)) AB_list_temp = temp_list[indices] indices = np.random.randint(AB_list_temp.shape[0], size=side_num) AB_far_candi[2*idx] = AB_list_temp[indices] temp_list = AB_lists_dic[A_start-temp_idx] indices = ((temp_list[:,1]>B_side_min) & (temp_list[:,1]<B_side_max)) AB_list_temp = temp_list[indices] indices = np.random.randint(AB_list_temp.shape[0], size=side_num) AB_far_candi[2*idx+1] = AB_list_temp[indices] except IndexError: print("AB_far_candi_IndexError: {}".format(temp_idx)) return AB_far_candi[:2*idx] return AB_far_candi # generate random (A, B) lists with batch size. (allowing for picking the same (A, B) candidates in the batch) def gen_random_lists_wrt_batch(AB_lists, batch): indices = np.random.randint(AB_lists.shape[0], size=batch) return AB_lists[indices] # generate (A, B) candidates with respect to the ratio for each B ranges. def gen_divided_wrt_B_bounds(AB_lists, bound_list, side_num): total_AB_lists = [] first_scale = 10 - np.sum(bound_list[:,1]) for idx, [bound, scale] in enumerate(bound_list): if idx==0: indices, = np.where(AB_lists[:, 1] <= bound) if len(indices)==0:pass else: total_AB_lists.append(gen_random_lists_wrt_batch(AB_lists[indices], int(side_num*first_scale))) indices, = np.where((AB_lists[:, 1] > bound) & (AB_lists[:, 1] <= bound_list[idx+1][0])) if len(indices)==0:pass else: total_AB_lists.append(gen_random_lists_wrt_batch(AB_lists[indices], int(side_num*scale))) elif idx==(len(bound_list)-1): indices, = np.where(AB_lists[:, 1] > bound) if len(indices)==0:pass else: total_AB_lists.append(gen_random_lists_wrt_batch(AB_lists[indices], int(side_num*scale))) else: indices, = np.where((AB_lists[:, 1] > bound) & (AB_lists[:, 1] <= bound_list[idx+1][0])) if len(indices)==0:pass else: total_AB_lists.append(gen_random_lists_wrt_batch(AB_lists[indices], int(side_num*scale))) for idx, temp_AB in enumerate(total_AB_lists): if idx==0: total_flatten = temp_AB.copy() else: total_flatten = np.concatenate((total_flatten, temp_AB), axis=0) np.random.shuffle(total_flatten) return total_flatten def gen_side_AB_candidates(*args): AB_lists_dic, A_side_idx_lists, side_num, B_side_min, B_side_max, bound_list, spin_zero_scale, class_num, class_batch, A_side_margin, side_candi_num = args for chosen_num in range(side_candi_num): side_AB_candi = np.zeros((A_side_idx_lists.shape[0], side_num, 2)) for idx, A_side_idx in enumerate(A_side_idx_lists): indices = ((AB_lists_dic[A_side_idx][:, 1] > B_side_min) & (AB_lists_dic[A_side_idx][:, 1] < B_side_max)) side_AB_temp = AB_lists_dic[A_side_idx][indices] indices = np.random.randint(side_AB_temp.shape[0], size=side_num) side_AB_candi[idx] = side_AB_temp[indices] side_AB_candi = side_AB_candi.reshape(-1, side_AB_candi.shape[-1]) side_AB_candi[:,0] = get_marginal_arr(side_AB_candi[:,0], A_side_margin) side_AB_candi_divided = gen_divided_wrt_B_bounds(side_AB_candi, bound_list, side_num) scaled_batch = int(class_batch*(1-spin_zero_scale['side'])) indices = np.random.randint(side_AB_candi_divided.shape[0], size=(class_num, scaled_batch)) AB_candidates_side = side_AB_candi_divided[indices] zero_candi = np.zeros((class_num, class_batch-scaled_batch, 2)) AB_candidates_side = np.concatenate((AB_candidates_side, zero_candi), axis=1) indices = np.random.randint(AB_candidates_side.shape[1], size=AB_candidates_side.shape[1]) AB_candidates_side = AB_candidates_side[:, indices, :] if chosen_num == 0: total_AB_candidates_side = np.expand_dims(AB_candidates_side, -2) else: total_AB_candidates_side = np.concatenate(( total_AB_candidates_side, np.expand_dims(AB_candidates_side, -2), ), axis=-2) return total_AB_candidates_side def gen_AB_candidates(is_hierarchical=False, *args): ''' This fuction generates (A, B) candidates with respect to keyword arguments listed below. AB_lists_dic: set of (A, B) lists grouped w.r.t. the local period. A_num : divided number of classes within the range: A_start ~ (A_start - A_resol*A_num) B_num : divided number of classes within the range: B_start ~ (B_start - B_resol*B_num) A_start : the initial value of A (Hz) in the target range ( cf) target range means A for [A_start ~ (A_start - A_resol*A_num)], B for [B_start ~ (B_start - B_resol*B_num)] B_start : the initial value of B (Hz) in the target range A_resol : the division resolution of A in the target range B_resol : the division resolution of B in the target range A_side_num : this determines 'how many (A, B) lists to be selected within the side range A_side_resol : the distance between each side spin in the lists above. B_side_min : the minimum B value of side spins B_side_max : the maximum B value of side spins B_target_gap : the distance of B value between each divided target range B_side_gap : the distance of B value between the same side range and the target range. (this highly affects the accuracy of training) A_target_margin : the marginal area of target A value A_side_margin : the marginal area of side A value A_far_side_margin : the marginal area of far side A value class_batch : batch size per class (=cpu_num_for_multi*batch_for_multi) class_num : this determines how many classes in a target AB candidates bound_list : dipicted below spin_zero_scale : this determines how many zero value spins included in (A, B) candidates A_side_start : the initial A value of side spins A_side_end : the end A value of side spins side_same_num : the variable determines 'how many spins in the (A, B) spin candidates for the same side spins. side_num : the variable determines 'how many spins in the (A, B) spin candidates for the side spins. side_candi_num : this determinces 'how many side spins' would be incldued per sample data. ''' AB_lists_dic, A_num, B_num, A_start, B_start, A_resol, B_resol, A_side_num, A_side_resol, B_side_min, \ B_side_max, B_target_gap, B_side_gap, A_target_margin, A_side_margin, A_far_side_margin, \ class_batch, class_num, bound_list, spin_zero_scale, \ A_side_start, A_side_end, side_same_num, side_num, side_candi_num = args A_idx_list = np.arange(A_start, A_start+A_resol*A_num, A_resol) # generate A lists for each class target_AB_candi = np.zeros((class_num-1, class_batch, 2)) hier_target_AB_candi = np.zeros((class_num-1, class_batch*16, 2)) side_same_target_candi = np.zeros((A_idx_list.shape[0], side_same_num, 2)) for idx, A_idx in enumerate(A_idx_list): target_AB = AB_lists_dic[A_idx] target_AB_candi[B_num*idx:B_num*(idx+1)] = gen_target_wrt_B(target_AB, class_batch, B_resol, B_start, B_num, B_target_gap) # target A list is divided by B range if spin_zero_scale['same'] != 1.: side_same_target_candi[idx] = gen_side_same_ABlist(target_AB, side_same_num, B_resol, B_start, B_num, B_side_gap, B_side_max) if is_hierarchical==True: hier_target_AB_candi[B_num*idx:B_num*(idx+1)] = gen_target_wrt_B(target_AB, class_batch*16, B_resol, B_start, B_num, B_target_gap) side_same_target_candi = side_same_target_candi.reshape(-1, side_same_target_candi.shape[-1]) side_same_target_candi[:,0] = get_marginal_arr(side_same_target_candi[:,0], A_side_margin) target_AB_candi[:,:,0] = get_marginal_arr(target_AB_candi[:,:,0], A_target_margin) A_side_idx_lists = np.hstack((np.arange(A_side_start, A_side_start-A_side_resol*A_side_num, -A_side_resol), np.arange(A_side_end, A_side_end+A_side_resol*A_side_num, A_side_resol))) args = AB_lists_dic, A_side_idx_lists, side_num, B_side_min, B_side_max, bound_list, spin_zero_scale, class_num, class_batch, A_side_margin, side_candi_num AB_candidates_side = gen_side_AB_candidates(*args) AB_far_candi = gen_far_AB_candi(A_start+A_resol*(A_num//2), AB_lists_dic, B_side_min, B_side_max, side_num) AB_far_candi = AB_far_candi.reshape(-1, AB_far_candi.shape[2]) AB_far_candi[:,0] = get_marginal_arr(AB_far_candi[:,0], A_far_side_margin) AB_mid_candi = gen_mid_AB_candi(A_start+A_resol*(A_num//2), AB_lists_dic, B_side_min, B_side_max, side_num) AB_mid_candi = AB_mid_candi.reshape(-1, AB_mid_candi.shape[2]) AB_mid_candi[:,0] = get_marginal_arr(AB_mid_candi[:,0], A_far_side_margin) side_same_target_candi_divided = gen_divided_wrt_B_bounds(side_same_target_candi, bound_list, side_num) AB_mid_candi_divided = gen_divided_wrt_B_bounds(AB_mid_candi, bound_list, side_num) AB_far_candi_divided = gen_divided_wrt_B_bounds(AB_far_candi, bound_list, side_num) scaled_batch = int(class_batch*(1-spin_zero_scale['mid'])) indices = np.random.randint(AB_mid_candi_divided.shape[0], size=(class_num, scaled_batch)) AB_candidates_mid = AB_mid_candi_divided[indices] zero_candi = np.zeros((class_num, class_batch-scaled_batch, 2)) AB_candidates_mid = np.concatenate((AB_candidates_mid, zero_candi), axis=1) indices = np.random.randint(AB_candidates_mid.shape[1], size=AB_candidates_mid.shape[1]) AB_candidates_mid = AB_candidates_mid[:, indices, :] scaled_batch = int(class_batch*(1-spin_zero_scale['far'])) indices = np.random.randint(AB_far_candi_divided.shape[0], size=(class_num, scaled_batch)) AB_candidates_far = AB_far_candi_divided[indices] zero_candi = np.zeros((class_num, class_batch-scaled_batch, 2)) AB_candidates_far = np.concatenate((AB_candidates_far, zero_candi), axis=1) indices = np.random.randint(AB_candidates_far.shape[1], size=AB_candidates_far.shape[1]) AB_candidates_far = AB_candidates_far[:, indices, :] scaled_batch = int(class_batch*(1-spin_zero_scale['same'])) indices = np.random.randint(side_same_target_candi_divided.shape[0], size=(class_num, scaled_batch)) AB_candidates_side_same = side_same_target_candi_divided[indices] zero_candi = np.zeros((class_num, class_batch-scaled_batch, 2)) AB_candidates_side_same = np.concatenate((AB_candidates_side_same, zero_candi), axis=1) indices = np.random.randint(AB_candidates_side_same.shape[1], size=AB_candidates_side_same.shape[1]) AB_candidates_side_same = AB_candidates_side_same[:, indices, :] indices = np.random.randint(AB_candidates_side.reshape(-1, 2).shape[0], size=(1, class_batch)) AB_pseudo_target = AB_candidates_side.reshape(-1, 2)[indices] target_AB_candi = np.concatenate((AB_pseudo_target, target_AB_candi), axis=0) AB_candidates = np.concatenate(( np.expand_dims(target_AB_candi, -2), np.expand_dims(AB_candidates_mid, -2), np.expand_dims(AB_candidates_far, -2), AB_candidates_side, np.expand_dims(AB_candidates_side_same, -2), ), axis=-2) return AB_candidates, hier_target_AB_candi # generate model index with respect to the image_width and time index threshold def get_model_index(total_indices, A_idx, *, time_thres_idx, image_width): temp_index = total_indices[A_idx][1] model_index = np.array([range(k-image_width, k+image_width+1) for k in temp_index if (((k-image_width)>0) & (k < (time_thres_idx-image_width)))]) return model_index def gen_TPk_AB_candidates(AB_target_set: "[[A1,B1],[A2,B2],..]", is_hierarchical=False, *args) -> "total_AB_candi, total_Y_train_arr": ''' The function generates (A,B) candidates with respect to each TPk of 'AB_target_set' variable. bound_list: the divided ratio w.r.t the range of B. This reflects the fact that the number of nuclear spins in diamond becomes bigger as the distance from the NV center becomes longer. --> therefore, the amount of spins should increase as B increases. ''' AB_lists_dic, N_PULSE, A_num, B_num, A_resol, B_resol, A_side_num, A_side_resol, B_side_min,\ B_side_max, B_target_gap, B_side_gap, A_target_margin, A_side_margin, A_far_side_margin,\ class_batch, class_num, spin_zero_scale, distance_btw_target_side, side_candi_num = args total_AB_candi = np.zeros((class_num, len(AB_target_set)*class_batch, 4+side_candi_num, 2)) # CAUTION: '3rd dimension' of 'total_AB_candi' is determined by the output of 'gen_AB_candidates' function total_Y_train_arr = np.zeros((class_num, len(AB_target_set)*class_batch, class_num)) # one-hot vector for each class total_hier_target_AB_candi = [] for target_index, [A_start, B_start] in enumerate(AB_target_set): if N_PULSE<=32: if B_start<15000: bound_list = np.array([[5000, 4], [11000, 2], [18000, 1], [35000, 1]]) # the 'first' ratio = 10 - all the rest of rates # in this case, the 'first' ratio -> 10-(4+2+1+1)=2 # meaning that (A,B) candidates in the 'first' range will make up for "20%" of the whole cadidates. else: bound_list = np.array([[8000, 3], [15000, 3], [27000, 2.5], [45000, 1]]) elif (32<N_PULSE) & (N_PULSE<=64): bound_list = np.array([[7000, 3], [13500, 3], [27000, 2.5], [45000, 1]]) elif (64<N_PULSE) & (N_PULSE<=96): bound_list = np.array([[6000, 3], [12000, 3], [27000, 2.5], [45000, 1]]) elif (96<N_PULSE) & (N_PULSE<=128): bound_list = np.array([[4000, 3], [11000, 3], [25000, 2.5], [45000, 1]]) elif 128<N_PULSE: bound_list = np.array([[1500, 4], [7500, 2], [17000, 1], [35000, 1]]) if is_hierarchical==True: A_side_start_margin = A_target_margin + distance_btw_target_side # 'distance' between target boundary and side boundary A_side_start = AB_target_set[0][0] - A_side_start_margin # 'left' starting point of A side A_side_end = AB_target_set[-1][0] + A_resol*(A_num-1) + A_side_start_margin # 'right' starting point of A side. 'A_start' means the center value of A_class else: A_side_start_margin = A_target_margin + distance_btw_target_side A_side_start = A_start - A_side_start_margin A_side_end = A_start + A_resol*(A_num-1) + A_side_start_margin side_same_num = AB_lists_dic[A_start].shape[0]*10 # these two variables determine 'how many spins in the (A, B) spin candidates for the same side and side spins. side_num = AB_lists_dic[A_start].shape[0]*10 # side_same_num, side_num are intentionally chosen 10 times larger than ABlists for these variables to have enough randomness # when generating (A, B) same_side(or side) candidates from these variables. args_AB_candi = (AB_lists_dic, A_num, B_num, A_start, B_start, A_resol, B_resol, A_side_num, A_side_resol, B_side_min, B_side_max, B_target_gap, B_side_gap, A_target_margin, A_side_margin, A_far_side_margin, class_batch, class_num, bound_list, spin_zero_scale, A_side_start, A_side_end, side_same_num, side_num, side_candi_num) AB_candidates, hier_target_AB_candi = gen_AB_candidates(is_hierarchical, *args_AB_candi) total_hier_target_AB_candi.append(hier_target_AB_candi) for total_idx in range(len(AB_candidates)): total_AB_candi[total_idx, target_index*class_batch:(target_index+1)*class_batch] = AB_candidates[total_idx] total_Y_train_arr[total_idx, target_index*class_batch:(target_index+1)*class_batch, total_idx] = 1 return total_AB_candi, total_Y_train_arr, np.array(total_hier_target_AB_candi).squeeze() # pre-processing of Px value def pre_processing(data: 'Px value', power=4): return 1-data**power def gen_M_arr_batch(AB_lists_batch, indexing, time_data, WL, PULSE, is_pre_processing=False, pre_process_scale=4, noise_scale=0., spin_bath=0., existing_spins_M=0): ''' The function generates M value array batch ''' index_flat = indexing.flatten() X_train_arr_batch = np.zeros((len(AB_lists_batch), indexing.shape[0], indexing.shape[1])) if type(spin_bath) == float: for idx1, AB_list_temp in enumerate(AB_lists_batch): X_train_arr_batch[idx1,:] = M_list_return(time_data[index_flat]*1e-6, WL, AB_list_temp*2*np.pi, PULSE).reshape(indexing.shape) else: for idx1, AB_list_temp in enumerate(AB_lists_batch): X_train_arr_batch[idx1,:] = (spin_bath[index_flat]*M_list_return(time_data[index_flat]*1e-6, WL, AB_list_temp*2*np.pi, PULSE)).reshape(indexing.shape) X_train_arr_batch = X_train_arr_batch.reshape(len(AB_lists_batch), len(indexing), len(indexing[2])) if noise_scale>0: X_train_arr_batch += np.random.uniform(size=X_train_arr_batch.shape)*noise_scale - np.random.uniform(size=X_train_arr_batch.shape)*noise_scale if is_pre_processing==True: if type(existing_spins_M)==int: return pre_processing((1+X_train_arr_batch)/2, power=pre_process_scale) else: return pre_processing((1+X_train_arr_batch*existing_spins_M)/2, power=pre_process_scale) else: if type(existing_spins_M)==int: return 1-X_train_arr_batch else: return 1-X_train_arr_batch*existing_spins_M # return A value of TPk from the input (A, B) candidate def return_TPk_from_AB(A: 'Hz', B: 'Hz', WL, k=10) -> "A(Hz)": A_temp = int(round(A*0.01)*100) A_list = np.arange(A_temp-15000, A_temp+15000, 50)*2*np.pi A *= 2*np.pi B *= 2*np.pi w_tilda = np.sqrt((A+WL)**2 + B**2) tau = np.pi*(2*k - 1) / (w_tilda + WL) B_ref = 10000*2*np.pi w_tilda_list = np.sqrt((A_list+WL)**2 + B_ref**2) tau_list = np.pi*(2*k - 1) / (w_tilda_list + WL) min_idx = np.argmin(np.abs(tau_list - tau)) return int(round(A_list[min_idx]/2/np.pi, 0)) # return [A_start, A_end, B_start, B_end] lists for HPC models def get_AB_model_lists(A_init, A_final, A_step: 'A step between models', A_range: 'A range of one model', B_init, B_final): A_list1 = np.arange(A_init, A_final+A_step, A_step) A_list2 = A_list1 + A_range B_list1 = np.full(A_list1.shape, B_init) B_list2 = np.full(A_list1.shape, B_final) return np.stack((A_list1, A_list2, B_list1, B_list2)).T def return_existing_spins_wrt_margins(existing_spins, reference_spins, A_existing_margin, B_existing_margin): ''' This function revises spin lists by merging the existing spins with the reference spins (with adding margins) ''' existing_spins = np.repeat(np.expand_dims(existing_spins, axis=0), reference_spins.shape[1], axis=0) existing_spins = np.repeat(np.expand_dims(existing_spins, axis=0), reference_spins.shape[0], axis=0) A_margin_arr = np.random.uniform(low=-A_existing_margin, high=A_existing_margin, size=(existing_spins.shape)) B_margin_arr = np.random.uniform(low=-B_existing_margin, high=B_existing_margin, size=(existing_spins.shape)) existing_spins[:,:,:,0] += A_margin_arr[:,:,:,0] existing_spins[:,:,:,1] += B_margin_arr[:,:,:,1] return np.concatenate((reference_spins, existing_spins), axis=-2) # return reorganized HPC prediction results for the confirmation modelregarding the threshold def return_filtered_A_lists_wrt_pred(pred_result, A_idx_list, threshold=0.8): (indices, ) = np.where(pred_result>threshold) grouped_indices = [] temp = [] for idx, index in enumerate(indices): if idx==0: if (indices[idx+1]-index)==1: temp.append(index) else: if (index-indices[idx-1]==1) | (index-indices[idx-1]==2): temp.append(index) elif (((index-indices[idx-1]) > 2) & (len(temp)>=2)): grouped_indices.append(temp) temp_index = index temp = [] if idx!=(len(indices)-1): if (indices[idx+1] - temp_index == 1) | (indices[idx+1] - temp_index == 2): temp.append(temp_index) if (idx==(len(indices)-1)) & (len(temp)>1): grouped_indices.append(temp) grouped_A_lists = [list(A_idx_list[temp_indices]) for temp_indices in grouped_indices if len(temp_indices) > 2] return grouped_A_lists # return prediction lists def return_pred_list(path): deno_pred_list = glob.glob(path+'total_N*_deno*') raw_pred_list = glob.glob(path+'total_N*_raw*') A_idx_list = glob.glob(path+'total_N*A_idx*') A_idx_list = np.load(A_idx_list[0]) for idx in range(len(deno_pred_list)): if idx==0: avg_raw_pred = np.load(raw_pred_list[idx]) avg_deno_pred = np.load(deno_pred_list[idx]) else: avg_raw_pred += np.load(raw_pred_list[idx]) avg_deno_pred += np.load(deno_pred_list[idx]) avg_raw_pred /= len(raw_pred_list) avg_deno_pred /= len(deno_pred_list) return A_idx_list, avg_raw_pred, avg_deno_pred # calculate the time of k-th dip of a spin with (A, B) pair. The unit of time (s). def return_target_period(A: 'Hz', B: 'Hz', WL, k: 'the position of the dip') -> 'time(s)': A *= 2*np.pi B *= 2*np.pi w_tilda = np.sqrt((A+WL)**2 + B**2) tau = np.pi*(2*k - 1) / (w_tilda + WL) return tau # calculate the gaussian decay rate(=decoherence effect) for time range. time_index: a time point of "mean value of Px" def gaussian_slope_px(M_lists: "data of M values", time_table: "time data", time_index: "time index of calculated point", px_mean_value_at_time: "px value at time index"): m_value_at_time = (px_mean_value_at_time * 2) - 1 Gaussian_co = -time_table[time_index] / np.log(m_value_at_time) slope = np.exp(-(time_table / Gaussian_co)**2) slope = slope.reshape(1, len(time_table)) M_lists_slope = M_lists * slope px_lists_slope = (M_lists_slope + 1) / 2 return px_lists_slope.squeeze(), slope.squeeze() # The following two functions are used for producing index combinations to select multiple Target Period(TP)s for HPC models. # : these two functions are used for determining the number of spins in a single broad dip in CPMG signal def return_combination_A_lists(chosen_indices, full_chosen_indices, cut_threshold): total_combination = [] for temp_idx in chosen_indices: indices = [] if type(temp_idx) == np.int64: temp_idx = np.array([temp_idx]) for j in full_chosen_indices: abs_temp = np.abs(temp_idx - j) if len(abs_temp[abs_temp<cut_threshold]) == 0: indices.append(j) temp_idx = list(temp_idx) total_combination += [temp_idx+[j] for j in indices] return np.array(total_combination) def return_total_hier_index_list(A_list, cut_threshold): total_index_lists = [] A_list_length = len(A_list) if (A_list_length==1): return np.array([[[0]]]) if (A_list_length==2): return np.array([[[0], [1]]]) if (A_list_length==3): return np.array([[[1]]]) if (A_list_length==4): return np.array([[[1], [2]]]) if (A_list_length==5): return np.array([[[1],[2],[3]], [[1,3]]]) if A_list_length%2 == 0: final_idx = A_list_length//2 else: final_idx = A_list_length//2 + 1 full_chosen_indices = np.arange(1, A_list_length-1) half_chosen_indices = np.arange(1, final_idx) temp_index = return_combination_A_lists(half_chosen_indices, full_chosen_indices, cut_threshold=cut_threshold) while 1: if (A_list_length>=10) & (A_list_length<12): if len(temp_index[0])>=2: total_index_lists.append(temp_index) elif (A_list_length>=12) & (A_list_length<15): if len(temp_index[0])>=3: total_index_lists.append(temp_index) elif (A_list_length>=15): if len(temp_index[0])>=4: total_index_lists.append(temp_index) else: total_index_lists.append(temp_index) temp_index = return_combination_A_lists(temp_index, full_chosen_indices, cut_threshold=cut_threshold) if len(temp_index) == 0:break return np.array(total_index_lists) # Exclude unnecessary indices def return_reduced_hier_indices(hier_indices): total_lists = [] for temp_line in hier_indices: temp = [] for line in temp_line: line.sort() temp.append(list(line)) set_lists = set(map(tuple, temp)) listed_lists = list(map(list, set_lists)) total_lists.append(listed_lists) return np.array(total_lists) # Used in a regression model to nomalize hyperfine parameters. def Y_train_normalization(arr): scale_list = [] res_arr = np.zeros((arr.shape)) for idx, line in enumerate(range(arr.shape[1])): column_max = np.max(arr[:, idx]) column_min = np.min(arr[:, idx]) res_arr[:, idx] = (column_max - arr[:, idx]) / (column_max - column_min) scale_list.append([column_min, column_max]) return res_arr, np.array(scale_list).flatten() # Used in a regression model to recover normalized hyperfine parameters. def reverse_normalization(pred_res, scale_list): reversed_list = [] for idx, pred in enumerate(pred_res): column_min = scale_list[2*idx] column_max = scale_list[2*idx+1] reversed_pred = column_max - pred * (column_max - column_min) reversed_list.append(reversed_pred) return reversed_list # return indexing array excluding targeted A index ( for example, to exclude the Larmor Frequency index, set A_idx = 0) def return_index_without_A_idx(total_indices, model_index, A_idx, TIME_RANGE, width): selected_index = get_model_index(total_indices, A_idx, time_thres_idx=TIME_RANGE, image_width=width) selected_index = selected_index.flatten() total_model_indices = list(range(len(model_index))) remove_index = [] for idx, temp_indices in enumerate(model_index): temp = [k for k in temp_indices if k in selected_index] if len(temp) > 0: total_model_indices.remove(idx) remove_index.append(idx) model_index = model_index[total_model_indices,:] return model_index, remove_index # return A value of TPk from the input (A, B) candidate def return_TPk_from_AB(A: 'Hz', B: 'Hz', WL, k=10) -> "A(Hz)": A_temp = int(round(A*0.01)*100) A_list = np.arange(A_temp-15000, A_temp+15000, 50)*2*np.pi A *= 2*np.pi B *= 2*np.pi w_tilda = np.sqrt((A+WL)**2 + B**2) tau = np.pi*(2*k - 1) / (w_tilda + WL) B_ref = 10000*2*np.pi w_tilda_list = np.sqrt((A_list+WL)**2 + B_ref**2) tau_list = np.pi*(2*k - 1) / (w_tilda_list + WL) min_idx = np.argmin(np.abs(tau_list - tau)) return int(round(A_list[min_idx]/2/np.pi, 0)) # return HPC_prediction_lists def HPC_prediction(model, AB_idx_set, total_indices, time_range, image_width, selected_index, cut_idx, is_removal, exp_data, exp_data_deno, total_A_lists, total_raw_pred_list, total_deno_pred_list, is_CNN, PRE_PROCESS, PRE_SCALE, save_to_file=False): model.eval() raw_pred = [] deno_pred = [] A_pred_lists = [] for idx1, [A_idx, B_idx] in enumerate(AB_idx_set): model_index = get_model_index(total_indices, A_idx, time_thres_idx=time_range, image_width=image_width) if is_removal: model_index = model_index[selected_index] else: model_index = model_index[:cut_idx] if PRE_PROCESS: exp_data_test = pre_processing(exp_data[model_index.flatten()], PRE_SCALE) exp_data_test = exp_data_test.reshape(1, -1) exp_data_test = torch.Tensor(exp_data_test).cuda() else: if is_CNN: exp_data_test = exp_data[model_index] exp_data_test = 1-(2*exp_data_test - 1) exp_data_test = exp_data_test.reshape(1, 1, model_index.shape[0], model_index.shape[1]) exp_data_test = torch.Tensor(exp_data_test).cuda() else: exp_data_test = exp_data[model_index.flatten()] exp_data_test = 1-(2*exp_data_test - 1) exp_data_test = exp_data_test.reshape(1, -1) exp_data_test = torch.Tensor(exp_data_test).cuda() pred = model(exp_data_test) pred = pred.detach().cpu().numpy() A_pred_lists.append(A_idx) raw_pred.append(pred[0]) total_A_lists.append(A_idx) total_raw_pred_list.append(pred[0]) print(A_idx, np.argmax(pred), np.max(pred), pred) if PRE_PROCESS: exp_data_test = pre_processing(exp_data_deno[model_index.flatten()], PRE_SCALE) exp_data_test = exp_data_test.reshape(1, -1) exp_data_test = torch.Tensor(exp_data_test).cuda() else: if is_CNN: exp_data_test = exp_data_deno[model_index] exp_data_test = 1-(2*exp_data_test - 1) exp_data_test = exp_data_test.reshape(1, 1, model_index.shape[0], model_index.shape[1]) exp_data_test = torch.Tensor(exp_data_test).cuda() else: exp_data_test = exp_data_deno[model_index.flatten()] exp_data_test = 1-(2*exp_data_test - 1) exp_data_test = exp_data_test.reshape(1, -1) exp_data_test = torch.Tensor(exp_data_test).cuda() pred = model(exp_data_test) pred = pred.detach().cpu().numpy() deno_pred.append(pred[0]) print(A_idx, np.argmax(pred), np.max(pred), pred) print() total_deno_pred_list.append(pred[0]) raw_pred = np.array(raw_pred).T deno_pred = np.array(deno_pred).T if save_to_file: np.save(MODEL_PATH+'A_idx_{}_A{}-{}_B{}-{}'.format(model_idx, A_first, A_end, B_first, B_end), A_pred_lists) np.save(MODEL_PATH+'raw_pred_{}_A{}-{}_B{}-{}'.format(model_idx, A_first, A_end, B_first, B_end), raw_pred) np.save(MODEL_PATH+'deno_pred_{}_A{}-{}_B{}-{}'.format(model_idx, A_first, A_end, B_first, B_end), deno_pred) return total_A_lists, total_raw_pred_list, total_deno_pred_list
[ "numpy.load", "numpy.sum", "numpy.abs", "numpy.argmax", "numpy.random.randint", "numpy.arange", "numpy.exp", "numpy.sin", "glob.glob", "numpy.prod", "numpy.full", "numpy.random.randn", "numpy.max", "torch.Tensor", "numpy.random.shuffle", "numpy.stack", "numpy.min", "numpy.cos", "...
[((302, 319), 'numpy.array', 'np.array', (['AB_list'], {}), '(AB_list)\n', (310, 319), True, 'import numpy as np\n'), ((1220, 1248), 'numpy.prod', 'np.prod', (['M_list_temp'], {'axis': '(0)'}), '(M_list_temp, axis=0)\n', (1227, 1248), True, 'import numpy as np\n'), ((1995, 2028), 'numpy.zeros', 'np.zeros', (['(B_num, class_batch, 2)'], {}), '((B_num, class_batch, 2))\n', (2003, 2028), True, 'import numpy as np\n'), ((2050, 2104), 'numpy.arange', 'np.arange', (['B_start', '(B_start + B_resol * B_num)', 'B_resol'], {}), '(B_start, B_start + B_resol * B_num, B_resol)\n', (2059, 2104), True, 'import numpy as np\n'), ((2844, 2901), 'numpy.random.randint', 'np.random.randint', (['side_temp.shape[0]'], {'size': 'side_same_num'}), '(side_temp.shape[0], size=side_same_num)\n', (2861, 2901), True, 'import numpy as np\n'), ((3194, 3224), 'numpy.arange', 'np.arange', (['(25000)', '(55000)', '(10000)'], {}), '(25000, 55000, 10000)\n', (3203, 3224), True, 'import numpy as np\n'), ((3245, 3292), 'numpy.zeros', 'np.zeros', (['(2 * idx_lists.shape[0], side_num, 2)'], {}), '((2 * idx_lists.shape[0], side_num, 2))\n', (3253, 3292), True, 'import numpy as np\n'), ((4382, 4413), 'numpy.arange', 'np.arange', (['(55000)', '(105000)', '(10000)'], {}), '(55000, 105000, 10000)\n', (4391, 4413), True, 'import numpy as np\n'), ((4434, 4481), 'numpy.zeros', 'np.zeros', (['(2 * idx_lists.shape[0], side_num, 2)'], {}), '((2 * idx_lists.shape[0], side_num, 2))\n', (4442, 4481), True, 'import numpy as np\n'), ((5534, 5582), 'numpy.random.randint', 'np.random.randint', (['AB_lists.shape[0]'], {'size': 'batch'}), '(AB_lists.shape[0], size=batch)\n', (5551, 5582), True, 'import numpy as np\n'), ((7117, 7149), 'numpy.random.shuffle', 'np.random.shuffle', (['total_flatten'], {}), '(total_flatten)\n', (7134, 7149), True, 'import numpy as np\n'), ((11643, 11697), 'numpy.arange', 'np.arange', (['A_start', '(A_start + A_resol * A_num)', 'A_resol'], {}), '(A_start, A_start + A_resol * A_num, A_resol)\n', (11652, 11697), True, 'import numpy as np\n'), ((11751, 11792), 'numpy.zeros', 'np.zeros', (['(class_num - 1, class_batch, 2)'], {}), '((class_num - 1, class_batch, 2))\n', (11759, 11792), True, 'import numpy as np\n'), ((11818, 11864), 'numpy.zeros', 'np.zeros', (['(class_num - 1, class_batch * 16, 2)'], {}), '((class_num - 1, class_batch * 16, 2))\n', (11826, 11864), True, 'import numpy as np\n'), ((11891, 11940), 'numpy.zeros', 'np.zeros', (['(A_idx_list.shape[0], side_same_num, 2)'], {}), '((A_idx_list.shape[0], side_same_num, 2))\n', (11899, 11940), True, 'import numpy as np\n'), ((14152, 14237), 'numpy.random.randint', 'np.random.randint', (['AB_mid_candi_divided.shape[0]'], {'size': '(class_num, scaled_batch)'}), '(AB_mid_candi_divided.shape[0], size=(class_num, scaled_batch)\n )\n', (14169, 14237), True, 'import numpy as np\n'), ((14306, 14358), 'numpy.zeros', 'np.zeros', (['(class_num, class_batch - scaled_batch, 2)'], {}), '((class_num, class_batch - scaled_batch, 2))\n', (14314, 14358), True, 'import numpy as np\n'), ((14381, 14436), 'numpy.concatenate', 'np.concatenate', (['(AB_candidates_mid, zero_candi)'], {'axis': '(1)'}), '((AB_candidates_mid, zero_candi), axis=1)\n', (14395, 14436), True, 'import numpy as np\n'), ((14452, 14530), 'numpy.random.randint', 'np.random.randint', (['AB_candidates_mid.shape[1]'], {'size': 'AB_candidates_mid.shape[1]'}), '(AB_candidates_mid.shape[1], size=AB_candidates_mid.shape[1])\n', (14469, 14530), True, 'import numpy as np\n'), ((14666, 14751), 'numpy.random.randint', 'np.random.randint', (['AB_far_candi_divided.shape[0]'], {'size': '(class_num, scaled_batch)'}), '(AB_far_candi_divided.shape[0], size=(class_num, scaled_batch)\n )\n', (14683, 14751), True, 'import numpy as np\n'), ((14820, 14872), 'numpy.zeros', 'np.zeros', (['(class_num, class_batch - scaled_batch, 2)'], {}), '((class_num, class_batch - scaled_batch, 2))\n', (14828, 14872), True, 'import numpy as np\n'), ((14895, 14950), 'numpy.concatenate', 'np.concatenate', (['(AB_candidates_far, zero_candi)'], {'axis': '(1)'}), '((AB_candidates_far, zero_candi), axis=1)\n', (14909, 14950), True, 'import numpy as np\n'), ((14966, 15044), 'numpy.random.randint', 'np.random.randint', (['AB_candidates_far.shape[1]'], {'size': 'AB_candidates_far.shape[1]'}), '(AB_candidates_far.shape[1], size=AB_candidates_far.shape[1])\n', (14983, 15044), True, 'import numpy as np\n'), ((15181, 15275), 'numpy.random.randint', 'np.random.randint', (['side_same_target_candi_divided.shape[0]'], {'size': '(class_num, scaled_batch)'}), '(side_same_target_candi_divided.shape[0], size=(class_num,\n scaled_batch))\n', (15198, 15275), True, 'import numpy as np\n'), ((15361, 15413), 'numpy.zeros', 'np.zeros', (['(class_num, class_batch - scaled_batch, 2)'], {}), '((class_num, class_batch - scaled_batch, 2))\n', (15369, 15413), True, 'import numpy as np\n'), ((15442, 15503), 'numpy.concatenate', 'np.concatenate', (['(AB_candidates_side_same, zero_candi)'], {'axis': '(1)'}), '((AB_candidates_side_same, zero_candi), axis=1)\n', (15456, 15503), True, 'import numpy as np\n'), ((15519, 15614), 'numpy.random.randint', 'np.random.randint', (['AB_candidates_side_same.shape[1]'], {'size': 'AB_candidates_side_same.shape[1]'}), '(AB_candidates_side_same.shape[1], size=\n AB_candidates_side_same.shape[1])\n', (15536, 15614), True, 'import numpy as np\n'), ((15868, 15927), 'numpy.concatenate', 'np.concatenate', (['(AB_pseudo_target, target_AB_candi)'], {'axis': '(0)'}), '((AB_pseudo_target, target_AB_candi), axis=0)\n', (15882, 15927), True, 'import numpy as np\n'), ((23124, 23155), 'numpy.sqrt', 'np.sqrt', (['((A + WL) ** 2 + B ** 2)'], {}), '((A + WL) ** 2 + B ** 2)\n', (23131, 23155), True, 'import numpy as np\n'), ((23238, 23278), 'numpy.sqrt', 'np.sqrt', (['((A_list + WL) ** 2 + B_ref ** 2)'], {}), '((A_list + WL) ** 2 + B_ref ** 2)\n', (23245, 23278), True, 'import numpy as np\n'), ((23631, 23674), 'numpy.arange', 'np.arange', (['A_init', '(A_final + A_step)', 'A_step'], {}), '(A_init, A_final + A_step, A_step)\n', (23640, 23674), True, 'import numpy as np\n'), ((23719, 23749), 'numpy.full', 'np.full', (['A_list1.shape', 'B_init'], {}), '(A_list1.shape, B_init)\n', (23726, 23749), True, 'import numpy as np\n'), ((23764, 23795), 'numpy.full', 'np.full', (['A_list1.shape', 'B_final'], {}), '(A_list1.shape, B_final)\n', (23771, 23795), True, 'import numpy as np\n'), ((24332, 24429), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-A_existing_margin)', 'high': 'A_existing_margin', 'size': 'existing_spins.shape'}), '(low=-A_existing_margin, high=A_existing_margin, size=\n existing_spins.shape)\n', (24349, 24429), True, 'import numpy as np\n'), ((24446, 24543), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-B_existing_margin)', 'high': 'B_existing_margin', 'size': 'existing_spins.shape'}), '(low=-B_existing_margin, high=B_existing_margin, size=\n existing_spins.shape)\n', (24463, 24543), True, 'import numpy as np\n'), ((24660, 24718), 'numpy.concatenate', 'np.concatenate', (['(reference_spins, existing_spins)'], {'axis': '(-2)'}), '((reference_spins, existing_spins), axis=-2)\n', (24674, 24718), True, 'import numpy as np\n'), ((24911, 24944), 'numpy.where', 'np.where', (['(pred_result > threshold)'], {}), '(pred_result > threshold)\n', (24919, 24944), True, 'import numpy as np\n'), ((25928, 25962), 'glob.glob', 'glob.glob', (["(path + 'total_N*_deno*')"], {}), "(path + 'total_N*_deno*')\n", (25937, 25962), False, 'import os, sys, glob, time, gc\n'), ((25981, 26014), 'glob.glob', 'glob.glob', (["(path + 'total_N*_raw*')"], {}), "(path + 'total_N*_raw*')\n", (25990, 26014), False, 'import os, sys, glob, time, gc\n'), ((26030, 26064), 'glob.glob', 'glob.glob', (["(path + 'total_N*A_idx*')"], {}), "(path + 'total_N*A_idx*')\n", (26039, 26064), False, 'import os, sys, glob, time, gc\n'), ((26080, 26102), 'numpy.load', 'np.load', (['A_idx_list[0]'], {}), '(A_idx_list[0])\n', (26087, 26102), True, 'import numpy as np\n'), ((26761, 26792), 'numpy.sqrt', 'np.sqrt', (['((A + WL) ** 2 + B ** 2)'], {}), '((A + WL) ** 2 + B ** 2)\n', (26768, 26792), True, 'import numpy as np\n'), ((27325, 27365), 'numpy.exp', 'np.exp', (['(-(time_table / Gaussian_co) ** 2)'], {}), '(-(time_table / Gaussian_co) ** 2)\n', (27331, 27365), True, 'import numpy as np\n'), ((28318, 28345), 'numpy.array', 'np.array', (['total_combination'], {}), '(total_combination)\n', (28326, 28345), True, 'import numpy as np\n'), ((28899, 28930), 'numpy.arange', 'np.arange', (['(1)', '(A_list_length - 1)'], {}), '(1, A_list_length - 1)\n', (28908, 28930), True, 'import numpy as np\n'), ((28956, 28979), 'numpy.arange', 'np.arange', (['(1)', 'final_idx'], {}), '(1, final_idx)\n', (28965, 28979), True, 'import numpy as np\n'), ((29703, 29730), 'numpy.array', 'np.array', (['total_index_lists'], {}), '(total_index_lists)\n', (29711, 29730), True, 'import numpy as np\n'), ((30120, 30141), 'numpy.array', 'np.array', (['total_lists'], {}), '(total_lists)\n', (30128, 30141), True, 'import numpy as np\n'), ((30274, 30293), 'numpy.zeros', 'np.zeros', (['arr.shape'], {}), '(arr.shape)\n', (30282, 30293), True, 'import numpy as np\n'), ((32041, 32072), 'numpy.sqrt', 'np.sqrt', (['((A + WL) ** 2 + B ** 2)'], {}), '((A + WL) ** 2 + B ** 2)\n', (32048, 32072), True, 'import numpy as np\n'), ((32155, 32195), 'numpy.sqrt', 'np.sqrt', (['((A_list + WL) ** 2 + B_ref ** 2)'], {}), '((A_list + WL) ** 2 + B_ref ** 2)\n', (32162, 32195), True, 'import numpy as np\n'), ((1010, 1021), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (1016, 1021), True, 'import numpy as np\n'), ((2329, 2386), 'numpy.random.randint', 'np.random.randint', (['target_temp.shape[0]'], {'size': 'class_batch'}), '(target_temp.shape[0], size=class_batch)\n', (2346, 2386), True, 'import numpy as np\n'), ((5797, 5821), 'numpy.sum', 'np.sum', (['bound_list[:, 1]'], {}), '(bound_list[:, 1])\n', (5803, 5821), True, 'import numpy as np\n'), ((7446, 7496), 'numpy.zeros', 'np.zeros', (['(A_side_idx_lists.shape[0], side_num, 2)'], {}), '((A_side_idx_lists.shape[0], side_num, 2))\n', (7454, 7496), True, 'import numpy as np\n'), ((8206, 8291), 'numpy.random.randint', 'np.random.randint', (['side_AB_candi_divided.shape[0]'], {'size': '(class_num, scaled_batch)'}), '(side_AB_candi_divided.shape[0], size=(class_num,\n scaled_batch))\n', (8223, 8291), True, 'import numpy as np\n'), ((8371, 8423), 'numpy.zeros', 'np.zeros', (['(class_num, class_batch - scaled_batch, 2)'], {}), '((class_num, class_batch - scaled_batch, 2))\n', (8379, 8423), True, 'import numpy as np\n'), ((8451, 8507), 'numpy.concatenate', 'np.concatenate', (['(AB_candidates_side, zero_candi)'], {'axis': '(1)'}), '((AB_candidates_side, zero_candi), axis=1)\n', (8465, 8507), True, 'import numpy as np\n'), ((8527, 8612), 'numpy.random.randint', 'np.random.randint', (['AB_candidates_side.shape[1]'], {'size': 'AB_candidates_side.shape[1]'}), '(AB_candidates_side.shape[1], size=AB_candidates_side.shape[1]\n )\n', (8544, 8612), True, 'import numpy as np\n'), ((23350, 23372), 'numpy.abs', 'np.abs', (['(tau_list - tau)'], {}), '(tau_list - tau)\n', (23356, 23372), True, 'import numpy as np\n'), ((23807, 23853), 'numpy.stack', 'np.stack', (['(A_list1, A_list2, B_list1, B_list2)'], {}), '((A_list1, A_list2, B_list1, B_list2))\n', (23815, 23853), True, 'import numpy as np\n'), ((24133, 24171), 'numpy.expand_dims', 'np.expand_dims', (['existing_spins'], {'axis': '(0)'}), '(existing_spins, axis=0)\n', (24147, 24171), True, 'import numpy as np\n'), ((24238, 24276), 'numpy.expand_dims', 'np.expand_dims', (['existing_spins'], {'axis': '(0)'}), '(existing_spins, axis=0)\n', (24252, 24276), True, 'import numpy as np\n'), ((27288, 27311), 'numpy.log', 'np.log', (['m_value_at_time'], {}), '(m_value_at_time)\n', (27294, 27311), True, 'import numpy as np\n'), ((28500, 28517), 'numpy.array', 'np.array', (['[[[0]]]'], {}), '([[[0]]])\n', (28508, 28517), True, 'import numpy as np\n'), ((28552, 28574), 'numpy.array', 'np.array', (['[[[0], [1]]]'], {}), '([[[0], [1]]])\n', (28560, 28574), True, 'import numpy as np\n'), ((28609, 28626), 'numpy.array', 'np.array', (['[[[1]]]'], {}), '([[[1]]])\n', (28617, 28626), True, 'import numpy as np\n'), ((28661, 28683), 'numpy.array', 'np.array', (['[[[1], [2]]]'], {}), '([[[1], [2]]])\n', (28669, 28683), True, 'import numpy as np\n'), ((28718, 28755), 'numpy.array', 'np.array', (['[[[1], [2], [3]], [[1, 3]]]'], {}), '([[[1], [2], [3]], [[1, 3]]])\n', (28726, 28755), True, 'import numpy as np\n'), ((30370, 30389), 'numpy.max', 'np.max', (['arr[:, idx]'], {}), '(arr[:, idx])\n', (30376, 30389), True, 'import numpy as np\n'), ((30411, 30430), 'numpy.min', 'np.min', (['arr[:, idx]'], {}), '(arr[:, idx])\n', (30417, 30430), True, 'import numpy as np\n'), ((32267, 32289), 'numpy.abs', 'np.abs', (['(tau_list - tau)'], {}), '(tau_list - tau)\n', (32273, 32289), True, 'import numpy as np\n'), ((35239, 35257), 'numpy.array', 'np.array', (['raw_pred'], {}), '(raw_pred)\n', (35247, 35257), True, 'import numpy as np\n'), ((35276, 35295), 'numpy.array', 'np.array', (['deno_pred'], {}), '(deno_pred)\n', (35284, 35295), True, 'import numpy as np\n'), ((941, 954), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (947, 954), True, 'import numpy as np\n'), ((963, 975), 'numpy.cos', 'np.cos', (['beta'], {}), '(beta)\n', (969, 975), True, 'import numpy as np\n'), ((1472, 1548), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-margin_value)', 'high': 'margin_value', 'size': 'arr_data.shape'}), '(low=-margin_value, high=margin_value, size=arr_data.shape)\n', (1489, 1548), True, 'import numpy as np\n'), ((3561, 3616), 'numpy.random.randint', 'np.random.randint', (['AB_list_temp.shape[0]'], {'size': 'side_num'}), '(AB_list_temp.shape[0], size=side_num)\n', (3578, 3616), True, 'import numpy as np\n'), ((3882, 3937), 'numpy.random.randint', 'np.random.randint', (['AB_list_temp.shape[0]'], {'size': 'side_num'}), '(AB_list_temp.shape[0], size=side_num)\n', (3899, 3937), True, 'import numpy as np\n'), ((4750, 4805), 'numpy.random.randint', 'np.random.randint', (['AB_list_temp.shape[0]'], {'size': 'side_num'}), '(AB_list_temp.shape[0], size=side_num)\n', (4767, 4805), True, 'import numpy as np\n'), ((5073, 5128), 'numpy.random.randint', 'np.random.randint', (['AB_list_temp.shape[0]'], {'size': 'side_num'}), '(AB_list_temp.shape[0], size=side_num)\n', (5090, 5128), True, 'import numpy as np\n'), ((5917, 5950), 'numpy.where', 'np.where', (['(AB_lists[:, 1] <= bound)'], {}), '(AB_lists[:, 1] <= bound)\n', (5925, 5950), True, 'import numpy as np\n'), ((6140, 6219), 'numpy.where', 'np.where', (['((AB_lists[:, 1] > bound) & (AB_lists[:, 1] <= bound_list[idx + 1][0]))'], {}), '((AB_lists[:, 1] > bound) & (AB_lists[:, 1] <= bound_list[idx + 1][0]))\n', (6148, 6219), True, 'import numpy as np\n'), ((7064, 7112), 'numpy.concatenate', 'np.concatenate', (['(total_flatten, temp_AB)'], {'axis': '(0)'}), '((total_flatten, temp_AB), axis=0)\n', (7078, 7112), True, 'import numpy as np\n'), ((7758, 7813), 'numpy.random.randint', 'np.random.randint', (['side_AB_temp.shape[0]'], {'size': 'side_num'}), '(side_AB_temp.shape[0], size=side_num)\n', (7775, 7813), True, 'import numpy as np\n'), ((8747, 8785), 'numpy.expand_dims', 'np.expand_dims', (['AB_candidates_side', '(-2)'], {}), '(AB_candidates_side, -2)\n', (8761, 8785), True, 'import numpy as np\n'), ((12868, 12953), 'numpy.arange', 'np.arange', (['A_side_start', '(A_side_start - A_side_resol * A_side_num)', '(-A_side_resol)'], {}), '(A_side_start, A_side_start - A_side_resol * A_side_num, -A_side_resol\n )\n', (12877, 12953), True, 'import numpy as np\n'), ((12981, 13056), 'numpy.arange', 'np.arange', (['A_side_end', '(A_side_end + A_side_resol * A_side_num)', 'A_side_resol'], {}), '(A_side_end, A_side_end + A_side_resol * A_side_num, A_side_resol)\n', (12990, 13056), True, 'import numpy as np\n'), ((15978, 16013), 'numpy.expand_dims', 'np.expand_dims', (['target_AB_candi', '(-2)'], {}), '(target_AB_candi, -2)\n', (15992, 16013), True, 'import numpy as np\n'), ((16023, 16060), 'numpy.expand_dims', 'np.expand_dims', (['AB_candidates_mid', '(-2)'], {}), '(AB_candidates_mid, -2)\n', (16037, 16060), True, 'import numpy as np\n'), ((16070, 16107), 'numpy.expand_dims', 'np.expand_dims', (['AB_candidates_far', '(-2)'], {}), '(AB_candidates_far, -2)\n', (16084, 16107), True, 'import numpy as np\n'), ((16145, 16188), 'numpy.expand_dims', 'np.expand_dims', (['AB_candidates_side_same', '(-2)'], {}), '(AB_candidates_side_same, -2)\n', (16159, 16188), True, 'import numpy as np\n'), ((23026, 23071), 'numpy.arange', 'np.arange', (['(A_temp - 15000)', '(A_temp + 15000)', '(50)'], {}), '(A_temp - 15000, A_temp + 15000, 50)\n', (23035, 23071), True, 'import numpy as np\n'), ((26193, 26220), 'numpy.load', 'np.load', (['raw_pred_list[idx]'], {}), '(raw_pred_list[idx])\n', (26200, 26220), True, 'import numpy as np\n'), ((26249, 26277), 'numpy.load', 'np.load', (['deno_pred_list[idx]'], {}), '(deno_pred_list[idx])\n', (26256, 26277), True, 'import numpy as np\n'), ((26321, 26348), 'numpy.load', 'np.load', (['raw_pred_list[idx]'], {}), '(raw_pred_list[idx])\n', (26328, 26348), True, 'import numpy as np\n'), ((26378, 26406), 'numpy.load', 'np.load', (['deno_pred_list[idx]'], {}), '(deno_pred_list[idx])\n', (26385, 26406), True, 'import numpy as np\n'), ((28011, 28031), 'numpy.array', 'np.array', (['[temp_idx]'], {}), '([temp_idx])\n', (28019, 28031), True, 'import numpy as np\n'), ((28095, 28115), 'numpy.abs', 'np.abs', (['(temp_idx - j)'], {}), '(temp_idx - j)\n', (28101, 28115), True, 'import numpy as np\n'), ((31943, 31988), 'numpy.arange', 'np.arange', (['(A_temp - 15000)', '(A_temp + 15000)', '(50)'], {}), '(A_temp - 15000, A_temp + 15000, 50)\n', (31952, 31988), True, 'import numpy as np\n'), ((34122, 34137), 'numpy.argmax', 'np.argmax', (['pred'], {}), '(pred)\n', (34131, 34137), True, 'import numpy as np\n'), ((34139, 34151), 'numpy.max', 'np.max', (['pred'], {}), '(pred)\n', (34145, 34151), True, 'import numpy as np\n'), ((35124, 35139), 'numpy.argmax', 'np.argmax', (['pred'], {}), '(pred)\n', (35133, 35139), True, 'import numpy as np\n'), ((35141, 35153), 'numpy.max', 'np.max', (['pred'], {}), '(pred)\n', (35147, 35153), True, 'import numpy as np\n'), ((854, 867), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (860, 867), True, 'import numpy as np\n'), ((870, 882), 'numpy.cos', 'np.cos', (['beta'], {}), '(beta)\n', (876, 882), True, 'import numpy as np\n'), ((906, 918), 'numpy.sin', 'np.sin', (['beta'], {}), '(beta)\n', (912, 918), True, 'import numpy as np\n'), ((1167, 1192), 'numpy.sin', 'np.sin', (['(n_pulse * phi / 2)'], {}), '(n_pulse * phi / 2)\n', (1173, 1192), True, 'import numpy as np\n'), ((6440, 6472), 'numpy.where', 'np.where', (['(AB_lists[:, 1] > bound)'], {}), '(AB_lists[:, 1] > bound)\n', (6448, 6472), True, 'import numpy as np\n'), ((6670, 6749), 'numpy.where', 'np.where', (['((AB_lists[:, 1] > bound) & (AB_lists[:, 1] <= bound_list[idx + 1][0]))'], {}), '((AB_lists[:, 1] > bound) & (AB_lists[:, 1] <= bound_list[idx + 1][0]))\n', (6678, 6749), True, 'import numpy as np\n'), ((17994, 18051), 'numpy.array', 'np.array', (['[[5000, 4], [11000, 2], [18000, 1], [35000, 1]]'], {}), '([[5000, 4], [11000, 2], [18000, 1], [35000, 1]])\n', (18002, 18051), True, 'import numpy as np\n'), ((18475, 18534), 'numpy.array', 'np.array', (['[[8000, 3], [15000, 3], [27000, 2.5], [45000, 1]]'], {}), '([[8000, 3], [15000, 3], [27000, 2.5], [45000, 1]])\n', (18483, 18534), True, 'import numpy as np\n'), ((18604, 18663), 'numpy.array', 'np.array', (['[[7000, 3], [13500, 3], [27000, 2.5], [45000, 1]]'], {}), '([[7000, 3], [13500, 3], [27000, 2.5], [45000, 1]])\n', (18612, 18663), True, 'import numpy as np\n'), ((21146, 21182), 'numpy.array', 'np.array', (['total_hier_target_AB_candi'], {}), '(total_hier_target_AB_candi)\n', (21154, 21182), True, 'import numpy as np\n'), ((22299, 22346), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'X_train_arr_batch.shape'}), '(size=X_train_arr_batch.shape)\n', (22316, 22346), True, 'import numpy as np\n'), ((22361, 22408), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'X_train_arr_batch.shape'}), '(size=X_train_arr_batch.shape)\n', (22378, 22408), True, 'import numpy as np\n'), ((30584, 30604), 'numpy.array', 'np.array', (['scale_list'], {}), '(scale_list)\n', (30592, 30604), True, 'import numpy as np\n'), ((890, 903), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (896, 903), True, 'import numpy as np\n'), ((8970, 9008), 'numpy.expand_dims', 'np.expand_dims', (['AB_candidates_side', '(-2)'], {}), '(AB_candidates_side, -2)\n', (8984, 9008), True, 'import numpy as np\n'), ((18733, 18792), 'numpy.array', 'np.array', (['[[6000, 3], [12000, 3], [27000, 2.5], [45000, 1]]'], {}), '([[6000, 3], [12000, 3], [27000, 2.5], [45000, 1]])\n', (18741, 18792), True, 'import numpy as np\n'), ((33251, 33278), 'torch.Tensor', 'torch.Tensor', (['exp_data_test'], {}), '(exp_data_test)\n', (33263, 33278), False, 'import torch\n'), ((34360, 34387), 'torch.Tensor', 'torch.Tensor', (['exp_data_test'], {}), '(exp_data_test)\n', (34372, 34387), False, 'import torch\n'), ((1610, 1646), 'numpy.random.randn', 'np.random.randn', ([], {'size': 'arr_data.shape'}), '(size=arr_data.shape)\n', (1625, 1646), True, 'import numpy as np\n'), ((18863, 18922), 'numpy.array', 'np.array', (['[[4000, 3], [11000, 3], [25000, 2.5], [45000, 1]]'], {}), '([[4000, 3], [11000, 3], [25000, 2.5], [45000, 1]])\n', (18871, 18922), True, 'import numpy as np\n'), ((33569, 33596), 'torch.Tensor', 'torch.Tensor', (['exp_data_test'], {}), '(exp_data_test)\n', (33581, 33596), False, 'import torch\n'), ((33835, 33862), 'torch.Tensor', 'torch.Tensor', (['exp_data_test'], {}), '(exp_data_test)\n', (33847, 33862), False, 'import torch\n'), ((34683, 34710), 'torch.Tensor', 'torch.Tensor', (['exp_data_test'], {}), '(exp_data_test)\n', (34695, 34710), False, 'import torch\n'), ((34954, 34981), 'torch.Tensor', 'torch.Tensor', (['exp_data_test'], {}), '(exp_data_test)\n', (34966, 34981), False, 'import torch\n'), ((18975, 19031), 'numpy.array', 'np.array', (['[[1500, 4], [7500, 2], [17000, 1], [35000, 1]]'], {}), '([[1500, 4], [7500, 2], [17000, 1], [35000, 1]])\n', (18983, 19031), True, 'import numpy as np\n')]
import unittest as ut from .. import tabular as ta from ....common import RTOL, ATOL, pandas, requires as _requires from ....examples import get_path from ...shapes import Polygon from ....io import geotable as pdio from ... import ops as GIS import numpy as np try: import shapely as shp except ImportError: shp = None PANDAS_EXTINCT = pandas is None SHAPELY_EXTINCT = shp is None @ut.skipIf(PANDAS_EXTINCT or SHAPELY_EXTINCT, 'missing pandas or shapely') class Test_Tabular(ut.TestCase): def setUp(self): import pandas as pd self.columbus = pdio.read_files(get_path('columbus.shp')) grid = [Polygon([(0,0),(0,1),(1,1),(1,0)]), Polygon([(0,1),(0,2),(1,2),(1,1)]), Polygon([(1,2),(2,2),(2,1),(1,1)]), Polygon([(1,1),(2,1),(2,0),(1,0)])] regime = [0,0,1,1] ids = list(range(4)) data = np.array((regime, ids)).T self.exdf = pd.DataFrame(data, columns=['regime', 'ids']) self.exdf['geometry'] = grid @_requires('geopandas') def test_round_trip(self): import geopandas as gpd import pandas as pd geodf = GIS.tabular.to_gdf(self.columbus) self.assertIsInstance(geodf, gpd.GeoDataFrame) new_df = GIS.tabular.to_df(geodf) self.assertIsInstance(new_df, pd.DataFrame) for new, old in zip(new_df.geometry, self.columbus.geometry): self.assertEqual(new, old) def test_spatial_join(self): pass def test_spatial_overlay(self): pass def test_dissolve(self): out = GIS.tabular.dissolve(self.exdf, by='regime') self.assertEqual(out[0].area, 2.0) self.assertEqual(out[1].area, 2.0) answer_vertices0 = [(0,0), (0,1), (0,2), (1,2), (1,1), (1,0), (0,0)] answer_vertices1 = [(2,1), (2,0), (1,0), (1,1), (1,2), (2,2), (2,1)] np.testing.assert_allclose(out[0].vertices, answer_vertices0) np.testing.assert_allclose(out[1].vertices, answer_vertices1) def test_clip(self): pass def test_erase(self): pass def test_union(self): new_geom = GIS.tabular.union(self.exdf) self.assertEqual(new_geom.area, 4) def test_intersection(self): pass def test_symmetric_difference(self): pass def test_difference(self): pass
[ "pandas.DataFrame", "unittest.skipIf", "numpy.testing.assert_allclose", "numpy.array" ]
[((394, 467), 'unittest.skipIf', 'ut.skipIf', (['(PANDAS_EXTINCT or SHAPELY_EXTINCT)', '"""missing pandas or shapely"""'], {}), "(PANDAS_EXTINCT or SHAPELY_EXTINCT, 'missing pandas or shapely')\n", (403, 467), True, 'import unittest as ut\n'), ((941, 986), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['regime', 'ids']"}), "(data, columns=['regime', 'ids'])\n", (953, 986), True, 'import pandas as pd\n'), ((1892, 1953), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['out[0].vertices', 'answer_vertices0'], {}), '(out[0].vertices, answer_vertices0)\n', (1918, 1953), True, 'import numpy as np\n'), ((1962, 2023), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['out[1].vertices', 'answer_vertices1'], {}), '(out[1].vertices, answer_vertices1)\n', (1988, 2023), True, 'import numpy as np\n'), ((895, 918), 'numpy.array', 'np.array', (['(regime, ids)'], {}), '((regime, ids))\n', (903, 918), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # Copyright (C) 2015-2018 by <NAME> <<EMAIL>> # All rights reserved. BSD 3-clause License. # This file is part of the SPORCO package. Details of the copyright # and user license can be found in the 'LICENSE.txt' file distributed # with the package. """Utility functions""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from future.utils import PY2 from builtins import range from builtins import object from timeit import default_timer as timer import os import imghdr import io import platform import multiprocessing as mp import itertools from future.moves.itertools import zip_longest import collections import socket if PY2: import urllib2 as urlrequest import urllib2 as urlerror else: import urllib.request as urlrequest import urllib.error as urlerror import numpy as np import scipy.ndimage.interpolation as sni import benchmarks.other.sporco.linalg as sla __author__ = """<NAME> <<EMAIL>>""" # Python 2/3 unicode literal compatibility if PY2: def u(x): """Python 2/3 compatible definition of utf8 literals""" return x.decode('utf8') else: def u(x): """Python 2/3 compatible definition of utf8 literals""" return x def ntpl2array(ntpl): """ Convert a :func:`collections.namedtuple` object to a :class:`numpy.ndarray` object that can be saved using :func:`numpy.savez`. Parameters ---------- ntpl : collections.namedtuple object Named tuple object to be converted to ndarray Returns ------- arr : ndarray Array representation of input named tuple """ return np.asarray((np.hstack([col for col in ntpl]), ntpl._fields, ntpl.__class__.__name__)) def array2ntpl(arr): """ Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array` back to the original :func:`collections.namedtuple` representation. Parameters ---------- arr : ndarray Array representation of named tuple constructed by :func:`ntpl2array` Returns ------- ntpl : collections.namedtuple object Named tuple object with the same name and fields as the original named typle object provided to :func:`ntpl2array` """ cls = collections.namedtuple(arr[2], arr[1]) return cls(*tuple(arr[0])) def transpose_ntpl_list(lst): """Transpose a list of named tuple objects (of the same type) into a named tuple of lists. Parameters ---------- lst : list of collections.namedtuple object List of named tuple objects of the same type Returns ------- ntpl : collections.namedtuple object Named tuple object with each entry consisting of a list of the corresponding fields of the named tuple objects in list ``lst`` """ if not lst: return None else: cls = collections.namedtuple(lst[0].__class__.__name__, lst[0]._fields) return cls(*[[lst[k][l] for k in range(len(lst))] for l in range(len(lst[0]))]) def tiledict(D, sz=None): """Construct an image allowing visualization of dictionary content. Parameters ---------- D : array_like Dictionary matrix/array. sz : tuple Size of each block in dictionary. Returns ------- im : ndarray Image tiled with dictionary entries. """ # Handle standard 2D (non-convolutional) dictionary if D.ndim == 2: D = D.reshape((sz + (D.shape[1],))) sz = None dsz = D.shape if D.ndim == 4: axisM = 3 szni = 3 else: axisM = 2 szni = 2 # Construct dictionary atom size vector if not provided if sz is None: sz = np.tile(np.array(dsz[0:2]).reshape([2, 1]), (1, D.shape[axisM])) else: sz = np.array(sum(tuple((x[0:2],) * x[szni] for x in sz), ())).T # Compute the maximum atom dimensions mxsz = np.amax(sz, 1) # Shift and scale values to [0, 1] D = D - D.min() D = D / D.max() # Construct tiled image N = dsz[axisM] Vr = int(np.floor(np.sqrt(N))) Vc = int(np.ceil(N / float(Vr))) if D.ndim == 4: im = np.ones((Vr*mxsz[0] + Vr - 1, Vc*mxsz[1] + Vc - 1, dsz[2])) else: im = np.ones((Vr*mxsz[0] + Vr - 1, Vc*mxsz[1] + Vc - 1)) k = 0 for l in range(0, Vr): for m in range(0, Vc): r = mxsz[0]*l + l c = mxsz[1]*m + m if D.ndim == 4: im[r:(r+sz[0, k]), c:(c+sz[1, k]), :] = D[0:sz[0, k], 0:sz[1, k], :, k] else: im[r:(r+sz[0, k]), c:(c+sz[1, k])] = D[0:sz[0, k], 0:sz[1, k], k] k = k + 1 if k >= N: break if k >= N: break return im def extractblocks(img, blksz, stpsz=None): """Extract blocks from an ndarray signal into an ndarray. Parameters ---------- img : ndarray or tuple of ndarrays nd array of images, or tuple of images blksz : tuple tuple of block sizes, blocks are taken starting from the first index of img stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- blks : ndarray image blocks """ # See http://stackoverflow.com/questions/16774148 and # sklearn.feature_extraction.image.extract_patches_2d if isinstance(img, tuple): img = np.stack(img, axis=-1) if stpsz is None: stpsz = (1,) * len(blksz) imgsz = img.shape # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a - b) / c) + 1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) # Calculate the strides for blocks blockstrides = tuple(a * b for a, b in zip_longest(img.strides, stpsz, fillvalue=1)) new_shape = blksz + numblocks new_strides = img.strides[:len(blksz)] + blockstrides blks = np.lib.stride_tricks.as_strided(img, new_shape, new_strides) return np.reshape(blks, blksz + (-1,)) def averageblocks(blks, imgsz, stpsz=None): """Average blocks together from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan """ blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a-b)/c)+1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) new_shape = blksz + numblocks blks = np.reshape(blks, new_shape) # Construct an imgs matrix of empty lists imgs = np.zeros(imgsz, dtype=blks.dtype) normalizer = np.zeros(imgsz, dtype=blks.dtype) # Iterate over each block and append the values to the corresponding # imgs cell for pos in np.ndindex(numblocks): slices = tuple(slice(a*c, a*c+b) for a, b, c in zip(pos, blksz, stpsz)) imgs[slices+pos[len(blksz):]] += blks[(Ellipsis, )+pos] normalizer[slices+pos[len(blksz):]] += blks.dtype.type(1) return np.where(normalizer > 0, (imgs/normalizer).astype(blks.dtype), np.nan) def combineblocks(blks, imgsz, stpsz=None, fn=np.median): """Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks fn : function, optional (default np.median) the function used to resolve multivalued cells Returns ------- imgs : ndarray reconstructed signal, unknown pixels are returned as np.nan """ # Construct a vectorized append function def listapp(x, y): x.append(y) veclistapp = np.vectorize(listapp, otypes=[np.object_]) blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a-b)/c) + 1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) new_shape = blksz + numblocks blks = np.reshape(blks, new_shape) # Construct an imgs matrix of empty lists imgs = np.empty(imgsz, dtype=np.object_) imgs.fill([]) imgs = np.frompyfunc(list, 1, 1)(imgs) # Iterate over each block and append the values to the corresponding # imgs cell for pos in np.ndindex(numblocks): slices = tuple(slice(a*c, a*c + b) for a, b, c in zip_longest(pos, blksz, stpsz, fillvalue=1)) veclistapp(imgs[slices].squeeze(), blks[(Ellipsis, ) + pos].squeeze()) return np.vectorize(fn, otypes=[blks.dtype])(imgs) def rgb2gray(rgb): """Convert an RGB image (or images) to grayscale. Parameters ---------- rgb : ndarray RGB image as Nr x Nc x 3 or Nr x Nc x 3 x K array Returns ------- gry : ndarray Grayscale image as Nr x Nc or Nr x Nc x K array """ w = sla.atleast_nd(rgb.ndim, np.array([0.299, 0.587, 0.144], dtype=rgb.dtype, ndmin=3)) return np.sum(w * rgb, axis=2) def complex_randn(*args): """Return a complex array of samples drawn from a standard normal distribution. Parameters ---------- d0, d1, ..., dn : int Dimensions of the random array Returns ------- a : ndarray Random array of shape (d0, d1, ..., dn) """ return np.random.randn(*args) + 1j*np.random.randn(*args) def spnoise(s, frc, smn=0.0, smx=1.0): """Return image with salt & pepper noise imposed on it. Parameters ---------- s : ndarray Input image frc : float Desired fraction of pixels corrupted by noise smn : float, optional (default 0.0) Lower value for noise (pepper) smx : float, optional (default 1.0) Upper value for noise (salt) Returns ------- sn : ndarray Noisy image """ sn = s.copy() spm = np.random.uniform(-1.0, 1.0, s.shape) sn[spm < frc - 1.0] = smn sn[spm > 1.0 - frc] = smx return sn def rndmask(shp, frc, dtype=None): r"""Return random mask image with values in :math:`\{0,1\}`. Parameters ---------- s : tuple Mask array shape frc : float Desired fraction of zero pixels dtype : data-type or None, optional (default None) Data type of mask array Returns ------- msk : ndarray Mask image """ msk = np.asarray(np.random.uniform(-1.0, 1.0, shp), dtype=dtype) msk[np.abs(msk) > frc] = 1.0 msk[np.abs(msk) < frc] = 0.0 return msk def pca(U, centre=False): """Compute the PCA basis for columns of input array `U`. Parameters ---------- U : array_like 2D data array with rows corresponding to different variables and columns corresponding to different observations center : bool, optional (default False) Flag indicating whether to centre data Returns ------- B : ndarray A 2D array representing the PCA basis; each column is a PCA component. B.T is the analysis transform into the PCA representation, and B is the corresponding synthesis transform S : ndarray The eigenvalues of the PCA components C : ndarray or None None if centering is disabled, otherwise the mean of the data matrix subtracted in performing the centering """ if centre: C = np.mean(U, axis=1, keepdims=True) U = U - C else: C = None B, S, _ = np.linalg.svd(U, full_matrices=False, compute_uv=True) return B, S**2, C def tikhonov_filter(s, lmbda, npd=16): r"""Lowpass filter based on Tikhonov regularization. Lowpass filter image(s) and return low and high frequency components, consisting of the lowpass filtered image and its difference with the input image. The lowpass filter is equivalent to Tikhonov regularization with `lmbda` as the regularization parameter and a discrete gradient as the operator in the regularization term, i.e. the lowpass component is the solution to .. math:: \mathrm{argmin}_\mathbf{x} \; (1/2) \left\|\mathbf{x} - \mathbf{s} \right\|_2^2 + (\lambda / 2) \sum_i \| G_i \mathbf{x} \|_2^2 \;\;, where :math:`\mathbf{s}` is the input image, :math:`\lambda` is the regularization parameter, and :math:`G_i` is an operator that computes the discrete gradient along image axis :math:`i`. Once the lowpass component :math:`\mathbf{x}` has been computed, the highpass component is just :math:`\mathbf{s} - \mathbf{x}`. Parameters ---------- s : array_like Input image or array of images. lmbda : float Regularization parameter controlling lowpass filtering. npd : int, optional (default=16) Number of samples to pad at image boundaries. Returns ------- sl : array_like Lowpass image or array of images. sh : array_like Highpass image or array of images. """ grv = np.array([-1.0, 1.0]).reshape([2, 1]) gcv = np.array([-1.0, 1.0]).reshape([1, 2]) Gr = sla.fftn(grv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) Gc = sla.fftn(gcv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) A = 1.0 + lmbda*np.conj(Gr)*Gr + lmbda*np.conj(Gc)*Gc if s.ndim > 2: A = A[(slice(None),)*2 + (np.newaxis,)*(s.ndim-2)] sp = np.pad(s, ((npd, npd),)*2 + ((0, 0),)*(s.ndim-2), 'symmetric') slp = np.real(sla.ifftn(sla.fftn(sp, axes=(0, 1)) / A, axes=(0, 1))) sl = slp[npd:(slp.shape[0] - npd), npd:(slp.shape[1] - npd)] sh = s - sl return sl.astype(s.dtype), sh.astype(s.dtype) def idle_cpu_count(mincpu=1): """Estimate number of idle CPUs, for use by multiprocessing code needing to determine how many processes can be run without excessive load. This function uses :func:`os.getloadavg` which is only available under a Unix OS. Parameters ---------- mincpu : int Minimum number of CPUs to report, independent of actual estimate Returns ------- idle : int Estimate of number of idle CPUs """ if PY2: ncpu = mp.cpu_count() else: ncpu = os.cpu_count() idle = int(ncpu - np.floor(os.getloadavg()[0])) return max(mincpu, idle) def grid_search(fn, grd, fmin=True, nproc=None): """Perform a grid search for optimal parameters of a specified function. In the simplest case the function returns a float value, and a single optimum value and corresponding parameter values are identified. If the function returns a tuple of values, each of these is taken to define a separate function on the search grid, with optimum function values and corresponding parameter values being identified for each of them. On all platforms except Windows (where ``mp.Pool`` usage has some limitations), the computation of the function at the grid points is computed in parallel. **Warning:** This function will hang if `fn` makes use of :mod:`pyfftw` with multi-threading enabled (the `bug <https://github.com/pyFFTW/pyFFTW/issues/135>`_ has been reported). When using the FFT functions in :mod:`sporco.linalg`, multi-threading can be disabled by including the following code:: import benchmarks.other.sporco.linalg sporco.linalg.pyfftw_threads = 1 Parameters ---------- fn : function Function to be evaluated. It should take a tuple of parameter values as an argument, and return a float value or a tuple of float values. grd : tuple of array_like A tuple providing an array of sample points for each axis of the grid on which the search is to be performed. fmin : bool, optional (default True) Determine whether optimal function values are selected as minima or maxima. If `fmin` is True then minima are selected. nproc : int or None, optional (default None) Number of processes to run in parallel. If None, the number of CPUs of the system is used. Returns ------- sprm : ndarray Optimal parameter values on each axis. If `fn` is multi-valued, `sprm` is a matrix with rows corresponding to parameter values and columns corresponding to function values. sfvl : float or ndarray Optimum function value or values fvmx : ndarray Function value(s) on search grid sidx : tuple of int or tuple of ndarray Indices of optimal values on parameter grid """ if fmin: slct = np.argmin else: slct = np.argmax fprm = itertools.product(*grd) if platform.system() == 'Windows': fval = list(map(fn, fprm)) else: if nproc is None: nproc = mp.cpu_count() pool = mp.Pool(processes=nproc) fval = pool.map(fn, fprm) pool.close() pool.join() if isinstance(fval[0], (tuple, list, np.ndarray)): nfnv = len(fval[0]) fvmx = np.reshape(fval, [a.size for a in grd] + [nfnv,]) sidx = np.unravel_index(slct(fvmx.reshape((-1, nfnv)), axis=0), fvmx.shape[0:-1]) + (np.array((range(nfnv))),) sprm = np.array([grd[k][sidx[k]] for k in range(len(grd))]) sfvl = tuple(fvmx[sidx]) else: fvmx = np.reshape(fval, [a.size for a in grd]) sidx = np.unravel_index(slct(fvmx), fvmx.shape) sprm = np.array([grd[k][sidx[k]] for k in range(len(grd))]) sfvl = fvmx[sidx] return sprm, sfvl, fvmx, sidx def convdicts(): """Access a set of example learned convolutional dictionaries. Returns ------- cdd : dict A dict associating description strings with dictionaries represented as ndarrays Examples -------- Print the dict keys to obtain the identifiers of the available dictionaries >>> from benchmarks.other.sporco import util >>> cd = util.convdicts() >>> print(cd.keys()) ['G:12x12x72', 'G:8x8x16,12x12x32,16x16x48', ...] Select a specific example dictionary using the corresponding identifier >>> D = cd['G:8x8x96'] """ pth = os.path.join(os.path.dirname(__file__), 'data', 'convdict.npz') npz = np.load(pth) cdd = {} for k in list(npz.keys()): cdd[k] = npz[k] return cdd def netgetdata(url, maxtry=3, timeout=10): """ Get content of a file via a URL. Parameters ---------- url : string URL of the file to be downloaded maxtry : int, optional (default 3) Maximum number of download retries timeout : int, optional (default 10) Timeout in seconds for blocking operations Returns ------- str : io.BytesIO Buffered I/O stream Raises ------ urlerror.URLError (urllib2.URLError in Python 2, urllib.error.URLError in Python 3) If the file cannot be downloaded """ err = ValueError('maxtry parameter should be greater than zero') for ntry in range(maxtry): try: rspns = urlrequest.urlopen(url, timeout=timeout) cntnt = rspns.read() break except urlerror.URLError as e: err = e if not isinstance(e.reason, socket.timeout): raise else: raise err return io.BytesIO(cntnt) def in_ipython(): """ Determine whether code is running in an ipython shell. Returns ------- ip : bool True if running in an ipython shell, False otherwise """ try: # See https://stackoverflow.com/questions/15411967 shell = get_ipython().__class__.__name__ return bool(shell == 'TerminalInteractiveShell') except NameError: return False def in_notebook(): """ Determine whether code is running in a Jupyter Notebook shell. Returns ------- ip : bool True if running in a notebook shell, False otherwise """ try: # See https://stackoverflow.com/questions/15411967 shell = get_ipython().__class__.__name__ return bool(shell == 'ZMQInteractiveShell') except NameError: return False def notebook_system_output(): """Get a context manager that attempts to use `wurlitzer <https://github.com/minrk/wurlitzer>`__ to capture system-level stdout/stderr within a Jupyter Notebook shell, without affecting normal operation when run as a Python script. For example: >>> sys_pipes = sporco.util.notebook_system_output() >>> with sys_pipes(): >>> command_producing_system_level_output() Returns ------- sys_pipes : context manager Context manager that handles output redirection when run within a Jupyter Notebook shell """ from contextlib import contextmanager @contextmanager def null_context_manager(): yield if in_notebook(): try: from wurlitzer import sys_pipes except ImportError: sys_pipes = null_context_manager else: sys_pipes = null_context_manager return sys_pipes class Timer(object): """Timer class supporting multiple independent labelled timers. The timer is based on the relative time returned by :func:`timeit.default_timer`. """ def __init__(self, labels=None, dfltlbl='main', alllbl='all'): """ Parameters ---------- labels : string or list, optional (default None) Specify the label(s) of the timer(s) to be initialised to zero. dfltlbl : string, optional (default 'main') Set the default timer label to be used when methods are called without specifying a label alllbl : string, optional (default 'all') Set the label string that will be used to denote all timer labels """ # Initialise current and accumulated time dictionaries self.t0 = {} self.td = {} # Record default label and string indicating all labels self.dfltlbl = dfltlbl self.alllbl = alllbl # Initialise dictionary entries for labels to be created # immediately if labels is not None: if not isinstance(labels, (list, tuple)): labels = [labels,] for lbl in labels: self.td[lbl] = 0.0 self.t0[lbl] = None def start(self, labels=None): """Start specified timer(s). Parameters ---------- labels : string or list, optional (default None) Specify the label(s) of the timer(s) to be started. If it is ``None``, start the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__`. """ # Default label is self.dfltlbl if labels is None: labels = self.dfltlbl # If label is not a list or tuple, create a singleton list # containing it if not isinstance(labels, (list, tuple)): labels = [labels,] # Iterate over specified label(s) t = timer() for lbl in labels: # On first call to start for a label, set its accumulator to zero if lbl not in self.td: self.td[lbl] = 0.0 self.t0[lbl] = None # Record the time at which start was called for this lbl if # it isn't already running if self.t0[lbl] is None: self.t0[lbl] = t def stop(self, labels=None): """Stop specified timer(s). Parameters ---------- labels : string or list, optional (default None) Specify the label(s) of the timer(s) to be stopped. If it is ``None``, stop the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__`. If it is equal to the string specified by the ``alllbl`` parameter of :meth:`__init__`, stop all timers. """ # Get current time t = timer() # Default label is self.dfltlbl if labels is None: labels = self.dfltlbl # All timers are affected if label is equal to self.alllbl, # otherwise only the timer(s) specified by label if labels == self.alllbl: labels = self.t0.keys() elif not isinstance(labels, (list, tuple)): labels = [labels,] # Iterate over specified label(s) for lbl in labels: if lbl not in self.t0: raise KeyError('Unrecognized timer key %s' % lbl) # If self.t0[lbl] is None, the corresponding timer is # already stopped, so no action is required if self.t0[lbl] is not None: # Increment time accumulator from the elapsed time # since most recent start call self.td[lbl] += t - self.t0[lbl] # Set start time to None to indicate timer is not running self.t0[lbl] = None def reset(self, labels=None): """Reset specified timer(s). Parameters ---------- labels : string or list, optional (default None) Specify the label(s) of the timer(s) to be stopped. If it is ``None``, stop the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__`. If it is equal to the string specified by the ``alllbl`` parameter of :meth:`__init__`, stop all timers. """ # Default label is self.dfltlbl if labels is None: labels = self.dfltlbl # All timers are affected if label is equal to self.alllbl, # otherwise only the timer(s) specified by label if labels == self.alllbl: labels = self.t0.keys() elif not isinstance(labels, (list, tuple)): labels = [labels,] # Iterate over specified label(s) for lbl in labels: if lbl not in self.t0: raise KeyError('Unrecognized timer key %s' % lbl) # Set start time to None to indicate timer is not running self.t0[lbl] = None # Set time accumulator to zero self.td[lbl] = 0.0 def elapsed(self, label=None, total=True): """Get elapsed time since timer start. Parameters ---------- label : string, optional (default None) Specify the label of the timer for which the elapsed time is required. If it is ``None``, the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__` is selected. total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time """ # Get current time t = timer() # Default label is self.dfltlbl if label is None: label = self.dfltlbl # Return 0.0 if default timer selected and it is not initialised if label not in self.t0: return 0.0 # Raise exception if timer with specified label does not exist if label not in self.t0: raise KeyError('Unrecognized timer key %s' % label) # If total flag is True return sum of accumulated time from # previous start/stop calls and current start call, otherwise # return just the time since the current start call te = 0.0 if self.t0[label] is not None: te = t - self.t0[label] if total: te += self.td[label] return te def labels(self): """Get a list of timer labels. Returns ------- lbl : list List of timer labels """ return self.t0.keys() def __str__(self): """Return string representation of object. The representation consists of a table with the following columns: * Timer label * Accumulated time from past start/stop calls * Time since current start call, or 'Stopped' if timer is not currently running """ # Get current time t = timer() # Length of label field, calculated from max label length lfldln = max([len(lbl) for lbl in self.t0] + [len(self.dfltlbl),]) + 2 # Header string for table of timers s = '%-*s Accum. Current\n' % (lfldln, 'Label') s += '-' * (lfldln + 25) + '\n' # Construct table of timer details for lbl in sorted(self.t0): td = self.td[lbl] if self.t0[lbl] is None: ts = ' Stopped' else: ts = ' %.2e s' % (t - self.t0[lbl]) s += '%-*s %.2e s %s\n' % (lfldln, lbl, td, ts) return s class ContextTimer(object): """A wrapper class for :class:`Timer` that enables its use as a context manager. For example, instead of >>> t = Timer() >>> t.start() >>> do_something() >>> t.stop() >>> elapsed = t.elapsed() one can use >>> t = Timer() >>> with ContextTimer(t): ... do_something() >>> elapsed = t.elapsed() """ def __init__(self, timer=None, label=None, action='StartStop'): """ Parameters ---------- timer : class:`Timer` object, optional (default None) Specify the timer object to be used as a context manager. If ``None``, a new class:`Timer` object is constructed. label : string, optional (default None) Specify the label of the timer to be used. If it is ``None``, start the default timer. action : string, optional (default 'StartStop') Specify actions to be taken on context entry and exit. If the value is 'StartStop', start the timer on entry and stop on exit; if it is 'StopStart', stop the timer on entry and start it on exit. """ if action not in ['StartStop', 'StopStart']: raise ValueError('Unrecognized action %s' % action) if timer is None: self.timer = Timer() else: self.timer = timer self.label = label self.action = action def __enter__(self): """Start the timer and return this ContextTimer instance.""" if self.action == 'StartStop': self.timer.start(self.label) else: self.timer.stop(self.label) return self def __exit__(self, type, value, traceback): """Stop the timer and return True if no exception was raised within the 'with' block, otherwise return False. """ if self.action == 'StartStop': self.timer.stop(self.label) else: self.timer.start(self.label) if type: return False else: return True def elapsed(self, total=True): """Return the elapsed time for the timer. Parameters ---------- total : bool, optional (default True) If ``True`` return the total elapsed time since the first call of :meth:`start` for the selected timer, otherwise return the elapsed time since the most recent call of :meth:`start` for which there has not been a corresponding call to :meth:`stop`. Returns ------- dlt : float Elapsed time """ return self.timer.elapsed(self.label, total=total)
[ "numpy.load", "numpy.sum", "numpy.abs", "numpy.empty", "numpy.floor", "numpy.ones", "numpy.linalg.svd", "numpy.frompyfunc", "numpy.mean", "builtins.range", "multiprocessing.cpu_count", "numpy.pad", "numpy.random.randn", "os.getloadavg", "os.path.dirname", "urllib.request.urlopen", "n...
[((2307, 2345), 'collections.namedtuple', 'collections.namedtuple', (['arr[2]', 'arr[1]'], {}), '(arr[2], arr[1])\n', (2329, 2345), False, 'import collections\n'), ((4008, 4022), 'numpy.amax', 'np.amax', (['sz', '(1)'], {}), '(sz, 1)\n', (4015, 4022), True, 'import numpy as np\n'), ((4414, 4426), 'builtins.range', 'range', (['(0)', 'Vr'], {}), '(0, Vr)\n', (4419, 4426), False, 'from builtins import range\n'), ((6269, 6329), 'numpy.lib.stride_tricks.as_strided', 'np.lib.stride_tricks.as_strided', (['img', 'new_shape', 'new_strides'], {}), '(img, new_shape, new_strides)\n', (6300, 6329), True, 'import numpy as np\n'), ((6341, 6372), 'numpy.reshape', 'np.reshape', (['blks', '(blksz + (-1,))'], {}), '(blks, blksz + (-1,))\n', (6351, 6372), True, 'import numpy as np\n'), ((7234, 7261), 'numpy.reshape', 'np.reshape', (['blks', 'new_shape'], {}), '(blks, new_shape)\n', (7244, 7261), True, 'import numpy as np\n'), ((7320, 7353), 'numpy.zeros', 'np.zeros', (['imgsz'], {'dtype': 'blks.dtype'}), '(imgsz, dtype=blks.dtype)\n', (7328, 7353), True, 'import numpy as np\n'), ((7371, 7404), 'numpy.zeros', 'np.zeros', (['imgsz'], {'dtype': 'blks.dtype'}), '(imgsz, dtype=blks.dtype)\n', (7379, 7404), True, 'import numpy as np\n'), ((7510, 7531), 'numpy.ndindex', 'np.ndindex', (['numblocks'], {}), '(numblocks)\n', (7520, 7531), True, 'import numpy as np\n'), ((8583, 8625), 'numpy.vectorize', 'np.vectorize', (['listapp'], {'otypes': '[np.object_]'}), '(listapp, otypes=[np.object_])\n', (8595, 8625), True, 'import numpy as np\n'), ((8986, 9013), 'numpy.reshape', 'np.reshape', (['blks', 'new_shape'], {}), '(blks, new_shape)\n', (8996, 9013), True, 'import numpy as np\n'), ((9072, 9105), 'numpy.empty', 'np.empty', (['imgsz'], {'dtype': 'np.object_'}), '(imgsz, dtype=np.object_)\n', (9080, 9105), True, 'import numpy as np\n'), ((9272, 9293), 'numpy.ndindex', 'np.ndindex', (['numblocks'], {}), '(numblocks)\n', (9282, 9293), True, 'import numpy as np\n'), ((9988, 10011), 'numpy.sum', 'np.sum', (['(w * rgb)'], {'axis': '(2)'}), '(w * rgb, axis=2)\n', (9994, 10011), True, 'import numpy as np\n'), ((10865, 10902), 'numpy.random.uniform', 'np.random.uniform', (['(-1.0)', '(1.0)', 's.shape'], {}), '(-1.0, 1.0, s.shape)\n', (10882, 10902), True, 'import numpy as np\n'), ((12436, 12490), 'numpy.linalg.svd', 'np.linalg.svd', (['U'], {'full_matrices': '(False)', 'compute_uv': '(True)'}), '(U, full_matrices=False, compute_uv=True)\n', (12449, 12490), True, 'import numpy as np\n'), ((14025, 14092), 'benchmarks.other.sporco.linalg.fftn', 'sla.fftn', (['grv', '(s.shape[0] + 2 * npd, s.shape[1] + 2 * npd)', '(0, 1)'], {}), '(grv, (s.shape[0] + 2 * npd, s.shape[1] + 2 * npd), (0, 1))\n', (14033, 14092), True, 'import benchmarks.other.sporco.linalg as sla\n'), ((14098, 14165), 'benchmarks.other.sporco.linalg.fftn', 'sla.fftn', (['gcv', '(s.shape[0] + 2 * npd, s.shape[1] + 2 * npd)', '(0, 1)'], {}), '(gcv, (s.shape[0] + 2 * npd, s.shape[1] + 2 * npd), (0, 1))\n', (14106, 14165), True, 'import benchmarks.other.sporco.linalg as sla\n'), ((14307, 14375), 'numpy.pad', 'np.pad', (['s', '(((npd, npd),) * 2 + ((0, 0),) * (s.ndim - 2))', '"""symmetric"""'], {}), "(s, ((npd, npd),) * 2 + ((0, 0),) * (s.ndim - 2), 'symmetric')\n", (14313, 14375), True, 'import numpy as np\n'), ((17510, 17533), 'itertools.product', 'itertools.product', (['*grd'], {}), '(*grd)\n', (17527, 17533), False, 'import itertools\n'), ((19132, 19144), 'numpy.load', 'np.load', (['pth'], {}), '(pth)\n', (19139, 19144), True, 'import numpy as np\n'), ((19896, 19909), 'builtins.range', 'range', (['maxtry'], {}), '(maxtry)\n', (19901, 19909), False, 'from builtins import range\n'), ((20214, 20231), 'io.BytesIO', 'io.BytesIO', (['cntnt'], {}), '(cntnt)\n', (20224, 20231), False, 'import io\n'), ((2913, 2978), 'collections.namedtuple', 'collections.namedtuple', (['lst[0].__class__.__name__', 'lst[0]._fields'], {}), '(lst[0].__class__.__name__, lst[0]._fields)\n', (2935, 2978), False, 'import collections\n'), ((4256, 4319), 'numpy.ones', 'np.ones', (['(Vr * mxsz[0] + Vr - 1, Vc * mxsz[1] + Vc - 1, dsz[2])'], {}), '((Vr * mxsz[0] + Vr - 1, Vc * mxsz[1] + Vc - 1, dsz[2]))\n', (4263, 4319), True, 'import numpy as np\n'), ((4339, 4394), 'numpy.ones', 'np.ones', (['(Vr * mxsz[0] + Vr - 1, Vc * mxsz[1] + Vc - 1)'], {}), '((Vr * mxsz[0] + Vr - 1, Vc * mxsz[1] + Vc - 1))\n', (4346, 4394), True, 'import numpy as np\n'), ((4445, 4457), 'builtins.range', 'range', (['(0)', 'Vc'], {}), '(0, Vc)\n', (4450, 4457), False, 'from builtins import range\n'), ((5652, 5674), 'numpy.stack', 'np.stack', (['img'], {'axis': '(-1)'}), '(img, axis=-1)\n', (5660, 5674), True, 'import numpy as np\n'), ((9135, 9160), 'numpy.frompyfunc', 'np.frompyfunc', (['list', '(1)', '(1)'], {}), '(list, 1, 1)\n', (9148, 9160), True, 'import numpy as np\n'), ((9512, 9549), 'numpy.vectorize', 'np.vectorize', (['fn'], {'otypes': '[blks.dtype]'}), '(fn, otypes=[blks.dtype])\n', (9524, 9549), True, 'import numpy as np\n'), ((9876, 9933), 'numpy.array', 'np.array', (['[0.299, 0.587, 0.144]'], {'dtype': 'rgb.dtype', 'ndmin': '(3)'}), '([0.299, 0.587, 0.144], dtype=rgb.dtype, ndmin=3)\n', (9884, 9933), True, 'import numpy as np\n'), ((10330, 10352), 'numpy.random.randn', 'np.random.randn', (['*args'], {}), '(*args)\n', (10345, 10352), True, 'import numpy as np\n'), ((11377, 11410), 'numpy.random.uniform', 'np.random.uniform', (['(-1.0)', '(1.0)', 'shp'], {}), '(-1.0, 1.0, shp)\n', (11394, 11410), True, 'import numpy as np\n'), ((12342, 12375), 'numpy.mean', 'np.mean', (['U'], {'axis': '(1)', 'keepdims': '(True)'}), '(U, axis=1, keepdims=True)\n', (12349, 12375), True, 'import numpy as np\n'), ((15078, 15092), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (15090, 15092), True, 'import multiprocessing as mp\n'), ((15118, 15132), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (15130, 15132), False, 'import os\n'), ((17541, 17558), 'platform.system', 'platform.system', ([], {}), '()\n', (17556, 17558), False, 'import platform\n'), ((17694, 17718), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'nproc'}), '(processes=nproc)\n', (17701, 17718), True, 'import multiprocessing as mp\n'), ((17892, 17940), 'numpy.reshape', 'np.reshape', (['fval', '([a.size for a in grd] + [nfnv])'], {}), '(fval, [a.size for a in grd] + [nfnv])\n', (17902, 17940), True, 'import numpy as np\n'), ((18219, 18258), 'numpy.reshape', 'np.reshape', (['fval', '[a.size for a in grd]'], {}), '(fval, [a.size for a in grd])\n', (18229, 18258), True, 'import numpy as np\n'), ((19071, 19096), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (19086, 19096), False, 'import os\n'), ((23975, 23982), 'timeit.default_timer', 'timer', ([], {}), '()\n', (23980, 23982), True, 'from timeit import default_timer as timer\n'), ((24915, 24922), 'timeit.default_timer', 'timer', ([], {}), '()\n', (24920, 24922), True, 'from timeit import default_timer as timer\n'), ((28025, 28032), 'timeit.default_timer', 'timer', ([], {}), '()\n', (28030, 28032), True, 'from timeit import default_timer as timer\n'), ((29379, 29386), 'timeit.default_timer', 'timer', ([], {}), '()\n', (29384, 29386), True, 'from timeit import default_timer as timer\n'), ((1691, 1723), 'numpy.hstack', 'np.hstack', (['[col for col in ntpl]'], {}), '([col for col in ntpl])\n', (1700, 1723), True, 'import numpy as np\n'), ((4173, 4183), 'numpy.sqrt', 'np.sqrt', (['N'], {}), '(N)\n', (4180, 4183), True, 'import numpy as np\n'), ((10358, 10380), 'numpy.random.randn', 'np.random.randn', (['*args'], {}), '(*args)\n', (10373, 10380), True, 'import numpy as np\n'), ((11433, 11444), 'numpy.abs', 'np.abs', (['msk'], {}), '(msk)\n', (11439, 11444), True, 'import numpy as np\n'), ((11466, 11477), 'numpy.abs', 'np.abs', (['msk'], {}), '(msk)\n', (11472, 11477), True, 'import numpy as np\n'), ((13930, 13951), 'numpy.array', 'np.array', (['[-1.0, 1.0]'], {}), '([-1.0, 1.0])\n', (13938, 13951), True, 'import numpy as np\n'), ((13978, 13999), 'numpy.array', 'np.array', (['[-1.0, 1.0]'], {}), '([-1.0, 1.0])\n', (13986, 13999), True, 'import numpy as np\n'), ((17664, 17678), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (17676, 17678), True, 'import multiprocessing as mp\n'), ((19944, 19984), 'urllib.request.urlopen', 'urlrequest.urlopen', (['url'], {'timeout': 'timeout'}), '(url, timeout=timeout)\n', (19962, 19984), True, 'import urllib.request as urlrequest\n'), ((5934, 5979), 'future.moves.itertools.zip_longest', 'zip_longest', (['imgsz', 'blksz', 'stpsz'], {'fillvalue': '(1)'}), '(imgsz, blksz, stpsz, fillvalue=1)\n', (5945, 5979), False, 'from future.moves.itertools import zip_longest\n'), ((6064, 6108), 'future.moves.itertools.zip_longest', 'zip_longest', (['img.strides', 'stpsz'], {'fillvalue': '(1)'}), '(img.strides, stpsz, fillvalue=1)\n', (6075, 6108), False, 'from future.moves.itertools import zip_longest\n'), ((7141, 7186), 'future.moves.itertools.zip_longest', 'zip_longest', (['imgsz', 'blksz', 'stpsz'], {'fillvalue': '(1)'}), '(imgsz, blksz, stpsz, fillvalue=1)\n', (7152, 7186), False, 'from future.moves.itertools import zip_longest\n'), ((8893, 8938), 'future.moves.itertools.zip_longest', 'zip_longest', (['imgsz', 'blksz', 'stpsz'], {'fillvalue': '(1)'}), '(imgsz, blksz, stpsz, fillvalue=1)\n', (8904, 8938), False, 'from future.moves.itertools import zip_longest\n'), ((14205, 14216), 'numpy.conj', 'np.conj', (['Gc'], {}), '(Gc)\n', (14212, 14216), True, 'import numpy as np\n'), ((14398, 14423), 'benchmarks.other.sporco.linalg.fftn', 'sla.fftn', (['sp'], {'axes': '(0, 1)'}), '(sp, axes=(0, 1))\n', (14406, 14423), True, 'import benchmarks.other.sporco.linalg as sla\n'), ((3814, 3832), 'numpy.array', 'np.array', (['dsz[0:2]'], {}), '(dsz[0:2])\n', (3822, 3832), True, 'import numpy as np\n'), ((5870, 5891), 'numpy.floor', 'np.floor', (['((a - b) / c)'], {}), '((a - b) / c)\n', (5878, 5891), True, 'import numpy as np\n'), ((7083, 7104), 'numpy.floor', 'np.floor', (['((a - b) / c)'], {}), '((a - b) / c)\n', (7091, 7104), True, 'import numpy as np\n'), ((8833, 8854), 'numpy.floor', 'np.floor', (['((a - b) / c)'], {}), '((a - b) / c)\n', (8841, 8854), True, 'import numpy as np\n'), ((9376, 9419), 'future.moves.itertools.zip_longest', 'zip_longest', (['pos', 'blksz', 'stpsz'], {'fillvalue': '(1)'}), '(pos, blksz, stpsz, fillvalue=1)\n', (9387, 9419), False, 'from future.moves.itertools import zip_longest\n'), ((14182, 14193), 'numpy.conj', 'np.conj', (['Gr'], {}), '(Gr)\n', (14189, 14193), True, 'import numpy as np\n'), ((15164, 15179), 'os.getloadavg', 'os.getloadavg', ([], {}), '()\n', (15177, 15179), False, 'import os\n'), ((18077, 18088), 'builtins.range', 'range', (['nfnv'], {}), '(nfnv)\n', (18082, 18088), False, 'from builtins import range\n')]
import binpacking import numpy as np from keras.models import load_model, Model class FusionData: def __init__( self, data, keys, input_dim=142, input_index=3, output_dim=1, output_index=3, warning=30, filter_size=128, batch_size=128, normalize=True, headless=True, model_path=None, **kwargs ): print("Loading data from {}".format(data)) data = np.load(data, allow_pickle=True)["shot_data"].item() print("Found {} shots".format(len(data.keys()))) print("Loading keys from {}".format(keys)) self.keys = np.load(keys) print("Found {} keys".format(len(self.keys))) print("Filtering data") self.disruptive = {key: data[key]["is_disruptive"] for key in self.keys} self.data = {key: data[key]["X"] for key in self.keys} print("Filtered to {} shots".format(len(self.data.keys()))) if normalize: print("Normalizing data") self.normalize() print("Packing data") self.pack( input_dim=input_dim, input_index=input_index, output_dim=output_dim, output_index=output_index, warning=warning, filter_size=filter_size, batch_size=batch_size, ) if model_path is not None: print("Loading model") # Open just to record in sacred model = load_model(model_path) if headless: # Remove final layer (disruptivity score decoder) model = Model(inputs=model.input, outputs=model.get_layer("lstm_2").output) print("Transforming data according to {}".format(model)) self.model = model self.transform() print("Removing pad") self.remove_pad() # Lol, very inefficient def normalize(self): num_measurements = np.sum([shot.shape[0] for shot in self.data.values()]) data = np.zeros((num_measurements, self.data[self.keys[0]].shape[1])) index = 0 for key, shot in self.data.items(): data[index : index + shot.shape[0], :] = shot index += shot.shape[0] mean = data.mean(axis=0) std = data.std(axis=0) self.data = {key: ((self.data[key] - mean) / std) for key in self.keys} def pack( self, input_dim=1, input_index=3, output_dim=1, output_index=3, warning=30, filter_size=1, batch_size=1, ): self.warning = warning self.filter_size = filter_size self.batch_size = batch_size self.input_dim = 1 if input_dim == 1 else self.data[list(self.data.keys())[0]].shape[1] self.input_index = input_index self.output_dim = 1 if output_dim == 1 else self.input_dim self.output_index = output_index balls = { key: (self.data[key].shape[0] - self.warning) // self.filter_size for key in self.keys } self.packing = binpacking.to_constant_bin_number(balls, self.batch_size) # Find batch with most chunks and multiply by filter_size to get total # time steps time_steps = self.filter_size * np.max( [np.sum(list(pack.values())) for pack in self.packing] ) # Create one input per batch of size time_steps by number of features inputs = np.zeros((self.batch_size, time_steps, self.input_dim)) # Create one output per batch of size time_steps by output dimensions outputs = np.zeros((self.batch_size, time_steps, self.output_dim)) self.start = {} self.end = {} # Loop over each batch for batch_id, pack in enumerate(self.packing): # Maintain an array index into input/output because shots are of # different lengths index = 0 # Loop over all time series assigned to a batch for shot_index, num_chunks in pack.items(): # Shot length in time steps shot_length = num_chunks * self.filter_size # Inputs ends warning steps before the end of data end = self.data[shot_index].shape[0] - self.warning # Start truncates so that (end - start) % filter_size == 0 start = end % self.filter_size self.start[shot_index] = start self.end[shot_index] = end # Capture time series from truncated start through end minus # `warning` steps if self.input_dim > 1: inputs[batch_id, index : (index + shot_length), :] = self.data[shot_index][ start:end, : ] else: inputs[batch_id, index : (index + shot_length), :] = self.data[shot_index][ start:end, self.input_index ].reshape(-1, 1) # Capture corresponding output time series (shift by `warning` # steps) if self.output_dim > 1: outputs[batch_id, index : (index + shot_length), :] = self.data[shot_index][ start + self.warning :, : ] else: outputs[batch_id, index : (index + shot_length), :] = self.data[shot_index][ start + self.warning :, self.output_index ].reshape(-1, 1) # Update index index += shot_length self.inputs = inputs self.outputs = outputs self.mask = self.inputs.any(axis=2) def transform(self): results = np.zeros( (self.inputs.shape[0], self.inputs.shape[1], self.model.output.shape[-1]) ) # Loop through each window and pass into the LSTM for results for filter_index in range(self.inputs.shape[1] // self.filter_size): start = filter_index * self.filter_size end = start + self.filter_size results[:, start:end, :] = self.model.predict( self.inputs[:, start:end, :], batch_size=self.batch_size, ) self.original_inputs = self.inputs self.inputs = results self.input_dim = int(self.model.output.shape[-1]) # Lol I can't call this mask... def remove_pad(self): # Remove any padding created during pack to be filter_size-aligned self.masked_outputs = self.outputs[self.mask] self.masked_inputs = self.inputs[self.mask] self.original_inputs = self.original_inputs[self.mask] self.masked_packing = [y for pack in self.packing for y in pack.items()] def featurize(self, window_size=1, yield_size=1, message=False): # TODO: Ignores arguments index = 0 for shot_index, num_chunks in self.masked_packing: start = index end = start + num_chunks * self.filter_size yield self.masked_inputs[start:end, :], self.masked_outputs[ start:end, : ], shot_index index = end # X = np.zeros((yield_size, window_size * self.inputs.shape[-1])) # Y = np.zeros((yield_size, self.outputs.shape[-1])) # yield_counter = 0 # shot_counter = 0 # for batch_id, pack in tqdm( # enumerate(self.packing), total=self.batch_size, desc="batch", position=0 # ): # index = 0 # for shot_index, num_chunks in tqdm( # pack.items(), total=len(pack.items()), desc="shot", position=1, leave=None, # ): # shot_counter += 1 # shot_length = num_chunks * self.filter_size # for time_index in tqdm( # range(window_size, shot_length + 1), desc="time", position=2, leave=None, # ): # yield_index = yield_counter % yield_size # if yield_index == 0: # if X is not None: # yield X, Y, shot_index # X[:, :], Y[:, :] = 0, 0 # start = index + time_index - window_size # end = index + time_index # if X.shape[1] > 1: # X[yield_index] = self.inputs[batch_id, start:end, :].ravel() # else: # X[yield_index] = self.inputs[batch_id, start:end] # if Y.shape[1] > 1: # Y[yield_index] = self.outputs[batch_id, start:end, :].ravel() # else: # Y[yield_index] = self.outputs[batch_id, start:end] # yield_counter += 1 # index += shot_length def __getitem__(self, key): return self.data[key]
[ "binpacking.to_constant_bin_number", "keras.models.load_model", "numpy.load", "numpy.zeros" ]
[((665, 678), 'numpy.load', 'np.load', (['keys'], {}), '(keys)\n', (672, 678), True, 'import numpy as np\n'), ((2053, 2115), 'numpy.zeros', 'np.zeros', (['(num_measurements, self.data[self.keys[0]].shape[1])'], {}), '((num_measurements, self.data[self.keys[0]].shape[1]))\n', (2061, 2115), True, 'import numpy as np\n'), ((3111, 3168), 'binpacking.to_constant_bin_number', 'binpacking.to_constant_bin_number', (['balls', 'self.batch_size'], {}), '(balls, self.batch_size)\n', (3144, 3168), False, 'import binpacking\n'), ((3491, 3546), 'numpy.zeros', 'np.zeros', (['(self.batch_size, time_steps, self.input_dim)'], {}), '((self.batch_size, time_steps, self.input_dim))\n', (3499, 3546), True, 'import numpy as np\n'), ((3644, 3700), 'numpy.zeros', 'np.zeros', (['(self.batch_size, time_steps, self.output_dim)'], {}), '((self.batch_size, time_steps, self.output_dim))\n', (3652, 3700), True, 'import numpy as np\n'), ((5805, 5893), 'numpy.zeros', 'np.zeros', (['(self.inputs.shape[0], self.inputs.shape[1], self.model.output.shape[-1])'], {}), '((self.inputs.shape[0], self.inputs.shape[1], self.model.output.\n shape[-1]))\n', (5813, 5893), True, 'import numpy as np\n'), ((1508, 1530), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (1518, 1530), False, 'from keras.models import load_model, Model\n'), ((483, 515), 'numpy.load', 'np.load', (['data'], {'allow_pickle': '(True)'}), '(data, allow_pickle=True)\n', (490, 515), True, 'import numpy as np\n')]
import indiesolver import numpy as np from pySDC.implementations.collocation_classes.gauss_radau_right import CollGaussRadau_Right def evaluate(solution): x = solution["parameters"] m = 5 coll = CollGaussRadau_Right(num_nodes=m, tleft=0.0, tright=1.0) Q = coll.Qmat[1:, 1:] Qd = np.array([[x['x11'], 0.0, 0.0, 0.0, 0.0], [x['x21'], x['x22'], 0.0, 0.0, 0.0], [x['x31'], x['x32'], x['x33'], 0.0, 0.0], [x['x41'], x['x42'], x['x43'], x['x44'], 0.0], [x['x51'], x['x52'], x['x53'], x['x54'], x['x55']]]) k = 0 obj_val = 0.0 for i in range(-8, 8): for l in range(-8, 8): k += 1 lamdt = -10 ** i + 1j * 10 ** l R = lamdt * np.linalg.inv(np.eye(m) - lamdt * Qd).dot(Q - Qd) rhoR = max(abs(np.linalg.eigvals(R))) obj_val += rhoR obj_val /= k solution["metrics"] = {} solution["metrics"]["rho"] = obj_val return solution # y = [5.8054876, 8.46779587, 17.72188108, 6.75505219, 5.53129906] # y = [1.0, 1.0, 1.0, 1.0, 1.0] y = [0.0, 0.0, 0.0, 0.0, 0.0] ymax = 20.0 ymin = 0.0 params = dict() params['x11'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[0]} params['x21'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x22'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[1]} params['x31'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x32'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x33'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[2]} params['x41'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x42'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x43'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x44'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[3]} params['x51'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x52'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x53'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x54'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': 0.0} params['x55'] = {'type': 'float', 'space': 'decision', 'min': ymin, 'max': ymax, 'init': y[4]} problem = {'problem_name': 'Qdelta_ld_sum', 'parameters': params, 'metrics': {'rho': {'type': 'objective', 'goal': 'minimize'}}} worker = indiesolver.indiesolver() worker.initialize("indiesolver.com", 8080, "dg8f5a0dd9ed") reply = worker.create_problem(problem) if reply["status"] != "success": print(reply) exit() curr_min = 99 pars = None for iteration in range(0, 100000): reply = worker.ask_new_solutions(1) solutions = dict() solutions["solutions"] = [] if reply["status"] == "success": for solution in reply["solutions"]: solutions["solutions"].append(evaluate(solution)) worker.tell_metrics(solutions) rho = reply["solutions"][0]["metrics"]["rho"] curr_min = min(curr_min, rho) if curr_min == rho: pars = reply["solutions"][0]["parameters"] print(iteration, rho, curr_min, pars) else: print(reply) exit()
[ "indiesolver.indiesolver", "numpy.linalg.eigvals", "numpy.array", "numpy.eye", "pySDC.implementations.collocation_classes.gauss_radau_right.CollGaussRadau_Right" ]
[((2825, 2850), 'indiesolver.indiesolver', 'indiesolver.indiesolver', ([], {}), '()\n', (2848, 2850), False, 'import indiesolver\n'), ((225, 281), 'pySDC.implementations.collocation_classes.gauss_radau_right.CollGaussRadau_Right', 'CollGaussRadau_Right', ([], {'num_nodes': 'm', 'tleft': '(0.0)', 'tright': '(1.0)'}), '(num_nodes=m, tleft=0.0, tright=1.0)\n', (245, 281), False, 'from pySDC.implementations.collocation_classes.gauss_radau_right import CollGaussRadau_Right\n'), ((321, 556), 'numpy.array', 'np.array', (["[[x['x11'], 0.0, 0.0, 0.0, 0.0], [x['x21'], x['x22'], 0.0, 0.0, 0.0], [x[\n 'x31'], x['x32'], x['x33'], 0.0, 0.0], [x['x41'], x['x42'], x['x43'], x\n ['x44'], 0.0], [x['x51'], x['x52'], x['x53'], x['x54'], x['x55']]]"], {}), "([[x['x11'], 0.0, 0.0, 0.0, 0.0], [x['x21'], x['x22'], 0.0, 0.0, \n 0.0], [x['x31'], x['x32'], x['x33'], 0.0, 0.0], [x['x41'], x['x42'], x[\n 'x43'], x['x44'], 0.0], [x['x51'], x['x52'], x['x53'], x['x54'], x['x55']]]\n )\n", (329, 556), True, 'import numpy as np\n'), ((882, 902), 'numpy.linalg.eigvals', 'np.linalg.eigvals', (['R'], {}), '(R)\n', (899, 902), True, 'import numpy as np\n'), ((818, 827), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (824, 827), True, 'import numpy as np\n')]
from __future__ import division import numpy as np from itertools import combinations_with_replacement from .core import Data, Summary, Propensity, PropensitySelect, Strata from .estimators import OLS, Blocking, Weighting, Matching, Estimators class CausalModel(object): """ Class that provides the main tools of Causal Inference. """ def __init__(self, Y, D, X): self.old_data = Data(Y, D, X) self.reset() def reset(self): """ Reinitializes data to original inputs, and drops any estimated results. """ Y, D, X = self.old_data['Y'], self.old_data['D'], self.old_data['X'] self.raw_data = Data(Y, D, X) self.summary_stats = Summary(self.raw_data) self.propensity = None self.cutoff = None self.blocks = None self.strata = None self.estimates = Estimators() def est_propensity(self, lin='all', qua=None): """ Estimates the propensity scores given list of covariates to include linearly or quadratically. The propensity score is the conditional probability of receiving the treatment given the observed covariates. Estimation is done via a logistic regression. Parameters ---------- lin: string or list, optional Column numbers (zero-based) of variables of the original covariate matrix X to include linearly. Defaults to the string 'all', which uses whole covariate matrix. qua: list, optional Tuples indicating which columns of the original covariate matrix to multiply and include. E.g., [(1,1), (2,3)] indicates squaring the 2nd column and including the product of the 3rd and 4th columns. Default is to not include any quadratic terms. """ lin_terms = parse_lin_terms(self.raw_data['K'], lin) qua_terms = parse_qua_terms(self.raw_data['K'], qua) self.propensity = Propensity(self.raw_data, lin_terms, qua_terms) self.raw_data._dict['pscore'] = self.propensity['fitted'] self._post_pscore_init() def est_propensity_s(self, lin_B=None, C_lin=1, C_qua=2.71): """ Estimates the propensity score with covariates selected using the algorithm suggested by [1]_. The propensity score is the conditional probability of receiving the treatment given the observed covariates. Estimation is done via a logistic regression. The covariate selection algorithm is based on a sequence of likelihood ratio tests. Parameters ---------- lin_B: list, optional Column numbers (zero-based) of variables of the original covariate matrix X to include linearly. Defaults to empty list, meaning every column of X is subjected to the selection algorithm. C_lin: scalar, optional Critical value used in likelihood ratio tests to decide whether candidate linear terms should be included. Defaults to 1 as in [1]_. C_qua: scalar, optional Critical value used in likelihood ratio tests to decide whether candidate quadratic terms should be included. Defaults to 2.71 as in [1]_. References ---------- .. [1] <NAME>. & <NAME>. (2015). Causal Inference in Statistics, Social, and Biomedical Sciences: An Introduction. """ lin_basic = parse_lin_terms(self.raw_data['K'], lin_B) self.propensity = PropensitySelect(self.raw_data, lin_basic, C_lin, C_qua) self.raw_data._dict['pscore'] = self.propensity['fitted'] self._post_pscore_init() def trim(self): """ Trims data based on propensity score to create a subsample with better covariate balance. The default cutoff value is set to 0.1. To set a custom cutoff value, modify the object attribute named cutoff directly. This method should only be executed after the propensity score has been estimated. """ if 0 < self.cutoff <= 0.5: pscore = self.raw_data['pscore'] keep = (pscore >= self.cutoff) & (pscore <= 1-self.cutoff) Y_trimmed = self.raw_data['Y'][keep] D_trimmed = self.raw_data['D'][keep] X_trimmed = self.raw_data['X'][keep] self.raw_data = Data(Y_trimmed, D_trimmed, X_trimmed) self.raw_data._dict['pscore'] = pscore[keep] self.summary_stats = Summary(self.raw_data) self.strata = None self.estimates = Estimators() elif self.cutoff == 0: pass else: raise ValueError('Invalid cutoff.') def trim_s(self): """ Trims data based on propensity score using the cutoff selection algorithm suggested by [1]_. This method should only be executed after the propensity score has been estimated. References ---------- .. [1] <NAME>., <NAME>., <NAME>., & <NAME>. (2009). Dealing with Limited Overlap in Estimation of Average Treatment Effects. Biometrika, 96, 187-199. """ pscore = self.raw_data['pscore'] g = 1.0/(pscore*(1-pscore)) # 1 over Bernoulli variance self.cutoff = select_cutoff(g) self.trim() def stratify(self): """ Stratifies the sample based on propensity score. By default the sample is divided into five equal-sized bins. The number of bins can be set by modifying the object attribute named blocks. Alternatively, custom-sized bins can be created by setting blocks equal to a sorted list of numbers between 0 and 1 indicating the bin boundaries. This method should only be executed after the propensity score has been estimated. """ Y, D, X = self.raw_data['Y'], self.raw_data['D'], self.raw_data['X'] pscore = self.raw_data['pscore'] if isinstance(self.blocks, int): blocks = split_equal_bins(pscore, self.blocks) else: blocks = self.blocks[:] # make a copy; should be sorted blocks[0] = 0 # avoids always dropping 1st unit def subset(p_low, p_high): return (p_low < pscore) & (pscore <= p_high) subsets = [subset(*ps) for ps in zip(blocks, blocks[1:])] strata = [CausalModel(Y[s], D[s], X[s]) for s in subsets] self.strata = Strata(strata, subsets, pscore) def stratify_s(self): """ Stratifies the sample based on propensity score using the bin selection procedure suggested by [1]_. The bin selection algorithm is based on a sequence of two-sample t tests performed on the log-odds ratio. This method should only be executed after the propensity score has been estimated. References ---------- .. [1] <NAME>. & <NAME>. (2015). Causal Inference in Statistics, Social, and Biomedical Sciences: An Introduction. """ pscore_order = self.raw_data['pscore'].argsort() pscore = self.raw_data['pscore'][pscore_order] D = self.raw_data['D'][pscore_order] logodds = np.log(pscore / (1-pscore)) K = self.raw_data['K'] blocks_uniq = set(select_blocks(pscore, logodds, D, K, 0, 1)) self.blocks = sorted(blocks_uniq) self.stratify() def est_via_ols(self, adj=2): """ Estimates average treatment effects using least squares. Parameters ---------- adj: int (0, 1, or 2) Indicates how covariate adjustments are to be performed. Set adj = 0 to not include any covariates. Set adj = 1 to include treatment indicator D and covariates X separately. Set adj = 2 to additionally include interaction terms between D and X. Defaults to 2. """ self.estimates['ols'] = OLS(self.raw_data, adj) def est_via_blocking(self, adj=1): """ Estimates average treatment effects using regression within blocks. This method should only be executed after the sample has been stratified. Parameters ---------- adj: int (0, 1, or 2) Indicates how covariate adjustments are to be performed for each within-bin regression. Set adj = 0 to not include any covariates. Set adj = 1 to include treatment indicator D and covariates X separately. Set adj = 2 to additionally include interaction terms between D and X. Defaults to 1. """ self.estimates['blocking'] = Blocking(self.strata, adj) def est_via_weighting(self): """ Estimates average treatment effects using doubly-robust version of the Horvitz-Thompson weighting estimator. """ self.estimates['weighting'] = Weighting(self.raw_data) def est_via_matching(self, weights='inv', matches=1, bias_adj=False): """ Estimates average treatment effects using nearest- neighborhood matching. Matching is done with replacement. Method supports multiple matching. Correcting bias that arise due to imperfect matches is also supported. For details on methodology, see [1]_. Parameters ---------- weights: str or positive definite square matrix Specifies weighting matrix used in computing distance measures. Defaults to string 'inv', which does inverse variance weighting. String 'maha' gives the weighting matrix used in the Mahalanobis metric. matches: int Number of matches to use for each subject. bias_adj: bool Specifies whether bias adjustments should be attempted. References ---------- .. [1] <NAME>. & <NAME>. (2015). Causal Inference in Statistics, Social, and Biomedical Sciences: An Introduction. """ X, K = self.raw_data['X'], self.raw_data['K'] X_c, X_t = self.raw_data['X_c'], self.raw_data['X_t'] if weights == 'inv': W = 1/X.var(0) elif weights == 'maha': V_c = np.cov(X_c, rowvar=False, ddof=0) V_t = np.cov(X_t, rowvar=False, ddof=0) if K == 1: W = 1/np.array([[(V_c+V_t)/2]]) # matrix form else: W = np.linalg.inv((V_c+V_t)/2) else: W = weights self.estimates['matching'] = Matching(self.raw_data, W, matches, bias_adj) def _post_pscore_init(self): self.cutoff = 0.1 self.blocks = 5 def parse_lin_terms(K, lin): if lin is None: return [] elif lin == 'all': return range(K) else: return lin def parse_qua_terms(K, qua): if qua is None: return [] elif qua == 'all': return list(combinations_with_replacement(range(K), 2)) else: return qua def sumlessthan(g, sorted_g, cumsum): deduped_values = dict(zip(sorted_g, cumsum)) return np.array([deduped_values[x] for x in g]) def select_cutoff(g): if g.max() <= 2*g.mean(): cutoff = 0 else: sorted_g = np.sort(g) cumsum_1 = range(1, len(g)+1) LHS = g * sumlessthan(g, sorted_g, cumsum_1) cumsum_g = np.cumsum(sorted_g) RHS = 2 * sumlessthan(g, sorted_g, cumsum_g) gamma = np.max(g[LHS <= RHS]) cutoff = 0.5 - np.sqrt(0.25 - 1./gamma) return cutoff def split_equal_bins(pscore, blocks): q = np.linspace(0, 100, blocks+1)[1:-1] # q as in qth centiles centiles = [np.percentile(pscore, x) for x in q] return [0] + centiles + [1] def calc_tstat(sample_c, sample_t): N_c = sample_c.shape[0] N_t = sample_t.shape[0] var_c = sample_c.var(ddof=1) var_t = sample_t.var(ddof=1) return (sample_t.mean()-sample_c.mean()) / np.sqrt(var_c/N_c+var_t/N_t) def calc_sample_sizes(D): N = D.shape[0] mid_index = N // 2 Nleft = mid_index Nleft_t = D[:mid_index].sum() Nleft_c = Nleft - Nleft_t Nright = N - Nleft Nright_t = D[mid_index:].sum() Nright_c = Nright - Nright_t return (Nleft_c, Nleft_t, Nright_c, Nright_t) def select_blocks(pscore, logodds, D, K, p_low, p_high): scope = (pscore >= p_low) & (pscore <= p_high) c, t = (scope & (D==0)), (scope & (D==1)) Nleft_c, Nleft_t, Nright_c, Nright_t = calc_sample_sizes(D[scope]) if min(Nleft_c, Nleft_t, Nright_c, Nright_t) < K+1: return [p_low, p_high] tstat = calc_tstat(logodds[c], logodds[t]) if tstat <= 1.96: return [p_low, p_high] low = pscore[scope][0] mid = pscore[scope][scope.sum() // 2] high = pscore[scope][-1] return select_blocks(pscore, logodds, D, K, low, mid) + \ select_blocks(pscore, logodds, D, K, mid, high)
[ "numpy.log", "numpy.percentile", "numpy.sort", "numpy.max", "numpy.cumsum", "numpy.array", "numpy.linalg.inv", "numpy.linspace", "numpy.cov", "numpy.sqrt" ]
[((9840, 9880), 'numpy.array', 'np.array', (['[deduped_values[x] for x in g]'], {}), '([deduped_values[x] for x in g])\n', (9848, 9880), True, 'import numpy as np\n'), ((6452, 6481), 'numpy.log', 'np.log', (['(pscore / (1 - pscore))'], {}), '(pscore / (1 - pscore))\n', (6458, 6481), True, 'import numpy as np\n'), ((9966, 9976), 'numpy.sort', 'np.sort', (['g'], {}), '(g)\n', (9973, 9976), True, 'import numpy as np\n'), ((10069, 10088), 'numpy.cumsum', 'np.cumsum', (['sorted_g'], {}), '(sorted_g)\n', (10078, 10088), True, 'import numpy as np\n'), ((10146, 10167), 'numpy.max', 'np.max', (['g[LHS <= RHS]'], {}), '(g[LHS <= RHS])\n', (10152, 10167), True, 'import numpy as np\n'), ((10272, 10303), 'numpy.linspace', 'np.linspace', (['(0)', '(100)', '(blocks + 1)'], {}), '(0, 100, blocks + 1)\n', (10283, 10303), True, 'import numpy as np\n'), ((10345, 10369), 'numpy.percentile', 'np.percentile', (['pscore', 'x'], {}), '(pscore, x)\n', (10358, 10369), True, 'import numpy as np\n'), ((10606, 10640), 'numpy.sqrt', 'np.sqrt', (['(var_c / N_c + var_t / N_t)'], {}), '(var_c / N_c + var_t / N_t)\n', (10613, 10640), True, 'import numpy as np\n'), ((10185, 10212), 'numpy.sqrt', 'np.sqrt', (['(0.25 - 1.0 / gamma)'], {}), '(0.25 - 1.0 / gamma)\n', (10192, 10212), True, 'import numpy as np\n'), ((9068, 9101), 'numpy.cov', 'np.cov', (['X_c'], {'rowvar': '(False)', 'ddof': '(0)'}), '(X_c, rowvar=False, ddof=0)\n', (9074, 9101), True, 'import numpy as np\n'), ((9111, 9144), 'numpy.cov', 'np.cov', (['X_t'], {'rowvar': '(False)', 'ddof': '(0)'}), '(X_t, rowvar=False, ddof=0)\n', (9117, 9144), True, 'import numpy as np\n'), ((9227, 9257), 'numpy.linalg.inv', 'np.linalg.inv', (['((V_c + V_t) / 2)'], {}), '((V_c + V_t) / 2)\n', (9240, 9257), True, 'import numpy as np\n'), ((9169, 9198), 'numpy.array', 'np.array', (['[[(V_c + V_t) / 2]]'], {}), '([[(V_c + V_t) / 2]])\n', (9177, 9198), True, 'import numpy as np\n')]
import numpy as np from numba import njit, objmode, types from numba.typed import List from numba.pycc import CC cc = CC('algoxtoolsp') cc.verbose = True @cc.export('annex_row', 'void( i2[:,:,:], i2, i2[:] )') @njit( 'void( i2[:,:,:], i2, i2[:] )') def annex_row( array, cur_row, col_list ): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 prv_col = -1 ncol_list = List() #[] ncol_list.append(INDEX) for col in range(len(col_list)) : ncol_list.append( col_list[col] ) first_col = ncol_list[0] last_col = 0 for cur_col in ncol_list: # Set Last, Total indices if array[ INDEX, cur_col, VALUE ] == -1: array[ INDEX, cur_col, U ] = cur_row else: # Set Up, Down last_row = array[ INDEX, cur_col, U ] array[ cur_row, cur_col, U ] = last_row array[ last_row, cur_col, D ] = cur_row first_row = array[ INDEX, cur_col, D ] array[ cur_row, cur_col, D ] = first_row array[ first_row, cur_col, U ] = cur_row if cur_col != INDEX: array[ INDEX, cur_col, VALUE ] += 1 if cur_row != INDEX: array[ cur_row, INDEX, VALUE ] += 1 # Set Right, left if prv_col != -1: array[ cur_row, prv_col, R ] = cur_col array[ cur_row, cur_col, L ] = prv_col array[ INDEX, cur_col, U ] = cur_row prv_col = cur_col last_col = cur_col if cur_row != INDEX and cur_col != INDEX: array[ cur_row, cur_col, VALUE ] = 1 if cur_row == INDEX: #array[ INDEX, INDEX, VALUE ] += 1 array[ INDEX, cur_col, LINKED ] = 1 array[ cur_row, INDEX, LINKED ] = 1 array[ cur_row, cur_col, LINKED ] = 1 # Make row toroidal array[ cur_row, first_col, L] = last_col array[ cur_row, last_col, R] = first_col # unlink row index col_index = array[ cur_row, INDEX ] array[ cur_row, col_index[R], L ] = col_index[L] array[ cur_row, col_index[L], R ] = col_index[R] @cc.export('init','i2[:,:,:](i2, i2)') @njit('i2[:,:,:](i2, i2)') def init( rows, cols ): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 META = -1 array=np.zeros( ( rows + 2, cols + 1, 6 ), np.int16 ) array[ INDEX, :, VALUE ] = -1 array[ :, INDEX, VALUE ] = -1 array[ META, INDEX, VALUE ] = 0 array[ INDEX, INDEX, VALUE ] = 0 col_ind = np.arange( 1, cols+1, 1, np.int16) annex_row( array, INDEX, col_ind ) #array[ INDEX, INDEX, VALUE ] = cols return array # Cover @cc.export('cover','void( i2[:,:,:],i2,i2,i2 )') @njit( 'void( i2[:,:,:],i2,i2,i2 )',nogil=True) def cover( array, row, col, level ): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 META, COVERCOUNT, SOLUTIONCOUNT = -1, -1, 0 ROW, COL = 0 ,1 array[ META, level, VALUE ] = row array[ META, COVERCOUNT, VALUE ] += array[ row, INDEX, VALUE ] j = col while True: #for j in r_sweep( array, row, col ): if array[ INDEX, j, LINKED ]: #unlink_col( array, j ) col_index = array[ INDEX, j ] # Unlink Left - Right array[ INDEX, col_index[L], R ] = col_index[R] array[ INDEX, col_index[R], L ] = col_index[L] col_index[LINKED] = 0 # Update main header index_index = array[ INDEX, INDEX ] if index_index[L] == j == index_index[R]: index_index[LINKED] = 0 if index_index[L] == j: index_index[L] = col_index[L] if index_index[R] == j: index_index[R] = col_index[R] j = array[ row, j, R ] if j == col: break j = col while True: #for j in r_sweep( array, row, col ): i = row while True: #for i in d_sweep( array, row, j ): if array[ i, INDEX, LINKED ]: #Works when left out #unlink_row(array, i ) row_index = array[ i, INDEX ] # Unlink Up - Down array[ row_index[D], INDEX, U ] = row_index[U] array[ row_index[U], INDEX, D ] = row_index[D] row_index[LINKED] = 0 # Update main header index_index = array[ INDEX, INDEX ] if index_index[U] == i == index_index[D]: index_index[LINKED] = 0 if index_index[U] == i: index_index[U] = row_index[U] if index_index[D] == i: index_index[D] = row_index[D] k = array[ i, j, R ] # Skip first collumn and unlink 'loose' nodes, ie. nodes not in both unlinked rows and cols lattice while k != j: if ( array[ INDEX, k, LINKED ] or array[ i, INDEX, LINKED ] ) and array[ i, k, LINKED ]: #unlink_node( array, i, k ) node = array[ i, k ] array[ node[D], k, U ] = node[U] array[ node[U], k, D ] = node[D] # Update collumn index col_index = array[ INDEX, k ] if i == col_index[U]: col_index[U] = node[U] if i == col_index[D]: col_index[D] = node[D] col_index[VALUE] -= 1 node[LINKED] = 0 k = array[ i, k, R ] i = array[ i, j, D ] if i == row: break j = array[ row, j, R ] if j == col: break # Uncover @cc.export('uncover','void( i2[:,:,:] )') @njit( 'void( i2[:,:,:] )',nogil=True) def uncover(array): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 META, COVERCOUNT, SOLUTIONCOUNT = -1, -1, 0 ROW, COL = 0 ,1 level = array[ INDEX, INDEX, VALUE ] row = array[ META, level, ROW ] col = array[ META, level, COL ] j = col while True: #for j in r_sweep( array, row, col ): if not array[ INDEX, j, LINKED ]: #relink_col(array, j ) col_index = array[ INDEX, j ] array[ INDEX, col_index[R], L] = array[ INDEX, col_index[L], R] = j col_index[LINKED] = 1 # Update main header index_index = array[ INDEX, INDEX ] if j > index_index[L]: index_index[L] = j if j < index_index[R]: index_index[R] = j index_index[LINKED] = 1 i = row while True: #for i in d_sweep( array, row, j ): if not array[ i, INDEX , LINKED ]: #relink_row( array, i ) row_index = array[ i, INDEX ] array[ row_index[U], INDEX, D ] = array[ row_index[D], INDEX, U ] = i row_index[LINKED] = 1 # Update main header index_index = array[ INDEX, INDEX ] if i < index_index[D]: index_index[D] = i if i > index_index[U]: index_index[U] = i index_index[LINKED] = 1 # for k in r_sweep( array, i ,j k = array[ i, j, R ] # Skip first collumn and relink 'loose' nodes, ie. nodes not in both unlinked rows and cols lattice while k != j: if not array[ i, k, LINKED ]: #relink_node( array, i, k ) node = array[ i, k ] array[ node[D], k, U ] = array[ node[U], k, D ] = i col_index = array[ INDEX, k ] if i > col_index[U]: col_index[U] = i if i < col_index[D]: col_index[D] = i col_index[VALUE] += 1 node[LINKED] = 1 k = array[ i, k, R ] i = array[ i, j, D ] if i == row: break j = array[ row, j, R ] if j == col: break array[ META, COVERCOUNT, VALUE ] -= array[ row, INDEX, VALUE ] @cc.export('min_col','i2( i2[:,:,:] )') @njit( 'i2( i2[:,:,:] )',nogil=True) def min_col( array ): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 min_val = np.iinfo(np.int16).max col = 0 cl = array[ INDEX, INDEX, R ] j = cl while True: #for j in r_sweep( array, INDEX, cl ): if array[ INDEX, j, VALUE ] < min_val: min_val = array[ INDEX, j, VALUE ] col = j j = array[ INDEX, j, R ] if j == cl: break return col def dump(array): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 rows = array.shape[0] cols = array.shape[1] print('rows',rows,'cols',cols) print() for cl in range(cols): print('\tcol',cl,end='') print() print() for rw,row in enumerate(array): print('\t',end='') for node in row: print(node[LINKED],node[U],'\t',end='') print() print('row',rw,'\t',end='') for node in row: print(node[L],node[VALUE],node[R],'\t',end='') print() print('\t',end='') for node in row: print(' ',node[D],'\t',end='') print() print() @cc.export('isempty','b1(i2[:,:,:])') @njit( 'b1(i2[:,:,:])', nogil=True) def isempty(array): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 META, COVERCOUNT, SOLUTIONCOUNT = -1, -1, 0 ROW, COL = 0 ,1 if not array[ INDEX, INDEX, LINKED ] and array[ META, COVERCOUNT, VALUE ] == array.shape[1] - 1: array[ META, SOLUTIONCOUNT, VALUE ] += 1 return True return False @cc.export('mcr_cover','b1(i2[:,:,:])') @njit( 'b1(i2[:,:,:])', nogil=True) def mcr_cover(array): L, R, U, D, LINKED, VALUE = range(6) INDEX = 0 META, ROW, COL, FIRSTROW = -1, 0, 1, 2 level = array[ INDEX, INDEX, VALUE ] first_row = array[ META, level, FIRSTROW ] if first_row == 0: col = min_col(array) if array[ INDEX, col, VALUE ] > 0: row = array[ INDEX, col, D ] array[ META, level, FIRSTROW ] = row array[ META, level, ROW ] = row array[ META, level, COL ] = col cover( array, row, col, level ) return True else: return False else: level = array[ INDEX, INDEX, VALUE ] first_row = array[ META, level, FIRSTROW ] row = array[ META, level, ROW ] col = array[ META, level, COL ] row = array[ row, col, D ] if row != first_row: array[ META, level, ROW ] = row cover( array, row, col, level ) return True else: array[ META, level, FIRSTROW ] = 0 return False @cc.export('exact_cover','b1(i2[:,:,:])') @njit ( 'b1(i2[:,:,:])', nogil=True) def exact_cover( array ): INDEX, VALUE, META, SOLUTIONCOUNT = 0, -1, -1, 0 ii = array[ INDEX, INDEX ] if ii[VALUE] == 0: # First time: # Reset solution counter array[ META, SOLUTIONCOUNT, VALUE ] = 0 # Level up ii[VALUE] += 1 else: # Consecutive time, Level down ii[VALUE] -= 1 if ii[VALUE] == 0: return False # Uncover preceding exact cover uncover(array) while True: # If any left, get next row in column with minimum node count and cover it if mcr_cover(array): # Level up ii[VALUE] += 1 # If exact cover found, hop in and out with result if isempty(array): return True # Else backtrack else: # Level down ii[VALUE] -= 1 if ii[VALUE] == 0: # Exit loop return False # Uncover preceding trivial cover uncover(array) if __name__ == '__main__': #cc.compile() """ #import os #os.environ['NUMBA_DISABLE_JIT'] = "1" """ INDEX, META, SOLUTIONCOUNT, VALUE, SOLUTION = 0, -1, 0, -1, 1 array = init( 6, 7 ) dt = np.int16 annex_row( array, 1, np.array([ 1, 4, 7 ], dt ) ) annex_row( array, 2, np.array([ 1, 4 ], dt ) ) annex_row( array, 3, np.array([ 4, 5, 7 ], dt ) ) annex_row( array, 4, np.array([ 3, 5, 6 ], dt ) ) annex_row( array, 5, np.array([ 2, 3, 6, 7 ], dt ) ) annex_row( array, 6, np.array([ 2, 7 ], dt ) ) ii = array[ INDEX, INDEX ] while exact_cover( array ): print( array[ META, SOLUTION : ii[VALUE], VALUE ] ) print( array[ META, SOLUTIONCOUNT, VALUE ])
[ "numba.pycc.CC", "numba.njit", "numpy.zeros", "numpy.iinfo", "numpy.arange", "numpy.array", "numba.typed.List" ]
[((119, 136), 'numba.pycc.CC', 'CC', (['"""algoxtoolsp"""'], {}), "('algoxtoolsp')\n", (121, 136), False, 'from numba.pycc import CC\n'), ((213, 249), 'numba.njit', 'njit', (['"""void( i2[:,:,:], i2, i2[:] )"""'], {}), "('void( i2[:,:,:], i2, i2[:] )')\n", (217, 249), False, 'from numba import njit, objmode, types\n'), ((2113, 2138), 'numba.njit', 'njit', (['"""i2[:,:,:](i2, i2)"""'], {}), "('i2[:,:,:](i2, i2)')\n", (2117, 2138), False, 'from numba import njit, objmode, types\n'), ((2639, 2685), 'numba.njit', 'njit', (['"""void( i2[:,:,:],i2,i2,i2 )"""'], {'nogil': '(True)'}), "('void( i2[:,:,:],i2,i2,i2 )', nogil=True)\n", (2643, 2685), False, 'from numba import njit, objmode, types\n'), ((5747, 5784), 'numba.njit', 'njit', (['"""void( i2[:,:,:] )"""'], {'nogil': '(True)'}), "('void( i2[:,:,:] )', nogil=True)\n", (5751, 5784), False, 'from numba import njit, objmode, types\n'), ((8318, 8353), 'numba.njit', 'njit', (['"""i2( i2[:,:,:] )"""'], {'nogil': '(True)'}), "('i2( i2[:,:,:] )', nogil=True)\n", (8322, 8353), False, 'from numba import njit, objmode, types\n'), ((9513, 9546), 'numba.njit', 'njit', (['"""b1(i2[:,:,:])"""'], {'nogil': '(True)'}), "('b1(i2[:,:,:])', nogil=True)\n", (9517, 9546), False, 'from numba import njit, objmode, types\n'), ((9931, 9964), 'numba.njit', 'njit', (['"""b1(i2[:,:,:])"""'], {'nogil': '(True)'}), "('b1(i2[:,:,:])', nogil=True)\n", (9935, 9964), False, 'from numba import njit, objmode, types\n'), ((11049, 11082), 'numba.njit', 'njit', (['"""b1(i2[:,:,:])"""'], {'nogil': '(True)'}), "('b1(i2[:,:,:])', nogil=True)\n", (11053, 11082), False, 'from numba import njit, objmode, types\n'), ((385, 391), 'numba.typed.List', 'List', ([], {}), '()\n', (389, 391), False, 'from numba.typed import List\n'), ((2245, 2288), 'numpy.zeros', 'np.zeros', (['(rows + 2, cols + 1, 6)', 'np.int16'], {}), '((rows + 2, cols + 1, 6), np.int16)\n', (2253, 2288), True, 'import numpy as np\n'), ((2448, 2483), 'numpy.arange', 'np.arange', (['(1)', '(cols + 1)', '(1)', 'np.int16'], {}), '(1, cols + 1, 1, np.int16)\n', (2457, 2483), True, 'import numpy as np\n'), ((8448, 8466), 'numpy.iinfo', 'np.iinfo', (['np.int16'], {}), '(np.int16)\n', (8456, 8466), True, 'import numpy as np\n'), ((12358, 12381), 'numpy.array', 'np.array', (['[1, 4, 7]', 'dt'], {}), '([1, 4, 7], dt)\n', (12366, 12381), True, 'import numpy as np\n'), ((12412, 12432), 'numpy.array', 'np.array', (['[1, 4]', 'dt'], {}), '([1, 4], dt)\n', (12420, 12432), True, 'import numpy as np\n'), ((12463, 12486), 'numpy.array', 'np.array', (['[4, 5, 7]', 'dt'], {}), '([4, 5, 7], dt)\n', (12471, 12486), True, 'import numpy as np\n'), ((12517, 12540), 'numpy.array', 'np.array', (['[3, 5, 6]', 'dt'], {}), '([3, 5, 6], dt)\n', (12525, 12540), True, 'import numpy as np\n'), ((12571, 12597), 'numpy.array', 'np.array', (['[2, 3, 6, 7]', 'dt'], {}), '([2, 3, 6, 7], dt)\n', (12579, 12597), True, 'import numpy as np\n'), ((12628, 12648), 'numpy.array', 'np.array', (['[2, 7]', 'dt'], {}), '([2, 7], dt)\n', (12636, 12648), True, 'import numpy as np\n')]
import cv2 import numpy as np from typing import List, Tuple, Union from statistics import mode, median, mean import io import uuid from collections import deque from minio.error import ResponseError from minio_setup import minio_client, bucket_name class ImagePreprocessingService: min_height_to_width_ratio: int = 1 max_height_to_width_ratio: int = 10 min_rect_height_to_image_height_ratio: float = 0.2 white_color = (255, 255, 255) green_color = (0, 255, 0) @classmethod def get_images_with_characters(cls, image: np.ndarray): image = cls.resize_image(image) contours, thres = cls.prepare_for_roi_from_biggest_countour(image) img_contours_roi = image.copy() cv2.drawContours(img_contours_roi, contours, -1, cls.green_color, 3) roi, boundary_rectangle = cls.get_roi_from_the_biggest_countour(image, contours) roi = cls.resize_image(roi) image_for_segmentation = cls.prepare_for_segmentation(roi) cont = cls.get_contours(image_for_segmentation) img_contours_characters = np.zeros_like(roi) for i in range(3): img_contours_characters[:, :, i] = image_for_segmentation cv2.drawContours(img_contours_characters, cont, -1, cls.green_color, 3) characters, rects = cls.get_rects(cont, roi) rectangle_characters_image = cls.draw_rectangles_on_image(roi, rects) concatenated_characters = cls.concatenate_characters(characters) # concatenated_characters_height = concatenated_characters.shape[0] # concatenated_characters_width = concatenated_characters.shape[1] # border_size = int(concatenated_characters_height * 0.3) border_size = 3 concatenated_characters_bordered = cv2.copyMakeBorder( concatenated_characters, border_size, border_size, border_size, border_size, cv2.BORDER_CONSTANT, value=cls.white_color, ) images = {} images["characters"] = characters images["concatenated"] = concatenated_characters images["concatenated_bordered"] = concatenated_characters_bordered images["roi"] = roi images["binary_seg"] = image_for_segmentation images["thresh_roi"] = thres images["countours_roi"] = img_contours_roi images["image_for_segmentation"] = image_for_segmentation images["countours_characters"] = img_contours_characters images["rectangles_characters"] = rectangle_characters_image return images @staticmethod def draw_rectangles_on_image( image: np.ndarray, rectangles: List[Tuple[int, int, int, int]] ): image_with_rectangles = image.copy() for rect in rectangles: cv2.rectangle( image_with_rectangles, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), ImagePreprocessingService.green_color, 2, ) return image_with_rectangles @classmethod def from_bytes_to_image(cls, img_bytes: bytes): np_img = np.frombuffer(img_bytes, dtype=np.uint8) return cv2.imdecode(np_img, cv2.IMREAD_UNCHANGED) @classmethod def prepare_for_segmentation(cls, img: np.ndarray) -> np.ndarray: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3, 3), 0) binary = cv2.threshold(blur, 150, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[ 1 ] return binary @classmethod def get_contours(cls, img: np.ndarray): cont, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) return cont @classmethod def sort_contours(cls, cnts, reverse: bool = False): i = 0 boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip( *sorted(zip(cnts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse) ) return cnts @classmethod def filter_contours_by_ratios(cls, cnts, img_height: int): filtered_cnts = [] for c in cnts: (x, y, w, h) = cv2.boundingRect(c) ratio = h / w if cls.min_height_to_width_ratio <= ratio <= cls.max_height_to_width_ratio: if h / img_height >= cls.min_rect_height_to_image_height_ratio: filtered_cnts.append(c) return filtered_cnts @staticmethod def contours_to_characters(contours, image): characters = [] for c in contours: (x, y, w, h) = cv2.boundingRect(c) character = image[y : (y + h), x : (x + w)] characters.append(character) return characters @staticmethod def save_images_to_minio(images: dict): paths = {} for key, image in images.items(): if isinstance(image, list): paths_list = {} for i in range(len(image)): path = ImagePreprocessingService.save_image_minio( image[i], filename_sufix=f"{key}{i}" ) paths_list[f"{key}{i}"] = path paths[key] = paths_list else: saved_image_path = ImagePreprocessingService.save_image_minio( image, key ) paths[key] = saved_image_path return paths @staticmethod def save_image_minio( image: Union[bytes, np.ndarray], filename_sufix: str = "" ) -> str: if image is None: return "" if isinstance(image, np.ndarray): success, encoded_image = cv2.imencode(".jpeg", image) image = encoded_image.tobytes() uid = uuid.uuid1() if filename_sufix != "": filename_sufix = f"-{filename_sufix}" filename = f"{uid}{filename_sufix}.jpeg" path = f"{bucket_name}/{filename}" try: with io.BytesIO(image) as data: _ = minio_client.put_object(bucket_name, filename, data, len(image)) except ResponseError as e: print(e) return path @staticmethod def save_image(image: np.ndarray, filename_prefix: str = ""): try: cv2.imwrite(f"/img/{filename_prefix}.jpeg", image) except Exception as e: print(e) @staticmethod def save_images( images: List[np.ndarray], filename_prefix: str = "", dir="/numbers" ): print("Number of images: ", len(images)) for i in range(len(images)): cv2.imwrite(f"{dir}/{filename_prefix}{i}.jpeg", images[i]) @staticmethod def save_images_with_key_as_prefix(images: dict): for key, image in images.items(): if isinstance(image, list): ImagePreprocessingService.save_images( image, filename_prefix=key, dir="/img/numbers" ) else: ImagePreprocessingService.save_image(image, filename_prefix=key) @staticmethod def is_rectangle1_in_rectangle2( rectangle1: Tuple[int], rectangle2: Tuple[int] ) -> bool: (x1, y1, w1, h1) = rectangle1 (x2, y2, w2, h2) = rectangle2 # centre of 1st rectangle x_central = x1 + w1 / 2 y_central = y1 + h1 / 2 return ( x2 < x_central and x_central < x2 + w2 and y2 < y_central and y_central < y2 + h2 ) @classmethod def get_rects(cls, cont, img: np.ndarray): cropped_characters: List[np.ndarray] = [] img_height = img.shape[0] img_width = img.shape[1] sorted_contours = cls.sort_contours(cont) sorted_characters = cls.contours_to_characters(sorted_contours, img) cls.save_images(sorted_characters, filename_prefix="sort") # filtered_contours = sorted_contours filtered_contours = cls.filter_contours_by_ratios(sorted_contours, img_height) filtered_characters = cls.contours_to_characters(filtered_contours, img) cls.save_images(filtered_characters, filename_prefix="fil") print("Number of filtered_contours", len(filtered_contours)) characters = [] for i in range(len(filtered_contours)): character = filtered_contours[i] (x, y, w, h) = cv2.boundingRect(character) characters_length = len(characters) if characters_length > 0: index = characters[characters_length - 1][1] prev_character = filtered_contours[index] prev_rect = cv2.boundingRect(prev_character) if cls.is_rectangle1_in_rectangle2((x, y, w, h), prev_rect): continue curr_num = (x, y, w, h) entry = (curr_num, i) characters.append(entry) characters = [c[0] for c in characters] heights = [c[3] for c in characters] height_mode = mode(heights) height_median = median(heights) widths = [c[2] for c in characters] width_mode = mode(widths) print("Height mode:", height_mode) print("Height median:", height_median) height_factor_min = 0.9 * height_median height_factor_max = 2 * height_median cropped_characters_filtered = list( filter( lambda c: c[3] > height_factor_min and c[3] < height_factor_max, characters, ), ) ys = [c[1] for c in cropped_characters_filtered] y_mean = mean(ys) print("Ys: ", ys) print("Y mean: ", y_mean) heights = [c[3] for c in cropped_characters_filtered] height_median = median(heights) # should change order of characters when process double row lp stack = deque() for i in range(len(cropped_characters_filtered)): if cropped_characters_filtered[i][1] < (y_mean - 0.5 * height_median): stack.append(i) corrected_characters = [ e for i, e in enumerate(cropped_characters_filtered) if i not in stack ] while len(stack) > 0: index = stack.pop() element = cropped_characters_filtered[index] corrected_characters.insert(0, element) cropped_characters_filtered = corrected_characters print( "Number of filtered cropped_characters: ", len(cropped_characters_filtered), ) bias_h = int(0.1 * height_mode) bias_w = int(0.15 * width_mode) for cords in cropped_characters_filtered: (x, y, w, h) = cords y_1 = 0 if y - bias_h < 0 else y - bias_h y_2 = img_height if y + h + bias_h > img_height else y + h + bias_h x_1 = 0 if x - bias_w < 0 else x - bias_w x_2 = img_width if x + w + bias_w > img_width else x + w + bias_w curr_num = img[y_1:y_2, x_1:x_2] cropped_characters.append(curr_num) print("Number of cropped_characters: ", len(cropped_characters)) return cropped_characters, cropped_characters_filtered @staticmethod def concatenate_characters(characters: List[np.ndarray]) -> np.ndarray: heights = [character.shape[0] for character in characters] height_mode = mode(heights) resized_characters = [] for c in characters: if height_mode == c.shape[1]: continue dim = (c.shape[1], height_mode) resized = cv2.resize(c, dim, interpolation=cv2.INTER_AREA) resized_characters.append(resized) return cv2.hconcat(resized_characters) @staticmethod def get_the_biggest_contour(contours): cnts = sorted(contours, key=cv2.contourArea, reverse=True) return cnts[0] @classmethod def get_roi_from_the_biggest_countour( cls, image, contours ) -> Tuple[np.ndarray, Tuple[int]]: countour = cls.get_the_biggest_contour(contours) rect = cv2.boundingRect(countour) (x, y, w, h) = rect result = image[y : y + h, x : x + w] return result, rect @classmethod def prepare_for_roi_from_biggest_countour(cls, image): gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) kernel = np.ones((5, 5), np.float32) / 15 filtered = cv2.filter2D(gray, -1, kernel) _, thresh = cv2.threshold(filtered, 250, 255, cv2.THRESH_OTSU) contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) return contours, thresh @staticmethod def resize_image(image: np.ndarray, scale: float = 4.0): width = int(image.shape[1] * scale) height = int(image.shape[0] * scale) dim = (width, height) resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) return resized
[ "cv2.GaussianBlur", "cv2.imdecode", "numpy.ones", "cv2.rectangle", "cv2.imencode", "collections.deque", "numpy.zeros_like", "cv2.filter2D", "cv2.cvtColor", "cv2.imwrite", "cv2.copyMakeBorder", "cv2.hconcat", "statistics.mode", "cv2.drawContours", "cv2.boundingRect", "cv2.resize", "io...
[((726, 794), 'cv2.drawContours', 'cv2.drawContours', (['img_contours_roi', 'contours', '(-1)', 'cls.green_color', '(3)'], {}), '(img_contours_roi, contours, -1, cls.green_color, 3)\n', (742, 794), False, 'import cv2\n'), ((1080, 1098), 'numpy.zeros_like', 'np.zeros_like', (['roi'], {}), '(roi)\n', (1093, 1098), True, 'import numpy as np\n'), ((1204, 1275), 'cv2.drawContours', 'cv2.drawContours', (['img_contours_characters', 'cont', '(-1)', 'cls.green_color', '(3)'], {}), '(img_contours_characters, cont, -1, cls.green_color, 3)\n', (1220, 1275), False, 'import cv2\n'), ((1767, 1910), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['concatenated_characters', 'border_size', 'border_size', 'border_size', 'border_size', 'cv2.BORDER_CONSTANT'], {'value': 'cls.white_color'}), '(concatenated_characters, border_size, border_size,\n border_size, border_size, cv2.BORDER_CONSTANT, value=cls.white_color)\n', (1785, 1910), False, 'import cv2\n'), ((3168, 3208), 'numpy.frombuffer', 'np.frombuffer', (['img_bytes'], {'dtype': 'np.uint8'}), '(img_bytes, dtype=np.uint8)\n', (3181, 3208), True, 'import numpy as np\n'), ((3224, 3266), 'cv2.imdecode', 'cv2.imdecode', (['np_img', 'cv2.IMREAD_UNCHANGED'], {}), '(np_img, cv2.IMREAD_UNCHANGED)\n', (3236, 3266), False, 'import cv2\n'), ((3370, 3407), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (3382, 3407), False, 'import cv2\n'), ((3423, 3456), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['gray', '(3, 3)', '(0)'], {}), '(gray, (3, 3), 0)\n', (3439, 3456), False, 'import cv2\n'), ((3673, 3734), 'cv2.findContours', 'cv2.findContours', (['img', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (3689, 3734), False, 'import cv2\n'), ((5833, 5845), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (5843, 5845), False, 'import uuid\n'), ((9090, 9103), 'statistics.mode', 'mode', (['heights'], {}), '(heights)\n', (9094, 9103), False, 'from statistics import mode, median, mean\n'), ((9128, 9143), 'statistics.median', 'median', (['heights'], {}), '(heights)\n', (9134, 9143), False, 'from statistics import mode, median, mean\n'), ((9209, 9221), 'statistics.mode', 'mode', (['widths'], {}), '(widths)\n', (9213, 9221), False, 'from statistics import mode, median, mean\n'), ((9681, 9689), 'statistics.mean', 'mean', (['ys'], {}), '(ys)\n', (9685, 9689), False, 'from statistics import mode, median, mean\n'), ((9838, 9853), 'statistics.median', 'median', (['heights'], {}), '(heights)\n', (9844, 9853), False, 'from statistics import mode, median, mean\n'), ((9942, 9949), 'collections.deque', 'deque', ([], {}), '()\n', (9947, 9949), False, 'from collections import deque\n'), ((11456, 11469), 'statistics.mode', 'mode', (['heights'], {}), '(heights)\n', (11460, 11469), False, 'from statistics import mode, median, mean\n'), ((11778, 11809), 'cv2.hconcat', 'cv2.hconcat', (['resized_characters'], {}), '(resized_characters)\n', (11789, 11809), False, 'import cv2\n'), ((12164, 12190), 'cv2.boundingRect', 'cv2.boundingRect', (['countour'], {}), '(countour)\n', (12180, 12190), False, 'import cv2\n'), ((12384, 12423), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2GRAY'], {}), '(image, cv2.COLOR_RGB2GRAY)\n', (12396, 12423), False, 'import cv2\n'), ((12493, 12523), 'cv2.filter2D', 'cv2.filter2D', (['gray', '(-1)', 'kernel'], {}), '(gray, -1, kernel)\n', (12505, 12523), False, 'import cv2\n'), ((12544, 12594), 'cv2.threshold', 'cv2.threshold', (['filtered', '(250)', '(255)', 'cv2.THRESH_OTSU'], {}), '(filtered, 250, 255, cv2.THRESH_OTSU)\n', (12557, 12594), False, 'import cv2\n'), ((12618, 12680), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_NONE'], {}), '(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n', (12634, 12680), False, 'import cv2\n'), ((12930, 12982), 'cv2.resize', 'cv2.resize', (['image', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(image, dim, interpolation=cv2.INTER_AREA)\n', (12940, 12982), False, 'import cv2\n'), ((2810, 2952), 'cv2.rectangle', 'cv2.rectangle', (['image_with_rectangles', '(rect[0], rect[1])', '(rect[0] + rect[2], rect[1] + rect[3])', 'ImagePreprocessingService.green_color', '(2)'], {}), '(image_with_rectangles, (rect[0], rect[1]), (rect[0] + rect[2],\n rect[1] + rect[3]), ImagePreprocessingService.green_color, 2)\n', (2823, 2952), False, 'import cv2\n'), ((3474, 3544), 'cv2.threshold', 'cv2.threshold', (['blur', '(150)', '(255)', '(cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)'], {}), '(blur, 150, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n', (3487, 3544), False, 'import cv2\n'), ((3869, 3888), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (3885, 3888), False, 'import cv2\n'), ((4216, 4235), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (4232, 4235), False, 'import cv2\n'), ((4650, 4669), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (4666, 4669), False, 'import cv2\n'), ((5745, 5773), 'cv2.imencode', 'cv2.imencode', (['""".jpeg"""', 'image'], {}), "('.jpeg', image)\n", (5757, 5773), False, 'import cv2\n'), ((6351, 6401), 'cv2.imwrite', 'cv2.imwrite', (['f"""/img/{filename_prefix}.jpeg"""', 'image'], {}), "(f'/img/{filename_prefix}.jpeg', image)\n", (6362, 6401), False, 'import cv2\n'), ((6676, 6734), 'cv2.imwrite', 'cv2.imwrite', (['f"""{dir}/{filename_prefix}{i}.jpeg"""', 'images[i]'], {}), "(f'{dir}/{filename_prefix}{i}.jpeg', images[i])\n", (6687, 6734), False, 'import cv2\n'), ((8463, 8490), 'cv2.boundingRect', 'cv2.boundingRect', (['character'], {}), '(character)\n', (8479, 8490), False, 'import cv2\n'), ((11666, 11714), 'cv2.resize', 'cv2.resize', (['c', 'dim'], {'interpolation': 'cv2.INTER_AREA'}), '(c, dim, interpolation=cv2.INTER_AREA)\n', (11676, 11714), False, 'import cv2\n'), ((12441, 12468), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.float32'], {}), '((5, 5), np.float32)\n', (12448, 12468), True, 'import numpy as np\n'), ((6052, 6069), 'io.BytesIO', 'io.BytesIO', (['image'], {}), '(image)\n', (6062, 6069), False, 'import io\n'), ((8725, 8757), 'cv2.boundingRect', 'cv2.boundingRect', (['prev_character'], {}), '(prev_character)\n', (8741, 8757), False, 'import cv2\n')]
import matplotlib.pyplot as plt import numpy as np x = np.array([1, 2, 3, 4, 5]) y1 = x ** 2 y2 = x ** 3 plt.subplot(1, 2, 1) plt.plot(x, y1, 'r-') plt.legend(['Y = x^2']) plt.subplot(1, 2, 2) plt.plot(x, y2, 'b-') plt.legend(['Y = x^3']) plt.suptitle('contoh grafik fungsi') plt.show()
[ "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.legend", "numpy.array" ]
[((56, 81), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (64, 81), True, 'import numpy as np\n'), ((107, 127), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (118, 127), True, 'import matplotlib.pyplot as plt\n'), ((128, 149), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y1', '"""r-"""'], {}), "(x, y1, 'r-')\n", (136, 149), True, 'import matplotlib.pyplot as plt\n'), ((150, 173), 'matplotlib.pyplot.legend', 'plt.legend', (["['Y = x^2']"], {}), "(['Y = x^2'])\n", (160, 173), True, 'import matplotlib.pyplot as plt\n'), ((175, 195), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (186, 195), True, 'import matplotlib.pyplot as plt\n'), ((196, 217), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y2', '"""b-"""'], {}), "(x, y2, 'b-')\n", (204, 217), True, 'import matplotlib.pyplot as plt\n'), ((218, 241), 'matplotlib.pyplot.legend', 'plt.legend', (["['Y = x^3']"], {}), "(['Y = x^3'])\n", (228, 241), True, 'import matplotlib.pyplot as plt\n'), ((243, 279), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""contoh grafik fungsi"""'], {}), "('contoh grafik fungsi')\n", (255, 279), True, 'import matplotlib.pyplot as plt\n'), ((280, 290), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (288, 290), True, 'import matplotlib.pyplot as plt\n')]
""" Testing for the openmm_wrapper module """ import pytest from janus.mm_wrapper import OpenMMWrapper import simtk.unit as OM_unit import numpy as np import os #ala_water_pdb_file = os.path.join(str('tests/files/test_openmm/ala_water.pdb')) water_pdb_file = os.path.join(str('tests/files/test_openmm/water.pdb')) ala_pdb_file = os.path.join(str('tests/files/test_openmm/ala_ala_ala.pdb')) wrapper = OpenMMWrapper(sys_info=water_pdb_file, **{'md_ensemble':'NVT', 'return_info':[]}) wrapper_ala = OpenMMWrapper(sys_info=ala_pdb_file, **{'md_ensemble':'NVT'}) #openmm_mech = openmm_wrapper.OpenMM_wrapper(sys_mech) #openmm_elec = openmm_wrapper.OpenMM_wrapper(sys_elec) #openmm_ala_link = openmm_wrapper.OpenMM_wrapper(sys_ala_link) #openmm_ala_link_2 = openmm_wrapper.OpenMM_wrapper(sys_ala_link) def test_create_new_residue_template(): mod = wrapper_ala.create_modeller(keep_atoms=False, atoms=[0,1,2,3]) wrapper_ala.create_new_residue_template(mod.topology) assert wrapper_ala.forcefield._templates['Modified_ALA'].name == 'Modified_ALA' def test_set_charge_zero(): sys1 = wrapper.create_openmm_system(wrapper.pdb.topology) sys2 = wrapper.create_openmm_system(wrapper.pdb.topology) wrapper.set_charge_zero(sys1) wrapper.set_charge_zero(sys2, link_atoms = [0]) assert sys1.getForce(3).getParticleParameters(0)[0]/OM_unit.elementary_charge == 0.0 assert sys1.getForce(3).getParticleParameters(1)[0]/OM_unit.elementary_charge == 0.0 assert sys2.getForce(3).getParticleParameters(0)[0]/OM_unit.elementary_charge == 0.0 assert sys2.getForce(3).getParticleParameters(1)[0]/OM_unit.elementary_charge == 0.417 def test_set_LJ_zero(): sys = wrapper.create_openmm_system(wrapper.pdb.topology) wrapper.set_LJ_zero(sys) assert sys.getForce(3).getParticleParameters(0)[0]/OM_unit.elementary_charge == -0.834 assert sys.getForce(3).getParticleParameters(0)[1]/OM_unit.nanometer == 0.0 assert sys.getForce(3).getParticleParameters(0)[2]/OM_unit.kilojoule_per_mole == 0.0 def test_create_openmm_system(): sys_1 = wrapper.create_openmm_system(wrapper.pdb.topology) sys_2 = wrapper.create_openmm_system(wrapper.pdb.topology, include_coulomb='all', initialize=True) sys_3 = wrapper.create_openmm_system(wrapper.pdb.topology, include_coulomb='only') assert sys_1.getNumForces() == 5 assert sys_2.getNumForces() == 6 assert sys_3.getNumForces() == 2 def test_compute_info(): #print(wrapper.md_ensemble) #print(wrapper.integrator) state1 = wrapper.compute_info(wrapper.pdb.topology, wrapper.pdb.positions) state2 = wrapper.compute_info(wrapper.pdb.topology, wrapper.pdb.positions, minimize=True) #print(state1['kinetic'] + state1['potential']) #print(state2['kinetic'] + state2['potential']) assert np.allclose(state1['kinetic'] + state1['potential'],-0.010557407627282312) assert np.allclose(state2['kinetic'] + state2['potential'],-0.02892,rtol=1e-05,atol=1e-05) def test_initialize(): wrapper.initialize('Mechanical') wrapper_ala.initialize('Electrostatic') assert np.allclose(wrapper.main_info['kinetic'] + wrapper.main_info['potential'], -0.010557407627282312) assert np.allclose(wrapper_ala.main_info['kinetic'] + wrapper_ala.main_info['potential'], 0.016526506142315156) def test_get_main_info(): state1 = wrapper.get_main_info() state2 = wrapper_ala.get_main_info() assert np.allclose(state1['kinetic'] + state1['potential'], -0.010557407627282312) assert np.allclose(state2['kinetic'] + state2['potential'],0.016526506142315156) assert 'topology' in state1 assert 'topology' in state2 def test_take_updated_step(): force1 = {0 : np.array([0.0,0.0,0.0]), 1 : np.array([0.0, 0.0, 0.0])} force2 = {0 : np.array([0.0,0.0,0.0]), 1 : np.array([-0.0001, -0.0001, -0.0001])} wrapper.take_updated_step(force1) energy1 = wrapper.main_info['kinetic'] + wrapper.main_info['potential'] #forces1 = wrapper.main_info['forces'][1] wrapper.take_updated_step(force2) energy2 = wrapper.main_info['kinetic'] + wrapper.main_info['potential'] #forces2 = wrapper.main_info['forces'][1] assert np.allclose(energy1, -0.0105, atol=1e-04) assert np.allclose(energy2, -0.009, atol=1e-03) def test_create_modeller(): mod1 = wrapper_ala.create_modeller(atoms=[0,1,2,3], keep_atoms=True) mod2 = wrapper_ala.create_modeller(atoms=[0,1,2,3], keep_atoms=False) atom1 = mod1.topology.getNumAtoms() atom2 = mod2.topology.getNumAtoms() assert atom1 == 4 assert atom2 == 29
[ "numpy.array", "numpy.allclose", "janus.mm_wrapper.OpenMMWrapper" ]
[((402, 489), 'janus.mm_wrapper.OpenMMWrapper', 'OpenMMWrapper', ([], {'sys_info': 'water_pdb_file'}), "(sys_info=water_pdb_file, **{'md_ensemble': 'NVT',\n 'return_info': []})\n", (415, 489), False, 'from janus.mm_wrapper import OpenMMWrapper\n'), ((498, 560), 'janus.mm_wrapper.OpenMMWrapper', 'OpenMMWrapper', ([], {'sys_info': 'ala_pdb_file'}), "(sys_info=ala_pdb_file, **{'md_ensemble': 'NVT'})\n", (511, 560), False, 'from janus.mm_wrapper import OpenMMWrapper\n'), ((2813, 2888), 'numpy.allclose', 'np.allclose', (["(state1['kinetic'] + state1['potential'])", '(-0.010557407627282312)'], {}), "(state1['kinetic'] + state1['potential'], -0.010557407627282312)\n", (2824, 2888), True, 'import numpy as np\n'), ((2899, 2989), 'numpy.allclose', 'np.allclose', (["(state2['kinetic'] + state2['potential'])", '(-0.02892)'], {'rtol': '(1e-05)', 'atol': '(1e-05)'}), "(state2['kinetic'] + state2['potential'], -0.02892, rtol=1e-05,\n atol=1e-05)\n", (2910, 2989), True, 'import numpy as np\n'), ((3099, 3201), 'numpy.allclose', 'np.allclose', (["(wrapper.main_info['kinetic'] + wrapper.main_info['potential'])", '(-0.010557407627282312)'], {}), "(wrapper.main_info['kinetic'] + wrapper.main_info['potential'], \n -0.010557407627282312)\n", (3110, 3201), True, 'import numpy as np\n'), ((3209, 3318), 'numpy.allclose', 'np.allclose', (["(wrapper_ala.main_info['kinetic'] + wrapper_ala.main_info['potential'])", '(0.016526506142315156)'], {}), "(wrapper_ala.main_info['kinetic'] + wrapper_ala.main_info[\n 'potential'], 0.016526506142315156)\n", (3220, 3318), True, 'import numpy as np\n'), ((3435, 3510), 'numpy.allclose', 'np.allclose', (["(state1['kinetic'] + state1['potential'])", '(-0.010557407627282312)'], {}), "(state1['kinetic'] + state1['potential'], -0.010557407627282312)\n", (3446, 3510), True, 'import numpy as np\n'), ((3522, 3596), 'numpy.allclose', 'np.allclose', (["(state2['kinetic'] + state2['potential'])", '(0.016526506142315156)'], {}), "(state2['kinetic'] + state2['potential'], 0.016526506142315156)\n", (3533, 3596), True, 'import numpy as np\n'), ((4185, 4227), 'numpy.allclose', 'np.allclose', (['energy1', '(-0.0105)'], {'atol': '(0.0001)'}), '(energy1, -0.0105, atol=0.0001)\n', (4196, 4227), True, 'import numpy as np\n'), ((4238, 4278), 'numpy.allclose', 'np.allclose', (['energy2', '(-0.009)'], {'atol': '(0.001)'}), '(energy2, -0.009, atol=0.001)\n', (4249, 4278), True, 'import numpy as np\n'), ((3710, 3735), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3718, 3735), True, 'import numpy as np\n'), ((3739, 3764), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3747, 3764), True, 'import numpy as np\n'), ((3784, 3809), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (3792, 3809), True, 'import numpy as np\n'), ((3813, 3850), 'numpy.array', 'np.array', (['[-0.0001, -0.0001, -0.0001]'], {}), '([-0.0001, -0.0001, -0.0001])\n', (3821, 3850), True, 'import numpy as np\n')]
#!/usr/bin/env python """ -------------------------------------------------------- READ_JSON_TCG reads communication game json files originating from the web version of the tcg or tcg kids INPUT Use as: data = read_json_tcg('room001225') where 'roomxxx' is a folder containing the '*.json' files OUTPUT A struct containing; info recording file, date and onset, and game type trial rows (trials) x columns (variables) label variable names event onsets and durations of task events token token positions <NAME>, 2022 -------------------------------------------------------- """ import os import datetime import glob import re import json import numpy as np class Data(object): # initialize data structure def __init__(self): # logfile, date, player 1 ID, player 2 ID, player 1 date, player 2 date self.info = [None] * 6 self.trial = [] self.label = ['TrialNr', 'TrialType', 'TrialTypeNr', 'TrialOnset', 'SenderPlayer', 'SenderPlanTime', 'SenderMovTime', 'SenderNumMoves', 'TargetNum', 'TargetTime', 'NonTargetTime', 'ReceiverPlayer', 'ReceiverPlanTime', 'ReceiverMovTime', 'ReceiverNumMoves', 'Success', 'SenderLocSuccess', 'SenderOriSuccess', 'ReceiverLocSuccess', 'ReceiverOriSuccess', 'Level', 'TrialOffset'] self.event = [] # onset timestamps of the five epochs # coord [xPos, yPos, angle], time, shape, control, action, target [xPos, yPos, angle] self.token_sender = [] self.token_receiver = [] def read_json_tcg(logfile): # recording information data = Data() data.info[0] = logfile data.info[1] = datetime.datetime.fromtimestamp( os.stat(logfile).st_mtime).strftime('%Y-%m-%d-%H:%M') # read all json files sess = ['practice', 'training', 'game'] epoch = ['roleassignment', 'tokenassignment', 'sender', 'receiver', 'feedback'] for sidx, s in enumerate(sess): data.trial.append([]) # multiple trials per session data.event.append([]) data.token_sender.append([]) data.token_receiver.append([]) # number of trials for this session list = glob.glob(logfile + os.path.sep + s + "*.json") ntrls = 0 for l in list: dig = re.findall(r'\d+', l) trl = int(dig[len(dig)-1]) if trl > ntrls: ntrls = trl # trial loop for t in range(ntrls): data.event[sidx].append([]) # multiple events/locations per trial data.token_sender[sidx].append([]) data.token_receiver[sidx].append([]) TrialOnset = np.nan TrialOffset = np.nan SenderPlayer = np.nan ReceiverPlayer = np.nan SenderPlanTime = np.nan SenderMovTime = np.nan SenderNumMoves = 0 ReceiverPlanTime = np.nan ReceiverMovTime = np.nan ReceiverNumMoves = 0 TargetNum = 0 TargetTime = [] NonTargetTime = [] ReceiverTargetPos = np.nan Success = np.nan SenderLocSuccess = np.nan SenderOriSuccess = np.nan ReceiverLocSuccess = np.nan ReceiverOriSuccess = np.nan SenderTarget = np.nan ReceiverTarget = np.nan Level = np.nan # epoch loop for eidx, e in enumerate(epoch): filename = logfile + os.path.sep + s + \ '_trial_' + str(t+1) + '_' + e + '.json' if os.path.exists(filename): # read in json structure with open(filename) as file: val = json.load(file) # trial onsets and roles if (val[0]['epoch'] == 'roleassignment' and (s == 'training' or s == 'game')) or \ (val[0]['epoch'] == 'tokenassignment' and s == 'practice'): TrialOnset = val[0]['timestamp'] if 'p1' in val[0] or 'p2' in val[0]: if 'angle' in val[0]['p1']: # tcg if 'p1' in val[0] and 'role' in val[0]['p1'] and val[0]['p1']['role'] == 'sender': SenderPlayer = 1 SenderTarget = [ val[0]['p1']['goal']['xPos'], val[0]['p1']['goal']['yPos'], val[0]['p1']['goal']['angle']] elif 'p2' in val[0] and 'role' in val[0]['p2'] and val[0]['p2']['role'] == 'sender': SenderPlayer = 2 SenderTarget = [ val[0]['p2']['goal']['xPos'], val[0]['p2']['goal']['yPos'], val[0]['p2']['goal']['angle']] if 'p1' in val[0] and 'role' in val[0]['p1'] and val[0]['p1']['role'] == 'receiver': ReceiverPlayer = 1 ReceiverTarget = [ val[0]['p1']['goal']['xPos'], val[0]['p1']['goal']['yPos'], val[0]['p1']['goal']['angle']] ReceiverTargetPos = [ val[0]['p1']['goal']['xPos'], val[0]['p1']['goal']['yPos']] elif 'p2' in val[0] and 'role' in val[0]['p2'] and val[0]['p2']['role'] == 'receiver': ReceiverPlayer = 2 ReceiverTarget = [ val[0]['p2']['goal']['xPos'], val[0]['p2']['goal']['yPos'], val[0]['p2']['goal']['angle']] ReceiverTargetPos = [ val[0]['p2']['goal']['xPos'], val[0]['p2']['goal']['yPos']] else: # tcg kids if 'p1' in val[0] and 'role' in val[0]['p1'] and val[0]['p1']['role'] == 'sender': SenderPlayer = 1 SenderTarget = [0, 0] elif 'p2' in val[0] and 'role' in val[0]['p2'] and val[0]['p2']['role'] == 'sender': SenderPlayer = 2 SenderTarget = [0, 0] if 'p1' in val[0] and 'role' in val[0]['p1'] and val[0]['p1']['role'] == 'receiver': ReceiverPlayer = 1 ReceiverTarget = val[0]['p1']['goal'] ReceiverTargetPos = val[0]['p1']['goal'] elif 'p2' in val[0] and 'role' in val[0]['p2'] and val[0]['p2']['role'] == 'receiver': ReceiverPlayer = 2 ReceiverTarget = val[0]['p2']['goal'] ReceiverTargetPos = val[0]['p2']['goal'] # player IDs (for relating to userinput) for v in val: if 'Iamplayer' in v: if v['Iamplayer'] == 1: data.info[2] = 'player 1: ' + \ v['player'] try: data.info[4] = 'date 1: ' + \ v['date'] except: print('player 1 date not found') elif v['Iamplayer'] == 2: data.info[3] = 'player 2: ' + \ v['player'] try: data.info[5] = 'date 2: ' + \ v['date'] except: print('player 2 date not found') # planning and movement times if val[0]['epoch'] == 'sender': for index, v in enumerate(val): # planning & movement time if 'action' in v: if v['action'] == 'start': SenderMovOnset = v['timestamp'] SenderPlanTime = SenderMovOnset - \ val[0]['timestamp'] # 1st timestamp is goal onset WaitForOffTarget = 0 elif v['action'] == 'stop' or v['action'] == 'timeout': SenderMovOffset = v['timestamp'] SenderMovTime = SenderMovOffset - SenderMovOnset if not TargetTime: # empty TargetTime = np.nan elif TargetTime: # not empty TargetTime = np.nanmean(TargetTime) if not NonTargetTime: # empty NonTargetTime = np.nan elif NonTargetTime: # not empty NonTargetTime = np.nanmean( NonTargetTime) elif v['action'] == 'up' or v['action'] == 'down' or \ v['action'] == 'left' or v['action'] == 'right' or \ v['action'] == 'rotateleft' or v['action'] == 'rotateright': SenderNumMoves = SenderNumMoves + 1 # tcg kids if SenderNumMoves == 1 and str(v['token']['shape']).isalpha(): SenderMovOnset = v['timestamp'] SenderPlanTime = SenderMovOnset - \ val[0]['timestamp'] # 1st timestamp is goal onset WaitForOffTarget = 0 # time spent at location if WaitForOffTarget == 1: TargetTime.append( v['timestamp'] - val[index-1]['timestamp']) WaitForOffTarget = 0 else: NonTargetTime.append( v['timestamp'] - val[index-1]['timestamp']) # on target # tcg if str(v['token']['shape']).isnumeric() and [v['token']['xPos'], v['token']['yPos']] == ReceiverTargetPos: TargetNum = TargetNum + 1 WaitForOffTarget = 1 # tcg kids elif str(v['token']['shape']).isalpha() and check_target(v['token']): TargetNum = TargetNum + 1 WaitForOffTarget = 1 # double check on target # overlooked targets if s != 'practice' and v['token']['onTarget'] and TargetNum == 0: print( 'WARNING: on target missed for ' + logfile + ', ' + s + ', trial ' + str(t)) # token coord & timestamps if 'token' in v: if 'angle' in v['token']: # tcg data.token_sender[sidx][t].append([[v['token']['xPos'], v['token']['yPos'], v['token']['angle']], v['timestamp'], v['token']['shape'], v['token']['control'], v['action'], SenderTarget]) else: # tcg kids data.token_sender[sidx][t].append([[v['token']['xPos'], v['token']['yPos']], v['timestamp'], v['token']['shape'], v['token']['control'], v['action'], SenderTarget]) elif val[0]['epoch'] == 'receiver': for index, v in enumerate(val): # planning & movement time if 'action' in v: if v['action'] == 'start': ReceiverMovOnset = v['timestamp'] ReceiverPlanTime = ReceiverMovOnset - \ val[0]['timestamp'] # 1st timestamp is goal onset elif v['action'] == 'stop' or v['action'] == 'timeout': ReceiverMovOffset = v['timestamp'] ReceiverMovTime = ReceiverMovOffset - ReceiverMovOnset elif v['action'] == 'up' or v['action'] == 'down' or \ v['action'] == 'left' or v['action'] == 'right' or \ v['action'] == 'rotateleft' or v['action'] == 'rotateright' or \ v['action'] == 'tracking': ReceiverNumMoves = ReceiverNumMoves + 1 # tcg kids if ReceiverNumMoves == 1 and str(v['token']['shape']).isalpha(): ReceiverMovOnset = v['timestamp'] ReceiverPlanTime = ReceiverMovOnset - \ val[0]['timestamp'] # 1st timestamp is goal onset # token coord & timestamps if 'token' in v: if 'angle' in v['token']: # tcg data.token_receiver[sidx][t].append([[v['token']['xPos'], v['token']['yPos'], v['token']['angle']], v['timestamp'], v['token']['shape'], v['token']['control'], v['action'], ReceiverTarget]) else: # tcg kids data.token_receiver[sidx][t].append([[v['token']['xPos'], v['token']['yPos']], v['timestamp'], v['token']['shape'], v['token']['control'], v['action'], ReceiverTarget]) # feedback, level and trial offset if val[0]['epoch'] == 'feedback': Success = val[0]['success'] if 'p1' in val[0] and 'role' in val[0]['p1'] and val[0]['p1']['role'] == 'sender': SenderLocSuccess, SenderOriSuccess = check_feedback( val[0]['p1']) elif 'p2' in val[0] and 'role' in val[0]['p2'] and val[0]['p2']['role'] == 'sender': SenderLocSuccess, SenderOriSuccess = check_feedback( val[0]['p2']) if 'p1' in val[0] and 'role' in val[0]['p1'] and val[0]['p1']['role'] == 'receiver': ReceiverLocSuccess, ReceiverOriSuccess = check_feedback( val[0]['p1']) elif 'p2' in val[0] and 'role' in val[0]['p2'] and val[0]['p2']['role'] == 'receiver': ReceiverLocSuccess, ReceiverOriSuccess = check_feedback( val[0]['p2']) if 'level' in val[0]: Level = val[0]['level'] TrialOffset = val[0]['timestamp']+1000 # event timestamps if val[0]['epoch'] == e: # register the first timestamp data.event[sidx][t].append(val[0]['timestamp']) # store in data structure data.trial[sidx].append([t+1, sidx+1, np.nan, TrialOnset, SenderPlayer, SenderPlanTime, SenderMovTime, SenderNumMoves, TargetNum, TargetTime, NonTargetTime, ReceiverPlayer, ReceiverPlanTime, ReceiverMovTime, ReceiverNumMoves, Success, SenderLocSuccess, SenderOriSuccess, ReceiverLocSuccess, ReceiverOriSuccess, Level, TrialOffset]) return data def check_feedback(p): loc, ori = 0, 0 # location if p['shape'] == 'bird' and [p['xPos'], p['yPos']] == [0, 0]: loc = 1 elif p['shape'] == 'squirrel': loc = np.nan elif [p['xPos'], p['yPos']] == [p['goal']['xPos'], p['goal']['yPos']]: loc = 1 # orientation if p['shape'] == 'bird' or p['shape'] == 'squirrel': ori = 1 elif p['shape'] == 1: # rectangle if p['angle'] == p['goal']['angle'] or abs(p['angle']-p['goal']['angle']) == 180: ori = 1 elif p['shape'] == 2: # circle if loc == 1: # angle ori = 1 elif p['shape'] == 3: # triangle if p['angle'] == p['goal']['angle']: # angle ori = 1 return loc, ori def check_target(t): # field field = [None] * 15 field[0] = [-1, 1] field[1] = [0, 1] field[2] = [0, 1] field[3] = [1, 1] field[4] = [1, 1] field[5] = [-1, 0] field[6] = [-1, 0] field[7] = [-1, 0] field[8] = [1, 0] field[9] = [-1, -1] field[10] = [0, -1] field[11] = [0, -1] field[12] = [1, -1] field[13] = [1, -1] field[14] = [1, -1] return [t['xPos'], t['yPos']] == field[t['goal']-1]
[ "json.load", "os.stat", "os.path.exists", "re.findall", "glob.glob", "numpy.nanmean" ]
[((2258, 2305), 'glob.glob', 'glob.glob', (["(logfile + os.path.sep + s + '*.json')"], {}), "(logfile + os.path.sep + s + '*.json')\n", (2267, 2305), False, 'import glob\n'), ((2365, 2386), 're.findall', 're.findall', (['"""\\\\d+"""', 'l'], {}), "('\\\\d+', l)\n", (2375, 2386), False, 'import re\n'), ((3669, 3693), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (3683, 3693), False, 'import os\n'), ((1773, 1789), 'os.stat', 'os.stat', (['logfile'], {}), '(logfile)\n', (1780, 1789), False, 'import os\n'), ((3820, 3835), 'json.load', 'json.load', (['file'], {}), '(file)\n', (3829, 3835), False, 'import json\n'), ((9612, 9634), 'numpy.nanmean', 'np.nanmean', (['TargetTime'], {}), '(TargetTime)\n', (9622, 9634), True, 'import numpy as np\n'), ((9906, 9931), 'numpy.nanmean', 'np.nanmean', (['NonTargetTime'], {}), '(NonTargetTime)\n', (9916, 9931), True, 'import numpy as np\n')]
from pyreeEngine.node import RenderNode, BaseNode, signalInput, signalOutput, execOut, execIn from pyreeEngine.basicObjects import ModelObject, FSQuad from pyreeEngine.engine import PerspectiveCamera, OrthoCamera, HotloadingShader, Camera from pyreeEngine.textures import TextureFromImage, RandomRGBATexture import math import time import numpy as np import quaternion from OpenGL.GL import * from OpenGL.GL import shaders from pathlib import Path from viddecoder.vidtexture import VideoTexture import mido import random from pyutil.img import imgAnim from pyutil.clk import Clkdiv from pyreeEngine.objloader import ObjLoader from pyutil.filter import PT1 class DuckGen(): duckvertlist = ObjLoader(Path("res/couch/duck.obj")).verts verts = [] for l in duckvertlist: verts += l @staticmethod def newDuckModel(): newModel = ModelObject() newModel.loadFromVerts(DuckGen.verts) return newModel class DuckCarpet: def __init__(self): self.width = 4 self.height = 4 self.spacing = 1 self.scale = np.array([0.1, 0.1, 0.1])*0.5 self.duckTex = TextureFromImage(Path("res/couch/duck.png")) self.duckShader = HotloadingShader(Path("res/couch/duck_vert.glsl"), Path("res/couch/duck_frag.glsl")) self.duckcontainer = [] self.renderlist = None self.genDucks() def randomizeRot(self): pass def changeDuckCount(self, width, height): self.width = width self.height = height self.genDucks() def genDucks(self): self.duckContainer = [] for w in range(self.width * 2 + 1): newcont = [] self.duckcontainer.append(newcont) for h in range(self.height * 2 + 1): x, y = w - self.width, h - self.height newDuck = DuckGen.newDuckModel() newDuck.textures = [self.duckTex.getTexture()] newDuck.scale = self.scale newDuck.uniforms["indx"] = [x, y] newDuck.shaderProgram = self.duckShader.getShaderProgram() newcont.append(newDuck) newDuck.pos = np.array([x * self.spacing, 0, y * self.spacing], np.float32) self.renderlist = [] for l in self.duckcontainer: self.renderlist += l def getRenderList(self): return self.renderlist def tick(self, globdata): self.duckShader.tick() for duck in self.renderlist: duck.uniforms["time"] = globdata.time duck.shaderProgram = self.duckShader.getShaderProgram() class Couch(RenderNode): def __init__(self, globdata): super(Couch, self).__init__(globdata) self.camera = None # type: PerspectiveCamera self.duckCarpet = None self.floorQuad = None self.floorShader = None self.pt1 = PT1(0.1) self.beatAccum = 0 self.beatPT1 = PT1(0.3) self.jerkPT1 = PT1(0.3) self.snareAccum = 0 self.snarePT1 = PT1(0.5) self.scaleDiv = Clkdiv() def init(self): if self.camera is None: self.camera = PerspectiveCamera() self.camera.setPerspective(50, self.globalData.resolution[0] / self.globalData.resolution[1], 0.1, 100.) if self.duckCarpet is None: self.duckCarpet = DuckCarpet() if self.floorQuad is None: self.floorQuad = FSQuad() self.floorQuad.rot = quaternion.from_euler_angles([math.pi/2, math.pi/2, 0]) self.floorQuad.scale = np.array([1, 1, 1])*10 if self.floorShader is None: self.floorShader = HotloadingShader(Path("res/couch/floor_vert.glsl"), Path("res/couch/floor_frag.glsl")) self.floorQuad.shaderProgram = self.floorShader.getShaderProgram() #self.midiIn = mido.open_input("Scarlett 2i4 USB:Scarlett 2i4 USB MIDI 1 16:0") def getData(self): return { "duckCarpet": self.duckCarpet } def setData(self, data): pass#self.duckCarpet = data["duckCarpet"] @execIn("run") def run(self): """for msg in self.midiIn.iter_pending(): if msg.type == "note_on": print(msg.note) if(msg.note == 36): self.duckModel.rot = quaternion.from_euler_angles(random.random()*360, random.random()*360, random.random()*360) s = self.pt1.set = random.random()*0.1 + 0.05""" self.register() self.duckCarpet.tick(self.globalData) self.floorQuad.uniforms["time"] = self.globalData.time self.floorShader.tick() self.floorQuad.shaderProgram = self.floorShader.getShaderProgram() if self.globalData.resChanged: self.camera.setPerspective(50, self.globalData.resolution[0]/self.globalData.resolution[1], 0.1, 10.) ## Uniforms if self.globalData.beat[0]: self.beatAccum += 1 self.beatPT1.set = self.beatAccum self.jerkPT1.cur = 1 self.rand1 = random.random() self.rand2 = random.random() self.rand3 = random.random() if self.globalData.beat[1]: self.snareAccum += 1 self.snarePT1.set = self.snareAccum self.beatPT1.tick(self.globalData.dt) self.jerkPT1.tick(self.globalData.dt) self.snarePT1.tick(self.globalData.dt) for duck in self.duckCarpet.renderlist: duck.uniforms["beat"] = self.beatPT1.cur duck.uniforms["jerk"] = self.jerkPT1.cur duck.uniforms["snare"] = self.snarePT1.cur duck.rot *= quaternion.from_euler_angles(np.array([random.random(), random.random(), random.random()] - np.ones(3)*0.5)*0.1) duck.scale += np.array([random.random(), random.random(), random.random()] - np.ones(3)*0.5)*0.0001 duck.pos += np.array([random.random(), random.random(), random.random()] - np.ones(3)*0.5)*0.0001 if self.scaleDiv.tick(100): for duck in self.duckCarpet.renderlist: duck.scale = np.array([0.1, 0.1, 0.1]) * random.random() ## orbitradius = 3 orbitspeed = 0.05 orbphase = self.globalData.time*orbitspeed*math.pi*2. #orbphase = math.pi*0.5 self.camera.lookAt(np.array([math.cos(orbphase*1)*orbitradius, 2., math.sin(orbphase)*orbitradius]), np.array([0., 0.5 , 0.]), np.array([0., 1., 0.])) glClear(GL_COLOR_BUFFER_BIT) glClear(GL_DEPTH_BUFFER_BIT) #glBindFramebuffer(GL_FRAMEBUFFER, 0) glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDisable(GL_BLEND) self.render([self.floorQuad] + self.duckCarpet.getRenderList(), self.camera, None) __nodeclasses__ = [Couch]
[ "pyreeEngine.basicObjects.ModelObject", "numpy.ones", "pyreeEngine.engine.PerspectiveCamera", "pyutil.clk.Clkdiv", "pyutil.filter.PT1", "random.random", "pathlib.Path", "pyreeEngine.basicObjects.FSQuad", "numpy.array", "math.cos", "math.sin", "quaternion.from_euler_angles", "pyreeEngine.node...
[((4125, 4138), 'pyreeEngine.node.execIn', 'execIn', (['"""run"""'], {}), "('run')\n", (4131, 4138), False, 'from pyreeEngine.node import RenderNode, BaseNode, signalInput, signalOutput, execOut, execIn\n'), ((872, 885), 'pyreeEngine.basicObjects.ModelObject', 'ModelObject', ([], {}), '()\n', (883, 885), False, 'from pyreeEngine.basicObjects import ModelObject, FSQuad\n'), ((2907, 2915), 'pyutil.filter.PT1', 'PT1', (['(0.1)'], {}), '(0.1)\n', (2910, 2915), False, 'from pyutil.filter import PT1\n'), ((2967, 2975), 'pyutil.filter.PT1', 'PT1', (['(0.3)'], {}), '(0.3)\n', (2970, 2975), False, 'from pyutil.filter import PT1\n'), ((2999, 3007), 'pyutil.filter.PT1', 'PT1', (['(0.3)'], {}), '(0.3)\n', (3002, 3007), False, 'from pyutil.filter import PT1\n'), ((3061, 3069), 'pyutil.filter.PT1', 'PT1', (['(0.5)'], {}), '(0.5)\n', (3064, 3069), False, 'from pyutil.filter import PT1\n'), ((3095, 3103), 'pyutil.clk.Clkdiv', 'Clkdiv', ([], {}), '()\n', (3101, 3103), False, 'from pyutil.clk import Clkdiv\n'), ((715, 741), 'pathlib.Path', 'Path', (['"""res/couch/duck.obj"""'], {}), "('res/couch/duck.obj')\n", (719, 741), False, 'from pathlib import Path\n'), ((1094, 1119), 'numpy.array', 'np.array', (['[0.1, 0.1, 0.1]'], {}), '([0.1, 0.1, 0.1])\n', (1102, 1119), True, 'import numpy as np\n'), ((1165, 1191), 'pathlib.Path', 'Path', (['"""res/couch/duck.png"""'], {}), "('res/couch/duck.png')\n", (1169, 1191), False, 'from pathlib import Path\n'), ((1236, 1268), 'pathlib.Path', 'Path', (['"""res/couch/duck_vert.glsl"""'], {}), "('res/couch/duck_vert.glsl')\n", (1240, 1268), False, 'from pathlib import Path\n'), ((1270, 1302), 'pathlib.Path', 'Path', (['"""res/couch/duck_frag.glsl"""'], {}), "('res/couch/duck_frag.glsl')\n", (1274, 1302), False, 'from pathlib import Path\n'), ((3183, 3202), 'pyreeEngine.engine.PerspectiveCamera', 'PerspectiveCamera', ([], {}), '()\n', (3200, 3202), False, 'from pyreeEngine.engine import PerspectiveCamera, OrthoCamera, HotloadingShader, Camera\n'), ((3465, 3473), 'pyreeEngine.basicObjects.FSQuad', 'FSQuad', ([], {}), '()\n', (3471, 3473), False, 'from pyreeEngine.basicObjects import ModelObject, FSQuad\n'), ((3507, 3566), 'quaternion.from_euler_angles', 'quaternion.from_euler_angles', (['[math.pi / 2, math.pi / 2, 0]'], {}), '([math.pi / 2, math.pi / 2, 0])\n', (3535, 3566), False, 'import quaternion\n'), ((5107, 5122), 'random.random', 'random.random', ([], {}), '()\n', (5120, 5122), False, 'import random\n'), ((5148, 5163), 'random.random', 'random.random', ([], {}), '()\n', (5161, 5163), False, 'import random\n'), ((5189, 5204), 'random.random', 'random.random', ([], {}), '()\n', (5202, 5204), False, 'import random\n'), ((6464, 6489), 'numpy.array', 'np.array', (['[0.0, 0.5, 0.0]'], {}), '([0.0, 0.5, 0.0])\n', (6472, 6489), True, 'import numpy as np\n'), ((6490, 6515), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (6498, 6515), True, 'import numpy as np\n'), ((2190, 2251), 'numpy.array', 'np.array', (['[x * self.spacing, 0, y * self.spacing]', 'np.float32'], {}), '([x * self.spacing, 0, y * self.spacing], np.float32)\n', (2198, 2251), True, 'import numpy as np\n'), ((3598, 3617), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (3606, 3617), True, 'import numpy as np\n'), ((3706, 3739), 'pathlib.Path', 'Path', (['"""res/couch/floor_vert.glsl"""'], {}), "('res/couch/floor_vert.glsl')\n", (3710, 3739), False, 'from pathlib import Path\n'), ((3741, 3774), 'pathlib.Path', 'Path', (['"""res/couch/floor_frag.glsl"""'], {}), "('res/couch/floor_frag.glsl')\n", (3745, 3774), False, 'from pathlib import Path\n'), ((6152, 6177), 'numpy.array', 'np.array', (['[0.1, 0.1, 0.1]'], {}), '([0.1, 0.1, 0.1])\n', (6160, 6177), True, 'import numpy as np\n'), ((6180, 6195), 'random.random', 'random.random', ([], {}), '()\n', (6193, 6195), False, 'import random\n'), ((6392, 6414), 'math.cos', 'math.cos', (['(orbphase * 1)'], {}), '(orbphase * 1)\n', (6400, 6414), False, 'import math\n'), ((6430, 6448), 'math.sin', 'math.sin', (['orbphase'], {}), '(orbphase)\n', (6438, 6448), False, 'import math\n'), ((5848, 5863), 'random.random', 'random.random', ([], {}), '()\n', (5861, 5863), False, 'import random\n'), ((5865, 5880), 'random.random', 'random.random', ([], {}), '()\n', (5878, 5880), False, 'import random\n'), ((5882, 5897), 'random.random', 'random.random', ([], {}), '()\n', (5895, 5897), False, 'import random\n'), ((5901, 5911), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (5908, 5911), True, 'import numpy as np\n'), ((5958, 5973), 'random.random', 'random.random', ([], {}), '()\n', (5971, 5973), False, 'import random\n'), ((5975, 5990), 'random.random', 'random.random', ([], {}), '()\n', (5988, 5990), False, 'import random\n'), ((5992, 6007), 'random.random', 'random.random', ([], {}), '()\n', (6005, 6007), False, 'import random\n'), ((6011, 6021), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (6018, 6021), True, 'import numpy as np\n'), ((5738, 5753), 'random.random', 'random.random', ([], {}), '()\n', (5751, 5753), False, 'import random\n'), ((5755, 5770), 'random.random', 'random.random', ([], {}), '()\n', (5768, 5770), False, 'import random\n'), ((5772, 5787), 'random.random', 'random.random', ([], {}), '()\n', (5785, 5787), False, 'import random\n'), ((5791, 5801), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (5798, 5801), True, 'import numpy as np\n')]
import click import sys import os import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from zipfile import ZipFile def extract_data(path="../data", zip_name="titanic.zip", data_name="train.csv"): """Extract dataset. Parameters: path (str): Path to extract dataset without ending with slash zip_name (str): Name of the zip file to extract data_name (str): Name of one of the csv file to extract """ if not os.path.exists(f"{path}/{data_name}"): ZipFile(f"{path}/{zip_name}", mode='r').extractall(path=path, members=None, pwd=None) def preprocess_data(train_set): """Preprocess dataset.\n It will normalise numeric values and transorm to float non numeric values Parameters: train_set (pd.dataframe): pandas datafram containing all the data """ train_set.loc[0:len(train_set) - 1, 'Pclass':'Pclass'] = [np.nanmean(train_set["Pclass"].values) if np.isnan(value) else value - 2 for value in train_set["Pclass"].values] train_set.loc[0:len(train_set) - 1, 'Sex':'Sex'] = [1 if value == "female" else -1 for value in train_set["Sex"].values] train_set.loc[0:len(train_set) - 1, 'Age':'Age'] = [np.nanmean(train_set["Age"].values) if np.isnan(value) else value / 10 for value in train_set["Age"].values] train_set.loc[0:len(train_set) - 1, 'Fare':'Fare'] = [np.nanmean(train_set["Fare"].values) if np.isnan(value) else value / 10 for value in train_set["Fare"].values] train_set.loc[0:len(train_set) - 1, 'Embarked':'Embarked'] = [-1 if value == 'Q' else 0 if value == 'S' else 1 for value in train_set["Embarked"].values] return train_set def create_data_viz(train_set): """Create data viz plot.\n Compare Surviving rate between men and women Parameters: train_set (pd.dataframe): pandas datafram containing all the data """ f, axes = plt.subplots(1, 3) axes[0].set_xlabel('Surviving rate of women') axes[1].set_xlabel('Global surviving rate') axes[2].set_xlabel('Surviving rate of men') sns.barplot(data=train_set[train_set['Sex'] == -1]['Survived'].values, estimator=lambda x: sum(x==0)*100.0/len(x), ax=axes[0], color="r").set(ylim=(0, 100)) sns.barplot(data=train_set['Survived'].values, estimator=lambda x: sum(x==0)*100.0/len(x), ax=axes[1], color="g").set(ylim=(0, 100)) sns.barplot(data=train_set[train_set['Sex'] == 1]['Survived'].values, estimator=lambda x: sum(x==0)*100.0/len(x), ax=axes[2], color="b").set(ylim=(0, 100)) if not os.path.exists("artifacts"): os.mkdir("artifacts") plt.savefig("artifacts/plot.png") @click.command( help="Given the titanic zip file (see dataset_folder and zip_name), exctract it" ", preprocess it and save it as npy file" ) @click.option("--dataset-folder", default="../data", type=str) @click.option("--zip-name", default="titanic.csv", type=str) @click.option("--data-name", default="train.csv", type=str) def preprocess(dataset_folder, zip_name, data_name): extract_data(path=dataset_folder, zip_name=zip_name, data_name=data_name) train_set = pd.read_csv(f"{dataset_folder}/{data_name}", low_memory=False).drop(["PassengerId", "Name", "Ticket", "Cabin"], axis=1) train_set = preprocess_data(train_set) create_data_viz(train_set) train_labels = train_set['Survived'] train_set = train_set.drop('Survived', axis=1) np.save("../data/train_set.npy", train_set) np.save("../data/train_labels.npy", train_labels) if __name__ == "__main__": preprocess()
[ "os.mkdir", "numpy.save", "zipfile.ZipFile", "pandas.read_csv", "click.option", "os.path.exists", "numpy.isnan", "click.command", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.nanmean" ]
[((2663, 2807), 'click.command', 'click.command', ([], {'help': '"""Given the titanic zip file (see dataset_folder and zip_name), exctract it, preprocess it and save it as npy file"""'}), "(help=\n 'Given the titanic zip file (see dataset_folder and zip_name), exctract it, preprocess it and save it as npy file'\n )\n", (2676, 2807), False, 'import click\n'), ((2812, 2873), 'click.option', 'click.option', (['"""--dataset-folder"""'], {'default': '"""../data"""', 'type': 'str'}), "('--dataset-folder', default='../data', type=str)\n", (2824, 2873), False, 'import click\n'), ((2875, 2934), 'click.option', 'click.option', (['"""--zip-name"""'], {'default': '"""titanic.csv"""', 'type': 'str'}), "('--zip-name', default='titanic.csv', type=str)\n", (2887, 2934), False, 'import click\n'), ((2936, 2994), 'click.option', 'click.option', (['"""--data-name"""'], {'default': '"""train.csv"""', 'type': 'str'}), "('--data-name', default='train.csv', type=str)\n", (2948, 2994), False, 'import click\n'), ((1935, 1953), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {}), '(1, 3)\n', (1947, 1953), True, 'import matplotlib.pyplot as plt\n'), ((2627, 2660), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""artifacts/plot.png"""'], {}), "('artifacts/plot.png')\n", (2638, 2660), True, 'import matplotlib.pyplot as plt\n'), ((3436, 3479), 'numpy.save', 'np.save', (['"""../data/train_set.npy"""', 'train_set'], {}), "('../data/train_set.npy', train_set)\n", (3443, 3479), True, 'import numpy as np\n'), ((3484, 3533), 'numpy.save', 'np.save', (['"""../data/train_labels.npy"""', 'train_labels'], {}), "('../data/train_labels.npy', train_labels)\n", (3491, 3533), True, 'import numpy as np\n'), ((505, 542), 'os.path.exists', 'os.path.exists', (['f"""{path}/{data_name}"""'], {}), "(f'{path}/{data_name}')\n", (519, 542), False, 'import os\n'), ((2572, 2599), 'os.path.exists', 'os.path.exists', (['"""artifacts"""'], {}), "('artifacts')\n", (2586, 2599), False, 'import os\n'), ((2601, 2622), 'os.mkdir', 'os.mkdir', (['"""artifacts"""'], {}), "('artifacts')\n", (2609, 2622), False, 'import os\n'), ((990, 1005), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (998, 1005), True, 'import numpy as np\n'), ((948, 986), 'numpy.nanmean', 'np.nanmean', (["train_set['Pclass'].values"], {}), "(train_set['Pclass'].values)\n", (958, 986), True, 'import numpy as np\n'), ((1282, 1297), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (1290, 1297), True, 'import numpy as np\n'), ((1243, 1278), 'numpy.nanmean', 'np.nanmean', (["train_set['Age'].values"], {}), "(train_set['Age'].values)\n", (1253, 1278), True, 'import numpy as np\n'), ((1450, 1465), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (1458, 1465), True, 'import numpy as np\n'), ((1410, 1446), 'numpy.nanmean', 'np.nanmean', (["train_set['Fare'].values"], {}), "(train_set['Fare'].values)\n", (1420, 1446), True, 'import numpy as np\n'), ((3143, 3205), 'pandas.read_csv', 'pd.read_csv', (['f"""{dataset_folder}/{data_name}"""'], {'low_memory': '(False)'}), "(f'{dataset_folder}/{data_name}', low_memory=False)\n", (3154, 3205), True, 'import pandas as pd\n'), ((552, 591), 'zipfile.ZipFile', 'ZipFile', (['f"""{path}/{zip_name}"""'], {'mode': '"""r"""'}), "(f'{path}/{zip_name}', mode='r')\n", (559, 591), False, 'from zipfile import ZipFile\n')]
# Copyright 2016 Hewlett Packard Enterprise Development LP # # 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. import unittest import numpy as np from ..operator import operator, evaluate from ..expression import output_like, position_in, minimum, maximum, power, arctan2, logical_and, logical_or from ..local import cuda_enabled, clear_op_cache def gen(input0, input1, ops_func, np_func): @operator() def binary_math(op_input0, op_input1): output = output_like(op_input0) pos = position_in(op_input0.shape) output[pos] = ops_func(op_input0[pos], op_input1[pos]) return output op = binary_math(input0, input1) op_c = evaluate(op, target_language='cpp') assert np.allclose(op_c, np_func(input0, input1)) if cuda_enabled: op_cuda = evaluate(op, target_language='cuda') assert np.allclose(op_cuda, np_func(input0, input1)) class TestBinary(unittest.TestCase): clear_op_cache() def test_binary(self): self.binary_math(np.float32) self.binary_math(np.float64) self.binary_math(np.int8) self.binary_math(np.int16) self.binary_math(np.int32) self.binary_math(np.int64) self.binary_math(np.uint8) self.binary_math(np.uint16) self.binary_math(np.uint32) self.binary_math(np.uint64) test_binary.regression = 1 def binary_math(self, dtype): length = 10 rng = np.random.RandomState(1) def cast(arg): uints = [np.uint8, np.uint16, np.uint32, np.uint64] if dtype in uints: return np.abs(arg).astype(dtype) else: return arg.astype(dtype) x = cast(rng.uniform(-10, 10, length)) y = cast(rng.uniform(-10, 10, length)) y_nonzero = y + np.equal(y, 0) x_binary = cast(rng.uniform(0, 1, length) > 0.5) y_binary = cast(rng.uniform(0, 1, length) > 0.5) gen(x, y, lambda a, b: a + b, lambda a, b: a + b) gen(x, y, lambda a, b: a - b, lambda a, b: a - b) gen(x, y, lambda a, b: a * b, lambda a, b: a * b) # use c style integer division (round towards 0) instead of python style (round towards negative infinity) def truncated_division(a, b): ints = [np.int8, np.int16, np.int32, np.int64] if b.dtype in ints: return np.trunc(np.true_divide(a, b)).astype(b.dtype) else: return np.true_divide(a, b).astype(b.dtype) gen(x, y_nonzero, lambda a, b: a / b, truncated_division) def truncated_mod(a, b): return a-b*np.trunc(np.true_divide(a, b)).astype(b.dtype) gen(x, y_nonzero, lambda a, b: a % b, truncated_mod) gen(x_binary, y_binary, lambda a, b: a == b, lambda a, b: np.equal(a, b)) gen(x_binary, y_binary, lambda a, b: a != b, lambda a, b: np.not_equal(a, b)) gen(x_binary, y_binary, lambda a, b: logical_or(a, b), lambda a, b: np.logical_or(a, b)) gen(x_binary, y_binary, lambda a, b: logical_and(a, b), lambda a, b: np.logical_and(a, b)) gen(x, y, lambda a, b: a < b, lambda a, b: np.less(a, b)) gen(x, y, lambda a, b: a <= b, lambda a, b: np.less_equal(a, b)) gen(x, y, lambda a, b: a > b, lambda a, b: np.greater(a, b)) gen(x, y, lambda a, b: a >= b, lambda a, b: np.greater_equal(a, b)) gen(x, y, lambda a, b: minimum(a, b), lambda a, b: np.minimum(a, b)) gen(x, y, lambda a, b: maximum(a, b), lambda a, b: np.maximum(a, b)) fp = [np.float32, np.float64] if dtype in fp: gen(np.abs(x), y, lambda a, b: power(a, b), lambda a, b: np.power(a, b)) gen(x, y, lambda a, b: arctan2(a, b), lambda a, b: np.arctan2(a, b))
[ "numpy.less_equal", "numpy.minimum", "numpy.maximum", "numpy.abs", "numpy.logical_and", "numpy.arctan2", "numpy.true_divide", "numpy.power", "numpy.greater", "numpy.random.RandomState", "numpy.not_equal", "numpy.equal", "numpy.logical_or", "numpy.less", "numpy.greater_equal" ]
[((1928, 1952), 'numpy.random.RandomState', 'np.random.RandomState', (['(1)'], {}), '(1)\n', (1949, 1952), True, 'import numpy as np\n'), ((2299, 2313), 'numpy.equal', 'np.equal', (['y', '(0)'], {}), '(y, 0)\n', (2307, 2313), True, 'import numpy as np\n'), ((3295, 3309), 'numpy.equal', 'np.equal', (['a', 'b'], {}), '(a, b)\n', (3303, 3309), True, 'import numpy as np\n'), ((3377, 3395), 'numpy.not_equal', 'np.not_equal', (['a', 'b'], {}), '(a, b)\n', (3389, 3395), True, 'import numpy as np\n'), ((3473, 3492), 'numpy.logical_or', 'np.logical_or', (['a', 'b'], {}), '(a, b)\n', (3486, 3492), True, 'import numpy as np\n'), ((3571, 3591), 'numpy.logical_and', 'np.logical_and', (['a', 'b'], {}), '(a, b)\n', (3585, 3591), True, 'import numpy as np\n'), ((3644, 3657), 'numpy.less', 'np.less', (['a', 'b'], {}), '(a, b)\n', (3651, 3657), True, 'import numpy as np\n'), ((3711, 3730), 'numpy.less_equal', 'np.less_equal', (['a', 'b'], {}), '(a, b)\n', (3724, 3730), True, 'import numpy as np\n'), ((3783, 3799), 'numpy.greater', 'np.greater', (['a', 'b'], {}), '(a, b)\n', (3793, 3799), True, 'import numpy as np\n'), ((3853, 3875), 'numpy.greater_equal', 'np.greater_equal', (['a', 'b'], {}), '(a, b)\n', (3869, 3875), True, 'import numpy as np\n'), ((3936, 3952), 'numpy.minimum', 'np.minimum', (['a', 'b'], {}), '(a, b)\n', (3946, 3952), True, 'import numpy as np\n'), ((4013, 4029), 'numpy.maximum', 'np.maximum', (['a', 'b'], {}), '(a, b)\n', (4023, 4029), True, 'import numpy as np\n'), ((4110, 4119), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (4116, 4119), True, 'import numpy as np\n'), ((4163, 4177), 'numpy.power', 'np.power', (['a', 'b'], {}), '(a, b)\n', (4171, 4177), True, 'import numpy as np\n'), ((4242, 4258), 'numpy.arctan2', 'np.arctan2', (['a', 'b'], {}), '(a, b)\n', (4252, 4258), True, 'import numpy as np\n'), ((2095, 2106), 'numpy.abs', 'np.abs', (['arg'], {}), '(arg)\n', (2101, 2106), True, 'import numpy as np\n'), ((2960, 2980), 'numpy.true_divide', 'np.true_divide', (['a', 'b'], {}), '(a, b)\n', (2974, 2980), True, 'import numpy as np\n'), ((2881, 2901), 'numpy.true_divide', 'np.true_divide', (['a', 'b'], {}), '(a, b)\n', (2895, 2901), True, 'import numpy as np\n'), ((3129, 3149), 'numpy.true_divide', 'np.true_divide', (['a', 'b'], {}), '(a, b)\n', (3143, 3149), True, 'import numpy as np\n')]
import numpy as np # ndarry.shape # 这一数组属性返回一个包含数组维度的元组,它也可以用于调整数组大小 # example 1 a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.shape) # example 2 # 调整数组大小 a = np.array([[1, 2, 3], [4, 5, 6]]) a.shape = (6, 1) print(a) # example 3 # Numpy也提供了reshape函数来调整数组大小 a = np.array([[1, 2, 3], [4, 5, 6]]) b = a.reshape(3, 2) print(b) # ndarry.ndim # 返回数组的维度 # example 1 # 等间隔数组的数组 a = np.arange(24) print(a) # example 2 # 以为数组 a = np.arange(24) print('OK!') print(a.ndim) # 调整大小 b = a.reshape(2, 4, 3) print(b, '\n', b.ndim) # numpy.itemsize # example 1 # 这一数组属性返回数组中每个元素的字节单位长度 # 数组dtype为int8(一个字节) x = np.array([1, 2, 3, 4, 5], dtype=np.int8) y = np.array([[1, 2], [3, 4]], dtype=np.int16) print(x.itemsize, y.itemsize) # numpy.flags # ndarray对象拥有以下属性, 这个函数返回了他们的当前值 # 1. C_CONTIGUOUS (C) 数组位于单一的, C风格的连续区段内 # 2. F_ConTIGUOUS (F) 数组位于单一的, Fortran风格的连续区段内 # 3. OWNDATA (O) 数组的内存从其他对象处借用 # 4. WRITEABLE (W) 数据区域可写入, 将它设置为false会 # 锁定数据, 使其制度 # 5. ALIGNED (A) 数据和任何元素会为硬件适当对齐 # 6. UPDATEIFCOPY (U) 这个数组时另一个数组的副本. # 当这个数组释放时, 源数组会由这个数组中的元素更新 # example import numpy as np x = np.array([1, 2, 3, 4, 5]) print(x.flags)
[ "numpy.array", "numpy.arange" ]
[((87, 119), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (95, 119), True, 'import numpy as np\n'), ((161, 193), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (169, 193), True, 'import numpy as np\n'), ((265, 297), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (273, 297), True, 'import numpy as np\n'), ((380, 393), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (389, 393), True, 'import numpy as np\n'), ((427, 440), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (436, 440), True, 'import numpy as np\n'), ((601, 641), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {'dtype': 'np.int8'}), '([1, 2, 3, 4, 5], dtype=np.int8)\n', (609, 641), True, 'import numpy as np\n'), ((646, 688), 'numpy.array', 'np.array', (['[[1, 2], [3, 4]]'], {'dtype': 'np.int16'}), '([[1, 2], [3, 4]], dtype=np.int16)\n', (654, 688), True, 'import numpy as np\n'), ((1082, 1107), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (1090, 1107), True, 'import numpy as np\n')]
__doc__ = """Iterative medoid clustering. Usage: >>> cluster_iterator = cluster(matrix, labels=contignames) >>> clusters = dict(cluster_iterator) Implements one core function, cluster, along with the helper functions write_clusters and read_clusters. For all functions in this module, a collection of clusters are represented as a {clustername, set(elements)} dict. """ import sys as _sys import os as _os import random as _random import numpy as _np import torch as _torch from collections import defaultdict as _defaultdict, deque as _deque from math import ceil as _ceil import vamb.vambtools as _vambtools _DELTA_X = 0.005 _XMAX = 0.3 # This is the PDF of normal with µ=0, s=0.01 from -0.075 to 0.075 with intervals # of DELTA_X, for a total of 31 values. We multiply by _DELTA_X so the density # of one point sums to approximately one _NORMALPDF = _DELTA_X * _torch.Tensor( [2.43432053e-11, 9.13472041e-10, 2.66955661e-08, 6.07588285e-07, 1.07697600e-05, 1.48671951e-04, 1.59837411e-03, 1.33830226e-02, 8.72682695e-02, 4.43184841e-01, 1.75283005e+00, 5.39909665e+00, 1.29517596e+01, 2.41970725e+01, 3.52065327e+01, 3.98942280e+01, 3.52065327e+01, 2.41970725e+01, 1.29517596e+01, 5.39909665e+00, 1.75283005e+00, 4.43184841e-01, 8.72682695e-02, 1.33830226e-02, 1.59837411e-03, 1.48671951e-04, 1.07697600e-05, 6.07588285e-07, 2.66955661e-08, 9.13472041e-10, 2.43432053e-11]) # Distance within which to search for medoid point _MEDOID_RADIUS = 0.05 def _calc_densities(histogram, cuda, pdf=_NORMALPDF): """Given an array of histogram, smoothes the histogram.""" pdf_len = len(pdf) if cuda: histogram = histogram.cpu() densities = _torch.zeros(len(histogram) + pdf_len - 1) for i in range(len(densities) - pdf_len + 1): densities[i:i+pdf_len] += pdf * histogram[i] densities = densities[15:-15] return densities def _find_threshold(histogram, peak_valley_ratio, default, cuda): """Find a threshold distance, where where is a dip in point density that separates an initial peak in densities from the larger bulk around 0.5. Returns (threshold, success), where succes is False if no threshold could be found, True if a good threshold could be found, and None if the point is alone, or the default threshold has been used. """ peak_density = 0 peak_over = False minimum_x = None density_at_minimum = None threshold = None success = False delta_x = _XMAX / len(histogram) # If the point is a loner, immediately return a threshold in where only # that point is contained. if histogram[:6].sum().item() == 0: return 0.025, None densities = _calc_densities(histogram, cuda) # Else we analyze the point densities to find the valley x = 0 for density in densities: # Define the first "peak" in point density. That's simply the max until # the peak is defined as being over. if not peak_over and density > peak_density: # Do not accept first peak to be after x = 0.1 if x > 0.1: break peak_density = density # Peak is over when density drops below 60% of peak density if not peak_over and density < 0.6 * peak_density: peak_over = True density_at_minimum = density # If another peak is detected, we stop if peak_over and density > 1.5 * density_at_minimum: break # Now find the minimum after the peak if peak_over and density < density_at_minimum: minimum_x, density_at_minimum = x, density # If this minimum is below ratio * peak, it's accepted as threshold if density < peak_valley_ratio * peak_density: threshold = minimum_x success = True x += delta_x # Don't allow a threshold too high - this is relaxed with p_v_ratio if threshold is not None and threshold > 0.14 + 0.1 * peak_valley_ratio: threshold = None success = False # If ratio has been set to 0.6, we do not accept returning no threshold. if threshold is None and peak_valley_ratio > 0.55: threshold = default success = None return threshold, success def _smaller_indices(tensor, kept_mask, threshold, cuda): """Get all indices where the tensor is smaller than the threshold. Uses Numpy because Torch is slow - See https://github.com/pytorch/pytorch/pull/15190""" # If it's on GPU, we remove the already clustered points at this step. if cuda: return _torch.nonzero((tensor <= threshold) & kept_mask).flatten() else: arr = tensor.numpy() indices = (arr <= threshold).nonzero()[0] torch_indices = _torch.from_numpy(indices) return torch_indices def _normalize(matrix, inplace=False): """Preprocess the matrix to make distance calculations faster. The distance functions in this module assumes input has been normalized and will not work otherwise. """ if isinstance(matrix, _np.ndarray): matrix = _torch.from_numpy(matrix) if not inplace: matrix = matrix.clone() # If any rows are kept all zeros, the distance function will return 0.5 to all points # inclusive itself, which can break the code in this module zeromask = matrix.sum(dim=1) == 0 matrix[zeromask] = 1/matrix.shape[1] matrix /= (matrix.norm(dim=1).reshape(-1, 1) * (2 ** 0.5)) return matrix def _calc_distances(matrix, index): "Return vector of cosine distances from rows of normalized matrix to given row." dists = 0.5 - matrix.matmul(matrix[index]) dists[index] = 0.0 # avoid float rounding errors return dists def _sample_medoid(matrix, kept_mask, medoid, threshold, cuda): """Returns: - A vector of indices to points within threshold - A vector of distances to all points - The mean distance from medoid to the other points in the first vector """ distances = _calc_distances(matrix, medoid) cluster = _smaller_indices(distances, kept_mask, threshold, cuda) if len(cluster) == 1: average_distance = 0.0 else: average_distance = distances[cluster].sum().item() / (len(cluster) - 1) return cluster, distances, average_distance def _wander_medoid(matrix, kept_mask, medoid, max_attempts, rng, cuda): """Keeps sampling new points within the cluster until it has sampled max_attempts without getting a new set of cluster with lower average distance""" futile_attempts = 0 tried = {medoid} # keep track of already-tried medoids cluster, distances, average_distance = _sample_medoid(matrix, kept_mask, medoid, _MEDOID_RADIUS, cuda) while len(cluster) - len(tried) > 0 and futile_attempts < max_attempts: sampled_medoid = rng.choice(cluster).item() # Prevent sampling same medoid multiple times. while sampled_medoid in tried: sampled_medoid = rng.choice(cluster).item() tried.add(sampled_medoid) sampling = _sample_medoid(matrix, kept_mask, sampled_medoid, _MEDOID_RADIUS, cuda) sample_cluster, sample_distances, sample_avg = sampling # If the mean distance of inner points of the sample is lower, # we move the medoid and reset the futile_attempts count if sample_avg < average_distance: medoid = sampled_medoid cluster = sample_cluster average_distance = sample_avg futile_attempts = 0 tried = {medoid} distances = sample_distances else: futile_attempts += 1 return medoid, distances def _findcluster(matrix, kept_mask, histogram, seed, peak_valley_ratio, max_steps, minsuccesses, default, rng, attempts, cuda): """Finds a cluster to output.""" threshold = None successes = sum(attempts) while threshold is None: # If on GPU, we need to take next seed which has not already been clusted out. # if not, clustered points have been removed, so we can just take next seed if cuda: seed = (seed + 1) % len(matrix) while kept_mask[seed] == False: seed = (seed + 1) % len(matrix) else: seed = (seed + 1) % len(matrix) medoid, distances = _wander_medoid(matrix, kept_mask, seed, max_steps, rng, cuda) # We need to make a histogram of only the unclustered distances - when run on GPU # these have not been removed and we must use the kept_mask if cuda: _torch.histc(distances[kept_mask], len(histogram), 0, _XMAX, out=histogram) else: _torch.histc(distances, len(histogram), 0, _XMAX, out=histogram) histogram[0] -= 1 # Remove distance to self threshold, success = _find_threshold(histogram, peak_valley_ratio, default, cuda) # If success is not None, either threshold detection failed or succeded. if success is not None: # Keep accurately track of successes if we exceed maxlen if len(attempts) == attempts.maxlen: successes -= attempts.popleft() # Add the current success to count successes += success attempts.append(success) # If less than minsuccesses of the last maxlen attempts were successful, # we relax the clustering criteria and reset counting successes. if len(attempts) == attempts.maxlen and successes < minsuccesses: peak_valley_ratio += 0.1 attempts.clear() successes = 0 # This is the final cluster AFTER establishing the threshold used cluster = _smaller_indices(distances, kept_mask, threshold, cuda) return cluster, medoid, seed, peak_valley_ratio def _cluster(matrix, labels, indices, max_steps, windowsize, minsuccesses, default, cuda): """Yields (medoid, points) pairs from a (obs x features) matrix""" seed = -1 rng = _random.Random(0) peak_valley_ratio = 0.1 attempts = _deque(maxlen=windowsize) if _torch.__version__ >= '1.2': # https://github.com/pytorch/pytorch/issues/20208 fixed in PyTorch 1.2 cuda_hist_dtype = _torch.float # Masking using uint8 tensors deprecated in PyTorch 1.2 kept_mask_dtype = _torch.bool else: cuda_hist_dtype = _torch.long kept_mask_dtype = _torch.uint8 kept_mask = _torch.ones(len(indices), dtype=kept_mask_dtype) if cuda: histogram = _torch.empty(_ceil(_XMAX/_DELTA_X), dtype=cuda_hist_dtype).cuda() kept_mask = kept_mask.cuda() else: histogram = _torch.empty(_ceil(_XMAX/_DELTA_X)) done = False while not done: _ = _findcluster(matrix, kept_mask, histogram, seed, peak_valley_ratio, max_steps, minsuccesses, default, rng, attempts, cuda) cluster, medoid, seed, peak_valley_ratio = _ # Write data to output. We use indices instead of labels directly to # prevent masking and thereby duplicating large string arrays if labels is None: yield indices[medoid].item(), {i.item() for i in indices[cluster]} else: yield labels[indices[medoid].item()], {labels[indices[i].item()] for i in cluster} for point in cluster: kept_mask[point] = 0 # If we use CUDA and the arrays are on GPU, it's too slow to modify the arrays and # faster to simply mask. if not cuda: _vambtools.torch_inplace_maskarray(matrix, kept_mask) indices = indices[kept_mask] # no need to inplace mask small array kept_mask.resize_(len(matrix)) kept_mask[:] = 1 done = len(matrix) == 0 else: done = not _torch.any(kept_mask).item() def _check_params(matrix, labels, maxsteps, windowsize, minsuccesses, default, logfile): """Checks matrix, labels, and maxsteps.""" if maxsteps < 1: raise ValueError('maxsteps must be a positive integer, not {}'.format(maxsteps)) if windowsize < 1: raise ValueError('windowsize must be at least 1, not {}'.format(windowsize)) if minsuccesses < 1 or minsuccesses > windowsize: raise ValueError('minsuccesses must be between 1 and windowsize, not {}'.format(minsuccesses)) if default <= 0.0: raise ValueError('default threshold must be a positive float, not {}'.format(default)) if len(matrix) < 1: raise ValueError('Matrix must have at least 1 observation.') if labels is not None: if len(labels) != len(matrix): raise ValueError('labels must have same length as matrix') if len(set(labels)) != len(matrix): raise ValueError('Labels must be unique') def cluster(matrix, labels=None, maxsteps=25, windowsize=200, minsuccesses=20, default=0.09, destroy=False, normalized=False, logfile=None, cuda=False): """Iterative medoid cluster generator. Yields (medoid), set(labels) pairs. Inputs: matrix: A (obs x features) Numpy matrix of data type numpy.float32 labels: None or Numpy array/list with labels for seqs [None = indices] maxsteps: Stop searching for optimal medoid after N futile attempts [25] default: Fallback threshold if cannot be estimated [0.09] windowsize: Length of window to count successes [200] minsuccesses: Minimum acceptable number of successes [15] destroy: Save memory by destroying matrix while clustering [False] normalized: Matrix is already preprocessed [False] logfile: Print threshold estimates and certainty to file [None] Output: Generator of (medoid, set(labels_in_cluster)) tuples. """ if matrix.dtype != _np.float32: raise(ValueError("Matrix must be of dtype float32")) if not destroy: matrix = matrix.copy() # Shuffle matrix in unison to prevent seed sampling bias. Indices keeps # track of which points are which. _np.random.RandomState(0).shuffle(matrix) indices = _np.random.RandomState(0).permutation(len(matrix)) indices = _torch.from_numpy(indices) matrix = _torch.from_numpy(matrix) if not normalized: _normalize(matrix, inplace=True) _check_params(matrix, labels, maxsteps, windowsize, minsuccesses, default, logfile) # Move to GPU if cuda: matrix = matrix.cuda() return _cluster(matrix, labels, indices, maxsteps, windowsize, minsuccesses, default, cuda) def write_clusters(filehandle, clusters, max_clusters=None, min_size=1, header=None, rename=True): """Writes clusters to an open filehandle. Inputs: filehandle: An open filehandle that can be written to clusters: An iterator generated by function `clusters` or a dict max_clusters: Stop printing after this many clusters [None] min_size: Don't output clusters smaller than N contigs header: Commented one-line header to add rename: Rename clusters to "cluster_1", "cluster_2" etc. Outputs: clusternumber: Number of clusters written ncontigs: Number of contigs written """ if not hasattr(filehandle, 'writable') or not filehandle.writable(): raise ValueError('Filehandle must be a writable file') # If clusters is not iterator it must be a dict - transform it to iterator if iter(clusters) is not clusters: clusters = clusters.items() if max_clusters is not None and max_clusters < 1: raise ValueError('max_clusters must None or at least 1, not {}'.format(max_clusters)) if header is not None and len(header) > 0: if '\n' in header: raise ValueError('Header cannot contain newline') if header[0] != '#': header = '# ' + header print(header, file=filehandle) clusternumber = 0 ncontigs = 0 for clustername, contigs in clusters: if len(contigs) < min_size: continue if rename: clustername = 'cluster_' + str(clusternumber + 1) for contig in contigs: print(clustername, contig, sep='\t', file=filehandle) filehandle.flush() clusternumber += 1 ncontigs += len(contigs) if clusternumber == max_clusters: break return clusternumber, ncontigs def read_clusters(filehandle, min_size=1): """Read clusters from a file as created by function `writeclusters`. Inputs: filehandle: An open filehandle that can be read from min_size: Minimum number of contigs in cluster to be kept Output: A {clustername: set(contigs)} dict""" contigsof = _defaultdict(set) for line in filehandle: stripped = line.strip() if not stripped or stripped[0] == '#': continue clustername, contigname = stripped.split('\t') contigsof[clustername].add(contigname) contigsof = {cl: co for cl, co in contigsof.items() if len(co) >= min_size} return contigsof
[ "math.ceil", "random.Random", "torch.any", "torch.nonzero", "numpy.random.RandomState", "collections.defaultdict", "torch.Tensor", "vamb.vambtools.torch_inplace_maskarray", "collections.deque", "torch.from_numpy" ]
[((869, 1345), 'torch.Tensor', '_torch.Tensor', (['[2.43432053e-11, 9.13472041e-10, 2.66955661e-08, 6.07588285e-07, \n 1.076976e-05, 0.000148671951, 0.00159837411, 0.0133830226, 0.0872682695,\n 0.443184841, 1.75283005, 5.39909665, 12.9517596, 24.1970725, 35.2065327,\n 39.894228, 35.2065327, 24.1970725, 12.9517596, 5.39909665, 1.75283005, \n 0.443184841, 0.0872682695, 0.0133830226, 0.00159837411, 0.000148671951,\n 1.076976e-05, 6.07588285e-07, 2.66955661e-08, 9.13472041e-10, \n 2.43432053e-11]'], {}), '([2.43432053e-11, 9.13472041e-10, 2.66955661e-08, \n 6.07588285e-07, 1.076976e-05, 0.000148671951, 0.00159837411, \n 0.0133830226, 0.0872682695, 0.443184841, 1.75283005, 5.39909665, \n 12.9517596, 24.1970725, 35.2065327, 39.894228, 35.2065327, 24.1970725, \n 12.9517596, 5.39909665, 1.75283005, 0.443184841, 0.0872682695, \n 0.0133830226, 0.00159837411, 0.000148671951, 1.076976e-05, \n 6.07588285e-07, 2.66955661e-08, 9.13472041e-10, 2.43432053e-11])\n', (882, 1345), True, 'import torch as _torch\n'), ((10065, 10082), 'random.Random', '_random.Random', (['(0)'], {}), '(0)\n', (10079, 10082), True, 'import random as _random\n'), ((10126, 10151), 'collections.deque', '_deque', ([], {'maxlen': 'windowsize'}), '(maxlen=windowsize)\n', (10132, 10151), True, 'from collections import defaultdict as _defaultdict, deque as _deque\n'), ((14237, 14263), 'torch.from_numpy', '_torch.from_numpy', (['indices'], {}), '(indices)\n', (14254, 14263), True, 'import torch as _torch\n'), ((14277, 14302), 'torch.from_numpy', '_torch.from_numpy', (['matrix'], {}), '(matrix)\n', (14294, 14302), True, 'import torch as _torch\n'), ((16803, 16820), 'collections.defaultdict', '_defaultdict', (['set'], {}), '(set)\n', (16815, 16820), True, 'from collections import defaultdict as _defaultdict, deque as _deque\n'), ((4802, 4828), 'torch.from_numpy', '_torch.from_numpy', (['indices'], {}), '(indices)\n', (4819, 4828), True, 'import torch as _torch\n'), ((5139, 5164), 'torch.from_numpy', '_torch.from_numpy', (['matrix'], {}), '(matrix)\n', (5156, 5164), True, 'import torch as _torch\n'), ((10744, 10767), 'math.ceil', '_ceil', (['(_XMAX / _DELTA_X)'], {}), '(_XMAX / _DELTA_X)\n', (10749, 10767), True, 'from math import ceil as _ceil\n'), ((11603, 11656), 'vamb.vambtools.torch_inplace_maskarray', '_vambtools.torch_inplace_maskarray', (['matrix', 'kept_mask'], {}), '(matrix, kept_mask)\n', (11637, 11656), True, 'import vamb.vambtools as _vambtools\n'), ((14115, 14140), 'numpy.random.RandomState', '_np.random.RandomState', (['(0)'], {}), '(0)\n', (14137, 14140), True, 'import numpy as _np\n'), ((14171, 14196), 'numpy.random.RandomState', '_np.random.RandomState', (['(0)'], {}), '(0)\n', (14193, 14196), True, 'import numpy as _np\n'), ((4629, 4678), 'torch.nonzero', '_torch.nonzero', (['((tensor <= threshold) & kept_mask)'], {}), '((tensor <= threshold) & kept_mask)\n', (4643, 4678), True, 'import torch as _torch\n'), ((10611, 10634), 'math.ceil', '_ceil', (['(_XMAX / _DELTA_X)'], {}), '(_XMAX / _DELTA_X)\n', (10616, 10634), True, 'from math import ceil as _ceil\n'), ((11881, 11902), 'torch.any', '_torch.any', (['kept_mask'], {}), '(kept_mask)\n', (11891, 11902), True, 'import torch as _torch\n')]
from __future__ import absolute_import, division, unicode_literals import numpy as np import struct from . import _common as common class dist_reader(): @staticmethod def read_matrix(filename): with open(filename, 'rb') as file: # check header file_signature = file.read(len(common.DIST_SIGNATURE)) if file_signature != common.DIST_SIGNATURE: raise RuntimeError('The given file is not a valid mm-dist ' 'file') # fetch header values value_type = ord(file.read(1)) size, = struct.unpack(b'<Q', file.read(8)) # read matrix values matrix_data_size = int(size * (size - 1) / 2) np_dtype = common.dtype_for_element_type[value_type] matrix_data = np.fromfile(file, dtype=np.dtype(np_dtype), count=matrix_data_size) # reshape to square result = np.zeros((size, size)) result[np.triu_indices(size, 1)] = matrix_data return result + result.T
[ "numpy.dtype", "numpy.zeros", "numpy.triu_indices" ]
[((994, 1016), 'numpy.zeros', 'np.zeros', (['(size, size)'], {}), '((size, size))\n', (1002, 1016), True, 'import numpy as np\n'), ((1036, 1060), 'numpy.triu_indices', 'np.triu_indices', (['size', '(1)'], {}), '(size, 1)\n', (1051, 1060), True, 'import numpy as np\n'), ((858, 876), 'numpy.dtype', 'np.dtype', (['np_dtype'], {}), '(np_dtype)\n', (866, 876), True, 'import numpy as np\n')]
"""Old (2018-19) adapted from <NAME>'s code""" from Generator import Generator from DynamicParameter import DynamicParameter import utils_old import numpy as np import os from shutil import copyfile, rmtree from time import time class Optimizer: def __init__(self, recorddir, random_seed=None, thread=None): if thread is not None: assert isinstance(thread, int), 'thread must be an integer' assert os.path.isdir(recorddir) assert isinstance(random_seed, int) or random_seed is None, 'random_seed must be an integer or None' self._generator = None self._istep = 0 # step num of Optimizer start from 0, at the end of each step _istep is 1...maxstep self._dynparams = {} self._curr_samples = None # array of codes self._curr_images = None # list of image arrays self._curr_sample_idc = None # range object self._curr_sample_ids = None # list self._next_sample_idx = 0 # scalar self._best_code = None self._best_score = None self._thread = thread if thread is not None: recorddir = os.path.join(recorddir, 'thread%02d' % self._thread) if not os.path.isdir(recorddir): os.mkdir(recorddir) self._recorddir = recorddir self._random_generator = np.random.RandomState() if random_seed is not None: if self._thread is not None: print('random seed set to %d for optimizer (thread %d)' % (random_seed, self._thread)) else: print('random seed set to %d for optimizer' % random_seed) self._random_seed = random_seed self._random_generator = np.random.RandomState(seed=self._random_seed) def load_generator(self): self._generator = Generator() self._prepare_images() def _prepare_images(self): ''' Use generator to generate image from each code in `_curr_samples` These images will finally be used in `scorer` ''' if self._generator is None: raise RuntimeError('generator not loaded. please run optimizer.load_generator() first') curr_images = [] for sample in self._curr_samples: im_arr = self._generator.visualize(sample) curr_images.append(im_arr) self._curr_images = curr_images def step(self, scores): '''Take in score for each sample and generate a next generation of samples.''' raise NotImplementedError def save_current_state(self, image_size=None): utils_old.write_images(self._curr_images, self._curr_sample_ids, self._recorddir, image_size) utils_old.write_codes(self._curr_samples, self._curr_sample_ids, self._recorddir) def save_current_codes(self): utils_old.write_codes(self._curr_samples, self._curr_sample_ids, self._recorddir) @property def current_images(self): # Wrapper of `_curr_images` if self._curr_images is None: raise RuntimeError('Current images have not been initialized. Is generator loaded?') return self._curr_images @property def current_images_copy(self): return list(np.array(self._curr_images).copy()) @property def current_image_ids(self): return self._curr_sample_ids @property def curr_image_idc(self): return self._curr_sample_idc @property def nsamples(self): return len(self._curr_samples) @property def dynamic_parameters(self): return self._dynparams def mutate(population, genealogy, mutation_size, mutation_rate, random_generator): do_mutate = random_generator.random_sample(population.shape) < mutation_rate population_new = population.copy() population_new[do_mutate] += random_generator.normal(loc=0, scale=mutation_size, size=np.sum(do_mutate)) genealogy_new = ['%s+mut' % gen for gen in genealogy] return population_new, genealogy_new def mate(population, genealogy, fitness, new_size, random_generator, skew=0.5): """ fitness > 0 """ # clean data assert len(population) == len(genealogy) assert len(population) == len(fitness) if np.max(fitness) == 0: fitness[np.argmax(fitness)] = 0.001 if np.min(fitness) <= 0: fitness[fitness <= 0] = np.min(fitness[fitness > 0]) fitness_bins = np.cumsum(fitness) fitness_bins /= fitness_bins[-1] parent1s = np.digitize(random_generator.random_sample(new_size), fitness_bins) parent2s = np.digitize(random_generator.random_sample(new_size), fitness_bins) new_samples = np.empty((new_size, population.shape[1])) new_genealogy = [] for i in range(new_size): parentage = random_generator.random_sample(population.shape[1]) < skew new_samples[i, parentage] = population[parent1s[i]][parentage] new_samples[i, ~parentage] = population[parent2s[i]][~parentage] new_genealogy.append('%s+%s' % (genealogy[parent1s[i]], genealogy[parent2s[i]])) return new_samples, new_genealogy class Genetic(Optimizer): def __init__(self, population_size, mutation_rate, mutation_size, kT_multiplier, recorddir, parental_skew=0.5, n_conserve=0, random_seed=None, thread=None): super(Genetic, self).__init__(recorddir, random_seed, thread) # various parameters self._popsize = int(population_size) self._mut_rate = float(mutation_rate) self._mut_size = float(mutation_size) self._kT_mul = float(kT_multiplier) self._kT = None # deprecated; will be overwritten self._n_conserve = int(n_conserve) assert (self._n_conserve < self._popsize) self._parental_skew = float(parental_skew) # initialize dynamic parameters & their types self._dynparams['mutation_rate'] = \ DynamicParameter('d', self._mut_rate, 'probability that each gene will mutate at each step') self._dynparams['mutation_size'] = \ DynamicParameter('d', self._mut_size, 'stdev of the stochastic size of mutation') self._dynparams['kT_multiplier'] = \ DynamicParameter('d', self._kT_mul, 'used to calculate kT; kT = kT_multiplier * stdev of scores') self._dynparams['n_conserve'] = \ DynamicParameter('i', self._n_conserve, 'number of best individuals kept unmutated in each step') self._dynparams['parental_skew'] = \ DynamicParameter('d', self._parental_skew, 'amount inherited from one parent; 1 means no recombination') self._dynparams['population_size'] = \ DynamicParameter('i', self._popsize, 'size of population') # initialize samples & indices self._init_population = self._random_generator.normal(loc=0, scale=1, size=(self._popsize, 4096)) self._init_population_dir = None self._init_population_fns = None self._curr_samples = self._init_population.copy() # curr_samples is current population of codes self._genealogy = ['standard_normal'] * self._popsize self._curr_sample_idc = range(self._popsize) self._next_sample_idx = self._popsize if self._thread is None: self._curr_sample_ids = ['gen%03d_%06d' % (self._istep, idx) for idx in self._curr_sample_idc] else: self._curr_sample_ids = ['thread%02d_gen%03d_%06d' % (self._thread, self._istep, idx) for idx in self._curr_sample_idc] # # reset random seed to ignore any calls during init # if random_seed is not None: # random_generator.seed(random_seed) def load_init_population(self, initcodedir, size): # make sure we are at the beginning of experiment assert self._istep == 0, 'initialization only allowed at the beginning' # make sure size <= population size assert size <= self._popsize, 'size %d too big for population of size %d' % (size, self._popsize) # load codes init_population, genealogy = utils_old.load_codes2(initcodedir, size) # fill the rest of population if size==len(codes) < population size if len(init_population) < self._popsize: remainder_size = self._popsize - len(init_population) remainder_pop, remainder_genealogy = mate( init_population, genealogy, # self._curr_sample_ids[:size], np.ones(len(init_population)), remainder_size, self._random_generator, self._parental_skew ) remainder_pop, remainder_genealogy = mutate( remainder_pop, remainder_genealogy, self._mut_size, self._mut_rate, self._random_generator ) init_population = np.concatenate((init_population, remainder_pop)) genealogy = genealogy + remainder_genealogy # apply self._init_population = init_population self._init_population_dir = initcodedir self._init_population_fns = genealogy # a list of '*.npy' file names self._curr_samples = self._init_population.copy() self._genealogy = ['[init]%s' % g for g in genealogy] # no update for idc, idx, ids because popsize unchanged try: self._prepare_images() except RuntimeError: # this means generator not loaded; on load, images will be prepared pass def save_init_population(self): '''Record experimental parameter: initial population in the directory "[:recorddir]/init_population" ''' assert (self._init_population_fns is not None) and (self._init_population_dir is not None), \ 'please load init population first by calling load_init_population();' + \ 'if init is not loaded from file, it can be found in experiment backup_images folder after experiment runs' recorddir = os.path.join(self._recorddir, 'init_population') try: os.mkdir(recorddir) except OSError as e: if e.errno == 17: # ADDED Sep.17, To let user delete the directory if existing during the system running. chs = input("Dir %s exist input y to delete the dir and write on it, n to exit" % recorddir) if chs is 'y': print("Directory %s all removed." % recorddir) rmtree(recorddir) os.mkdir(recorddir) else: raise OSError('trying to save init population but directory already exists: %s' % recorddir) else: raise for fn in self._init_population_fns: copyfile(os.path.join(self._init_population_dir, fn), os.path.join(recorddir, fn)) def step(self, scores, no_image=False): # clean variables assert len(scores) == len(self._curr_samples), \ 'number of scores (%d) != population size (%d)' % (len(scores), len(self._curr_samples)) new_size = self._popsize # this may != len(curr_samples) if it has been dynamically updated new_samples = np.empty((new_size, self._curr_samples.shape[1])) # instead of chaining the genealogy, alias it at every step curr_genealogy = np.array(self._curr_sample_ids, dtype=str) new_genealogy = [''] * new_size # np array not used because str len will be limited by len at init # deal with nan scores: nan_mask = np.isnan(scores) n_nans = int(np.sum(nan_mask)) valid_mask = ~nan_mask n_valid = int(np.sum(valid_mask)) if n_nans > 0: print('optimizer: missing %d scores for samples %s' % ( n_nans, str(np.array(self._curr_sample_idc)[nan_mask]))) if n_nans > new_size: print('Warning: n_nans > new population_size because population_size has just been changed AND ' + 'too many images failed to score. This will lead to arbitrary loss of some nan score images.') if n_nans > new_size - self._n_conserve: print('Warning: n_nans > new population_size - self._n_conserve. ' + 'IFF population_size has just been changed, ' + 'this will lead to aribitrary loss of some/all nan score images.') # carry over images with no scores thres_n_nans = min(n_nans, new_size) new_samples[-thres_n_nans:] = self._curr_samples[nan_mask][-thres_n_nans:] new_genealogy[-thres_n_nans:] = curr_genealogy[nan_mask][-thres_n_nans:] # if some images have scores if n_valid > 0: valid_scores = scores[valid_mask] self._kT = max((np.std(valid_scores) * self._kT_mul, 1e-8)) # prevents underflow kT = 0 print('kT: %f' % self._kT) sort_order = np.argsort(valid_scores)[::-1] # sort from high to low valid_scores = valid_scores[sort_order] # Note: if new_size is smalled than n_valid, low ranking images will be lost thres_n_valid = min(n_valid, new_size) new_samples[:thres_n_valid] = self._curr_samples[valid_mask][sort_order][:thres_n_valid] new_genealogy[:thres_n_valid] = curr_genealogy[valid_mask][sort_order][:thres_n_valid] # if need to generate new samples if n_nans < new_size - self._n_conserve: fitness = np.exp((valid_scores - valid_scores[0]) / self._kT) # skips first n_conserve samples n_mate = new_size - self._n_conserve - n_nans new_samples[self._n_conserve:thres_n_valid], new_genealogy[self._n_conserve:thres_n_valid] = \ mate( new_samples[:thres_n_valid], new_genealogy[:thres_n_valid], fitness, n_mate, self._random_generator, self._parental_skew ) new_samples[self._n_conserve:thres_n_valid], new_genealogy[self._n_conserve:thres_n_valid] = \ mutate( new_samples[self._n_conserve:thres_n_valid], new_genealogy[self._n_conserve:thres_n_valid], self._mut_size, self._mut_rate, self._random_generator ) # if any score turned out to be best if self._best_score is None or self._best_score < valid_scores[0]: self._best_score = valid_scores[0] self._best_code = new_samples[0].copy() self._istep += 1 self._curr_samples = new_samples self._genealogy = new_genealogy self._curr_sample_idc = range(self._next_sample_idx, self._next_sample_idx + new_size) # cumulative id . self._next_sample_idx += new_size if self._thread is None: self._curr_sample_ids = ['gen%03d_%06d' % (self._istep, idx) for idx in self._curr_sample_idc] else: self._curr_sample_ids = ['thread%02d_gen%03d_%06d' % (self._thread, self._istep, idx) for idx in self._curr_sample_idc] if not no_image: self._prepare_images() def step_simple(self, scores, codes): """ Taking scores and codes from outside to return new codes, without generating images Used in cases when the images are better handled in outer objects like Experiment object Discard the nan handling part! Discard the genealogy recording part """ assert len(scores) == len(codes), \ 'number of scores (%d) != population size (%d)' % (len(scores), len(codes)) new_size = self._popsize # this may != len(curr_samples) if it has been dynamically updated new_samples = np.empty((new_size, codes.shape[1])) # instead of chaining the genealogy, alias it at every step curr_genealogy = np.array(self._curr_sample_ids, dtype=str) new_genealogy = [''] * new_size # np array not used because str len will be limited by len at init # deal with nan scores: nan_mask = np.isnan(scores) n_nans = int(np.sum(nan_mask)) valid_mask = ~nan_mask n_valid = int(np.sum(valid_mask)) assert n_nans == 0 # discard the part dealing with nans # if some images have scores valid_scores = scores[valid_mask] self._kT = max((np.std(valid_scores) * self._kT_mul, 1e-8)) # prevents underflow kT = 0 print('kT: %f' % self._kT) sort_order = np.argsort(valid_scores)[::-1] # sort from high to low valid_scores = valid_scores[sort_order] # Note: if new_size is smalled than n_valid, low ranking images will be lost thres_n_valid = min(n_valid, new_size) new_samples[:thres_n_valid] = codes[valid_mask][sort_order][:thres_n_valid] new_genealogy[:thres_n_valid] = curr_genealogy[valid_mask][sort_order][:thres_n_valid] fitness = np.exp((valid_scores - valid_scores[0]) / self._kT) # skips first n_conserve samples n_mate = new_size - self._n_conserve - n_nans new_samples[self._n_conserve:thres_n_valid], new_genealogy[self._n_conserve:thres_n_valid] = \ mate( new_samples[:thres_n_valid], new_genealogy[:thres_n_valid], fitness, n_mate, self._random_generator, self._parental_skew ) new_samples[self._n_conserve:thres_n_valid], new_genealogy[self._n_conserve:thres_n_valid] = \ mutate( new_samples[self._n_conserve:thres_n_valid], new_genealogy[self._n_conserve:thres_n_valid], self._mut_size, self._mut_rate, self._random_generator ) self._istep += 1 self._genealogy = new_genealogy self._curr_samples = new_samples self._genealogy = new_genealogy self._curr_sample_idc = range(self._next_sample_idx, self._next_sample_idx + new_size) # cumulative id . self._next_sample_idx += new_size if self._thread is None: self._curr_sample_ids = ['gen%03d_%06d' % (self._istep, idx) for idx in self._curr_sample_idc] else: self._curr_sample_ids = ['thread%02d_gen%03d_%06d' % (self._thread, self._istep, idx) for idx in self._curr_sample_idc] return new_samples # def step_with_immigration(self, scores, immigrants, immigrant_scores): # assert len(immigrants.shape) == 2, 'population is not batch sized (dim != 2)' # self._curr_samples = np.concatenate((self._curr_samples, immigrants)) # scores = np.concatenate((scores, immigrant_scores)) # self.step(scores) def add_immigrants(self, codedir, size, ignore_conserve=False): if not ignore_conserve: assert size <= len(self._curr_samples) - self._n_conserve, \ 'size of immigrantion should be <= size of unconserved population because ignore_conserve is False' else: assert size < len(self._curr_samples), 'size of immigrantion should be < size of population' if size > len(self._curr_samples) - self._n_conserve: print('Warning: some conserved codes are being overwritten') immigrants, immigrant_codefns = utils_old.load_codes2(codedir, size) n_immi = len(immigrants) n_conserve = len(self._curr_samples) - n_immi self._curr_samples = np.concatenate((self._curr_samples[:n_conserve], immigrants)) self._genealogy = self._genealogy[:n_conserve] + ['[immi]%s' % fn for fn in immigrant_codefns] next_sample_idx = self._curr_sample_idc[n_conserve] + n_immi self._curr_sample_idc = range(self._curr_sample_idc[0], next_sample_idx) self._next_sample_idx = next_sample_idx if self._thread is None: new_sample_ids = ['gen%03d_%06d' % (self._istep, idx) for idx in self._curr_sample_idc[n_conserve:]] else: new_sample_ids = ['thread%02d_gen%03d_%06d' % (self._thread, self._istep, idx) for idx in self._curr_sample_idc[n_conserve:]] self._curr_sample_ids = self._curr_sample_ids[:n_conserve] + new_sample_ids self._prepare_images() def update_dynamic_parameters(self): if self._dynparams['mutation_rate'].value != self._mut_rate: self._mut_rate = self._dynparams['mutation_rate'].value print('updated mutation_rate to %f at step %d' % (self._mut_rate, self._istep)) if self._dynparams['mutation_size'].value != self._mut_size: self._mut_size = self._dynparams['mutation_size'].value print('updated mutation_size to %f at step %d' % (self._mut_size, self._istep)) if self._dynparams['kT_multiplier'].value != self._kT_mul: self._kT_mul = self._dynparams['kT_multiplier'].value print('updated kT_multiplier to %.2f at step %d' % (self._kT_mul, self._istep)) if self._dynparams['parental_skew'].value != self._parental_skew: self._parental_skew = self._dynparams['parental_skew'].value print('updated parental_skew to %.2f at step %d' % (self._parental_skew, self._istep)) if self._dynparams['population_size'].value != self._popsize or \ self._dynparams['n_conserve'].value != self._n_conserve: n_conserve = self._dynparams['n_conserve'].value popsize = self._dynparams['population_size'].value if popsize < n_conserve: # both newest if popsize == self._popsize: # if popsize hasn't changed self._dynparams['n_conserve'].set_value(self._n_conserve) print('rejected n_conserve update: new n_conserve > old population_size') else: # popsize has changed self._dynparams['population_size'].set_value(self._popsize) print('rejected population_size update: new population_size < new/old n_conserve') if n_conserve <= self._popsize: self._n_conserve = n_conserve print('updated n_conserve to %d at step %d' % (self._n_conserve, self._istep)) else: self._dynparams['n_conserve'].set_value(self._n_conserve) print('rejected n_conserve update: new n_conserve > old population_size') else: if self._popsize != popsize: self._popsize = popsize print('updated population_size to %d at step %d' % (self._popsize, self._istep)) if self._n_conserve != n_conserve: self._n_conserve = n_conserve print('updated n_conserve to %d at step %d' % (self._n_conserve, self._istep)) def save_current_genealogy(self): savefpath = os.path.join(self._recorddir, 'genealogy_gen%03d.npz' % self._istep) save_kwargs = {'image_ids': np.array(self._curr_sample_ids, dtype=str), 'genealogy': np.array(self._genealogy, dtype=str)} utils_old.savez(savefpath, save_kwargs) @property def generation(self): '''Return current step number''' return self._istep from numpy.linalg import norm from numpy.random import randn from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin # from numpy.linalg import norm class CMAES(Optimizer): # functions to be added # load_init_population(initcodedir, size=population_size) # save_init_population() # step() # Note this is a single step version of CMAES def __init__(self, recorddir, space_dimen, init_sigma=None, population_size=None, maximize=True, random_seed=None, thread=None): super(CMAES, self).__init__(recorddir, random_seed, thread) # -------------------- Initialization -------------------------------- # assert len(initX) == N or initX.size == N # xmean = np.array(initX) # xmean.shape = (-1, 1) N = space_dimen self.space_dimen = space_dimen # Overall control parameter self.maximize = maximize # if the program is to maximize or to minimize # Strategy parameter setting: Selection if population_size is None: self.lambda_ = int(4 + floor(3 * log2(N))) # population size, offspring number # the relation between dimension and population size. else: self.lambda_ = population_size # use custom specified population size mu = self.lambda_ / 2 # number of parents/points for recombination # Select half the population size as parents weights = log(mu + 1 / 2) - (log(np.arange(1, 1 + floor(mu)))) # muXone array for weighted recombination self.mu = int(floor(mu)) self.weights = weights / sum(weights) # normalize recombination weights array mueff = self.weights.sum() ** 2 / sum(self.weights ** 2) # variance-effectiveness of sum w_i x_i self.weights.shape = (1, -1) # Add the 1st dim to the weights mat self.mueff = mueff # add to class variable self.sigma = init_sigma # Note by default, sigma is None here. print("Space dimension: %d, Population size: %d, Select size:%d, Optimization Parameters:\nInitial sigma: %.3f" % (self.space_dimen, self.lambda_, self.mu, self.sigma)) # Strategy parameter settiself.weightsng: Adaptation self.cc = (4 + mueff / N) / (N + 4 + 2 * mueff / N) # time constant for cumulation for C self.cs = (mueff + 2) / (N + mueff + 5) # t-const for cumulation for sigma control self.c1 = 2 / ((N + 1.3) ** 2 + mueff) # learning rate for rank-one update of C self.cmu = min(1 - self.c1, 2 * (mueff - 2 + 1 / mueff) / ((N + 2) ** 2 + mueff)) # and for rank-mu update self.damps = 1 + 2 * max(0, sqrt((mueff - 1) / (N + 1)) - 1) + self.cs # damping for sigma # usually close to 1 print("cc=%.3f, cs=%.3f, c1=%.3f, cmu=%.3f, damps=%.3f" % (self.cc, self.cs, self.c1, self.cmu, self.damps)) self.xmean = zeros((1, N)) self.xold = zeros((1, N)) # Initialize dynamic (internal) strategy parameters and constants self.pc = zeros((1, N)) self.ps = zeros((1, N)) # evolution paths for C and sigma self.B = eye(N) # B defines the coordinate system self.D = ones(N) # diagonal D defines the scaling self.C = self.B * diag(self.D ** 2) * self.B.T # covariance matrix C self.invsqrtC = self.B * diag(1 / self.D) * self.B.T # C^-1/2 # self.D.shape = (-1, 1) self.eigeneval = 0 # track update of B and D self.counteval = 0 self.chiN = sqrt(N) * (1 - 1 / (4 * N) + 1 / ( 21 * N ** 2)) # expectation of ||N(0,I)|| == norm(randn(N,1)) in 1/N expansion formula def step(self, scores): # Note it's important to decide which variable is to be saved in the `Optimizer` object # Note to conform with other code, this part is transposed. N = self.space_dimen lambda_, mu, mueff, chiN = self.lambda_, self.mu, self.mueff, self.chiN cc, cs, c1, cmu, damps = self.cc, self.cs, self.c1, self.cmu, self.damps sigma, C, B, D, invsqrtC, ps, pc, = self.sigma, self.C, self.B, self.D, self.invsqrtC, self.ps, self.pc, # set short name for everything # Sort by fitness and compute weighted mean into xmean if self.maximize is False: code_sort_index = np.argsort(scores) # add - operator it will do maximization. else: code_sort_index = np.argsort(-scores) # scores = scores[code_sort_index] # Ascending order. minimization if self._istep == 0: # if without initialization, the first xmean is evaluated from weighted average all the natural images self.xmean = self.weights @ self._curr_samples[code_sort_index[0:mu], :] else: self.xold = self.xmean self.xmean = self.weights @ self._curr_samples[code_sort_index[0:mu], :] # Weighted recombination, new mean value # Cumulation: Update evolution paths norm_step_len = (self.xmean - self.xold) / sigma ps = (1 - cs) * ps + sqrt(cs * (2 - cs) * mueff) * (norm_step_len @ invsqrtC) hsig = norm(ps) / chiN / sqrt(1 - (1 - cs) ** (2 * self.counteval / lambda_)) < (1.4 + 2 / (N + 1)) pc = (1 - cc) * pc + hsig * sqrt(cc * (2 - cc) * mueff) * norm_step_len # Adapt covariance matrix C # x_tmp = (1 / sigma) * (self._curr_samples[code_sort_index[0:mu], :] - self.xold) # # C = ((1 - c1 - cmu) * C # regard old matrix # + c1 * (pc.T @ pc # plus rank one update # + (1 - hsig) * cc * (2 - cc) * C) # minor correction if hsig==0 # + cmu * x_tmp.T @ diag(self.weights.flat) @ x_tmp) # plus rank mu update # Adapt step size sigma sigma = sigma * exp((cs / damps) * (norm(ps) / chiN - 1)) # self.sigma = self.sigma * exp((self.cs / self.damps) * (norm(ps) / self.chiN - 1)) print("sigma: %.2f" % sigma) # Decomposition of C into B*diag(D.^2)*B' (diagonalization) # if self.counteval - self.eigeneval > lambda_ / (c1 + cmu) / N / 10: # to achieve O(N^2) # # FIXME: Seems every time after this decomposition , the score went down! # t1 = time() # self.eigeneval = self.counteval # C = np.triu(C) + np.triu(C, 1).T # enforce symmetry # [D, B] = np.linalg.eig(C) # eigen decomposition, B==normalized eigenvectors # print("Spectrum Range:%.2f, %.2f" % (D.min(), D.max())) # D = sqrt(D) # D is a vector of standard deviations now # invsqrtC = B @ diag(1 / D) @ B.T # t2 = time() # print("Cov Matrix Eigenvalue Decomposition (linalg) time cost: %.2f s" % (t2-t1)) # Generate new sample by sampling from Gaussian distribution new_samples = zeros((self.lambda_, N)) new_ids = [] for k in range(self.lambda_): new_samples[k:k + 1, :] = self.xmean + sigma * ((D * randn(1, N)) @ B.T) # m + sig * Normal(0,C) # Clever way to generate multivariate gaussian!! # Stretch the guassian hyperspher with D and transform the # ellipsoid by B mat linear transform between coordinates new_ids.append("gen%03d_%06d" % (self._istep, self.counteval)) # assign id to newly generated images. These will be used as file names at 2nd round self.counteval += 1 self.sigma, self.C, self.B, self.D, self.invsqrtC, self.ps, self.pc, = sigma, C, B, D, invsqrtC, ps, pc, self._istep += 1 self._curr_samples = new_samples self._curr_sample_ids = new_ids self._prepare_images() def save_optimizer_state(self): # if needed, a save Optimizer status function. Automatic save the optimization parameters at 1st step. if self._istep == 1: optim_setting = {"space_dimen": self.space_dimen, "population_size": self.lambda_, "select_num": self.mu, "weights": self.weights, "cc": self.cc, "cs": self.cs, "c1": self.c1, "cmu": self.cmu, "damps": self.damps} utils_old.savez(os.path.join(self._recorddir, "optimizer_setting.npz"), optim_setting) utils_old.savez(os.path.join(self._recorddir, "optimizer_state_block%03d.npz" % self._istep), {"sigma": self.sigma, "C": self.C, "D": self.D, "ps": self.ps, "pc": self.pc}) def load_init_population(self, initcodedir, size): # make sure we are at the beginning of experiment assert self._istep == 0, 'initialization only allowed at the beginning' # make sure size <= population size assert size <= self.lambda_, 'size %d too big for population of size %d' % (size, self.lambda_) # load codes init_population, genealogy = utils_old.load_codes2(initcodedir, size) # find `size` # of images in the target dir. # if needed can be control the number # apply self._init_population = init_population self._init_population_dir = initcodedir self._init_population_fns = genealogy # a list of '*.npy' file names self._curr_samples = self._init_population.copy() self._curr_sample_ids = genealogy.copy() # self._curr_samples = self._curr_samples.T # no update for idc, idx, ids because popsize unchanged try: self._prepare_images() except RuntimeError: # this means generator not loaded; on load, images will be prepared pass def save_init_population(self): '''Record experimental parameter: initial population in the directory "[:recorddir]/init_population" ''' assert (self._init_population_fns is not None) and (self._init_population_dir is not None), \ 'please load init population first by calling load_init_population();' + \ 'if init is not loaded from file, it can be found in experiment backup_images folder after experiment runs' recorddir = os.path.join(self._recorddir, 'init_population') try: os.mkdir(recorddir) except OSError as e: if e.errno == 17: # ADDED Sep.17, To let user delete the directory if existing during the system running. chs = input("Dir %s exist input y to delete the dir and write on it, n to exit" % recorddir) if chs is 'y': print("Directory %s all removed." % recorddir) rmtree(recorddir) os.mkdir(recorddir) else: raise OSError('trying to save init population but directory already exists: %s' % recorddir) else: raise for fn in self._init_population_fns: copyfile(os.path.join(self._init_population_dir, fn), os.path.join(recorddir, fn)) class CholeskyCMAES(Optimizer): # functions to be added # load_init_population(initcodedir, size=population_size) # save_init_population() # step() """ Note this is a variant of CMAES Cholesky suitable for high dimensional optimization""" def __init__(self, recorddir, space_dimen, init_sigma=None, init_code=None, population_size=None, Aupdate_freq=None, maximize=True, random_seed=None, thread=None, optim_params={}): super(CholeskyCMAES, self).__init__(recorddir, random_seed, thread) # -------------------- Initialization -------------------------------- # assert len(initX) == N or initX.size == N # xmean = np.array(initX) # xmean.shape = (-1, 1) N = space_dimen self.space_dimen = space_dimen # Overall control parameter self.maximize = maximize # if the program is to maximize or to minimize # Strategy parameter setting: Selection if population_size is None: self.lambda_ = int(4 + floor(3 * log2(N))) # population size, offspring number # the relation between dimension and population size. else: self.lambda_ = population_size # use custom specified population size mu = self.lambda_ / 2 # number of parents/points for recombination # Select half the population size as parents weights = log(mu + 1 / 2) - (log(np.arange(1, 1 + floor(mu)))) # muXone array for weighted recombination self.mu = int(floor(mu)) self.weights = weights / sum(weights) # normalize recombination weights array mueff = self.weights.sum() ** 2 / sum(self.weights ** 2) # variance-effectiveness of sum w_i x_i self.weights.shape = (1, -1) # Add the 1st dim 1 to the weights mat self.mueff = mueff # add to class variable self.sigma = init_sigma # Note by default, sigma is None here. print("Space dimension: %d, Population size: %d, Select size:%d, Optimization Parameters:\nInitial sigma: %.3f" % (self.space_dimen, self.lambda_, self.mu, self.sigma)) # Strategy parameter settiself.weightsng: Adaptation # self.cc = (4 + mueff / N) / (N + 4 + 2 * mueff / N) # time constant for cumulation for C # self.cs = (mueff + 2) / (N + mueff + 5) # t-const for cumulation for sigma control # self.c1 = 2 / ((N + 1.3) ** 2 + mueff) # learning rate for rank-one update of C # self.cmu = min(1 - self.c1, 2 * (mueff - 2 + 1 / mueff) / ((N + 2) ** 2 + mueff)) # and for rank-mu update # self.damps = 1 + 2 * max(0, sqrt((mueff - 1) / (N + 1)) - 1) + self.cs # damping for sigma self.cc = 4 / (N + 4) # defaultly 0.0009756 self.cs = sqrt(mueff) / (sqrt(mueff) + sqrt(N)) # 0.0499 self.c1 = 2 / (N + sqrt(2)) ** 2 # 1.1912701410022985e-07 if "cc" in optim_params.keys(): # if there is outside value for these parameter, overwrite them self.cc = optim_params["cc"] if "cs" in optim_params.keys(): self.cs = optim_params["cs"] if "c1" in optim_params.keys(): self.c1 = optim_params["c1"] self.damps = 1 + self.cs + 2 * max(0, sqrt((mueff - 1) / (N + 1)) - 1) # damping for sigma usually close to 1 print("cc=%.3f, cs=%.3f, c1=%.3f damps=%.3f" % (self.cc, self.cs, self.c1, self.damps)) if init_code is not None: self.init_x = np.asarray(init_code) self.init_x.shape = (1, N) else: self.init_x = None # FIXED Nov. 1st self.xmean = zeros((1, N)) self.xold = zeros((1, N)) # Initialize dynamic (internal) strategy parameters and constants self.pc = zeros((1, N)) self.ps = zeros((1, N)) # evolution paths for C and sigma self.A = eye(N, N) # covariant matrix is represent by the factors A * A '=C self.Ainv = eye(N, N) self.eigeneval = 0 # track update of B and D self.counteval = 0 if Aupdate_freq is None: self.update_crit = self.lambda_ / self.c1 / N / 10 else: self.update_crit = Aupdate_freq * self.lambda_ self.chiN = sqrt(N) * (1 - 1 / (4 * N) + 1 / (21 * N ** 2)) # expectation of ||N(0,I)|| == norm(randn(N,1)) in 1/N expansion formula def step(self, scores, no_image=False): # Note it's important to decide which variable is to be saved in the `Optimizer` object # Note to conform with other code, this part is transposed. # set short name for everything to simplify equations N = self.space_dimen lambda_, mu, mueff, chiN = self.lambda_, self.mu, self.mueff, self.chiN cc, cs, c1, damps = self.cc, self.cs, self.c1, self.damps sigma, A, Ainv, ps, pc, = self.sigma, self.A, self.Ainv, self.ps, self.pc, # Sort by fitness and compute weighted mean into xmean if self.maximize is False: code_sort_index = np.argsort(scores) # add - operator it will do maximization. else: code_sort_index = np.argsort(-scores) # scores = scores[code_sort_index] # Ascending order. minimization if self._istep == 0: # Population Initialization: if without initialization, the first xmean is evaluated from weighted average all the natural images if self.init_x is None: self.xmean = self.weights @ self._curr_samples[code_sort_index[0:mu], :] else: self.xmean = self.init_x else: self.xold = self.xmean self.xmean = self.weights @ self._curr_samples[code_sort_index[0:mu], :] # Weighted recombination, new mean value # Cumulation statistics through steps: Update evolution paths randzw = self.weights @ self.randz[code_sort_index[0:mu], :] ps = (1 - cs) * ps + sqrt(cs * (2 - cs) * mueff) * randzw pc = (1 - cc) * pc + sqrt(cc * (2 - cc) * mueff) * randzw @ A # Adapt step size sigma sigma = sigma * exp((cs / damps) * (norm(ps) / chiN - 1)) # self.sigma = self.sigma * exp((self.cs / self.damps) * (norm(ps) / self.chiN - 1)) print("sigma: %.2f" % sigma) # Update A and Ainv with search path if self.counteval - self.eigeneval > self.update_crit: # to achieve O(N ^ 2) do decomposition less frequently self.eigeneval = self.counteval t1 = time() v = pc @ Ainv normv = v @ v.T # Directly update the A Ainv instead of C itself A = sqrt(1 - c1) * A + sqrt(1 - c1) / normv * ( sqrt(1 + normv * c1 / (1 - c1)) - 1) * v @ pc.T # FIXME, dimension error Ainv = 1 / sqrt(1 - c1) * Ainv - 1 / sqrt(1 - c1) / normv * ( 1 - 1 / sqrt(1 + normv * c1 / (1 - c1))) * Ainv @ v.T @ v t2 = time() print("A, Ainv update! Time cost: %.2f s" % (t2 - t1)) # if self.counteval - self.eigeneval > lambda_ / (c1 + cmu) / N / 10: # to achieve O(N^2) # # FIXME: Seems every time after this decomposition , the score went down! # t1 = time() # self.eigeneval = self.counteval # C = np.triu(C) + np.triu(C, 1).T # enforce symmetry # [D, B] = np.linalg.eig(C) # eigen decomposition, B==normalized eigenvectors # print("Spectrum Range:%.2f, %.2f" % (D.min(), D.max())) # D = sqrt(D) # D is a vector of standard deviations now # invsqrtC = B @ diag(1 / D) @ B.T # t2 = time() # print("Cov Matrix Eigenvalue Decomposition (linalg) time cost: %.2f s" % (t2-t1)) # Generate new sample by sampling from Gaussian distribution new_samples = zeros((self.lambda_, N)) new_ids = [] self.randz = randn(self.lambda_, N) # save the random number for generating the code. for k in range(self.lambda_): new_samples[k:k + 1, :] = self.xmean + sigma * (self.randz[k, :] @ A) # m + sig * Normal(0,C) # Clever way to generate multivariate gaussian!! # Stretch the guassian hyperspher with D and transform the # ellipsoid by B mat linear transform between coordinates if self._thread is None: new_ids.append("gen%03d_%06d" % (self._istep, self.counteval)) else: new_ids.append('thread%02d_gen%03d_%06d' % (self._thread, self._istep, self.counteval)) # FIXME A little inconsistent with the naming at line 173/175/305/307 esp. for gen000 code # assign id to newly generated images. These will be used as file names at 2nd round self.counteval += 1 self.sigma, self.A, self.Ainv, self.ps, self.pc = sigma, A, Ainv, ps, pc, self._istep += 1 self._curr_samples = new_samples self._curr_sample_ids = new_ids if not no_image: self._prepare_images() return new_samples def step_simple(self, scores, codes): """ Taking scores and codes to return new codes, without generating images Used in cases when the images are better handled in outer objects like Experiment object """ # Note it's important to decide which variable is to be saved in the `Optimizer` object # Note to confirm with other code, this part is transposed. # set short name for everything to simplify equations N = self.space_dimen lambda_, mu, mueff, chiN = self.lambda_, self.mu, self.mueff, self.chiN cc, cs, c1, damps = self.cc, self.cs, self.c1, self.damps sigma, A, Ainv, ps, pc, = self.sigma, self.A, self.Ainv, self.ps, self.pc, # Sort by fitness and compute weighted mean into xmean if self.maximize is False: code_sort_index = np.argsort(scores) # add - operator it will do maximization. else: code_sort_index = np.argsort(-scores) # scores = scores[code_sort_index] # Ascending order. minimization if self._istep == 0: # Population Initialization: if without initialization, the first xmean is evaluated from weighted average all the natural images if self.init_x is None: self.xmean = self.weights @ codes[code_sort_index[0:mu], :] else: self.xmean = self.init_x else: self.xold = self.xmean self.xmean = self.weights @ codes[code_sort_index[0:mu], :] # Weighted recombination, new mean value # Cumulation statistics through steps: Update evolution paths randzw = self.weights @ self.randz[code_sort_index[0:mu], :] ps = (1 - cs) * ps + sqrt(cs * (2 - cs) * mueff) * randzw pc = (1 - cc) * pc + sqrt(cc * (2 - cc) * mueff) * randzw @ A # Adapt step size sigma sigma = sigma * exp((cs / damps) * (norm(ps) / chiN - 1)) # self.sigma = self.sigma * exp((self.cs / self.damps) * (norm(ps) / self.chiN - 1)) print("sigma: %.2f" % sigma) # Update A and Ainv with search path if self.counteval - self.eigeneval > self.update_crit: # to achieve O(N ^ 2) do decomposition less frequently self.eigeneval = self.counteval t1 = time() v = pc @ Ainv normv = v @ v.T # Directly update the A Ainv instead of C itself A = sqrt(1 - c1) * A + sqrt(1 - c1) / normv * ( sqrt(1 + normv * c1 / (1 - c1)) - 1) * v @ pc.T # FIXME, dimension error Ainv = 1 / sqrt(1 - c1) * Ainv - 1 / sqrt(1 - c1) / normv * ( 1 - 1 / sqrt(1 + normv * c1 / (1 - c1))) * Ainv @ v.T @ v t2 = time() print("A, Ainv update! Time cost: %.2f s" % (t2 - t1)) # Generate new sample by sampling from Gaussian distribution new_samples = zeros((self.lambda_, N)) self.randz = randn(self.lambda_, N) # save the random number for generating the code. for k in range(self.lambda_): new_samples[k:k + 1, :] = self.xmean + sigma * (self.randz[k, :] @ A) # m + sig * Normal(0,C) # Clever way to generate multivariate gaussian!! # Stretch the guassian hyperspher with D and transform the # ellipsoid by B mat linear transform between coordinates # FIXME A little inconsistent with the naming at line 173/175/305/307 esp. for gen000 code # assign id to newly generated images. These will be used as file names at 2nd round self.counteval += 1 self.sigma, self.A, self.Ainv, self.ps, self.pc = sigma, A, Ainv, ps, pc, self._istep += 1 return new_samples def save_optimizer_state(self): """a save Optimizer status function. Automatic save the optimization parameters at 1st step.save the changing parameters if not""" if self._istep == 1: optim_setting = {"space_dimen": self.space_dimen, "population_size": self.lambda_, "select_num": self.mu, "weights": self.weights, "cc": self.cc, "cs": self.cs, "c1": self.c1, "damps": self.damps, "init_x": self.init_x} utils_old.savez(os.path.join(self._recorddir, "optimizer_setting.npz"), optim_setting) utils_old.savez(os.path.join(self._recorddir, "optimizer_state_block%03d.npz" % self._istep), {"sigma": self.sigma, "A": self.A, "Ainv": self.Ainv, "ps": self.ps, "pc": self.pc}) def load_init_population(self, initcodedir, size): # make sure we are at the beginning of experiment assert self._istep == 0, 'initialization only allowed at the beginning' # make sure size <= population size assert size <= self.lambda_, 'size %d too big for population of size %d' % (size, self.lambda_) # load codes init_population, genealogy = utils_old.load_codes2(initcodedir, size) # find `size` # of images in the target dir. # if needed can be control the number # apply self._init_population = init_population self._init_population_dir = initcodedir self._init_population_fns = genealogy # a list of '*.npy' file names self._curr_samples = self._init_population.copy() if self._thread is None: self._curr_sample_ids = ['gen%03d_%06d' % (self._istep, idx) for idx in range(size)] else: self._curr_sample_ids = ['thread%02d_gen%03d_%06d' % (self._thread, self._istep, idx) for idx in range(size)] # Note: FIXED on Nov. 14th in consistant with former version of code. # self._curr_sample_ids = genealogy.copy() # FIXED: @Nov.14 keep the nomenclatuere the same # no update for idc, idx, ids because popsize unchanged try: self._prepare_images() except RuntimeError: # this means generator not loaded; on load, images will be prepared pass def save_init_population(self): '''Record experimental parameter: initial population in the directory "[:recorddir]/init_population" ''' assert (self._init_population_fns is not None) and (self._init_population_dir is not None), \ 'please load init population first by calling load_init_population();' + \ 'if init is not loaded from file, it can be found in experiment backup_images folder after experiment runs' recorddir = os.path.join(self._recorddir, 'init_population') try: os.mkdir(recorddir) except OSError as e: if e.errno == 17: # ADDED Sep.17, To let user delete the directory if existing during the system running. chs = input("Dir %s exist input y to delete the dir and write on it, n to exit" % recorddir) if chs is 'y': print("Directory %s all removed." % recorddir) rmtree(recorddir) os.mkdir(recorddir) else: raise OSError('trying to save init population but directory already exists: %s' % recorddir) else: raise for fn in self._init_population_fns: copyfile(os.path.join(self._init_population_dir, fn), os.path.join(recorddir, fn)) class CholeskyCMAES_Sphere(CholeskyCMAES): # functions to be added # load_init_population(initcodedir, size=population_size) # save_init_population() # step() """ Note this is a variant of CMAES Cholesky suitable for high dimensional optimization""" def __init__(self, recorddir, space_dimen, init_sigma=None, init_code=None, population_size=None, Aupdate_freq=None, sphere_norm=300, maximize=True, random_seed=None, thread=None, optim_params={}): super(CholeskyCMAES_Sphere, self).__init__(recorddir, space_dimen, init_sigma=init_sigma, init_code=init_code, population_size=population_size, Aupdate_freq=Aupdate_freq, maximize=maximize, random_seed=random_seed, thread=thread, optim_params=optim_params) N = space_dimen self.space_dimen = space_dimen # Overall control parameter self.maximize = maximize # if the program is to maximize or to minimize # Strategy parameter setting: Selection if population_size is None: self.lambda_ = int(4 + floor(3 * log2(N))) # population size, offspring number # the relation between dimension and population size. else: self.lambda_ = population_size # use custom specified population size mu = self.lambda_ / 2 # number of parents/points for recombination # Select half the population size as parents weights = log(mu + 1 / 2) - (log(np.arange(1, 1 + floor(mu)))) # muXone array for weighted recombination self.mu = int(floor(mu)) self.weights = weights / sum(weights) # normalize recombination weights array mueff = self.weights.sum() ** 2 / sum(self.weights ** 2) # variance-effectiveness of sum w_i x_i self.weights.shape = (1, -1) # Add the 1st dim 1 to the weights mat self.mueff = mueff # add to class variable self.sigma = init_sigma # Note by default, sigma is None here. print("Space dimension: %d, Population size: %d, Select size:%d, Optimization Parameters:\nInitial sigma: %.3f" % (self.space_dimen, self.lambda_, self.mu, self.sigma)) # Strategy parameter settiself.weightsng: Adaptation self.cc = 4 / (N + 4) # defaultly 0.0009756 self.cs = sqrt(mueff) / (sqrt(mueff) + sqrt(N)) # 0.0499 self.c1 = 2 / (N + sqrt(2)) ** 2 # 1.1912701410022985e-07 if "cc" in optim_params.keys(): # if there is outside value for these parameter, overwrite them self.cc = optim_params["cc"] if "cs" in optim_params.keys(): self.cs = optim_params["cs"] if "c1" in optim_params.keys(): self.c1 = optim_params["c1"] self.damps = 1 + self.cs + 2 * max(0, sqrt((mueff - 1) / (N + 1)) - 1) # damping for sigma usually close to 1 self.MAXSGM = 0.5 if "MAXSGM" in optim_params.keys(): self.MAXSGM = optim_params["MAXSGM"] self.sphere_norm = sphere_norm if "sphere_norm" in optim_params.keys(): self.sphere_norm = optim_params["sphere_norm"] print("cc=%.3f, cs=%.3f, c1=%.3f damps=%.3f" % (self.cc, self.cs, self.c1, self.damps)) print("Maximum Sigma %.2f" % self.MAXSGM) if init_code is not None: self.init_x = np.asarray(init_code) self.init_x.shape = (1, N) else: self.init_x = None # FIXED Nov. 1st self.xmean = zeros((1, N)) self.xold = zeros((1, N)) # Initialize dynamic (internal) strategy parameters and constants self.pc = zeros((1, N)) self.ps = zeros((1, N)) # evolution paths for C and sigma self.A = eye(N, N) # covariant matrix is represent by the factors A * A '=C self.Ainv = eye(N, N) self.tang_codes = zeros((self.lambda_, N)) self.eigeneval = 0 # track update of B and D self.counteval = 0 if Aupdate_freq is None: self.update_crit = self.lambda_ / self.c1 / N / 10 else: self.update_crit = Aupdate_freq * self.lambda_ self.chiN = sqrt(N) * (1 - 1 / (4 * N) + 1 / (21 * N ** 2)) def step(self, scores, no_image=False): # Note it's important to decide which variable is to be saved in the `Optimizer` object # Note to conform with other code, this part is transposed. # set short name for everything to simplify equations N = self.space_dimen lambda_, mu, mueff, chiN = self.lambda_, self.mu, self.mueff, self.chiN cc, cs, c1, damps = self.cc, self.cs, self.c1, self.damps sigma, A, Ainv, ps, pc, = self.sigma, self.A, self.Ainv, self.ps, self.pc, # obj.codes = codes; # Sort by fitness and compute weighted mean into xmean if self.maximize is False: code_sort_index = np.argsort(scores) # add - operator it will do maximization. else: code_sort_index = np.argsort(-scores) sorted_score = scores[code_sort_index] # print(sorted_score) if self._istep == 0: print('First generation\n') # Population Initialization: if without initialization, the first xmean is evaluated from weighted average all the natural images if self.init_x is None: if mu <= len(scores): self.xmean = self.weights @ self._curr_samples[code_sort_index[0:mu], :] else: # if ever the obj.mu (selected population size) larger than the initial population size (init_population is 1 ?) tmpmu = max(floor(len(scores) / 2), 1) # make sure at least one element! self.xmean = self.weights[:tmpmu] @ self._curr_samples[code_sort_index[:tmpmu], :] / sum( self.weights[:tmpmu]) self.xmean = self.xmean / norm(self.xmean) else: self.xmean = self.init_x else: # if not first step # print('Not First generation\n') self.xold = self.xmean xold = self.xold # Weighted recombination, move the mean value # mean_tangent = self.weights * self.tang_codes(code_sort_index(1:self.mu), :); # self.xmean = ExpMap(self.xmean, mean_tangent); # Map the mean tangent onto sphere # Do spherical mean in embedding space, not in tangent # vector space! # self.xmean = self.weights * self.codes(code_sort_index(1:self.mu), :); # self.xmean = self.xmean / norm(self.xmean); # Spherical Mean # [vtan_old, vtan_new] = InvExpMap(xold, self.xmean); # Tangent vector of the arc between old and new mean vtan_old = self.weights @ self.tang_codes[code_sort_index[0:mu], :] # mean in Tangent Space for tang_codes in last generation xmean = ExpMap(xold, vtan_old) # Project to new tangent space self.xmean = xmean print(norm(vtan_old)) vtan_new = VecTransport(xold, xmean, vtan_old); # Transport this vector to new spot uni_vtan_old = vtan_old / norm(vtan_old); uni_vtan_new = vtan_new / norm(vtan_new); # uniform the tangent vector ps_transp = VecTransport(xold, xmean, ps); # transport the path vector from old to new mean pc_transp = VecTransport(xold, xmean, pc); # Cumulation: Update evolution paths # In the sphereical case we have to transport the vector to # the new center # FIXME, pc explode problem???? # randzw = weights * randz(code_sort_index(1:mu), :); # Note, use the randz saved from last generation # ps = (1 - cs) * ps + sqrt(cs * (2 - cs) * mueff) * randzw; # pc = (1 - cc) * pc + sqrt(cc * (2 - cc) * mueff) * randzw * A; pc = (1 - cc) * pc_transp + sqrt( cc * (2 - cc) * mueff) * vtan_new / sigma; # do the update in the new tangent space # Transport the A and Ainv to the new tangent space A = A + A @ uni_vtan_old.T @ (uni_vtan_new - uni_vtan_old) + A @ xold.T @ ( xmean - xold) # transport the A mapping from old to new mean Ainv = Ainv + (uni_vtan_new - uni_vtan_old).T @ uni_vtan_old @ Ainv + (xmean - xold).T @ xold @ Ainv # Use the new Ainv to transform ps to z space ps = (1 - cs) * ps_transp + sqrt(cs * (2 - cs) * mueff) * vtan_new @ Ainv / sigma # Adapt step size sigma. # Decide whether to grow sigma or shrink sigma by comparing # the cumulated path length norm(ps) with expectation chiN # chiN = RW_Step_Size_Sphere(lambda, sigma, N); sigma = min(self.MAXSGM, sigma * exp((cs / damps) * (norm(real(ps)) * sqrt(N) / chiN - 1))) if sigma == self.MAXSGM: print("Reach upper limit for sigma! ") print("Step %d, sigma: %0.2e, Scores\n" % (self._istep, sigma)) # disp(A * Ainv) # Update the A and Ainv mapping if self.counteval - self.eigeneval > self.update_crit: # to achieve O(N ^ 2) self.eigeneval = self.counteval t1 = time() v = pc @ Ainv normv = v @ v.T A = sqrt(1 - c1) * A + sqrt(1 - c1) / normv * ( sqrt(1 + normv * c1 / (1 - c1)) - 1) * v.T @ pc # FIXED! dimension error Ainv = 1 / sqrt(1 - c1) * Ainv - 1 / sqrt(1 - c1) / normv * ( 1 - 1 / sqrt(1 + normv * c1 / (1 - c1))) * Ainv @ v.T @ v print("A, Ainv update! Time cost: %.2f s" % (time() - t1)) print("A Ainv Deiviation Norm from identity %.2E", norm(eye(N) - self.A * self.Ainv)) # Deviation from being inverse to each other # of first step # Generate new sample by sampling from Multivar Gaussian distribution self.tang_codes = zeros((self.lambda_, N)) new_samples = zeros((self.lambda_, N)) new_ids = [] self.randz = randn(self.lambda_, N) # save the random number for generating the code. # For optimization path update in the next generation. self.tang_codes = self.sigma * (self.randz @ self.A) / sqrt(N) # sig * Normal(0,C) # Clever way to generate multivariate gaussian!! self.tang_codes = self.tang_codes - (self.tang_codes @ self.xmean.T) @ self.xmean # FIXME, wrap back problem # DO SOLVED, by limiting the sigma to small value? new_samples = ExpMap(self.xmean, self.tang_codes) # Exponential map the tang vector from center to the sphere for k in range(self.lambda_): if self._thread is None: new_ids.append("gen%03d_%06d" % (self._istep, self.counteval)) else: new_ids.append('thread%02d_gen%03d_%06d' % (self._thread, self._istep, self.counteval)) # FIXME self.A little inconsistent with the naming at line 173/175/305/307 esp. for gen000 code # assign id to newly generated images. These will be used as file names at 2nd round self.counteval = self.counteval + 1 # self._istep = self._istep + 1 self.sigma, self.A, self.Ainv, self.ps, self.pc = sigma, A, Ainv, ps, pc, self._istep += 1 self._curr_samples = new_samples * self.sphere_norm self._curr_sample_ids = new_ids if not no_image: self._prepare_images() def ExpMap(x, tang_vec): '''Assume x is (1, N)''' # EPS = 1E-3; # assert(abs(norm(x)-1) < EPS) # assert(sum(x * tang_vec') < EPS) angle_dist = sqrt((tang_vec ** 2).sum(axis=1)) # vectorized angle_dist = angle_dist[:, np.newaxis] uni_tang_vec = tang_vec / angle_dist # x = repmat(x, size(tang_vec, 1), 1); # vectorized y = cos(angle_dist) @ x[:] + sin(angle_dist) * uni_tang_vec return y def VecTransport(xold, xnew, v): xold = xold / norm(xold) xnew = xnew / norm(xnew) x_symm_axis = xold + xnew v_transport = v - 2 * v @ x_symm_axis.T / norm( x_symm_axis) ** 2 * x_symm_axis # Equation for vector parallel transport along geodesic # Don't use dot in numpy, it will have wierd behavior if the array is not single dimensional return v_transport # # class FDGD(Optimizer): # def __init__(self, nsamples, mutation_size, learning_rate, antithetic=True, init_code=None): # self._nsamples = int(nsamples) # self._mut_size = float(mutation_size) # self._lr = float(learning_rate) # self._antithetic = antithetic # self.parameters = {'mutation_size': mutation_size, 'learning_rate': learning_rate, # 'nsamples': nsamples, 'antithetic': antithetic} # # if init_code is not None: # self._init_code = init_code.copy().reshape(4096) # else: # # self.init_code = np.random.normal(loc=0, scale=1, size=(4096)) # self._init_code = np.zeros(shape=(4096,)) # self._curr = self._init_code.copy() # self._best_code = self._curr.copy() # self._best_score = None # # self._pos_isteps = None # self._norm_isteps = None # # self._prepare_next_samples() # # def _prepare_next_samples(self): # self._pos_isteps = np.random.normal(loc=0, scale=self._mut_size, size=(self._nsamples, len(self._curr))) # self._norm_isteps = np.linalg.norm(self._pos_isteps, axis=1) # # pos_samples = self._pos_isteps + self._curr # if self._antithetic: # neg_samples = -self._pos_isteps + self._curr # self._curr_samples = np.concatenate((pos_samples, neg_samples)) # else: # self._curr_samples = np.concatenate((pos_samples, (self._curr.copy(),))) # # self._curr_sample_idc = range(self._next_sample_idx, self._next_sample_idx + len(self._curr_samples)) # self._next_sample_idx += len(self._curr_samples) # # curr_images = [] # for sample in self._curr_samples: # im_arr = self._generator.visualize(sample) # curr_images.append(im_arr) # self._curr_images = curr_images # # def step(self, scores): # """ # Use scores for current samples to update samples # :param scores: array or list of scalar scores, one for each current sample, in order # :param write: # if True, immediately writes after samples are prepared. # if False, user need to call .write_images(path) # :return: None # """ # scores = np.array(scores) # assert len(scores) == len(self._curr_samples),\ # 'number of scores (%d) and number of samples (%d) are different' % (len(scores), len(self._curr_samples)) # # pos_scores = scores[:self._nsamples] # if self._antithetic: # neg_scores = scores[self._nsamples:] # dscore = (pos_scores - neg_scores) / 2. # else: # dscore = pos_scores - scores[-1] # # grad = np.mean(dscore.reshape(-1, 1) * self._pos_isteps * (self._norm_isteps ** -2).reshape(-1, 1), axis=0) # self._curr += self._lr * grad # # score_argmax = np.argsort(scores)[-1] # if self._best_score is None or self._best_score < scores[score_argmax]: # self._best_score = scores[score_argmax] # self._best_code = self._curr_samples[score_argmax] # # self._prepare_next_samples()
[ "utils_old.write_images", "os.mkdir", "numpy.sum", "numpy.argmax", "numpy.empty", "numpy.floor", "numpy.ones", "numpy.isnan", "numpy.argsort", "numpy.sin", "numpy.linalg.norm", "numpy.exp", "numpy.diag", "shutil.rmtree", "os.path.join", "utils_old.savez", "numpy.random.randn", "num...
[((4387, 4405), 'numpy.cumsum', 'np.cumsum', (['fitness'], {}), '(fitness)\n', (4396, 4405), True, 'import numpy as np\n'), ((4627, 4668), 'numpy.empty', 'np.empty', (['(new_size, population.shape[1])'], {}), '((new_size, population.shape[1]))\n', (4635, 4668), True, 'import numpy as np\n'), ((432, 456), 'os.path.isdir', 'os.path.isdir', (['recorddir'], {}), '(recorddir)\n', (445, 456), False, 'import os\n'), ((1342, 1365), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (1363, 1365), True, 'import numpy as np\n'), ((1823, 1834), 'Generator.Generator', 'Generator', ([], {}), '()\n', (1832, 1834), False, 'from Generator import Generator\n'), ((2590, 2688), 'utils_old.write_images', 'utils_old.write_images', (['self._curr_images', 'self._curr_sample_ids', 'self._recorddir', 'image_size'], {}), '(self._curr_images, self._curr_sample_ids, self.\n _recorddir, image_size)\n', (2612, 2688), False, 'import utils_old\n'), ((2692, 2778), 'utils_old.write_codes', 'utils_old.write_codes', (['self._curr_samples', 'self._curr_sample_ids', 'self._recorddir'], {}), '(self._curr_samples, self._curr_sample_ids, self.\n _recorddir)\n', (2713, 2778), False, 'import utils_old\n'), ((2817, 2903), 'utils_old.write_codes', 'utils_old.write_codes', (['self._curr_samples', 'self._curr_sample_ids', 'self._recorddir'], {}), '(self._curr_samples, self._curr_sample_ids, self.\n _recorddir)\n', (2838, 2903), False, 'import utils_old\n'), ((4211, 4226), 'numpy.max', 'np.max', (['fitness'], {}), '(fitness)\n', (4217, 4226), True, 'import numpy as np\n'), ((4284, 4299), 'numpy.min', 'np.min', (['fitness'], {}), '(fitness)\n', (4290, 4299), True, 'import numpy as np\n'), ((4338, 4366), 'numpy.min', 'np.min', (['fitness[fitness > 0]'], {}), '(fitness[fitness > 0])\n', (4344, 4366), True, 'import numpy as np\n'), ((5874, 5970), 'DynamicParameter.DynamicParameter', 'DynamicParameter', (['"""d"""', 'self._mut_rate', '"""probability that each gene will mutate at each step"""'], {}), "('d', self._mut_rate,\n 'probability that each gene will mutate at each step')\n", (5890, 5970), False, 'from DynamicParameter import DynamicParameter\n'), ((6024, 6109), 'DynamicParameter.DynamicParameter', 'DynamicParameter', (['"""d"""', 'self._mut_size', '"""stdev of the stochastic size of mutation"""'], {}), "('d', self._mut_size,\n 'stdev of the stochastic size of mutation')\n", (6040, 6109), False, 'from DynamicParameter import DynamicParameter\n'), ((6163, 6264), 'DynamicParameter.DynamicParameter', 'DynamicParameter', (['"""d"""', 'self._kT_mul', '"""used to calculate kT; kT = kT_multiplier * stdev of scores"""'], {}), "('d', self._kT_mul,\n 'used to calculate kT; kT = kT_multiplier * stdev of scores')\n", (6179, 6264), False, 'from DynamicParameter import DynamicParameter\n'), ((6315, 6416), 'DynamicParameter.DynamicParameter', 'DynamicParameter', (['"""i"""', 'self._n_conserve', '"""number of best individuals kept unmutated in each step"""'], {}), "('i', self._n_conserve,\n 'number of best individuals kept unmutated in each step')\n", (6331, 6416), False, 'from DynamicParameter import DynamicParameter\n'), ((6470, 6578), 'DynamicParameter.DynamicParameter', 'DynamicParameter', (['"""d"""', 'self._parental_skew', '"""amount inherited from one parent; 1 means no recombination"""'], {}), "('d', self._parental_skew,\n 'amount inherited from one parent; 1 means no recombination')\n", (6486, 6578), False, 'from DynamicParameter import DynamicParameter\n'), ((6634, 6692), 'DynamicParameter.DynamicParameter', 'DynamicParameter', (['"""i"""', 'self._popsize', '"""size of population"""'], {}), "('i', self._popsize, 'size of population')\n", (6650, 6692), False, 'from DynamicParameter import DynamicParameter\n'), ((8062, 8102), 'utils_old.load_codes2', 'utils_old.load_codes2', (['initcodedir', 'size'], {}), '(initcodedir, size)\n', (8083, 8102), False, 'import utils_old\n'), ((9900, 9948), 'os.path.join', 'os.path.join', (['self._recorddir', '"""init_population"""'], {}), "(self._recorddir, 'init_population')\n", (9912, 9948), False, 'import os\n'), ((11109, 11158), 'numpy.empty', 'np.empty', (['(new_size, self._curr_samples.shape[1])'], {}), '((new_size, self._curr_samples.shape[1]))\n', (11117, 11158), True, 'import numpy as np\n'), ((11252, 11294), 'numpy.array', 'np.array', (['self._curr_sample_ids'], {'dtype': 'str'}), '(self._curr_sample_ids, dtype=str)\n', (11260, 11294), True, 'import numpy as np\n'), ((11455, 11471), 'numpy.isnan', 'np.isnan', (['scores'], {}), '(scores)\n', (11463, 11471), True, 'import numpy as np\n'), ((15747, 15783), 'numpy.empty', 'np.empty', (['(new_size, codes.shape[1])'], {}), '((new_size, codes.shape[1]))\n', (15755, 15783), True, 'import numpy as np\n'), ((15877, 15919), 'numpy.array', 'np.array', (['self._curr_sample_ids'], {'dtype': 'str'}), '(self._curr_sample_ids, dtype=str)\n', (15885, 15919), True, 'import numpy as np\n'), ((16080, 16096), 'numpy.isnan', 'np.isnan', (['scores'], {}), '(scores)\n', (16088, 16096), True, 'import numpy as np\n'), ((16940, 16991), 'numpy.exp', 'np.exp', (['((valid_scores - valid_scores[0]) / self._kT)'], {}), '((valid_scores - valid_scores[0]) / self._kT)\n', (16946, 16991), True, 'import numpy as np\n'), ((19273, 19309), 'utils_old.load_codes2', 'utils_old.load_codes2', (['codedir', 'size'], {}), '(codedir, size)\n', (19294, 19309), False, 'import utils_old\n'), ((19426, 19487), 'numpy.concatenate', 'np.concatenate', (['(self._curr_samples[:n_conserve], immigrants)'], {}), '((self._curr_samples[:n_conserve], immigrants))\n', (19440, 19487), True, 'import numpy as np\n'), ((22882, 22950), 'os.path.join', 'os.path.join', (['self._recorddir', "('genealogy_gen%03d.npz' % self._istep)"], {}), "(self._recorddir, 'genealogy_gen%03d.npz' % self._istep)\n", (22894, 22950), False, 'import os\n'), ((23113, 23152), 'utils_old.savez', 'utils_old.savez', (['savefpath', 'save_kwargs'], {}), '(savefpath, save_kwargs)\n', (23128, 23152), False, 'import utils_old\n'), ((26243, 26256), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (26248, 26256), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((26277, 26290), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (26282, 26290), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((26383, 26396), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (26388, 26396), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((26415, 26428), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (26420, 26428), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((26481, 26487), 'numpy.eye', 'eye', (['N'], {}), '(N)\n', (26484, 26487), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((26540, 26547), 'numpy.ones', 'ones', (['N'], {}), '(N)\n', (26544, 26547), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((30349, 30373), 'numpy.zeros', 'zeros', (['(self.lambda_, N)'], {}), '((self.lambda_, N))\n', (30354, 30373), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((32366, 32406), 'utils_old.load_codes2', 'utils_old.load_codes2', (['initcodedir', 'size'], {}), '(initcodedir, size)\n', (32387, 32406), False, 'import utils_old\n'), ((33562, 33610), 'os.path.join', 'os.path.join', (['self._recorddir', '"""init_population"""'], {}), "(self._recorddir, 'init_population')\n", (33574, 33610), False, 'import os\n'), ((38048, 38061), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (38053, 38061), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((38082, 38095), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (38087, 38095), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((38188, 38201), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (38193, 38201), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((38220, 38233), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (38225, 38233), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((38286, 38295), 'numpy.eye', 'eye', (['N', 'N'], {}), '(N, N)\n', (38289, 38295), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((38374, 38383), 'numpy.eye', 'eye', (['N', 'N'], {}), '(N, N)\n', (38377, 38383), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((42421, 42445), 'numpy.zeros', 'zeros', (['(self.lambda_, N)'], {}), '((self.lambda_, N))\n', (42426, 42445), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((42488, 42510), 'numpy.random.randn', 'randn', (['self.lambda_', 'N'], {}), '(self.lambda_, N)\n', (42493, 42510), False, 'from numpy.random import randn\n'), ((46677, 46701), 'numpy.zeros', 'zeros', (['(self.lambda_, N)'], {}), '((self.lambda_, N))\n', (46682, 46701), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((46723, 46745), 'numpy.random.randn', 'randn', (['self.lambda_', 'N'], {}), '(self.lambda_, N)\n', (46728, 46745), False, 'from numpy.random import randn\n'), ((48724, 48764), 'utils_old.load_codes2', 'utils_old.load_codes2', (['initcodedir', 'size'], {}), '(initcodedir, size)\n', (48745, 48764), False, 'import utils_old\n'), ((50301, 50349), 'os.path.join', 'os.path.join', (['self._recorddir', '"""init_population"""'], {}), "(self._recorddir, 'init_population')\n", (50313, 50349), False, 'import os\n'), ((54786, 54799), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (54791, 54799), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((54820, 54833), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (54825, 54833), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((54926, 54939), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (54931, 54939), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((54958, 54971), 'numpy.zeros', 'zeros', (['(1, N)'], {}), '((1, N))\n', (54963, 54971), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((55024, 55033), 'numpy.eye', 'eye', (['N', 'N'], {}), '(N, N)\n', (55027, 55033), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((55112, 55121), 'numpy.eye', 'eye', (['N', 'N'], {}), '(N, N)\n', (55115, 55121), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((55148, 55172), 'numpy.zeros', 'zeros', (['(self.lambda_, N)'], {}), '((self.lambda_, N))\n', (55153, 55172), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((61406, 61430), 'numpy.zeros', 'zeros', (['(self.lambda_, N)'], {}), '((self.lambda_, N))\n', (61411, 61430), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((61453, 61477), 'numpy.zeros', 'zeros', (['(self.lambda_, N)'], {}), '((self.lambda_, N))\n', (61458, 61477), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((61520, 61542), 'numpy.random.randn', 'randn', (['self.lambda_', 'N'], {}), '(self.lambda_, N)\n', (61525, 61542), False, 'from numpy.random import randn\n'), ((63472, 63482), 'numpy.linalg.norm', 'norm', (['xold'], {}), '(xold)\n', (63476, 63482), False, 'from numpy.linalg import norm\n'), ((63501, 63511), 'numpy.linalg.norm', 'norm', (['xnew'], {}), '(xnew)\n', (63505, 63511), False, 'from numpy.linalg import norm\n'), ((1138, 1190), 'os.path.join', 'os.path.join', (['recorddir', "('thread%02d' % self._thread)"], {}), "(recorddir, 'thread%02d' % self._thread)\n", (1150, 1190), False, 'import os\n'), ((1720, 1765), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': 'self._random_seed'}), '(seed=self._random_seed)\n', (1741, 1765), True, 'import numpy as np\n'), ((3867, 3884), 'numpy.sum', 'np.sum', (['do_mutate'], {}), '(do_mutate)\n', (3873, 3884), True, 'import numpy as np\n'), ((4249, 4267), 'numpy.argmax', 'np.argmax', (['fitness'], {}), '(fitness)\n', (4258, 4267), True, 'import numpy as np\n'), ((8771, 8819), 'numpy.concatenate', 'np.concatenate', (['(init_population, remainder_pop)'], {}), '((init_population, remainder_pop))\n', (8785, 8819), True, 'import numpy as np\n'), ((9974, 9993), 'os.mkdir', 'os.mkdir', (['recorddir'], {}), '(recorddir)\n', (9982, 9993), False, 'import os\n'), ((11493, 11509), 'numpy.sum', 'np.sum', (['nan_mask'], {}), '(nan_mask)\n', (11499, 11509), True, 'import numpy as np\n'), ((11564, 11582), 'numpy.sum', 'np.sum', (['valid_mask'], {}), '(valid_mask)\n', (11570, 11582), True, 'import numpy as np\n'), ((16118, 16134), 'numpy.sum', 'np.sum', (['nan_mask'], {}), '(nan_mask)\n', (16124, 16134), True, 'import numpy as np\n'), ((16189, 16207), 'numpy.sum', 'np.sum', (['valid_mask'], {}), '(valid_mask)\n', (16195, 16207), True, 'import numpy as np\n'), ((16506, 16530), 'numpy.argsort', 'np.argsort', (['valid_scores'], {}), '(valid_scores)\n', (16516, 16530), True, 'import numpy as np\n'), ((22987, 23029), 'numpy.array', 'np.array', (['self._curr_sample_ids'], {'dtype': 'str'}), '(self._curr_sample_ids, dtype=str)\n', (22995, 23029), True, 'import numpy as np\n'), ((23067, 23103), 'numpy.array', 'np.array', (['self._genealogy'], {'dtype': 'str'}), '(self._genealogy, dtype=str)\n', (23075, 23103), True, 'import numpy as np\n'), ((24806, 24821), 'numpy.log', 'log', (['(mu + 1 / 2)'], {}), '(mu + 1 / 2)\n', (24809, 24821), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((24924, 24933), 'numpy.floor', 'floor', (['mu'], {}), '(mu)\n', (24929, 24933), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((26866, 26873), 'numpy.sqrt', 'sqrt', (['N'], {}), '(N)\n', (26870, 26873), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((27670, 27688), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (27680, 27688), True, 'import numpy as np\n'), ((27776, 27795), 'numpy.argsort', 'np.argsort', (['(-scores)'], {}), '(-scores)\n', (27786, 27795), True, 'import numpy as np\n'), ((31785, 31861), 'os.path.join', 'os.path.join', (['self._recorddir', "('optimizer_state_block%03d.npz' % self._istep)"], {}), "(self._recorddir, 'optimizer_state_block%03d.npz' % self._istep)\n", (31797, 31861), False, 'import os\n'), ((33636, 33655), 'os.mkdir', 'os.mkdir', (['recorddir'], {}), '(recorddir)\n', (33644, 33655), False, 'import os\n'), ((35850, 35865), 'numpy.log', 'log', (['(mu + 1 / 2)'], {}), '(mu + 1 / 2)\n', (35853, 35865), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((35968, 35977), 'numpy.floor', 'floor', (['mu'], {}), '(mu)\n', (35973, 35977), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((37203, 37214), 'numpy.sqrt', 'sqrt', (['mueff'], {}), '(mueff)\n', (37207, 37214), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((37903, 37924), 'numpy.asarray', 'np.asarray', (['init_code'], {}), '(init_code)\n', (37913, 37924), True, 'import numpy as np\n'), ((38655, 38662), 'numpy.sqrt', 'sqrt', (['N'], {}), '(N)\n', (38659, 38662), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((39443, 39461), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (39453, 39461), True, 'import numpy as np\n'), ((39549, 39568), 'numpy.argsort', 'np.argsort', (['(-scores)'], {}), '(-scores)\n', (39559, 39568), True, 'import numpy as np\n'), ((44535, 44553), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (44545, 44553), True, 'import numpy as np\n'), ((44641, 44660), 'numpy.argsort', 'np.argsort', (['(-scores)'], {}), '(-scores)\n', (44651, 44660), True, 'import numpy as np\n'), ((48137, 48213), 'os.path.join', 'os.path.join', (['self._recorddir', "('optimizer_state_block%03d.npz' % self._istep)"], {}), "(self._recorddir, 'optimizer_state_block%03d.npz' % self._istep)\n", (48149, 48213), False, 'import os\n'), ((50375, 50394), 'os.mkdir', 'os.mkdir', (['recorddir'], {}), '(recorddir)\n', (50383, 50394), False, 'import os\n'), ((52777, 52792), 'numpy.log', 'log', (['(mu + 1 / 2)'], {}), '(mu + 1 / 2)\n', (52780, 52792), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((52895, 52904), 'numpy.floor', 'floor', (['mu'], {}), '(mu)\n', (52900, 52904), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((53625, 53636), 'numpy.sqrt', 'sqrt', (['mueff'], {}), '(mueff)\n', (53629, 53636), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((54641, 54662), 'numpy.asarray', 'np.asarray', (['init_code'], {}), '(init_code)\n', (54651, 54662), True, 'import numpy as np\n'), ((55444, 55451), 'numpy.sqrt', 'sqrt', (['N'], {}), '(N)\n', (55448, 55451), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((56181, 56199), 'numpy.argsort', 'np.argsort', (['scores'], {}), '(scores)\n', (56191, 56199), True, 'import numpy as np\n'), ((56287, 56306), 'numpy.argsort', 'np.argsort', (['(-scores)'], {}), '(-scores)\n', (56297, 56306), True, 'import numpy as np\n'), ((61720, 61727), 'numpy.sqrt', 'sqrt', (['N'], {}), '(N)\n', (61724, 61727), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((63350, 63365), 'numpy.cos', 'cos', (['angle_dist'], {}), '(angle_dist)\n', (63353, 63365), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((63375, 63390), 'numpy.sin', 'sin', (['angle_dist'], {}), '(angle_dist)\n', (63378, 63390), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((1210, 1234), 'os.path.isdir', 'os.path.isdir', (['recorddir'], {}), '(recorddir)\n', (1223, 1234), False, 'import os\n'), ((1252, 1271), 'os.mkdir', 'os.mkdir', (['recorddir'], {}), '(recorddir)\n', (1260, 1271), False, 'import os\n'), ((10683, 10726), 'os.path.join', 'os.path.join', (['self._init_population_dir', 'fn'], {}), '(self._init_population_dir, fn)\n', (10695, 10726), False, 'import os\n'), ((10728, 10755), 'os.path.join', 'os.path.join', (['recorddir', 'fn'], {}), '(recorddir, fn)\n', (10740, 10755), False, 'import os\n'), ((12848, 12872), 'numpy.argsort', 'np.argsort', (['valid_scores'], {}), '(valid_scores)\n', (12858, 12872), True, 'import numpy as np\n'), ((13422, 13473), 'numpy.exp', 'np.exp', (['((valid_scores - valid_scores[0]) / self._kT)'], {}), '((valid_scores - valid_scores[0]) / self._kT)\n', (13428, 13473), True, 'import numpy as np\n'), ((26608, 26625), 'numpy.diag', 'diag', (['(self.D ** 2)'], {}), '(self.D ** 2)\n', (26612, 26625), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((26693, 26709), 'numpy.diag', 'diag', (['(1 / self.D)'], {}), '(1 / self.D)\n', (26697, 26709), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((31690, 31744), 'os.path.join', 'os.path.join', (['self._recorddir', '"""optimizer_setting.npz"""'], {}), "(self._recorddir, 'optimizer_setting.npz')\n", (31702, 31744), False, 'import os\n'), ((34345, 34388), 'os.path.join', 'os.path.join', (['self._init_population_dir', 'fn'], {}), '(self._init_population_dir, fn)\n', (34357, 34388), False, 'import os\n'), ((34390, 34417), 'os.path.join', 'os.path.join', (['recorddir', 'fn'], {}), '(recorddir, fn)\n', (34402, 34417), False, 'import os\n'), ((37218, 37229), 'numpy.sqrt', 'sqrt', (['mueff'], {}), '(mueff)\n', (37222, 37229), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((37232, 37239), 'numpy.sqrt', 'sqrt', (['N'], {}), '(N)\n', (37236, 37239), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((40996, 41002), 'time.time', 'time', ([], {}), '()\n', (41000, 41002), False, 'from time import time\n'), ((41481, 41487), 'time.time', 'time', ([], {}), '()\n', (41485, 41487), False, 'from time import time\n'), ((46022, 46028), 'time.time', 'time', ([], {}), '()\n', (46026, 46028), False, 'from time import time\n'), ((46507, 46513), 'time.time', 'time', ([], {}), '()\n', (46511, 46513), False, 'from time import time\n'), ((48042, 48096), 'os.path.join', 'os.path.join', (['self._recorddir', '"""optimizer_setting.npz"""'], {}), "(self._recorddir, 'optimizer_setting.npz')\n", (48054, 48096), False, 'import os\n'), ((51084, 51127), 'os.path.join', 'os.path.join', (['self._init_population_dir', 'fn'], {}), '(self._init_population_dir, fn)\n', (51096, 51127), False, 'import os\n'), ((51129, 51156), 'os.path.join', 'os.path.join', (['recorddir', 'fn'], {}), '(recorddir, fn)\n', (51141, 51156), False, 'import os\n'), ((53640, 53651), 'numpy.sqrt', 'sqrt', (['mueff'], {}), '(mueff)\n', (53644, 53651), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((53654, 53661), 'numpy.sqrt', 'sqrt', (['N'], {}), '(N)\n', (53658, 53661), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((58368, 58382), 'numpy.linalg.norm', 'norm', (['vtan_old'], {}), '(vtan_old)\n', (58372, 58382), False, 'from numpy.linalg import norm\n'), ((58519, 58533), 'numpy.linalg.norm', 'norm', (['vtan_old'], {}), '(vtan_old)\n', (58523, 58533), False, 'from numpy.linalg import norm\n'), ((58573, 58587), 'numpy.linalg.norm', 'norm', (['vtan_new'], {}), '(vtan_new)\n', (58577, 58587), False, 'from numpy.linalg import norm\n'), ((60633, 60639), 'time.time', 'time', ([], {}), '()\n', (60637, 60639), False, 'from time import time\n'), ((3211, 3238), 'numpy.array', 'np.array', (['self._curr_images'], {}), '(self._curr_images)\n', (3219, 3238), True, 'import numpy as np\n'), ((16377, 16397), 'numpy.std', 'np.std', (['valid_scores'], {}), '(valid_scores)\n', (16383, 16397), True, 'import numpy as np\n'), ((28462, 28489), 'numpy.sqrt', 'sqrt', (['(cs * (2 - cs) * mueff)'], {}), '(cs * (2 - cs) * mueff)\n', (28466, 28489), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((28556, 28608), 'numpy.sqrt', 'sqrt', (['(1 - (1 - cs) ** (2 * self.counteval / lambda_))'], {}), '(1 - (1 - cs) ** (2 * self.counteval / lambda_))\n', (28560, 28608), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((37278, 37285), 'numpy.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (37282, 37285), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((40398, 40425), 'numpy.sqrt', 'sqrt', (['(cs * (2 - cs) * mueff)'], {}), '(cs * (2 - cs) * mueff)\n', (40402, 40425), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((45424, 45451), 'numpy.sqrt', 'sqrt', (['(cs * (2 - cs) * mueff)'], {}), '(cs * (2 - cs) * mueff)\n', (45428, 45451), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((53700, 53707), 'numpy.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (53704, 53707), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((57190, 57206), 'numpy.linalg.norm', 'norm', (['self.xmean'], {}), '(self.xmean)\n', (57194, 57206), False, 'from numpy.linalg import norm\n'), ((63588, 63605), 'numpy.linalg.norm', 'norm', (['x_symm_axis'], {}), '(x_symm_axis)\n', (63592, 63605), False, 'from numpy.linalg import norm\n'), ((10384, 10401), 'shutil.rmtree', 'rmtree', (['recorddir'], {}), '(recorddir)\n', (10390, 10401), False, 'from shutil import copyfile, rmtree\n'), ((10422, 10441), 'os.mkdir', 'os.mkdir', (['recorddir'], {}), '(recorddir)\n', (10430, 10441), False, 'import os\n'), ((12711, 12731), 'numpy.std', 'np.std', (['valid_scores'], {}), '(valid_scores)\n', (12717, 12731), True, 'import numpy as np\n'), ((24846, 24855), 'numpy.floor', 'floor', (['mu'], {}), '(mu)\n', (24851, 24855), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((28538, 28546), 'numpy.linalg.norm', 'norm', (['ps'], {}), '(ps)\n', (28542, 28546), False, 'from numpy.linalg import norm\n'), ((28671, 28698), 'numpy.sqrt', 'sqrt', (['(cc * (2 - cc) * mueff)'], {}), '(cc * (2 - cc) * mueff)\n', (28675, 28698), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((34046, 34063), 'shutil.rmtree', 'rmtree', (['recorddir'], {}), '(recorddir)\n', (34052, 34063), False, 'from shutil import copyfile, rmtree\n'), ((34084, 34103), 'os.mkdir', 'os.mkdir', (['recorddir'], {}), '(recorddir)\n', (34092, 34103), False, 'import os\n'), ((35890, 35899), 'numpy.floor', 'floor', (['mu'], {}), '(mu)\n', (35895, 35899), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((37672, 37699), 'numpy.sqrt', 'sqrt', (['((mueff - 1) / (N + 1))'], {}), '((mueff - 1) / (N + 1))\n', (37676, 37699), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((40468, 40495), 'numpy.sqrt', 'sqrt', (['(cc * (2 - cc) * mueff)'], {}), '(cc * (2 - cc) * mueff)\n', (40472, 40495), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((41150, 41162), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (41154, 41162), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((45494, 45521), 'numpy.sqrt', 'sqrt', (['(cc * (2 - cc) * mueff)'], {}), '(cc * (2 - cc) * mueff)\n', (45498, 45521), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((46176, 46188), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (46180, 46188), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((50785, 50802), 'shutil.rmtree', 'rmtree', (['recorddir'], {}), '(recorddir)\n', (50791, 50802), False, 'from shutil import copyfile, rmtree\n'), ((50823, 50842), 'os.mkdir', 'os.mkdir', (['recorddir'], {}), '(recorddir)\n', (50831, 50842), False, 'import os\n'), ((52817, 52826), 'numpy.floor', 'floor', (['mu'], {}), '(mu)\n', (52822, 52826), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((54094, 54121), 'numpy.sqrt', 'sqrt', (['((mueff - 1) / (N + 1))'], {}), '((mueff - 1) / (N + 1))\n', (54098, 54121), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((59279, 59306), 'numpy.sqrt', 'sqrt', (['(cc * (2 - cc) * mueff)'], {}), '(cc * (2 - cc) * mueff)\n', (59283, 59306), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60722, 60734), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (60726, 60734), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((24448, 24455), 'numpy.log2', 'log2', (['N'], {}), '(N)\n', (24452, 24455), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((26011, 26038), 'numpy.sqrt', 'sqrt', (['((mueff - 1) / (N + 1))'], {}), '((mueff - 1) / (N + 1))\n', (26015, 26038), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((30498, 30509), 'numpy.random.randn', 'randn', (['(1)', 'N'], {}), '(1, N)\n', (30503, 30509), False, 'from numpy.random import randn\n'), ((35492, 35499), 'numpy.log2', 'log2', (['N'], {}), '(N)\n', (35496, 35499), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((41323, 41335), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (41327, 41335), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((46349, 46361), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (46353, 46361), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((52419, 52426), 'numpy.log2', 'log2', (['N'], {}), '(N)\n', (52423, 52426), False, 'from numpy import exp, floor, log, log2, sqrt, zeros, eye, ones, diag\n'), ((59835, 59862), 'numpy.sqrt', 'sqrt', (['(cs * (2 - cs) * mueff)'], {}), '(cs * (2 - cs) * mueff)\n', (59839, 59862), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60895, 60907), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (60899, 60907), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((61093, 61099), 'time.time', 'time', ([], {}), '()\n', (61097, 61099), False, 'from time import time\n'), ((61201, 61207), 'numpy.eye', 'eye', (['N'], {}), '(N)\n', (61204, 61207), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((11699, 11730), 'numpy.array', 'np.array', (['self._curr_sample_idc'], {}), '(self._curr_sample_idc)\n', (11707, 11730), True, 'import numpy as np\n'), ((29255, 29263), 'numpy.linalg.norm', 'norm', (['ps'], {}), '(ps)\n', (29259, 29263), False, 'from numpy.linalg import norm\n'), ((40594, 40602), 'numpy.linalg.norm', 'norm', (['ps'], {}), '(ps)\n', (40598, 40602), False, 'from numpy.linalg import norm\n'), ((45620, 45628), 'numpy.linalg.norm', 'norm', (['ps'], {}), '(ps)\n', (45624, 45628), False, 'from numpy.linalg import norm\n'), ((41169, 41181), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (41173, 41181), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((41222, 41253), 'numpy.sqrt', 'sqrt', (['(1 + normv * c1 / (1 - c1))'], {}), '(1 + normv * c1 / (1 - c1))\n', (41226, 41253), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((46195, 46207), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (46199, 46207), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((46248, 46279), 'numpy.sqrt', 'sqrt', (['(1 + normv * c1 / (1 - c1))'], {}), '(1 + normv * c1 / (1 - c1))\n', (46252, 46279), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60741, 60753), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (60745, 60753), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60794, 60825), 'numpy.sqrt', 'sqrt', (['(1 + normv * c1 / (1 - c1))'], {}), '(1 + normv * c1 / (1 - c1))\n', (60798, 60825), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60211, 60218), 'numpy.sqrt', 'sqrt', (['N'], {}), '(N)\n', (60215, 60218), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((41349, 41361), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (41353, 41361), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((41410, 41441), 'numpy.sqrt', 'sqrt', (['(1 + normv * c1 / (1 - c1))'], {}), '(1 + normv * c1 / (1 - c1))\n', (41414, 41441), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((46375, 46387), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (46379, 46387), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((46436, 46467), 'numpy.sqrt', 'sqrt', (['(1 + normv * c1 / (1 - c1))'], {}), '(1 + normv * c1 / (1 - c1))\n', (46440, 46467), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60199, 60207), 'numpy.real', 'real', (['ps'], {}), '(ps)\n', (60203, 60207), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60921, 60933), 'numpy.sqrt', 'sqrt', (['(1 - c1)'], {}), '(1 - c1)\n', (60925, 60933), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n'), ((60982, 61013), 'numpy.sqrt', 'sqrt', (['(1 + normv * c1 / (1 - c1))'], {}), '(1 + normv * c1 / (1 - c1))\n', (60986, 61013), False, 'from numpy import exp, sqrt, real, eye, zeros, dot, cos, sin\n')]
import os import sys import csv import numpy as np # matplotlib import matplotlib.pyplot as plt; plt.rcdefaults() import matplotlib.pyplot as plt def run(path): d = {} for f in os.listdir(path): c_path = os.path.join(path, f) if '.pdf' not in c_path: with open(c_path, 'r') as of: # d[os.path.basename(of.name)] = {} csv_reader = csv.reader(of, delimiter=',') for row in csv_reader: if row[0] != 'total': if not d.get(row[0]): d[row[0]] = {} # d[os.path.basename(of.name)][row[0]] = [float(x) for x in row[1:]] d[row[0]][os.path.basename(of.name)] = [float(x) for x in row[1:]] print(d) build_graph(d, './graph.pdf'.format(sys.argv[1])) def build_graph(md, graph_path): # print(md) for run_nr, value in md.items(): for comp, value2 in value.items(): value2[1] = value2[0] - value2[1] del value2[-1] fig, ax = plt.subplots() ax.set_xticks([0., 0.5, 1.]) x_pos = np.arange(4) patterns = ('--', '\\\\', '///', '//') xticks_labels = [] s = 0.35 ss = 0.15 bars = [] l_comp = [] for index, comp in enumerate(md): value = md.get(comp) means = [] l_comp = [] yerr = [] comps = sorted([int(x) for x in value.keys()]) for run_nr_n in comps: run_nr_v = value.get(str(run_nr_n)) means.append(run_nr_v[0]) yerr.append(run_nr_v[1]) l_comp.append(int(''.join([n for n in str(run_nr_n) if n.isdigit()]))) print(means) print(yerr) bars.append(ax.bar(x_pos + ss, means, yerr=yerr, align='center', alpha=1., edgecolor='black', ecolor='black', capsize=10, hatch=patterns[index], color='white', width=s) ) ss = ss + s xticks_labels.append(comp if comp != 'nbi' else comp.upper()) ax.set_xlabel('Number of OSM NSs') ax.set_ylabel('Milliseconds - ms') ax.set_xticks(x_pos + s) ax.set_xticklabels(l_comp) leg = ax.legend(tuple(x[0] for x in bars), tuple(xticks_labels), labelspacing=1.5, handlelength=4, borderpad=1) leg.get_frame().set_linewidth(0.0) for patch in leg.get_patches(): patch.set_height(22) patch.set_y(-6) ax.yaxis.grid(False) # Save the plot in pdf plt.tight_layout() plt.savefig(graph_path) if __name__ == '__main__': if len(sys.argv) != 2: print('USAGE: python create_total_graph.py <folder>') exit(2) run(sys.argv[1])
[ "csv.reader", "os.path.join", "os.path.basename", "matplotlib.pyplot.subplots", "matplotlib.pyplot.rcdefaults", "numpy.arange", "matplotlib.pyplot.tight_layout", "os.listdir", "matplotlib.pyplot.savefig" ]
[((99, 115), 'matplotlib.pyplot.rcdefaults', 'plt.rcdefaults', ([], {}), '()\n', (113, 115), True, 'import matplotlib.pyplot as plt\n'), ((189, 205), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (199, 205), False, 'import os\n'), ((1075, 1089), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1087, 1089), True, 'import matplotlib.pyplot as plt\n'), ((1135, 1147), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (1144, 1147), True, 'import numpy as np\n'), ((2812, 2830), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2828, 2830), True, 'import matplotlib.pyplot as plt\n'), ((2835, 2858), 'matplotlib.pyplot.savefig', 'plt.savefig', (['graph_path'], {}), '(graph_path)\n', (2846, 2858), True, 'import matplotlib.pyplot as plt\n'), ((224, 245), 'os.path.join', 'os.path.join', (['path', 'f'], {}), '(path, f)\n', (236, 245), False, 'import os\n'), ((402, 431), 'csv.reader', 'csv.reader', (['of'], {'delimiter': '""","""'}), "(of, delimiter=',')\n", (412, 431), False, 'import csv\n'), ((729, 754), 'os.path.basename', 'os.path.basename', (['of.name'], {}), '(of.name)\n', (745, 754), False, 'import os\n')]
import yaml import numpy as np import os from tensorflow import keras from spektral.layers import * # Some helper functions def yaml_load(filename: str) -> dict: with open(filename, 'rt') as f: return yaml.load(f, Loader=yaml.CLoader) def yaml_write(filename: str, obj, mode='wt'): with open(filename, mode) as f: yaml.dump(obj, f) # Very bad way, but faster def get_section(filename: str, section: str): lines = [] with open(filename) as f: count = False for line in f.readlines(): if line.startswith(section): count = True continue if count: if str.isspace(line[0]): lines.append(line) else: return lines return lines class GraphDataGenerator(keras.utils.Sequence): 'Generates data for Keras' def __init__(self, data_root: str, filenames: list, labels: dict, batch_size: int=16, shuffle: bool=True): 'Initialization' self.data_root = data_root self.filenames = filenames self.labels = labels self.batch_size = batch_size self.shuffle = shuffle self.on_epoch_end() def __len__(self): 'Denotes the number of batches per epoch' return int(np.floor(len(self.filenames) / self.batch_size)) def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of files files = [self.filenames[idx] for idx in indexes] # Generate data graphs, features, speedups = self.__data_generation(files) return [features[:,0,:,:], graphs[:,0,:,:], features[:,1,:,:], graphs[:,1,:,:]], [speedups[:,0:4], speedups[:,4]] def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(len(self.filenames)) if self.shuffle: np.random.shuffle(self.indexes) def __data_generation(self, list_files): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Generate data graphs = [] features = [] labels = [] for f in list_files: filename = os.path.join(self.data_root, f'{f}.npz') np_loaded = np.load(filename, allow_pickle=True) graphs.append(np_loaded['graph']) features.append(np_loaded['feature']) label = self.labels[f] y_c = np.zeros(5) if label <= 0.996: y_c[0]=1 elif label > 0.996 and label < 1.0: y_c[1]=1 elif (label >= 1.0 and label < 1.15): y_c[2]=1 elif (label > 1.15): y_c[3]= 1 y_c[4] = label labels.append(y_c) graphs = np.stack(graphs) features = np.stack(features) labels = np.stack(labels) graphs[:,0,:,:] = GraphConv.preprocess(graphs[:,0,:,:]).astype('f4') graphs[:,1,:,:] = GraphConv.preprocess(graphs[:,1,:,:]).astype('f4') return graphs, features, labels
[ "numpy.stack", "yaml.load", "numpy.load", "yaml.dump", "numpy.zeros", "os.path.join", "numpy.random.shuffle" ]
[((215, 248), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml.CLoader'}), '(f, Loader=yaml.CLoader)\n', (224, 248), False, 'import yaml\n'), ((345, 362), 'yaml.dump', 'yaml.dump', (['obj', 'f'], {}), '(obj, f)\n', (354, 362), False, 'import yaml\n'), ((2959, 2975), 'numpy.stack', 'np.stack', (['graphs'], {}), '(graphs)\n', (2967, 2975), True, 'import numpy as np\n'), ((2995, 3013), 'numpy.stack', 'np.stack', (['features'], {}), '(features)\n', (3003, 3013), True, 'import numpy as np\n'), ((3031, 3047), 'numpy.stack', 'np.stack', (['labels'], {}), '(labels)\n', (3039, 3047), True, 'import numpy as np\n'), ((2028, 2059), 'numpy.random.shuffle', 'np.random.shuffle', (['self.indexes'], {}), '(self.indexes)\n', (2045, 2059), True, 'import numpy as np\n'), ((2344, 2384), 'os.path.join', 'os.path.join', (['self.data_root', 'f"""{f}.npz"""'], {}), "(self.data_root, f'{f}.npz')\n", (2356, 2384), False, 'import os\n'), ((2409, 2445), 'numpy.load', 'np.load', (['filename'], {'allow_pickle': '(True)'}), '(filename, allow_pickle=True)\n', (2416, 2445), True, 'import numpy as np\n'), ((2608, 2619), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (2616, 2619), True, 'import numpy as np\n')]
#xml reader functions for IRS 990 files. import xml.etree.ElementTree as ET import matplotlib.pyplot as plt import numpy as np import os def read_xml(file): ''' Reads an xml file to ElementTree Inputs: file: xml file Returns: ElementTree object ''' tree = ET.parse(file) root = tree.getroot() return root def print_xml(tree): ''' Prints xml file tag and content to screen. Inputs: ElementTree object Returns: nothing ''' for line in tree.iter(): print(line.tag,":", line.text) def clean_xml(tree): ''' Removes IRS website prefixes. Input: ElementTree object Returns: nothing ''' for line in tree.iter(): line.tag = line.tag.split('}')[1] return None def xml_to_dict(tree): ''' Takes ElementTree object and writes to a dictionary. Appends an additional count to repeated keys, as the IRS form repeats keys for many categories. Looking for better way to implement this. Input: ElementTree Object Returns: Dictionary of item tag and text. ''' items = {} count = 0 for line in tree.iter(): if label in items.keys(): label = label + str(count) + ":" items[label] = items.get(label, line.text) count += 1 else: items[label] = items.get(label, line.text) return items def write_long_labels(tree, prefix=None): ''' Add in section labels (the full path) to data. Input: ElementTree object Returns: nothing ''' if not prefix: tree.tag = tree.tag else: tree.tag = prefix + ":" + tree.tag for child in tree: write_long_labels(child, tree.tag) return None def search_tree(tree, tag, children=False): ''' Recursively searches tree for given tag and returns a dictionary of tag and text pairs. If children is true, will return all values for children of inputted tag. Input: tree: ElementTree object tag: given path or tag children: Boolean Output: dictionary with selected tags as keys and the texts as values. ''' g = {} if tag == tree.tag: if children: for child in list(tree): g[child.tag] = g.get(child.tag, child.text) else: g[tree.tag] = g.get(tree.tag, tree.text) else: for i in list(tree): r = search_tree(i, tag, children) g = {**r, **g} return g def search_tags(tree, keyword): ''' Takes in a key and returns list of tags that include that given keyword. Allows user to search for tag that may correspond to what they are looking for. Input: tree: ElementTree object keyword: text to search for in tags Returns: list of tags with keyword included ''' tags = set() if keyword.lower() in tree.tag.lower(): tags.add(tree.tag) for child in list(tree): result = search_tags(child, keyword) if result: tags.update(result) return list(tags) def filter_tree(trees, **kwargs): ''' Takes a list of trees and returns those only which meet parameters. Inputs: trees: a list of trees **kwargs: a list of filters to be applied to the trees Output: a list of filtered ElementTree objects ''' filtered_trees = [] for tree in trees: for key, value in kwargs.items(): check = search_tree(tree, key) if check[key] == value: filtered_trees.append(tree) return filtered_trees def aggregate(folder_path, *args): ''' Iterate through folder of 990s, applies given functions to them, and returns a list. Input: folder_path: system path to folder of 990s *args: functions to apply Output: list of ElementTree objects ''' forms = [] for file in os.listdir(folder_path): location = folder_path + "/" + file form = read_xml(location) for function in args: function(form) forms.append(form) return forms def averages(trees, tag, missingdata): ''' Returns the average value for the selected tag. Input: trees: list of ElementTree objects tag: selected tag missingdata: Boolean. If true, assigns non-entered data a zero or '' value and sample size is equal to population. If false, only uses data when a value was entered on the form and prints out number of forms with values used. Output: int ''' values = list_values(trees, tag, True, missingdata) return sum(values)/len(values) def plot_hist_values(values, missingdata=False): ''' Plots values of given tag across list of trees given. Inputs: values: list of values Returns: histogram ''' return plt.hist(values) def list_values(trees, tag, integers, missingdata): ''' Creates a list of values for given tag across a list of ElementTree objects Inputs: trees: list of ElementTree objects tag: a given tag integer: if values are integers, otherwise values are returned as strings missingdata: Boolean. If true, assigns non-entered data a zero or '' value and sample size is equal to population. If false, only uses data when a value was entered on the form and prints out number of forms with values used. Returns: list of values ''' values = [] n = len(trees) sample_size = 0 for tree in trees: val = search_tree(tree, tag) if missingdata: if len(val) == 0: (values.append(0) if integers else values.append('')) else: (values.append(int(val[tag])) if integers else values.append(val[tag])) else: if len(val) != 0: (values.append(int(val[tag])) if integers else values.append(val[tag])) sample_size += 1 if not missingdata: print("Out of {} given forms, {}, ({}%), had values".format( n, sample_size, (sample_size/n)*100)) return values def find_highest_forms(trees, tag, num_vals): ''' Returns list of ElementTree objects in which given tag values are highest. Allows us to examine seemingly abnormally high values for a specific organization. Input: trees: list of ElementTree objects tag: given tag number_wanted: number of highest values you want returned ''' filtered_trees = {} for tree in trees: check = search_tree(tree, tag) if len(check) != 0: filtered_trees[tree] = filtered_trees.get(tree, int(check[tag])) return sorted(filtered_trees, key=filtered_trees.get, reverse=True)[:num_vals] def get_quantiles(values, num_quantiles): ''' Returns list of tuples (quantile, value) Input: values: list of integers num_quantiles: list of percentiles, e.g., [0,.25, .5, .75, 1] ''' results = [] new_vals = np.array(values) for val in num_quantiles: amt = np.quantile(new_vals, val) results.append((val, amt)) return results
[ "xml.etree.ElementTree.parse", "numpy.quantile", "matplotlib.pyplot.hist", "numpy.array", "os.listdir" ]
[((299, 313), 'xml.etree.ElementTree.parse', 'ET.parse', (['file'], {}), '(file)\n', (307, 313), True, 'import xml.etree.ElementTree as ET\n'), ((4036, 4059), 'os.listdir', 'os.listdir', (['folder_path'], {}), '(folder_path)\n', (4046, 4059), False, 'import os\n'), ((5028, 5044), 'matplotlib.pyplot.hist', 'plt.hist', (['values'], {}), '(values)\n', (5036, 5044), True, 'import matplotlib.pyplot as plt\n'), ((7305, 7321), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (7313, 7321), True, 'import numpy as np\n'), ((7366, 7392), 'numpy.quantile', 'np.quantile', (['new_vals', 'val'], {}), '(new_vals, val)\n', (7377, 7392), True, 'import numpy as np\n')]
import sys from matplotlib.animation import FuncAnimation, PillowWriter import matplotlib.pyplot as plt import numpy as np def make_note(i, f, dy=5): X = np.linspace(i, i+1, 100) m1 = 100 + np.random.rand() * 100 m2 = np.random.rand() * 2 * np.pi m3 = np.random.normal(dy, 2) Y = f + (np.sin(X * m1 /(2*np.pi) + m2) + np.random.rand(X.size))*m3 return X, Y def plot_single(p, X, F, I, txt=[]): fig, ax = plt.subplots(1,2, figsize=(10,4.25)) for a in ax: a.spines['top'].set_visible(False) a.spines['right'].set_visible(False) a.set_xlim(-0.5, 8.5) ax[0].set_ylim(180, 420) ax[1].set_ylim(-50, 1250) for x, f in zip(X, F): ax[0].plot(*make_note(x, f, 2), '-k') ax[0].set_ylabel("Frequency / Hz") ax[0].set_xticks([]) if len(I): for x, i in zip(X, I): ax[1].plot(*make_note(x, i), '-k') ax[1].set_ylabel("Log Frequency ratio (interval) / cents") else: # fig.delaxes(ax[1]) ax[1].spines['bottom'].set_visible(False) ax[1].spines['left'].set_visible(False) ax[1].set_yticks([]) ax[1].set_xticks([]) yextra = [10, 30] if len(txt): for i, a in enumerate(ax): for x, y, t in zip(X, [F, I][i], txt): a.annotate(t, (x+0.2, y + yextra[i]), fontsize=14) fig.savefig(f"../Figures/scales_intro_{p}.pdf", bbox_inches='tight') fig.savefig(f"../Figures/scales_intro_{p}.png", bbox_inches='tight') def plot_series(): imaj = np.array([0, 200, 200, 100, 200, 200, 200, 100]) smaj = np.cumsum(imaj) fmaj = 200 * 2**(smaj/1200) X = np.arange(fmaj.size) plot_single(0, [X[0]], [fmaj[0]], []) plot_single(1, X, fmaj, []) plot_single(2, X, fmaj, smaj) plot_single(3, list(X) + [X[-1]], list(fmaj) + [fmaj[0]], list(smaj) + [smaj[0]]) txt = "CDEFGABCC" plot_single(4, list(X) + [X[-1]], list(fmaj) + [fmaj[0]], list(smaj) + [smaj[0]], txt=txt) def scale_evolution(): mut = {'color':'r', 'idx':[]} scale = [0, 200, 500, 700, 800, 1000, 1200] def mutate_scale(scale): cointoss = np.random.rand() N = len(scale) if cointoss < 0.1 and N < 12: # print('Insert') i = np.random.randint(N-1) + 1 scale.insert(i, np.mean(scale[i-1:i+1])) mut = {'color':'g', 'idx':[i]} elif cointoss < 0.2 and N > 3: i = np.random.randint(N-2) + 1 # print('Delete') scale.pop(i) mut = {'color':'g', 'idx':[]} else: # print('Mutate') i = np.random.randint(N-2) + 1 noise = np.random.normal(0, 30) scale[i] = scale[i] + noise mut = {'color':'b', 'idx':[i]} # print(scale) return scale, mut def plot_scale(scale, mut, i): fig, ax = plt.subplots() for j, s in enumerate(scale): if j in mut['idx']: ax.plot([s]*2, [0,1], '-', c=mut['color'], lw=3) else: ax.plot([s]*2, [0,1], '-k', lw=2) for d in ['top', 'bottom', 'left', 'right']: ax.spines[d].set_visible(False) ax.set_xticks([]) ax.set_yticks([]) fig.savefig(f"../Figures/Giffig/{i:03d}.png") plt.close() # inputs = [(scale, mut)] for i in range(40): plot_scale(scale, mut, i) scale, mut = mutate_scale(scale) # inputs.append((scale, mut)) # def update_animation(i): # plot_scale(ax, *inputs[i]) # plot_scale(ax, scale, mut) # anim = FuncAnimation(fig, update_animation, frames=np.arange(0, 40), interval=200) # writer = PillowWriter(fps=25) # anim.save('../tmp.gif', writer=writer) if __name__ == '__main__': plot_series() # scale_evolution()
[ "matplotlib.pyplot.close", "numpy.cumsum", "numpy.sin", "numpy.array", "numpy.arange", "numpy.random.normal", "numpy.linspace", "numpy.random.rand", "numpy.random.randint", "numpy.mean", "matplotlib.pyplot.subplots" ]
[((161, 187), 'numpy.linspace', 'np.linspace', (['i', '(i + 1)', '(100)'], {}), '(i, i + 1, 100)\n', (172, 187), True, 'import numpy as np\n'), ((271, 294), 'numpy.random.normal', 'np.random.normal', (['dy', '(2)'], {}), '(dy, 2)\n', (287, 294), True, 'import numpy as np\n'), ((437, 475), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(10, 4.25)'}), '(1, 2, figsize=(10, 4.25))\n', (449, 475), True, 'import matplotlib.pyplot as plt\n'), ((1534, 1582), 'numpy.array', 'np.array', (['[0, 200, 200, 100, 200, 200, 200, 100]'], {}), '([0, 200, 200, 100, 200, 200, 200, 100])\n', (1542, 1582), True, 'import numpy as np\n'), ((1594, 1609), 'numpy.cumsum', 'np.cumsum', (['imaj'], {}), '(imaj)\n', (1603, 1609), True, 'import numpy as np\n'), ((1651, 1671), 'numpy.arange', 'np.arange', (['fmaj.size'], {}), '(fmaj.size)\n', (1660, 1671), True, 'import numpy as np\n'), ((2149, 2165), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (2163, 2165), True, 'import numpy as np\n'), ((2888, 2902), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2900, 2902), True, 'import matplotlib.pyplot as plt\n'), ((3317, 3328), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3326, 3328), True, 'import matplotlib.pyplot as plt\n'), ((201, 217), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (215, 217), True, 'import numpy as np\n'), ((233, 249), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (247, 249), True, 'import numpy as np\n'), ((308, 341), 'numpy.sin', 'np.sin', (['(X * m1 / (2 * np.pi) + m2)'], {}), '(X * m1 / (2 * np.pi) + m2)\n', (314, 341), True, 'import numpy as np\n'), ((341, 363), 'numpy.random.rand', 'np.random.rand', (['X.size'], {}), '(X.size)\n', (355, 363), True, 'import numpy as np\n'), ((2271, 2295), 'numpy.random.randint', 'np.random.randint', (['(N - 1)'], {}), '(N - 1)\n', (2288, 2295), True, 'import numpy as np\n'), ((2326, 2353), 'numpy.mean', 'np.mean', (['scale[i - 1:i + 1]'], {}), '(scale[i - 1:i + 1])\n', (2333, 2353), True, 'import numpy as np\n'), ((2678, 2701), 'numpy.random.normal', 'np.random.normal', (['(0)', '(30)'], {}), '(0, 30)\n', (2694, 2701), True, 'import numpy as np\n'), ((2450, 2474), 'numpy.random.randint', 'np.random.randint', (['(N - 2)'], {}), '(N - 2)\n', (2467, 2474), True, 'import numpy as np\n'), ((2631, 2655), 'numpy.random.randint', 'np.random.randint', (['(N - 2)'], {}), '(N - 2)\n', (2648, 2655), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ run 9999: 8 6 [32, 32].int64 [[0 1 0 0 1 1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 1 0 1 0 0 1 0 0 1] [1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 1 0 1 0 1 1 0 1 0 1 1 1 0 1 0] [0 0 1 0 1 1 1 0 1 0 0 0 1 0 0 0 1 0 0 1 1 1 0 1 0 1 1 0 0 0 0 1] [1 1 1 0 0 0 1 0 1 0 1 1 0 1 1 1 0 1 0 1 0 0 0 1 1 0 1 0 1 1 0 1] [1 0 1 1 1 1 1 0 1 0 0 1 1 1 0 1 0 1 1 1 0 1 0 0 1 0 1 0 0 1 0 1] [1 0 0 0 0 0 0 1 0 1 1 0 0 0 0 1 1 0 0 0 1 0 1 1 1 0 0 1 0 1 1 0] [1 0 1 0 1 0 1 1 1 0 0 1 0 1 0 1 0 1 0 1 0 0 1 0 1 1 0 0 0 0 1 1] [1 0 1 0 1 0 0 0 1 0 1 0 0 1 1 0 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0] [0 1 0 0 0 1 1 1 0 0 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 0 1 0 1 1 0] [1 0 1 1 1 0 0 1 0 1 1 0 0 0 0 1 0 1 0 0 1 0 0 1 0 1 1 0 1 0 0 1] [0 1 0 1 0 1 0 0 0 1 0 1 1 0 1 0 0 1 1 0 1 1 0 1 0 1 1 0 0 0 1 1] [1 0 1 0 0 1 1 1 1 0 0 1 0 1 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 1 0 0] [1 0 0 1 0 1 0 1 0 1 0 1 0 0 0 1 0 1 0 1 1 1 1 1 1 0 1 1 0 1 1 0] [0 1 0 1 0 1 1 0 0 1 1 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 0 0 0 1 0 1] [0 1 0 1 0 1 0 0 1 0 1 0 0 1 1 1 1 0 1 0 1 0 1 0 1 0 0 1 1 0 1 1] [0 1 1 0 1 0 1 1 1 0 0 1 0 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 1 0 0 0] [1 0 0 1 0 0 0 1 0 1 0 1 1 1 1 0 1 0 1 1 0 1 0 1 1 1 1 0 0 1 0 1] [1 0 1 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1 0 0 1 0 0 1 0 0 0 1 0 1 0 1] [0 1 0 1 0 1 0 0 1 1 0 1 1 1 0 1 0 0 1 0 0 1 1 0 1 0 1 1 0 1 1 0] [0 1 0 1 0 1 1 1 0 0 0 1 0 0 1 0 1 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1] [1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 0 1 1 0 1 0 1 1 1 0 1 0 1 0 0 1 0] [0 0 0 1 1 1 1 1 0 1 1 0 1 1 0 1 0 0 0 1 1 0 0 0 0 1 0 1 1 1 1 0] [1 0 0 0 1 0 1 1 0 1 1 1 0 0 0 0 0 1 1 0 0 0 1 0 1 0 1 0 1 0 0 0] [1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 0 1 0 1 1 1 0 1 0 1 0 1 1 0 1 1] [0 1 1 0 0 1 0 0 0 1 1 0 0 1 0 1 0 0 0 1 0 0 1 0 0 1 1 0 1 0 0 1] [1 0 1 0 1 1 0 1 0 1 0 1 0 1 1 0 1 1 0 1 1 1 0 1 1 0 1 0 0 1 0 1] [0 1 1 0 1 0 1 1 1 0 0 1 0 1 1 0 0 1 1 0 0 0 1 1 0 1 1 1 0 1 1 1] [1 0 0 1 0 1 0 0 0 1 0 1 0 1 0 1 1 0 0 1 1 1 0 0 0 1 0 0 1 0 0 0] [1 1 1 0 1 1 1 1 1 0 0 1 1 0 1 0 0 1 1 1 0 1 0 1 0 0 1 0 0 0 1 0] [0 0 1 0 0 0 0 0 0 1 1 0 1 0 1 0 1 0 0 0 1 0 1 1 0 1 1 0 1 1 1 0] [1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0 1 1 0 0 0 1 0 0 0] [0 1 0 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1 1 0 0 1 1 0 0 1 1 1 1 0 1 1]] [178, 68, 152, 146, 141, 183, 107, 93, 116, 17, 185, 134, 71, 237, 138, 181, 125, 185, 46, 165, 129, 134, 209, 105, 213, 169, 74, 195, 21, 101, 57, 62, 226, 180, 110, 105, 157, 134, 146, 150, 42, 90, 182, 198, 229, 169, 138, 58, 169, 138, 250, 109, 106, 182, 6, 161, 42, 229, 85, 217, 214, 41, 105, 26, 137, 122, 173, 167, 181, 134, 146, 168, 42, 187, 100, 109, 234, 72, 173, 161, 7, 98, 235, 74, 248, 182, 24, 122, 209, 14, 70, 21, 139, 241, 186, 218, 38, 166, 72, 150, 181, 106, 187, 165, 214, 105, 198, 238, 41, 170, 57, 18, 247, 89, 174, 68, 4, 86, 209, 118, 173, 74, 148, 17, 138, 121, 103, 222] s = <b2449892 8db76b5d 7411b986 47ed8ab5 7db92ea5 8186d169 d5a94ac3 1565393e e2b46e69 9d869296 2a5ab6c6 e5a98a3a a98afa6d 6ab606a1 2ae555d9 d629691a 897aada7 b58692a8 2abb646d ea48ada1 0762eb4a f8b6187a d10e4615 8bf1bada 26a64896 b56abba5 d669c6ee 29aa3912 f759ae44 0456d176 ad4a9411 8a7967de> """ from __future__ import division, print_function import numpy as np import random np.set_printoptions(threshold=64*65, linewidth=200) def b2x2(): b = [] for i in range(4): for j in range(4): if i == j: continue xj = j % 2 yj = j // 2 xi = i % 2 yi = i // 2 a = np.zeros((2, 2), dtype=int) a[xi, yi] = 1 a[xj, yj] = 1 b.append(a) return b def block(n, b): assert n % 2 == 0 a = np.zeros((n // 2, n // 2), dtype=int) lut = [i % len(b) for i in range(n * n // 4)] random.shuffle(lut) def ind(x, y): return lut[y * n // 2 + x] for y in range(n // 2): for x in range(n // 2): k = ind(x, y) while True: ok = (x == 0 or k != a[y, x - 1]) and (y == 0 or k != a[y - 1, x]) if ok: break k = random.randint(0, len(b) - 1) a[y, x] = k return a def matrix(n): assert n % 2 == 0 a = np.zeros((n, n), dtype=int) b = b2x2() c = block(n, b) for y in range(n // 2): for x in range(n // 2): a[y * 2:y * 2 + 2, x * 2:x * 2 + 2] = b[c[y, x]] return a def fix(a): n = a.shape[0] # a9 = np.empty((n * 3, n * 3), dtype=int) # for y in range(3): # for x in range(3): # a9[y * n:(y + 1) * n, x * n:(x + 1) * n] = a def m(i): return i % n def S(a): return set(a.flatten().tolist()) def neig(y, x): y1 = min(y + 2, n) x1 = min(x + 2, n) s = S(a[y:y1, x:x1]) if y + 2 > n: s |= S(a[0: m(y + 2), x:x1]) if x + 2 > n: s |= S(a[y:y1, 0:m(x + 2)]) if y + 2 > n and x + 2 > n: s |= S(a[0:m(y + 2), 0:m(x + 2)]) return len(s) good = False for y in range(n): for x in range(n): if neig(y, x) > 1: continue # print('**1',) a[y, m(x + 1) % n], a[y, m(x + 2)] = a[y, m(x + 2)], a[y, m(x + 1)] if neig(y, x) > 1: continue # print('**2') a[y, m(x + 1)], a[y, m(x + 2)] = a[y, m(x + 2)], a[y, m(x + 1)] if neig(y, x) > 1: continue # print('**3') a[m(y + 1), m(x + 1)], a[m(y + 1), m(x + 2)] = a[m(y + 1), m(x + 2)], a[m(y + 1), m(x + 1)] if neig(y, x) > 1: continue # print('**4') a[m(y + 1), m(x + 1)], a[m(y + 1), m(x + 2)] = a[m(y + 1), m(x + 2)], a[m(y + 1), m(x + 1)] if neig(y, x) > 1: continue # print('**5') a[m(y + 1), m(x + 1)], a[m(y + 2), m(x + 2)] = a[m(y + 2), m(x + 2)], a[m(y + 1), m(x + 1)] if neig(y, x) > 1: continue # print('***') good = True return a, good def runs(a): n = a.shape[0] assert n >= 8 r = [] bad = 0 for x0 in range(-n, n): u = 1 b = [(0, x0)] k0 = -1 # print('!', x0) for z in range(1, 2*n): x = x0 + z y = z # print('$', y, x) if x < 0 or x >= n or y < 0 or y >= n: continue k = a[y, x] if k == k0: b.append((y, x)) u += 1 # print([y, x], k) else: r.append(u) u = 1 k0 = k r.append(u) for x0 in range(n, 2 * n): u = 0 k0 = -1 # print('!', x0) for z in range(1, 2 * n): x = x0 - z y = z # print('$', y, x) if x < 0 or x >= n or y < 0 or y >= n: continue k = a[y, x] if k == k0: u += 1 # print([y, x], k) else: r.append(u) u = 1 k0 = k r.append(u) for x0 in range(n): u = 1 k0 = a[0, x0] # print('!!!!!', x0) for y in range(1, n): k = a[y, x0] if k == k0: u += 1 # print([y, x], k) else: r.append(u) # print('#', u) u = 1 k0 = k r.append(u) for y0 in range(n): u = 1 k0 = a[y0, 0] # print('!', x0) for x in range(1, n): k = a[y0, x] if k == k0: u += 1 # print([y, x], k) else: r.append(u) u = 1 k0 = k r.append(u) # print(r) return max(r) def checker(n): best_a = None best_run = n + 1 for j in range(10000): a = matrix(n) for i in range(25): # print('-' * 20, i) a, good = fix(a) if good: break # print(type(a)) r = runs(a) if r < best_run: best_run = r best_a = a print('run %d: %d %d' % (j, r, best_run)) if best_run <= 3: break print('%s.%s' % (list(a.shape), a.dtype)) # for y in range(n): # for x in range(n): # a[y, x] = (x + y) % 2 return best_a def tohex(row): assert len(row) % 8 == 0 h = len(row) // 8 out = [] for i in range(h): x = 0 for j in range(8): if row[i * 8 + j]: x += 2 ** j out.append(x) return out def arrhex(a): out = [] for row in a: out.extend(tohex(row)) return out def tostr(a): for x in a: assert isinstance(x, int), (x, type(x)) s = ''.join('%02x' % x for x in a) chunks = [s[i:i + 8] for i in range(0, len(s), 8)] lines = [' '.join(chunks[i:i + 8]) for i in range(0, len(chunks), 8)] s = '\n'.join(lines) return '<%s>' % s random.seed(114) n = 32 a = checker(n) print(a) # for row in a: # print(' ', row) b = arrhex(a) print(b) s = tostr(b) print('s = %s' % s) print('zzzzzzz') print()
[ "numpy.zeros", "random.shuffle", "numpy.set_printoptions", "random.seed" ]
[((3343, 3396), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': '(64 * 65)', 'linewidth': '(200)'}), '(threshold=64 * 65, linewidth=200)\n', (3362, 3396), True, 'import numpy as np\n'), ((9312, 9328), 'random.seed', 'random.seed', (['(114)'], {}), '(114)\n', (9323, 9328), False, 'import random\n'), ((3794, 3831), 'numpy.zeros', 'np.zeros', (['(n // 2, n // 2)'], {'dtype': 'int'}), '((n // 2, n // 2), dtype=int)\n', (3802, 3831), True, 'import numpy as np\n'), ((3886, 3905), 'random.shuffle', 'random.shuffle', (['lut'], {}), '(lut)\n', (3900, 3905), False, 'import random\n'), ((4338, 4365), 'numpy.zeros', 'np.zeros', (['(n, n)'], {'dtype': 'int'}), '((n, n), dtype=int)\n', (4346, 4365), True, 'import numpy as np\n'), ((3628, 3655), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {'dtype': 'int'}), '((2, 2), dtype=int)\n', (3636, 3655), True, 'import numpy as np\n')]
from warnings import filters import numpy as np import tensorflow as tf from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization from tensorflow.keras.models import load_model, Model from tensorflow.keras.callbacks import ModelCheckpoint from Common import test_training_utils as ttu from ImageObjectDetectors.CNN4ImagesBase import CNN4ImagesBase from Common.DL_FilePaths import PROJECT_ROOT from tensorflow.keras.utils import get_custom_objects from Activations.Mish import mish physical_devices = tf.config.list_physical_devices('GPU') print(f"physical_devices: {physical_devices}") KERNEL_SIZE = (3, 3) STRIDE = 1 # PADDING = 'valid' PADDING = 'same' # Has to be same for ResNet blocks NUM_RESNET_BLOCKS_PER_FILTER_SIZE = 4 MAX_POOL_SIZE = (2, 2) class TensorflowResNet(CNN4ImagesBase): def __init__(self, input_shape, n_output, learning_rate=CNN4ImagesBase.DEFAULT_LEARNING_RATE, activation='relu', dropout=0.5, optimizer='sgd', n_start_filters=32, n_resnet_filter_blocks=2, n_resnet_blocks_per_filter_block=NUM_RESNET_BLOCKS_PER_FILTER_SIZE, default_seed=CNN4ImagesBase.DEFAULT_SEED, filename='tensorflow_deeper'): if activation == 'mish': # Add mish activation function: get_custom_objects().update({'mish': mish}) # Can't use in mac... # Use mixed precision: # policy = tf.keras.mixed_precision.Policy('mixed_float16') # tf.keras.mixed_precision.set_policy(policy) self.n_output = n_output self.activation = activation self.dropout = dropout self._optimizer = optimizer self.n_start_filters = n_start_filters self.num_resnet_filter_blocks = n_resnet_filter_blocks, self.num_resnet_blocks_per_filter_block = n_resnet_blocks_per_filter_block model_fn = self.get_full_model_filepath(model_filename=filename) self.checkpoint_callback = ModelCheckpoint( # filepath=f'{PROJECT_ROOT}/models/checkpoint_{model_fn}', filepath=f'{PROJECT_ROOT}/models/{model_fn}', save_weights_only=False, monitor='val_accuracy', mode='max', save_best_only=True, verbose=1 ) self.model = self.construct_model(input_shape, n_output, learning_rate, activation, dropout, n_resnet_filter_blocks, default_seed) def get_output_layer_and_loss(self, n_output): if n_output == 1: output_layer = Dense(units=1, activation='sigmoid', name='output_layer_binary') loss = 'binary_crossentropy' else: output_layer = Dense(units=n_output, activation='softmax', name='output_layer_categorical') loss = 'categorical_crossentropy' return output_layer, loss def get_optimizer(self, learning_rate): if self._optimizer.lower() == 'sgd': optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate) elif self._optimizer.lower() == 'adam': # optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate, amsgrad=True) optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) elif self._optimizer.lower() == 'nadam': optimizer = tf.keras.optimizers.Nadam(learning_rate=learning_rate) elif self._optimizer.lower() == 'rmsprop': optimizer = tf.keras.optimizers.RMSprop(learning_rate=learning_rate) else: optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate) return optimizer # Using Keras Functional API since ResNets aren't sequential: def construct_model(self, input_shape, n_output, learning_rate, activation, dropout, n_resnet_filter_blocks, default_seed): print(f'TF Keras backend: {tf.keras.backend}') with tf.device('/GPU:0'): kernel_init = tf.keras.initializers.glorot_uniform(seed=default_seed) print(f'Input Shape: {input_shape}') output_layer, loss = self.get_output_layer_and_loss(n_output) optimizer = self.get_optimizer(learning_rate) first_block_num_filters = self.n_start_filters * 2 inputs = Input(shape=input_shape) x = Conv2D(filters=self.n_start_filters, kernel_size=KERNEL_SIZE, strides=STRIDE, padding=PADDING, activation=activation, data_format='channels_last', kernel_initializer=kernel_init, name="Conv1")(inputs) x = Conv2D(filters=first_block_num_filters, kernel_size=KERNEL_SIZE, strides=STRIDE, padding=PADDING, activation=activation, data_format='channels_last', kernel_initializer=kernel_init, name="Conv2")(x) x = MaxPool2D(pool_size=MAX_POOL_SIZE)(x) block_num_filters = first_block_num_filters for filter_block in range(n_resnet_filter_blocks): for resnet_block in range(self.num_resnet_blocks_per_filter_block): x = self.resnet_block(x, block_num_filters, KERNEL_SIZE, STRIDE, PADDING, activation, kernel_init, f"ResNet_F_{filter_block + 1}_BLK_{resnet_block + 1}") if filter_block < n_resnet_filter_blocks - 1: # TODO: This doesn't work - you need intermediate layer to add next resnet block increase in layers # Update number of block filters: block_num_filters *= 2 # Intermediate layer to add filters: x = Conv2D(filters=block_num_filters, kernel_size=KERNEL_SIZE, strides=STRIDE, padding=PADDING, activation=activation, data_format='channels_last', kernel_initializer=kernel_init, name=f"ConvUpdateNumFilters_{block_num_filters}")(x) x = Conv2D(filters=first_block_num_filters, kernel_size=KERNEL_SIZE, strides=STRIDE, padding=PADDING, activation=activation, data_format='channels_last', kernel_initializer=kernel_init, name="ConvLast")(x) x = GlobalAveragePooling2D()(x) x = Dense(units=256, activation=activation)(x) x = Dropout(dropout)(x) outputs = output_layer(x) model = Model(inputs, outputs) model.compile(optimizer=optimizer, loss=loss, metrics=['accuracy']) model.summary() return model # With inspiration from: # https://adventuresinmachinelearning.com/introduction-resnet-tensorflow-2/ def resnet_block(self, input_data, n_filters, kernel_size, stride, padding, activation, kernel_initializer, name_prefix): x = Conv2D(filters=n_filters, kernel_size=kernel_size, strides=stride, padding=padding, activation=activation, data_format='channels_last', kernel_initializer=kernel_initializer, name=f'{name_prefix}_1_conv2D_{kernel_size[0]}x{kernel_size[1]}_{n_filters}')(input_data) x = BatchNormalization()(x) x = Conv2D(filters=n_filters, kernel_size=kernel_size, strides=stride, padding=padding, activation=None, # Activation will be applied after residual addition data_format='channels_last', kernel_initializer=kernel_initializer, name=f'{name_prefix}_2_conv2D_{kernel_size[0]}x{kernel_size[1]}_{n_filters}')(x) x = Add()([x, input_data]) x = Activation(activation)(x) return x def train(self, train_images, train_labels, batch_size, n_epochs, train_validation_split=0.2): X_train, X_val, y_train, y_val = ttu.split_train_validation_data(train_images, train_labels, train_validation_split) with tf.device('/GPU:0'): history = self.model.fit(x=X_train, y=y_train, epochs=n_epochs, batch_size=batch_size, validation_data=(X_val, y_val), callbacks=[self.checkpoint_callback]) # test_loss, test_accuracy = self.model.evaluate(X_val, y_val) # print(f"Test loss: {test_loss:0.4f}, " # f"Test accuracy: {test_accuracy:0.4f}") return history def train_all(self, train_gen, valid_gen, n_epochs, batch_size): with tf.device('/GPU:0'): history = self.model.fit(train_gen, epochs=n_epochs, batch_size=batch_size, validation_data=valid_gen, callbacks=[self.checkpoint_callback]) return history def predict_classes(self, input_data): # print(f"input data shape: {input_data.shape}") pred = self.model.predict(input_data) return np.argmax(pred, axis=1) def predict(self, input_data, flatten_output=False, one_hot=False): predictions = self.predict_classes(input_data) if one_hot: predictions = tf.one_hot(predictions, depth=self.n_output) if flatten_output: predictions = predictions.flatten() predictions = predictions.numpy() return predictions def get_full_model_filepath(self, model_filename): model_filename += f'_tf_d_{self.activation}_{self.dropout}_do_{self._optimizer}_{self.n_start_filters}_' + \ f'sf_bn_{self.num_resnet_filter_blocks}_rfb_{self.num_resnet_blocks_per_filter_block}_rbpfb' return model_filename def save_model(self, model_filename, rel_path='models', using_checkpoints=True): model_filepath = self.get_full_model_filepath(model_filename) if using_checkpoints: # Load best weights first: self.model = load_model(f'{PROJECT_ROOT}/{rel_path}/{model_filepath}') model_filename = self.add_file_type(model_filepath) self.model.save(f'{PROJECT_ROOT}/{rel_path}/{model_filename}', save_format='h5') def load_model(self, model_filename, rel_path='models', is_checkpoint=False): model_filepath = self.get_full_model_filepath(model_filename) if is_checkpoint: self.model = load_model(f'{PROJECT_ROOT}/{rel_path}/{model_filepath}') else: model_filename = self.add_file_type(model_filepath) self.model = load_model(f'{PROJECT_ROOT}/{rel_path}/{model_filename}')
[ "tensorflow.keras.layers.Dense", "numpy.argmax", "tensorflow.keras.utils.get_custom_objects", "tensorflow.keras.optimizers.SGD", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.keras.layers.MaxPool2D", "tensorflow.keras.initializers.glorot_uniform", "tensorflow.keras.optimizers.RMSprop", "...
[((582, 620), 'tensorflow.config.list_physical_devices', 'tf.config.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (613, 620), True, 'import tensorflow as tf\n'), ((2155, 2317), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': 'f"""{PROJECT_ROOT}/models/{model_fn}"""', 'save_weights_only': '(False)', 'monitor': '"""val_accuracy"""', 'mode': '"""max"""', 'save_best_only': '(True)', 'verbose': '(1)'}), "(filepath=f'{PROJECT_ROOT}/models/{model_fn}',\n save_weights_only=False, monitor='val_accuracy', mode='max',\n save_best_only=True, verbose=1)\n", (2170, 2317), False, 'from tensorflow.keras.callbacks import ModelCheckpoint\n'), ((8933, 9020), 'Common.test_training_utils.split_train_validation_data', 'ttu.split_train_validation_data', (['train_images', 'train_labels', 'train_validation_split'], {}), '(train_images, train_labels,\n train_validation_split)\n', (8964, 9020), True, 'from Common import test_training_utils as ttu\n'), ((10345, 10368), 'numpy.argmax', 'np.argmax', (['pred'], {'axis': '(1)'}), '(pred, axis=1)\n', (10354, 10368), True, 'import numpy as np\n'), ((2707, 2771), 'tensorflow.keras.layers.Dense', 'Dense', ([], {'units': '(1)', 'activation': '"""sigmoid"""', 'name': '"""output_layer_binary"""'}), "(units=1, activation='sigmoid', name='output_layer_binary')\n", (2712, 2771), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((2854, 2930), 'tensorflow.keras.layers.Dense', 'Dense', ([], {'units': 'n_output', 'activation': '"""softmax"""', 'name': '"""output_layer_categorical"""'}), "(units=n_output, activation='softmax', name='output_layer_categorical')\n", (2859, 2930), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((3125, 3177), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (3148, 3177), True, 'import tensorflow as tf\n'), ((4037, 4056), 'tensorflow.device', 'tf.device', (['"""/GPU:0"""'], {}), "('/GPU:0')\n", (4046, 4056), True, 'import tensorflow as tf\n'), ((4084, 4139), 'tensorflow.keras.initializers.glorot_uniform', 'tf.keras.initializers.glorot_uniform', ([], {'seed': 'default_seed'}), '(seed=default_seed)\n', (4120, 4139), True, 'import tensorflow as tf\n'), ((4408, 4432), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (4413, 4432), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((7331, 7353), 'tensorflow.keras.models.Model', 'Model', (['inputs', 'outputs'], {}), '(inputs, outputs)\n', (7336, 7353), False, 'from tensorflow.keras.models import load_model, Model\n'), ((7735, 8001), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'n_filters', 'kernel_size': 'kernel_size', 'strides': 'stride', 'padding': 'padding', 'activation': 'activation', 'data_format': '"""channels_last"""', 'kernel_initializer': 'kernel_initializer', 'name': 'f"""{name_prefix}_1_conv2D_{kernel_size[0]}x{kernel_size[1]}_{n_filters}"""'}), "(filters=n_filters, kernel_size=kernel_size, strides=stride, padding=\n padding, activation=activation, data_format='channels_last',\n kernel_initializer=kernel_initializer, name=\n f'{name_prefix}_1_conv2D_{kernel_size[0]}x{kernel_size[1]}_{n_filters}')\n", (7741, 8001), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((8152, 8172), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (8170, 8172), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((8188, 8448), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'n_filters', 'kernel_size': 'kernel_size', 'strides': 'stride', 'padding': 'padding', 'activation': 'None', 'data_format': '"""channels_last"""', 'kernel_initializer': 'kernel_initializer', 'name': 'f"""{name_prefix}_2_conv2D_{kernel_size[0]}x{kernel_size[1]}_{n_filters}"""'}), "(filters=n_filters, kernel_size=kernel_size, strides=stride, padding=\n padding, activation=None, data_format='channels_last',\n kernel_initializer=kernel_initializer, name=\n f'{name_prefix}_2_conv2D_{kernel_size[0]}x{kernel_size[1]}_{n_filters}')\n", (8194, 8448), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((8644, 8649), 'tensorflow.keras.layers.Add', 'Add', ([], {}), '()\n', (8647, 8649), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((8679, 8701), 'tensorflow.keras.layers.Activation', 'Activation', (['activation'], {}), '(activation)\n', (8689, 8701), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((9176, 9195), 'tensorflow.device', 'tf.device', (['"""/GPU:0"""'], {}), "('/GPU:0')\n", (9185, 9195), True, 'import tensorflow as tf\n'), ((9838, 9857), 'tensorflow.device', 'tf.device', (['"""/GPU:0"""'], {}), "('/GPU:0')\n", (9847, 9857), True, 'import tensorflow as tf\n'), ((10543, 10587), 'tensorflow.one_hot', 'tf.one_hot', (['predictions'], {'depth': 'self.n_output'}), '(predictions, depth=self.n_output)\n', (10553, 10587), True, 'import tensorflow as tf\n'), ((11305, 11362), 'tensorflow.keras.models.load_model', 'load_model', (['f"""{PROJECT_ROOT}/{rel_path}/{model_filepath}"""'], {}), "(f'{PROJECT_ROOT}/{rel_path}/{model_filepath}')\n", (11315, 11362), False, 'from tensorflow.keras.models import load_model, Model\n'), ((11716, 11773), 'tensorflow.keras.models.load_model', 'load_model', (['f"""{PROJECT_ROOT}/{rel_path}/{model_filepath}"""'], {}), "(f'{PROJECT_ROOT}/{rel_path}/{model_filepath}')\n", (11726, 11773), False, 'from tensorflow.keras.models import load_model, Model\n'), ((11877, 11934), 'tensorflow.keras.models.load_model', 'load_model', (['f"""{PROJECT_ROOT}/{rel_path}/{model_filename}"""'], {}), "(f'{PROJECT_ROOT}/{rel_path}/{model_filename}')\n", (11887, 11934), False, 'from tensorflow.keras.models import load_model, Model\n'), ((3344, 3397), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (3368, 3397), True, 'import tensorflow as tf\n'), ((4449, 4651), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'self.n_start_filters', 'kernel_size': 'KERNEL_SIZE', 'strides': 'STRIDE', 'padding': 'PADDING', 'activation': 'activation', 'data_format': '"""channels_last"""', 'kernel_initializer': 'kernel_init', 'name': '"""Conv1"""'}), "(filters=self.n_start_filters, kernel_size=KERNEL_SIZE, strides=\n STRIDE, padding=PADDING, activation=activation, data_format=\n 'channels_last', kernel_initializer=kernel_init, name='Conv1')\n", (4455, 4651), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((4840, 5045), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'first_block_num_filters', 'kernel_size': 'KERNEL_SIZE', 'strides': 'STRIDE', 'padding': 'PADDING', 'activation': 'activation', 'data_format': '"""channels_last"""', 'kernel_initializer': 'kernel_init', 'name': '"""Conv2"""'}), "(filters=first_block_num_filters, kernel_size=KERNEL_SIZE, strides=\n STRIDE, padding=PADDING, activation=activation, data_format=\n 'channels_last', kernel_initializer=kernel_init, name='Conv2')\n", (4846, 5045), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((5217, 5251), 'tensorflow.keras.layers.MaxPool2D', 'MaxPool2D', ([], {'pool_size': 'MAX_POOL_SIZE'}), '(pool_size=MAX_POOL_SIZE)\n', (5226, 5251), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((6769, 6977), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'first_block_num_filters', 'kernel_size': 'KERNEL_SIZE', 'strides': 'STRIDE', 'padding': 'PADDING', 'activation': 'activation', 'data_format': '"""channels_last"""', 'kernel_initializer': 'kernel_init', 'name': '"""ConvLast"""'}), "(filters=first_block_num_filters, kernel_size=KERNEL_SIZE, strides=\n STRIDE, padding=PADDING, activation=activation, data_format=\n 'channels_last', kernel_initializer=kernel_init, name='ConvLast')\n", (6775, 6977), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((7149, 7173), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'GlobalAveragePooling2D', ([], {}), '()\n', (7171, 7173), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((7193, 7232), 'tensorflow.keras.layers.Dense', 'Dense', ([], {'units': '(256)', 'activation': 'activation'}), '(units=256, activation=activation)\n', (7198, 7232), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((7252, 7268), 'tensorflow.keras.layers.Dropout', 'Dropout', (['dropout'], {}), '(dropout)\n', (7259, 7268), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n'), ((1487, 1507), 'tensorflow.keras.utils.get_custom_objects', 'get_custom_objects', ([], {}), '()\n', (1505, 1507), False, 'from tensorflow.keras.utils import get_custom_objects\n'), ((3471, 3525), 'tensorflow.keras.optimizers.Nadam', 'tf.keras.optimizers.Nadam', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (3496, 3525), True, 'import tensorflow as tf\n'), ((3601, 3657), 'tensorflow.keras.optimizers.RMSprop', 'tf.keras.optimizers.RMSprop', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (3628, 3657), True, 'import tensorflow as tf\n'), ((3696, 3748), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (3719, 3748), True, 'import tensorflow as tf\n'), ((6294, 6532), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': 'block_num_filters', 'kernel_size': 'KERNEL_SIZE', 'strides': 'STRIDE', 'padding': 'PADDING', 'activation': 'activation', 'data_format': '"""channels_last"""', 'kernel_initializer': 'kernel_init', 'name': 'f"""ConvUpdateNumFilters_{block_num_filters}"""'}), "(filters=block_num_filters, kernel_size=KERNEL_SIZE, strides=STRIDE,\n padding=PADDING, activation=activation, data_format='channels_last',\n kernel_initializer=kernel_init, name=\n f'ConvUpdateNumFilters_{block_num_filters}')\n", (6300, 6532), False, 'from tensorflow.keras.layers import Add, Activation, Input, Conv2D, MaxPool2D, Dense, Dropout, GlobalAveragePooling2D, BatchNormalization\n')]
from datasets import PartDataset import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim from kdtree import make_cKDTree import sys num_points = 2048 class KDNet(nn.Module): def __init__(self, k = 16): super(KDNet, self).__init__() self.conv1 = nn.Conv1d(3,8 * 3,1,1) self.conv2 = nn.Conv1d(8,32 * 3,1,1) self.conv3 = nn.Conv1d(32,64 * 3,1,1) self.conv4 = nn.Conv1d(64,64 * 3,1,1) self.conv5 = nn.Conv1d(64,64 * 3,1,1) self.conv6 = nn.Conv1d(64,128 * 3,1,1) self.conv7 = nn.Conv1d(128,256 * 3,1,1) self.conv8 = nn.Conv1d(256,512 * 3,1,1) self.conv9 = nn.Conv1d(512,512 * 3,1,1) self.conv10 = nn.Conv1d(512,512 * 3,1,1) self.conv11 = nn.Conv1d(512,1024 * 3,1,1) self.fc = nn.Linear(1024, k) def forward(self, x, c): def kdconv(x, dim, featdim, sel, conv): batchsize = x.size(0) # print(batchsize) x = F.relu(conv(x)) x = x.view(-1, featdim, 3, dim) x = x.view(-1, featdim, 3 * dim) sel = Variable(sel + (torch.arange(0, dim) * 3).long()) if x.is_cuda: sel = sel.cuda() x = torch.index_select(x, dim=2, index=sel) x = x.view(-1, featdim, dim / 2, 2) x = torch.squeeze(torch.max(x, dim=-1, keepdim=True)[0], 3) return x x1 = kdconv(x, 2048, 8, c[-1], self.conv1) x2 = kdconv(x1, 1024, 32, c[-2], self.conv2) x3 = kdconv(x2, 512, 64, c[-3], self.conv3) x4 = kdconv(x3, 256, 64, c[-4], self.conv4) x5 = kdconv(x4, 128, 64, c[-5], self.conv5) x6 = kdconv(x5, 64, 128, c[-6], self.conv6) x7 = kdconv(x6, 32, 256, c[-7], self.conv7) x8 = kdconv(x7, 16, 512, c[-8], self.conv8) x9 = kdconv(x8, 8, 512, c[-9], self.conv9) x10 = kdconv(x9, 4, 512, c[-10], self.conv10) x11 = kdconv(x10, 2, 1024, c[-11], self.conv11) x11 = x11.view(-1,1024) out = F.log_softmax(self.fc(x11)) return out def split_ps(point_set): #print point_set.size() num_points = point_set.size()[0]/2 diff = point_set.max(dim=0)[0] - point_set.min(dim=0)[0] dim = torch.max(diff, dim = 1)[1][0,0] cut = torch.median(point_set[:,dim])[0][0] left_idx = torch.squeeze(torch.nonzero(point_set[:,dim] > cut)) right_idx = torch.squeeze(torch.nonzero(point_set[:,dim] < cut)) middle_idx = torch.squeeze(torch.nonzero(point_set[:,dim] == cut)) if torch.numel(left_idx) < num_points: left_idx = torch.cat([left_idx, middle_idx[0:1].repeat(num_points - torch.numel(left_idx))], 0) if torch.numel(right_idx) < num_points: right_idx = torch.cat([right_idx, middle_idx[0:1].repeat(num_points - torch.numel(right_idx))], 0) left_ps = torch.index_select(point_set, dim = 0, index = left_idx) right_ps = torch.index_select(point_set, dim = 0, index = right_idx) return left_ps, right_ps, dim def split_ps_reuse(point_set, level, pos, tree, cutdim): sz = point_set.size() num_points = np.array(sz)[0]/2 max_value = point_set.max(dim=0)[0] min_value = -(-point_set).max(dim=0)[0] diff = max_value - min_value dim = torch.max(diff, dim = 1)[1][0,0] cut = torch.median(point_set[:,dim])[0][0] left_idx = torch.squeeze(torch.nonzero(point_set[:,dim] > cut)) right_idx = torch.squeeze(torch.nonzero(point_set[:,dim] < cut)) middle_idx = torch.squeeze(torch.nonzero(point_set[:,dim] == cut)) if torch.numel(left_idx) < num_points: left_idx = torch.cat([left_idx, middle_idx[0:1].repeat(num_points - torch.numel(left_idx))], 0) if torch.numel(right_idx) < num_points: right_idx = torch.cat([right_idx, middle_idx[0:1].repeat(num_points - torch.numel(right_idx))], 0) left_ps = torch.index_select(point_set, dim = 0, index = left_idx) right_ps = torch.index_select(point_set, dim = 0, index = right_idx) tree[level+1][pos * 2] = left_ps tree[level+1][pos * 2 + 1] = right_ps cutdim[level][pos * 2] = dim cutdim[level][pos * 2 + 1] = dim return d = PartDataset(root = 'shapenetcore_partanno_segmentation_benchmark_v0', classification = True, train = False) l = len(d) print(len(d.classes), l) levels = (np.log(num_points)/np.log(2)).astype(int) net = KDNet().cuda() #optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9) model_name = sys.argv[1] net.load_state_dict(torch.load(model_name)) net.eval() corrects = [] for j in range(len(d)): point_set, class_label = d[j] target = Variable(class_label).cuda() if target != 0: pass point_set = point_set[:num_points] if point_set.size(0) < num_points: point_set = torch.cat([point_set, point_set[0:num_points - point_set.size(0)]], 0) cutdim, tree = make_cKDTree(point_set.numpy(), depth=levels) cutdim_v = [(torch.from_numpy(np.array(item).astype(np.int64))) for item in cutdim] points = torch.FloatTensor(tree[-1]) points_v = Variable(torch.unsqueeze(torch.squeeze(points), 0)).transpose(2, 1).cuda() pred = net(points_v, cutdim_v) pred_choice = pred.data.max(1)[1] correct = pred_choice.eq(target.data).cpu().sum() corrects.append(correct) print("%d/%d , %f" %(j, len(d), float(sum(corrects))/ float(len(corrects)))) print(float(sum(corrects))/ float(len(d)))
[ "torch.median", "torch.numel", "numpy.log", "torch.autograd.Variable", "torch.load", "torch.nn.Conv1d", "torch.FloatTensor", "torch.nonzero", "torch.squeeze", "torch.index_select", "torch.max", "numpy.array", "torch.arange", "torch.nn.Linear", "datasets.PartDataset" ]
[((4294, 4399), 'datasets.PartDataset', 'PartDataset', ([], {'root': '"""shapenetcore_partanno_segmentation_benchmark_v0"""', 'classification': '(True)', 'train': '(False)'}), "(root='shapenetcore_partanno_segmentation_benchmark_v0',\n classification=True, train=False)\n", (4305, 4399), False, 'from datasets import PartDataset\n'), ((2954, 3006), 'torch.index_select', 'torch.index_select', (['point_set'], {'dim': '(0)', 'index': 'left_idx'}), '(point_set, dim=0, index=left_idx)\n', (2972, 3006), False, 'import torch\n'), ((3026, 3079), 'torch.index_select', 'torch.index_select', (['point_set'], {'dim': '(0)', 'index': 'right_idx'}), '(point_set, dim=0, index=right_idx)\n', (3044, 3079), False, 'import torch\n'), ((3989, 4041), 'torch.index_select', 'torch.index_select', (['point_set'], {'dim': '(0)', 'index': 'left_idx'}), '(point_set, dim=0, index=left_idx)\n', (4007, 4041), False, 'import torch\n'), ((4061, 4114), 'torch.index_select', 'torch.index_select', (['point_set'], {'dim': '(0)', 'index': 'right_idx'}), '(point_set, dim=0, index=right_idx)\n', (4079, 4114), False, 'import torch\n'), ((4621, 4643), 'torch.load', 'torch.load', (['model_name'], {}), '(model_name)\n', (4631, 4643), False, 'import torch\n'), ((5146, 5173), 'torch.FloatTensor', 'torch.FloatTensor', (['tree[-1]'], {}), '(tree[-1])\n', (5163, 5173), False, 'import torch\n'), ((361, 386), 'torch.nn.Conv1d', 'nn.Conv1d', (['(3)', '(8 * 3)', '(1)', '(1)'], {}), '(3, 8 * 3, 1, 1)\n', (370, 386), True, 'import torch.nn as nn\n'), ((405, 431), 'torch.nn.Conv1d', 'nn.Conv1d', (['(8)', '(32 * 3)', '(1)', '(1)'], {}), '(8, 32 * 3, 1, 1)\n', (414, 431), True, 'import torch.nn as nn\n'), ((450, 477), 'torch.nn.Conv1d', 'nn.Conv1d', (['(32)', '(64 * 3)', '(1)', '(1)'], {}), '(32, 64 * 3, 1, 1)\n', (459, 477), True, 'import torch.nn as nn\n'), ((496, 523), 'torch.nn.Conv1d', 'nn.Conv1d', (['(64)', '(64 * 3)', '(1)', '(1)'], {}), '(64, 64 * 3, 1, 1)\n', (505, 523), True, 'import torch.nn as nn\n'), ((542, 569), 'torch.nn.Conv1d', 'nn.Conv1d', (['(64)', '(64 * 3)', '(1)', '(1)'], {}), '(64, 64 * 3, 1, 1)\n', (551, 569), True, 'import torch.nn as nn\n'), ((588, 616), 'torch.nn.Conv1d', 'nn.Conv1d', (['(64)', '(128 * 3)', '(1)', '(1)'], {}), '(64, 128 * 3, 1, 1)\n', (597, 616), True, 'import torch.nn as nn\n'), ((635, 664), 'torch.nn.Conv1d', 'nn.Conv1d', (['(128)', '(256 * 3)', '(1)', '(1)'], {}), '(128, 256 * 3, 1, 1)\n', (644, 664), True, 'import torch.nn as nn\n'), ((683, 712), 'torch.nn.Conv1d', 'nn.Conv1d', (['(256)', '(512 * 3)', '(1)', '(1)'], {}), '(256, 512 * 3, 1, 1)\n', (692, 712), True, 'import torch.nn as nn\n'), ((731, 760), 'torch.nn.Conv1d', 'nn.Conv1d', (['(512)', '(512 * 3)', '(1)', '(1)'], {}), '(512, 512 * 3, 1, 1)\n', (740, 760), True, 'import torch.nn as nn\n'), ((780, 809), 'torch.nn.Conv1d', 'nn.Conv1d', (['(512)', '(512 * 3)', '(1)', '(1)'], {}), '(512, 512 * 3, 1, 1)\n', (789, 809), True, 'import torch.nn as nn\n'), ((829, 859), 'torch.nn.Conv1d', 'nn.Conv1d', (['(512)', '(1024 * 3)', '(1)', '(1)'], {}), '(512, 1024 * 3, 1, 1)\n', (838, 859), True, 'import torch.nn as nn\n'), ((881, 899), 'torch.nn.Linear', 'nn.Linear', (['(1024)', 'k'], {}), '(1024, k)\n', (890, 899), True, 'import torch.nn as nn\n'), ((2453, 2491), 'torch.nonzero', 'torch.nonzero', (['(point_set[:, dim] > cut)'], {}), '(point_set[:, dim] > cut)\n', (2466, 2491), False, 'import torch\n'), ((2522, 2560), 'torch.nonzero', 'torch.nonzero', (['(point_set[:, dim] < cut)'], {}), '(point_set[:, dim] < cut)\n', (2535, 2560), False, 'import torch\n'), ((2592, 2631), 'torch.nonzero', 'torch.nonzero', (['(point_set[:, dim] == cut)'], {}), '(point_set[:, dim] == cut)\n', (2605, 2631), False, 'import torch\n'), ((2644, 2665), 'torch.numel', 'torch.numel', (['left_idx'], {}), '(left_idx)\n', (2655, 2665), False, 'import torch\n'), ((2791, 2813), 'torch.numel', 'torch.numel', (['right_idx'], {}), '(right_idx)\n', (2802, 2813), False, 'import torch\n'), ((3488, 3526), 'torch.nonzero', 'torch.nonzero', (['(point_set[:, dim] > cut)'], {}), '(point_set[:, dim] > cut)\n', (3501, 3526), False, 'import torch\n'), ((3557, 3595), 'torch.nonzero', 'torch.nonzero', (['(point_set[:, dim] < cut)'], {}), '(point_set[:, dim] < cut)\n', (3570, 3595), False, 'import torch\n'), ((3627, 3666), 'torch.nonzero', 'torch.nonzero', (['(point_set[:, dim] == cut)'], {}), '(point_set[:, dim] == cut)\n', (3640, 3666), False, 'import torch\n'), ((3679, 3700), 'torch.numel', 'torch.numel', (['left_idx'], {}), '(left_idx)\n', (3690, 3700), False, 'import torch\n'), ((3826, 3848), 'torch.numel', 'torch.numel', (['right_idx'], {}), '(right_idx)\n', (3837, 3848), False, 'import torch\n'), ((1307, 1346), 'torch.index_select', 'torch.index_select', (['x'], {'dim': '(2)', 'index': 'sel'}), '(x, dim=2, index=sel)\n', (1325, 1346), False, 'import torch\n'), ((2342, 2364), 'torch.max', 'torch.max', (['diff'], {'dim': '(1)'}), '(diff, dim=1)\n', (2351, 2364), False, 'import torch\n'), ((2385, 2416), 'torch.median', 'torch.median', (['point_set[:, dim]'], {}), '(point_set[:, dim])\n', (2397, 2416), False, 'import torch\n'), ((3222, 3234), 'numpy.array', 'np.array', (['sz'], {}), '(sz)\n', (3230, 3234), True, 'import numpy as np\n'), ((3372, 3394), 'torch.max', 'torch.max', (['diff'], {'dim': '(1)'}), '(diff, dim=1)\n', (3381, 3394), False, 'import torch\n'), ((3420, 3451), 'torch.median', 'torch.median', (['point_set[:, dim]'], {}), '(point_set[:, dim])\n', (3432, 3451), False, 'import torch\n'), ((4448, 4466), 'numpy.log', 'np.log', (['num_points'], {}), '(num_points)\n', (4454, 4466), True, 'import numpy as np\n'), ((4467, 4476), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (4473, 4476), True, 'import numpy as np\n'), ((4745, 4766), 'torch.autograd.Variable', 'Variable', (['class_label'], {}), '(class_label)\n', (4753, 4766), False, 'from torch.autograd import Variable\n'), ((1425, 1459), 'torch.max', 'torch.max', (['x'], {'dim': '(-1)', 'keepdim': '(True)'}), '(x, dim=-1, keepdim=True)\n', (1434, 1459), False, 'import torch\n'), ((5078, 5092), 'numpy.array', 'np.array', (['item'], {}), '(item)\n', (5086, 5092), True, 'import numpy as np\n'), ((2756, 2777), 'torch.numel', 'torch.numel', (['left_idx'], {}), '(left_idx)\n', (2767, 2777), False, 'import torch\n'), ((2906, 2928), 'torch.numel', 'torch.numel', (['right_idx'], {}), '(right_idx)\n', (2917, 2928), False, 'import torch\n'), ((3791, 3812), 'torch.numel', 'torch.numel', (['left_idx'], {}), '(left_idx)\n', (3802, 3812), False, 'import torch\n'), ((3941, 3963), 'torch.numel', 'torch.numel', (['right_idx'], {}), '(right_idx)\n', (3952, 3963), False, 'import torch\n'), ((5214, 5235), 'torch.squeeze', 'torch.squeeze', (['points'], {}), '(points)\n', (5227, 5235), False, 'import torch\n'), ((1198, 1218), 'torch.arange', 'torch.arange', (['(0)', 'dim'], {}), '(0, dim)\n', (1210, 1218), False, 'import torch\n')]
import os import time import numpy def recall_2at1(score_list, k=1): num_correct = 0 num_total = len(score_list) for scores in score_list: ranking_index = numpy.argsort(-numpy.array(scores[0:2])) # Message at index 0 is always correct next message in our test data if 0 in ranking_index[:k]: num_correct += 1 return float(num_correct) / num_total def recall_at_k(labels, scores, k=1, doc_num=10): scores = scores.reshape(-1, doc_num) # [batch, doc_num] labels = labels.reshape(-1, doc_num) # # [batch, doc_num] sorted, indices = numpy.sort(scores, 1), numpy.argsort(-scores, 1) count_nonzero = 0 recall = 0 for i in range(indices.shape[0]): num_rel = numpy.sum(labels[i]) if num_rel==0: continue rel = 0 for j in range(k): if labels[i, indices[i, j]] == 1: rel += 1 recall += float(rel) / float(num_rel) count_nonzero += 1 return float(recall) / count_nonzero def precision_at_k(labels, scores, k=1, doc_num=10): scores = scores.reshape(-1,doc_num) # [batch, doc_num] labels = labels.reshape(-1,doc_num) # [batch, doc_num] sorted, indices = numpy.sort(scores, 1), numpy.argsort(-scores, 1) count_nonzero = 0 precision = 0 for i in range(indices.shape[0]): num_rel = numpy.sum(labels[i]) if num_rel==0: continue rel = 0 for j in range(k): if labels[i, indices[i, j]] == 1: rel += 1 precision += float(rel) / float(k) count_nonzero += 1 return precision / count_nonzero def MAP(target, logits, k=10): """ Compute mean average precision. :param target: 2d array [batch_size x num_clicks_per_query] true :param logits: 2d array [batch_size x num_clicks_per_query] pred :return: mean average precision [a float value] """ assert logits.shape == target.shape target = target.reshape(-1,k) logits = logits.reshape(-1,k) sorted, indices = numpy.sort(logits, 1)[::-1], numpy.argsort(-logits, 1) count_nonzero = 0 map_sum = 0 for i in range(indices.shape[0]): average_precision = 0 num_rel = 0 for j in range(indices.shape[1]): if target[i, indices[i, j]] == 1: num_rel += 1 average_precision += float(num_rel) / (j + 1) if num_rel==0: continue average_precision = average_precision / num_rel # print("average_precision: ", average_precision) map_sum += average_precision count_nonzero += 1 #return map_sum / indices.shape[0] return float(map_sum) / count_nonzero def MRR(target, logits, k=10): """ Compute mean reciprocal rank. :param target: 2d array [batch_size x rel_docs_per_query] :param logits: 2d array [batch_size x rel_docs_per_query] :return: mean reciprocal rank [a float value] """ assert logits.shape == target.shape target = target.reshape(-1,k) logits = logits.reshape(-1,k) sorted, indices = numpy.sort(logits, 1)[::-1], numpy.argsort(-logits, 1) count_nonzero=0 reciprocal_rank = 0 for i in range(indices.shape[0]): flag=0 for j in range(indices.shape[1]): if target[i, indices[i, j]] == 1: reciprocal_rank += float(1.0) / (j + 1) flag=1 break if flag: count_nonzero += 1 #return reciprocal_rank / indices.shape[0] return float(reciprocal_rank) / count_nonzero def NDCG(target, logits, k): """ Compute normalized discounted cumulative gain. :param target: 2d array [batch_size x rel_docs_per_query] :param logits: 2d array [batch_size x rel_docs_per_query] :return: mean average precision [a float value] """ assert logits.shape == target.shape target = target.reshape(-1,k) logits = logits.reshape(-1,k) assert logits.shape[1] >= k, 'NDCG@K cannot be computed, invalid value of K.' sorted, indices = numpy.sort(logits, 1)[::-1], numpy.argsort(-logits, 1) NDCG = 0 for i in range(indices.shape[0]): DCG_ref = 0 num_rel_docs = numpy.count_nonzero(target[i]) for j in range(indices.shape[1]): if j == k: break if target[i, indices[i, j]] == 1: DCG_ref += float(1.0) / numpy.log2(j + 2) DCG_gt = 0 for j in range(num_rel_docs): if j == k: break DCG_gt += float(1.0) / numpy.log2(j + 2) NDCG += DCG_ref / DCG_gt return float(NDCG) / indices.shape[0] if __name__=="__main__": pass
[ "numpy.count_nonzero", "numpy.sum", "numpy.log2", "numpy.argsort", "numpy.sort", "numpy.array" ]
[((597, 618), 'numpy.sort', 'numpy.sort', (['scores', '(1)'], {}), '(scores, 1)\n', (607, 618), False, 'import numpy\n'), ((620, 645), 'numpy.argsort', 'numpy.argsort', (['(-scores)', '(1)'], {}), '(-scores, 1)\n', (633, 645), False, 'import numpy\n'), ((739, 759), 'numpy.sum', 'numpy.sum', (['labels[i]'], {}), '(labels[i])\n', (748, 759), False, 'import numpy\n'), ((1221, 1242), 'numpy.sort', 'numpy.sort', (['scores', '(1)'], {}), '(scores, 1)\n', (1231, 1242), False, 'import numpy\n'), ((1244, 1269), 'numpy.argsort', 'numpy.argsort', (['(-scores)', '(1)'], {}), '(-scores, 1)\n', (1257, 1269), False, 'import numpy\n'), ((1366, 1386), 'numpy.sum', 'numpy.sum', (['labels[i]'], {}), '(labels[i])\n', (1375, 1386), False, 'import numpy\n'), ((2080, 2105), 'numpy.argsort', 'numpy.argsort', (['(-logits)', '(1)'], {}), '(-logits, 1)\n', (2093, 2105), False, 'import numpy\n'), ((3119, 3144), 'numpy.argsort', 'numpy.argsort', (['(-logits)', '(1)'], {}), '(-logits, 1)\n', (3132, 3144), False, 'import numpy\n'), ((4082, 4107), 'numpy.argsort', 'numpy.argsort', (['(-logits)', '(1)'], {}), '(-logits, 1)\n', (4095, 4107), False, 'import numpy\n'), ((4202, 4232), 'numpy.count_nonzero', 'numpy.count_nonzero', (['target[i]'], {}), '(target[i])\n', (4221, 4232), False, 'import numpy\n'), ((2051, 2072), 'numpy.sort', 'numpy.sort', (['logits', '(1)'], {}), '(logits, 1)\n', (2061, 2072), False, 'import numpy\n'), ((3090, 3111), 'numpy.sort', 'numpy.sort', (['logits', '(1)'], {}), '(logits, 1)\n', (3100, 3111), False, 'import numpy\n'), ((4053, 4074), 'numpy.sort', 'numpy.sort', (['logits', '(1)'], {}), '(logits, 1)\n', (4063, 4074), False, 'import numpy\n'), ((191, 215), 'numpy.array', 'numpy.array', (['scores[0:2]'], {}), '(scores[0:2])\n', (202, 215), False, 'import numpy\n'), ((4561, 4578), 'numpy.log2', 'numpy.log2', (['(j + 2)'], {}), '(j + 2)\n', (4571, 4578), False, 'import numpy\n'), ((4406, 4423), 'numpy.log2', 'numpy.log2', (['(j + 2)'], {}), '(j + 2)\n', (4416, 4423), False, 'import numpy\n')]
# -*- coding: utf-8 -*- import numpy as np from qupy.operator import X, Y, Z from scipy.sparse import csr_matrix, kron class Hamiltonian: """ Creats Hamiltonian as a sum of pauli terms. $ H = \sum_j coefs[j]*ops[j] $ Args: n_qubit (:class:`int`): Number of qubits. coefs (:class:`list`): list of floats. coefficient of each pauli terms. ops (:class:`list`): pauli terms each element of this argument is a str specifying the pauli term. e.g. ops[0] = "IIZZI" Attributes: n_qubit (:class:`int`): Number of qubits. coefs (:class:`list`): list of floats. coefficient of each pauli terms. ops (:class:`list`): pauli terms each element of this argument is a str specifying the pauli term. e.g. ops[0] = "IIZZI" """ def __init__(self, n_qubit, coefs=None, ops=None): self.n_qubit = n_qubit self.coefs = coefs if coefs is not None else [] self.ops = ops if ops is not None else [] def append(self, coef, op): """append(self, coef, op) appends an pauli term to the hamiltonian Args: coef (:class:`float`): coefficient of the term you want to add op (:class:`str`): pauli term represented by a string, e.g. "IIZZI" """ self.coefs.append(coef) self.ops.append(op) def get_matrix(self, ifdense=False): """get_matrix(self) get a matrix representation of the Hamiltonian Args: ifdense (:class:`Bool`): select sparse or dense. Default is False. Returns: :class:`scipy.sparse.csr_matrix` or `numpy.ndarray`: matrix representation of the Hamiltonian """ op = self.ops[0] coef = self.coefs[0] H = self._kron_N(*[self._get_sparse_pauli_matrix(c) for c in op]).multiply(coef) for coef, op in zip(self.coefs[1:], self.ops[1:]): H += self._kron_N(*[self._get_sparse_pauli_matrix(c) for c in op]).multiply(coef) if ifdense: H = H.toarray() return H def _get_sparse_pauli_matrix(self, pauli_char): if pauli_char == "I": return csr_matrix([[1, 0], [0, 1]]) elif pauli_char == "X": return csr_matrix(X) elif pauli_char == "Y": return csr_matrix(Y) elif pauli_char == "Z": return csr_matrix(Z) def _kron_N(self, *args): if len(args) > 2: return kron(args[0], self._kron_N(*args[1:])) elif len(args) == 2: return kron(args[0], args[1]) else: raise ValueError("kron_N needs at least 2 arguments.") def expect(q, H): """expect(q, H) calculates expectation value of H with respect to q Args: q (:class:`qupy.qubit.Qubits`): the state you want to take the expectation H (:class:`qupy.hamiltonian.Hamiltonian`) the Hamiltonian Return: :class:`float`: expectation value of H with respect to q """ assert q.size == H.n_qubit xp = q.xp ret = 0 org_data = np.copy(q.data) character = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' c_index = character[:q.size] subscripts = '{},{}'.format(c_index, c_index) for coef, op in zip(H.coefs, H.ops): for i in range(H.n_qubit): if op[i] == "I": pass elif op[i] == "X": q.gate(X, target=i) elif op[i] == "Y": q.gate(Y, target=i) elif op[i] == "Z": q.gate(Z, target=i) ret += coef * xp.real(xp.einsum(subscripts, np.conj(org_data), q.data)) q.set_state(np.copy(org_data)) return ret if __name__ == '__main__': from qubit import Qubits import qupy.operator as operator ham = Hamiltonian(3, coefs=[2, 1, 3], ops=["XII", "IYI", "IIZ"]) q = Qubits(3) q.set_state("101") q.gate(operator.H, target=0) q.gate(operator.H, target=1) q.gate(operator.S, target=1) print(q.get_state()) print(q.expect(ham)) print(expect(q, ham)) from scipy.sparse.linalg import eigsh from numpy.linalg import eigh ham_matrix = ham.get_matrix(ifdense=True) print(ham_matrix) eigvals, eigvecs = eigh(ham_matrix) # for sparse matrix #eigvals, eigvecs = eigsh(ham_matrix) print(eigvals)
[ "numpy.conj", "scipy.sparse.kron", "numpy.copy", "numpy.linalg.eigh", "scipy.sparse.csr_matrix", "qubit.Qubits" ]
[((3452, 3467), 'numpy.copy', 'np.copy', (['q.data'], {}), '(q.data)\n', (3459, 3467), True, 'import numpy as np\n'), ((4280, 4289), 'qubit.Qubits', 'Qubits', (['(3)'], {}), '(3)\n', (4286, 4289), False, 'from qubit import Qubits\n'), ((4669, 4685), 'numpy.linalg.eigh', 'eigh', (['ham_matrix'], {}), '(ham_matrix)\n', (4673, 4685), False, 'from numpy.linalg import eigh\n'), ((2490, 2518), 'scipy.sparse.csr_matrix', 'csr_matrix', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (2500, 2518), False, 'from scipy.sparse import csr_matrix, kron\n'), ((4066, 4083), 'numpy.copy', 'np.copy', (['org_data'], {}), '(org_data)\n', (4073, 4083), True, 'import numpy as np\n'), ((2572, 2585), 'scipy.sparse.csr_matrix', 'csr_matrix', (['X'], {}), '(X)\n', (2582, 2585), False, 'from scipy.sparse import csr_matrix, kron\n'), ((2889, 2911), 'scipy.sparse.kron', 'kron', (['args[0]', 'args[1]'], {}), '(args[0], args[1])\n', (2893, 2911), False, 'from scipy.sparse import csr_matrix, kron\n'), ((2639, 2652), 'scipy.sparse.csr_matrix', 'csr_matrix', (['Y'], {}), '(Y)\n', (2649, 2652), False, 'from scipy.sparse import csr_matrix, kron\n'), ((4017, 4034), 'numpy.conj', 'np.conj', (['org_data'], {}), '(org_data)\n', (4024, 4034), True, 'import numpy as np\n'), ((2706, 2719), 'scipy.sparse.csr_matrix', 'csr_matrix', (['Z'], {}), '(Z)\n', (2716, 2719), False, 'from scipy.sparse import csr_matrix, kron\n')]
from .. import material from .. import geometry import numpy import shapely from shapely.geometry import Polygon class upstreamWaterPressure: """ Attributes --------------------------------- fx:Horizontal force of upstream pressure fy:Vertical force of upstream pressure xFocus:Centroid's x-coordinate yFocus:Centroid's y-coordinate """ def __init__(self,damGeometry,water): if damGeometry.H>damGeometry.hu: self.fx=0.5*water.density*9.81*damGeometry.hu*damGeometry.hu self.fy=-0.5*water.density*9.81*damGeometry.hu*damGeometry.hu*(damGeometry.a/damGeometry.H) self.xFocus=(1/3)*damGeometry.a*damGeometry.hu/damGeometry.H self.yFocus=(1/3)*damGeometry.hu else: self.fx=0.5*water.density*9.81*damGeometry.hu*damGeometry.hu self.fy=-0.5*water.density*9.81*damGeometry.a*(2*damGeometry.hu-damGeometry.H) self.xFocus=(1/3)*damGeometry.a*(3*damGeometry.hu-2*damGeometry.H)/(2*damGeometry.hu-damGeometry.H) self.yFocus=(1/3)*damGeometry.hu class downstreamWaterPressure: """ Attributes --------------------------------- fx:Horizontal force of downstream pressure fy:Vertical force of downstream pressure xFocus:Centroid's x-coordinate yFocus:Centroid's y-coordinate **Assume that downstream water head is lower than h """ def __init__(self,damGeometry,water): self.fx=-0.5*water.density*9.81*damGeometry.hd*damGeometry.hd self.fy=-0.5*water.density*9.81*damGeometry.hd*damGeometry.hd*(damGeometry.b/damGeometry.h) self.xFocus=damGeometry.a+damGeometry.l+damGeometry.b-(1/3)*damGeometry.b*damGeometry.hd/damGeometry.h self.yFocus=(1/3)*damGeometry.hd class upliftForce: """ Attributes ---------------------- up:Tuples of the uplift pressure's shape upliftPolygon:Instance of shapely of up f:Magnitude of centroid uplift force x:Centroid force's x-center of uplift force """ def __init__(self,upliftPressure,damGeometry): self.uP=upliftPressure+[(damGeometry.a+damGeometry.l+damGeometry.b,0),(0,0)] self.upliftPolygon = Polygon(self.uP) self.f=self.upliftPolygon.area self.x=self.upliftPolygon.centroid.coords[:][0][0] class damGravity: ''' Attributes -------------------------- gravity:gravity of the dame x:Centroid's x-coordinate y:Centroid's y-coordinate ''' def __init__(self,sectionArea,sectionCentroid,concrete): self.gravity=-1*9.81*sectionArea.area*concrete.density self.x=sectionCentroid.xCentroid self.y=sectionCentroid.yCentroid class maxFriction: ''' Attributes -------------------- f:Friction on the dam's bottom face ''' def __init__(self,damGravity,upstreamWaterPressure,downstreamWaterPressure,upliftForce): self.f=-1*numpy.tan(40/180*numpy.pi)*(-1*damGravity.gravity-upstreamWaterPressure.fy-downstreamWaterPressure.fy-upliftForce.f)
[ "numpy.tan", "shapely.geometry.Polygon" ]
[((2243, 2259), 'shapely.geometry.Polygon', 'Polygon', (['self.uP'], {}), '(self.uP)\n', (2250, 2259), False, 'from shapely.geometry import Polygon\n'), ((2986, 3016), 'numpy.tan', 'numpy.tan', (['(40 / 180 * numpy.pi)'], {}), '(40 / 180 * numpy.pi)\n', (2995, 3016), False, 'import numpy\n')]
import unittest from qlearn import QLearn from action_state import ActionState import numpy as np class QlearnTest(unittest.TestCase): def testStateEquality(self): ai = QLearn([-1, 0, 1]) a1 = ActionState(1.0, 1.0, {'vol60': 1}) a2 = ActionState(1.0, 1.0, {'vol60': 1}) ai.learn(a1, 1, 1.0, a2) self.assertEqual(ai.getQAction(a2), 1) #def testQTableLookup(self): actions = [5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -7, -10, -15, -20] ai = QLearn(actions) ai.q = np.load('test_q.npy').item() ai.q state = ActionState(30, 0.9, {}) ai.q.get((state, -10)) print(ai.getQAction(state))
[ "qlearn.QLearn", "action_state.ActionState", "numpy.load" ]
[((487, 502), 'qlearn.QLearn', 'QLearn', (['actions'], {}), '(actions)\n', (493, 502), False, 'from qlearn import QLearn\n'), ((552, 576), 'action_state.ActionState', 'ActionState', (['(30)', '(0.9)', '{}'], {}), '(30, 0.9, {})\n', (563, 576), False, 'from action_state import ActionState\n'), ((183, 201), 'qlearn.QLearn', 'QLearn', (['[-1, 0, 1]'], {}), '([-1, 0, 1])\n', (189, 201), False, 'from qlearn import QLearn\n'), ((215, 250), 'action_state.ActionState', 'ActionState', (['(1.0)', '(1.0)', "{'vol60': 1}"], {}), "(1.0, 1.0, {'vol60': 1})\n", (226, 250), False, 'from action_state import ActionState\n'), ((264, 299), 'action_state.ActionState', 'ActionState', (['(1.0)', '(1.0)', "{'vol60': 1}"], {}), "(1.0, 1.0, {'vol60': 1})\n", (275, 299), False, 'from action_state import ActionState\n'), ((510, 531), 'numpy.load', 'np.load', (['"""test_q.npy"""'], {}), "('test_q.npy')\n", (517, 531), True, 'import numpy as np\n')]
import gym import numpy as np # Init environment env = gym.make("FrozenLake-v0") # you can set it to deterministic with: # env = gym.make("FrozenLake-v0", is_slippery=False) # If you want to try larger maps you can do this using: #random_map = gym.envs.toy_text.frozen_lake.generate_random_map(size=5, p=0.8) #env = gym.make("FrozenLake-v0", desc=random_map) # Init some useful variables: n_states = env.observation_space.n n_actions = env.action_space.n print(n_states) def value_iteration(max_iterations=10000): V_states = np.zeros(n_states) # init values as zero policy = V_states.copy() theta = 1e-8 gamma = 0.8 for i in range(max_iterations): last_V_states = V_states.copy() for state in range(n_states): action_values = [] for action in range(n_actions): state_value = 0 for action_step in env.P[state][action]: p, n_state, r, is_terminal = action_step state_value += p * (r + gamma * V_states[n_state]) action_values.append(state_value) best_action = np.argmax(np.asarray(action_values)) V_states[state] = action_values[best_action] policy[state] = best_action delta = np.abs(np.sum(np.array(V_states)) - np.sum(np.array(last_V_states))) if (delta < theta): print("#Steps to converge: ", i) print(np.round(np.array(V_states), 3)) break return np.array(policy).astype(int) # TODO: implement the value iteration algorithm and return the policy # Hint: env.P[state][action] gives you tuples (p, n_state, r, is_terminal), which tell you the probability p that you end up in the next state n_state and receive reward r def main(): # print the environment print("current environment: ") env.render() print("") # run the value iteration policy = value_iteration() print("Computed policy:") print(policy) # This code can be used to "rollout" a policy in the environment: print ("rollout policy:") maxiter = 100 state = env.reset() for i in range(maxiter): new_state, reward, done, info = env.step(policy[state]) env.render() state=new_state if done: print ("Finished episode") break if __name__ == "__main__": main()
[ "numpy.array", "numpy.asarray", "numpy.zeros", "gym.make" ]
[((56, 81), 'gym.make', 'gym.make', (['"""FrozenLake-v0"""'], {}), "('FrozenLake-v0')\n", (64, 81), False, 'import gym\n'), ((534, 552), 'numpy.zeros', 'np.zeros', (['n_states'], {}), '(n_states)\n', (542, 552), True, 'import numpy as np\n'), ((1513, 1529), 'numpy.array', 'np.array', (['policy'], {}), '(policy)\n', (1521, 1529), True, 'import numpy as np\n'), ((1134, 1159), 'numpy.asarray', 'np.asarray', (['action_values'], {}), '(action_values)\n', (1144, 1159), True, 'import numpy as np\n'), ((1288, 1306), 'numpy.array', 'np.array', (['V_states'], {}), '(V_states)\n', (1296, 1306), True, 'import numpy as np\n'), ((1317, 1340), 'numpy.array', 'np.array', (['last_V_states'], {}), '(last_V_states)\n', (1325, 1340), True, 'import numpy as np\n'), ((1443, 1461), 'numpy.array', 'np.array', (['V_states'], {}), '(V_states)\n', (1451, 1461), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Wed May 6 14:05:46 2020 Content: patially reuse code from ml-sound-classifier-master\..\realtime_predictor.py @author: magicalme """ # import scipy import numpy as np from librosa import feature, power_to_db from pyaudio import paContinue, PyAudio, paInt16 #import pandas as pd #import csv #import shutil #from os import listdir #from os.path import isfile, join # import struct from queue import Queue from array import array from collections import deque #import tensorflow as tf from tensorflow.keras import losses, models, optimizers from tensorflow.keras.activations import softmax from tensorflow.keras.layers import (Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense) from time import sleep, strftime from datetime import datetime from os import system import logging log = logging.getLogger('detect') log.setLevel(logging.DEBUG) log_handler = logging.StreamHandler() log.addHandler(log_handler) class Config(object): def __init__(self, sampling_rate=16000, audio_duration=2, n_classes=41, use_mfcc=False, n_folds=10, learning_rate=0.0001, max_epochs=50, n_mfcc=20): self.sampling_rate = sampling_rate self.audio_duration = audio_duration self.n_classes = n_classes self.use_mfcc = use_mfcc self.n_mfcc = n_mfcc self.n_folds = n_folds self.learning_rate = learning_rate self.max_epochs = max_epochs self.audio_length = self.sampling_rate * self.audio_duration if self.use_mfcc: self.dim = (self.n_mfcc, 1 + int(np.floor(self.audio_length/512)), 1) else: self.dim = (self.audio_length, 1) ''' def prepare_data_fileinput(file_path, config): X = np.empty(shape=(1, config.dim[0], config.dim[1], 1)) input_length = config.audio_length #print(file_path) data, _ = librosa.core.load(file_path, sr=config.sampling_rate, res_type="kaiser_fast") # Remove silence or noise or things like that # Random offset / Padding if len(data) > input_length: max_offset = len(data) - input_length offset = np.random.randint(max_offset) data = data[offset:(input_length+offset)] else: if input_length > len(data): max_offset = input_length - len(data) offset = np.random.randint(max_offset) else: offset = 0 data = np.pad(data, (offset, input_length - len(data) - offset), "constant") #data = librosa.feature.mfcc(data, sr=config.sampling_rate, n_mfcc=config.n_mfcc) S = librosa.feature.melspectrogram(data, sr=config.sampling_rate, n_fft=2048, hop_length=512, n_mels=config.n_mfcc) S_DB = librosa.power_to_db(S, ref=np.max) data = np.expand_dims(S_DB, axis=-1) X[0,] = data return X ''' def prepare_data_streaminput(data, config): X = np.empty(shape=(1, config.dim[0], config.dim[1], 1)) input_length = config.audio_length # Remove silence or noise or things like that # Random offset / Padding if len(data) > input_length: max_offset = len(data) - input_length offset = np.random.randint(max_offset) data = data[offset:(input_length+offset)] else: if input_length > len(data): max_offset = input_length - len(data) offset = np.random.randint(max_offset) else: offset = 0 data = np.pad(data, (offset, input_length - len(data) - offset), "constant") #data = librosa.feature.mfcc(data, sr=config.sampling_rate, n_mfcc=config.n_mfcc) S = feature.melspectrogram(data, sr=config.sampling_rate, n_fft=2048, hop_length=512, n_mels=config.n_mfcc) S_DB = power_to_db(S, ref=np.max) data = np.expand_dims(S_DB, axis=-1) X[0,] = data return X def get_2d_conv_model(config): nclass = config.n_classes inp = Input(shape=(config.dim[0],config.dim[1],1)) x = Convolution2D(32, (4,10), padding="same")(inp) x = BatchNormalization()(x) x = Activation("relu")(x) x = MaxPool2D()(x) x = Convolution2D(32, (4,10), padding="same")(x) x = BatchNormalization()(x) x = Activation("relu")(x) x = MaxPool2D()(x) x = Convolution2D(32, (4,10), padding="same")(x) x = BatchNormalization()(x) x = Activation("relu")(x) x = MaxPool2D()(x) x = Convolution2D(32, (4,10), padding="same")(x) x = BatchNormalization()(x) x = Activation("relu")(x) x = MaxPool2D()(x) x = Flatten()(x) x = Dense(64)(x) x = BatchNormalization()(x) x = Activation("relu")(x) out = Dense(nclass, activation=softmax)(x) model = models.Model(inputs=inp, outputs=out) opt = optimizers.Adam(config.learning_rate) model.compile(optimizer=opt, loss=losses.categorical_crossentropy, metrics=['acc']) return model ''' test_files_one_by_one("/test/Car_crash", "Car_crash") ''' ''' def test_files_one_by_one(file_path, class_name): model = get_2d_conv_model(config) file_names = [f for f in listdir(file_path) if isfile(join(file_path, f))] n = 0 t1 = time.time() for name in file_names: X_test = prepare_data_fileinput(file_path + "\\" + name, config) test_prediction = model.predict(X_test, batch_size=2, verbose=0) top1_max = np.array(LABELS)[np.argsort(-test_prediction, axis=1)[:, :1]] print("File_{} predicted {}".format(name, top1_max[0][0])) if(top1_max[0][0] in class_name): n = n + 1 print("Success/Total: {}/{}".format(n, len(file_names))) print("Accuracy %.2f %%" %(100 * n/len(file_names))) print("Done testing files!") t2 = time.time() print('Run time:', t2 - t1, '(s)') ''' def callback(in_data, frame_count, time_info, status): wave = array('h', in_data) raw_frames.put(wave, True) return (None, paContinue) def on_predicted(): global k global current_index if (len(pred_queue) == PRED_TIMES): label_indexes = [] predictions = [] for i in range(PRED_TIMES): predictions.append(pred_queue.popleft()) for pred in predictions: #label_index label_indexes.append(np.argsort(-pred, axis=1)[:, :1][0][0]) current_datetime = datetime.now() #if (current_index > -1): # print("{} {}".format(current_datetime.strftime("%Y-%m-%d %H:%M:%S"), LABELS[current_index])) if (current_index != label_indexes[0]): #print(1) #print(label_indexes) result = np.array(LABELS)[np.argsort(-predictions[0], axis=1)[:, :1]][0][0] log.info("-"*100) log.info("{} {} ({} %)".format(current_datetime.strftime("%Y-%m-%d %H:%M:%S"), result, round(100 * np.max(predictions[0])/np.sum(predictions[0]),2))) if (result != 'Back_ground'): system('echo 1 > /sys/class/gpio/gpio24/value') #else: # system('echo 0 > /sys/class/gpio/gpio24/value') # result = LABELS[0] # if(label_indexes[0] == 1 or label_indexes[0] == 2): # result = "Car" # elif(label_indexes[0] == 3 or label_indexes[0] == 4): # result = "Human" # elif(label_indexes[0] == 5): # result = "Danger" # print("{} {} ({} %)".format(current_datetime.strftime("%Y-%m-%d %H:%M:%S"), result, round(100 * np.max(predictions[0])/np.sum(predictions[0]),2))) current_index = label_indexes[0] number_of_results = len(label_indexes) if (label_indexes[1] != label_indexes[0]): #print(2) #print(label_indexes) top1_max = np.array(LABELS)[np.argsort(-predictions[1], axis=1)[:, :1]] log.info("-"*100) log.info("{} {} ({} %)".format(current_datetime.strftime("%Y-%m-%d %H:%M:%S"), top1_max[0][0], round(100 * np.max(predictions[1])/np.sum(predictions[1]),2))) if (top1_max != 'Back_ground'): system('echo 1 > /sys/class/gpio/gpio112/value') #else : # system('echo 0 > /sys/class/gpio/gpio112/value') # if(label_indexes[i + 1] == 1 or label_indexes[i + 1] == 2): # result = "Car" # elif(label_indexes[i + 1] == 3 or label_indexes[i + 1] == 4): # result = "Human" # elif(label_indexes[i + 1] == 5): # result = "Danger" # print("{} {} ({} %)".format(current_datetime.strftime("%Y-%m-%d %H:%M:%S"), result, round(100 * np.max(predictions[0])/np.sum(predictions[0]),2))) current_index = label_indexes[1] label_indexes = [] predictions = [] def main_process(model, on_predicted): # Pool audio data global raw_audio_buffer while not raw_frames.empty(): raw_audio_buffer.extend(raw_frames.get()) if len(raw_audio_buffer) >= MAX_NUMBER_SAMPLES: break if len(raw_audio_buffer) < MAX_NUMBER_SAMPLES: return # print("raw buffer: " + str(len(raw_audio_buffer))) audio_to_convert = np.array(raw_audio_buffer[:MAX_NUMBER_SAMPLES]) / 32767 # print(len(audio_to_convert)) # print("audio_to_convert: " + str(len(audio_to_convert))) # print(audio_to_convert) raw_audio_buffer = raw_audio_buffer[STEP_NUMBER_SAMPLES:] # print("raw buffer after convert: " + str(len(raw_audio_buffer))) X_test = prepare_data_streaminput(audio_to_convert, config) #test_prediction = models[0].predict(X_test, batch_size=1, verbose=0) test_predictions = model.predict(X_test, batch_size=1, verbose=0) ensemble_prediction = np.ones_like(test_predictions) ensemble_prediction = ensemble_prediction * test_predictions ensemble_prediction = ensemble_prediction**(1./len(test_predictions)) pred_queue.append(ensemble_prediction) on_predicted() def run_predictor(): # range(1) means ensamble learning is not used to get faster inference # model_0.h5 is the best one chosen among models # range(5) means we have 5 models and want to apply ensamble learning into these 5 models model = get_2d_conv_model(config) model.load_weights(MODEL_FOLDER + '/model_0.h5') #model.load_weights(MODEL_FOLDER + '/model_%d.h5'%i) # realtime recording audio = PyAudio() stream = audio.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, #input_device_index=0, frames_per_buffer=SAMPLES_PER_CHUNK, start=False, stream_callback=callback ) # print(audio.get_sample_size(FORMAT)) # sample_width = audio.get_sample_size(FORMAT) # main loop stream.start_stream() while stream.is_active(): main_process(model, on_predicted) sleep(0.001) stream.stop_stream() stream.close() # finish audio.terminate() exit(0) if __name__ == "__main__": DEBUG = False SAMPLES_PER_CHUNK = 4096 FORMAT = paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 2 # WAVE_OUTPUT_FILENAME = "recordings/" + strftime("%Y%m%d_%H%M%S") + "_output_" MODEL_FOLDER = "models" MAX_NUMBER_SAMPLES = RATE * RECORD_SECONDS # STEP_NUMBER_SAMPLES = 4410 # PRED_TIMES = 20 # STEP_NUMBER_SAMPLES = 5880 # PRED_TIMES = 15 # STEP_NUMBER_SAMPLES = 8820 # PRED_TIMES = 10 # STEP_NUMBER_SAMPLES = 11025 # PRED_TIMES = 8 # STEP_NUMBER_SAMPLES = 17640 # PRED_TIMES = 5 # STEP_NUMBER_SAMPLES = 22050 # PRED_TIMES = 4 STEP_NUMBER_SAMPLES = 44100 PRED_TIMES = 2 # STEP_NUMBER_SAMPLES = 88200 # PRED_TIMES = 1 ''' ['Back_ground','Car_crash','Car_passing_by','Clapping','Crowd_clapping','Screaming'] output new class names based on their index depending on the requirement 0 (Back_ground) 1 (Car_crash) ---> Danger 2 (Car) ---> Car 3 (Clapping) ---> Human 4 (Crowd_clapping) ---> Human 5 (Screaming) ---> Danger ''' #train = pd.read_csv("csv/label_original.csv") # LABELS=[] # f = open('csv/label_original.csv', 'r', encoding='utf-8') # train = csv.reader(f) # for line in train: # LABELS.append(line) #LABELS = list(train.label.unique()) #print(LABELS) LABELS = ['Back_ground', 'Car_crash', 'Car_passing_by', 'Clapping', 'Crowd_clapping', 'Screaming'] ''' these variables below are shared between recording thread and main thread (main process) ''' raw_frames = Queue(maxsize=100) raw_audio_buffer = [] pred_queue = deque(maxlen=PRED_TIMES) # save PRED_TIMES of results for every two seconds #50m audio_data_queue = deque(maxlen=PRED_TIMES) # write recording files in DEBUG mode config = Config(sampling_rate=44100, audio_duration=2, learning_rate=0.001, use_mfcc=True, n_mfcc=40, n_classes=len(LABELS)) k = 0 current_index = -1 run_predictor()
[ "numpy.sum", "tensorflow.keras.layers.Dense", "numpy.empty", "numpy.floor", "numpy.argsort", "librosa.power_to_db", "numpy.random.randint", "tensorflow.keras.layers.MaxPool2D", "librosa.feature.melspectrogram", "collections.deque", "tensorflow.keras.layers.Flatten", "tensorflow.keras.layers.Ba...
[((894, 921), 'logging.getLogger', 'logging.getLogger', (['"""detect"""'], {}), "('detect')\n", (911, 921), False, 'import logging\n'), ((966, 989), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (987, 989), False, 'import logging\n'), ((3055, 3107), 'numpy.empty', 'np.empty', ([], {'shape': '(1, config.dim[0], config.dim[1], 1)'}), '(shape=(1, config.dim[0], config.dim[1], 1))\n', (3063, 3107), True, 'import numpy as np\n'), ((3793, 3900), 'librosa.feature.melspectrogram', 'feature.melspectrogram', (['data'], {'sr': 'config.sampling_rate', 'n_fft': '(2048)', 'hop_length': '(512)', 'n_mels': 'config.n_mfcc'}), '(data, sr=config.sampling_rate, n_fft=2048,\n hop_length=512, n_mels=config.n_mfcc)\n', (3815, 3900), False, 'from librosa import feature, power_to_db\n'), ((3909, 3935), 'librosa.power_to_db', 'power_to_db', (['S'], {'ref': 'np.max'}), '(S, ref=np.max)\n', (3920, 3935), False, 'from librosa import feature, power_to_db\n'), ((3954, 3983), 'numpy.expand_dims', 'np.expand_dims', (['S_DB'], {'axis': '(-1)'}), '(S_DB, axis=-1)\n', (3968, 3983), True, 'import numpy as np\n'), ((4114, 4160), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(config.dim[0], config.dim[1], 1)'}), '(shape=(config.dim[0], config.dim[1], 1))\n', (4119, 4160), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4920, 4957), 'tensorflow.keras.models.Model', 'models.Model', ([], {'inputs': 'inp', 'outputs': 'out'}), '(inputs=inp, outputs=out)\n', (4932, 4957), False, 'from tensorflow.keras import losses, models, optimizers\n'), ((4969, 5006), 'tensorflow.keras.optimizers.Adam', 'optimizers.Adam', (['config.learning_rate'], {}), '(config.learning_rate)\n', (4984, 5006), False, 'from tensorflow.keras import losses, models, optimizers\n'), ((6099, 6118), 'array.array', 'array', (['"""h"""', 'in_data'], {}), "('h', in_data)\n", (6104, 6118), False, 'from array import array\n'), ((10333, 10363), 'numpy.ones_like', 'np.ones_like', (['test_predictions'], {}), '(test_predictions)\n', (10345, 10363), True, 'import numpy as np\n'), ((11039, 11048), 'pyaudio.PyAudio', 'PyAudio', ([], {}), '()\n', (11046, 11048), False, 'from pyaudio import paContinue, PyAudio, paInt16\n'), ((13543, 13561), 'queue.Queue', 'Queue', ([], {'maxsize': '(100)'}), '(maxsize=100)\n', (13548, 13561), False, 'from queue import Queue\n'), ((13607, 13631), 'collections.deque', 'deque', ([], {'maxlen': 'PRED_TIMES'}), '(maxlen=PRED_TIMES)\n', (13612, 13631), False, 'from collections import deque\n'), ((13718, 13742), 'collections.deque', 'deque', ([], {'maxlen': 'PRED_TIMES'}), '(maxlen=PRED_TIMES)\n', (13723, 13742), False, 'from collections import deque\n'), ((3337, 3366), 'numpy.random.randint', 'np.random.randint', (['max_offset'], {}), '(max_offset)\n', (3354, 3366), True, 'import numpy as np\n'), ((4168, 4210), 'tensorflow.keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(4, 10)'], {'padding': '"""same"""'}), "(32, (4, 10), padding='same')\n", (4181, 4210), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4224, 4244), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4242, 4244), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4257, 4275), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4267, 4275), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4288, 4299), 'tensorflow.keras.layers.MaxPool2D', 'MaxPool2D', ([], {}), '()\n', (4297, 4299), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4318, 4360), 'tensorflow.keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(4, 10)'], {'padding': '"""same"""'}), "(32, (4, 10), padding='same')\n", (4331, 4360), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4372, 4392), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4390, 4392), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4405, 4423), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4415, 4423), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4436, 4447), 'tensorflow.keras.layers.MaxPool2D', 'MaxPool2D', ([], {}), '()\n', (4445, 4447), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4466, 4508), 'tensorflow.keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(4, 10)'], {'padding': '"""same"""'}), "(32, (4, 10), padding='same')\n", (4479, 4508), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4520, 4540), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4538, 4540), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4553, 4571), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4563, 4571), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4584, 4595), 'tensorflow.keras.layers.MaxPool2D', 'MaxPool2D', ([], {}), '()\n', (4593, 4595), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4614, 4656), 'tensorflow.keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(4, 10)'], {'padding': '"""same"""'}), "(32, (4, 10), padding='same')\n", (4627, 4656), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4668, 4688), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4686, 4688), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4701, 4719), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4711, 4719), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4732, 4743), 'tensorflow.keras.layers.MaxPool2D', 'MaxPool2D', ([], {}), '()\n', (4741, 4743), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4758, 4767), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (4765, 4767), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4780, 4789), 'tensorflow.keras.layers.Dense', 'Dense', (['(64)'], {}), '(64)\n', (4785, 4789), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4802, 4822), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4820, 4822), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4835, 4853), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4845, 4853), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((4868, 4901), 'tensorflow.keras.layers.Dense', 'Dense', (['nclass'], {'activation': 'softmax'}), '(nclass, activation=softmax)\n', (4873, 4901), False, 'from tensorflow.keras.layers import Convolution2D, BatchNormalization, Flatten, MaxPool2D, Activation, Input, Dense\n'), ((6629, 6643), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (6641, 6643), False, 'from datetime import datetime\n'), ((9753, 9800), 'numpy.array', 'np.array', (['raw_audio_buffer[:MAX_NUMBER_SAMPLES]'], {}), '(raw_audio_buffer[:MAX_NUMBER_SAMPLES])\n', (9761, 9800), True, 'import numpy as np\n'), ((11616, 11628), 'time.sleep', 'sleep', (['(0.001)'], {}), '(0.001)\n', (11621, 11628), False, 'from time import sleep, strftime\n'), ((3540, 3569), 'numpy.random.randint', 'np.random.randint', (['max_offset'], {}), '(max_offset)\n', (3557, 3569), True, 'import numpy as np\n'), ((7288, 7335), 'os.system', 'system', (['"""echo 1 > /sys/class/gpio/gpio24/value"""'], {}), "('echo 1 > /sys/class/gpio/gpio24/value')\n", (7294, 7335), False, 'from os import system\n'), ((8209, 8225), 'numpy.array', 'np.array', (['LABELS'], {}), '(LABELS)\n', (8217, 8225), True, 'import numpy as np\n'), ((8574, 8622), 'os.system', 'system', (['"""echo 1 > /sys/class/gpio/gpio112/value"""'], {}), "('echo 1 > /sys/class/gpio/gpio112/value')\n", (8580, 8622), False, 'from os import system\n'), ((8226, 8261), 'numpy.argsort', 'np.argsort', (['(-predictions[1])'], {'axis': '(1)'}), '(-predictions[1], axis=1)\n', (8236, 8261), True, 'import numpy as np\n'), ((1702, 1735), 'numpy.floor', 'np.floor', (['(self.audio_length / 512)'], {}), '(self.audio_length / 512)\n', (1710, 1735), True, 'import numpy as np\n'), ((6935, 6951), 'numpy.array', 'np.array', (['LABELS'], {}), '(LABELS)\n', (6943, 6951), True, 'import numpy as np\n'), ((6551, 6576), 'numpy.argsort', 'np.argsort', (['(-pred)'], {'axis': '(1)'}), '(-pred, axis=1)\n', (6561, 6576), True, 'import numpy as np\n'), ((6952, 6987), 'numpy.argsort', 'np.argsort', (['(-predictions[0])'], {'axis': '(1)'}), '(-predictions[0], axis=1)\n', (6962, 6987), True, 'import numpy as np\n'), ((7188, 7210), 'numpy.sum', 'np.sum', (['predictions[0]'], {}), '(predictions[0])\n', (7194, 7210), True, 'import numpy as np\n'), ((8476, 8498), 'numpy.sum', 'np.sum', (['predictions[1]'], {}), '(predictions[1])\n', (8482, 8498), True, 'import numpy as np\n'), ((7165, 7187), 'numpy.max', 'np.max', (['predictions[0]'], {}), '(predictions[0])\n', (7171, 7187), True, 'import numpy as np\n'), ((8453, 8475), 'numpy.max', 'np.max', (['predictions[1]'], {}), '(predictions[1])\n', (8459, 8475), True, 'import numpy as np\n')]
import numpy as np from decimal import * from matplotlib.patches import Ellipse import matplotlib.transforms as transforms def gaussian_dec(x, m, var): ''' Computes the Gaussian pdf value (Decimal type) at x. x: value at which the pdf is computed (Decimal type) m: mean (Decimal type) var: variance ''' p = np.exp(-(x-m)**Decimal(2)/(Decimal(2)*Decimal(var)))/(np.sqrt(Decimal(2)*Decimal(np.pi)*Decimal(var))) return p def gaussian(x, m, var): ''' Computes the Gaussian pdf value at x. x: value at which the pdf is computed (Decimal type) m: mean var: variance ''' p = np.exp(-(x-m)**2/(2*var))/(np.sqrt(2*np.pi*var)) return p def laplace_dec(x, m, b): ''' Computes the Laplace pdf value (Decimal type) at x. x: value at which the pdf is computed (Decimal type) m: mean b: scale parameter ''' p = np.exp(-np.abs(x-m)/(Decimal(b)))/(Decimal(2)*Decimal(b)) return p def laplace(x, m, b): ''' Computes the Laplace pdf value at x. x: value at which the pdf is computed m: mean b: scale parameter ''' p = np.exp(-np.abs((x-m)/b))/(2*b) return p def bayesian_update(L, mu): ''' Computes the Bayesian update. L: likelihoods matrix mu: beliefs matrix ''' aux = L*mu bu = aux/aux.sum(axis = 1)[:, None] return bu def asl_bayesian_update(L, mu, delta): ''' Computes the adaptive Bayesian update. L: likelihoods matrix mu: beliefs matrix delta: step size ''' aux = L**(delta)*mu**(1-delta) bu = aux/aux.sum(axis = 1)[:, None] return bu def DKL(m,n,dx): ''' Computes the KL divergence between m and n. m: true distribution in vector form n: second distribution in vector form dx : sample size ''' mn = m/n mnlog = np.log(mn) return np.sum(m*dx*mnlog) def decimal_array(arr): ''' Converts an array to an array of Decimal objects. arr: array to be converted ''' if len(arr.shape) == 1: return np.array([Decimal(y) for y in arr]) else: return np.array([[Decimal(x) for x in y] for y in arr]) def float_array(arr): ''' Converts an array to an array of float objects. arr: array to be converted ''' if len(arr.shape)==1: return np.array([float(y) for y in arr]) else: return np.array([[float(x) for x in y] for y in arr]) def asl_markov(mu_0, csi, A, N_ITER, theta, b, delta = 0): ''' Executes the adaptive social learning algorithm with Laplace likelihoods for the Markovian example mu_0: initial beliefs csi: observations A: list of combination matrices N_ITER: number of iterations theta: vector of means for the Laplace likelihoods b: scale parameter of the Laplace likelihoods delta: step size ''' mu = mu_0.copy() N = len(A[0]) MU = [mu] for i in range(N_ITER): L_i = np.array([laplace(csi[:,i], t, b) for t in theta]).T # unindentifiability L_i[:N//3, 1] = L_i[:N//3, 0] L_i[N//3:2*N//3, 1] = L_i[N//3:2*N//3, 2] L_i[2*N//3:, 2] = L_i[2*N//3:, 0] psi = asl_bayesian_update(L_i, mu, delta) decpsi = np.log(psi) mu = np.exp((A[i].T).dot(decpsi)) / np.sum(np.exp((A[i].T).dot(decpsi)), axis=1)[:, None] MU.append(mu) return MU def sl_markov(mu_0, csi, A, N_ITER, thetadec, b): ''' Executes the social learning algorithm with Laplace likelihoods for the Markovian example mu_0: initial beliefs csi: observations A: Combination matrix N_ITER: number of iterations thetadec: vector of means for the Laplace likelihoods (Decimal type) b: scale parameter of the Laplace likelihoods is_gaussian: flag indicating if the likelihoods are Gaussian ''' mu = decimal_array(mu_0) N = len(A[0]) MU = [mu] for i in range(N_ITER): L_i = np.array([laplace_dec(csi[:,i], t, b) for t in thetadec]).T # unindentifiability L_i[:N//3, 1] = L_i[:N//3, 0] L_i[N//3:2*N//3, 1] = L_i[N//3:2*N//3, 2] L_i[2*N//3:, 2] = L_i[2*N//3:, 0] psi = bayesian_update(L_i, mu) decpsi = np.array([[x.ln() for x in y] for y in psi]) C = decimal_array(A[i]) mu = np.exp((C.T).dot(decpsi)) / np.sum(np.exp((C.T).dot(decpsi)), axis=1)[:, None] MU.append(mu) return MU def asl(mu_0, csi, A, N_ITER, theta, var, delta = 0, is_gaussian = False): ''' Executes the adaptive social learning algorithm with Gaussian or Laplace likelihoods. mu_0: initial beliefs csi: observations A: Combination matrix N_ITER: number of iterations theta: vector of means for the likelihoods var: variance of Gaussian likelihoods/ scale parameter of the Laplace likelihoods delta: step size is_gaussian: flag indicating if the likelihoods are Gaussian ''' mu = mu_0.copy() N = len(A) MU = [mu] for i in range(N_ITER): if is_gaussian: L_i = np.array([gaussian(csi[:, i], t, var) for t in theta]).T else: L_i = np.array([laplace(csi[:, i], t, var) for t in theta]).T # unindentifiability L_i[:N//3, 1] = L_i[:N//3, 0] L_i[N//3:2*N//3, 1] = L_i[N//3:2*N//3, 2] L_i[2*N//3:, 2] = L_i[2*N//3:, 0] psi = asl_bayesian_update(L_i, mu, delta) decpsi = np.log(psi) mu = np.exp((A.T).dot(decpsi)) / np.sum(np.exp((A.T).dot(decpsi)), axis=1)[:, None] MU.append(mu) return MU def sl(mu_0, csi, A, N_ITER, thetadec, var, is_gaussian = False): ''' Executes the social learning algorithm with Gaussian or Laplace likelihoods. mu_0: initial beliefs csi: observations A: Combination matrix N_ITER: number of iterations thetadec: vector of means for the likelihoods (Decimal type) var: variance of Gaussian likelihoods/ scale parameter of the Laplace likelihoods is_gaussian: flag indicating if the likelihoods are Gaussian ''' mu = mu_0.copy() N = len(A) MU = [mu] for i in range(N_ITER): if is_gaussian: L_i = np.array([gaussian_dec(csi[:, i], t, var) for t in thetadec]).T else: L_i = np.array([laplace_dec(csi[:, i], t, var) for t in thetadec]).T # unindentifiability L_i[:N//3, 1] = L_i[:N//3, 0] L_i[N//3:2*N//3, 1] = L_i[N//3:2*N//3, 2] L_i[2*N//3:, 2] = L_i[2*N//3:, 0] psi = bayesian_update(L_i, mu) decpsi = np.array([[x.ln() for x in y] for y in psi]) mu = np.exp((A.T).dot(decpsi)) / np.sum(np.exp((A.T).dot(decpsi)), axis =1)[:, None] MU.append(mu) return MU def comb_matrix_from_p(p, G): ''' Computes combination matrix from the Perron eigenvector and graph specification. G: adjacency matrix p: Perron eigenvector ''' A = np.where(G > 0, (p.T * np.ones((10,1))).T, 0) np.fill_diagonal(A, 1 - np.sum(A - np.diag(np.diag(A)), axis=0)) return A def lmgf(thetazero, theta1, t): ''' Computes the LMGF for the family of Laplace distributions, specified in section VIII. C. thetazero: true state of nature theta1: state different than true state t: vector of real values ''' alpha = theta1 - thetazero if thetazero >= theta1: f = np.log(np.exp(alpha * (t + 1)) + np.exp(-alpha * t) - np.exp(alpha / 2) * np.sinh(alpha*(t + 1/2))/(t + 1/2)) - np.log(2) elif thetazero<theta1: f = np.log(np.exp(-alpha * (t + 1)) + np.exp(alpha * t) + np.exp(-alpha / 2) * np.sinh(alpha*(t + 1/2))/(t + 1/2)) - np.log(2) return f def Cave(L, t1, t2, dt): ''' Computes the covariance between the log likelihood ratios for two hypotheses. L: likelihood Functions t1: hypothesis 1 t2: hypothesis 2 dt: step size ''' aux = L[0] / L[t1] auxlog = np.log(aux) aux1 = L[0] / L[t2] auxlog1 = np.log(aux1) return np.sum(L[0] * dt * auxlog1 * auxlog) - DKL(L[0], L[t1], dt) * DKL(L[0], L[t2], dt) def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs): ''' Create a plot of the covariance confidence ellipse of *x* and *y*. Inspired on the code in: https://matplotlib.org/devdocs/gallery/statistics/confidence_ellipse.html ''' if x.size != y.size: raise ValueError("x and y must be the same size") cov = np.cov(x, y) pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1]) ell_radius_x = np.sqrt(1 + pearson) ell_radius_y = np.sqrt(1 - pearson) ellipse = Ellipse((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2, facecolor=facecolor, **kwargs) scale_x = np.sqrt(cov[0, 0]) * n_std mean_x = np.mean(x) scale_y = np.sqrt(cov[1, 1]) * n_std mean_y = np.mean(y) transf = transforms.Affine2D() \ .rotate_deg(45) \ .scale(scale_x, scale_y) \ .translate(mean_x, mean_y) ellipse.set_transform(transf + ax.transData) return ax.add_patch(ellipse) def gaussian_ellipse(C, Ave, ax, n_std=3.0, facecolor='none', **kwargs): ''' Create a plot of the covariance confidence ellipse relative to the Covariance matrix C. C: covariance matrix Ave: average vector n_std: number of standard deviation ellipses ''' cov = C pearson = cov[0, 1]/np.sqrt(cov[0, 0] * cov[1, 1]) ell_radius_x = np.sqrt(1 + pearson) ell_radius_y = np.sqrt(1 - pearson) ellipse = Ellipse((0, 0), width = ell_radius_x * 2, height = ell_radius_y * 2, facecolor = facecolor, **kwargs) scale_x = np.sqrt(cov[0, 0]) * n_std mean_x = Ave[0] scale_y = np.sqrt(cov[1, 1]) * n_std mean_y = Ave[1] transf = transforms.Affine2D() \ .rotate_deg(45) \ .scale(scale_x, scale_y) \ .translate(mean_x, mean_y) ellipse.set_transform(transf + ax.transData) return ax.add_patch(ellipse)
[ "numpy.sum", "numpy.log", "numpy.abs", "numpy.ones", "numpy.mean", "numpy.exp", "matplotlib.transforms.Affine2D", "numpy.diag", "matplotlib.patches.Ellipse", "numpy.cov", "numpy.sinh", "numpy.sqrt" ]
[((1844, 1854), 'numpy.log', 'np.log', (['mn'], {}), '(mn)\n', (1850, 1854), True, 'import numpy as np\n'), ((1866, 1888), 'numpy.sum', 'np.sum', (['(m * dx * mnlog)'], {}), '(m * dx * mnlog)\n', (1872, 1888), True, 'import numpy as np\n'), ((7956, 7967), 'numpy.log', 'np.log', (['aux'], {}), '(aux)\n', (7962, 7967), True, 'import numpy as np\n'), ((8006, 8018), 'numpy.log', 'np.log', (['aux1'], {}), '(aux1)\n', (8012, 8018), True, 'import numpy as np\n'), ((8471, 8483), 'numpy.cov', 'np.cov', (['x', 'y'], {}), '(x, y)\n', (8477, 8483), True, 'import numpy as np\n'), ((8558, 8578), 'numpy.sqrt', 'np.sqrt', (['(1 + pearson)'], {}), '(1 + pearson)\n', (8565, 8578), True, 'import numpy as np\n'), ((8598, 8618), 'numpy.sqrt', 'np.sqrt', (['(1 - pearson)'], {}), '(1 - pearson)\n', (8605, 8618), True, 'import numpy as np\n'), ((8633, 8733), 'matplotlib.patches.Ellipse', 'Ellipse', (['(0, 0)'], {'width': '(ell_radius_x * 2)', 'height': '(ell_radius_y * 2)', 'facecolor': 'facecolor'}), '((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2, facecolor=\n facecolor, **kwargs)\n', (8640, 8733), False, 'from matplotlib.patches import Ellipse\n'), ((8815, 8825), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (8822, 8825), True, 'import numpy as np\n'), ((8880, 8890), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (8887, 8890), True, 'import numpy as np\n'), ((9473, 9493), 'numpy.sqrt', 'np.sqrt', (['(1 + pearson)'], {}), '(1 + pearson)\n', (9480, 9493), True, 'import numpy as np\n'), ((9513, 9533), 'numpy.sqrt', 'np.sqrt', (['(1 - pearson)'], {}), '(1 - pearson)\n', (9520, 9533), True, 'import numpy as np\n'), ((9548, 9648), 'matplotlib.patches.Ellipse', 'Ellipse', (['(0, 0)'], {'width': '(ell_radius_x * 2)', 'height': '(ell_radius_y * 2)', 'facecolor': 'facecolor'}), '((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2, facecolor=\n facecolor, **kwargs)\n', (9555, 9648), False, 'from matplotlib.patches import Ellipse\n'), ((633, 666), 'numpy.exp', 'np.exp', (['(-(x - m) ** 2 / (2 * var))'], {}), '(-(x - m) ** 2 / (2 * var))\n', (639, 666), True, 'import numpy as np\n'), ((660, 684), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi * var)'], {}), '(2 * np.pi * var)\n', (667, 684), True, 'import numpy as np\n'), ((3238, 3249), 'numpy.log', 'np.log', (['psi'], {}), '(psi)\n', (3244, 3249), True, 'import numpy as np\n'), ((5433, 5444), 'numpy.log', 'np.log', (['psi'], {}), '(psi)\n', (5439, 5444), True, 'import numpy as np\n'), ((8030, 8066), 'numpy.sum', 'np.sum', (['(L[0] * dt * auxlog1 * auxlog)'], {}), '(L[0] * dt * auxlog1 * auxlog)\n', (8036, 8066), True, 'import numpy as np\n'), ((8508, 8538), 'numpy.sqrt', 'np.sqrt', (['(cov[0, 0] * cov[1, 1])'], {}), '(cov[0, 0] * cov[1, 1])\n', (8515, 8538), True, 'import numpy as np\n'), ((8775, 8793), 'numpy.sqrt', 'np.sqrt', (['cov[0, 0]'], {}), '(cov[0, 0])\n', (8782, 8793), True, 'import numpy as np\n'), ((8840, 8858), 'numpy.sqrt', 'np.sqrt', (['cov[1, 1]'], {}), '(cov[1, 1])\n', (8847, 8858), True, 'import numpy as np\n'), ((9423, 9453), 'numpy.sqrt', 'np.sqrt', (['(cov[0, 0] * cov[1, 1])'], {}), '(cov[0, 0] * cov[1, 1])\n', (9430, 9453), True, 'import numpy as np\n'), ((9696, 9714), 'numpy.sqrt', 'np.sqrt', (['cov[0, 0]'], {}), '(cov[0, 0])\n', (9703, 9714), True, 'import numpy as np\n'), ((9757, 9775), 'numpy.sqrt', 'np.sqrt', (['cov[1, 1]'], {}), '(cov[1, 1])\n', (9764, 9775), True, 'import numpy as np\n'), ((7503, 7512), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (7509, 7512), True, 'import numpy as np\n'), ((1140, 1159), 'numpy.abs', 'np.abs', (['((x - m) / b)'], {}), '((x - m) / b)\n', (1146, 1159), True, 'import numpy as np\n'), ((6944, 6960), 'numpy.ones', 'np.ones', (['(10, 1)'], {}), '((10, 1))\n', (6951, 6960), True, 'import numpy as np\n'), ((7684, 7693), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (7690, 7693), True, 'import numpy as np\n'), ((903, 916), 'numpy.abs', 'np.abs', (['(x - m)'], {}), '(x - m)\n', (909, 916), True, 'import numpy as np\n'), ((7014, 7024), 'numpy.diag', 'np.diag', (['A'], {}), '(A)\n', (7021, 7024), True, 'import numpy as np\n'), ((7379, 7402), 'numpy.exp', 'np.exp', (['(alpha * (t + 1))'], {}), '(alpha * (t + 1))\n', (7385, 7402), True, 'import numpy as np\n'), ((7405, 7423), 'numpy.exp', 'np.exp', (['(-alpha * t)'], {}), '(-alpha * t)\n', (7411, 7423), True, 'import numpy as np\n'), ((7426, 7443), 'numpy.exp', 'np.exp', (['(alpha / 2)'], {}), '(alpha / 2)\n', (7432, 7443), True, 'import numpy as np\n'), ((7465, 7493), 'numpy.sinh', 'np.sinh', (['(alpha * (t + 1 / 2))'], {}), '(alpha * (t + 1 / 2))\n', (7472, 7493), True, 'import numpy as np\n'), ((7559, 7583), 'numpy.exp', 'np.exp', (['(-alpha * (t + 1))'], {}), '(-alpha * (t + 1))\n', (7565, 7583), True, 'import numpy as np\n'), ((7586, 7603), 'numpy.exp', 'np.exp', (['(alpha * t)'], {}), '(alpha * t)\n', (7592, 7603), True, 'import numpy as np\n'), ((8904, 8925), 'matplotlib.transforms.Affine2D', 'transforms.Affine2D', ([], {}), '()\n', (8923, 8925), True, 'import matplotlib.transforms as transforms\n'), ((9817, 9838), 'matplotlib.transforms.Affine2D', 'transforms.Affine2D', ([], {}), '()\n', (9836, 9838), True, 'import matplotlib.transforms as transforms\n'), ((7606, 7624), 'numpy.exp', 'np.exp', (['(-alpha / 2)'], {}), '(-alpha / 2)\n', (7612, 7624), True, 'import numpy as np\n'), ((7646, 7674), 'numpy.sinh', 'np.sinh', (['(alpha * (t + 1 / 2))'], {}), '(alpha * (t + 1 / 2))\n', (7653, 7674), True, 'import numpy as np\n')]
import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import dirt import dirt.lighting import dirt.matrices import dirt.projection DATA_PATH = os.path.realpath(os.path.join(__file__, '../../data')) SHAPE_BASIS_PATH = os.path.join(DATA_PATH, "shape_basis.npy") SHAPE_MEAN_PATH = os.path.join(DATA_PATH, "shape_mean.npy") EXPR_BASIS_PATH = os.path.join(DATA_PATH, "expression_basis.npy") COLOR_BASIS_PATH = os.path.join(DATA_PATH, "color_basis.npy") MESH_FACES_PATH = os.path.join(DATA_PATH, "mesh_faces.npy") TEXTURE_PATH = os.path.join(DATA_PATH, 'rainbow.png') if __name__ == '__main__': canvas_width, canvas_height = 512, 512 shape_mean = np.load(SHAPE_MEAN_PATH).astype(np.float32) shape_basis = np.load(SHAPE_BASIS_PATH).astype(np.float32) expr_basis = np.load(EXPR_BASIS_PATH).astype(np.float32) faces = np.load(MESH_FACES_PATH).T texture = tf.cast(tf.image.decode_png(tf.io.read_file(TEXTURE_PATH)), tf.float32) / 255 uv_map = texture[:, :, :2] * 512 uv_map = tf.image.resize(uv_map, [canvas_height, canvas_width]) shape_params = np.random.standard_normal([shape_basis.shape[1]]).astype(np.float32) expr_params = np.random.standard_normal([expr_basis.shape[1]]).astype(np.float32) shape_params = shape_params * 10. expr_params = expr_params * 10. verts_offsets = np.matmul(shape_basis, shape_params) + np.matmul(expr_basis, expr_params) raw_verts = np.reshape(shape_mean, [-1, 3]) + np.reshape(verts_offsets, [-1, 3]) normals = dirt.lighting.vertex_normals(raw_verts, faces) # Homogenous coordinates verts_obj = tf.concat([ raw_verts, tf.ones_like(raw_verts[:, -1:]) ], axis=1) view_matrix = dirt.matrices.compose( dirt.matrices.rodrigues([0., 0., 0.]), dirt.matrices.translation([0., 0., -5000])) verts_camera = tf.matmul(verts_obj, view_matrix) projection_matrix = dirt.matrices.perspective_projection( near=50.0, far=10000., right=1.0, aspect=1.) verts_clip = tf.matmul(verts_camera, projection_matrix) def shader_fn(gbuffer, texture, light_direction, uv_map): # Unpack the different attributes from the G-buffer mask = gbuffer[:, :, :1] normals = gbuffer[:, :, 1:4] uvs = tf.cast(gbuffer[:, :, 4:], tf.int32) # Sample the texture at locations corresponding to each pixel # this defines the unlit material color at each point unlit_colors = tf.gather_nd(texture, uvs) # Calculate a simple grey ambient lighting component ambient_contribution = unlit_colors * [0.4, 0.4, 0.4] # Calculate a diffuse (Lambertian) lighting component diffuse_contribution = dirt.lighting.diffuse_directional( tf.reshape(normals, [-1, 3]), tf.reshape(unlit_colors, [-1, 3]), light_direction, light_color=[0.6, 0.6, 0.6], double_sided=True ) diffuse_contribution = tf.reshape(diffuse_contribution, [canvas_height, canvas_width, 3]) pixels = (diffuse_contribution + ambient_contribution) * mask + [0., 0., 0.3] * (1. - mask) return pixels max_x = tf.reduce_max(tf.abs(verts_obj[:, 0])) max_y = tf.reduce_max(tf.abs(verts_obj[:, 1])) max_xy = np.array([max_x, max_y]).reshape([1, 2]) fixed_indices = tf.cast(verts_obj[:, :2] / max_xy * 256 + 256, tf.int32) indices = tf.gather_nd(uv_map, fixed_indices[:, :, ::-1]) # xy to yx light_direction = tf.linalg.l2_normalize([1., -0.3, -0.5]) pixels = dirt.rasterise_deferred( vertices=verts_clip, vertex_attributes=tf.concat([ tf.ones_like(verts_clip[:, :1]), # mask normals, # normals indices # uv coordinates ], axis=1), faces=faces, background_attributes=tf.zeros([canvas_height, canvas_width, 6]), shader_fn=shader_fn, shader_additional_inputs=[texture, light_direction, uv_map] ) plt.imshow(pixels) plt.show()
[ "numpy.load", "tensorflow.gather_nd", "tensorflow.reshape", "tensorflow.matmul", "os.path.join", "tensorflow.abs", "dirt.matrices.perspective_projection", "matplotlib.pyplot.imshow", "tensorflow.cast", "numpy.reshape", "tensorflow.io.read_file", "dirt.lighting.vertex_normals", "matplotlib.py...
[((250, 292), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""shape_basis.npy"""'], {}), "(DATA_PATH, 'shape_basis.npy')\n", (262, 292), False, 'import os\n'), ((311, 352), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""shape_mean.npy"""'], {}), "(DATA_PATH, 'shape_mean.npy')\n", (323, 352), False, 'import os\n'), ((371, 418), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""expression_basis.npy"""'], {}), "(DATA_PATH, 'expression_basis.npy')\n", (383, 418), False, 'import os\n'), ((438, 480), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""color_basis.npy"""'], {}), "(DATA_PATH, 'color_basis.npy')\n", (450, 480), False, 'import os\n'), ((499, 540), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""mesh_faces.npy"""'], {}), "(DATA_PATH, 'mesh_faces.npy')\n", (511, 540), False, 'import os\n'), ((556, 594), 'os.path.join', 'os.path.join', (['DATA_PATH', '"""rainbow.png"""'], {}), "(DATA_PATH, 'rainbow.png')\n", (568, 594), False, 'import os\n'), ((193, 229), 'os.path.join', 'os.path.join', (['__file__', '"""../../data"""'], {}), "(__file__, '../../data')\n", (205, 229), False, 'import os\n'), ((1033, 1087), 'tensorflow.image.resize', 'tf.image.resize', (['uv_map', '[canvas_height, canvas_width]'], {}), '(uv_map, [canvas_height, canvas_width])\n', (1048, 1087), True, 'import tensorflow as tf\n'), ((1533, 1579), 'dirt.lighting.vertex_normals', 'dirt.lighting.vertex_normals', (['raw_verts', 'faces'], {}), '(raw_verts, faces)\n', (1561, 1579), False, 'import dirt\n'), ((1873, 1906), 'tensorflow.matmul', 'tf.matmul', (['verts_obj', 'view_matrix'], {}), '(verts_obj, view_matrix)\n', (1882, 1906), True, 'import tensorflow as tf\n'), ((1931, 2018), 'dirt.matrices.perspective_projection', 'dirt.matrices.perspective_projection', ([], {'near': '(50.0)', 'far': '(10000.0)', 'right': '(1.0)', 'aspect': '(1.0)'}), '(near=50.0, far=10000.0, right=1.0,\n aspect=1.0)\n', (1967, 2018), False, 'import dirt\n'), ((2039, 2081), 'tensorflow.matmul', 'tf.matmul', (['verts_camera', 'projection_matrix'], {}), '(verts_camera, projection_matrix)\n', (2048, 2081), True, 'import tensorflow as tf\n'), ((3337, 3393), 'tensorflow.cast', 'tf.cast', (['(verts_obj[:, :2] / max_xy * 256 + 256)', 'tf.int32'], {}), '(verts_obj[:, :2] / max_xy * 256 + 256, tf.int32)\n', (3344, 3393), True, 'import tensorflow as tf\n'), ((3408, 3455), 'tensorflow.gather_nd', 'tf.gather_nd', (['uv_map', 'fixed_indices[:, :, ::-1]'], {}), '(uv_map, fixed_indices[:, :, ::-1])\n', (3420, 3455), True, 'import tensorflow as tf\n'), ((3491, 3532), 'tensorflow.linalg.l2_normalize', 'tf.linalg.l2_normalize', (['[1.0, -0.3, -0.5]'], {}), '([1.0, -0.3, -0.5])\n', (3513, 3532), True, 'import tensorflow as tf\n'), ((4032, 4050), 'matplotlib.pyplot.imshow', 'plt.imshow', (['pixels'], {}), '(pixels)\n', (4042, 4050), True, 'import matplotlib.pyplot as plt\n'), ((4055, 4065), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4063, 4065), True, 'import matplotlib.pyplot as plt\n'), ((864, 888), 'numpy.load', 'np.load', (['MESH_FACES_PATH'], {}), '(MESH_FACES_PATH)\n', (871, 888), True, 'import numpy as np\n'), ((1358, 1394), 'numpy.matmul', 'np.matmul', (['shape_basis', 'shape_params'], {}), '(shape_basis, shape_params)\n', (1367, 1394), True, 'import numpy as np\n'), ((1397, 1431), 'numpy.matmul', 'np.matmul', (['expr_basis', 'expr_params'], {}), '(expr_basis, expr_params)\n', (1406, 1431), True, 'import numpy as np\n'), ((1449, 1480), 'numpy.reshape', 'np.reshape', (['shape_mean', '[-1, 3]'], {}), '(shape_mean, [-1, 3])\n', (1459, 1480), True, 'import numpy as np\n'), ((1483, 1517), 'numpy.reshape', 'np.reshape', (['verts_offsets', '[-1, 3]'], {}), '(verts_offsets, [-1, 3])\n', (1493, 1517), True, 'import numpy as np\n'), ((1762, 1802), 'dirt.matrices.rodrigues', 'dirt.matrices.rodrigues', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (1785, 1802), False, 'import dirt\n'), ((1809, 1853), 'dirt.matrices.translation', 'dirt.matrices.translation', (['[0.0, 0.0, -5000]'], {}), '([0.0, 0.0, -5000])\n', (1834, 1853), False, 'import dirt\n'), ((2290, 2326), 'tensorflow.cast', 'tf.cast', (['gbuffer[:, :, 4:]', 'tf.int32'], {}), '(gbuffer[:, :, 4:], tf.int32)\n', (2297, 2326), True, 'import tensorflow as tf\n'), ((2483, 2509), 'tensorflow.gather_nd', 'tf.gather_nd', (['texture', 'uvs'], {}), '(texture, uvs)\n', (2495, 2509), True, 'import tensorflow as tf\n'), ((2969, 3035), 'tensorflow.reshape', 'tf.reshape', (['diffuse_contribution', '[canvas_height, canvas_width, 3]'], {}), '(diffuse_contribution, [canvas_height, canvas_width, 3])\n', (2979, 3035), True, 'import tensorflow as tf\n'), ((3187, 3210), 'tensorflow.abs', 'tf.abs', (['verts_obj[:, 0]'], {}), '(verts_obj[:, 0])\n', (3193, 3210), True, 'import tensorflow as tf\n'), ((3238, 3261), 'tensorflow.abs', 'tf.abs', (['verts_obj[:, 1]'], {}), '(verts_obj[:, 1])\n', (3244, 3261), True, 'import tensorflow as tf\n'), ((684, 708), 'numpy.load', 'np.load', (['SHAPE_MEAN_PATH'], {}), '(SHAPE_MEAN_PATH)\n', (691, 708), True, 'import numpy as np\n'), ((746, 771), 'numpy.load', 'np.load', (['SHAPE_BASIS_PATH'], {}), '(SHAPE_BASIS_PATH)\n', (753, 771), True, 'import numpy as np\n'), ((808, 832), 'numpy.load', 'np.load', (['EXPR_BASIS_PATH'], {}), '(EXPR_BASIS_PATH)\n', (815, 832), True, 'import numpy as np\n'), ((1108, 1157), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[shape_basis.shape[1]]'], {}), '([shape_basis.shape[1]])\n', (1133, 1157), True, 'import numpy as np\n'), ((1195, 1243), 'numpy.random.standard_normal', 'np.random.standard_normal', (['[expr_basis.shape[1]]'], {}), '([expr_basis.shape[1]])\n', (1220, 1243), True, 'import numpy as np\n'), ((1665, 1696), 'tensorflow.ones_like', 'tf.ones_like', (['raw_verts[:, -1:]'], {}), '(raw_verts[:, -1:])\n', (1677, 1696), True, 'import tensorflow as tf\n'), ((2775, 2803), 'tensorflow.reshape', 'tf.reshape', (['normals', '[-1, 3]'], {}), '(normals, [-1, 3])\n', (2785, 2803), True, 'import tensorflow as tf\n'), ((2817, 2850), 'tensorflow.reshape', 'tf.reshape', (['unlit_colors', '[-1, 3]'], {}), '(unlit_colors, [-1, 3])\n', (2827, 2850), True, 'import tensorflow as tf\n'), ((3276, 3300), 'numpy.array', 'np.array', (['[max_x, max_y]'], {}), '([max_x, max_y])\n', (3284, 3300), True, 'import numpy as np\n'), ((3880, 3922), 'tensorflow.zeros', 'tf.zeros', (['[canvas_height, canvas_width, 6]'], {}), '([canvas_height, canvas_width, 6])\n', (3888, 3922), True, 'import tensorflow as tf\n'), ((933, 962), 'tensorflow.io.read_file', 'tf.io.read_file', (['TEXTURE_PATH'], {}), '(TEXTURE_PATH)\n', (948, 962), True, 'import tensorflow as tf\n'), ((3649, 3680), 'tensorflow.ones_like', 'tf.ones_like', (['verts_clip[:, :1]'], {}), '(verts_clip[:, :1])\n', (3661, 3680), True, 'import tensorflow as tf\n')]
####################################################################################################################### # Quantile loss modeling example # This example takes data from dataset presented in [1]. It is a much simpler version of what is done in [2], the # example has only didactic purposes. In particular: # 1) here we only use endogenous data to model the quantiles, while in [2] we used also NWP signals # (also available in [1]) and categorical data, like day of the week and vacations. # 2) here we only predict quantiles for the first step-ahead, while in [2] we predicted quantiles for 24-hours ahead # # [1] "L.Nespoli, V.Medici, <NAME>, <NAME>, Hierarchical Demand Forecasting Benchmark for the # Distribution Grid, PSCC 2020, accepted" # [2] "L.Nespoli, V.Medici, Multivariate Boosted Trees and Applications to Forecasting and Control, 2020, under review" ####################################################################################################################### import numpy as np import mbtr.utils as ut from mbtr.mbtr import MBT from scipy.linalg import hankel import matplotlib.pyplot as plt from mbtr.utils import set_figure # --------------------------- Download and format data ---------------------------------------------------------------- # download power data from "Hierarchical Demand Forecasting Benchmark for the Distribution Grid" dataset # from https://zenodo.org/record/3463137#.XruXbx9fiV7 if needed power_data = ut.load_dataset() total_power = power_data['P_mean']['all'].values.reshape(-1, 1) # down-sample it to 1 hour, bin averages total_power = np.mean(total_power[:len(total_power)-len(total_power) % 6].reshape(-1, 6), axis=1, keepdims=True) # embed the signal in a 2-days matrix total_power = hankel(total_power, np.zeros((25, 1)))[:-25, :] # create feature matrix and target for the training and test sets x = total_power[:, :24] y = total_power[:, 24:] n_tr = int(len(x)*0.8) x_tr, y_tr, x_te, y_te = [x[:n_tr, :], y[:n_tr, :], x[n_tr:, :], y[n_tr:, :]] # visual check on the first 50 samples of features and targets fig, ax = set_figure((5,4)) y_min = np.min(y_tr[:50, :]) * 0.9 y_max = np.max(y_tr[:50, :]) * 1.1 for i in range(50): ax.cla() ax.plot(np.arange(24), x_tr[i,:], label='features') ax.scatter(25, y_tr[i, :], label='multivariate targets', marker='.') ax.set_xlabel('step ahead [h]') ax.set_ylabel('P [kW]') ax.legend(loc='upper right') ax.set_ylim(y_min, y_max) plt.pause(1e-6) plt.close('all') # --------------------------- Set up an MBT for quantiles prediction and train it ------------------------------------- alphas = np.linspace(0.05, 0.95, 7) m = MBT(loss_type='quantile', alphas=alphas, n_boosts=40, min_leaf=300, lambda_weights=1e-3).fit(x_tr, y_tr, do_plot=True) # --------------------------- Predict and plot ------------------------------------------------------------------------ y_hat = m.predict(x_te) fig, ax = set_figure((5,4)) y_min = np.min(y_tr[:50, :]) * 0.9 y_max = np.max(y_tr[:50, :]) * 1.1 n_q = y_hat.shape[1] n_sa = y_te.shape[1] n_plot = 300 colors = plt.get_cmap('plasma', int(n_q)) for fl in np.arange(np.floor(n_q / 2), dtype=int): q_low = np.squeeze(y_hat[:n_plot, fl]) q_up = np.squeeze(y_hat[:n_plot, n_q - fl - 1]) x = np.arange(len(q_low)) ax.fill_between(x, q_low, q_up, color=colors(fl), alpha=0.1 + 0.6*fl/n_q, linewidth=0.0) plt.plot(y_te[:n_plot], linewidth=2) plt.xlabel('step [h]') plt.ylabel('P [kW]') plt.title('Quantiles on first 300 samples')
[ "matplotlib.pyplot.title", "mbtr.mbtr.MBT", "matplotlib.pyplot.plot", "mbtr.utils.set_figure", "matplotlib.pyplot.close", "numpy.floor", "numpy.squeeze", "numpy.zeros", "numpy.min", "numpy.max", "numpy.arange", "numpy.linspace", "mbtr.utils.load_dataset", "matplotlib.pyplot.ylabel", "mat...
[((1512, 1529), 'mbtr.utils.load_dataset', 'ut.load_dataset', ([], {}), '()\n', (1527, 1529), True, 'import mbtr.utils as ut\n'), ((2142, 2160), 'mbtr.utils.set_figure', 'set_figure', (['(5, 4)'], {}), '((5, 4))\n', (2152, 2160), False, 'from mbtr.utils import set_figure\n'), ((2540, 2556), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2549, 2556), True, 'import matplotlib.pyplot as plt\n'), ((2687, 2713), 'numpy.linspace', 'np.linspace', (['(0.05)', '(0.95)', '(7)'], {}), '(0.05, 0.95, 7)\n', (2698, 2713), True, 'import numpy as np\n'), ((3002, 3020), 'mbtr.utils.set_figure', 'set_figure', (['(5, 4)'], {}), '((5, 4))\n', (3012, 3020), False, 'from mbtr.utils import set_figure\n'), ((3456, 3492), 'matplotlib.pyplot.plot', 'plt.plot', (['y_te[:n_plot]'], {'linewidth': '(2)'}), '(y_te[:n_plot], linewidth=2)\n', (3464, 3492), True, 'import matplotlib.pyplot as plt\n'), ((3493, 3515), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""step [h]"""'], {}), "('step [h]')\n", (3503, 3515), True, 'import matplotlib.pyplot as plt\n'), ((3516, 3536), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""P [kW]"""'], {}), "('P [kW]')\n", (3526, 3536), True, 'import matplotlib.pyplot as plt\n'), ((3537, 3580), 'matplotlib.pyplot.title', 'plt.title', (['"""Quantiles on first 300 samples"""'], {}), "('Quantiles on first 300 samples')\n", (3546, 3580), True, 'import matplotlib.pyplot as plt\n'), ((2168, 2188), 'numpy.min', 'np.min', (['y_tr[:50, :]'], {}), '(y_tr[:50, :])\n', (2174, 2188), True, 'import numpy as np\n'), ((2203, 2223), 'numpy.max', 'np.max', (['y_tr[:50, :]'], {}), '(y_tr[:50, :])\n', (2209, 2223), True, 'import numpy as np\n'), ((2524, 2540), 'matplotlib.pyplot.pause', 'plt.pause', (['(1e-06)'], {}), '(1e-06)\n', (2533, 2540), True, 'import matplotlib.pyplot as plt\n'), ((3028, 3048), 'numpy.min', 'np.min', (['y_tr[:50, :]'], {}), '(y_tr[:50, :])\n', (3034, 3048), True, 'import numpy as np\n'), ((3063, 3083), 'numpy.max', 'np.max', (['y_tr[:50, :]'], {}), '(y_tr[:50, :])\n', (3069, 3083), True, 'import numpy as np\n'), ((3207, 3224), 'numpy.floor', 'np.floor', (['(n_q / 2)'], {}), '(n_q / 2)\n', (3215, 3224), True, 'import numpy as np\n'), ((3250, 3280), 'numpy.squeeze', 'np.squeeze', (['y_hat[:n_plot, fl]'], {}), '(y_hat[:n_plot, fl])\n', (3260, 3280), True, 'import numpy as np\n'), ((3292, 3332), 'numpy.squeeze', 'np.squeeze', (['y_hat[:n_plot, n_q - fl - 1]'], {}), '(y_hat[:n_plot, n_q - fl - 1])\n', (3302, 3332), True, 'import numpy as np\n'), ((1823, 1840), 'numpy.zeros', 'np.zeros', (['(25, 1)'], {}), '((25, 1))\n', (1831, 1840), True, 'import numpy as np\n'), ((2276, 2289), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (2285, 2289), True, 'import numpy as np\n'), ((2718, 2811), 'mbtr.mbtr.MBT', 'MBT', ([], {'loss_type': '"""quantile"""', 'alphas': 'alphas', 'n_boosts': '(40)', 'min_leaf': '(300)', 'lambda_weights': '(0.001)'}), "(loss_type='quantile', alphas=alphas, n_boosts=40, min_leaf=300,\n lambda_weights=0.001)\n", (2721, 2811), False, 'from mbtr.mbtr import MBT\n')]
# # Copyright 2022 NVIDIA Corporation # # 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. # # Starting from Python 3.8 DLL search policy has changed. # We need to add path to CUDA DLLs explicitly. import sys import os import cv2 import numpy as np import torch import torchvision if os.name == 'nt': # Add CUDA_PATH env variable cuda_path = os.environ["CUDA_PATH"] if cuda_path: os.add_dll_directory(cuda_path) else: print("CUDA_PATH environment variable is not set.", file=sys.stderr) print("Can't set CUDA DLLs search path.", file=sys.stderr) exit(1) # Add PATH as well for minor CUDA releases sys_path = os.environ["PATH"] if sys_path: paths = sys_path.split(';') for path in paths: if os.path.isdir(path): os.add_dll_directory(path) else: print("PATH environment variable is not set.", file=sys.stderr) exit(1) import PyNvCodec as nvc import PytorchNvCodec as pnvc coco_names = [ '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table', 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush' ] def tensor_to_mat(img_tensor: torch.tensor): """ Convert planar RGB cuda float tensor to OpenCV uint8 rgb Mat """ img_r = img_tensor[0].cpu().numpy() img_g = img_tensor[1].cpu().numpy() img_b = img_tensor[2].cpu().numpy() img_rgb = np.empty((img_r.shape[0], img_r.shape[1], 3), 'uint8') img_rgb[..., 0] = img_r * 255 img_rgb[..., 1] = img_g * 255 img_rgb[..., 2] = img_b * 255 return img_rgb COLORS = np.random.uniform(0, 255, size=(len(coco_names), 3)) def draw_boxes(boxes, classes, labels, image): """ Draws the bounding box around a detected object. """ out_image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR) for i, box in enumerate(boxes): color = COLORS[labels[i]] cv2.rectangle( out_image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), color, 2 ) cv2.putText(out_image, classes[i], (int(box[0]), int(box[1]+15)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, lineType=cv2.LINE_AA) return out_image def run_inference_on_video(gpu_id: int, input_video: str): # Init resnet model = torchvision.models.detection.ssd300_vgg16(pretrained=True) model.eval() model.to('cuda') # Init HW decoder nvDec = nvc.PyNvDecoder(input_video, gpu_id) # NN expects images to be 3 channel planar RGB. # No requirements for input image resolution, it will be rescaled internally. target_w, target_h = nvDec.Width(), nvDec.Height() # Converter from NV12 which is Nvdec native pixel fomat. to_rgb = nvc.PySurfaceConverter(target_w, target_h, nvc.PixelFormat.NV12, nvc.PixelFormat.RGB, gpu_id) # Converter from RGB to planar RGB because that's the way # pytorch likes to store the data in it's tensors. to_pln = nvc.PySurfaceConverter(target_w, target_h, nvc.PixelFormat.RGB, nvc.PixelFormat.RGB_PLANAR, gpu_id) # Use bt709 and jpeg just for illustration purposes. cc_ctx = nvc.ColorspaceConversionContext(nvc.ColorSpace.BT_709, nvc.ColorRange.JPEG) # Decoding cycle + inference on video frames. while True: # Decode 1 compressed video frame to CUDA memory. nv12_surface = nvDec.DecodeSingleSurface() if nv12_surface.Empty(): print('Can not decode frame') break # Convert NV12 > RGB. rgb24_small = to_rgb.Execute(nv12_surface, cc_ctx) if rgb24_small.Empty(): print('Can not convert nv12 -> rgb') break # Convert RGB > planar RGB. rgb24_planar = to_pln.Execute(rgb24_small, cc_ctx) if rgb24_planar.Empty(): print('Can not convert rgb -> rgb planar') break # Export to PyTorch tensor. surf_plane = rgb24_planar.PlanePtr() img_tensor = pnvc.makefromDevicePtrUint8(surf_plane.GpuMem(), surf_plane.Width(), surf_plane.Height(), surf_plane.Pitch(), surf_plane.ElemSize()) # This step is essential because rgb24_planar.PlanePtr() returns a simple # 2D CUDA pitched memory allocation. Here we convert it the way # pytorch expects it's tensor data to be arranged. img_tensor.resize_(3, target_h, target_w) img_tensor = img_tensor.type(dtype=torch.cuda.FloatTensor) img_tensor = torch.divide(img_tensor, 255.0) data_transforms = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) surface_tensor = data_transforms(img_tensor) input_batch = surface_tensor.unsqueeze(0).to('cuda') # Run inference. with torch.no_grad(): outputs = model(input_batch) # Collect segmentation results. pred_classes = [coco_names[i] for i in outputs[0]['labels'].cpu().numpy()] pred_scores = outputs[0]['scores'].detach().cpu().numpy() pred_bboxes = outputs[0]['boxes'].detach().cpu().numpy() boxes = pred_bboxes[pred_scores >= 0.5].astype(np.int32) # Convert tensor to OpenCV Mat, draw labels and boxes. img_rgb = tensor_to_mat(img_tensor) image = draw_boxes(boxes, pred_classes, outputs[0]['labels'], img_rgb) # Show in GUI. cv2.imshow("Decode image", image) cv2.waitKey(0) if __name__ == "__main__": if len(sys.argv) < 3: print('Provide gpu ID, paths to input video file.') exit gpu_id = int(sys.argv[1]) input_video = sys.argv[2] run_inference_on_video(gpu_id, input_video)
[ "cv2.waitKey", "numpy.empty", "numpy.asarray", "PyNvCodec.PyNvDecoder", "torch.divide", "os.path.isdir", "PyNvCodec.PySurfaceConverter", "os.add_dll_directory", "torchvision.models.detection.ssd300_vgg16", "torchvision.transforms.Normalize", "cv2.imshow", "torch.no_grad", "PyNvCodec.Colorspa...
[((2765, 2819), 'numpy.empty', 'np.empty', (['(img_r.shape[0], img_r.shape[1], 3)', '"""uint8"""'], {}), "((img_r.shape[0], img_r.shape[1], 3), 'uint8')\n", (2773, 2819), True, 'import numpy as np\n'), ((3707, 3765), 'torchvision.models.detection.ssd300_vgg16', 'torchvision.models.detection.ssd300_vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (3748, 3765), False, 'import torchvision\n'), ((3839, 3875), 'PyNvCodec.PyNvDecoder', 'nvc.PyNvDecoder', (['input_video', 'gpu_id'], {}), '(input_video, gpu_id)\n', (3854, 3875), True, 'import PyNvCodec as nvc\n'), ((4141, 4239), 'PyNvCodec.PySurfaceConverter', 'nvc.PySurfaceConverter', (['target_w', 'target_h', 'nvc.PixelFormat.NV12', 'nvc.PixelFormat.RGB', 'gpu_id'], {}), '(target_w, target_h, nvc.PixelFormat.NV12, nvc.\n PixelFormat.RGB, gpu_id)\n', (4163, 4239), True, 'import PyNvCodec as nvc\n'), ((4438, 4542), 'PyNvCodec.PySurfaceConverter', 'nvc.PySurfaceConverter', (['target_w', 'target_h', 'nvc.PixelFormat.RGB', 'nvc.PixelFormat.RGB_PLANAR', 'gpu_id'], {}), '(target_w, target_h, nvc.PixelFormat.RGB, nvc.\n PixelFormat.RGB_PLANAR, gpu_id)\n', (4460, 4542), True, 'import PyNvCodec as nvc\n'), ((4645, 4720), 'PyNvCodec.ColorspaceConversionContext', 'nvc.ColorspaceConversionContext', (['nvc.ColorSpace.BT_709', 'nvc.ColorRange.JPEG'], {}), '(nvc.ColorSpace.BT_709, nvc.ColorRange.JPEG)\n', (4676, 4720), True, 'import PyNvCodec as nvc\n'), ((896, 927), 'os.add_dll_directory', 'os.add_dll_directory', (['cuda_path'], {}), '(cuda_path)\n', (916, 927), False, 'import os\n'), ((3153, 3170), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (3163, 3170), True, 'import numpy as np\n'), ((6210, 6241), 'torch.divide', 'torch.divide', (['img_tensor', '(255.0)'], {}), '(img_tensor, 255.0)\n', (6222, 6241), False, 'import torch\n'), ((6268, 6360), 'torchvision.transforms.Normalize', 'torchvision.transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, \n 0.224, 0.225])\n', (6300, 6360), False, 'import torchvision\n'), ((7189, 7222), 'cv2.imshow', 'cv2.imshow', (['"""Decode image"""', 'image'], {}), "('Decode image', image)\n", (7199, 7222), False, 'import cv2\n'), ((7231, 7245), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (7242, 7245), False, 'import cv2\n'), ((1275, 1294), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (1288, 1294), False, 'import os\n'), ((6568, 6583), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6581, 6583), False, 'import torch\n'), ((1312, 1338), 'os.add_dll_directory', 'os.add_dll_directory', (['path'], {}), '(path)\n', (1332, 1338), False, 'import os\n')]
#!/usr/bin/env python import sys, os import argparse import numpy as np from nmtpytorch.utils.embedding import load_fasttext,load_glove,load_word2vec from nmtpytorch.vocabulary import Vocabulary # main def main(args): vocab = Vocabulary(args.vocab, None) if args.type == 'fastText': embs = load_fasttext(args.embedding, vocab) elif args.type == 'glove': embs = load_glove(args.embedding, vocab) elif args.type == 'word2vec': embs = load_word2vec(args.embedding, vocab) else: raise Exception() np.save(args.output, embs) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-v', '--vocab', type=str, required=True) parser.add_argument('-e', '--embedding', type=str, required=True) parser.add_argument('-t', '--type', choices=['fastText', 'glove', 'word2vec'], required=True) parser.add_argument('-o', '--output', type=str, required=True) args = parser.parse_args() print(args, file=sys.stderr) main(args)
[ "nmtpytorch.utils.embedding.load_fasttext", "numpy.save", "nmtpytorch.vocabulary.Vocabulary", "argparse.ArgumentParser", "nmtpytorch.utils.embedding.load_glove", "nmtpytorch.utils.embedding.load_word2vec" ]
[((234, 262), 'nmtpytorch.vocabulary.Vocabulary', 'Vocabulary', (['args.vocab', 'None'], {}), '(args.vocab, None)\n', (244, 262), False, 'from nmtpytorch.vocabulary import Vocabulary\n'), ((559, 585), 'numpy.save', 'np.save', (['args.output', 'embs'], {}), '(args.output, embs)\n', (566, 585), True, 'import numpy as np\n'), ((627, 652), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (650, 652), False, 'import argparse\n'), ((315, 351), 'nmtpytorch.utils.embedding.load_fasttext', 'load_fasttext', (['args.embedding', 'vocab'], {}), '(args.embedding, vocab)\n', (328, 351), False, 'from nmtpytorch.utils.embedding import load_fasttext, load_glove, load_word2vec\n'), ((398, 431), 'nmtpytorch.utils.embedding.load_glove', 'load_glove', (['args.embedding', 'vocab'], {}), '(args.embedding, vocab)\n', (408, 431), False, 'from nmtpytorch.utils.embedding import load_fasttext, load_glove, load_word2vec\n'), ((481, 517), 'nmtpytorch.utils.embedding.load_word2vec', 'load_word2vec', (['args.embedding', 'vocab'], {}), '(args.embedding, vocab)\n', (494, 517), False, 'from nmtpytorch.utils.embedding import load_fasttext, load_glove, load_word2vec\n')]
import pandas as pd import scipy.sparse as sp import numpy as np import pickle from collections import defaultdict raw_allx = pd.read_csv('ind.game.allx.csv', sep=' ', header=None) allx = sp.csr_matrix(raw_allx.values) raw_tx = pd.read_csv('ind.game.tx.csv', sep=' ', header=None) tx = sp.csr_matrix(raw_tx.values) raw_x = pd.read_csv('ind.game.x.csv', sep=' ', header=None) x = sp.csr_matrix(raw_x.values) trainset_size = raw_allx.shape[0] unlabelset_size = trainset_size - raw_x.shape[0] testset_size = raw_tx.shape[0] print("trainset_size: %d" % trainset_size) print("unlabelset_size: %d" % unlabelset_size) print("testset_size: %d" % testset_size) raw_ally = pd.read_csv('ind.game.ally.csv', sep=',', header=None) raw_ally.columns = ['userid','tag'] ally = [] for i in range(trainset_size): one_hot = [0 for l in range(2)] label_index = raw_ally.iat[i, 1] if label_index > -1 : one_hot[label_index] = 1 ally.append(one_hot) ally = np.array(ally) y=[] raw_y =pd.read_csv('ind.game.y.csv', sep=',', header=None) raw_y.columns = ['userid', 'tag'] for i in range(trainset_size-unlabelset_size): one_hot = [0 for l in range(2)] label_index = raw_y.iat[i, 1] if label_index > -1 : one_hot[label_index] = 1 y.append(one_hot) y = np.array(y) print(y) print(len(y)) for i in range(3,5): print(i) raw_ty = pd.read_csv('ind.game.ty.csv', sep=',', header=None) raw_ty.columns = ['userid','tag'] ty = [] for i in range(testset_size): one_hot = [0 for l in range(2)] label_index = raw_ty.iat[i, 1] if label_index > -1: one_hot[label_index] = 1 ty.append(one_hot) ty = np.array(ty) raw_graph = pd.read_csv('ind.game.graph.csv', sep=',', header=None) graph = defaultdict(list) for i in range(raw_graph.shape[0]): graph[raw_graph.iat[i,0]].append(raw_graph.iat[i,1]) # names = [(x,'x'), (y,'y'), (tx,'tx'), (ty,'ty'), (allx,'allx'), (ally,'ally'), (graph,'graph')] # for i in range(len(names)): # with open('../data/ind.game.{}'.format(names[i][1]),'wb') as f: # pickle.dump(names[i][0], f, pickle.HIGHEST_PROTOCOL) with open('../data/ind.game.x','wb') as f: pickle.dump(x, f, pickle.HIGHEST_PROTOCOL) with open('../data/ind.game.y','wb') as f: pickle.dump(y, f, pickle.HIGHEST_PROTOCOL) with open('../data/ind.game.tx','wb') as f: pickle.dump(tx, f, pickle.HIGHEST_PROTOCOL) with open('../data/ind.game.ty','wb') as f: pickle.dump(ty, f, pickle.HIGHEST_PROTOCOL) with open('../data/ind.game.allx','wb') as f: pickle.dump(allx, f, pickle.HIGHEST_PROTOCOL) with open('../data/ind.game.ally','wb') as f: pickle.dump(ally, f, pickle.HIGHEST_PROTOCOL) with open('../data/ind.game.graph','wb') as f: pickle.dump(graph, f, pickle.HIGHEST_PROTOCOL)
[ "pickle.dump", "pandas.read_csv", "collections.defaultdict", "scipy.sparse.csr_matrix", "numpy.array" ]
[((128, 182), 'pandas.read_csv', 'pd.read_csv', (['"""ind.game.allx.csv"""'], {'sep': '""" """', 'header': 'None'}), "('ind.game.allx.csv', sep=' ', header=None)\n", (139, 182), True, 'import pandas as pd\n'), ((190, 220), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['raw_allx.values'], {}), '(raw_allx.values)\n', (203, 220), True, 'import scipy.sparse as sp\n'), ((231, 283), 'pandas.read_csv', 'pd.read_csv', (['"""ind.game.tx.csv"""'], {'sep': '""" """', 'header': 'None'}), "('ind.game.tx.csv', sep=' ', header=None)\n", (242, 283), True, 'import pandas as pd\n'), ((289, 317), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['raw_tx.values'], {}), '(raw_tx.values)\n', (302, 317), True, 'import scipy.sparse as sp\n'), ((327, 378), 'pandas.read_csv', 'pd.read_csv', (['"""ind.game.x.csv"""'], {'sep': '""" """', 'header': 'None'}), "('ind.game.x.csv', sep=' ', header=None)\n", (338, 378), True, 'import pandas as pd\n'), ((383, 410), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['raw_x.values'], {}), '(raw_x.values)\n', (396, 410), True, 'import scipy.sparse as sp\n'), ((671, 725), 'pandas.read_csv', 'pd.read_csv', (['"""ind.game.ally.csv"""'], {'sep': '""","""', 'header': 'None'}), "('ind.game.ally.csv', sep=',', header=None)\n", (682, 725), True, 'import pandas as pd\n'), ((969, 983), 'numpy.array', 'np.array', (['ally'], {}), '(ally)\n', (977, 983), True, 'import numpy as np\n'), ((998, 1049), 'pandas.read_csv', 'pd.read_csv', (['"""ind.game.y.csv"""'], {'sep': '""","""', 'header': 'None'}), "('ind.game.y.csv', sep=',', header=None)\n", (1009, 1049), True, 'import pandas as pd\n'), ((1286, 1297), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1294, 1297), True, 'import numpy as np\n'), ((1366, 1418), 'pandas.read_csv', 'pd.read_csv', (['"""ind.game.ty.csv"""'], {'sep': '""","""', 'header': 'None'}), "('ind.game.ty.csv', sep=',', header=None)\n", (1377, 1418), True, 'import pandas as pd\n'), ((1648, 1660), 'numpy.array', 'np.array', (['ty'], {}), '(ty)\n', (1656, 1660), True, 'import numpy as np\n'), ((1675, 1730), 'pandas.read_csv', 'pd.read_csv', (['"""ind.game.graph.csv"""'], {'sep': '""","""', 'header': 'None'}), "('ind.game.graph.csv', sep=',', header=None)\n", (1686, 1730), True, 'import pandas as pd\n'), ((1739, 1756), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1750, 1756), False, 'from collections import defaultdict\n'), ((2162, 2204), 'pickle.dump', 'pickle.dump', (['x', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(x, f, pickle.HIGHEST_PROTOCOL)\n', (2173, 2204), False, 'import pickle\n'), ((2252, 2294), 'pickle.dump', 'pickle.dump', (['y', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(y, f, pickle.HIGHEST_PROTOCOL)\n', (2263, 2294), False, 'import pickle\n'), ((2343, 2386), 'pickle.dump', 'pickle.dump', (['tx', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(tx, f, pickle.HIGHEST_PROTOCOL)\n', (2354, 2386), False, 'import pickle\n'), ((2435, 2478), 'pickle.dump', 'pickle.dump', (['ty', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(ty, f, pickle.HIGHEST_PROTOCOL)\n', (2446, 2478), False, 'import pickle\n'), ((2529, 2574), 'pickle.dump', 'pickle.dump', (['allx', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(allx, f, pickle.HIGHEST_PROTOCOL)\n', (2540, 2574), False, 'import pickle\n'), ((2625, 2670), 'pickle.dump', 'pickle.dump', (['ally', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(ally, f, pickle.HIGHEST_PROTOCOL)\n', (2636, 2670), False, 'import pickle\n'), ((2722, 2768), 'pickle.dump', 'pickle.dump', (['graph', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(graph, f, pickle.HIGHEST_PROTOCOL)\n', (2733, 2768), False, 'import pickle\n')]
# * cancer 데이터셋 : 위스콘신 유방암 데이터셋. 유방암 종양의 임상 데이터가 기록된 실제 데이터셋. # 569개의 데이터와 30개의 특성을 가진다. 그중 212개는 악성이고 357개는 양성이다. import scipy as sp import numpy as np import matplotlib.pyplot as plt import pandas as pd import mglearn from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() print("cancer.keys():\n{}".format(cancer.keys())) print("데이터의 형태: {}".format(cancer.data.shape)) print("클래스별 샘플 개수:\n{}".format( {n: v for n, v in zip(cancer.target_names, np.bincount(cancer.target))})) print("특성 이름:\n{}".format(cancer.feature_names))
[ "sklearn.datasets.load_breast_cancer", "numpy.bincount" ]
[((289, 309), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (307, 309), False, 'from sklearn.datasets import load_breast_cancer\n'), ((490, 516), 'numpy.bincount', 'np.bincount', (['cancer.target'], {}), '(cancer.target)\n', (501, 516), True, 'import numpy as np\n')]
import librosa import librosa.display import numpy as np import speech_recognition as sr r = sr.Recognizer() mic = sr.Microphone() import datetime import os import Database as db import Compression as cp import Recorder as rec import CompareAlgorithms as ca start = datetime.datetime.now() def findmostaccurate(test, songlist, resample): tests = [] for _ in range(len(songlist)): r = ca.comparealgorithhm(test, songlist[_], resample) r["song"] = songlist[_] tests.append(r) maxacc = {"accuracy": 0} for test in tests: if test["accuracy"] > maxacc["accuracy"]: maxacc = test return maxacc def findmostaccuratetext(test): decompressedsongs = [] songlist = os.listdir("AudioTexts") compedtest = np.loadtxt("AudioTexts/" + test + ".txt") songs = [] for song in songlist: if ".DS_" not in song and test not in song: sstart = datetime.datetime.now() songdata = np.loadtxt("AudioTexts/" + song) output = ca.textcomparealgorithhmv2(compedtest, songdata) songs.append({"name": song.replace(".txt", ""), "accuracy": output["accuracy"], "start": output["start"]}) # print("Compared in", datetime.datetime.now() - sstart, song) retmax = {"accuracy": 0} for match in songs: try: songacc = float(match["accuracy"]) maxac = float(retmax["accuracy"]) if songacc > maxac: retmax = match except: pass return retmax def findmostaccuraterec(test): songlist = os.listdir("AudioTexts") songlist.sort() compedtest = np.transpose(cp.hashsupercompression(test, True)) songs = [] index = 0 t = datetime.datetime.now() lasttime = 100000 for song in songlist: perc = (100 * index / len(songlist)) passedtime = datetime.datetime.now() - t try: perctime = (100 * (passedtime.total_seconds() / perc)) - passedtime.total_seconds() if perctime < lasttime: print("%" + str(int(perc)), "remaining time", str(int(perctime)), "seconds") lasttime = perctime except: pass if ".DS_" not in song and test not in song: songdata = np.loadtxt("AudioTexts/" + song) output = ca.textcomparealgorithhmv2(compedtest, songdata) entry = {"name": song.replace(".txt", ""), "accuracy": output["accuracy"], "start": output["start"]} songs.append(entry) # print(entry) index += 1 retmax = {"accuracy": 0} for match in songs: try: songacc = float(match["accuracy"]) maxac = float(retmax["accuracy"]) if songacc > maxac: retmax = match except: pass retmax["found in"]=str(datetime.datetime.now()-t) return retmax def runtests(): testcountingstars = "counting_stars_1-45_1-50" testlikeastone = "like_a_stone_1-25_1-30-WAV" testbeliever = "believer_2-00_2-05" songlist = ["believer.wav", "counting_stars.wav", "like_a_stone.wav"] start1 = datetime.datetime.now() print(testcountingstars, findmostaccuratetext(testcountingstars, songlist), "found in", datetime.datetime.now() - start1) start2 = datetime.datetime.now() print(testlikeastone, findmostaccuratetext(testlikeastone, songlist), "found in", datetime.datetime.now() - start2) start3 = datetime.datetime.now() print(testbeliever, findmostaccuratetext(testbeliever, songlist), "found in", datetime.datetime.now() - start3) def lookdata(filename, resample): y_file, fs = librosa.load(filename) if resample: targetsample = 2000 y_file = librosa.resample(y_file, target_sr=targetsample, orig_sr=fs) D = librosa.stft(y_file) S_db = np.transpose(np.array(librosa.amplitude_to_db(np.abs(D), ref=np.max))).tolist() song = {"name": filename.replace(".wav", ""), "data": D, "shape": np.shape(np.array(D))} print(song["name"], fs, song["shape"]) def runrecordingtest(): recording = rec.Record() rtime=datetime.datetime.now() result=findmostaccuraterec(recording) #runtime = datetime.datetime.now() - rtime #print("Proccess completed in", str(runtime.seconds + (round(100 * runtime.microseconds / 1000000) / 100)), "seconds") print('Currently playing "'+result["name"]+" current") #db.newdatabase()
[ "numpy.abs", "CompareAlgorithms.comparealgorithhm", "librosa.stft", "speech_recognition.Microphone", "Recorder.Record", "librosa.resample", "librosa.load", "numpy.loadtxt", "CompareAlgorithms.textcomparealgorithhmv2", "numpy.array", "Compression.hashsupercompression", "datetime.datetime.now", ...
[((94, 109), 'speech_recognition.Recognizer', 'sr.Recognizer', ([], {}), '()\n', (107, 109), True, 'import speech_recognition as sr\n'), ((116, 131), 'speech_recognition.Microphone', 'sr.Microphone', ([], {}), '()\n', (129, 131), True, 'import speech_recognition as sr\n'), ((268, 291), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (289, 291), False, 'import datetime\n'), ((732, 756), 'os.listdir', 'os.listdir', (['"""AudioTexts"""'], {}), "('AudioTexts')\n", (742, 756), False, 'import os\n'), ((774, 815), 'numpy.loadtxt', 'np.loadtxt', (["('AudioTexts/' + test + '.txt')"], {}), "('AudioTexts/' + test + '.txt')\n", (784, 815), True, 'import numpy as np\n'), ((1595, 1619), 'os.listdir', 'os.listdir', (['"""AudioTexts"""'], {}), "('AudioTexts')\n", (1605, 1619), False, 'import os\n'), ((1744, 1767), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1765, 1767), False, 'import datetime\n'), ((3155, 3178), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3176, 3178), False, 'import datetime\n'), ((3328, 3351), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3349, 3351), False, 'import datetime\n'), ((3485, 3508), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3506, 3508), False, 'import datetime\n'), ((3678, 3700), 'librosa.load', 'librosa.load', (['filename'], {}), '(filename)\n', (3690, 3700), False, 'import librosa\n'), ((3832, 3852), 'librosa.stft', 'librosa.stft', (['y_file'], {}), '(y_file)\n', (3844, 3852), False, 'import librosa\n'), ((4124, 4136), 'Recorder.Record', 'rec.Record', ([], {}), '()\n', (4134, 4136), True, 'import Recorder as rec\n'), ((4147, 4170), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4168, 4170), False, 'import datetime\n'), ((404, 453), 'CompareAlgorithms.comparealgorithhm', 'ca.comparealgorithhm', (['test', 'songlist[_]', 'resample'], {}), '(test, songlist[_], resample)\n', (424, 453), True, 'import CompareAlgorithms as ca\n'), ((1670, 1705), 'Compression.hashsupercompression', 'cp.hashsupercompression', (['test', '(True)'], {}), '(test, True)\n', (1693, 1705), True, 'import Compression as cp\n'), ((3763, 3823), 'librosa.resample', 'librosa.resample', (['y_file'], {'target_sr': 'targetsample', 'orig_sr': 'fs'}), '(y_file, target_sr=targetsample, orig_sr=fs)\n', (3779, 3823), False, 'import librosa\n'), ((930, 953), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (951, 953), False, 'import datetime\n'), ((977, 1009), 'numpy.loadtxt', 'np.loadtxt', (["('AudioTexts/' + song)"], {}), "('AudioTexts/' + song)\n", (987, 1009), True, 'import numpy as np\n'), ((1031, 1079), 'CompareAlgorithms.textcomparealgorithhmv2', 'ca.textcomparealgorithhmv2', (['compedtest', 'songdata'], {}), '(compedtest, songdata)\n', (1057, 1079), True, 'import CompareAlgorithms as ca\n'), ((1882, 1905), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1903, 1905), False, 'import datetime\n'), ((2288, 2320), 'numpy.loadtxt', 'np.loadtxt', (["('AudioTexts/' + song)"], {}), "('AudioTexts/' + song)\n", (2298, 2320), True, 'import numpy as np\n'), ((2342, 2390), 'CompareAlgorithms.textcomparealgorithhmv2', 'ca.textcomparealgorithhmv2', (['compedtest', 'songdata'], {}), '(compedtest, songdata)\n', (2368, 2390), True, 'import CompareAlgorithms as ca\n'), ((2864, 2887), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2885, 2887), False, 'import datetime\n'), ((3281, 3304), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3302, 3304), False, 'import datetime\n'), ((3438, 3461), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3459, 3461), False, 'import datetime\n'), ((3591, 3614), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3612, 3614), False, 'import datetime\n'), ((4024, 4035), 'numpy.array', 'np.array', (['D'], {}), '(D)\n', (4032, 4035), True, 'import numpy as np\n'), ((3910, 3919), 'numpy.abs', 'np.abs', (['D'], {}), '(D)\n', (3916, 3919), True, 'import numpy as np\n')]
import numpy as np def MatMul(A,B): ''' A function for matrix multiplication ''' if (A.shape[1]!=B.shape[0]): return "Matrix Multiplication not possible due to shape mismatch" shape_A = A.shape[0] shape_B = B.shape[1] result = np.zeros(shape = (shape_A,shape_B),dtype = int) for i in range(shape_A): for j in range(shape_B): for k in range(A.shape[1]): result[i,j] += A[i,k]*B[k,j] return result def isequal(A,B): ''' Program to check if two matrices are equal ''' if A.shape!=B.shape: return False else: for i in range(A.shape[0]): for j in range(A.shape[1]): if (A[i,j]!=B[i,j]): return False return True # Defining the matrices a = np.array([[5,-1],[6,7]]) b = np.array([[2,1],[3,4]]) # Calculating the products ab = MatMul(a,b) ba = MatMul(b,a) ''' Alternatively: Use Numpy builtin numpy.matmul function ab = np.matmul(a,b) ba = np.matmul(b,a) ''' # Decision if (isequal(ab,ba)): print("AB = BA") else: print("AB != BA")
[ "numpy.zeros", "numpy.array" ]
[((722, 749), 'numpy.array', 'np.array', (['[[5, -1], [6, 7]]'], {}), '([[5, -1], [6, 7]])\n', (730, 749), True, 'import numpy as np\n'), ((751, 777), 'numpy.array', 'np.array', (['[[2, 1], [3, 4]]'], {}), '([[2, 1], [3, 4]])\n', (759, 777), True, 'import numpy as np\n'), ((245, 290), 'numpy.zeros', 'np.zeros', ([], {'shape': '(shape_A, shape_B)', 'dtype': 'int'}), '(shape=(shape_A, shape_B), dtype=int)\n', (253, 290), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris class Perceptron: def __init__(self): self.W = None self.b = None def _init_params(self, dim): self.W = np.random.randn(dim) self.b = 0 def linear(self, x): """ Calculate linear transformation of a sample, of shape [dim] :param x: a sample instance :type x: numpy array :return: numpy array of single value :rtype: float """ return np.dot(x, self.W) + self.b def train(self, X, Y, lr): # init weight and bias self._init_params(X.shape[1]) # while loop to train wight and bias has_error = True while has_error: has_error = False # iter each sample instance for x, y in zip(X, Y): # misclassified point if y * self.linear(x) <= 0: # update weight and bias self.W += lr * y * x self.b += lr * y # set has_error to True has_error = True def predict(self, X): return ((np.dot(X, self.W) + self.b) > 0).astype(np.int8) if __name__ == '__main__': iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df['label'] = iris.target df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label'] # only take first two-columns and target label as our training data data = np.array(df.iloc[:100, [0, 1, -1]]) X, Y = data[:, :-1], data[:, -1] Y = np.where(Y == 1, np.ones_like(Y), np.ones_like(Y) * -1) # plot perceptron perceptron = Perceptron() perceptron.train(X, Y, 0.01) _x_min, _x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 _y_min, _y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(_x_min, _x_max, 0.02), np.arange(_y_min, _y_max, 0.02)) Z = perceptron.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu) # plot data plt.scatter(df['sepal length'][:50], df['sepal width'][:50], c='yellow', label='class 0') plt.scatter(df['sepal length'][50:100], df['sepal width'][50:100], c='black', label='class 1') plt.xlabel('sepal length') plt.ylabel('sepal width') plt.legend() plt.show()
[ "pandas.DataFrame", "sklearn.datasets.load_iris", "matplotlib.pyplot.show", "numpy.ones_like", "numpy.random.randn", "matplotlib.pyplot.scatter", "matplotlib.pyplot.legend", "numpy.array", "matplotlib.pyplot.contourf", "numpy.arange", "numpy.dot", "matplotlib.pyplot.ylabel", "matplotlib.pypl...
[((1301, 1312), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (1310, 1312), False, 'from sklearn.datasets import load_iris\n'), ((1322, 1373), 'pandas.DataFrame', 'pd.DataFrame', (['iris.data'], {'columns': 'iris.feature_names'}), '(iris.data, columns=iris.feature_names)\n', (1334, 1373), True, 'import pandas as pd\n'), ((1576, 1611), 'numpy.array', 'np.array', (['df.iloc[:100, [0, 1, -1]]'], {}), '(df.iloc[:100, [0, 1, -1]])\n', (1584, 1611), True, 'import numpy as np\n'), ((2100, 2143), 'matplotlib.pyplot.contourf', 'plt.contourf', (['xx', 'yy', 'Z'], {'cmap': 'plt.cm.RdYlBu'}), '(xx, yy, Z, cmap=plt.cm.RdYlBu)\n', (2112, 2143), True, 'import matplotlib.pyplot as plt\n'), ((2164, 2257), 'matplotlib.pyplot.scatter', 'plt.scatter', (["df['sepal length'][:50]", "df['sepal width'][:50]"], {'c': '"""yellow"""', 'label': '"""class 0"""'}), "(df['sepal length'][:50], df['sepal width'][:50], c='yellow',\n label='class 0')\n", (2175, 2257), True, 'import matplotlib.pyplot as plt\n'), ((2258, 2357), 'matplotlib.pyplot.scatter', 'plt.scatter', (["df['sepal length'][50:100]", "df['sepal width'][50:100]"], {'c': '"""black"""', 'label': '"""class 1"""'}), "(df['sepal length'][50:100], df['sepal width'][50:100], c=\n 'black', label='class 1')\n", (2269, 2357), True, 'import matplotlib.pyplot as plt\n'), ((2357, 2383), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""sepal length"""'], {}), "('sepal length')\n", (2367, 2383), True, 'import matplotlib.pyplot as plt\n'), ((2388, 2413), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""sepal width"""'], {}), "('sepal width')\n", (2398, 2413), True, 'import matplotlib.pyplot as plt\n'), ((2418, 2430), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2428, 2430), True, 'import matplotlib.pyplot as plt\n'), ((2435, 2445), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2443, 2445), True, 'import matplotlib.pyplot as plt\n'), ((249, 269), 'numpy.random.randn', 'np.random.randn', (['dim'], {}), '(dim)\n', (264, 269), True, 'import numpy as np\n'), ((1674, 1689), 'numpy.ones_like', 'np.ones_like', (['Y'], {}), '(Y)\n', (1686, 1689), True, 'import numpy as np\n'), ((1939, 1970), 'numpy.arange', 'np.arange', (['_x_min', '_x_max', '(0.02)'], {}), '(_x_min, _x_max, 0.02)\n', (1948, 1970), True, 'import numpy as np\n'), ((1972, 2003), 'numpy.arange', 'np.arange', (['_y_min', '_y_max', '(0.02)'], {}), '(_y_min, _y_max, 0.02)\n', (1981, 2003), True, 'import numpy as np\n'), ((554, 571), 'numpy.dot', 'np.dot', (['x', 'self.W'], {}), '(x, self.W)\n', (560, 571), True, 'import numpy as np\n'), ((1691, 1706), 'numpy.ones_like', 'np.ones_like', (['Y'], {}), '(Y)\n', (1703, 1706), True, 'import numpy as np\n'), ((1212, 1229), 'numpy.dot', 'np.dot', (['X', 'self.W'], {}), '(X, self.W)\n', (1218, 1229), True, 'import numpy as np\n')]
import pandas as pd import matplotlib.pyplot as plt from numpy.core.fromnumeric import shape import numpy as np from astropy.table import Table from scipy.interpolate import interp1d import os import sys sys.path.insert(1, '/home/astrolab/pycmpfit/build/lib.linux-x86_64-3.6') import pycmpfit # from kapteyn import kmpfit abspath = os.path.dirname(__file__) FPCA_dir = os.path.join(abspath, 'LCfPCA_He') # def phase_limit(fpca_f): # ''' # :params fpca_f: Template filter that you'd like to use. B, V, R, I filters available, Otherwise, use band vague # ''' # if fpca_f in ['B', 'V', 'R', 'I']: # phaselim = [-10, 50] # else: # phaselim = [-10, 40] # return phaselim def get_pctemplates(fpca_f): ''' returns corresponding fpca templates :params fpca_f: Template filter that you'd like to use. B, V, R, I filters available, Otherwise, use band vague template. return: list of interpolated template functions [mean, pc1, pc2, pc3, pc4] -- note that returned interpolated functions\ are in -10 to 40/50 for time axis (40 for band vague, 50 for BVRI) ''' if fpca_f in ['B', 'V', 'R', 'I']: fname = 'bandSpecific_%s.txt' % fpca_f else: fname = 'bandVague.txt' fpca_file = os.path.join(FPCA_dir, fname) # FIXME t_pc = Table.read(fpca_file, format='ascii') phase, mean, pc1, pc2, pc3, pc4 = t_pc['phase'], t_pc['mean'], \ t_pc['FPC1'], t_pc['FPC2'], t_pc['FPC3'], t_pc['FPC4'] fpc0 = interp1d(phase, mean, fill_value=np.nan, bounds_error=False) fpc1 = interp1d(phase, pc1, fill_value=np.nan, bounds_error=False) fpc2 = interp1d(phase, pc2, fill_value=np.nan, bounds_error=False) fpc3 = interp1d(phase, pc3, fill_value=np.nan, bounds_error=False) fpc4 = interp1d(phase, pc4, fill_value=np.nan, bounds_error=False) return [fpc0, fpc1, fpc2, fpc3, fpc4] def fit_pcparams(*data, fpca_f='vague', init_guess=None, components=2, penalty=True, penalty_increase=None, penalty_decrease=None, boundary=None): ''' :params data: list of dates, OR 3*n array or n*3 array when mag and magerr are None :params fpca_f: fpca filter that you want to use to fit the lc. options:\ vague, B, V, R, I :params init_guess: list, initial guess of parameters, None for default :params components: number of fPCA components you want to use :params penalty: :params penalty_increase: latest epoch before which you'd like the lc to be monotonically increasing :params penalty_decrease: earliest epoch after which you'd like the lc to be monotonically decreasing :params boundary: lists of shape components*2 [[low, high], [low, high]], put constraints on pc parameters return fpca_f, mpfit_result mpfit_result: as long as it contains attributes params, covar, chi2 ''' # Read in data if given separate arrays or lists if len(data) == 3: date, mag, emag = [np.array(ii) for ii in data] if len(data) == 2: date, mag = [np.array(ii) for ii in data] # if no magnitude error is provided, then use constant 1 for all epochs. # This makes the denominator in the merit function = 1 emag = np.array([1]*len(date)) # Read in data if given a dictionary if len(data) == 1 and isinstance(data[0], dict): data = data[0] date, mag = map(lambda x: np.array(data[x]), ['date', 'mag']) # I think this should be data.keys() in the next line: if 'emag' not in data: emag = np.array([1]*len(date)) else: emag = np.array(data['emag']) # Read in data if given an astropy table if len(data) == 1 and isinstance(data[0], Table): data = data[0] date, mag = np.array(data['date']), np.array(data['mag']) if 'emag' not in data.colnames: emag = np.array([1]*len(date)) else: emag = np.array(data['emag']) def get_modelval(date, theta, fpca_f): ''' Calculates the linear combination of coefficients and PC vectors at every point in the grid. Given a phase and parameters, returns the corresponding fitted magnitude. :params date: float or list/array :params theta: list of length 6. fitting parameters return: float if input is float, array if input is array [tmax, mmax, a1, a2, a3, a4] ''' basis = get_pctemplates(fpca_f) if not isinstance(date, float): date = np.array(date) tmax, mmax, a1, a2, a3, a4 = theta coeffs = [1, a1, a2, a3, a4] mphase = date-tmax y = mmax + (np.dot((coeffs), np.array([fbasis(mphase) for fbasis in basis]))) return y def meritfunc(m, n, theta, input_data): # , penalty=penalty, \ # penalty_increase=penalty_increase, penalty_decrease=penalty_decrease): # FIXME not sure if mpfit allows users to add more arguments in userfunc? ''' Chisq to be minimized. :m number of samples (len(data)): :n number of parameters (len(theta)): ''' x, y, ey = map(lambda xx: np.array( input_data[xx]), ['date', 'mag', 'emag']) fpca_f, penalty_increase, penalty_decrease = map( lambda x: input_data[x], ['fpca_f', 'penalty_increase', 'penalty_decrease']) y_model = get_modelval(x, theta, fpca_f) resid = (y - y_model)/ey resid = np.where(np.isnan(resid), 0, resid) # resid_dict if penalty: if penalty_increase is None: penalty_increase = -1 # -0.03? FIXME if penalty_decrease is None: penalty_decrease = 35 model_x = np.arange(-10, 50, 0.01) + theta[0] model_y = get_modelval(model_x, theta, fpca_f) idx = ~np.isnan(model_y) model_x = model_x[idx] model_y = model_y[idx] # first let's make sure the fitted Tmax is the real Tmax. # --> this is added bc when coefficients of higher PC templates # are too large, the acutal maximum on the fitted line maybe # at different epoch that the Tmax we fitted. # True maxmimum magnitude at fitted Tmax max_mag = get_modelval(theta[0], theta, fpca_f) # or max_mag = get_modelval(-0.03?, theta) FIXME # whenever fitted lc is brighter than maxmimum date's magnitude, add that difference to residual. max_violate = np.sum(abs(model_y-max_mag)[model_y < max_mag]) # second add the constraints of monotonically increase before penalty_increase # note preidx here is a number preidx = np.sum(model_x < penalty_increase) pre_diff = model_y[1:preidx] - model_y[0:preidx-1] pre_violate = np.sum(np.where(pre_diff < 0, 0, pre_diff)) # thrid add the constraints of monotonically decrease after penalty_decrease afteridx = np.sum(model_x < penalty_decrease) after_diff = model_y[afteridx+1:] - model_y[afteridx:-1] after_violate = np.sum(np.where(after_diff > 0, 0, after_diff)) resid += max_violate*10 + abs(after_violate) * \ 10 + abs(pre_violate*10) # user_dict = {"deviates": resid} return user_dict if init_guess is None: init_guess = [date[np.argmin(mag)], 17, 1, 0, 0, 0] init_guess = np.array(init_guess) m, n = len(date), len(init_guess) input_data = {'date': date, 'mag': mag, 'emag': emag, 'fpca_f': fpca_f, 'penalty_increase': penalty_increase, 'penalty_decrease': penalty_decrease} py_mp_par = list(pycmpfit.MpPar() for i in range(n)) py_mp_par[0].limited = [1, 1] py_mp_par[0].limits = [init_guess[0]-10, init_guess[0]+10] for ii in range(4-components): py_mp_par[-(ii+1)].fixed = True if boundary: for ii in range(components): py_mp_par[2+ii].limited = [1, 1] py_mp_par[2+ii].limits = boundary[ii] fit = pycmpfit.Mpfit(meritfunc, m, init_guess, private_data=input_data, py_mp_par=py_mp_par) fit.mpfit() # NOTE now init_guess has been updated fit_result = {'mpfit_result': fit.result, 'params': init_guess, } # calculate true reduced chi square # resid = get_modelval() return fit_result def make_fittedlc(fpca_f, fit_result, fpca_dir='', return_func=True): ''' :params fpca_f: fpca filter, options: vague, B, V, R, I :params mpfit_result :params fpca_dir: directory where fpca templates are at :params return_func: if true, return function, if not, return grids return function or grids depending on return_func ''' if fpca_f in ['B', 'V', 'R', 'I']: date = np.arange(-10, 50, 0.1) else: date = np.arange(-10, 40, 0.1) PCvecs = np.array(get_pctemplates(fpca_f)) PCvecs_discrete = [] for vec in PCvecs: PCvecs_discrete.append([vec(t) for t in date]) PCvecs_discrete = np.array(PCvecs_discrete) coeffs = np.array([fit_result['params'][i] for i in range(2, 6)]) coeffs = np.insert(coeffs, 0, 1) date += fit_result['params'][0] LC = fit_result['params'][1] + np.dot(np.transpose(PCvecs_discrete), coeffs) all_the_jacobians = np.column_stack((np.zeros(len(date)), np.ones(len(date)), PCvecs_discrete[0], PCvecs_discrete[1], PCvecs_discrete[2], PCvecs_discrete[3])) lc_error = [] # I don't want this to be a loop, but it works, so make this a vector operation later. for jac in all_the_jacobians: j = np.sqrt(np.matmul(jac,np.matmul(fit_result['mpfit_result'].covar,np.transpose(jac)))) lc_error.append(j) lc_error = np.array(lc_error) if return_func == False: return date, LC, lc_error else: return interp1d(date, LC), interp1d(date, lc_error) ############################################################################### # # test_dict = {'date': [1, 2, 3], 'mag': [3, 4, 5], 'emag': [4, 6, 3]} # # fit_pcparams(test_dict) # test_tab = Table([[1, 2, 3], [4, 5, 6], [7, 8, 9]], # names=('date', 'mag', 'emag')) # print('success') # fit_pcparams(test_tab) # print('success #2') fpca_f = 'V' basis = get_pctemplates(fpca_f) # print(basis[0](-20)) def get_modelval(date, theta, fpca_f): ''' Calculates the linear combination of coefficients and PC vectors at every point in the grid. Given a phase and parameters, returns the corresponding fitted magnitude. :params phase: :params theta: ''' basis = get_pctemplates(fpca_f) if not isinstance(date, float): date = np.array(date) tmax, mmax, a1, a2, a3, a4 = theta coeffs = [1, a1, a2, a3, a4] mphase = date-tmax y = mmax + (np.dot(coeffs, np.array([fbasis(mphase) for fbasis in basis]))) return y theta = [0, 0, 10, 0, 0, 0] x = np.arange(-10, 60, 1) # print(get_modelval([0, 1], theta)) # plt.scatter(x, get_modelval(x, theta)) # plt.show() a = pd.read_csv(os.path.join(abspath, '02boPriv.csv')) a = a[a.Passband == 'V(kait3)'] # print(a) data = {'date': np.array(a['MJD_OBS']) - a['MJD_OBS'].tolist()[np.argmin(np.array(a['MAG']))], 'mag': np.array( a['MAG']), 'emag': np.array(a['eMAG'])} res = fit_pcparams(data, fpca_f=fpca_f, init_guess=None, components=2, penalty=False, penalty_increase=None, penalty_decrease=None, boundary=None) # Test make_fittedlc() with return_func=True: lc,lcerr = make_fittedlc(fpca_f, res, fpca_dir='', return_func=True) plt.errorbar(data['date'],data['mag'],yerr=data['emag'],marker='o',linestyle='') plt.plot(np.arange(-9,50,0.1), lc(np.arange(-9,50,0.1)),label='make fitted lc') plt.plot(np.arange(-9,50,0.1),get_modelval(np.arange(-9,50,0.1),res['params'],fpca_f),label='get modelval') plt.fill_between(np.arange(-9,50,0.1), lc(np.arange(-9,50,0.1)) + lcerr(np.arange(-9,50,0.1)), lc(np.arange(-9,50,0.1)) - lcerr(np.arange(-9,50,0.1))) plt.gca().invert_yaxis() plt.legend() plt.show() # Test make_fittedlc() with return_func=False: # epoch,lc,lcerr = make_fittedlc(fpca_f, res, fpca_dir='', return_func=False) # plt.errorbar(data['date'],data['mag'],yerr=data['emag'],marker='o',linestyle='') # plt.plot(epoch,lc,label='make fitted lc') # plt.plot(np.arange(-9,50,0.1),get_modelval(np.arange(-9,50,0.1),res['params'],fpca_f),label='get modelval') # plt.fill_between(epoch,lc+lcerr, lc-lcerr) # plt.gca().invert_yaxis() # plt.legend() # plt.show()
[ "numpy.sum", "numpy.isnan", "numpy.argmin", "pycmpfit.MpPar", "numpy.arange", "matplotlib.pyplot.gca", "scipy.interpolate.interp1d", "os.path.join", "os.path.dirname", "numpy.transpose", "numpy.insert", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.show", "pycmpfit.Mpfit", "matplotlib...
[((204, 276), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""/home/astrolab/pycmpfit/build/lib.linux-x86_64-3.6"""'], {}), "(1, '/home/astrolab/pycmpfit/build/lib.linux-x86_64-3.6')\n", (219, 276), False, 'import sys\n'), ((333, 358), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (348, 358), False, 'import os\n'), ((370, 404), 'os.path.join', 'os.path.join', (['abspath', '"""LCfPCA_He"""'], {}), "(abspath, 'LCfPCA_He')\n", (382, 404), False, 'import os\n'), ((11083, 11104), 'numpy.arange', 'np.arange', (['(-10)', '(60)', '(1)'], {}), '(-10, 60, 1)\n', (11092, 11104), True, 'import numpy as np\n'), ((11753, 11841), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (["data['date']", "data['mag']"], {'yerr': "data['emag']", 'marker': '"""o"""', 'linestyle': '""""""'}), "(data['date'], data['mag'], yerr=data['emag'], marker='o',\n linestyle='')\n", (11765, 11841), True, 'import matplotlib.pyplot as plt\n'), ((12198, 12210), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (12208, 12210), True, 'import matplotlib.pyplot as plt\n'), ((12211, 12221), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12219, 12221), True, 'import matplotlib.pyplot as plt\n'), ((1281, 1310), 'os.path.join', 'os.path.join', (['FPCA_dir', 'fname'], {}), '(FPCA_dir, fname)\n', (1293, 1310), False, 'import os\n'), ((1331, 1368), 'astropy.table.Table.read', 'Table.read', (['fpca_file'], {'format': '"""ascii"""'}), "(fpca_file, format='ascii')\n", (1341, 1368), False, 'from astropy.table import Table\n'), ((1513, 1573), 'scipy.interpolate.interp1d', 'interp1d', (['phase', 'mean'], {'fill_value': 'np.nan', 'bounds_error': '(False)'}), '(phase, mean, fill_value=np.nan, bounds_error=False)\n', (1521, 1573), False, 'from scipy.interpolate import interp1d\n'), ((1585, 1644), 'scipy.interpolate.interp1d', 'interp1d', (['phase', 'pc1'], {'fill_value': 'np.nan', 'bounds_error': '(False)'}), '(phase, pc1, fill_value=np.nan, bounds_error=False)\n', (1593, 1644), False, 'from scipy.interpolate import interp1d\n'), ((1656, 1715), 'scipy.interpolate.interp1d', 'interp1d', (['phase', 'pc2'], {'fill_value': 'np.nan', 'bounds_error': '(False)'}), '(phase, pc2, fill_value=np.nan, bounds_error=False)\n', (1664, 1715), False, 'from scipy.interpolate import interp1d\n'), ((1727, 1786), 'scipy.interpolate.interp1d', 'interp1d', (['phase', 'pc3'], {'fill_value': 'np.nan', 'bounds_error': '(False)'}), '(phase, pc3, fill_value=np.nan, bounds_error=False)\n', (1735, 1786), False, 'from scipy.interpolate import interp1d\n'), ((1798, 1857), 'scipy.interpolate.interp1d', 'interp1d', (['phase', 'pc4'], {'fill_value': 'np.nan', 'bounds_error': '(False)'}), '(phase, pc4, fill_value=np.nan, bounds_error=False)\n', (1806, 1857), False, 'from scipy.interpolate import interp1d\n'), ((7534, 7554), 'numpy.array', 'np.array', (['init_guess'], {}), '(init_guess)\n', (7542, 7554), True, 'import numpy as np\n'), ((8155, 8246), 'pycmpfit.Mpfit', 'pycmpfit.Mpfit', (['meritfunc', 'm', 'init_guess'], {'private_data': 'input_data', 'py_mp_par': 'py_mp_par'}), '(meritfunc, m, init_guess, private_data=input_data, py_mp_par\n =py_mp_par)\n', (8169, 8246), False, 'import pycmpfit\n'), ((9150, 9175), 'numpy.array', 'np.array', (['PCvecs_discrete'], {}), '(PCvecs_discrete)\n', (9158, 9175), True, 'import numpy as np\n'), ((9260, 9283), 'numpy.insert', 'np.insert', (['coeffs', '(0)', '(1)'], {}), '(coeffs, 0, 1)\n', (9269, 9283), True, 'import numpy as np\n'), ((9889, 9907), 'numpy.array', 'np.array', (['lc_error'], {}), '(lc_error)\n', (9897, 9907), True, 'import numpy as np\n'), ((11213, 11250), 'os.path.join', 'os.path.join', (['abspath', '"""02boPriv.csv"""'], {}), "(abspath, '02boPriv.csv')\n", (11225, 11250), False, 'import os\n'), ((11397, 11415), 'numpy.array', 'np.array', (["a['MAG']"], {}), "(a['MAG'])\n", (11405, 11415), True, 'import numpy as np\n'), ((11430, 11449), 'numpy.array', 'np.array', (["a['eMAG']"], {}), "(a['eMAG'])\n", (11438, 11449), True, 'import numpy as np\n'), ((11843, 11865), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (11852, 11865), True, 'import numpy as np\n'), ((11923, 11945), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (11932, 11945), True, 'import numpy as np\n'), ((12039, 12061), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (12048, 12061), True, 'import numpy as np\n'), ((8900, 8923), 'numpy.arange', 'np.arange', (['(-10)', '(50)', '(0.1)'], {}), '(-10, 50, 0.1)\n', (8909, 8923), True, 'import numpy as np\n'), ((8949, 8972), 'numpy.arange', 'np.arange', (['(-10)', '(40)', '(0.1)'], {}), '(-10, 40, 0.1)\n', (8958, 8972), True, 'import numpy as np\n'), ((10822, 10836), 'numpy.array', 'np.array', (['date'], {}), '(date)\n', (10830, 10836), True, 'import numpy as np\n'), ((11311, 11333), 'numpy.array', 'np.array', (["a['MJD_OBS']"], {}), "(a['MJD_OBS'])\n", (11319, 11333), True, 'import numpy as np\n'), ((11868, 11890), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (11877, 11890), True, 'import numpy as np\n'), ((11957, 11979), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (11966, 11979), True, 'import numpy as np\n'), ((12173, 12182), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (12180, 12182), True, 'import matplotlib.pyplot as plt\n'), ((2998, 3010), 'numpy.array', 'np.array', (['ii'], {}), '(ii)\n', (3006, 3010), True, 'import numpy as np\n'), ((3071, 3083), 'numpy.array', 'np.array', (['ii'], {}), '(ii)\n', (3079, 3083), True, 'import numpy as np\n'), ((3641, 3663), 'numpy.array', 'np.array', (["data['emag']"], {}), "(data['emag'])\n", (3649, 3663), True, 'import numpy as np\n'), ((3807, 3829), 'numpy.array', 'np.array', (["data['date']"], {}), "(data['date'])\n", (3815, 3829), True, 'import numpy as np\n'), ((3831, 3852), 'numpy.array', 'np.array', (["data['mag']"], {}), "(data['mag'])\n", (3839, 3852), True, 'import numpy as np\n'), ((3969, 3991), 'numpy.array', 'np.array', (["data['emag']"], {}), "(data['emag'])\n", (3977, 3991), True, 'import numpy as np\n'), ((4540, 4554), 'numpy.array', 'np.array', (['date'], {}), '(date)\n', (4548, 4554), True, 'import numpy as np\n'), ((5533, 5548), 'numpy.isnan', 'np.isnan', (['resid'], {}), '(resid)\n', (5541, 5548), True, 'import numpy as np\n'), ((6794, 6828), 'numpy.sum', 'np.sum', (['(model_x < penalty_increase)'], {}), '(model_x < penalty_increase)\n', (6800, 6828), True, 'import numpy as np\n'), ((7075, 7109), 'numpy.sum', 'np.sum', (['(model_x < penalty_decrease)'], {}), '(model_x < penalty_decrease)\n', (7081, 7109), True, 'import numpy as np\n'), ((7786, 7802), 'pycmpfit.MpPar', 'pycmpfit.MpPar', ([], {}), '()\n', (7800, 7802), False, 'import pycmpfit\n'), ((9362, 9391), 'numpy.transpose', 'np.transpose', (['PCvecs_discrete'], {}), '(PCvecs_discrete)\n', (9374, 9391), True, 'import numpy as np\n'), ((9997, 10015), 'scipy.interpolate.interp1d', 'interp1d', (['date', 'LC'], {}), '(date, LC)\n', (10005, 10015), False, 'from scipy.interpolate import interp1d\n'), ((10017, 10041), 'scipy.interpolate.interp1d', 'interp1d', (['date', 'lc_error'], {}), '(date, lc_error)\n', (10025, 10041), False, 'from scipy.interpolate import interp1d\n'), ((12064, 12086), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (12073, 12086), True, 'import numpy as np\n'), ((12094, 12116), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (12103, 12116), True, 'import numpy as np\n'), ((12120, 12142), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (12129, 12142), True, 'import numpy as np\n'), ((12150, 12172), 'numpy.arange', 'np.arange', (['(-9)', '(50)', '(0.1)'], {}), '(-9, 50, 0.1)\n', (12159, 12172), True, 'import numpy as np\n'), ((3435, 3452), 'numpy.array', 'np.array', (['data[x]'], {}), '(data[x])\n', (3443, 3452), True, 'import numpy as np\n'), ((5215, 5239), 'numpy.array', 'np.array', (['input_data[xx]'], {}), '(input_data[xx])\n', (5223, 5239), True, 'import numpy as np\n'), ((5798, 5822), 'numpy.arange', 'np.arange', (['(-10)', '(50)', '(0.01)'], {}), '(-10, 50, 0.01)\n', (5807, 5822), True, 'import numpy as np\n'), ((5912, 5929), 'numpy.isnan', 'np.isnan', (['model_y'], {}), '(model_y)\n', (5920, 5929), True, 'import numpy as np\n'), ((6925, 6960), 'numpy.where', 'np.where', (['(pre_diff < 0)', '(0)', 'pre_diff'], {}), '(pre_diff < 0, 0, pre_diff)\n', (6933, 6960), True, 'import numpy as np\n'), ((7214, 7253), 'numpy.where', 'np.where', (['(after_diff > 0)', '(0)', 'after_diff'], {}), '(after_diff > 0, 0, after_diff)\n', (7222, 7253), True, 'import numpy as np\n'), ((7484, 7498), 'numpy.argmin', 'np.argmin', (['mag'], {}), '(mag)\n', (7493, 7498), True, 'import numpy as np\n'), ((11368, 11386), 'numpy.array', 'np.array', (["a['MAG']"], {}), "(a['MAG'])\n", (11376, 11386), True, 'import numpy as np\n'), ((9826, 9843), 'numpy.transpose', 'np.transpose', (['jac'], {}), '(jac)\n', (9838, 9843), True, 'import numpy as np\n')]
import os import sys import torch import random import logging import numpy as np def setup_seed(seed=20211117): # there are still other seed to set, NASBenchDataset random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True def setup_logger(save_path=None, mode='a') -> logging.Logger: logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.propagate = False formatter = logging.Formatter("[%(asctime)s]: %(message)s", datefmt="%m/%d %H:%M:%S") if save_path is not None: if os.path.exists(save_path): os.remove(save_path) log_file = open(save_path, 'w') log_file.close() file_handler = logging.FileHandler(save_path, mode=mode) file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) logger.addHandler(file_handler) console_handler = logging.StreamHandler(sys.stdout) console_handler.setLevel(logging.DEBUG) console_handler.setFormatter(formatter) logger.addHandler(console_handler) return logger
[ "os.remove", "numpy.random.seed", "logging.FileHandler", "torch.manual_seed", "logging.StreamHandler", "torch.cuda.manual_seed", "os.path.exists", "logging.Formatter", "torch.cuda.manual_seed_all", "random.seed", "logging.getLogger" ]
[((176, 193), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (187, 193), False, 'import random\n'), ((198, 218), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (212, 218), True, 'import numpy as np\n'), ((223, 246), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (240, 246), False, 'import torch\n'), ((251, 279), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (273, 279), False, 'import torch\n'), ((284, 316), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (310, 316), False, 'import torch\n'), ((482, 501), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (499, 501), False, 'import logging\n'), ((582, 655), 'logging.Formatter', 'logging.Formatter', (['"""[%(asctime)s]: %(message)s"""'], {'datefmt': '"""%m/%d %H:%M:%S"""'}), "('[%(asctime)s]: %(message)s', datefmt='%m/%d %H:%M:%S')\n", (599, 655), False, 'import logging\n'), ((1076, 1109), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (1097, 1109), False, 'import logging\n'), ((732, 757), 'os.path.exists', 'os.path.exists', (['save_path'], {}), '(save_path)\n', (746, 757), False, 'import os\n'), ((881, 922), 'logging.FileHandler', 'logging.FileHandler', (['save_path'], {'mode': 'mode'}), '(save_path, mode=mode)\n', (900, 922), False, 'import logging\n'), ((771, 791), 'os.remove', 'os.remove', (['save_path'], {}), '(save_path)\n', (780, 791), False, 'import os\n')]
import numpy as np def train_test_splice(X, y, test_ratio=0.2, seed = None): """将数据 X 和 y 按照 test_ratio 分割成 X_train, y_train, X_test, y_test""" assert X.shape[0] == y.shape[0], \ "the size of X must be equal to the size of y" assert 0.0 <= test_ratio <= 1.0, \ "test_ratio must be valid" if seed: np.random.seed(seed) shuffle_index = np.random.permutation(len(X)) test_ratio = 0.2 test_size = int(len(X) * test_ratio) train_index = shuffle_index[test_size:] test_index = shuffle_index[:test_size] X_train = X[train_index] y_train = y[train_index] X_test = X[test_index] y_test = y[test_index] return X_train, y_train, X_test, y_test
[ "numpy.random.seed" ]
[((338, 358), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (352, 358), True, 'import numpy as np\n')]
from Clean_Json import clean_json from Find_Best_Hyperparameters import get_best_lr import numpy as np from Pycox import evaluate_model from Train_models import train_MTL_model from Make_h5_trained_models.py import Extract_Image_Features import warnings import pandas import os from extract_variables import extract_variables extract_variables() clean_json() for Clinical_Set in ['Efficientnet_fine', 'Resnet_fine', 'Resnet_pretrained','Efficientnet_pretrained']: train_MTL_model(Clinical_Set) Extract_Image_Features(Clinical_Set) LRs = 1 / (10 ** (np.arange(4, 15) / 4)) visits = [['00', '04', '06'],['00']] Clinical_Sets = ['a','b','Efficientnet_fine', 'Resnet_fine', 'Resnet_pretrained','Efficientnet_pretrained'] best_lrs = {} best_lrs_df = pandas.DataFrame() model_types = ['LSTM','MLP','CoxPH'] # for model_type in model_types: for visit in visits: for Clinical_Set in Clinical_Sets: if(model_type == 'LSTM' and len(visit) == 1): best_lrs[Clinical_Set.upper()+str(len(visit))] = 0 else: results = evaluate_model(top_dir = os.getcwd()+'/data/', visits = visit, Clinical_Set = Clinical_Set, model_type=model_type, test='dev', LRs = LRs) best_lr = get_best_lr(results) best_lrs[Clinical_Set.upper()+str(len(visit))] = best_lr print(best_lrs) best_lrs_df = pandas.concat([best_lrs_df, pandas.DataFrame.from_dict(best_lrs, orient='index', columns = [model_type])], axis=1) best_lrs_df.to_csv('data/Best_LRs.csv') best_lrs_df = pandas.read_csv('data/Best_LRs.csv', index_col=0) test_results = pandas.DataFrame() for model_type in model_types: for visit in visits: for Clinical_Set in Clinical_Sets: if(model_type == 'LSTM' and len(visit) == 1): pass else: lr = [best_lrs_df.loc[Clinical_Set.upper()+str(len(visit))][model_type]] results = evaluate_model(top_dir = '/Users/gregory/Documents/Weill_Cornell/Wang_Lab/AMD/AMIA/Coding_Files/data/', visits = visit, Clinical_Set = Clinical_Set, model_type=model_type, test='test', LRs = lr) #results.to_csv(model_type+'_'+Clinical_Set.upper()+str(len(visit))+'.csv') results.columns = [model_type+'_'+Clinical_Set.upper()+str(len(visit))] test_results = pandas.concat([test_results, results], axis=1) test_results.to_csv('TEST_RESULTS.csv')
[ "Clean_Json.clean_json", "pandas.DataFrame", "pandas.DataFrame.from_dict", "pandas.read_csv", "os.getcwd", "Make_h5_trained_models.py.Extract_Image_Features", "Train_models.train_MTL_model", "numpy.arange", "Pycox.evaluate_model", "pandas.concat", "Find_Best_Hyperparameters.get_best_lr", "extr...
[((327, 346), 'extract_variables.extract_variables', 'extract_variables', ([], {}), '()\n', (344, 346), False, 'from extract_variables import extract_variables\n'), ((347, 359), 'Clean_Json.clean_json', 'clean_json', ([], {}), '()\n', (357, 359), False, 'from Clean_Json import clean_json\n'), ((755, 773), 'pandas.DataFrame', 'pandas.DataFrame', ([], {}), '()\n', (771, 773), False, 'import pandas\n'), ((1559, 1608), 'pandas.read_csv', 'pandas.read_csv', (['"""data/Best_LRs.csv"""'], {'index_col': '(0)'}), "('data/Best_LRs.csv', index_col=0)\n", (1574, 1608), False, 'import pandas\n'), ((1624, 1642), 'pandas.DataFrame', 'pandas.DataFrame', ([], {}), '()\n', (1640, 1642), False, 'import pandas\n'), ((469, 498), 'Train_models.train_MTL_model', 'train_MTL_model', (['Clinical_Set'], {}), '(Clinical_Set)\n', (484, 498), False, 'from Train_models import train_MTL_model\n'), ((503, 539), 'Make_h5_trained_models.py.Extract_Image_Features', 'Extract_Image_Features', (['Clinical_Set'], {}), '(Clinical_Set)\n', (525, 539), False, 'from Make_h5_trained_models.py import Extract_Image_Features\n'), ((559, 575), 'numpy.arange', 'np.arange', (['(4)', '(15)'], {}), '(4, 15)\n', (568, 575), True, 'import numpy as np\n'), ((1413, 1487), 'pandas.DataFrame.from_dict', 'pandas.DataFrame.from_dict', (['best_lrs'], {'orient': '"""index"""', 'columns': '[model_type]'}), "(best_lrs, orient='index', columns=[model_type])\n", (1439, 1487), False, 'import pandas\n'), ((1245, 1265), 'Find_Best_Hyperparameters.get_best_lr', 'get_best_lr', (['results'], {}), '(results)\n', (1256, 1265), False, 'from Find_Best_Hyperparameters import get_best_lr\n'), ((1954, 2155), 'Pycox.evaluate_model', 'evaluate_model', ([], {'top_dir': '"""/Users/gregory/Documents/Weill_Cornell/Wang_Lab/AMD/AMIA/Coding_Files/data/"""', 'visits': 'visit', 'Clinical_Set': 'Clinical_Set', 'model_type': 'model_type', 'test': '"""test"""', 'LRs': 'lr'}), "(top_dir=\n '/Users/gregory/Documents/Weill_Cornell/Wang_Lab/AMD/AMIA/Coding_Files/data/'\n , visits=visit, Clinical_Set=Clinical_Set, model_type=model_type, test=\n 'test', LRs=lr)\n", (1968, 2155), False, 'from Pycox import evaluate_model\n'), ((2360, 2406), 'pandas.concat', 'pandas.concat', (['[test_results, results]'], {'axis': '(1)'}), '([test_results, results], axis=1)\n', (2373, 2406), False, 'import pandas\n'), ((1106, 1117), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1115, 1117), False, 'import os\n')]
from math import cos import matplotlib.pyplot as plt import numpy as np from src.eig_problem.FFTfromFile1D import FFTfromFile1D from src.eig_problem.WektorySieciOdwrotnej import WektorySieciOdwrotnej # FIXME: Move from ParametryMaterialowe to nwe concept of reading data class StaticDemagnetizingField1D: def __init__(self, input_fft, field_angle): self.tmp = FFTfromFile1D(input_fft) self.field_angle = field_angle self.ilosc_wektorow = self.tmp.ilosc_wektorow self.input_fft = input_fft self.coefficient = self.tmp.fourier_coefficient(ParametryMaterialowe.MoA, ParametryMaterialowe.MoB) self.reciprocal_vector = 2 * np.pi * WektorySieciOdwrotnej(self.ilosc_wektorow).lista_wektorow1d('max') \ / ParametryMaterialowe.a def elementary_cell_reconstruction(self, grid): coefficient = np.transpose(np.loadtxt('c_coef_100.txt').view(complex)) x = np.linspace(-ParametryMaterialowe.a, 0, grid) tmp = np.zeros(grid) for ind in enumerate(x): tmp[ind[0]] = abs(self.inverse_discrete_fourier_transform(coefficient, ind[1])) return x , tmp / (10 / 7) + 0.3 def inverse_discrete_fourier_transform(self, data, vector_position): reciprocal_vectors = np.array(2 * np.pi * WektorySieciOdwrotnej(max(data.shape)).lista_wektorow1d('min') / ParametryMaterialowe.a) return np.sum(data * np.exp(1j * reciprocal_vectors * vector_position)) def demagnetizing_field_at_point(self, location): tmp1 = np.ones(len(self.coefficient)) - np.exp(-np.absolute(self.reciprocal_vector) * ParametryMaterialowe.d / 2.) return np.sum(tmp1 * self.coefficient * np.exp(1j * location * self.reciprocal_vector)).real \ * cos(self.field_angle / 360 * 2 * np.pi) def demagnetizing_field(self): elementary_cell = np.linspace(-ParametryMaterialowe.a, 0, 1000) demag = np.zeros(len(elementary_cell)) for i in enumerate(elementary_cell): demag[i[0]] = self.demagnetizing_field_at_point(i[1]) return elementary_cell, -demag *ParametryMaterialowe.mu0 def demagnetizing_field_plot(self): tmp = self.demagnetizing_field() #tmp1 = self.elementary_cell_reconstruction(500) #plt.plot(tmp1[0], tmp1[1]) plt.plot(tmp[0], tmp[1]) #plt.ylim([-120000, 120000]) plt.savefig('normalized_demagnetized_field_sin_like.png') plt.show() def save_to_file(self): tmp = self.demagnetizing_field() np.savetxt('demag_field_' + str(self.field_angle) + '.txt', np.transpose(tmp)) if __name__ == "__main__": pass
[ "numpy.absolute", "matplotlib.pyplot.show", "src.eig_problem.WektorySieciOdwrotnej.WektorySieciOdwrotnej", "matplotlib.pyplot.plot", "numpy.zeros", "numpy.transpose", "math.cos", "numpy.linspace", "numpy.exp", "src.eig_problem.FFTfromFile1D.FFTfromFile1D", "numpy.loadtxt", "matplotlib.pyplot.s...
[((376, 400), 'src.eig_problem.FFTfromFile1D.FFTfromFile1D', 'FFTfromFile1D', (['input_fft'], {}), '(input_fft)\n', (389, 400), False, 'from src.eig_problem.FFTfromFile1D import FFTfromFile1D\n'), ((953, 998), 'numpy.linspace', 'np.linspace', (['(-ParametryMaterialowe.a)', '(0)', 'grid'], {}), '(-ParametryMaterialowe.a, 0, grid)\n', (964, 998), True, 'import numpy as np\n'), ((1013, 1027), 'numpy.zeros', 'np.zeros', (['grid'], {}), '(grid)\n', (1021, 1027), True, 'import numpy as np\n'), ((1924, 1969), 'numpy.linspace', 'np.linspace', (['(-ParametryMaterialowe.a)', '(0)', '(1000)'], {}), '(-ParametryMaterialowe.a, 0, 1000)\n', (1935, 1969), True, 'import numpy as np\n'), ((2376, 2400), 'matplotlib.pyplot.plot', 'plt.plot', (['tmp[0]', 'tmp[1]'], {}), '(tmp[0], tmp[1])\n', (2384, 2400), True, 'import matplotlib.pyplot as plt\n'), ((2446, 2503), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""normalized_demagnetized_field_sin_like.png"""'], {}), "('normalized_demagnetized_field_sin_like.png')\n", (2457, 2503), True, 'import matplotlib.pyplot as plt\n'), ((2512, 2522), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2520, 2522), True, 'import matplotlib.pyplot as plt\n'), ((1822, 1861), 'math.cos', 'cos', (['(self.field_angle / 360 * 2 * np.pi)'], {}), '(self.field_angle / 360 * 2 * np.pi)\n', (1825, 1861), False, 'from math import cos\n'), ((2661, 2678), 'numpy.transpose', 'np.transpose', (['tmp'], {}), '(tmp)\n', (2673, 2678), True, 'import numpy as np\n'), ((1473, 1524), 'numpy.exp', 'np.exp', (['(1.0j * reciprocal_vectors * vector_position)'], {}), '(1.0j * reciprocal_vectors * vector_position)\n', (1479, 1524), True, 'import numpy as np\n'), ((897, 925), 'numpy.loadtxt', 'np.loadtxt', (['"""c_coef_100.txt"""'], {}), "('c_coef_100.txt')\n", (907, 925), True, 'import numpy as np\n'), ((682, 724), 'src.eig_problem.WektorySieciOdwrotnej.WektorySieciOdwrotnej', 'WektorySieciOdwrotnej', (['self.ilosc_wektorow'], {}), '(self.ilosc_wektorow)\n', (703, 724), False, 'from src.eig_problem.WektorySieciOdwrotnej import WektorySieciOdwrotnej\n'), ((1750, 1798), 'numpy.exp', 'np.exp', (['(1.0j * location * self.reciprocal_vector)'], {}), '(1.0j * location * self.reciprocal_vector)\n', (1756, 1798), True, 'import numpy as np\n'), ((1635, 1670), 'numpy.absolute', 'np.absolute', (['self.reciprocal_vector'], {}), '(self.reciprocal_vector)\n', (1646, 1670), True, 'import numpy as np\n')]
from styx_msgs.msg import TrafficLight import cv2 import numpy as np import tensorflow as tf import rospy import os import yaml img_path = os.path.dirname(os.path.realpath(__file__)) + '/../../../../test_images/simulator/' m_wdt = 300 m_hgt = 300 r_image = False class TLClassifier(object): def __init__(self): self.session = None self.model_gb = None self.image_counter = 0 self.classes = {1: TrafficLight.RED, 2: TrafficLight.YELLOW, 3: TrafficLight.GREEN, 4: TrafficLight.UNKNOWN} config_string = rospy.get_param("/traffic_light_config") self.config = yaml.load(config_string) self.load_model(self.get_model_path()) def get_classification(self, image): """Determines the color of the traffic light in the image Args: image (cv::Mat): image containing the traffic light Returns: int: ID of traffic light color (specified in styx_msgs/TrafficLight) """ class_idx, prb = self.predict(image) if class_idx is not None: rospy.logdebug("class: %d, prb: %f", class_idx, prb) return class_idx def load_model(self, model_path): config = tf.ConfigProto() config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1 self.model_gb = tf.Graph() with tf.Session(graph=self.model_gb, config=config) as sess: self.session = sess graph_def = tf.GraphDef() with tf.gfile.GFile(model_path, 'rb') as model_file: serialized_graph = model_file.read() graph_def.ParseFromString(serialized_graph) tf.import_graph_def(graph_def, name='') def predict(self, img_np_, score_thresh=0.5): image_tensor = self.model_gb.get_tensor_by_name('image_tensor:0') detection_boxes = self.model_gb.get_tensor_by_name('detection_boxes:0') detection_scores = self.model_gb.get_tensor_by_name('detection_scores:0') detection_classes = self.model_gb.get_tensor_by_name('detection_classes:0') img_np_ = self.preprocess_img(img_np_) (boxes, scores, classes) = self.session.run( [detection_boxes, detection_scores, detection_classes], feed_dict={image_tensor: np.expand_dims(img_np_, axis=0)}) scores = np.squeeze(scores) classes = np.squeeze(classes) boxes = np.squeeze(boxes) for i, box in enumerate(boxes): if scores[i] > score_thresh: light_class = self.classes[classes[i]] self.save_image(img_np_, light_class) rospy.logdebug("Traffic Light detected by the model : %d Class", light_class) return light_class, scores[i] else: self.save_image(img_np_, TrafficLight.UNKNOWN) return None, None def preprocess_img(self, img): img = cv2.resize(img, (m_wdt, m_hgt)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img def save_image(self, image, light_class): if r_image: bgr_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) cv2.imwrite(os.path.join(img_path, "image_%04i_%d.jpg" % (self.image_counter, light_class)), bgr_image) self.image_counter += 1 def get_model_path(self): return os.path.dirname(os.path.realpath(__file__)) + self.config['detection_model'] def resize_image(self, image): hgt, wdt = image.shape[:2] if m_hgt < hgt or m_wdt < wdt: scaling_factor = m_hgt / float(hgt) if m_wdt / float(wdt) < scaling_factor: scaling_factor = m_wdt / float(wdt) image = cv2.resize(image, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) return image
[ "yaml.load", "cv2.cvtColor", "os.path.realpath", "tensorflow.Session", "numpy.expand_dims", "rospy.get_param", "tensorflow.ConfigProto", "rospy.logdebug", "tensorflow.gfile.GFile", "tensorflow.Graph", "numpy.squeeze", "tensorflow.import_graph_def", "tensorflow.GraphDef", "os.path.join", ...
[((156, 182), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (172, 182), False, 'import os\n'), ((619, 659), 'rospy.get_param', 'rospy.get_param', (['"""/traffic_light_config"""'], {}), "('/traffic_light_config')\n", (634, 659), False, 'import rospy\n'), ((682, 706), 'yaml.load', 'yaml.load', (['config_string'], {}), '(config_string)\n', (691, 706), False, 'import yaml\n'), ((1280, 1296), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (1294, 1296), True, 'import tensorflow as tf\n'), ((1412, 1422), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1420, 1422), True, 'import tensorflow as tf\n'), ((2423, 2441), 'numpy.squeeze', 'np.squeeze', (['scores'], {}), '(scores)\n', (2433, 2441), True, 'import numpy as np\n'), ((2460, 2479), 'numpy.squeeze', 'np.squeeze', (['classes'], {}), '(classes)\n', (2470, 2479), True, 'import numpy as np\n'), ((2496, 2513), 'numpy.squeeze', 'np.squeeze', (['boxes'], {}), '(boxes)\n', (2506, 2513), True, 'import numpy as np\n'), ((3001, 3032), 'cv2.resize', 'cv2.resize', (['img', '(m_wdt, m_hgt)'], {}), '(img, (m_wdt, m_hgt))\n', (3011, 3032), False, 'import cv2\n'), ((3047, 3083), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (3059, 3083), False, 'import cv2\n'), ((3898, 3936), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (3910, 3936), False, 'import cv2\n'), ((1146, 1198), 'rospy.logdebug', 'rospy.logdebug', (['"""class: %d, prb: %f"""', 'class_idx', 'prb'], {}), "('class: %d, prb: %f', class_idx, prb)\n", (1160, 1198), False, 'import rospy\n'), ((1436, 1482), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.model_gb', 'config': 'config'}), '(graph=self.model_gb, config=config)\n', (1446, 1482), True, 'import tensorflow as tf\n'), ((1548, 1561), 'tensorflow.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (1559, 1561), True, 'import tensorflow as tf\n'), ((3194, 3232), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2BGR'], {}), '(image, cv2.COLOR_RGB2BGR)\n', (3206, 3232), False, 'import cv2\n'), ((3790, 3886), 'cv2.resize', 'cv2.resize', (['image', 'None'], {'fx': 'scaling_factor', 'fy': 'scaling_factor', 'interpolation': 'cv2.INTER_AREA'}), '(image, None, fx=scaling_factor, fy=scaling_factor, interpolation\n =cv2.INTER_AREA)\n', (3800, 3886), False, 'import cv2\n'), ((1579, 1611), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['model_path', '"""rb"""'], {}), "(model_path, 'rb')\n", (1593, 1611), True, 'import tensorflow as tf\n'), ((1756, 1795), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['graph_def'], {'name': '""""""'}), "(graph_def, name='')\n", (1775, 1795), True, 'import tensorflow as tf\n'), ((2720, 2797), 'rospy.logdebug', 'rospy.logdebug', (['"""Traffic Light detected by the model : %d Class"""', 'light_class'], {}), "('Traffic Light detected by the model : %d Class', light_class)\n", (2734, 2797), False, 'import rospy\n'), ((3257, 3336), 'os.path.join', 'os.path.join', (['img_path', "('image_%04i_%d.jpg' % (self.image_counter, light_class))"], {}), "(img_path, 'image_%04i_%d.jpg' % (self.image_counter, light_class))\n", (3269, 3336), False, 'import os\n'), ((3447, 3473), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (3463, 3473), False, 'import os\n'), ((2372, 2403), 'numpy.expand_dims', 'np.expand_dims', (['img_np_'], {'axis': '(0)'}), '(img_np_, axis=0)\n', (2386, 2403), True, 'import numpy as np\n')]
# coding=utf-8 # Copyright 2021 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 experiment.""" import os import tempfile from absl.testing import absltest from absl.testing import parameterized import numpy as np import experiment class ExperimentTest(parameterized.TestCase): def _write_mock_mogwai_state_dict(self): l = 3 v = 2 bias = np.ones((l, v)) weight = np.zeros((l, v, l, v)) query_seq = np.zeros(l) state_dict = { 'bias': bias, 'weight': weight , 'query_seq': query_seq, } _, filepath = tempfile.mkstemp(suffix='.npz') np.savez(filepath, **state_dict) self._vocab_size = v self._mock_mogwai_filepath = filepath def setUp(self): super().setUp() self._write_mock_mogwai_state_dict() def tearDown(self): super().tearDown() os.remove(self._mock_mogwai_filepath) @parameterized.parameters( ('cnn'), ('linear'), ) def test_run_regression_experiment_deterministic(self, model_name): regression_kwargs = dict( mogwai_filepath=self._mock_mogwai_filepath, potts_coupling_scale=1.0, potts_field_scale=1.0, potts_single_mut_offset=0.0, potts_epi_offset=0.0, vocab_size=self._vocab_size, training_set_min_num_mutations=0, training_set_max_num_mutations=3, training_set_num_samples=100, training_set_include_singles=True, training_set_random_seed=0, model_name=model_name, model_random_seed=0, metrics_random_split_fraction=0.8, metrics_random_split_random_seed=0, metrics_distance_split_radii=[1, 2]) run_one = experiment.run_regression_experiment(**regression_kwargs) run_two = experiment.run_regression_experiment(**regression_kwargs) # Test deterministic runs. self.assertEqual(run_one, run_two) expected_split_keys = [ 'random_split', 'distance_split_1', 'distance_split_2' ] expected_metric_keys = [ 'mse', 'std_test', 'std_predicted', 'test_size', 'train_size' ] for split_key in expected_split_keys: self.assertIn(split_key, run_one.keys()) for metric_key in expected_metric_keys: self.assertIn(metric_key, run_one[split_key].keys()) @parameterized.parameters( ('cnn',), ('linear',), ) def test_run_design_experiment_deterministic(self, model_name): design_kwargs = dict( mogwai_filepath=self._mock_mogwai_filepath, potts_coupling_scale=1.0, potts_field_scale=1.0, potts_single_mut_offset=0.0, potts_epi_offset=0.0, vocab_size=self._vocab_size, training_set_min_num_mutations=0, training_set_max_num_mutations=3, training_set_num_samples=100, training_set_include_singles=True, training_set_random_seed=0, model_name=model_name, model_random_seed=0, mbo_random_seed=0, mbo_num_designs=1000, inner_loop_solver_top_k=50, inner_loop_solver_min_mutations=1, inner_loop_solver_max_mutations=3, inner_loop_num_rounds=1, inner_loop_num_samples=10, design_metrics_hit_threshold=0, design_metrics_cluster_hamming_distance=3, design_metrics_fitness_percentiles=[0.5, 0.9], ) run_one = experiment.run_design_experiment(**design_kwargs) run_two = experiment.run_design_experiment(**design_kwargs) # Test deterministic runs. self.assertEqual(run_one, run_two) expected_keys = [ 'diversity_normalize_hit_rate', '0.5_percentile_fitness', '0.9_percentile_fitness' ] for key in expected_keys: self.assertIn(key, run_one.keys()) if __name__ == '__main__': absltest.main()
[ "absl.testing.absltest.main", "os.remove", "tempfile.mkstemp", "numpy.zeros", "numpy.ones", "absl.testing.parameterized.parameters", "experiment.run_regression_experiment", "numpy.savez", "experiment.run_design_experiment" ]
[((1415, 1456), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['"""cnn"""', '"""linear"""'], {}), "('cnn', 'linear')\n", (1439, 1456), False, 'from absl.testing import parameterized\n'), ((2809, 2856), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (["('cnn',)", "('linear',)"], {}), "(('cnn',), ('linear',))\n", (2833, 2856), False, 'from absl.testing import parameterized\n'), ((4275, 4290), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (4288, 4290), False, 'from absl.testing import absltest\n'), ((897, 912), 'numpy.ones', 'np.ones', (['(l, v)'], {}), '((l, v))\n', (904, 912), True, 'import numpy as np\n'), ((926, 948), 'numpy.zeros', 'np.zeros', (['(l, v, l, v)'], {}), '((l, v, l, v))\n', (934, 948), True, 'import numpy as np\n'), ((965, 976), 'numpy.zeros', 'np.zeros', (['l'], {}), '(l)\n', (973, 976), True, 'import numpy as np\n'), ((1104, 1135), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'suffix': '""".npz"""'}), "(suffix='.npz')\n", (1120, 1135), False, 'import tempfile\n'), ((1141, 1173), 'numpy.savez', 'np.savez', (['filepath'], {}), '(filepath, **state_dict)\n', (1149, 1173), True, 'import numpy as np\n'), ((1373, 1410), 'os.remove', 'os.remove', (['self._mock_mogwai_filepath'], {}), '(self._mock_mogwai_filepath)\n', (1382, 1410), False, 'import os\n'), ((2206, 2263), 'experiment.run_regression_experiment', 'experiment.run_regression_experiment', ([], {}), '(**regression_kwargs)\n', (2242, 2263), False, 'import experiment\n'), ((2278, 2335), 'experiment.run_regression_experiment', 'experiment.run_regression_experiment', ([], {}), '(**regression_kwargs)\n', (2314, 2335), False, 'import experiment\n'), ((3861, 3910), 'experiment.run_design_experiment', 'experiment.run_design_experiment', ([], {}), '(**design_kwargs)\n', (3893, 3910), False, 'import experiment\n'), ((3925, 3974), 'experiment.run_design_experiment', 'experiment.run_design_experiment', ([], {}), '(**design_kwargs)\n', (3957, 3974), False, 'import experiment\n')]
#!/usr/bin/env python from setuptools import setup import numpy as np numpy_include_dir = np.get_include() # Setup script written by <NAME> # Modified by <NAME> setup( name = 'prosci', version = '1.0', description = "FREAD: fragment-based loop modelling method", author='<NAME>', author_email = "<EMAIL>", url='http://opig.stats.ox.ac.uk/webapps/newsabdab/sabpred/fread/', packages = [ "prosci", # Entire module "prosci.loops", "prosci.util", "prosci.cpp" ], package_dir = { "prosci": "lib/python/prosci", "prosci.loops": "lib/python/prosci/loops", "prosci.util": "lib/python/prosci/util", "prosci.cpp":"lib/python/prosci/cpp",# Entire protocol as a master script }, scripts = ["bin/esst.txt", "bin/esst.txt", "bin/fread_db_add", "bin/fread_db_optimise", "bin/multifread", "bin/multifread.orig", "bin/pyfread", "bin/pyfread_cpp/", "bin/tools/", "bin/pyfread_cpp/"], )
[ "numpy.get_include", "setuptools.setup" ]
[((92, 108), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (106, 108), True, 'import numpy as np\n'), ((165, 842), 'setuptools.setup', 'setup', ([], {'name': '"""prosci"""', 'version': '"""1.0"""', 'description': '"""FREAD: fragment-based loop modelling method"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""http://opig.stats.ox.ac.uk/webapps/newsabdab/sabpred/fread/"""', 'packages': "['prosci', 'prosci.loops', 'prosci.util', 'prosci.cpp']", 'package_dir': "{'prosci': 'lib/python/prosci', 'prosci.loops': 'lib/python/prosci/loops',\n 'prosci.util': 'lib/python/prosci/util', 'prosci.cpp':\n 'lib/python/prosci/cpp'}", 'scripts': "['bin/esst.txt', 'bin/esst.txt', 'bin/fread_db_add',\n 'bin/fread_db_optimise', 'bin/multifread', 'bin/multifread.orig',\n 'bin/pyfread', 'bin/pyfread_cpp/', 'bin/tools/', 'bin/pyfread_cpp/']"}), "(name='prosci', version='1.0', description=\n 'FREAD: fragment-based loop modelling method', author='<NAME>',\n author_email='<EMAIL>', url=\n 'http://opig.stats.ox.ac.uk/webapps/newsabdab/sabpred/fread/', packages\n =['prosci', 'prosci.loops', 'prosci.util', 'prosci.cpp'], package_dir={\n 'prosci': 'lib/python/prosci', 'prosci.loops':\n 'lib/python/prosci/loops', 'prosci.util': 'lib/python/prosci/util',\n 'prosci.cpp': 'lib/python/prosci/cpp'}, scripts=['bin/esst.txt',\n 'bin/esst.txt', 'bin/fread_db_add', 'bin/fread_db_optimise',\n 'bin/multifread', 'bin/multifread.orig', 'bin/pyfread',\n 'bin/pyfread_cpp/', 'bin/tools/', 'bin/pyfread_cpp/'])\n", (170, 842), False, 'from setuptools import setup\n')]
import numpy import torch import util class SequenceLoader(object): def __init__(self, data, batch_begin, n_steps): self.data = data self.batch_begin = batch_begin self.n_steps = n_steps def __iter__(self): self.t = 0 return self def __next__(self): if self.t == self.n_steps: raise StopIteration() x = {} x['self_motion'] = self.data['self_motion'][:, self.t] x['self_position'] = self.data['self_position'][:, self.t] x['self_vision'] = self.data['self_vision'][:, self.t] x['other_motion'] = self.data['other_motion'][:, self.t] x['other_position'] = self.data['other_position'][:, self.t] y = {} y['self_motion'] = self.data['self_motion'][:, self.t + 1] y['self_vision'] = self.data['self_vision'][:, self.t + 1] y['self_position'] = self.data['self_position'][:, self.t + 1] y['other_motion'] = self.data['other_motion'][:, self.t + 1] y['other_position'] = self.data['other_position'][:, self.t + 1] current_t = self.t self.t += 1 return x, y, current_t class DataLoader(object): def __init__(self, data, batch_size, shuffle, device): self.data = data self.batch_size = batch_size self.shuffle = shuffle self.device = device self.n_data = data['self_position'].shape[0] self.n_steps = data['self_position'].shape[1] - 1 def num_flatten(self): return self.n_data, self.n_steps + 1 def num_sequence(self): return self.n_data, self.n_steps def load_flatten(self): if not (hasattr(self, '_flatten')): self._flatten = FlattenLoader(self.data, self.batch_size, self.n_data, self.n_steps + 1, self.shuffle, self.device) return self._flatten def load_sequence(self): if not (hasattr(self, '_seq')): self._seq = SeqLoader(self.data, self.batch_size, self.n_data, self.n_steps, self.shuffle, self.device) return self._seq class SeqLoader(object): def __init__(self, data, batch_size, n_data, n_steps, shuffle, device): self.data = data self.batch_size = batch_size self.shuffle = shuffle self.device = device self.n_data = n_data self.n_steps = n_steps def get_n_data(self): return self.n_data def __len__(self): return self.n_data // self.batch_size def __iter__(self): self.order = numpy.random.permutation( self.n_data) if self.shuffle else numpy.arange(self.n_data) self.i = 0 return self def __next__(self): if self.i >= self.n_data: raise StopIteration() batch_begin = self.i batch_end = batch_begin + self.batch_size batch_index = self.order[batch_begin:batch_end] batch_index = numpy.sort(batch_index) # required for h5py fancy-index batch = {} batch['self_vision'] = util.scale_vision( util.transpose_vision(self.data['self_vision'][batch_index])) batch['self_vision'] = torch.from_numpy(batch['self_vision']).to( self.device) batch['self_motion'] = self.data['self_motion'][batch_index] batch['self_motion'] = torch.from_numpy(batch['self_motion']).to( self.device) batch['self_position'] = self.data['self_position'][batch_index] batch['self_position'] = torch.from_numpy(batch['self_position']).to( self.device) batch['other_motion'] = self.data['other_motion'][batch_index] batch['other_motion'] = torch.from_numpy(batch['other_motion']).to( self.device) batch['other_position'] = self.data['other_position'][batch_index] batch['other_position'] = torch.from_numpy(batch['other_position']).to( self.device) self._batch_index = batch_index self.i += self.batch_size return SequenceLoader(batch, self.i, self.n_steps), self._batch_index class FlattenLoader(object): def __init__(self, data, batch_size, n_data, n_steps, shuffle, device): self.data = data self.batch_size = batch_size self.shuffle = shuffle self.device = device self._n_data = n_data self._n_steps = n_steps self.n_data = self._n_data * self._n_steps def __len__(self): return self.n_data // self.batch_size def __iter__(self): self.order = numpy.random.permutation( self.n_data) if self.shuffle else numpy.arange(self.n_data) self.i = 0 return self def __next__(self): if self.i >= self.n_data: raise StopIteration() batch_begin = self.i batch_end = batch_begin + self.batch_size batch_index = self.order[batch_begin:batch_end] batch_index = numpy.sort(batch_index) # required for h5py fancy-index batch_index = numpy.unravel_index(batch_index, (self._n_data, self._n_steps)) batch = {} batch['self_vision'] = util.scale_vision( util.transpose_vision( self.data['self_vision'][batch_index[0], batch_index[1]], dim=4)) batch['self_vision'] = torch.from_numpy(batch['self_vision']).to( self.device) # batch['self_motion'] = self.data['self_motion'][batch_index[0], # batch_index[1]] # batch['self_motion'] = torch.from_numpy(batch['self_motion']).to( # self.device) batch['self_position'] = self.data['self_position'][batch_index[0], batch_index[1]] batch['self_position'] = torch.from_numpy(batch['self_position']).to( self.device) if 'other_vision' in self.data.keys(): batch['other_vision'] = util.scale_vision( util.transpose_vision( self.data['other_vision'][batch_index[0], batch_index[1]], dim=4)) batch['other_vision'] = torch.from_numpy(batch['other_vision']).to( self.device) # batch['other_motion'] = self.data['other_motion'][batch_index[0], # batch_index[1]] # batch['other_motion'] = torch.from_numpy(batch['other_motion']).to( # self.device) batch['other_position'] = self.data['other_position'][batch_index[0], batch_index[1]] batch['other_position'] = torch.from_numpy(batch['other_position']).to( self.device) self.i += self.batch_size return batch, batch_index
[ "util.transpose_vision", "numpy.unravel_index", "numpy.sort", "numpy.arange", "numpy.random.permutation", "torch.from_numpy" ]
[((3038, 3061), 'numpy.sort', 'numpy.sort', (['batch_index'], {}), '(batch_index)\n', (3048, 3061), False, 'import numpy\n'), ((5046, 5069), 'numpy.sort', 'numpy.sort', (['batch_index'], {}), '(batch_index)\n', (5056, 5069), False, 'import numpy\n'), ((5126, 5189), 'numpy.unravel_index', 'numpy.unravel_index', (['batch_index', '(self._n_data, self._n_steps)'], {}), '(batch_index, (self._n_data, self._n_steps))\n', (5145, 5189), False, 'import numpy\n'), ((2649, 2686), 'numpy.random.permutation', 'numpy.random.permutation', (['self.n_data'], {}), '(self.n_data)\n', (2673, 2686), False, 'import numpy\n'), ((2721, 2746), 'numpy.arange', 'numpy.arange', (['self.n_data'], {}), '(self.n_data)\n', (2733, 2746), False, 'import numpy\n'), ((3178, 3238), 'util.transpose_vision', 'util.transpose_vision', (["self.data['self_vision'][batch_index]"], {}), "(self.data['self_vision'][batch_index])\n", (3199, 3238), False, 'import util\n'), ((4657, 4694), 'numpy.random.permutation', 'numpy.random.permutation', (['self.n_data'], {}), '(self.n_data)\n', (4681, 4694), False, 'import numpy\n'), ((4729, 4754), 'numpy.arange', 'numpy.arange', (['self.n_data'], {}), '(self.n_data)\n', (4741, 4754), False, 'import numpy\n'), ((5315, 5406), 'util.transpose_vision', 'util.transpose_vision', (["self.data['self_vision'][batch_index[0], batch_index[1]]"], {'dim': '(4)'}), "(self.data['self_vision'][batch_index[0], batch_index[\n 1]], dim=4)\n", (5336, 5406), False, 'import util\n'), ((3271, 3309), 'torch.from_numpy', 'torch.from_numpy', (["batch['self_vision']"], {}), "(batch['self_vision'])\n", (3287, 3309), False, 'import torch\n'), ((3441, 3479), 'torch.from_numpy', 'torch.from_numpy', (["batch['self_motion']"], {}), "(batch['self_motion'])\n", (3457, 3479), False, 'import torch\n'), ((3617, 3657), 'torch.from_numpy', 'torch.from_numpy', (["batch['self_position']"], {}), "(batch['self_position'])\n", (3633, 3657), False, 'import torch\n'), ((3792, 3831), 'torch.from_numpy', 'torch.from_numpy', (["batch['other_motion']"], {}), "(batch['other_motion'])\n", (3808, 3831), False, 'import torch\n'), ((3972, 4013), 'torch.from_numpy', 'torch.from_numpy', (["batch['other_position']"], {}), "(batch['other_position'])\n", (3988, 4013), False, 'import torch\n'), ((5467, 5505), 'torch.from_numpy', 'torch.from_numpy', (["batch['self_vision']"], {}), "(batch['self_vision'])\n", (5483, 5505), False, 'import torch\n'), ((5975, 6015), 'torch.from_numpy', 'torch.from_numpy', (["batch['self_position']"], {}), "(batch['self_position'])\n", (5991, 6015), False, 'import torch\n'), ((6164, 6256), 'util.transpose_vision', 'util.transpose_vision', (["self.data['other_vision'][batch_index[0], batch_index[1]]"], {'dim': '(4)'}), "(self.data['other_vision'][batch_index[0], batch_index\n [1]], dim=4)\n", (6185, 6256), False, 'import util\n'), ((6854, 6895), 'torch.from_numpy', 'torch.from_numpy', (["batch['other_position']"], {}), "(batch['other_position'])\n", (6870, 6895), False, 'import torch\n'), ((6330, 6369), 'torch.from_numpy', 'torch.from_numpy', (["batch['other_vision']"], {}), "(batch['other_vision'])\n", (6346, 6369), False, 'import torch\n')]
from dataclasses import dataclass from typing import List import numpy as np import pint from pandas.api.types import is_datetime64_any_dtype as is_datetime from pandas.api.types import is_timedelta64_dtype as is_timedelta from weldx.asdf.types import WeldxType from weldx.constants import WELDX_QUANTITY as Q_ @dataclass class Dimension: """ Stores data of a dimension. """ name: str length: int class DimensionTypeASDF(WeldxType): """Serialization class for the 'Dimension' type""" name = "core/dimension" version = "1.0.0" types = [Dimension] requires = ["weldx"] handle_dynamic_subclasses = True @classmethod def to_tree(cls, node: Dimension, ctx): """ Convert an instance of the 'Dimension' type into YAML representations. Parameters ---------- node : Instance of the 'Dimension' type to be serialized. ctx : An instance of the 'AsdfFile' object that is being written out. Returns ------- A basic YAML type ('dict', 'list', 'str', 'int', 'float', or 'complex') representing the properties of the 'Dimension' type to be serialized. """ tree = {"name": node.name, "length": node.length} return tree @classmethod def from_tree(cls, tree, ctx): """ Converts basic types representing YAML trees into custom types. Parameters ---------- tree : An instance of a basic Python type (possibly nested) that corresponds to a YAML subtree. ctx : An instance of the 'AsdfFile' object that is being constructed. Returns ------- Dimension : An instance of the 'Dimension' type. """ return Dimension(tree["name"], tree["length"]) @dataclass class Variable: """Represents an n-dimensional piece of data.""" name: str dimensions: List data: np.ndarray class VariableTypeASDF(WeldxType): """Serialization class for a Variable""" name = "core/variable" version = "1.0.0" types = [Variable] requires = ["weldx"] handle_dynamic_subclasses = True @staticmethod def convert_time_dtypes(data: np.ndarray): """ Convert time format data types to a corresponding numeric data type. If the data's type isn't a time format, the function returns the unmodified data. Parameters ---------- data : Data that should be converted. Returns ------- np.ndarray : Unmodified or converted data. """ if is_datetime(data.dtype) or is_timedelta(data.dtype): return data.astype(np.int64) return data @classmethod def to_tree(cls, node: Variable, ctx): """ Convert an instance of the 'Variable' type into YAML representations. Parameters ---------- node : Instance of the 'Variable' type to be serialized. ctx : An instance of the 'AsdfFile' object that is being written out. Returns ------- A basic YAML type ('dict', 'list', 'str', 'int', 'float', or 'complex') representing the properties of the 'Variable' type to be serialized. """ if isinstance(node.data, pint.Quantity): unit = str(node.data.units) data = node.data.magnitude else: unit = None data = node.data dtype = node.data.dtype.str data = cls.convert_time_dtypes(data=data) tree = { "name": node.name, "dimensions": node.dimensions, "dtype": dtype, "data": data, } if unit: tree["unit"] = unit return tree @classmethod def from_tree(cls, tree, ctx): """ Converts basic types representing YAML trees into custom types. Parameters ---------- tree : An instance of a basic Python type (possibly nested) that corresponds to a YAML subtree. ctx : An instance of the 'AsdfFile' object that is being constructed. Returns ------- Variable : An instance of the 'Variable' type. """ dtype = np.dtype(tree["dtype"]) if "unit" in tree: # convert to pint.Quantity data = Q_(tree["data"].astype(dtype), tree["unit"]) else: data = tree["data"].astype(dtype) return Variable(tree["name"], tree["dimensions"], data)
[ "pandas.api.types.is_datetime64_any_dtype", "numpy.dtype", "pandas.api.types.is_timedelta64_dtype" ]
[((4432, 4455), 'numpy.dtype', 'np.dtype', (["tree['dtype']"], {}), "(tree['dtype'])\n", (4440, 4455), True, 'import numpy as np\n'), ((2707, 2730), 'pandas.api.types.is_datetime64_any_dtype', 'is_datetime', (['data.dtype'], {}), '(data.dtype)\n', (2718, 2730), True, 'from pandas.api.types import is_datetime64_any_dtype as is_datetime\n'), ((2734, 2758), 'pandas.api.types.is_timedelta64_dtype', 'is_timedelta', (['data.dtype'], {}), '(data.dtype)\n', (2746, 2758), True, 'from pandas.api.types import is_timedelta64_dtype as is_timedelta\n')]
# coding=utf-8 import io import sys import requests from bs4 import BeautifulSoup import numpy as np import pandas as pd sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030') # 改变标准输出的默认编码, 防止控制台打印乱码 url = "https://www.checkee.info/main.php?dispdate=2019-06" def get_soup(url): try: r = requests.get(url, timeout=30) r.raise_for_status() # 若请求不成功,抛出HTTPError 异常 # r.encoding = 'gbk' soup = BeautifulSoup(r.text, 'lxml') return soup except HTTPError: return "Request Error" def saveTocsv(data, fileName): ''' 将checkee.info表格[6]的数据保存至csv文件 ''' result_weather = pd.DataFrame(data, columns=['date', 'tq', 'temp', 'wind']) result_weather.to_csv(fileName, index=False, encoding='gbk') print('Save all weather success!') def saveToMysql(data): ''' 将天气数据保存至MySQL数据库 ''' # 建立连接 conn = pymysql.connect(host="localhost", port=3306, user='root', passwd='<PASSWORD>', database='test', charset="utf8") # 获取游标 cursor = conn.cursor() sql = "INSERT INTO weather(date,tq,temp,wind) VALUES(%s,%s,%s,%s)" data_list = np.ndarray.tolist(data) # 将numpy数组转化为列表 try: cursor.executemany(sql, data_list) print(cursor.rowcount) conn.commit() except Exception as e: print(e) conn.rollback() cursor.close() conn.close() def get_data(): soup = get_soup(url) all_weather = soup.find('div', class_="wdetail").find('table').find_all("tr") data = list() for tr in all_weather[1:]: td_li = tr.find_all("td") for td in td_li: s = td.get_text() data.append("".join(s.split())) res = np.array(data).reshape(-1, 4) return res if __name__ == '__main__': data = get_data() saveTocsv(data, "E:\weather.csv")
[ "pandas.DataFrame", "io.TextIOWrapper", "numpy.array", "requests.get", "numpy.ndarray.tolist", "bs4.BeautifulSoup" ]
[((143, 198), 'io.TextIOWrapper', 'io.TextIOWrapper', (['sys.stdout.buffer'], {'encoding': '"""gb18030"""'}), "(sys.stdout.buffer, encoding='gb18030')\n", (159, 198), False, 'import io\n'), ((682, 740), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['date', 'tq', 'temp', 'wind']"}), "(data, columns=['date', 'tq', 'temp', 'wind'])\n", (694, 740), True, 'import pandas as pd\n'), ((1186, 1209), 'numpy.ndarray.tolist', 'np.ndarray.tolist', (['data'], {}), '(data)\n', (1203, 1209), True, 'import numpy as np\n'), ((334, 363), 'requests.get', 'requests.get', (['url'], {'timeout': '(30)'}), '(url, timeout=30)\n', (346, 363), False, 'import requests\n'), ((465, 494), 'bs4.BeautifulSoup', 'BeautifulSoup', (['r.text', '"""lxml"""'], {}), "(r.text, 'lxml')\n", (478, 494), False, 'from bs4 import BeautifulSoup\n'), ((1786, 1800), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1794, 1800), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Sun Feb 2 11:50:01 2020 @author: Sander """ import numpy as np import matplotlib.pyplot as plt def function(num, complex_number): return num ** 2 + complex_number def iterate(num, iterations): value = num for i in range(iterations): value = function(value, num) if np.abs(value) >= 2: return False return True resolution = 50 bin_map = np.empty((resolution, resolution), dtype = np.uint8) map_range = (-2,2,-2,2) zoom = 0.5 offset_x = -1 offset_y = 0 m = np.meshgrid(np.linspace(map_range[0] * zoom + offset_x, \ map_range[1] * zoom + offset_x, bin_map.shape[0]), \ np.linspace(map_range[2] * zoom - offset_y,\ map_range[3] * zoom - offset_y, bin_map.shape[0])) m = m[0].astype(np.complex64) + 1j * m[1].astype(np.complex64) print(m.shape) for y in range(bin_map.shape[0]): print("Loading[") for x in range(bin_map.shape[1]): bin_map[y, x] = iterate(m[y,x], 25) plt.imshow(bin_map*255, cmap = "gray")
[ "numpy.empty", "numpy.abs", "numpy.linspace", "matplotlib.pyplot.imshow" ]
[((424, 474), 'numpy.empty', 'np.empty', (['(resolution, resolution)'], {'dtype': 'np.uint8'}), '((resolution, resolution), dtype=np.uint8)\n', (432, 474), True, 'import numpy as np\n'), ((1048, 1086), 'matplotlib.pyplot.imshow', 'plt.imshow', (['(bin_map * 255)'], {'cmap': '"""gray"""'}), "(bin_map * 255, cmap='gray')\n", (1058, 1086), True, 'import matplotlib.pyplot as plt\n'), ((555, 652), 'numpy.linspace', 'np.linspace', (['(map_range[0] * zoom + offset_x)', '(map_range[1] * zoom + offset_x)', 'bin_map.shape[0]'], {}), '(map_range[0] * zoom + offset_x, map_range[1] * zoom + offset_x,\n bin_map.shape[0])\n', (566, 652), True, 'import numpy as np\n'), ((698, 795), 'numpy.linspace', 'np.linspace', (['(map_range[2] * zoom - offset_y)', '(map_range[3] * zoom - offset_y)', 'bin_map.shape[0]'], {}), '(map_range[2] * zoom - offset_y, map_range[3] * zoom - offset_y,\n bin_map.shape[0])\n', (709, 795), True, 'import numpy as np\n'), ((336, 349), 'numpy.abs', 'np.abs', (['value'], {}), '(value)\n', (342, 349), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Fri Feb 15 19:37:48 2019 @author: <NAME> <EMAIL> """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.decomposition import KernelPCA # ============================================================================= # OLS # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from sklearn import metrics diabetes = load_diabetes() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = diabetes.data[:400], diabetes.target[:400] test_x, test_y = diabetes.data[400:], diabetes.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model ols = LinearRegression() ols.fit(train_x, train_y) err = metrics.mean_squared_error(test_y, ols.predict(test_x)) r2 = metrics.r2_score(test_y, ols.predict(test_x)) # --- SECTION 4 --- # Print the model print('---OLS on diabetes dataset.---') print('Coefficients:') print('Intercept (b): %.2f'%ols.intercept_) for i in range(len(diabetes.feature_names)): print(diabetes.feature_names[i]+': %.2f'%ols.coef_[i]) print('-'*30) print('R-squared: %.2f'%r2, ' MSE: %.2f \n'%err) # ============================================================================= # LOGIT # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_breast_cancer from sklearn import metrics bc = load_breast_cancer() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = bc.data[:400], bc.target[:400] test_x, test_y = bc.data[400:], bc.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model logit = LogisticRegression() logit.fit(train_x, train_y) acc = metrics.accuracy_score(test_y, logit.predict(test_x)) # --- SECTION 4 --- # Print the model print('---Logistic Regression on breast cancer dataset.---') print('Coefficients:') print('Intercept (b): %.2f'%logit.intercept_) for i in range(len(bc.feature_names)): print(bc.feature_names[i]+': %.2f'%logit.coef_[0][i]) print('-'*30) print('Accuracy: %.2f \n'%acc) print(metrics.confusion_matrix(test_y, logit.predict(test_x))) # ============================================================================= # SVM FIGURE # ============================================================================= f = lambda x: 2 * x - 5 f_upp = lambda x: 2 * x - 5 + 2 f_lower = lambda x: 2 * x - 5 - 2 pos = [] neg = [] np.random.seed(345234) for i in range(80): x = np.random.randint(15) y = np.random.randint(15) d = np.abs(2*x-y-5)/np.sqrt(2**2+1) if f(x) < y and d>=1: pos.append([x,y]) elif f(x) > y and d>=1 : neg.append([x,y]) pos.append([4, f_upp(4)]) neg.append([8, f_lower(8)]) plt.figure() plt.xticks([]) plt.yticks([]) plt.scatter(*zip(*pos)) plt.scatter(*zip(*neg)) plt.plot([0,10],[f(0),f(10)], linestyle='--', color='m') plt.plot([0,10],[f_upp(0),f_upp(10)], linestyle='--', color='red') plt.plot([0,10],[f_lower(0),f_lower(10)], linestyle='--', color='red') plt.plot([4,3],[f_lower(4),f_upp(3)], linestyle='-', color='black') plt.plot([7,6],[f_lower(7),f_upp(6)], linestyle='-', color='black') plt.xlabel('x') plt.ylabel('y') plt.title('SVM') # ============================================================================= # SVC # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.svm import SVC from sklearn.datasets import load_breast_cancer from sklearn import metrics # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = bc.data[:400], bc.target[:400] test_x, test_y = bc.data[400:], bc.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model svc = SVC(kernel='linear') svc.fit(train_x, train_y) acc = metrics.accuracy_score(test_y, svc.predict(test_x)) # --- SECTION 4 --- # Print the model's accuracy print('---SVM on breast cancer dataset.---') print('Accuracy: %.2f \n'%acc) print(metrics.confusion_matrix(test_y, svc.predict(test_x))) # ============================================================================= # SVR # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_diabetes from sklearn.svm import SVR from sklearn import metrics diabetes = load_diabetes() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = diabetes.data[:400], diabetes.target[:400] test_x, test_y = diabetes.data[400:], diabetes.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model svr = SVR(kernel='linear', C=1000) svr.fit(train_x, train_y) err = metrics.mean_squared_error(test_y, svr.predict(test_x)) r2 = metrics.r2_score(test_y, svr.predict(test_x)) # --- SECTION 4 --- # Print the model print('---SVM on diabetes dataset.---') print('R-squared: %.2f'%r2, ' MSE: %.2f \n'%err) # ============================================================================= # MLP REGRESSION # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_diabetes from sklearn.neural_network import MLPRegressor from sklearn import metrics diabetes = load_diabetes() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = diabetes.data[:400], diabetes.target[:400] test_x, test_y = diabetes.data[400:], diabetes.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model mlpr = MLPRegressor(solver='sgd') mlpr.fit(train_x, train_y) err = metrics.mean_squared_error(test_y, mlpr.predict(test_x)) r2 = metrics.r2_score(test_y, mlpr.predict(test_x)) # --- SECTION 4 --- # Print the model print('---Neural Networks on diabetes dataset.---') print('R-squared: %.2f'%r2, ' MSE: %.2f \n'%err) # ============================================================================= # MLP CLASSIFICATION # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_breast_cancer from sklearn.neural_network import MLPClassifier from sklearn import metrics bc = load_breast_cancer() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = bc.data[:400], bc.target[:400] test_x, test_y = bc.data[400:], bc.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model mlpc = MLPClassifier(solver='lbfgs', random_state=12418) mlpc.fit(train_x, train_y) acc = metrics.accuracy_score(test_y, mlpc.predict(test_x)) # --- SECTION 4 --- # Print the model's accuracy print('---Neural Networks on breast cancer dataset.---') print('Accuracy: %.2f \n'%acc) print(metrics.confusion_matrix(test_y, mlpc.predict(test_x))) # ============================================================================= # MLP REGRESSION # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_diabetes from sklearn.neural_network import MLPRegressor from sklearn import metrics diabetes = load_diabetes() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = diabetes.data[:400], diabetes.target[:400] test_x, test_y = diabetes.data[400:], diabetes.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model mlpr = MLPRegressor(solver='sgd') mlpr.fit(train_x, train_y) err = metrics.mean_squared_error(test_y, mlpr.predict(test_x)) r2 = metrics.r2_score(test_y, mlpr.predict(test_x)) # --- SECTION 4 --- # Print the model print('---Neural Networks on diabetes dataset.---') print('R-squared: %.2f'%r2, ' MSE: %.2f \n'%err) # ============================================================================= # DTREE REGRESSION # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_diabetes from sklearn.tree import DecisionTreeRegressor from sklearn import metrics diabetes = load_diabetes() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = diabetes.data[:400], diabetes.target[:400] test_x, test_y = diabetes.data[400:], diabetes.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model dtr = DecisionTreeRegressor(max_depth=2) dtr.fit(train_x, train_y) err = metrics.mean_squared_error(test_y, dtr.predict(test_x)) r2 = metrics.r2_score(test_y, dtr.predict(test_x)) # --- SECTION 4 --- # Print the model print('---Neural Networks on diabetes dataset.---') print('R-squared: %.2f'%r2, ' MSE: %.2f \n'%err) # ============================================================================= # DTREE CLASSIFICATION # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_breast_cancer from sklearn.tree import DecisionTreeClassifier from sklearn import metrics bc = load_breast_cancer() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = bc.data[:400], bc.target[:400] test_x, test_y = bc.data[400:], bc.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model dtc = DecisionTreeClassifier(max_depth=2) dtc.fit(train_x, train_y) acc = metrics.accuracy_score(test_y, dtc.predict(test_x)) # --- SECTION 4 --- # Print the model's accuracy print('---Neural Networks on breast cancer dataset.---') print('Accuracy: %.2f \n'%acc) print(metrics.confusion_matrix(test_y, dtc.predict(test_x))) from sklearn.tree import export_graphviz export_graphviz(dtc, feature_names=bc.feature_names, class_names=bc.target_names, impurity=False) # ============================================================================= # KNN REGRESSION # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_diabetes from sklearn.neighbors import KNeighborsRegressor from sklearn import metrics diabetes = load_diabetes() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = diabetes.data[:400], diabetes.target[:400] test_x, test_y = diabetes.data[400:], diabetes.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model knnr = KNeighborsRegressor(n_neighbors=14) knnr.fit(train_x, train_y) err = metrics.mean_squared_error(test_y, knnr.predict(test_x)) r2 = metrics.r2_score(test_y, knnr.predict(test_x)) # --- SECTION 4 --- # Print the model print('---Neural Networks on diabetes dataset.---') print('R-squared: %.2f'%r2, ' MSE: %.2f \n'%err) # ============================================================================= # KNN CLASSIFICATION # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_breast_cancer from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics bc = load_breast_cancer() # --- SECTION 2 --- # Split the data into train and test set train_x, train_y = bc.data[:400], bc.target[:400] test_x, test_y = bc.data[400:], bc.target[400:] # --- SECTION 3 --- # Instantiate, train and evaluate the model dtc = KNeighborsClassifier(n_neighbors=5) dtc.fit(train_x, train_y) acc = metrics.accuracy_score(test_y, dtc.predict(test_x)) # --- SECTION 4 --- # Print the model's accuracy print('---Neural Networks on breast cancer dataset.---') print('Accuracy: %.2f \n'%acc) print(metrics.confusion_matrix(test_y, dtc.predict(test_x))) # ============================================================================= # K-MEANS # ============================================================================= # --- SECTION 1 --- # Libraries and data loading from sklearn.datasets import load_breast_cancer from sklearn.cluster import KMeans bc = load_breast_cancer() bc.data=bc.data[:,:2] # --- SECTION 2 --- # Instantiate and train km = KMeans(n_clusters=3) km.fit(bc.data) # --- SECTION 3 --- # Create a point mesh to plot cluster areas # Step size of the mesh. h = .02 # Plot the decision boundary. For that, we will assign a color to each x_min, x_max = bc.data[:, 0].min() - 1, bc.data[:, 0].max() + 1 y_min, y_max = bc.data[:, 1].min() - 1, bc.data[:, 1].max() + 1 # Create the actual mesh and cluster it xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = km.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure(1) plt.clf() plt.imshow(Z, interpolation='nearest', extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto', origin='lower') # --- SECTION 4 --- # Plot the actual data c = km.predict(bc.data) r = c == 0 b = c == 1 g = c == 2 plt.scatter(bc.data[r, 0], bc.data[r, 1], label='cluster 1', color='silver') plt.scatter(bc.data[b, 0], bc.data[b, 1], label='cluster 2', color='white') plt.scatter(bc.data[g, 0], bc.data[g, 1], label='cluster 3', color='black') plt.title('K-means') plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xticks(()) plt.yticks(()) plt.xlabel(bc.feature_names[0]) plt.ylabel(bc.feature_names[1]) plt.show() plt.legend()
[ "matplotlib.pyplot.title", "numpy.random.seed", "numpy.abs", "matplotlib.pyplot.clf", "sklearn.datasets.load_diabetes", "sklearn.tree.DecisionTreeClassifier", "matplotlib.pyplot.figure", "numpy.random.randint", "numpy.arange", "sklearn.neural_network.MLPClassifier", "sklearn.svm.SVC", "sklearn...
[((613, 628), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {}), '()\n', (626, 628), False, 'from sklearn.datasets import load_diabetes\n'), ((895, 913), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (911, 913), False, 'from sklearn.linear_model import LinearRegression\n'), ((1743, 1763), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (1761, 1763), False, 'from sklearn.datasets import load_breast_cancer\n'), ((2006, 2026), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (2024, 2026), False, 'from sklearn.linear_model import LogisticRegression\n'), ((2798, 2820), 'numpy.random.seed', 'np.random.seed', (['(345234)'], {}), '(345234)\n', (2812, 2820), True, 'import numpy as np\n'), ((3121, 3133), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3131, 3133), True, 'import matplotlib.pyplot as plt\n'), ((3135, 3149), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (3145, 3149), True, 'import matplotlib.pyplot as plt\n'), ((3151, 3165), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (3161, 3165), True, 'import matplotlib.pyplot as plt\n'), ((3555, 3570), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (3565, 3570), True, 'import matplotlib.pyplot as plt\n'), ((3572, 3587), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y"""'], {}), "('y')\n", (3582, 3587), True, 'import matplotlib.pyplot as plt\n'), ((3589, 3605), 'matplotlib.pyplot.title', 'plt.title', (['"""SVM"""'], {}), "('SVM')\n", (3598, 3605), True, 'import matplotlib.pyplot as plt\n'), ((4175, 4195), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""'}), "(kernel='linear')\n", (4178, 4195), False, 'from sklearn.svm import SVC\n'), ((4811, 4826), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {}), '()\n', (4824, 4826), False, 'from sklearn.datasets import load_diabetes\n'), ((5093, 5121), 'sklearn.svm.SVR', 'SVR', ([], {'kernel': '"""linear"""', 'C': '(1000)'}), "(kernel='linear', C=1000)\n", (5096, 5121), False, 'from sklearn.svm import SVR\n'), ((5770, 5785), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {}), '()\n', (5783, 5785), False, 'from sklearn.datasets import load_diabetes\n'), ((6053, 6079), 'sklearn.neural_network.MLPRegressor', 'MLPRegressor', ([], {'solver': '"""sgd"""'}), "(solver='sgd')\n", (6065, 6079), False, 'from sklearn.neural_network import MLPRegressor\n'), ((6743, 6763), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (6761, 6763), False, 'from sklearn.datasets import load_breast_cancer\n'), ((7011, 7060), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'solver': '"""lbfgs"""', 'random_state': '(12418)'}), "(solver='lbfgs', random_state=12418)\n", (7024, 7060), False, 'from sklearn.neural_network import MLPClassifier\n'), ((7724, 7739), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {}), '()\n', (7737, 7739), False, 'from sklearn.datasets import load_diabetes\n'), ((8007, 8033), 'sklearn.neural_network.MLPRegressor', 'MLPRegressor', ([], {'solver': '"""sgd"""'}), "(solver='sgd')\n", (8019, 8033), False, 'from sklearn.neural_network import MLPRegressor\n'), ((8694, 8709), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {}), '()\n', (8707, 8709), False, 'from sklearn.datasets import load_diabetes\n'), ((8976, 9010), 'sklearn.tree.DecisionTreeRegressor', 'DecisionTreeRegressor', ([], {'max_depth': '(2)'}), '(max_depth=2)\n', (8997, 9010), False, 'from sklearn.tree import DecisionTreeRegressor\n'), ((9672, 9692), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (9690, 9692), False, 'from sklearn.datasets import load_breast_cancer\n'), ((9937, 9972), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'max_depth': '(2)'}), '(max_depth=2)\n', (9959, 9972), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((10307, 10409), 'sklearn.tree.export_graphviz', 'export_graphviz', (['dtc'], {'feature_names': 'bc.feature_names', 'class_names': 'bc.target_names', 'impurity': '(False)'}), '(dtc, feature_names=bc.feature_names, class_names=bc.\n target_names, impurity=False)\n', (10322, 10409), False, 'from sklearn.tree import export_graphviz\n'), ((10810, 10825), 'sklearn.datasets.load_diabetes', 'load_diabetes', ([], {}), '()\n', (10823, 10825), False, 'from sklearn.datasets import load_diabetes\n'), ((11093, 11128), 'sklearn.neighbors.KNeighborsRegressor', 'KNeighborsRegressor', ([], {'n_neighbors': '(14)'}), '(n_neighbors=14)\n', (11112, 11128), False, 'from sklearn.neighbors import KNeighborsRegressor\n'), ((11794, 11814), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (11812, 11814), False, 'from sklearn.datasets import load_breast_cancer\n'), ((12059, 12094), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(5)'}), '(n_neighbors=5)\n', (12079, 12094), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((12707, 12727), 'sklearn.datasets.load_breast_cancer', 'load_breast_cancer', ([], {}), '()\n', (12725, 12727), False, 'from sklearn.datasets import load_breast_cancer\n'), ((12809, 12829), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(3)'}), '(n_clusters=3)\n', (12815, 12829), False, 'from sklearn.cluster import KMeans\n'), ((13388, 13401), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (13398, 13401), True, 'import matplotlib.pyplot as plt\n'), ((13403, 13412), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (13410, 13412), True, 'import matplotlib.pyplot as plt\n'), ((13672, 13748), 'matplotlib.pyplot.scatter', 'plt.scatter', (['bc.data[r, 0]', 'bc.data[r, 1]'], {'label': '"""cluster 1"""', 'color': '"""silver"""'}), "(bc.data[r, 0], bc.data[r, 1], label='cluster 1', color='silver')\n", (13683, 13748), True, 'import matplotlib.pyplot as plt\n'), ((13750, 13825), 'matplotlib.pyplot.scatter', 'plt.scatter', (['bc.data[b, 0]', 'bc.data[b, 1]'], {'label': '"""cluster 2"""', 'color': '"""white"""'}), "(bc.data[b, 0], bc.data[b, 1], label='cluster 2', color='white')\n", (13761, 13825), True, 'import matplotlib.pyplot as plt\n'), ((13827, 13902), 'matplotlib.pyplot.scatter', 'plt.scatter', (['bc.data[g, 0]', 'bc.data[g, 1]'], {'label': '"""cluster 3"""', 'color': '"""black"""'}), "(bc.data[g, 0], bc.data[g, 1], label='cluster 3', color='black')\n", (13838, 13902), True, 'import matplotlib.pyplot as plt\n'), ((13904, 13924), 'matplotlib.pyplot.title', 'plt.title', (['"""K-means"""'], {}), "('K-means')\n", (13913, 13924), True, 'import matplotlib.pyplot as plt\n'), ((13926, 13948), 'matplotlib.pyplot.xlim', 'plt.xlim', (['x_min', 'x_max'], {}), '(x_min, x_max)\n', (13934, 13948), True, 'import matplotlib.pyplot as plt\n'), ((13950, 13972), 'matplotlib.pyplot.ylim', 'plt.ylim', (['y_min', 'y_max'], {}), '(y_min, y_max)\n', (13958, 13972), True, 'import matplotlib.pyplot as plt\n'), ((13974, 13988), 'matplotlib.pyplot.xticks', 'plt.xticks', (['()'], {}), '(())\n', (13984, 13988), True, 'import matplotlib.pyplot as plt\n'), ((13990, 14004), 'matplotlib.pyplot.yticks', 'plt.yticks', (['()'], {}), '(())\n', (14000, 14004), True, 'import matplotlib.pyplot as plt\n'), ((14006, 14037), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['bc.feature_names[0]'], {}), '(bc.feature_names[0])\n', (14016, 14037), True, 'import matplotlib.pyplot as plt\n'), ((14039, 14070), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['bc.feature_names[1]'], {}), '(bc.feature_names[1])\n', (14049, 14070), True, 'import matplotlib.pyplot as plt\n'), ((14072, 14082), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14080, 14082), True, 'import matplotlib.pyplot as plt\n'), ((14084, 14096), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (14094, 14096), True, 'import matplotlib.pyplot as plt\n'), ((2851, 2872), 'numpy.random.randint', 'np.random.randint', (['(15)'], {}), '(15)\n', (2868, 2872), True, 'import numpy as np\n'), ((2882, 2903), 'numpy.random.randint', 'np.random.randint', (['(15)'], {}), '(15)\n', (2899, 2903), True, 'import numpy as np\n'), ((13221, 13247), 'numpy.arange', 'np.arange', (['x_min', 'x_max', 'h'], {}), '(x_min, x_max, h)\n', (13230, 13247), True, 'import numpy as np\n'), ((13249, 13275), 'numpy.arange', 'np.arange', (['y_min', 'y_max', 'h'], {}), '(y_min, y_max, h)\n', (13258, 13275), True, 'import numpy as np\n'), ((2915, 2936), 'numpy.abs', 'np.abs', (['(2 * x - y - 5)'], {}), '(2 * x - y - 5)\n', (2921, 2936), True, 'import numpy as np\n'), ((2931, 2950), 'numpy.sqrt', 'np.sqrt', (['(2 ** 2 + 1)'], {}), '(2 ** 2 + 1)\n', (2938, 2950), True, 'import numpy as np\n')]
import sys if sys.hexversion < 0x3000000: raise RuntimeError("expecting python v3+ instead of %x" % sys.hexversion) import array import numpy as np import time # ---------------------------------------------------------------------------- ''' this is an almost one-for-one translation of the Julia version, see knapsack.jl for more comments. running this benchmark from command line: >python3 -O ...knapsack.py ''' class item(object): def __init__(self, value, weight): self.value = value self.weight = weight def __repr__(self): return "(" + str(self.value) + ", " + str(self.weight) + ")" # ............................................................................ def opt_value(W, items): n = len(items) V = [0 for i in range(W)] V_prev = [0 for i in range(W)] # use the next 2 lines to use python "native" arrays instead: # (for me, this choice is slower 2x than plain python lists) # V = array.array('q', [0 for i in range(W)]) # V_prev = array.array('q', [0 for i in range(W)]) # use the next 2 lines to use numpy arrays instead: # (for me, this choice is nearly 2x slower) # V = np.array([0 for i in range(W)], dtype="i8") # V_prev = np.array([0 for i in range(W)], dtype="i8") for w in range(items[0].weight, W + 1): V[w - 1] = items[0].value; for j in range(1, n): V, V_prev = V_prev, V item_j = items[j] for w in range(1, W + 1): V_without_item_j = V_prev[w - 1] V_allow_item_j = (V_without_item_j if w < item_j.weight else (item_j.value + (V_prev[w - 1 - item_j.weight] if w != item_j.weight else 0))) V[w - 1] = max(V_allow_item_j, V_without_item_j) return V[W - 1] # ............................................................................ # some contortions are needed in python to ensure uint64_t arithmetic: _13 = np.uint64(13) _7 = np.uint64(7) _17 = np.uint64(17) def xorshift_rand(seed): assert seed != 0 x = np.uint64(seed) def _next(): nonlocal x x ^= (x << _13); x ^= (x >> _7); x ^= (x << _17); return int(x); return _next def make_random_data(W, seed): assert W > 1000 n = W // 100 rng = xorshift_rand(seed) items = [] for i in range(n): v = rng() % 1000 w = 1 + rng() % (2 * W) items.append(item(v, w)) return W, items # ............................................................................ def run(repeats = 5): times = [0.0 for i in range(repeats)] seed = 12345 for W in [5000, 10000, 20000, 40000, 80000]: for repeat in range(repeats): seed += 1 W, items = make_random_data(W, seed) start = time.time_ns () V = opt_value(W, items) stop = time.time_ns() times[repeat] = (stop - start) / 1e9 # print("V = %d, time = %f" % (V, times[repeat])) times.sort() print("python, %d, %f" % (W, times[repeats // 2])) # ............................................................................ if __name__ == '__main__': run () # ----------------------------------------------------------------------------
[ "numpy.uint64", "time.time_ns" ]
[((2054, 2067), 'numpy.uint64', 'np.uint64', (['(13)'], {}), '(13)\n', (2063, 2067), True, 'import numpy as np\n'), ((2074, 2086), 'numpy.uint64', 'np.uint64', (['(7)'], {}), '(7)\n', (2083, 2086), True, 'import numpy as np\n'), ((2093, 2106), 'numpy.uint64', 'np.uint64', (['(17)'], {}), '(17)\n', (2102, 2106), True, 'import numpy as np\n'), ((2162, 2177), 'numpy.uint64', 'np.uint64', (['seed'], {}), '(seed)\n', (2171, 2177), True, 'import numpy as np\n'), ((2960, 2974), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (2972, 2974), False, 'import time\n'), ((3057, 3071), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (3069, 3071), False, 'import time\n')]
"""The Nyles main class.""" import sys import numpy as np import pickle import model_les import model_advection as model_adv import variables import grid import nylesIO import plotting import timing import topology as topo import mpitools from time import time class Nyles(object): """ Attributes : - self.grid - self.model - self.IO - self.tend - self.auto_dt - self.dt0 - self.cfl - self.dt_max Methods : *private : - initiate(param): loads the desired model and copies the time variables from param - compute_dt(): calculate the timestep *public : - run() : main loop. Iterates the model forward and saves the state in the history file """ def __init__(self, user_param): # Check, freeze, and get user parameters user_param.check() user_param.freeze() param = user_param.view_parameters() self.param = param npx = param["npx"] npy = param["npy"] npz = param["npz"] # Add parameters that are automatically set param["nx"] = param["global_nx"] // npx param["ny"] = param["global_ny"] // npy param["nz"] = param["global_nz"] // npz # Set up MPI topo.topology = param["geometry"] procs = [npz, npy, npx] myrank = mpitools.get_myrank(procs) loc = topo.rank2loc(myrank, procs) neighbours = topo.get_neighbours(loc, procs) param["procs"] = procs param["myrank"] = myrank param["neighbours"] = neighbours param["loc"] = loc self.myrank = myrank if self.myrank == 0: print("-"*80) self.banner() # Load the grid with the extended parameters self.grid = grid.Grid(param) # Load the IO; only the parameters modifiable by the user are saved self.IO = nylesIO.NylesIO(param) # redirect the x11 to output.txt #sys.stdout = Logger(self.IO.output_directory+'/output.txt') # save the param dictionary in a pkl file if self.myrank == 0: with open(self.IO.output_directory+"/param.pkl", "wb") as fid: pickle.dump(param, fid) # Initiate the model and needed variables self.initiate(param) def initiate(self, param): if param['modelname'] == 'LES': self.model = model_les.LES(param, self.grid) elif param['modelname'] == 'linear': self.model = model_les.LES(param, self.grid, linear=True) elif param['modelname'] == 'advection': self.model = model_adv.Advection(param, self.grid) self.tend = param['tend'] self.auto_dt = param['auto_dt'] self.dt0 = param['dt'] self.cfl = param['cfl'] self.dt_max = param['dt_max'] # Load the plotting module if param["show"]: self.plotting = plotting.Plotting( param, self.model.state, self.grid) else: self.plotting = None # number of grid cell per subdomain self.gridcellpersubdom = param["nx"]*param["ny"]*param["nz"] def run(self): t = 0.0 n = 0 self.model.diagnose_var(self.model.state) # Open the plotting window and draw the initial state if self.plotting: self.plotting.init(t, n) print("Resize the window to a suitable size,") print("move the camera into a good angle,") print("lean back in your seat and ...") input("... press Enter to start! ") if self.myrank == 0: print("Creating output file:", self.IO.hist_path) self.IO.init(self.model.state, self.grid, t, n) if self.myrank == 0: print("Backing up script to:", self.IO.script_path) self.IO.backup_scriptfile(sys.argv[0]) try: self.IO.write_githashnumber() except: # this occurs at TGCC where the code # can't be installed from github print("Failed to save the git version of the code experiment") time_length = len(str(int(self.tend))) + 3 time_string = "\r"+", ".join([ "n = {:3d}", "t = {:" + str(time_length) + ".2f}/{:" + str(time_length) + ".2f}", "dt = {:.4f}", "perf = {:.2e}" ]) if self.myrank == 0: print("-"*80) stop = False realtime0 = time() while not(stop): dt = self.compute_dt() blowup = self.model.forward(t, dt) t += dt n += 1 stop = self.IO.write(self.model.state, t, n) if self.myrank == 0: realtime = time() # cpu per iteration per grid cell (in second) # this is very good metric of how fast the code runs # typical values are O(4e-6) # > 1e-5 is not good (e.g. too large subdomains) # < 2e-6 is excellent, report it to the developpers! perf = (realtime-realtime0)/(self.gridcellpersubdom) realtime0 = realtime print(time_string.format(n, t, self.tend, dt, perf), end='') # Blowup might be detected on one subdomain # and not on the other. # We need to spread the word that blowup # had occured and that all cores should stop. # An easy way to do it is to do a global sum # of localmood (0=fine, 1=blowup) localmood = 1. if blowup else 0. globalmood = mpitools.global_sum(localmood) # and test globalmood if globalmood > 0.: if self.myrank == 0: print('') print('BLOW UP!') print('write a last snapshot at blowup time', end="") # force a last write in the netCDF # might help locate the origin of the # blowup self.IO.t_next_hist = t stop = self.IO.write(self.model.state, t, n) if self.plotting: self.plotting.update(t, n) if t >= self.tend or stop: break mpitools.barrier() if self.myrank == 0: print() print("-"*80) if self.myrank == 0: if stop: print("Job is aborted") else: print("Job completed as expected") self.IO.finalize(self.model.state, t, n) if self.myrank == 0: print("Output written to:", self.IO.hist_path) self.model.write_stats(self.IO.output_directory) timing.write_timings(self.IO.output_directory) timing.analyze_timing(self.IO.output_directory) def compute_dt(self): """Calculate timestep dt from contravariant velocity U and cfl. The fixed value self.dt0 is returned if and only if self.auto_dt is False. Otherwise, the timestep is calculated as dt = cfl / max(|U|) . Note that the "dx" is hidden in the contravariant velocity U, which has dimension 1/T. In the formula, |U| denotes the norm of the contravariant velocity vector. If the velocity is zero everywhere, self.dt_max is returned. Otherwise, the smaller value of dt and dt_max is returned. """ if self.auto_dt: # Get U, V, and W in the same orientation U_object = self.model.state.U["i"] U = U_object.view() V = self.model.state.U["j"].viewlike(U_object) W = self.model.state.U["k"].viewlike(U_object) # Since the sqrt-function is strictly monotonically # increasing, the order of sqrt and max can be exchanged. # This way, it is only necessary to calculate the square # root of a single value, which is faster. U_max = np.sqrt(np.max(U**2 + V**2 + W**2)) U_max = mpitools.global_max(U_max) # Note: the if-statement cannot be replaced by try-except, # because U_max is a numpy-float which throws a warning # instead of an error in case of division by zero. if U_max == 0.0: return self.dt_max else: dt = self.cfl / U_max return min(dt, self.dt_max) else: return self.dt0 def banner(self): logo = [ " _ _ _ ", " | \ | | | | ", " | \| |_ _| | ___ ___ ", " | . ` | | | | |/ _ \/ __| ", " | |\ | |_| | | __/\__ \ ", " |_| \_|\__, |_|\___||___/ ", " __/ | ", " |___/ ", " "] if self.myrank == 0: print("Welcome to") for l in logo: print(" "*10+l) class Logger(object): def __init__(self, logfile): self.terminal = sys.stdout self.log = open(logfile, "w") def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): # this flush method is needed for python 3 compatibility. # this handles the flush command by doing nothing. # you might want to specify some extra behavior here. pass if __name__ == "__main__": from parameters import UserParameters param = UserParameters() param.time["dt_max"] = 1.5 nyles = Nyles(param) U = nyles.model.state.U["i"].view() V = nyles.model.state.U["j"].view() W = nyles.model.state.U["k"].view() if param.time["auto_dt"]: print("Case 1: U = 0, V = 0, W = 0") print(" dt is", nyles.compute_dt()) print("should be", param.time["dt_max"]) U += 1 print("Case 2: U = 1, V = 0, W = 0") print(" dt is", nyles.compute_dt()) print("should be", param.time["cfl"] / np.sqrt(1)) V += 1 print("Case 3: U = 1, V = 1, W = 0") print(" dt is", nyles.compute_dt()) print("should be", param.time["cfl"] / np.sqrt(2)) W += 1 print("Case 4: U = 1, V = 1, W = 1") print(" dt is", nyles.compute_dt()) print("should be", param.time["cfl"] / np.sqrt(3))
[ "pickle.dump", "model_advection.Advection", "timing.write_timings", "mpitools.global_max", "grid.Grid", "parameters.UserParameters", "mpitools.get_myrank", "topology.rank2loc", "nylesIO.NylesIO", "time.time", "timing.analyze_timing", "mpitools.barrier", "mpitools.global_sum", "numpy.max", ...
[((9685, 9701), 'parameters.UserParameters', 'UserParameters', ([], {}), '()\n', (9699, 9701), False, 'from parameters import UserParameters\n'), ((1409, 1435), 'mpitools.get_myrank', 'mpitools.get_myrank', (['procs'], {}), '(procs)\n', (1428, 1435), False, 'import mpitools\n'), ((1450, 1478), 'topology.rank2loc', 'topo.rank2loc', (['myrank', 'procs'], {}), '(myrank, procs)\n', (1463, 1478), True, 'import topology as topo\n'), ((1500, 1531), 'topology.get_neighbours', 'topo.get_neighbours', (['loc', 'procs'], {}), '(loc, procs)\n', (1519, 1531), True, 'import topology as topo\n'), ((1845, 1861), 'grid.Grid', 'grid.Grid', (['param'], {}), '(param)\n', (1854, 1861), False, 'import grid\n'), ((1957, 1979), 'nylesIO.NylesIO', 'nylesIO.NylesIO', (['param'], {}), '(param)\n', (1972, 1979), False, 'import nylesIO\n'), ((4590, 4596), 'time.time', 'time', ([], {}), '()\n', (4594, 4596), False, 'from time import time\n'), ((6850, 6896), 'timing.write_timings', 'timing.write_timings', (['self.IO.output_directory'], {}), '(self.IO.output_directory)\n', (6870, 6896), False, 'import timing\n'), ((6905, 6952), 'timing.analyze_timing', 'timing.analyze_timing', (['self.IO.output_directory'], {}), '(self.IO.output_directory)\n', (6926, 6952), False, 'import timing\n'), ((2463, 2494), 'model_les.LES', 'model_les.LES', (['param', 'self.grid'], {}), '(param, self.grid)\n', (2476, 2494), False, 'import model_les\n'), ((2987, 3040), 'plotting.Plotting', 'plotting.Plotting', (['param', 'self.model.state', 'self.grid'], {}), '(param, self.model.state, self.grid)\n', (3004, 3040), False, 'import plotting\n'), ((5737, 5767), 'mpitools.global_sum', 'mpitools.global_sum', (['localmood'], {}), '(localmood)\n', (5756, 5767), False, 'import mpitools\n'), ((6391, 6409), 'mpitools.barrier', 'mpitools.barrier', ([], {}), '()\n', (6407, 6409), False, 'import mpitools\n'), ((8167, 8193), 'mpitools.global_max', 'mpitools.global_max', (['U_max'], {}), '(U_max)\n', (8186, 8193), False, 'import mpitools\n'), ((2262, 2285), 'pickle.dump', 'pickle.dump', (['param', 'fid'], {}), '(param, fid)\n', (2273, 2285), False, 'import pickle\n'), ((2565, 2609), 'model_les.LES', 'model_les.LES', (['param', 'self.grid'], {'linear': '(True)'}), '(param, self.grid, linear=True)\n', (2578, 2609), False, 'import model_les\n'), ((4861, 4867), 'time.time', 'time', ([], {}), '()\n', (4865, 4867), False, 'from time import time\n'), ((8119, 8151), 'numpy.max', 'np.max', (['(U ** 2 + V ** 2 + W ** 2)'], {}), '(U ** 2 + V ** 2 + W ** 2)\n', (8125, 8151), True, 'import numpy as np\n'), ((10205, 10215), 'numpy.sqrt', 'np.sqrt', (['(1)'], {}), '(1)\n', (10212, 10215), True, 'import numpy as np\n'), ((10371, 10381), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (10378, 10381), True, 'import numpy as np\n'), ((10537, 10547), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (10544, 10547), True, 'import numpy as np\n'), ((2683, 2720), 'model_advection.Advection', 'model_adv.Advection', (['param', 'self.grid'], {}), '(param, self.grid)\n', (2702, 2720), True, 'import model_advection as model_adv\n')]
""" Phase plane plot function """ import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm __all__ = [ 'phase_plane' ] def phase_plane(odeobject, initial_conditions, display_window, nvectors=[20, 20], calculation_window=None, solution_direction='both', markinitialpoint=False, ax=None): """ Plot vector field and solution curves in the phase plane for planar autonomous systems. Parameters ---------- odeobject : callable A generic interface class to numeric integrators, defined in scipy.integrate. initial_conditions : array of arrays A list containing a set of initial conditions. For each of these initial conditions the system will be simulated and plot in the phase plane display_window : array_like Contain 4 elements, respectively, the lower limit and upper limits of x and y axis. nvectors : array_like, optional A list containing 2 elements, the number of columns and rows on the vector field grid. By default [20, 20]. calculation_window : array_like, optional Contain 4 elements, respectively, the lower limit and upper limits of x and y axis. By default, 4 times the display window in every direction. solution_direction : str, optional The solution can go 'foward', 'backward' or 'both'. The default is 'both' markinitialpoint : boolean, optional If True mark the initial point on the plot. By default it is False. ax : matplotlib axis object, optional Axis in which the phase plane will be plot. If none is provided create a new one. """ # Create new subplot if no axis is provided if ax is None: _, ax = plt.subplots() # If no calculation window is provided, define one from display_window if calculation_window is None: x1mean = np.mean(display_window[:2]) x2mean = np.mean(display_window[2:]) x1min = display_window[0] x1max = display_window[1] x2min = display_window[2] x2max = display_window[3] calculation_window = [(x1min-x1mean)*4+x1mean, (x1max-x1mean)*4+x1mean, (x2min-x2mean)*4+x2mean, (x2max-x2mean)*4+x2mean] # Define lower and upper limits from calculation_window lower_limit = [calculation_window[0], calculation_window[2]] upper_limit = [calculation_window[1], calculation_window[3]] # Get function from odeobject object def func(z): return odeobject.f(0, z, *odeobject.f_params) # Generate grid of points x = np.linspace(display_window[0], display_window[1], nvectors[0]) y = np.linspace(display_window[2], display_window[3], nvectors[1]) x, y = np.meshgrid(x, y) # Compute vector field xv = np.zeros_like(x) yv = np.zeros_like(y) for i in range(x.shape[0]): for j in range(x.shape[1]): state2d = np.array([x[i, j], y[i, j]]) state2d_derivative = func(state2d) xv[i, j] = state2d_derivative[0] yv[i, j] = state2d_derivative[1] # Normalize vector field norm = np.hypot(xv, yv) norm[norm == 0] = 1 xv, yv = xv/norm, yv/norm # Plot vector Field ax.quiver(x, y, xv, yv, norm, pivot='mid', units='xy', cmap=cm.plasma) # Set simulation parameters t1 = 100*1/np.mean(norm)*(np.max(upper_limit)-np.min(lower_limit)) dt = 1/100*1/np.mean(norm)*(np.max(upper_limit)-np.min(lower_limit)) for x0 in initial_conditions: foward = [] backward = [] if solution_direction is'foward' or solution_direction is'both': odeobject.set_initial_value(x0) while odeobject.successful() and odeobject.t < t1: xnext = odeobject.integrate(odeobject.t+dt) if np.logical_or(xnext < lower_limit, xnext > upper_limit).any(): break foward.append(xnext) if solution_direction is 'backward' or solution_direction is'both': odeobject.set_initial_value(x0) while odeobject.successful() and odeobject.t > -1*t1: xnext = odeobject.integrate(odeobject.t-dt) if np.logical_or(xnext < lower_limit, xnext > upper_limit).any(): break backward.append(xnext) if markinitialpoint: ax.plot(x0[0], x0[1], marker='o', markersize=5, color='black') x0 = np.reshape(x0, (-1, 2)) foward = np.reshape(foward, (-1, 2)) backward = np.reshape(backward[::-1], (-1, 2)) x = np.concatenate((backward, x0, foward), axis=0) ax.plot(x[:, 0], x[:, 1], linewidth=1.5) ax.axis(display_window) return
[ "numpy.meshgrid", "numpy.zeros_like", "numpy.hypot", "numpy.max", "numpy.mean", "numpy.array", "numpy.reshape", "numpy.linspace", "numpy.min", "numpy.logical_or", "matplotlib.pyplot.subplots", "numpy.concatenate" ]
[((2724, 2786), 'numpy.linspace', 'np.linspace', (['display_window[0]', 'display_window[1]', 'nvectors[0]'], {}), '(display_window[0], display_window[1], nvectors[0])\n', (2735, 2786), True, 'import numpy as np\n'), ((2795, 2857), 'numpy.linspace', 'np.linspace', (['display_window[2]', 'display_window[3]', 'nvectors[1]'], {}), '(display_window[2], display_window[3], nvectors[1])\n', (2806, 2857), True, 'import numpy as np\n'), ((2869, 2886), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (2880, 2886), True, 'import numpy as np\n'), ((2924, 2940), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (2937, 2940), True, 'import numpy as np\n'), ((2950, 2966), 'numpy.zeros_like', 'np.zeros_like', (['y'], {}), '(y)\n', (2963, 2966), True, 'import numpy as np\n'), ((3264, 3280), 'numpy.hypot', 'np.hypot', (['xv', 'yv'], {}), '(xv, yv)\n', (3272, 3280), True, 'import numpy as np\n'), ((1809, 1823), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1821, 1823), True, 'import matplotlib.pyplot as plt\n'), ((1952, 1979), 'numpy.mean', 'np.mean', (['display_window[:2]'], {}), '(display_window[:2])\n', (1959, 1979), True, 'import numpy as np\n'), ((1997, 2024), 'numpy.mean', 'np.mean', (['display_window[2:]'], {}), '(display_window[2:])\n', (2004, 2024), True, 'import numpy as np\n'), ((4654, 4677), 'numpy.reshape', 'np.reshape', (['x0', '(-1, 2)'], {}), '(x0, (-1, 2))\n', (4664, 4677), True, 'import numpy as np\n'), ((4695, 4722), 'numpy.reshape', 'np.reshape', (['foward', '(-1, 2)'], {}), '(foward, (-1, 2))\n', (4705, 4722), True, 'import numpy as np\n'), ((4742, 4777), 'numpy.reshape', 'np.reshape', (['backward[::-1]', '(-1, 2)'], {}), '(backward[::-1], (-1, 2))\n', (4752, 4777), True, 'import numpy as np\n'), ((4791, 4837), 'numpy.concatenate', 'np.concatenate', (['(backward, x0, foward)'], {'axis': '(0)'}), '((backward, x0, foward), axis=0)\n', (4805, 4837), True, 'import numpy as np\n'), ((3057, 3085), 'numpy.array', 'np.array', (['[x[i, j], y[i, j]]'], {}), '([x[i, j], y[i, j]])\n', (3065, 3085), True, 'import numpy as np\n'), ((3484, 3497), 'numpy.mean', 'np.mean', (['norm'], {}), '(norm)\n', (3491, 3497), True, 'import numpy as np\n'), ((3499, 3518), 'numpy.max', 'np.max', (['upper_limit'], {}), '(upper_limit)\n', (3505, 3518), True, 'import numpy as np\n'), ((3519, 3538), 'numpy.min', 'np.min', (['lower_limit'], {}), '(lower_limit)\n', (3525, 3538), True, 'import numpy as np\n'), ((3557, 3570), 'numpy.mean', 'np.mean', (['norm'], {}), '(norm)\n', (3564, 3570), True, 'import numpy as np\n'), ((3572, 3591), 'numpy.max', 'np.max', (['upper_limit'], {}), '(upper_limit)\n', (3578, 3591), True, 'import numpy as np\n'), ((3592, 3611), 'numpy.min', 'np.min', (['lower_limit'], {}), '(lower_limit)\n', (3598, 3611), True, 'import numpy as np\n'), ((3949, 4004), 'numpy.logical_or', 'np.logical_or', (['(xnext < lower_limit)', '(xnext > upper_limit)'], {}), '(xnext < lower_limit, xnext > upper_limit)\n', (3962, 4004), True, 'import numpy as np\n'), ((4374, 4429), 'numpy.logical_or', 'np.logical_or', (['(xnext < lower_limit)', '(xnext > upper_limit)'], {}), '(xnext < lower_limit, xnext > upper_limit)\n', (4387, 4429), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # Author: <NAME> (<EMAIL>) # License: BSD-3-Clause import os import numpy as np import astropy.units as u import matplotlib.pyplot as plt import matplotlib import pandas as pd from astropy import units as u from astropy.cosmology import Planck15 as cosmo from astropy import constants as const from scipy.interpolate import UnivariateSpline from . import utilities, sncosmo_spectral_v13 FIG_WIDTH = 5 FONTSIZE = 10 FONTSIZE_TICKMARKS = 9 FONTSIZE_LEGEND = 12 FONTSIZE_LABEL = 12 ANNOTATION_FONTSIZE = 8 TITLE_FONTSIZE = 10 DPI = 400 XRTCOLUMN = "flux0310_pi_-2" nice_fonts = { "text.usetex": True, "font.family": "serif", "font.serif": "Times New Roman", } matplotlib.rcParams.update(nice_fonts) cmap = utilities.load_info_json("cmap") filter_wl = utilities.load_info_json("filter_wl") filterlabel = utilities.load_info_json("filterlabel") def plot_sed_from_flux( flux: list, bands: list, spectrum, fittype: str = "powerlaw", redshift: float = None, flux_err: list = None, index: int = None, plotmag: bool = False, ): """ """ outpath = os.path.join("plots", "global", fittype) if not os.path.exists(outpath): os.makedirs(outpath) wl_observed = [] for band in bands: wl_observed.append(filter_wl[band]) freq_observed = const.c.value / (np.array(wl_observed) * 1e-10) plt.figure(figsize=(8, 0.75 * 8), dpi=DPI) ax1 = plt.subplot(111) ax1.invert_yaxis() if plotmag: ax1.set_ylim([20.5, 17.5]) ax1.set_xlim(1000, 10000) else: ax1.set_ylim([2e-28, 4e-27]) ax1.set_xlim([3.5e14, 2e15]) plt.xscale("log") plt.yscale("log") if plotmag: mag_model = [] model_wl = [] for band in bands: mag_model.append(utilities.magnitude_in_band(band, spectrum)) model_wl.append(filter_wl[band]) ax1.scatter(model_wl, mag_model, marker=".", color="black", label="model") if flux_err is not None: ax1.errorbar( utilities.nu_to_lambda(freq_observed), utilities.flux_to_abmag(flux), utilities.flux_err_to_abmag_err(flux, flux_err), fmt=".", color="blue", label="data", ) else: ax1.scatter( utilities.nu_to_lambda(freq_observed), utilities.flux_to_abmag(flux), marker=".", color="blue", label="data", ) ax1.plot( np.array(spectrum.wave), utilities.flux_to_abmag(spectrum.flux), color="gray", label="model spectrum", ) ax1.set_ylabel("Magnitude [AB]", fontsize=FONTSIZE_LABEL) else: if flux_err is not None: ax1.errorbar( freq_observed, flux, flux_err, fmt=".", color="blue", label="data" ) else: ax1.scatter(freq_observed, flux, marker=".", color="blue", label="data") ax1.plot( utilities.lambda_to_nu(np.array(spectrum.wave)), spectrum.flux, color="gray", label="model spectrum", ) ax1.set_ylabel( r"F_$\nu$ [erg s$^{-1}$ cm$^{-2}$ Hz^${-1}$]", fontsize=FONTSIZE_LABEL ) ax2 = ax1.secondary_xaxis( "top", functions=(utilities.lambda_to_nu, utilities.nu_to_lambda) ) ax2.set_xlabel(r"$\nu$ [Hz]", fontsize=FONTSIZE_LABEL) ax1.set_xlabel(r"$\lambda$ [Å]", fontsize=FONTSIZE_LABEL) plt.legend(fontsize=FONTSIZE_LEGEND) if plotmag: if index is not None: plt.savefig(f"{fittype}_global_bin_{index+1}_mag.png") else: plt.savefig(f"{fittype}_global_mag.png") else: if index is not None: plt.savefig(f"{fittype}_global_bin_{index+1}_flux.png") else: plt.savefig(f"{fittype}_global_flux.png") plt.close() def plot_sed_from_dict( mags: dict, spectrum, annotations: dict = None, plotmag: bool = False, **kwargs ): """ """ if "temperature" in annotations.keys(): outpath = os.path.join("plots", "blackbody") elif "alpha" in annotations.keys(): outpath = os.path.join("plots", "powerlaw") else: outpath = "plots" if not os.path.exists(outpath): os.makedirs(outpath) frequencies = utilities.lambda_to_nu(spectrum.wave) * u.Hz spectrum_mags = [] plt.figure(figsize=(FIG_WIDTH, 0.75 * FIG_WIDTH), dpi=DPI) ax1 = plt.subplot(111) plt.xscale("log") if not plotmag: ax1.set_ylabel(r"$F_\nu~[$erg$~/~ s \cdot $cm$^2 \cdot$ Hz]") ax1.set_xlabel(r"$\nu$ [Hz]") plt.yscale("log") # ax1.set_ylim([1e-28, 4e-26]) ax1.set_ylim([2e-28, 4e-27]) # ax1.set_xlim([1e14, 2e15]) ax1.set_xlim([3.5e14, 2e15]) if "alpha" in annotations.keys(): alpha = annotations["alpha"] if "alpha_err" in annotations.keys(): alpha_err = annotations["alpha_err"] ax1.plot(frequencies.value, spectrum._flux, color="black") for key in mags.keys(): mag = mags[key]["observed"] mag_err = mags[key]["observed_err"] flux = utilities.abmag_to_flux(mag) flux_err = utilities.abmag_err_to_flux_err(mag, mag_err) ax1.errorbar( mags[key]["frequency"], flux, flux_err, color=cmap[key], fmt=".", label=filterlabel[key], ) ax2 = ax1.secondary_xaxis( "top", functions=(utilities.lambda_to_nu, utilities.nu_to_lambda) ) ax2.set_xlabel(r"$\lambda$ [Å]") else: ax1.set_ylabel("Magnitude [AB]") ax1.set_xlabel(r"$\lambda$ [Å]") ax1.invert_yaxis() ax1.set_ylim([21, 17]) ax1.plot(spectrum.wave, spectrum_mags) for key in mags.keys(): ax1.scatter(filter_wl[key], mags[key]["observed"], color=cmap[key]) ax2 = ax1.secondary_xaxis( "top", functions=(utilities.nu_to_lambda, utilities.lambda_to_nu) ) ax2.set_xlabel(r"$\nu$ [Hz]") bbox = dict(boxstyle="round", fc="none", ec="black") bbox2 = dict(boxstyle="round", fc="none", ec="blue") if annotations: annotationstr = "" if "alpha" in annotations.keys(): alpha = annotations["alpha"] annotationstr += f"Spectral index $\\alpha$={alpha:.3f}\n" if "temperature" in annotations.keys(): temperature = annotations["temperature"] annotationstr += f"temperature={temperature:.2E}\n" if "scale" in annotations.keys(): scale = annotations["scale"] annotationstr += f"normalization $\\beta$={scale:.2E}\n" if "mjd" in annotations.keys(): mjd = annotations["mjd"] annotationstr += f"MJD={mjd:.2f}\n" # if "reduced_chisquare" in annotations.keys(): # temp = "red. $\\chi^2$=" # reduced_chisquare = annotations["reduced_chisquare"] # annotationstr += temp # annotationstr += f"{reduced_chisquare:.2f}\n" if "bolometric_luminosity" in annotations.keys(): bolometric_luminosity = annotations["bolometric_luminosity"] annotationstr += f"bol. lum.={bolometric_luminosity:.2E}\n" if annotationstr.endswith("\n"): annotationstr = annotationstr[:-2] if not plotmag: annotation_location = (0.7e15, 1.5e-26) else: annotation_location = (2e4, 18.0) ax1.legend( fontsize=FONTSIZE_LEGEND, fancybox=True, edgecolor="black", loc=0, ) plt.savefig(os.path.join(outpath, f"{mjd}.png")) plt.close() def plot_luminosity(fitparams, fittype, **kwargs): """ """ mjds = [] lumi_without_nir = [] lumi_with_nir = [] bolo_lumi = [] bolo_lumi_err = [] radius = [] radius_err = [] for entry in fitparams: mjds.append(fitparams[entry]["mjd"]) lumi_without_nir.append(fitparams[entry]["luminosity_uv_optical"]) lumi_with_nir.append(fitparams[entry]["luminosity_uv_nir"]) if fittype == "blackbody": for entry in fitparams: bolo_lumi.append(fitparams[entry]["bolometric_luminosity"]) bolo_lumi_err.append(fitparams[entry]["bolometric_luminosity_err"]) radius.append(fitparams[entry]["radius"]) radius_err.append(fitparams[entry]["radius_err"]) plt.figure(figsize=(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH), dpi=DPI) ax1 = plt.subplot(111) ax1.set_xlabel("Date [MJD]") if fittype == "blackbody": ax1.set_ylabel(r"Blackbody luminosity [erg s$^{-1}$]", fontsize=FONTSIZE_LABEL) plot1 = ax1.plot( mjds, bolo_lumi, label="Blackbody luminosity", color="tab:blue", alpha=0 ) if bolo_lumi_err[0] is not None: bolo_lumi = np.asarray(bolo_lumi) bolo_lumi_err = np.asarray(bolo_lumi_err) ax1.fill_between( mjds, bolo_lumi - bolo_lumi_err, bolo_lumi + bolo_lumi_err, label="Blackbody luminosity", color="tab:blue", alpha=0.3, ) ax2 = ax1.twinx() plot2 = ax2.plot( mjds, radius, color="tab:red", label="Blackbody radius", alpha=0 ) if radius_err[0] is not None: radius = np.asarray(radius) radius_err = np.asarray(radius_err) ax2.fill_between( mjds, radius - radius_err, radius + radius_err, color="tab:red", label="Blackbody radius", alpha=0.3, ) ax2.set_ylabel("Blackbody radius [cm]", fontsize=FONTSIZE_LABEL) plots = plot1 + plot2 labels = [p.get_label() for p in plots] ax2.yaxis.label.set_color("tab:red") ax1.yaxis.label.set_color("tab:blue") else: ax1.set_ylabel(r"Intrinsic luminosity [erg s$^{-1}$]", fontsize=FONTSIZE_LABEL) ax1.plot(mjds, lumi_without_nir, label="UV to Optical", color="tab:blue") ax1.plot(mjds, lumi_with_nir, label="UV to NIR", color="tab:red") ax1.legend(fontsize=FONTSIZE_LEGEND) plt.grid(which="both", axis="both", alpha=0.15) plt.tight_layout() plt.savefig(f"plots/luminosity_{fittype}.png") plt.close() def plot_lightcurve( df, bands, fitparams=None, fittype=None, redshift=None, nufnu=False, **kwargs ): """ """ filter_wl = utilities.load_info_json("filter_wl") cmap = utilities.load_info_json("cmap") mjds = df.obsmjd.values mjd_min = np.min(mjds) mjd_max = np.max(mjds) plt.figure(figsize=(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH), dpi=DPI) ax1 = plt.subplot(111) if nufnu: ax1.set_ylabel( r"F$_\nu$ [erg s$^{-1}$ cm$^{-2}$ Hz$^{-1}$]", fontsize=FONTSIZE_LABEL ) plt.yscale("log") else: ax1.set_ylabel("Magnitude [AB]", fontsize=FONTSIZE_LABEL) ax1.invert_yaxis() ax1.set_xlabel("Date [MJD]", fontsize=FONTSIZE_LABEL) if bands is None: bands_to_plot = df.band.unique() else: bands_to_plot = bands if fitparams: alpha = 0.2 else: alpha = 1 for key in filter_wl.keys(): if key in bands_to_plot: _df = df.query(f"telescope_band == '{key}'") wl = filter_wl[key] nu = utilities.lambda_to_nu(wl) if nufnu: ax1.errorbar( _df.obsmjd, utilities.abmag_to_flux(_df.mag), utilities.abmag_err_to_flux_err(_df.mag, _df.mag_err), color=cmap[key], fmt=".", alpha=alpha, edgecolors=None, label=filterlabel[key], ) else: ax1.errorbar( _df.obsmjd, _df.mag, _df.mag_err, color=cmap[key], fmt=".", alpha=alpha, edgecolors=None, label=filterlabel[key], ) # Now evaluate the model spectrum wavelengths = np.arange(1000, 60000, 10) * u.AA frequencies = const.c.value / (wavelengths.value * 1e-10) df_model = pd.DataFrame(columns=["mjd", "band", "mag"]) if fitparams: for entry in fitparams: if fittype == "powerlaw": alpha = fitparams[entry]["alpha"] alpha_err = fitparams[entry]["alpha_err"] scale = fitparams[entry]["scale"] scale_err = fitparams[entry]["scale_err"] flux_nu = ( (frequencies ** alpha * scale) * u.erg / u.cm ** 2 * u.Hz / u.s ) flux_nu_err = utilities.powerlaw_error_prop( frequencies, alpha, alpha_err, scale, scale_err ) spectrum = sncosmo_spectral_v13.Spectrum( wave=wavelengths, flux=flux_nu, unit=utilities.FNU ) if fittype == "blackbody": spectrum = utilities.blackbody_spectrum( temperature=fitparams[entry]["temperature"], scale=fitparams[entry]["scale"], redshift=redshift, extinction_av=fitparams[entry]["extinction_av"], extinction_rv=fitparams[entry]["extinction_rv"], ) for band in filter_wl.keys(): if band in bands_to_plot: wl = filter_wl[band] for index, _wl in enumerate(spectrum.wave): if _wl > wl: flux = spectrum.flux[index] mag = utilities.flux_to_abmag(flux) break # mag = utilities.magnitude_in_band(band, spectrum) df_model = df_model.append( { "mjd": fitparams[entry]["mjd"], "band": band, "mag": mag, "flux": flux, }, ignore_index=True, ) for key in filter_wl.keys(): if key in bands_to_plot: wl = filter_wl[key] nu = utilities.lambda_to_nu(wl) df_model_band = df_model.query(f"band == '{key}'") if len(df_model_band) > 1: spline = UnivariateSpline( df_model_band.mjd.values, df_model_band.mag.values ) spline.set_smoothing_factor(0.001) if nufnu: ax1.plot( df_model_band.mjd.values, utilities.abmag_to_flux(spline(df_model_band.mjd.values)), color=cmap[key], ) else: ax1.plot( df_model_band.mjd.values, spline(df_model_band.mjd.values), color=cmap[key], ) else: if nufnu: ax1.scatter( df_model_band.mjd.values, df_model_band.flux.values, color=cmap[key], ) else: ax1.scatter( df_model_band.mjd.values, df_model_band.mag.values, color=cmap[key], ) if fittype == "powerlaw": alphas = set() alpha_errs = set() for entry in fitparams: alpha = fitparams[entry]["alpha"] alpha_err = fitparams[entry]["alpha_err"] alphas.add(alpha) alpha_errs.add(alpha_err) # if len(alphas) == 1: # plt.title( # f"Powerlaw fit, spectral index $\\alpha$ = {list(alphas)[0]:.2f} $\pm$ {list(alpha_errs)[0]:.2f}", fontsize=TITLE_FONTSIZE, # ) if fittype == "blackbody": extinction_avs = set() extinction_rvs = set() extinction_av_errs = set() extinction_rv_errs = set() for entry in fitparams: av = fitparams[entry]["extinction_av"] rv = fitparams[entry]["extinction_rv"] av_err = fitparams[entry]["extinction_av_err"] rv_err = fitparams[entry]["extinction_rv_err"] extinction_avs.add(av) extinction_rvs.add(rv) extinction_av_errs.add(av_err) extinction_rv_errs.add(rv_err) title = "Blackbody fit, " if len(extinction_avs) == 1: extinction_av = list(extinction_avs)[0] extinction_av_err = list(extinction_av_errs)[0] if extinction_av_err is not None: title += ( f"$A_V$ = {extinction_av:.2f} $\pm$ {extinction_av_err:.2f}" ) elif extinction_av is not None: title += f"$A_V$ = {extinction_av:.2f}" else: title += f"$A_V$ = None" if len(extinction_rvs) == 1: extinction_rv = list(extinction_rvs)[0] extinction_rv_err = list(extinction_rv_errs)[0] if extinction_rv_err is not None: title += ( f", $R_V$ = {extinction_rv:.2f} $\pm$ {extinction_rv_err:.2f}" ) elif extinction_rv is not None: title += f", $R_V$ = {extinction_rv:.2f}" else: title += f", $R_V$ = None" # if len(title) > 0: # plt.title(title, fontsize=TITLE_FONTSIZE) # if redshift is not None: # d = cosmo.luminosity_distance(redshift) # d = d.to(u.cm).value # lumi = lambda flux: flux * 4 * np.pi * d ** 2 # flux = lambda lumi: lumi / (4 * np.pi * d ** 2) # ax2 = ax1.secondary_yaxis("right", functions=(lumi, flux)) # ax2.tick_params(axis="y", which="major", labelsize=FONTSIZE) # ax2.set_ylabel(r"$\nu$ L$_\nu$ [erg s$^{-1}$]", labelsize=FONTSIZE_LABEL) ax1.tick_params(axis="both", which="major", labelsize=FONTSIZE_TICKMARKS) plt.legend(fontsize=FONTSIZE_LEGEND) # , loc=(0.25,0.06)) plt.grid(which="both", alpha=0.15) plt.tight_layout() if fitparams: plt.savefig(f"plots/lightcurve_{fittype}.png") else: plt.savefig(f"plots/lightcurve.png") plt.close() def plot_temperature(fitparams, **kwargs): """ """ plt.figure(figsize=(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH), dpi=DPI) ax1 = plt.subplot(111) ax1.set_ylabel("Temperature [K]", fontsize=FONTSIZE_LABEL) ax1.set_xlabel("Date [MJD]", fontsize=FONTSIZE_LABEL) ax2 = ax1.twinx() ax2.set_ylabel("Blackbody radius [cm]", fontsize=FONTSIZE_LABEL) mjds = [] temps = [] temps_err = [] radii = [] radii_err = [] for entry in fitparams: mjds.append(fitparams[entry]["mjd"]) temps.append(fitparams[entry]["temperature"]) temps_err.append(fitparams[entry]["temperature_err"]) radii.append(fitparams[entry]["radius"]) radii_err.append(fitparams[entry]["radius_err"]) # ax1.plot(mjds, temps, color="blue") # ax2.plot(mjds, radii, color="red") if temps_err[0] is not None: temps = np.asarray(temps) temps_err = np.asarray(temps_err) ax1.fill_between( mjds, temps - temps_err, temps + temps_err, color="tab:blue", alpha=0.3 ) if radii_err[0] is not None: radii = np.asarray(radii) radii_err = np.asarray(radii_err) ax2.fill_between( mjds, radii - radii_err, radii + radii_err, color="tab:red", alpha=0.3 ) ax1.yaxis.label.set_color("tab:blue") ax2.yaxis.label.set_color("tab:red") plt.tight_layout() plt.savefig(f"plots/temperature_radius.png") plt.close() def plot_sed(df, spectrum, annotations: dict = None, plotmag: bool = False, **kwargs): """ """ if "temperature" in annotations.keys(): outpath = os.path.join("plots", "blackbody") elif "alpha" in annotations.keys(): outpath = os.path.join("plots", "powerlaw") else: outpath = "plots" if not os.path.exists(outpath): os.makedirs(outpath) frequencies = utilities.lambda_to_nu(spectrum.wave) * u.Hz spectrum_mags = [] plt.figure(figsize=(FIG_WIDTH, 0.75 * FIG_WIDTH), dpi=DPI) ax1 = plt.subplot(111) plt.xscale("log") if not plotmag: ax1.set_ylabel( r"$F_\nu~[$erg$~/~ s \cdot $cm$^2 \cdot$ Hz]", fontsize=FONTSIZE_LABEL ) ax1.set_xlabel(r"Frequency [Hz]", fontsize=FONTSIZE_LABEL) plt.yscale("log") ax1.set_ylim([2e-28, 4e-27]) ax1.set_xlim([3.5e14, 2e15]) if "alpha" in annotations.keys(): alpha = annotations["alpha"] if "alpha_err" in annotations.keys(): alpha_err = annotations["alpha_err"] ax1.plot(frequencies.value, spectrum._flux, color="black") for index, row in df.iterrows(): ax1.errorbar( utilities.lambda_to_nu(row.wavelength), row["mean_flux"], row["mean_flux_err"], color=cmap[row.telescope_band], fmt=".", label=filterlabel[row.telescope_band], ) ax2 = ax1.secondary_xaxis( "top", functions=(utilities.lambda_to_nu, utilities.nu_to_lambda) ) ax2.set_xlabel(r"Wavelength [Å]", fontsize=FONTSIZE_LABEL) else: ax1.set_ylabel("Magnitude [AB]", fontsize=FONTSIZE_LABEL) ax1.set_xlabel(r"Wavelength [Å]", fontsize=FONTSIZE_LABEL) ax1.invert_yaxis() ax1.set_ylim([21, 16]) ax1.plot(spectrum.wave, utilities.flux_to_abmag(spectrum._flux)) for index, row in df.iterrows(): ax1.errorbar( row.wavelength, row["mean_mag"], row["mean_mag_err"], color=cmap[row.telescope_band], fmt=".", label=filterlabel[row.telescope_band], ) ax2 = ax1.secondary_xaxis( "top", functions=(utilities.nu_to_lambda, utilities.lambda_to_nu) ) ax2.set_xlabel(r"Frequency [Hz]", fontsize=FONTSIZE_LABEL) # # begin ugly hack # # Swift V # mjd = annotations["mjd"] # mags_v = {58714.54667777777: [17.7093705099824, 0.159859385437542], 58715.650394444434: [17.3533111527872, 0.153035370548604], 58716.51125555553: [17.0886959322036, 0.213560248915708], 58718.47233888889: [17.4349390440326, 0.172562127107652]} # mags_b = {58714.54667777777: [17.6337374189878, 0.100476947040498], 58715.650394444434: [17.5348778339957, 0.109744027303754], 58716.51125555553: [17.5482380417231, 0.170389000863806], 58718.47233888889: [17.3444649425843, 0.104057279236277]} # ax1.errorbar( # filter_wl["Swift+V"], # mags_v[mjd][0], # mags_v[mjd][1], # color=cmap["Swift+V"], # fmt=".", # label=filterlabel["Swift+V"], # ) # ax1.errorbar( # filter_wl["Swift+B"], # mags_b[mjd][0], # mags_b[mjd][1], # color=cmap["Swift+B"], # fmt=".", # label=filterlabel["Swift+B"], # ) # # end of ugly hack bbox = dict(boxstyle="round", fc="none", ec="black") bbox2 = dict(boxstyle="round", fc="none", ec="blue") if annotations: annotationstr = "" if "alpha" in annotations.keys(): alpha = annotations["alpha"] annotationstr += f"Spectral index $\\alpha$={alpha:.3f}\n" if "temperature" in annotations.keys(): temperature = annotations["temperature"] annotationstr += f"temperature={temperature:.2E} K\n" if "scale" in annotations.keys(): scale = annotations["scale"] annotationstr += f"normalization $\\beta$={scale:.2E}\n" if "mjd" in annotations.keys(): mjd = annotations["mjd"] annotationstr += f"MJD={mjd:.2f}\n" if "bolometric_luminosity" in annotations.keys(): bolometric_luminosity = annotations["bolometric_luminosity"] annotationstr += f"bol. lum.={bolometric_luminosity:.2E}\n" if annotationstr.endswith("\n"): annotationstr = annotationstr[:-1] # if not plotmag: annotation_location = (0.7e15, 1.5e-26) # else: annotation_location = (2e4, 18.0) bbox = dict(boxstyle="round", fc="1") ax1.text( 0.3, 0.07, annotationstr, transform=ax1.transAxes, bbox=bbox, fontsize=FONTSIZE_LEGEND - 2, ) ax1.legend( fontsize=FONTSIZE_LEGEND - 2, fancybox=True, edgecolor="black", loc=0, ) plt.tight_layout() plt.savefig(os.path.join(outpath, f"{mjd}.png")) plt.close()
[ "matplotlib.pyplot.yscale", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.tight_layout", "os.path.join", "pandas.DataFrame", "matplotlib.pyplot.close", "matplotlib.rcParams.update", "scipy.interpolate.UnivariateSpline", "os.path.exists", "numpy.max", "matplotlib.pyplot.legend"...
[((697, 735), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (['nice_fonts'], {}), '(nice_fonts)\n', (723, 735), False, 'import matplotlib\n'), ((1121, 1161), 'os.path.join', 'os.path.join', (['"""plots"""', '"""global"""', 'fittype'], {}), "('plots', 'global', fittype)\n", (1133, 1161), False, 'import os\n'), ((1390, 1432), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 0.75 * 8)', 'dpi': 'DPI'}), '(figsize=(8, 0.75 * 8), dpi=DPI)\n', (1400, 1432), True, 'import matplotlib.pyplot as plt\n'), ((1443, 1459), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (1454, 1459), True, 'import matplotlib.pyplot as plt\n'), ((3607, 3643), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': 'FONTSIZE_LEGEND'}), '(fontsize=FONTSIZE_LEGEND)\n', (3617, 3643), True, 'import matplotlib.pyplot as plt\n'), ((4006, 4017), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4015, 4017), True, 'import matplotlib.pyplot as plt\n'), ((4526, 4584), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(FIG_WIDTH, 0.75 * FIG_WIDTH)', 'dpi': 'DPI'}), '(figsize=(FIG_WIDTH, 0.75 * FIG_WIDTH), dpi=DPI)\n', (4536, 4584), True, 'import matplotlib.pyplot as plt\n'), ((4595, 4611), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (4606, 4611), True, 'import matplotlib.pyplot as plt\n'), ((4616, 4633), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (4626, 4633), True, 'import matplotlib.pyplot as plt\n'), ((7898, 7909), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7907, 7909), True, 'import matplotlib.pyplot as plt\n'), ((8670, 8733), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH)', 'dpi': 'DPI'}), '(figsize=(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH), dpi=DPI)\n', (8680, 8733), True, 'import matplotlib.pyplot as plt\n'), ((8744, 8760), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (8755, 8760), True, 'import matplotlib.pyplot as plt\n'), ((10492, 10539), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'which': '"""both"""', 'axis': '"""both"""', 'alpha': '(0.15)'}), "(which='both', axis='both', alpha=0.15)\n", (10500, 10539), True, 'import matplotlib.pyplot as plt\n'), ((10544, 10562), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10560, 10562), True, 'import matplotlib.pyplot as plt\n'), ((10567, 10613), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""plots/luminosity_{fittype}.png"""'], {}), "(f'plots/luminosity_{fittype}.png')\n", (10578, 10613), True, 'import matplotlib.pyplot as plt\n'), ((10618, 10629), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (10627, 10629), True, 'import matplotlib.pyplot as plt\n'), ((10891, 10903), 'numpy.min', 'np.min', (['mjds'], {}), '(mjds)\n', (10897, 10903), True, 'import numpy as np\n'), ((10918, 10930), 'numpy.max', 'np.max', (['mjds'], {}), '(mjds)\n', (10924, 10930), True, 'import numpy as np\n'), ((10936, 10999), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH)', 'dpi': 'DPI'}), '(figsize=(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH), dpi=DPI)\n', (10946, 10999), True, 'import matplotlib.pyplot as plt\n'), ((11010, 11026), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (11021, 11026), True, 'import matplotlib.pyplot as plt\n'), ((12635, 12679), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['mjd', 'band', 'mag']"}), "(columns=['mjd', 'band', 'mag'])\n", (12647, 12679), True, 'import pandas as pd\n'), ((19019, 19055), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': 'FONTSIZE_LEGEND'}), '(fontsize=FONTSIZE_LEGEND)\n', (19029, 19055), True, 'import matplotlib.pyplot as plt\n'), ((19082, 19116), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'which': '"""both"""', 'alpha': '(0.15)'}), "(which='both', alpha=0.15)\n", (19090, 19116), True, 'import matplotlib.pyplot as plt\n'), ((19121, 19139), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (19137, 19139), True, 'import matplotlib.pyplot as plt\n'), ((19273, 19284), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (19282, 19284), True, 'import matplotlib.pyplot as plt\n'), ((19346, 19409), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH)', 'dpi': 'DPI'}), '(figsize=(FIG_WIDTH, 1 / 1.414 * FIG_WIDTH), dpi=DPI)\n', (19356, 19409), True, 'import matplotlib.pyplot as plt\n'), ((19420, 19436), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (19431, 19436), True, 'import matplotlib.pyplot as plt\n'), ((20659, 20677), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (20675, 20677), True, 'import matplotlib.pyplot as plt\n'), ((20682, 20726), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""plots/temperature_radius.png"""'], {}), "(f'plots/temperature_radius.png')\n", (20693, 20726), True, 'import matplotlib.pyplot as plt\n'), ((20731, 20742), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (20740, 20742), True, 'import matplotlib.pyplot as plt\n'), ((21227, 21285), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(FIG_WIDTH, 0.75 * FIG_WIDTH)', 'dpi': 'DPI'}), '(figsize=(FIG_WIDTH, 0.75 * FIG_WIDTH), dpi=DPI)\n', (21237, 21285), True, 'import matplotlib.pyplot as plt\n'), ((21296, 21312), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (21307, 21312), True, 'import matplotlib.pyplot as plt\n'), ((21317, 21334), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (21327, 21334), True, 'import matplotlib.pyplot as plt\n'), ((25830, 25848), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (25846, 25848), True, 'import matplotlib.pyplot as plt\n'), ((25906, 25917), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (25915, 25917), True, 'import matplotlib.pyplot as plt\n'), ((1174, 1197), 'os.path.exists', 'os.path.exists', (['outpath'], {}), '(outpath)\n', (1188, 1197), False, 'import os\n'), ((1207, 1227), 'os.makedirs', 'os.makedirs', (['outpath'], {}), '(outpath)\n', (1218, 1227), False, 'import os\n'), ((1661, 1678), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (1671, 1678), True, 'import matplotlib.pyplot as plt\n'), ((1687, 1704), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (1697, 1704), True, 'import matplotlib.pyplot as plt\n'), ((4205, 4239), 'os.path.join', 'os.path.join', (['"""plots"""', '"""blackbody"""'], {}), "('plots', 'blackbody')\n", (4217, 4239), False, 'import os\n'), ((4380, 4403), 'os.path.exists', 'os.path.exists', (['outpath'], {}), '(outpath)\n', (4394, 4403), False, 'import os\n'), ((4413, 4433), 'os.makedirs', 'os.makedirs', (['outpath'], {}), '(outpath)\n', (4424, 4433), False, 'import os\n'), ((4771, 4788), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (4781, 4788), True, 'import matplotlib.pyplot as plt\n'), ((7857, 7892), 'os.path.join', 'os.path.join', (['outpath', 'f"""{mjd}.png"""'], {}), "(outpath, f'{mjd}.png')\n", (7869, 7892), False, 'import os\n'), ((11166, 11183), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (11176, 11183), True, 'import matplotlib.pyplot as plt\n'), ((12524, 12550), 'numpy.arange', 'np.arange', (['(1000)', '(60000)', '(10)'], {}), '(1000, 60000, 10)\n', (12533, 12550), True, 'import numpy as np\n'), ((19166, 19212), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""plots/lightcurve_{fittype}.png"""'], {}), "(f'plots/lightcurve_{fittype}.png')\n", (19177, 19212), True, 'import matplotlib.pyplot as plt\n'), ((19231, 19267), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""plots/lightcurve.png"""'], {}), "(f'plots/lightcurve.png')\n", (19242, 19267), True, 'import matplotlib.pyplot as plt\n'), ((20162, 20179), 'numpy.asarray', 'np.asarray', (['temps'], {}), '(temps)\n', (20172, 20179), True, 'import numpy as np\n'), ((20200, 20221), 'numpy.asarray', 'np.asarray', (['temps_err'], {}), '(temps_err)\n', (20210, 20221), True, 'import numpy as np\n'), ((20392, 20409), 'numpy.asarray', 'np.asarray', (['radii'], {}), '(radii)\n', (20402, 20409), True, 'import numpy as np\n'), ((20430, 20451), 'numpy.asarray', 'np.asarray', (['radii_err'], {}), '(radii_err)\n', (20440, 20451), True, 'import numpy as np\n'), ((20906, 20940), 'os.path.join', 'os.path.join', (['"""plots"""', '"""blackbody"""'], {}), "('plots', 'blackbody')\n", (20918, 20940), False, 'import os\n'), ((21081, 21104), 'os.path.exists', 'os.path.exists', (['outpath'], {}), '(outpath)\n', (21095, 21104), False, 'import os\n'), ((21114, 21134), 'os.makedirs', 'os.makedirs', (['outpath'], {}), '(outpath)\n', (21125, 21134), False, 'import os\n'), ((21548, 21565), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (21558, 21565), True, 'import matplotlib.pyplot as plt\n'), ((25865, 25900), 'os.path.join', 'os.path.join', (['outpath', 'f"""{mjd}.png"""'], {}), "(outpath, f'{mjd}.png')\n", (25877, 25900), False, 'import os\n'), ((1355, 1376), 'numpy.array', 'np.array', (['wl_observed'], {}), '(wl_observed)\n', (1363, 1376), True, 'import numpy as np\n'), ((2594, 2617), 'numpy.array', 'np.array', (['spectrum.wave'], {}), '(spectrum.wave)\n', (2602, 2617), True, 'import numpy as np\n'), ((3703, 3759), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{fittype}_global_bin_{index + 1}_mag.png"""'], {}), "(f'{fittype}_global_bin_{index + 1}_mag.png')\n", (3714, 3759), True, 'import matplotlib.pyplot as plt\n'), ((3784, 3824), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{fittype}_global_mag.png"""'], {}), "(f'{fittype}_global_mag.png')\n", (3795, 3824), True, 'import matplotlib.pyplot as plt\n'), ((3877, 3934), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{fittype}_global_bin_{index + 1}_flux.png"""'], {}), "(f'{fittype}_global_bin_{index + 1}_flux.png')\n", (3888, 3934), True, 'import matplotlib.pyplot as plt\n'), ((3959, 4000), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{fittype}_global_flux.png"""'], {}), "(f'{fittype}_global_flux.png')\n", (3970, 4000), True, 'import matplotlib.pyplot as plt\n'), ((4298, 4331), 'os.path.join', 'os.path.join', (['"""plots"""', '"""powerlaw"""'], {}), "('plots', 'powerlaw')\n", (4310, 4331), False, 'import os\n'), ((9101, 9122), 'numpy.asarray', 'np.asarray', (['bolo_lumi'], {}), '(bolo_lumi)\n', (9111, 9122), True, 'import numpy as np\n'), ((9151, 9176), 'numpy.asarray', 'np.asarray', (['bolo_lumi_err'], {}), '(bolo_lumi_err)\n', (9161, 9176), True, 'import numpy as np\n'), ((9636, 9654), 'numpy.asarray', 'np.asarray', (['radius'], {}), '(radius)\n', (9646, 9654), True, 'import numpy as np\n'), ((9680, 9702), 'numpy.asarray', 'np.asarray', (['radius_err'], {}), '(radius_err)\n', (9690, 9702), True, 'import numpy as np\n'), ((20999, 21032), 'os.path.join', 'os.path.join', (['"""plots"""', '"""powerlaw"""'], {}), "('plots', 'powerlaw')\n", (21011, 21032), False, 'import os\n'), ((3128, 3151), 'numpy.array', 'np.array', (['spectrum.wave'], {}), '(spectrum.wave)\n', (3136, 3151), True, 'import numpy as np\n'), ((14923, 14991), 'scipy.interpolate.UnivariateSpline', 'UnivariateSpline', (['df_model_band.mjd.values', 'df_model_band.mag.values'], {}), '(df_model_band.mjd.values, df_model_band.mag.values)\n', (14939, 14991), False, 'from scipy.interpolate import UnivariateSpline\n')]
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import math import numbers from abc import abstractmethod from typing import Optional, Tuple import numpy as np from ..core._imperative_rt.core2 import apply from ..core.ops import builtin from ..core.ops.builtin import BatchNorm from ..functional import stack, zeros from ..tensor import Parameter, Tensor from . import init from .module import Module class RNNCellBase(Module): def __init__( self, input_size: int, hidden_size: int, bias: bool, num_chunks: int, ) -> None: # num_chunks indicates the number of gates super(RNNCellBase, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias # initialize weights self.gate_hidden_size = num_chunks * hidden_size self.weight_ih = Parameter( np.zeros((self.gate_hidden_size, input_size), dtype=np.float32) ) self.weight_hh = Parameter( np.zeros((self.gate_hidden_size, hidden_size), dtype=np.float32) ) if bias: self.bias_ih = Parameter( np.zeros((self.gate_hidden_size), dtype=np.float32) ) self.bias_hh = Parameter( np.zeros((self.gate_hidden_size), dtype=np.float32) ) else: self.bias_ih = zeros(shape=(self.gate_hidden_size)) self.bias_hh = zeros(shape=(self.gate_hidden_size)) self.reset_parameters() # if bias is False self.bias will remain zero def reset_parameters(self) -> None: stdv = 1.0 / math.sqrt(self.hidden_size) for weight in self.parameters(): init.uniform_(weight, -stdv, stdv) @abstractmethod def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor: raise NotImplementedError("forward not implemented !") class RNNCell(RNNCellBase): r"""An Elman RNN cell with tanh or ReLU non-linearity. .. math:: h' = \tanh(W_{ih} x + b_{ih} + W_{hh} h + b_{hh}) If :attr:`nonlinearity` is `'relu'`, then ReLU is used in place of tanh. Args: input_size: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` nonlinearity: The non-linearity to use. Can be either ``'tanh'`` or ``'relu'``. Default: ``'tanh'`` Inputs: input, hidden - **input** of shape `(batch, input_size)`: tensor containing input features - **hidden** of shape `(batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. Outputs: h' - **h'** of shape `(batch, hidden_size)`: tensor containing the next hidden state for each element in the batch Shape: - Input1: :math:`(N, H_{in})` tensor containing input features where :math:`H_{in}` = `input_size` - Input2: :math:`(N, H_{out})` tensor containing the initial hidden state for each element in the batch where :math:`H_{out}` = `hidden_size` Defaults to zero if not provided. - Output: :math:`(N, H_{out})` tensor containing the next hidden state for each element in the batch Examples: .. code-block:: import numpy as np import megengine as mge import megengine.module as M m = M.RNNCell(10, 20) inp = mge.tensor(np.random.randn(3, 10), dtype=np.float32) hx = mge.tensor(np.random.randn(3, 20), dtype=np.float32) out = m(inp, hx) print(out.numpy().shape) Outputs: .. code-block:: (3, 20) """ def __init__( self, input_size: int, hidden_size: int, bias: bool = True, nonlinearity: str = "tanh", ) -> None: self.nonlinearity = nonlinearity super(RNNCell, self).__init__(input_size, hidden_size, bias, num_chunks=1) def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor: if hx is None: hx = zeros(shape=(input.shape[0], self.gate_hidden_size),) op = builtin.RNNCell(nonlineMode=self.nonlinearity) return apply( op, input, self.weight_ih, self.bias_ih, hx, self.weight_hh, self.bias_hh )[0] class LSTMCell(RNNCellBase): r"""A long short-term memory (LSTM) cell. .. math:: \begin{array}{ll} i = \sigma(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\ f = \sigma(W_{if} x + b_{if} + W_{hf} h + b_{hf}) \\ g = \tanh(W_{ig} x + b_{ig} + W_{hg} h + b_{hg}) \\ o = \sigma(W_{io} x + b_{io} + W_{ho} h + b_{ho}) \\ c' = f * c + i * g \\ h' = o * \tanh(c') \\ \end{array} where :math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product. Args: input_size: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` Inputs: input, (h_0, c_0) - **input** of shape `(batch, input_size)`: tensor containing input features - **h_0** of shape `(batch, hidden_size)`: tensor containing the initial hidden state for each element in the batch. - **c_0** of shape `(batch, hidden_size)`: tensor containing the initial cell state for each element in the batch. If `(h_0, c_0)` is not provided, both **h_0** and **c_0** default to zero. Outputs: (h_1, c_1) - **h_1** of shape `(batch, hidden_size)`: tensor containing the next hidden state for each element in the batch - **c_1** of shape `(batch, hidden_size)`: tensor containing the next cell state for each element in the batch Examples: .. code-block:: import numpy as np import megengine as mge import megengine.module as M m = M.LSTMCell(10, 20) inp = mge.tensor(np.random.randn(3, 10), dtype=np.float32) hx = mge.tensor(np.random.randn(3, 20), dtype=np.float32) cx = mge.tensor(np.random.randn(3, 20), dtype=np.float32) hy, cy = m(inp, (hx, cx)) print(hy.numpy().shape) print(cy.numpy().shape) Outputs: .. code-block:: (3, 20) (3, 20) """ def __init__(self, input_size: int, hidden_size: int, bias: bool = True,) -> None: super(LSTMCell, self).__init__(input_size, hidden_size, bias, num_chunks=4) def forward( self, input: Tensor, hx: Optional[Tuple[Tensor, Tensor]] = None ) -> Tuple[Tensor, Tensor]: # hx: (h, c) if hx is None: h = zeros(shape=(input.shape[0], self.hidden_size)) c = zeros(shape=(input.shape[0], self.hidden_size)) else: h, c = hx op = builtin.LSTMCell() return apply( op, input, self.weight_ih, self.bias_ih, h, self.weight_hh, self.bias_hh, c )[:2] class RNNBase(Module): def __init__( self, input_size: int, hidden_size: int, num_layers: int = 1, bias: bool = True, batch_first: bool = False, dropout: float = 0, bidirectional: bool = False, proj_size: int = 0, ) -> None: super(RNNBase, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.bias = bias self.batch_first = batch_first self.dropout = float(dropout) self.bidirectional = bidirectional self.num_directions = 2 if self.bidirectional else 1 self.proj_size = proj_size # check validity of dropout if ( not isinstance(dropout, numbers.Number) or not 0 <= dropout <= 1 or isinstance(dropout, bool) ): raise ValueError( "Dropout should be a float in [0, 1], which indicates the probability " "of an element to be zero" ) if proj_size < 0: raise ValueError( "proj_size should be a positive integer or zero to disable projections" ) elif proj_size >= hidden_size: raise ValueError("proj_size has to be smaller than hidden_size") self.cells = [] for layer in range(self.num_layers): self.cells.append([]) for _ in range(self.num_directions): self.cells[layer].append(self.create_cell(layer)) # parameters have been initialized during the creation of the cells # if flatten, then delete cells self._flatten_parameters(self.cells) def _flatten_parameters(self, cells): gate_hidden_size = cells[0][0].gate_hidden_size size_dim1 = 0 for layer in range(self.num_layers): for direction in range(self.num_directions): size_dim1 += cells[layer][direction].weight_ih.shape[1] size_dim1 += cells[layer][direction].weight_hh.shape[1] if self.bias: size_dim1 += 2 * self.num_directions * self.num_layers self._flatten_weights = Parameter( np.zeros((gate_hidden_size, size_dim1), dtype=np.float32) ) self.reset_parameters() def reset_parameters(self) -> None: stdv = 1.0 / math.sqrt(self.hidden_size) for weight in self.parameters(): init.uniform_(weight, -stdv, stdv) @abstractmethod def create_cell(self, layer): raise NotImplementedError("Cell not implemented !") @abstractmethod def init_hidden(self): raise NotImplementedError("init_hidden not implemented !") @abstractmethod def get_output_from_hidden(self, hx): raise NotImplementedError("get_output_from_hidden not implemented !") @abstractmethod def apply_op(self, input, hx): raise NotImplementedError("apply_op not implemented !") def _apply_fn_to_hx(self, hx, fn): return fn(hx) def _stack_h_n(self, h_n): return stack(h_n, axis=0) def forward(self, input: Tensor, hx=None): if self.batch_first: batch_size = input.shape[0] input = input.transpose((1, 0, 2)) # [seq_len, batch_size, dim] else: batch_size = input.shape[1] if hx is None: hx = self.init_hidden(batch_size) output, h = self.apply_op(input, hx) if self.batch_first: output = output.transpose((1, 0, 2)) return output, h class RNN(RNNBase): r"""Applies a multi-layer Elman RNN with :math:`\tanh` or :math:`\text{ReLU}` non-linearity to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: h_t = \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{(t-1)} + b_{hh}) where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input at time `t`, and :math:`h_{(t-1)}` is the hidden state of the previous layer at time `t-1` or the initial hidden state at time `0`. If :attr:`nonlinearity` is ``'relu'``, then :math:`\text{ReLU}` is used instead of :math:`\tanh`. Args: input_size: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` num_layers: Number of recurrent layers. E.g., setting ``num_layers=2`` would mean stacking two RNNs together to form a `stacked RNN`, with the second RNN taking in outputs of the first RNN and computing the final results. Default: 1 nonlinearity: The non-linearity to use. Can be either ``'tanh'`` or ``'relu'``. Default: ``'tanh'`` bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` batch_first: If ``True``, then the input and output tensors are provided as `(batch, seq, feature)` instead of `(seq, batch, feature)`. Note that this does not apply to hidden or cell states. See the Inputs/Outputs sections below for details. Default: ``False`` dropout: If non-zero, introduces a `Dropout` layer on the outputs of each RNN layer except the last layer, with dropout probability equal to :attr:`dropout`. Default: 0 bidirectional: If ``True``, becomes a bidirectional RNN. Default: ``False`` Inputs: input, h_0 * **input**: tensor of shape :math:`(L, N, H_{in})` when ``batch_first=False`` or :math:`(N, L, H_{in})` when ``batch_first=True`` containing the features of the input sequence. The input can also be a packed variable length sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence` or :func:`torch.nn.utils.rnn.pack_sequence` for details. * **h_0**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the initial hidden state for each element in the batch. Defaults to zeros if not provided. where: .. math:: \begin{aligned} N ={} & \text{batch size} \\ L ={} & \text{sequence length} \\ D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\ H_{in} ={} & \text{input\_size} \\ H_{out} ={} & \text{hidden\_size} \end{aligned} Outputs: output, h_n * **output**: tensor of shape :math:`(L, N, D * H_{out})` when ``batch_first=False`` or :math:`(N, L, D * H_{out})` when ``batch_first=True`` containing the output features `(h_t)` from the last layer of the RNN, for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been given as the input, the output will also be a packed sequence. * **h_n**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the final hidden state for each element in the batch. Examples: .. code-block:: import numpy as np import megengine as mge import megengine.module as M m = M.RNN(10,20,2,batch_first=False,nonlinearity="relu",bias=True,bidirectional=True) inp = mge.tensor(np.random.randn(6, 30, 10), dtype=np.float32) hx = mge.tensor(np.random.randn(4, 30, 20), dtype=np.float32) out, hn = m(inp, hx) print(out.numpy().shape) Outputs: .. code-block:: (6, 30, 40) """ def __init__(self, *args, **kwargs) -> None: self.nonlinearity = kwargs.pop("nonlinearity", "tanh") super(RNN, self).__init__(*args, **kwargs) def create_cell(self, layer): if layer == 0: input_size = self.input_size else: input_size = self.num_directions * self.hidden_size return RNNCell(input_size, self.hidden_size, self.bias, self.nonlinearity) def init_hidden(self, batch_size): hidden_shape = ( self.num_directions * self.num_layers, batch_size, self.hidden_size, ) return zeros(shape=hidden_shape) def get_output_from_hidden(self, hx): return hx def apply_op(self, input, hx): fwd_mode = ( BatchNorm.FwdMode.TRAINING if self.training else BatchNorm.FwdMode.INFERENCE ) op = builtin.RNN( num_layers=self.num_layers, bidirectional=self.bidirectional, bias=self.bias, hidden_size=self.hidden_size, dropout=self.dropout, nonlineMode=self.nonlinearity, fwd_mode=fwd_mode, ) output, h = apply(op, input, hx, self._flatten_weights)[:2] output = output + h.sum() * 0 h = h + output.sum() * 0 return output, h class LSTM(RNNBase): r"""Applies a multi-layer long short-term memory LSTM to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} \\ i_t = \sigma(W_{ii} x_t + b_{ii} + W_{hi} h_{t-1} + b_{hi}) \\ f_t = \sigma(W_{if} x_t + b_{if} + W_{hf} h_{t-1} + b_{hf}) \\ g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hg} h_{t-1} + b_{hg}) \\ o_t = \sigma(W_{io} x_t + b_{io} + W_{ho} h_{t-1} + b_{ho}) \\ c_t = f_t \odot c_{t-1} + i_t \odot g_t \\ h_t = o_t \odot \tanh(c_t) \\ \end{array} where :math:`h_t` is the hidden state at time `t`, :math:`c_t` is the cell state at time `t`, :math:`x_t` is the input at time `t`, :math:`h_{t-1}` is the hidden state of the layer at time `t-1` or the initial hidden state at time `0`, and :math:`i_t`, :math:`f_t`, :math:`g_t`, :math:`o_t` are the input, forget, cell, and output gates, respectively. :math:`\sigma` is the sigmoid function, and :math:`\odot` is the Hadamard product. In a multilayer LSTM, the input :math:`x^{(l)}_t` of the :math:`l` -th layer (:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random variable which is :math:`0` with probability :attr:`dropout`. If ``proj_size > 0`` is specified, LSTM with projections will be used. This changes the LSTM cell in the following way. First, the dimension of :math:`h_t` will be changed from ``hidden_size`` to ``proj_size`` (dimensions of :math:`W_{hi}` will be changed accordingly). Second, the output hidden state of each layer will be multiplied by a learnable projection matrix: :math:`h_t = W_{hr}h_t`. Note that as a consequence of this, the output of LSTM network will be of different shape as well. See Inputs/Outputs sections below for exact dimensions of all variables. You can find more details in https://arxiv.org/abs/1402.1128. Args: input_size: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` num_layers: Number of recurrent layers. E.g., setting ``num_layers=2`` would mean stacking two LSTMs together to form a `stacked LSTM`, with the second LSTM taking in outputs of the first LSTM and computing the final results. Default: 1 bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` batch_first: If ``True``, then the input and output tensors are provided as `(batch, seq, feature)` instead of `(seq, batch, feature)`. Note that this does not apply to hidden or cell states. See the Inputs/Outputs sections below for details. Default: ``False`` dropout: If non-zero, introduces a `Dropout` layer on the outputs of each LSTM layer except the last layer, with dropout probability equal to :attr:`dropout`. Default: 0 bidirectional: If ``True``, becomes a bidirectional LSTM. Default: ``False`` proj_size: If ``> 0``, will use LSTM with projections of corresponding size. Default: 0 Inputs: input, (h_0, c_0) * **input**: tensor of shape :math:`(L, N, H_{in})` when ``batch_first=False`` or :math:`(N, L, H_{in})` when ``batch_first=True`` containing the features of the input sequence. The input can also be a packed variable length sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence` or :func:`torch.nn.utils.rnn.pack_sequence` for details. * **h_0**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the initial hidden state for each element in the batch. Defaults to zeros if (h_0, c_0) is not provided. * **c_0**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{cell})` containing the initial cell state for each element in the batch. Defaults to zeros if (h_0, c_0) is not provided. where: .. math:: \begin{aligned} N ={} & \text{batch size} \\ L ={} & \text{sequence length} \\ D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\ H_{in} ={} & \text{input\_size} \\ H_{cell} ={} & \text{hidden\_size} \\ H_{out} ={} & \text{proj\_size if } \text{proj\_size}>0 \text{ otherwise hidden\_size} \\ \end{aligned} Outputs: output, (h_n, c_n) * **output**: tensor of shape :math:`(L, N, D * H_{out})` when ``batch_first=False`` or :math:`(N, L, D * H_{out})` when ``batch_first=True`` containing the output features `(h_t)` from the last layer of the LSTM, for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been given as the input, the output will also be a packed sequence. * **h_n**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{out})` containing the final hidden state for each element in the batch. * **c_n**: tensor of shape :math:`(D * \text{num\_layers}, N, H_{cell})` containing the final cell state for each element in the batch. Examples: .. code-block:: import numpy as np import megengine as mge import megengine.module as M m = M.LSTM(10, 20, 2, batch_first=False, bidirectional=True, bias=True) inp = mge.tensor(np.random.randn(6, 30, 10), dtype=np.float32) hx = mge.tensor(np.random.randn(4, 30, 20), dtype=np.float32) cx = mge.tensor(np.random.randn(4, 30, 20), dtype=np.float32) out, (hn, cn) = m(inp,(hx,cx)) print(out.numpy().shape) Outputs: .. code-block:: (6, 30, 40) """ def __init__(self, *args, **kwargs) -> None: super(LSTM, self).__init__(*args, **kwargs) def create_cell(self, layer): if layer == 0: input_size = self.input_size else: input_size = self.num_directions * self.hidden_size return LSTMCell(input_size, self.hidden_size, self.bias) def init_hidden(self, batch_size): hidden_shape = ( self.num_directions * self.num_layers, batch_size, self.hidden_size, ) h = zeros(shape=hidden_shape) c = zeros(shape=hidden_shape) return (h, c) def get_output_from_hidden(self, hx): return hx[0] def apply_op(self, input, hx): fwd_mode = ( BatchNorm.FwdMode.TRAINING if self.training else BatchNorm.FwdMode.INFERENCE ) op = builtin.LSTM( num_layers=self.num_layers, bidirectional=self.bidirectional, bias=self.bias, hidden_size=self.hidden_size, proj_size=self.proj_size, dropout=self.dropout, fwd_mode=fwd_mode, ) output, h, c = apply(op, input, hx[0], hx[1], self._flatten_weights)[:3] placeholders = [output.sum() * 0, h.sum() * 0, c.sum() * 0] output = output + placeholders[1] + placeholders[2] h = h + placeholders[0] + placeholders[2] c = c + placeholders[0] + placeholders[1] return output, (h, c) def _apply_fn_to_hx(self, hx, fn): return (fn(hx[0]), fn(hx[1])) def _stack_h_n(self, h_n): h = [tup[0] for tup in h_n] c = [tup[1] for tup in h_n] return (stack(h, axis=0), stack(c, axis=0))
[ "numpy.zeros", "math.sqrt" ]
[((1204, 1267), 'numpy.zeros', 'np.zeros', (['(self.gate_hidden_size, input_size)'], {'dtype': 'np.float32'}), '((self.gate_hidden_size, input_size), dtype=np.float32)\n', (1212, 1267), True, 'import numpy as np\n'), ((1326, 1390), 'numpy.zeros', 'np.zeros', (['(self.gate_hidden_size, hidden_size)'], {'dtype': 'np.float32'}), '((self.gate_hidden_size, hidden_size), dtype=np.float32)\n', (1334, 1390), True, 'import numpy as np\n'), ((1948, 1975), 'math.sqrt', 'math.sqrt', (['self.hidden_size'], {}), '(self.hidden_size)\n', (1957, 1975), False, 'import math\n'), ((9885, 9942), 'numpy.zeros', 'np.zeros', (['(gate_hidden_size, size_dim1)'], {'dtype': 'np.float32'}), '((gate_hidden_size, size_dim1), dtype=np.float32)\n', (9893, 9942), True, 'import numpy as np\n'), ((10047, 10074), 'math.sqrt', 'math.sqrt', (['self.hidden_size'], {}), '(self.hidden_size)\n', (10056, 10074), False, 'import math\n'), ((1472, 1521), 'numpy.zeros', 'np.zeros', (['self.gate_hidden_size'], {'dtype': 'np.float32'}), '(self.gate_hidden_size, dtype=np.float32)\n', (1480, 1521), True, 'import numpy as np\n'), ((1592, 1641), 'numpy.zeros', 'np.zeros', (['self.gate_hidden_size'], {'dtype': 'np.float32'}), '(self.gate_hidden_size, dtype=np.float32)\n', (1600, 1641), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np x = np.array([1, 2, 3, 4]) print(np.sum(x)) print(x.sum()) x = np.array([[1, 1], [2, 2]]) print(x) # columns (first dimension) print(x.sum(axis=0)) print(x[:, 0].sum(), x[:, 1].sum()) # rows (second dimension) print(x.sum(axis=1)) print(x[0, :].sum(), x[1, :].sum()) x = np.random.rand(2, 2, 2) print(x.sum(axis=2)[0, 1]) print(x[0, 1, :].sum()) x = np.array([1, 3, 2]) print(x.min()) print(x.max()) # index of minimum print(x.argmin()) # index of maximum print(x.argmax()) print(np.all([True, True, False])) print(np.any([True, True, False])) a = np.zeros((100, 100)) print(np.any(a != 0)) print(np.all(a == a)) a = np.array([1, 2, 3, 2]) b = np.array([2, 2, 3, 2]) c = np.array([6, 4, 4, 5]) print(((a <= b) & (b <= c)).all()) x = np.array([1, 2, 3, 1]) y = np.array([[1, 2, 3], [5, 6, 1]]) print(x.mean()) print(np.median(x)) # last axis print(np.median(y, axis=-1)) # full population standard dev. print(x.std()) print(x.prod()) print(x.cumsum())
[ "numpy.sum", "numpy.median", "numpy.zeros", "numpy.any", "numpy.array", "numpy.random.rand", "numpy.all" ]
[((71, 93), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (79, 93), True, 'import numpy as np\n'), ((130, 156), 'numpy.array', 'np.array', (['[[1, 1], [2, 2]]'], {}), '([[1, 1], [2, 2]])\n', (138, 156), True, 'import numpy as np\n'), ((340, 363), 'numpy.random.rand', 'np.random.rand', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (354, 363), True, 'import numpy as np\n'), ((419, 438), 'numpy.array', 'np.array', (['[1, 3, 2]'], {}), '([1, 3, 2])\n', (427, 438), True, 'import numpy as np\n'), ((619, 639), 'numpy.zeros', 'np.zeros', (['(100, 100)'], {}), '((100, 100))\n', (627, 639), True, 'import numpy as np\n'), ((688, 710), 'numpy.array', 'np.array', (['[1, 2, 3, 2]'], {}), '([1, 2, 3, 2])\n', (696, 710), True, 'import numpy as np\n'), ((715, 737), 'numpy.array', 'np.array', (['[2, 2, 3, 2]'], {}), '([2, 2, 3, 2])\n', (723, 737), True, 'import numpy as np\n'), ((742, 764), 'numpy.array', 'np.array', (['[6, 4, 4, 5]'], {}), '([6, 4, 4, 5])\n', (750, 764), True, 'import numpy as np\n'), ((804, 826), 'numpy.array', 'np.array', (['[1, 2, 3, 1]'], {}), '([1, 2, 3, 1])\n', (812, 826), True, 'import numpy as np\n'), ((831, 863), 'numpy.array', 'np.array', (['[[1, 2, 3], [5, 6, 1]]'], {}), '([[1, 2, 3], [5, 6, 1]])\n', (839, 863), True, 'import numpy as np\n'), ((100, 109), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (106, 109), True, 'import numpy as np\n'), ((551, 578), 'numpy.all', 'np.all', (['[True, True, False]'], {}), '([True, True, False])\n', (557, 578), True, 'import numpy as np\n'), ((586, 613), 'numpy.any', 'np.any', (['[True, True, False]'], {}), '([True, True, False])\n', (592, 613), True, 'import numpy as np\n'), ((646, 660), 'numpy.any', 'np.any', (['(a != 0)'], {}), '(a != 0)\n', (652, 660), True, 'import numpy as np\n'), ((668, 682), 'numpy.all', 'np.all', (['(a == a)'], {}), '(a == a)\n', (674, 682), True, 'import numpy as np\n'), ((886, 898), 'numpy.median', 'np.median', (['x'], {}), '(x)\n', (895, 898), True, 'import numpy as np\n'), ((918, 939), 'numpy.median', 'np.median', (['y'], {'axis': '(-1)'}), '(y, axis=-1)\n', (927, 939), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt import pandas as pd t = np.linspace(0,39.98,num=2000) u = pd.read_excel('deslocamentos_artificial.xlsx').to_numpy() def plot_graph(u,t,no): """u = matrix of displacements, accelerations or velocitys no = number of node""" plt.figure(1,figsize=(12,4)) plt.plot(t,100*u[no*6-144-6 ,:],'b') plt.xlabel('Tempo (s)'); plt.ylabel('Deslocamento (cm)') plt.xlim(0,max(t)) plt.ylim(-max(100*u[no*6-144-6,:])*1.1,max(100*u[no*6-144-6,:])*1.1) plt.title(f'Deslocamento do nó {no} na direção 0 DEG') plt.grid(True) plt.show() plt.figure(2,figsize=(12,4)) plt.plot(t,100*u[no*6-144-5 ,:],'b') plt.xlabel('Tempo (s)'); plt.ylabel('Deslocamento (cm)') plt.xlim(0,max(t)) plt.ylim(-max(100*u[no*6-144-5,:])*1.1,max(100*u[no*6-144-5,:])*1.1) plt.title(f'Deslocamento do nó {no} na direção 90 DEG') plt.grid(True) plt.show() plt.figure(3,figsize=(12,4)) plt.plot(t,100*u[no*6-144-4 ,:],'b') plt.xlabel('Tempo (s)'); plt.ylabel('Deslocamento (cm)') plt.xlim(0,max(t)) plt.ylim(-max(100*u[no*6-144-4,:])*1.1,max(100*u[no*6-144-4,:])*1.1) plt.title(f'Deslocamento do nó {no} na direção UP') plt.grid(True) plt.show() plot_graph(u,t,212) plot_graph(u,t,201) plot_graph(u,t,195) plot_graph(u,t,213) plot_graph(u,t,202)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "pandas.read_excel", "matplotlib.pyplot.figure", "numpy.linspace", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.grid" ]
[((80, 111), 'numpy.linspace', 'np.linspace', (['(0)', '(39.98)'], {'num': '(2000)'}), '(0, 39.98, num=2000)\n', (91, 111), True, 'import numpy as np\n'), ((303, 333), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(12, 4)'}), '(1, figsize=(12, 4))\n', (313, 333), True, 'import matplotlib.pyplot as plt\n'), ((340, 386), 'matplotlib.pyplot.plot', 'plt.plot', (['t', '(100 * u[no * 6 - 144 - 6, :])', '"""b"""'], {}), "(t, 100 * u[no * 6 - 144 - 6, :], 'b')\n", (348, 386), True, 'import matplotlib.pyplot as plt\n'), ((382, 405), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Tempo (s)"""'], {}), "('Tempo (s)')\n", (392, 405), True, 'import matplotlib.pyplot as plt\n'), ((407, 438), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Deslocamento (cm)"""'], {}), "('Deslocamento (cm)')\n", (417, 438), True, 'import matplotlib.pyplot as plt\n'), ((542, 596), 'matplotlib.pyplot.title', 'plt.title', (['f"""Deslocamento do nó {no} na direção 0 DEG"""'], {}), "(f'Deslocamento do nó {no} na direção 0 DEG')\n", (551, 596), True, 'import matplotlib.pyplot as plt\n'), ((602, 616), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (610, 616), True, 'import matplotlib.pyplot as plt\n'), ((622, 632), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (630, 632), True, 'import matplotlib.pyplot as plt\n'), ((640, 670), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {'figsize': '(12, 4)'}), '(2, figsize=(12, 4))\n', (650, 670), True, 'import matplotlib.pyplot as plt\n'), ((677, 723), 'matplotlib.pyplot.plot', 'plt.plot', (['t', '(100 * u[no * 6 - 144 - 5, :])', '"""b"""'], {}), "(t, 100 * u[no * 6 - 144 - 5, :], 'b')\n", (685, 723), True, 'import matplotlib.pyplot as plt\n'), ((719, 742), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Tempo (s)"""'], {}), "('Tempo (s)')\n", (729, 742), True, 'import matplotlib.pyplot as plt\n'), ((744, 775), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Deslocamento (cm)"""'], {}), "('Deslocamento (cm)')\n", (754, 775), True, 'import matplotlib.pyplot as plt\n'), ((879, 934), 'matplotlib.pyplot.title', 'plt.title', (['f"""Deslocamento do nó {no} na direção 90 DEG"""'], {}), "(f'Deslocamento do nó {no} na direção 90 DEG')\n", (888, 934), True, 'import matplotlib.pyplot as plt\n'), ((940, 954), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (948, 954), True, 'import matplotlib.pyplot as plt\n'), ((960, 970), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (968, 970), True, 'import matplotlib.pyplot as plt\n'), ((978, 1008), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {'figsize': '(12, 4)'}), '(3, figsize=(12, 4))\n', (988, 1008), True, 'import matplotlib.pyplot as plt\n'), ((1015, 1061), 'matplotlib.pyplot.plot', 'plt.plot', (['t', '(100 * u[no * 6 - 144 - 4, :])', '"""b"""'], {}), "(t, 100 * u[no * 6 - 144 - 4, :], 'b')\n", (1023, 1061), True, 'import matplotlib.pyplot as plt\n'), ((1057, 1080), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Tempo (s)"""'], {}), "('Tempo (s)')\n", (1067, 1080), True, 'import matplotlib.pyplot as plt\n'), ((1082, 1113), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Deslocamento (cm)"""'], {}), "('Deslocamento (cm)')\n", (1092, 1113), True, 'import matplotlib.pyplot as plt\n'), ((1217, 1268), 'matplotlib.pyplot.title', 'plt.title', (['f"""Deslocamento do nó {no} na direção UP"""'], {}), "(f'Deslocamento do nó {no} na direção UP')\n", (1226, 1268), True, 'import matplotlib.pyplot as plt\n'), ((1274, 1288), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (1282, 1288), True, 'import matplotlib.pyplot as plt\n'), ((1294, 1304), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1302, 1304), True, 'import matplotlib.pyplot as plt\n'), ((115, 161), 'pandas.read_excel', 'pd.read_excel', (['"""deslocamentos_artificial.xlsx"""'], {}), "('deslocamentos_artificial.xlsx')\n", (128, 161), True, 'import pandas as pd\n')]
""" Input is group of motion corrected micrographs. Output is group of equalized images. """ import sys import mrcfile import cv2 import numpy as np import os from multiprocessing import Pool from icebreaker import filter_designer as fd from icebreaker import window_mean as wm from icebreaker import local_mask as lm from icebreaker import KNN_segmenter as KNN_seg def load_img(img_path): with mrcfile.open(img_path, "r", permissive=True) as mrc: img = mrc.data return img def multigroup(filelist_full): # for filename in filelist: img = load_img(filelist_full) # (os.path.join(indir, filename)) splitpath = os.path.split(filelist_full) # Config params x_patches = 40 y_patches = 40 num_of_segments = 32 final_image = equalize_im(img, x_patches, y_patches, num_of_segments) # final_image = img # !!!! TESTING # with mrcfile.new((path1+str(filename[:-4]) +'_' # +str(x_patches)+'x'+str(y_patches)+'x'+str(num_of_segments)+'flattened'+'.mrc'), # overwrite=True) as out_image: # Make fstring with mrcfile.new( os.path.join( splitpath[0] + "/flattened/" + splitpath[1][:-4] + "_flattened.mrc" ), overwrite=True, ) as out_image: # Make fstring out_image.set_data(final_image) def equalize_im(img, x_patches, y_patches, num_of_segments): filter_mask = fd.lowpass(img, 0.85, 20, "cos", 50) lowpass, mag = fd.filtering(img, filter_mask) lowpass = cv2.GaussianBlur(lowpass, (45, 45), 0) rolled = wm.window(lowpass, x_patches, y_patches) rolled_resized = cv2.resize(rolled, (185, 190), interpolation=cv2.INTER_NEAREST) rolled_resized = cv2.GaussianBlur(rolled_resized, (5, 5), 0) KNNsegmented = KNN_seg.segmenter(rolled_resized, num_of_segments) # upscaled_region = cv2.resize( # KNNsegmented, (lowpass.shape[1], lowpass.shape[0]), interpolation=cv2.INTER_AREA) regions_vals = np.unique(KNNsegmented) averaged_loc = np.zeros( (lowpass.shape[0], lowpass.shape[1], num_of_segments), np.uint8 ) res = np.zeros((lowpass.shape[0], lowpass.shape[1]), np.uint8) for i in range(len(regions_vals)): averaged_loc[:, :, i] = lm.local_mask(lowpass, KNNsegmented, regions_vals[i]) res[:, :] += averaged_loc[:, :, i] final_image = res # cv2.GaussianBlur(res, (45, 45), 0) return final_image def main(indir, cpus): outdir = "flattened" path1 = os.path.join(indir, outdir) try: os.mkdir(path1) except OSError: print(f"Creation of the directory {path1} failed") else: print(f"Successfully created the directory {path1}") filelist = [] for filename in os.listdir(indir): if filename.endswith(".mrc"): finalpath = os.path.join(indir, filename) filelist.append(finalpath) else: continue # cc = 0 # for filename in filelist: # img = load_img(os.path.join(indir, filename)) # Config params # x_patches = 40 # y_patches = 40 # num_of_segments = 32 # final_image = equalize_im(img, x_patches, y_patches, num_of_segments) # final_image = img # !!!! TESTING # with mrcfile.new((path1+str(filename[:-4]) +'_'+str(x_patches)+'x'+str(y_patches)+ # 'x'+str(num_of_segments)+'flattened'+'.mrc'), overwrite=True) as out_image: # Make fstring # with mrcfile.new(os.path.join(path1, filename[:-4] + f'_{outdir}.mrc'), # overwrite=True) as out_image: # Make fstring # out_image.set_data(final_image) # cc += 1 # print(f'{cc}/{len(filelist)}') with Pool(cpus) as p: p.map(multigroup, filelist) return True if __name__ == "__main__": indir = sys.argv[1] batch_size = sys.argv[2] main(indir, batch_size)
[ "cv2.resize", "cv2.GaussianBlur", "os.mkdir", "icebreaker.local_mask.local_mask", "numpy.unique", "numpy.zeros", "mrcfile.open", "icebreaker.window_mean.window", "icebreaker.KNN_segmenter.segmenter", "multiprocessing.Pool", "icebreaker.filter_designer.filtering", "os.path.split", "os.path.jo...
[((649, 677), 'os.path.split', 'os.path.split', (['filelist_full'], {}), '(filelist_full)\n', (662, 677), False, 'import os\n'), ((1389, 1425), 'icebreaker.filter_designer.lowpass', 'fd.lowpass', (['img', '(0.85)', '(20)', '"""cos"""', '(50)'], {}), "(img, 0.85, 20, 'cos', 50)\n", (1399, 1425), True, 'from icebreaker import filter_designer as fd\n'), ((1445, 1475), 'icebreaker.filter_designer.filtering', 'fd.filtering', (['img', 'filter_mask'], {}), '(img, filter_mask)\n', (1457, 1475), True, 'from icebreaker import filter_designer as fd\n'), ((1490, 1528), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['lowpass', '(45, 45)', '(0)'], {}), '(lowpass, (45, 45), 0)\n', (1506, 1528), False, 'import cv2\n'), ((1542, 1582), 'icebreaker.window_mean.window', 'wm.window', (['lowpass', 'x_patches', 'y_patches'], {}), '(lowpass, x_patches, y_patches)\n', (1551, 1582), True, 'from icebreaker import window_mean as wm\n'), ((1604, 1667), 'cv2.resize', 'cv2.resize', (['rolled', '(185, 190)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(rolled, (185, 190), interpolation=cv2.INTER_NEAREST)\n', (1614, 1667), False, 'import cv2\n'), ((1689, 1732), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['rolled_resized', '(5, 5)', '(0)'], {}), '(rolled_resized, (5, 5), 0)\n', (1705, 1732), False, 'import cv2\n'), ((1752, 1802), 'icebreaker.KNN_segmenter.segmenter', 'KNN_seg.segmenter', (['rolled_resized', 'num_of_segments'], {}), '(rolled_resized, num_of_segments)\n', (1769, 1802), True, 'from icebreaker import KNN_segmenter as KNN_seg\n'), ((1948, 1971), 'numpy.unique', 'np.unique', (['KNNsegmented'], {}), '(KNNsegmented)\n', (1957, 1971), True, 'import numpy as np\n'), ((1991, 2064), 'numpy.zeros', 'np.zeros', (['(lowpass.shape[0], lowpass.shape[1], num_of_segments)', 'np.uint8'], {}), '((lowpass.shape[0], lowpass.shape[1], num_of_segments), np.uint8)\n', (1999, 2064), True, 'import numpy as np\n'), ((2089, 2145), 'numpy.zeros', 'np.zeros', (['(lowpass.shape[0], lowpass.shape[1])', 'np.uint8'], {}), '((lowpass.shape[0], lowpass.shape[1]), np.uint8)\n', (2097, 2145), True, 'import numpy as np\n'), ((2464, 2491), 'os.path.join', 'os.path.join', (['indir', 'outdir'], {}), '(indir, outdir)\n', (2476, 2491), False, 'import os\n'), ((2715, 2732), 'os.listdir', 'os.listdir', (['indir'], {}), '(indir)\n', (2725, 2732), False, 'import os\n'), ((403, 447), 'mrcfile.open', 'mrcfile.open', (['img_path', '"""r"""'], {'permissive': '(True)'}), "(img_path, 'r', permissive=True)\n", (415, 447), False, 'import mrcfile\n'), ((2217, 2270), 'icebreaker.local_mask.local_mask', 'lm.local_mask', (['lowpass', 'KNNsegmented', 'regions_vals[i]'], {}), '(lowpass, KNNsegmented, regions_vals[i])\n', (2230, 2270), True, 'from icebreaker import local_mask as lm\n'), ((2510, 2525), 'os.mkdir', 'os.mkdir', (['path1'], {}), '(path1)\n', (2518, 2525), False, 'import os\n'), ((3650, 3660), 'multiprocessing.Pool', 'Pool', (['cpus'], {}), '(cpus)\n', (3654, 3660), False, 'from multiprocessing import Pool\n'), ((1102, 1187), 'os.path.join', 'os.path.join', (["(splitpath[0] + '/flattened/' + splitpath[1][:-4] + '_flattened.mrc')"], {}), "(splitpath[0] + '/flattened/' + splitpath[1][:-4] +\n '_flattened.mrc')\n", (1114, 1187), False, 'import os\n'), ((2796, 2825), 'os.path.join', 'os.path.join', (['indir', 'filename'], {}), '(indir, filename)\n', (2808, 2825), False, 'import os\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 18 21:08:18 2021 @author: rick """ import os from glob import glob import numpy as np import subprocess, collections from obspy.geodetics import gps2dist_azimuth ev_info = collections.namedtuple('ev_info','st stack_p lon lat dep') BP_path = './out_data/BP_out' time_dif = 2 # time threshold dist_dif = 20 # dist threshold stack_req = '2.0' # stacking threshold # start time yr = 2019 jdy_s = 188 jdy_e = 188 #===== get folder list hr_list_glob = glob(os.path.join(BP_path, '????.???.??')) hr_list = np.sort([os.path.basename(h) for h in hr_list_glob]) print('there are ', len(hr_list), ' folders!') for hr_dir in hr_list: print('working on : ', hr_dir) #===== go to the folder os.chdir(os.path.join(os.path.abspath(BP_path), hr_dir)) subprocess.call('cat 00*_BP.out > ' + hr_dir + '_BPev.list', shell=True) subprocess.call('cat 01*_BP.out >> ' + hr_dir + '_BPev.list', shell=True) subprocess.call('cat 02*_BP.out >> ' + hr_dir + '_BPev.list', shell=True) #==== select qualified stacking subprocess.call("awk '$2>" + stack_req + "{print $0}' " + hr_dir +\ '_BPev.list > ' + hr_dir + '_BPev.list2', shell=True) #===== check file emepty or not if (os.stat(hr_dir + '_BPev.list2').st_size == 0): print(hr_dir + '_BPev.list2 is empty') continue #==== sort by time subprocess.call('sort -n -o ' + hr_dir + '_BPev.list_sel '+hr_dir + '_BPev.list2', shell=True) #===== read all events print(hr_dir, ' read all events!') ev_file = open(hr_dir + '_BPev.list_sel', 'r') all_ev = [] for i1, ev_tmp in enumerate(ev_file): ev_tmp2 = ev_tmp.strip().split() ev_st = float(ev_tmp2[0]) ev_stack_p = float(ev_tmp2[1]) ev_lon = float(ev_tmp2[2]) ev_lat = float(ev_tmp2[3]) ev_dep = float(ev_tmp2[4]) all_ev.append(ev_info(ev_st,ev_stack_p,ev_lon,ev_lat,ev_dep)) ev_file.close() print(hr_dir, i1+1, ' events!') #====== check events out_catalog = '../' + hr_dir + '_BP_T' + str(time_dif) + 's_D' +\ str(dist_dif)+'km.catalog' ev_out = open(out_catalog, 'w') rej_idx = [] for i1, ev_tmp in enumerate(all_ev): ev_in = 1 # for event select or not if i1 in rej_idx: #print('skip ', i1) continue for i2 in range(i1+1, len(all_ev)): ev_dist, az, baz = gps2dist_azimuth(ev_tmp.lat, ev_tmp.lon, \ all_ev[i2].lat, all_ev[i2].lon) ev_dist = np.sqrt((ev_dist / 1000)**2 + (all_ev[i2].dep-ev_tmp.dep)**2) # convert to km tt_dif = all_ev[i2].st - ev_tmp.st #==== reject the event if ((tt_dif <= time_dif) & (ev_dist <= dist_dif)): if (ev_tmp.stack_p < all_ev[i2].stack_p): #=== reject master event #print('reject1:',i1, i2, ev_tmp.st, all_ev[i2].st, ev_tmp.stack_p, \ # all_ev[i2].stack_p, ev_dist) ev_in = 0 break else: #==== reject checked event rej_idx.append(i2) #print('rej checked: ',i2) #===== time diff too large break if tt_dif > time_dif: #print('time diff too large ', tt_dif) break #======= write or not if ev_in == 1: ev_out.write('{0.st:7.2f} {0.stack_p:7.4f} {0.lon:9.4f} {0.lat:8.4f} {0.dep:6.2f}\n'\ .format(ev_tmp)) ev_out.close()
[ "os.path.abspath", "os.stat", "os.path.basename", "obspy.geodetics.gps2dist_azimuth", "subprocess.call", "collections.namedtuple", "os.path.join", "numpy.sqrt" ]
[((244, 303), 'collections.namedtuple', 'collections.namedtuple', (['"""ev_info"""', '"""st stack_p lon lat dep"""'], {}), "('ev_info', 'st stack_p lon lat dep')\n", (266, 303), False, 'import subprocess, collections\n'), ((540, 576), 'os.path.join', 'os.path.join', (['BP_path', '"""????.???.??"""'], {}), "(BP_path, '????.???.??')\n", (552, 576), False, 'import os\n'), ((843, 915), 'subprocess.call', 'subprocess.call', (["('cat 00*_BP.out > ' + hr_dir + '_BPev.list')"], {'shell': '(True)'}), "('cat 00*_BP.out > ' + hr_dir + '_BPev.list', shell=True)\n", (858, 915), False, 'import subprocess, collections\n'), ((920, 993), 'subprocess.call', 'subprocess.call', (["('cat 01*_BP.out >> ' + hr_dir + '_BPev.list')"], {'shell': '(True)'}), "('cat 01*_BP.out >> ' + hr_dir + '_BPev.list', shell=True)\n", (935, 993), False, 'import subprocess, collections\n'), ((998, 1071), 'subprocess.call', 'subprocess.call', (["('cat 02*_BP.out >> ' + hr_dir + '_BPev.list')"], {'shell': '(True)'}), "('cat 02*_BP.out >> ' + hr_dir + '_BPev.list', shell=True)\n", (1013, 1071), False, 'import subprocess, collections\n'), ((1112, 1236), 'subprocess.call', 'subprocess.call', (['("awk \'$2>" + stack_req + "{print $0}\' " + hr_dir + \'_BPev.list > \' +\n hr_dir + \'_BPev.list2\')'], {'shell': '(True)'}), '("awk \'$2>" + stack_req + "{print $0}\' " + hr_dir +\n \'_BPev.list > \' + hr_dir + \'_BPev.list2\', shell=True)\n', (1127, 1236), False, 'import subprocess, collections\n'), ((1442, 1542), 'subprocess.call', 'subprocess.call', (["('sort -n -o ' + hr_dir + '_BPev.list_sel ' + hr_dir + '_BPev.list2')"], {'shell': '(True)'}), "('sort -n -o ' + hr_dir + '_BPev.list_sel ' + hr_dir +\n '_BPev.list2', shell=True)\n", (1457, 1542), False, 'import subprocess, collections\n'), ((597, 616), 'os.path.basename', 'os.path.basename', (['h'], {}), '(h)\n', (613, 616), False, 'import os\n'), ((804, 828), 'os.path.abspath', 'os.path.abspath', (['BP_path'], {}), '(BP_path)\n', (819, 828), False, 'import os\n'), ((1295, 1326), 'os.stat', 'os.stat', (["(hr_dir + '_BPev.list2')"], {}), "(hr_dir + '_BPev.list2')\n", (1302, 1326), False, 'import os\n'), ((2495, 2567), 'obspy.geodetics.gps2dist_azimuth', 'gps2dist_azimuth', (['ev_tmp.lat', 'ev_tmp.lon', 'all_ev[i2].lat', 'all_ev[i2].lon'], {}), '(ev_tmp.lat, ev_tmp.lon, all_ev[i2].lat, all_ev[i2].lon)\n', (2511, 2567), False, 'from obspy.geodetics import gps2dist_azimuth\n'), ((2608, 2675), 'numpy.sqrt', 'np.sqrt', (['((ev_dist / 1000) ** 2 + (all_ev[i2].dep - ev_tmp.dep) ** 2)'], {}), '((ev_dist / 1000) ** 2 + (all_ev[i2].dep - ev_tmp.dep) ** 2)\n', (2615, 2675), True, 'import numpy as np\n')]
""" Additional transformations """ import warnings import numpy as np from dimarray.core import Axes, Axis # # INTERPOLATION # def interp1d_numpy(obj, values, axis=0, **kwargs): """ interpolate along one axis: wrapper around numpy's interp Parameters ---------- obj : DimArray values : 1d array, or Axis object axis, optional : `str` (axis name), required if newaxis is an array Returns ------- interpolated data (n-d) """ warnings.warn(FutureWarning("Deprecated. Use DimArray.interp_axis")) return obj.interp_axis(values, axis=axis, **kwargs) interp1d = interp1d_numpy def interp2d(dim_array, newaxes, dims=(-2, -1), **kwargs): """ Two-dimensional interpolation Parameters ---------- dim_array : DimArray instance newaxes : sequence of two array-like, or dict. axes on which to interpolate dims : sequence of two axis names or integer rank, optional Indicate dimensions which match `newaxes`. By default (-2, -1) (last two dimensions). **kwargs : passed to scipy.interpolate.RegularGridInterpolator method : 'nearest' or 'linear' (default) bounds_error : True by default fill_value : np.nan by default, but set to None to extrapolate outside bounds. Returns ------- dim_array_int : DimArray instance interpolated array Examples -------- >>> from dimarray import DimArray, interp2d >>> x = np.array([0, 1, 2]) >>> y = np.array([0, 10]) >>> a = DimArray([[0,0,1],[1,0.,0.]], [('y',y),('x',x)]) >>> a dimarray: 6 non-null elements (0 null) 0 / y (2): 0 to 10 1 / x (3): 0 to 2 array([[0., 0., 1.], [1., 0., 0.]]) >>> newx = [0.5, 1.5] >>> newy = np.linspace(0,10,5) >>> ai = interp2d(a, [newy, newx]) >>> ai dimarray: 10 non-null elements (0 null) 0 / y (5): 0.0 to 10.0 1 / x (2): 0.5 to 1.5 array([[0. , 0.5 ], [0.125, 0.375], [0.25 , 0.25 ], [0.375, 0.125], [0.5 , 0. ]]) Use dims keyword argument if new axes order does not match array dimensions >>> (ai == interp2d(a, [newx, newy], dims=('x','y'))).all() True Out-of-bounds filled with NaN: >>> newx = [-1, 1] >>> newy = [-5, 0, 10] >>> interp2d(a, [newy, newx], bounds_error=False) dimarray: 2 non-null elements (4 null) 0 / y (3): -5 to 10 1 / x (2): -1 to 1 array([[nan, nan], [nan, 0.], [nan, 0.]]) Nearest neighbor interpolation and out-of-bounds extrapolation >>> interp2d(a, [newy, newx], method='nearest', bounds_error=False, fill_value=None) dimarray: 6 non-null elements (0 null) 0 / y (3): -5 to 10 1 / x (2): -1 to 1 array([[0., 0.], [0., 0.], [1., 0.]]) """ from scipy.interpolate import RegularGridInterpolator # back compatibility _order = kwargs.pop('order', None) if _order is not None: warnings.warn('order is deprecated, use method instead', DeprecationWarning) if _order == 3: warnings.warn('cubic not supported. Switch to linear.', DeprecationWarning) kwargs['method'] = {0:'nearest', 1:'linear', 3:'linear'}[_order] _clip = kwargs.pop('clip', None) if _clip is not None: warnings.warn('clip is deprecated, set bounds_error=False and fill_value=None \ for similar results (see scipy.interpolate.RegularGridInterpolator)', DeprecationWarning) if _clip is True: kwargs['bounds_error'] = False kwargs['fill_value'] = None # provided as a dictionary if isinstance(newaxes, dict): dims = newaxes.keys() newaxes = newaxes.values() if not isinstance(newaxes, list) or isinstance(newaxes, tuple): raise TypeError("newaxes must be a sequence of axes to interpolate on") if len(newaxes) != 2: raise ValueError("must provide two axis values to interpolate on") if len(dims) != 2: raise ValueError("must provide two axis names to interpolate on") x0 = dim_array.axes[dims[0]] y0 = dim_array.axes[dims[1]] # new axes xi, yi = newaxes xi = Axis(xi, x0.name) # convert to Axis yi = Axis(yi, y0.name) ## transpose the array to shape .., x0, y0 dims_orig = dim_array.dims dims_new = [d for d in dim_array.dims if d not in [x0.name, y0.name]] + [x0.name, y0.name] dim_array = dim_array.transpose(dims_new) _xi2, _yi2 = np.meshgrid(xi.values, yi.values, indexing='ij') # requires 2-D grid _new_points = np.array([_xi2.flatten(), _yi2.flatten()]).T def _interp_map(x, y, z): f = RegularGridInterpolator((x, y), z, **kwargs) return f(_new_points).reshape(_xi2.shape) if dim_array.ndim == 2: newvalues = _interp_map(x0.values, y0.values, dim_array.values) dim_array_int = dim_array._constructor(newvalues, [xi, yi]) else: # first reshape to 3-D, flattening everything except horizontal_coordinates coordinates dim_array = dim_array.flatten((x0.name, y0.name), reverse=True, insert=0) newvalues = [] for k, suba in dim_array.iter(axis=0): # iterate over the first dimension newval = _interp_map(x0.values, y0.values, suba.values) newvalues.append(newval) # stack the arrays together newvalues = np.array(newvalues) flattened_dim_array = dim_array._constructor(newvalues, [dim_array.axes[0], xi, yi]) dim_array_int = flattened_dim_array.unflatten(axis=0) # reshape back # ...replace old axis names by new ones of the projection dims_orig = list(dims_orig) # ...transpose dim_array_int = dim_array_int.transpose(dims_orig) # add metadata dim_array_int.attrs.update(dim_array.attrs) return dim_array_int
[ "numpy.meshgrid", "numpy.array", "scipy.interpolate.RegularGridInterpolator", "warnings.warn", "dimarray.core.Axis" ]
[((4227, 4244), 'dimarray.core.Axis', 'Axis', (['xi', 'x0.name'], {}), '(xi, x0.name)\n', (4231, 4244), False, 'from dimarray.core import Axes, Axis\n'), ((4272, 4289), 'dimarray.core.Axis', 'Axis', (['yi', 'y0.name'], {}), '(yi, y0.name)\n', (4276, 4289), False, 'from dimarray.core import Axes, Axis\n'), ((4530, 4578), 'numpy.meshgrid', 'np.meshgrid', (['xi.values', 'yi.values'], {'indexing': '"""ij"""'}), "(xi.values, yi.values, indexing='ij')\n", (4541, 4578), True, 'import numpy as np\n'), ((2997, 3073), 'warnings.warn', 'warnings.warn', (['"""order is deprecated, use method instead"""', 'DeprecationWarning'], {}), "('order is deprecated, use method instead', DeprecationWarning)\n", (3010, 3073), False, 'import warnings\n'), ((3332, 3531), 'warnings.warn', 'warnings.warn', (['"""clip is deprecated, set bounds_error=False and fill_value=None for similar results (see scipy.interpolate.RegularGridInterpolator)"""', 'DeprecationWarning'], {}), "(\n 'clip is deprecated, set bounds_error=False and fill_value=None for similar results (see scipy.interpolate.RegularGridInterpolator)'\n , DeprecationWarning)\n", (3345, 3531), False, 'import warnings\n'), ((4704, 4748), 'scipy.interpolate.RegularGridInterpolator', 'RegularGridInterpolator', (['(x, y)', 'z'], {}), '((x, y), z, **kwargs)\n', (4727, 4748), False, 'from scipy.interpolate import RegularGridInterpolator\n'), ((5426, 5445), 'numpy.array', 'np.array', (['newvalues'], {}), '(newvalues)\n', (5434, 5445), True, 'import numpy as np\n'), ((3111, 3186), 'warnings.warn', 'warnings.warn', (['"""cubic not supported. Switch to linear."""', 'DeprecationWarning'], {}), "('cubic not supported. Switch to linear.', DeprecationWarning)\n", (3124, 3186), False, 'import warnings\n')]
import numpy as np import os import time from estimator import * import matplotlib matplotlib.use('TKAgg') matplotlib.rcParams['text.usetex'] = True matplotlib.rcParams['font.family'] = 'serif' matplotlib.rcParams['font.serif'] = 'Computer Modern' import matplotlib.pyplot as plt LAMBDAS = [0, 1/512, 1/256, 1/128, 1/64, 1/32, 1/16, 1/8, 1/4, 1/2, 1,\ 2, 4, 8, 16, 32, np.inf] NUM_SAMPLES = 100 # number of sampled total orderings to approximate interpolation fontsize=25 legendsize=20 ticksize=17.5 linewidth=2.5 markersize=10 markeredgewidth=4 axissize=17.5 PLOT_DIR = 'plots' MARKERS = { 'mean': 'x', 'median': 'o', 'subsample': 's', 'cv': '<', 'oracle': 'd', } LINESTYLES = { 'mean': 'dotted', 'median': 'dashed', 'subsample': 'dashdot', 'cv': 'solid', 'oracle': (0, (1, 5)), } COLORS = { 'mean': '#ff7f0e', # orange 'median': '#d62728', # red 'subsample': '#9467bd', # purple 'cv': '#1f77b4', # blue 'oracle': '#7f7f7f', # gray } text_l2_err = r'squared $\ell_2$ error' LAMBDAS_TEXT = [str(lda) for lda in LAMBDAS] LAMBDAS_TEXT[1:9] = ['\\frac{1}{512}', '\\frac{1}{256}', '1/128', '\\frac{1}{64}', '1/32', '\\frac{1}{16}', '1/8', '\\frac{1}{4}'] LAMBDAS_TEXT[-1] = '\infty' # Run simulation varying the paramter N # MODE_ORDER: noninterleaving | interleaving | binary # MODE_BIAS_NOISE: bias | noise | noisy def simulate_vary_n(mode_order='noninterleaving', mode_bias_noise='bias', lambdas=LAMBDAS, num_samples=NUM_SAMPLES): (delta, epsilon) = map_mode_bias_noise(mode_bias_noise) if mode_order in ['noninterleaving', 'interleaving']: d = 3 ns = [2, 5, 10, 25, 50, 100] elif mode_order =='binary' : # binary (10%/90%) d = 4 ns = [10, 20, 30, 40, 50, 70, 100] else: raise Exception('Unknown mode order') print('simulate_vary_n [d=%d | order %s | bias-noise %s]... ' % (d, mode_order, mode_bias_noise)) repeat = 250 ns = np.array(ns, dtype=int) N = len(ns) L = len(lambdas) ests_cv_sample = np.zeros((d, N, repeat)) ests_mean = np.zeros((d, N, repeat)) ests_median = np.zeros((d, N, repeat)) ests_subsample_weighted = np.zeros((d, N, repeat)) ests_solution = np.zeros((d, N, L, repeat)) # \lambda count counts_il = np.zeros((N, L)) tic = time.time() for i in range(N): n = ns[i] if mode_order == 'noninterleaving': ordering = np.reshape(np.arange(d*n), (d, n)) elif mode_order == 'interleaving': ordering = np.reshape(np.arange(d*n), (d, n), order='F') elif mode_order =='binary': n_percent = 0.1 m = int(n_percent * n) assert(d % 2 == 0) d_half = int(d/2) ordering = np.zeros((d, n), dtype=int) ordering[:d_half, (n-m):] = 1 ordering[d_half:, m:] = 1 print('ordering:') print(ordering) print('[n: %d/%d] %d iters...' % (i+1, N, repeat)) for r in range(repeat): if r % 10 == 0: print('%d/%d (%s | %d sec)' % (r+1, repeat, time.strftime("%H:%M", time.localtime()), time.time() - tic)) # normal noise = np.random.normal(size=(d, n)) * epsilon bias = generate_bias_marginal_gaussian(d, n, ordering) * delta y = noise + bias (il_sample, xs_sample) = \ perform_cv(y, lambdas, ordering, num_samples=num_samples) # compute solutions for all LAMBDAS # XS: d x L # BS: d x n x L (xs, bs) = solve_opt(y, lambdas, ordering=ordering) ests_cv_sample[:, i, r] = xs[:, il_sample] ests_mean[:, i, r] = np.mean(y, axis=1) ests_median[:, i, r] = np.median(y, axis=1) ests_subsample_weighted[:, i, r] = solve_subsampling_weighted_recenter(y, ordering) ests_solution[:, i, :, r] = xs # d x n x L x repeat counts_il[i, il_sample] += 1 # FIG 1: L2 err vs. n errs_cv_sample_l2 = l2(ests_cv_sample) errs_mean_l2 = l2(ests_mean) errs_median_l2 = l2(ests_median) errs_subsample_weighted_l2 = l2(ests_subsample_weighted) errs_bestfixed_l2 = keep_best_fixed(ests_solution) fig = plt.figure() ax = plt.subplot(111) ax.tick_params(axis='x', labelsize=ticksize) ax.tick_params(axis='y', labelsize=ticksize) ax.tick_params(axis='x', which='minor', bottom=False) ax.errorbar(ns, np.mean(errs_mean_l2, axis=1), np.std(errs_mean_l2, axis=1) / np.sqrt(repeat), label='mean', color=COLORS['mean'], marker=MARKERS['mean'], linestyle=LINESTYLES['mean'], markersize=markersize, markeredgewidth=markeredgewidth, linewidth=linewidth) ax.errorbar(ns, np.mean(errs_median_l2, axis=1), np.std(errs_median_l2, axis=1) / np.sqrt(repeat), label='median', color=COLORS['median'], marker=MARKERS['median'], linestyle=LINESTYLES['median'], markersize=markersize, markeredgewidth=markeredgewidth, linewidth=linewidth) if mode_order == 'binary': # no subsample for total order ax.errorbar(ns, np.mean(errs_subsample_weighted_l2, axis=1), yerr=np.std(errs_subsample_weighted_l2, axis=1) / np.sqrt(repeat), label='weighted mean', color=COLORS['subsample'], marker=MARKERS['subsample'], linestyle=LINESTYLES['subsample'], markersize=markersize, markeredgewidth=markeredgewidth, linewidth=linewidth) ax.errorbar(ns, np.mean(errs_cv_sample_l2, axis=1), yerr=np.std(errs_cv_sample_l2, axis=1) / np.sqrt(repeat), label='CV', color=COLORS['cv'], marker=MARKERS['cv'], linestyle=LINESTYLES['cv'], markersize=markersize, markeredgewidth=markeredgewidth, linewidth=linewidth) ax.errorbar(ns, np.mean(errs_bestfixed_l2, axis=1), yerr=np.std(errs_bestfixed_l2, axis=1)/ np.sqrt(repeat), label='best fixed ' + r'$\lambda$', color=COLORS['oracle'], marker=MARKERS['oracle'], linestyle=LINESTYLES['oracle'], markersize=markersize, markeredgewidth=markeredgewidth, linewidth=linewidth) plt.xlabel(r'$n$', fontsize=axissize) if mode_bias_noise == 'bias': plt.ylabel(text_l2_err, fontsize=axissize) plt.xscale('log') plt.yscale('log') if mode_order == 'binary': ax.set_xticks([10, 20, 30, 40, 50, 70, 100]) ax.set_xticklabels([r'$10$', r'$20$', r'$30$', r'$40$', r'$50$', r'$70$', r'$100$']) else: ax.set_xticks([2, 5, 10, 25, 50,100]) ax.set_xticklabels([r'$2$', r'$5$', r'$10$', r'$25$', r'$50$', r'$100$']) ax.tick_params(axis='x', labelsize=ticksize) ax.tick_params(axis='y', labelsize=ticksize) plt.savefig('%s/vary_n_%s_%s_d%d.pdf' % (PLOT_DIR, mode_order, mode_bias_noise, d), bbox_inches='tight') # count \lambda if mode_order == 'binary': # only plot d == 50 i = np.where(ns == 50)[0][0] fig = plt.figure() ax = plt.subplot(111) xs = np.arange(L) width = 0.7 probs = counts_il[i, :] / repeat ax.bar(xs , probs, width, label='CV', color=COLORS['cv']) plt.xlabel(r'$\lambda$', fontsize=axissize) if mode_bias_noise == 'bias': plt.ylabel('Fraction of times', fontsize=axissize) ax.set_xticks(xs) text_lda = [r'$%s$' % lda for lda in LAMBDAS_TEXT] for il in np.arange(1, L, 2): text_lda[il] = '' ax.set_xticklabels(text_lda) ax.tick_params(axis='x', labelsize=ticksize) ax.tick_params(axis='y', labelsize=ticksize) plt.savefig('%s/vary_n_lambda_%s_%s_d%d.pdf' % (PLOT_DIR, mode_order, mode_bias_noise, d), bbox_inches='tight') # MODE: bias | mixed | noise def map_mode_bias_noise(mode): if mode == 'bias': return (1, 0) elif mode == 'mixed': return (0.5, 0.5) elif mode == 'noise': return (0, 1) # Generate marginal-Gaussian bias obeying ORDERING # ORDERING: d-by-n def generate_bias_marginal_gaussian(d, n, ordering=None): idxs = sample_total_from_partial(d, n, ordering=ordering) # increasing order bias = np.zeros(d*n) bias[idxs] = np.sort(np.random.normal(size=d*n)) bias = np.reshape(bias, (d, n)) return bias # X: d * T1 * T2 * ... # # X_TRUE: length-D vector # Compute L2 along axis 0 # # Returns: # # ERR: T1 * T2 * ... def l2(x, x_true=None): if x_true is None: x_true = np.zeros(x.shape[0]) else: assert(x_true.ndim == 1) assert(x.shape[0] == len(x_true)) n = x.ndim for _ in range(n-1): x_true = np.expand_dims(x_true, axis=1) err = np.square(x - x_true) err = np.mean(err, axis=0) return err # Y: d-by-n # ORDERING can be group grades (with an inherent ordering, or simply types (without an ordering on the types) # deterministic (no randomness) def solve_subsampling_weighted(Y, ordering, mask_data=None): (d, n) = Y.shape if mask_data is None: mask_data = np.full((d, n), True) assert(is_valid_ordering(ordering)) T = int(np.max(ordering)) + 1 # number of types (index from 0) assert(np.min(ordering) == 0) counts = np.zeros((d, T), dtype=int) for t in range(T): counts[:, t] = np.sum((ordering == t) * mask_data, axis=1) counts = np.min(counts, axis=0) # len-T array C = np.sum(counts) if C == 0: return np.full(d, np.nan) ests = np.zeros(d) for i in range(d): for t in range(T): if counts[t] == 0: continue idxs = np.where(np.logical_and(ordering[i, :] == t, mask_data[i, :]) )[0] assert(len(idxs) >= counts[t]) ests[i] += np.mean(Y[i, idxs]) * counts[t] / C return ests def solve_subsampling_weighted_recenter(Y, ordering, mask_data=None): if mask_data is None: (d, n) = Y.shape mask_data = np.full((d, n), True) xs = solve_subsampling_weighted(Y, ordering, mask_data=mask_data) counts = np.sum(mask_data, axis=1) shift = np.sum(Y * mask_data) / np.sum(mask_data) - np.sum(counts * xs) / np.sum(counts) xs = xs + shift return xs # Y: d x T x L x repeat or d x L x repeat (T: #settings) # Returns: # ERRS_BEST_FIXED: T x repeat matrix or repeat-array def keep_best_fixed(y): if len(y.shape) == 4: T = y.shape[1] repeat = y.shape[-1] errs_best_fixed = np.zeros((T, repeat)) for t in range(T): errs_best_fixed[t, :] = keep_best_fixed(y[:, t, :, :]) return errs_best_fixed elif len(y.shape) == 3: err = l2(y) # L x repeat err_mean = np.mean(err, axis=1) # length-L il = np.argmin(err_mean) return err[il, :] # length-repeat ###### if __name__ == '__main__': np.random.seed(0) if not os.path.exists(PLOT_DIR): os.makedirs(PLOT_DIR) for mode_order in ['noninterleaving', 'interleaving', 'binary']: for mode_bias_noise in ['bias', 'mixed', 'noise']: simulate_vary_n(mode_order=mode_order, mode_bias_noise=mode_bias_noise)
[ "matplotlib.pyplot.yscale", "numpy.sum", "numpy.random.seed", "numpy.argmin", "matplotlib.pyplot.figure", "numpy.mean", "numpy.arange", "numpy.random.normal", "numpy.full", "numpy.std", "os.path.exists", "numpy.max", "numpy.reshape", "time.localtime", "numpy.median", "numpy.square", ...
[((85, 108), 'matplotlib.use', 'matplotlib.use', (['"""TKAgg"""'], {}), "('TKAgg')\n", (99, 108), False, 'import matplotlib\n'), ((1868, 1891), 'numpy.array', 'np.array', (['ns'], {'dtype': 'int'}), '(ns, dtype=int)\n', (1876, 1891), True, 'import numpy as np\n'), ((1942, 1966), 'numpy.zeros', 'np.zeros', (['(d, N, repeat)'], {}), '((d, N, repeat))\n', (1950, 1966), True, 'import numpy as np\n'), ((1980, 2004), 'numpy.zeros', 'np.zeros', (['(d, N, repeat)'], {}), '((d, N, repeat))\n', (1988, 2004), True, 'import numpy as np\n'), ((2020, 2044), 'numpy.zeros', 'np.zeros', (['(d, N, repeat)'], {}), '((d, N, repeat))\n', (2028, 2044), True, 'import numpy as np\n'), ((2072, 2096), 'numpy.zeros', 'np.zeros', (['(d, N, repeat)'], {}), '((d, N, repeat))\n', (2080, 2096), True, 'import numpy as np\n'), ((2114, 2141), 'numpy.zeros', 'np.zeros', (['(d, N, L, repeat)'], {}), '((d, N, L, repeat))\n', (2122, 2141), True, 'import numpy as np\n'), ((2173, 2189), 'numpy.zeros', 'np.zeros', (['(N, L)'], {}), '((N, L))\n', (2181, 2189), True, 'import numpy as np\n'), ((2198, 2209), 'time.time', 'time.time', ([], {}), '()\n', (2207, 2209), False, 'import time\n'), ((3834, 3846), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3844, 3846), True, 'import matplotlib.pyplot as plt\n'), ((3853, 3869), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (3864, 3869), True, 'import matplotlib.pyplot as plt\n'), ((5542, 5578), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$n$"""'], {'fontsize': 'axissize'}), "('$n$', fontsize=axissize)\n", (5552, 5578), True, 'import matplotlib.pyplot as plt\n'), ((5658, 5675), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (5668, 5675), True, 'import matplotlib.pyplot as plt\n'), ((5677, 5694), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (5687, 5694), True, 'import matplotlib.pyplot as plt\n'), ((6076, 6184), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('%s/vary_n_%s_%s_d%d.pdf' % (PLOT_DIR, mode_order, mode_bias_noise, d))"], {'bbox_inches': '"""tight"""'}), "('%s/vary_n_%s_%s_d%d.pdf' % (PLOT_DIR, mode_order,\n mode_bias_noise, d), bbox_inches='tight')\n", (6087, 6184), True, 'import matplotlib.pyplot as plt\n'), ((7360, 7375), 'numpy.zeros', 'np.zeros', (['(d * n)'], {}), '(d * n)\n', (7368, 7375), True, 'import numpy as np\n'), ((7432, 7456), 'numpy.reshape', 'np.reshape', (['bias', '(d, n)'], {}), '(bias, (d, n))\n', (7442, 7456), True, 'import numpy as np\n'), ((7816, 7837), 'numpy.square', 'np.square', (['(x - x_true)'], {}), '(x - x_true)\n', (7825, 7837), True, 'import numpy as np\n'), ((7845, 7865), 'numpy.mean', 'np.mean', (['err'], {'axis': '(0)'}), '(err, axis=0)\n', (7852, 7865), True, 'import numpy as np\n'), ((8318, 8345), 'numpy.zeros', 'np.zeros', (['(d, T)'], {'dtype': 'int'}), '((d, T), dtype=int)\n', (8326, 8345), True, 'import numpy as np\n'), ((8438, 8460), 'numpy.min', 'np.min', (['counts'], {'axis': '(0)'}), '(counts, axis=0)\n', (8444, 8460), True, 'import numpy as np\n'), ((8481, 8495), 'numpy.sum', 'np.sum', (['counts'], {}), '(counts)\n', (8487, 8495), True, 'import numpy as np\n'), ((8545, 8556), 'numpy.zeros', 'np.zeros', (['d'], {}), '(d)\n', (8553, 8556), True, 'import numpy as np\n'), ((9031, 9056), 'numpy.sum', 'np.sum', (['mask_data'], {'axis': '(1)'}), '(mask_data, axis=1)\n', (9037, 9056), True, 'import numpy as np\n'), ((9733, 9750), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (9747, 9750), True, 'import numpy as np\n'), ((4036, 4065), 'numpy.mean', 'np.mean', (['errs_mean_l2'], {'axis': '(1)'}), '(errs_mean_l2, axis=1)\n', (4043, 4065), True, 'import numpy as np\n'), ((4304, 4335), 'numpy.mean', 'np.mean', (['errs_median_l2'], {'axis': '(1)'}), '(errs_median_l2, axis=1)\n', (4311, 4335), True, 'import numpy as np\n'), ((4973, 5007), 'numpy.mean', 'np.mean', (['errs_cv_sample_l2'], {'axis': '(1)'}), '(errs_cv_sample_l2, axis=1)\n', (4980, 5007), True, 'import numpy as np\n'), ((5248, 5282), 'numpy.mean', 'np.mean', (['errs_bestfixed_l2'], {'axis': '(1)'}), '(errs_bestfixed_l2, axis=1)\n', (5255, 5282), True, 'import numpy as np\n'), ((5613, 5655), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['text_l2_err'], {'fontsize': 'axissize'}), '(text_l2_err, fontsize=axissize)\n', (5623, 5655), True, 'import matplotlib.pyplot as plt\n'), ((6292, 6304), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6302, 6304), True, 'import matplotlib.pyplot as plt\n'), ((6312, 6328), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (6323, 6328), True, 'import matplotlib.pyplot as plt\n'), ((6336, 6348), 'numpy.arange', 'np.arange', (['L'], {}), '(L)\n', (6345, 6348), True, 'import numpy as np\n'), ((6462, 6505), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\lambda$"""'], {'fontsize': 'axissize'}), "('$\\\\lambda$', fontsize=axissize)\n", (6472, 6505), True, 'import matplotlib.pyplot as plt\n'), ((6678, 6696), 'numpy.arange', 'np.arange', (['(1)', 'L', '(2)'], {}), '(1, L, 2)\n', (6687, 6696), True, 'import numpy as np\n'), ((6848, 6963), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('%s/vary_n_lambda_%s_%s_d%d.pdf' % (PLOT_DIR, mode_order, mode_bias_noise, d))"], {'bbox_inches': '"""tight"""'}), "('%s/vary_n_lambda_%s_%s_d%d.pdf' % (PLOT_DIR, mode_order,\n mode_bias_noise, d), bbox_inches='tight')\n", (6859, 6963), True, 'import matplotlib.pyplot as plt\n'), ((7396, 7424), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(d * n)'}), '(size=d * n)\n', (7412, 7424), True, 'import numpy as np\n'), ((7640, 7660), 'numpy.zeros', 'np.zeros', (['x.shape[0]'], {}), '(x.shape[0])\n', (7648, 7660), True, 'import numpy as np\n'), ((7777, 7807), 'numpy.expand_dims', 'np.expand_dims', (['x_true'], {'axis': '(1)'}), '(x_true, axis=1)\n', (7791, 7807), True, 'import numpy as np\n'), ((8151, 8172), 'numpy.full', 'np.full', (['(d, n)', '(True)'], {}), '((d, n), True)\n', (8158, 8172), True, 'import numpy as np\n'), ((8284, 8300), 'numpy.min', 'np.min', (['ordering'], {}), '(ordering)\n', (8290, 8300), True, 'import numpy as np\n'), ((8383, 8426), 'numpy.sum', 'np.sum', (['((ordering == t) * mask_data)'], {'axis': '(1)'}), '((ordering == t) * mask_data, axis=1)\n', (8389, 8426), True, 'import numpy as np\n'), ((8517, 8535), 'numpy.full', 'np.full', (['d', 'np.nan'], {}), '(d, np.nan)\n', (8524, 8535), True, 'import numpy as np\n'), ((8931, 8952), 'numpy.full', 'np.full', (['(d, n)', '(True)'], {}), '((d, n), True)\n', (8938, 8952), True, 'import numpy as np\n'), ((9410, 9431), 'numpy.zeros', 'np.zeros', (['(T, repeat)'], {}), '((T, repeat))\n', (9418, 9431), True, 'import numpy as np\n'), ((9760, 9784), 'os.path.exists', 'os.path.exists', (['PLOT_DIR'], {}), '(PLOT_DIR)\n', (9774, 9784), False, 'import os\n'), ((9788, 9809), 'os.makedirs', 'os.makedirs', (['PLOT_DIR'], {}), '(PLOT_DIR)\n', (9799, 9809), False, 'import os\n'), ((3345, 3363), 'numpy.mean', 'np.mean', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (3352, 3363), True, 'import numpy as np\n'), ((3390, 3410), 'numpy.median', 'np.median', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (3399, 3410), True, 'import numpy as np\n'), ((4067, 4095), 'numpy.std', 'np.std', (['errs_mean_l2'], {'axis': '(1)'}), '(errs_mean_l2, axis=1)\n', (4073, 4095), True, 'import numpy as np\n'), ((4098, 4113), 'numpy.sqrt', 'np.sqrt', (['repeat'], {}), '(repeat)\n', (4105, 4113), True, 'import numpy as np\n'), ((4337, 4367), 'numpy.std', 'np.std', (['errs_median_l2'], {'axis': '(1)'}), '(errs_median_l2, axis=1)\n', (4343, 4367), True, 'import numpy as np\n'), ((4370, 4385), 'numpy.sqrt', 'np.sqrt', (['repeat'], {}), '(repeat)\n', (4377, 4385), True, 'import numpy as np\n'), ((4645, 4688), 'numpy.mean', 'np.mean', (['errs_subsample_weighted_l2'], {'axis': '(1)'}), '(errs_subsample_weighted_l2, axis=1)\n', (4652, 4688), True, 'import numpy as np\n'), ((6541, 6591), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Fraction of times"""'], {'fontsize': 'axissize'}), "('Fraction of times', fontsize=axissize)\n", (6551, 6591), True, 'import matplotlib.pyplot as plt\n'), ((8221, 8237), 'numpy.max', 'np.max', (['ordering'], {}), '(ordering)\n', (8227, 8237), True, 'import numpy as np\n'), ((9066, 9087), 'numpy.sum', 'np.sum', (['(Y * mask_data)'], {}), '(Y * mask_data)\n', (9072, 9087), True, 'import numpy as np\n'), ((9090, 9107), 'numpy.sum', 'np.sum', (['mask_data'], {}), '(mask_data)\n', (9096, 9107), True, 'import numpy as np\n'), ((9110, 9129), 'numpy.sum', 'np.sum', (['(counts * xs)'], {}), '(counts * xs)\n', (9116, 9129), True, 'import numpy as np\n'), ((9133, 9147), 'numpy.sum', 'np.sum', (['counts'], {}), '(counts)\n', (9139, 9147), True, 'import numpy as np\n'), ((9602, 9622), 'numpy.mean', 'np.mean', (['err'], {'axis': '(1)'}), '(err, axis=1)\n', (9609, 9622), True, 'import numpy as np\n'), ((9641, 9660), 'numpy.argmin', 'np.argmin', (['err_mean'], {}), '(err_mean)\n', (9650, 9660), True, 'import numpy as np\n'), ((2306, 2322), 'numpy.arange', 'np.arange', (['(d * n)'], {}), '(d * n)\n', (2315, 2322), True, 'import numpy as np\n'), ((2923, 2952), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(d, n)'}), '(size=(d, n))\n', (2939, 2952), True, 'import numpy as np\n'), ((5014, 5047), 'numpy.std', 'np.std', (['errs_cv_sample_l2'], {'axis': '(1)'}), '(errs_cv_sample_l2, axis=1)\n', (5020, 5047), True, 'import numpy as np\n'), ((5050, 5065), 'numpy.sqrt', 'np.sqrt', (['repeat'], {}), '(repeat)\n', (5057, 5065), True, 'import numpy as np\n'), ((5289, 5322), 'numpy.std', 'np.std', (['errs_bestfixed_l2'], {'axis': '(1)'}), '(errs_bestfixed_l2, axis=1)\n', (5295, 5322), True, 'import numpy as np\n'), ((5324, 5339), 'numpy.sqrt', 'np.sqrt', (['repeat'], {}), '(repeat)\n', (5331, 5339), True, 'import numpy as np\n'), ((6259, 6277), 'numpy.where', 'np.where', (['(ns == 50)'], {}), '(ns == 50)\n', (6267, 6277), True, 'import numpy as np\n'), ((2392, 2408), 'numpy.arange', 'np.arange', (['(d * n)'], {}), '(d * n)\n', (2401, 2408), True, 'import numpy as np\n'), ((2560, 2587), 'numpy.zeros', 'np.zeros', (['(d, n)'], {'dtype': 'int'}), '((d, n), dtype=int)\n', (2568, 2587), True, 'import numpy as np\n'), ((4695, 4737), 'numpy.std', 'np.std', (['errs_subsample_weighted_l2'], {'axis': '(1)'}), '(errs_subsample_weighted_l2, axis=1)\n', (4701, 4737), True, 'import numpy as np\n'), ((4740, 4755), 'numpy.sqrt', 'np.sqrt', (['repeat'], {}), '(repeat)\n', (4747, 4755), True, 'import numpy as np\n'), ((8648, 8700), 'numpy.logical_and', 'np.logical_and', (['(ordering[i, :] == t)', 'mask_data[i, :]'], {}), '(ordering[i, :] == t, mask_data[i, :])\n', (8662, 8700), True, 'import numpy as np\n'), ((8754, 8773), 'numpy.mean', 'np.mean', (['Y[i, idxs]'], {}), '(Y[i, idxs])\n', (8761, 8773), True, 'import numpy as np\n'), ((2860, 2876), 'time.localtime', 'time.localtime', ([], {}), '()\n', (2874, 2876), False, 'import time\n'), ((2879, 2890), 'time.time', 'time.time', ([], {}), '()\n', (2888, 2890), False, 'import time\n')]
import os import numpy as np import torch import torch.nn as nn from torch import Tensor import librosa from torch.utils.data import Dataset ___author__ = "<NAME>" __email__ = "<EMAIL>" def genSpoof_list( dir_meta,is_train=False,is_eval=False): d_meta = {} file_list=[] with open(dir_meta, 'r') as f: l_meta = f.readlines() if (is_train): for line in l_meta: _, key,_,_,label = line.strip().split(' ') file_list.append(key) d_meta[key] = 1 if label == 'bonafide' else 0 return d_meta,file_list elif(is_eval): for line in l_meta: key= line.strip() file_list.append(key) return file_list else: for line in l_meta: _, key,_,_,label = line.strip().split(' ') file_list.append(key) d_meta[key] = 1 if label == 'bonafide' else 0 return d_meta,file_list def pad(x, max_len=64600): x_len = x.shape[0] if x_len >= max_len: return x[:max_len] # need to pad num_repeats = int(max_len / x_len)+1 padded_x = np.tile(x, (1, num_repeats))[:, :max_len][0] return padded_x class Dataset_ASVspoof2017_train(Dataset): def __init__(self, list_IDs, labels, base_dir): '''self.list_IDs : list of strings (each string: utt key), self.labels : dictionary (key: utt key, value: label integer)''' self.list_IDs = list_IDs self.labels = labels self.base_dir = base_dir def __len__(self): return len(self.list_IDs) def __getitem__(self, index): self.cut=64600 # take ~4 sec audio (64600 samples) key = self.list_IDs[index] X,fs = librosa.load(self.base_dir+key+'.flac', sr=16000) X_pad= pad(X,self.cut) x_inp= Tensor(X_pad) y = self.labels[key] return x_inp, y class Dataset_ASVspoof2017_eval(Dataset): def __init__(self, list_IDs, base_dir): '''self.list_IDs : list of strings (each string: utt key), ''' self.list_IDs = list_IDs self.base_dir = base_dir def __len__(self): return len(self.list_IDs) def __getitem__(self, index): self.cut=64600 # take ~4 sec audio (64600 samples) key = self.list_IDs[index] X, fs = librosa.load(self.base_dir+key+'.flac', sr=16000) X_pad = pad(X,self.cut) x_inp = Tensor(X_pad) return x_inp,key
[ "torch.Tensor", "librosa.load", "numpy.tile" ]
[((1791, 1844), 'librosa.load', 'librosa.load', (["(self.base_dir + key + '.flac')"], {'sr': '(16000)'}), "(self.base_dir + key + '.flac', sr=16000)\n", (1803, 1844), False, 'import librosa\n'), ((1896, 1909), 'torch.Tensor', 'Tensor', (['X_pad'], {}), '(X_pad)\n', (1902, 1909), False, 'from torch import Tensor\n'), ((2487, 2540), 'librosa.load', 'librosa.load', (["(self.base_dir + key + '.flac')"], {'sr': '(16000)'}), "(self.base_dir + key + '.flac', sr=16000)\n", (2499, 2540), False, 'import librosa\n'), ((2593, 2606), 'torch.Tensor', 'Tensor', (['X_pad'], {}), '(X_pad)\n', (2599, 2606), False, 'from torch import Tensor\n'), ((1124, 1152), 'numpy.tile', 'np.tile', (['x', '(1, num_repeats)'], {}), '(x, (1, num_repeats))\n', (1131, 1152), True, 'import numpy as np\n')]